index int64 0 0 | repo_id stringlengths 9 205 | file_path stringlengths 31 246 | content stringlengths 1 12.2M | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/PathExistsMessageFilter.java | package com.netflix.suro.routing.filter;
import org.apache.commons.jxpath.JXPathContext;
import org.apache.commons.jxpath.Pointer;
import org.apache.commons.jxpath.ri.model.beans.NullPointer;
public class PathExistsMessageFilter extends BaseMessageFilter {
private String xpath;
public PathExistsMessageFilter(String path) {
this.xpath = path;
}
@Override
public boolean apply(Object input) {
JXPathContext jxpath = JXPathContext.newContext(input);
// We should allow non-existing path, and let predicate handle it.
jxpath.setLenient(true);
Pointer pointer = jxpath.getPointer(xpath);
return pointer != null && !(pointer instanceof NullPointer) && pointer.getValue() != null;
}
public String getXpath() {
return xpath;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("PathExistsMessageFilter [xpath=");
builder.append(xpath);
builder.append("]");
return builder.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((xpath == null) ? 0 : xpath.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
PathExistsMessageFilter other = (PathExistsMessageFilter) obj;
if (xpath == null) {
if (other.xpath != null) {
return false;
}
} else if (!xpath.equals(other.xpath)) {
return false;
}
return true;
}
}
| 6,800 |
0 | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/OrMessageFilter.java | package com.netflix.suro.routing.filter;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
public class OrMessageFilter extends BaseMessageFilter {
final private Predicate<Object> orPredicate;
public OrMessageFilter(MessageFilter... filters) {
this.orPredicate = Predicates.or(filters);
}
public OrMessageFilter(Iterable<? extends MessageFilter> filters) {
this.orPredicate = Predicates.or(filters);
}
@Override
public boolean apply(Object input) {
return orPredicate.apply(input);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("OrMessageFilter");
sb.append("{orPredicate=").append(orPredicate);
sb.append('}');
return sb.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
OrMessageFilter that = (OrMessageFilter) o;
if (orPredicate != null ? !orPredicate.equals(that.orPredicate) : that.orPredicate != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
return orPredicate != null ? orPredicate.hashCode() : 0;
}
}
| 6,801 |
0 | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/AlwaysFalseMessageFilter.java | package com.netflix.suro.routing.filter;
final public class AlwaysFalseMessageFilter extends BaseMessageFilter {
// There's no point of creating multiple instance of this class
private AlwaysFalseMessageFilter(){
setOriginalDslString("false");
}
@Override
public boolean apply(Object input) {
return false;
}
public static final AlwaysFalseMessageFilter INSTANCE = new AlwaysFalseMessageFilter();
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("AlwaysFalseMessageFilter []");
return builder.toString();
}
@Override
public int hashCode() {
return Boolean.FALSE.hashCode();
}
@Override
public boolean equals(Object obj) {
return obj instanceof AlwaysFalseMessageFilter;
}
}
| 6,802 |
0 | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/MessageFilter.java | package com.netflix.suro.routing.filter;
import com.google.common.base.Predicate;
/**
* A contract for filtering events. These filters can be applied/defined both at the publisher and subscriber level.<p/>
* It is recommended to use a filter language as specified in {@link com.netflix.suro.routing.filter.lang} which provides
* flexible ways of defining filters. However, for programmatic creation of simple or custom filters it may be easy
* to directly implement this interface. <p/>
* The structure of the event filters is entirely opaque to the event bus and all processing related to evaluation of
* the same is left to the implementations.
*/
public interface MessageFilter extends Predicate<Object> {
// Emphasize that every {@code MessageFilter} instance can be used as a key
// in a collection.
public int hashCode();
public boolean equals(Object o);
}
| 6,803 |
0 | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/NullValuePredicate.java | package com.netflix.suro.routing.filter;
/**
* This predicate returns true if its input is null. That is, it identifies
* null object.
*
*/
final public class NullValuePredicate implements ValuePredicate{
private static final byte KEY = 0x00;
private NullValuePredicate(){}
@Override
public boolean apply(final Object input) {
return input == null;
}
public static final NullValuePredicate INSTANCE = new NullValuePredicate();
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("NullValuePredicate []");
return builder.toString();
}
@Override
public final int hashCode() {
return KEY;
}
@Override
public final boolean equals(Object obj) {
return obj instanceof NullValuePredicate;
}
}
| 6,804 |
0 | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/TimeMillisValuePredicate.java | package com.netflix.suro.routing.filter;
import org.joda.time.format.DateTimeFormatter;
import javax.annotation.Nullable;
public class TimeMillisValuePredicate implements ValuePredicate<Long> {
private String timeFormat;
private String value;
private String fnName;
private NumericValuePredicate longPredicate;
public TimeMillisValuePredicate(String timeFormat, String value, String fnName){
this.timeFormat = timeFormat;
this.value = value;
this.fnName = fnName;
DateTimeFormatter formatter = TimeUtil.toDateTimeFormatter("time format", timeFormat);
long timeInMs = formatter.parseMillis(value);
this.longPredicate = new NumericValuePredicate(timeInMs, fnName);
}
@Override
public boolean apply(@Nullable Long input) {
return longPredicate.apply(input);
}
public String getValue(){
return value;
}
public String getTimeFormat(){
return this.timeFormat;
}
String getFnName() {
return this.fnName;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("TimeMillisValuePredicate [timeFormat=");
builder.append(timeFormat);
builder.append(", value=");
builder.append(value);
builder.append(", fnName=");
builder.append(fnName);
builder.append(", longPredicate=");
builder.append(longPredicate);
builder.append("]");
return builder.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((fnName == null) ? 0 : fnName.hashCode());
result = prime * result + ((timeFormat == null) ? 0 : timeFormat.hashCode());
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
TimeMillisValuePredicate other = (TimeMillisValuePredicate) obj;
if (fnName == null) {
if (other.fnName != null) {
return false;
}
} else if (!fnName.equals(other.fnName)) {
return false;
}
if (timeFormat == null) {
if (other.timeFormat != null) {
return false;
}
} else if (!timeFormat.equals(other.timeFormat)) {
return false;
}
if (value == null) {
if (other.value != null) {
return false;
}
} else if (!value.equals(other.value)) {
return false;
}
return true;
}
}
| 6,805 |
0 | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/StringValuePredicate.java | package com.netflix.suro.routing.filter;
import com.google.common.base.Objects;
import javax.annotation.Nullable;
public class StringValuePredicate implements ValuePredicate<String> {
private String value;
public StringValuePredicate(@Nullable String value){
this.value = value;
}
@Override
public boolean apply(@Nullable String input) {
return Objects.equal(value, input);
}
String getValue(){
return value;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("StringValuePredicate [value=");
builder.append(value);
builder.append("]");
return builder.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
StringValuePredicate other = (StringValuePredicate) obj;
if (value == null) {
if (other.value != null) {
return false;
}
} else if (!value.equals(other.value)) {
return false;
}
return true;
}
}
| 6,806 |
0 | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/PathValuePredicate.java | package com.netflix.suro.routing.filter;
import com.google.common.base.Objects;
import org.apache.commons.jxpath.JXPathContext;
import javax.annotation.Nullable;
public class PathValuePredicate implements ValuePredicate<String> {
private String valueXpath;
private String inputXpath;
public PathValuePredicate(String valueXpath, String inputXpath){
this.valueXpath = valueXpath;
this.inputXpath = inputXpath;
}
@Override
public boolean apply(@Nullable String input) {
JXPathContext context = JXPathContext.newContext(input);
context.setLenient(true);
return Objects.equal(context.getValue(valueXpath), context.getValue(inputXpath));
}
public String getInputXpath(){
return inputXpath;
}
public String getValueXpath() {
return valueXpath;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((inputXpath == null) ? 0 : inputXpath.hashCode());
result = prime * result + ((valueXpath == null) ? 0 : valueXpath.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
PathValuePredicate other = (PathValuePredicate) obj;
if (inputXpath == null) {
if (other.inputXpath != null) {
return false;
}
} else if (!inputXpath.equals(other.inputXpath)) {
return false;
}
if (valueXpath == null) {
if (other.valueXpath != null) {
return false;
}
} else if (!valueXpath.equals(other.valueXpath)) {
return false;
}
return true;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("PathValuePredicate [valueXpath=");
builder.append(valueXpath);
builder.append(", inputXpath=");
builder.append(inputXpath);
builder.append("]");
return builder.toString();
}
}
| 6,807 |
0 | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/lang/FilterLanguageSupport.java | package com.netflix.suro.routing.filter.lang;
import com.netflix.suro.routing.filter.MessageFilter;
/**
* General contract for any filter language which relates to a methodology of converting a language expression to a
* valid {@link com.netflix.suro.routing.filter.MessageFilter} instance consumable by {@link com.netflix.suro.routing.filter}
*
* @author Nitesh Kant (nkant@netflix.com)
*/
public interface FilterLanguageSupport<T> {
/**
* Converts the passed filter object to a valid {@link MessageFilter}.
*
* @param filter Filter object to convert.
*
* @return {@link MessageFilter} corresponding to the passed filter.
*
* @throws InvalidFilterException If the passed filter was invalid.
*/
MessageFilter convert(T filter) throws InvalidFilterException;
}
| 6,808 |
0 | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/lang/MessageFilterParser.java | // $ANTLR 3.4 MessageFilter.g 2012-08-22 11:55:58
package com.netflix.suro.routing.filter.lang;
import org.antlr.runtime.*;
import org.antlr.runtime.tree.*;
@SuppressWarnings({"all", "warnings", "unchecked"})
public class MessageFilterParser extends Parser {
public static final String[] tokenNames = new String[] {
"<invalid>", "<EOR>", "<DOWN>", "<UP>", "AND", "BETWEEN", "COMMENT", "EQUALS", "ESC_SEQ", "EXISTS", "EXPONENT", "FALSE", "GE", "GT", "HEX_DIGIT", "IN", "IS", "LE", "LT", "MATCHES", "NOT", "NOT_EQUALS", "NULL", "NUMBER", "OCTAL_ESC", "OR", "STRING", "TIME_MILLIS_FUN_NAME", "TIME_STRING_FUN_NAME", "TRUE", "UNICODE_ESC", "WS", "XPATH_FUN_NAME", "'('", "')'", "','"
};
public static final int EOF=-1;
public static final int T__33=33;
public static final int T__34=34;
public static final int T__35=35;
public static final int AND=4;
public static final int BETWEEN=5;
public static final int COMMENT=6;
public static final int EQUALS=7;
public static final int ESC_SEQ=8;
public static final int EXISTS=9;
public static final int EXPONENT=10;
public static final int FALSE=11;
public static final int GE=12;
public static final int GT=13;
public static final int HEX_DIGIT=14;
public static final int IN=15;
public static final int IS=16;
public static final int LE=17;
public static final int LT=18;
public static final int MATCHES=19;
public static final int NOT=20;
public static final int NOT_EQUALS=21;
public static final int NULL=22;
public static final int NUMBER=23;
public static final int OCTAL_ESC=24;
public static final int OR=25;
public static final int STRING=26;
public static final int TIME_MILLIS_FUN_NAME=27;
public static final int TIME_STRING_FUN_NAME=28;
public static final int TRUE=29;
public static final int UNICODE_ESC=30;
public static final int WS=31;
public static final int XPATH_FUN_NAME=32;
// delegates
public Parser[] getDelegates() {
return new Parser[] {};
}
// delegators
public MessageFilterParser(TokenStream input) {
this(input, new RecognizerSharedState());
}
public MessageFilterParser(TokenStream input, RecognizerSharedState state) {
super(input, state);
}
protected TreeAdaptor adaptor = new CommonTreeAdaptor();
public void setTreeAdaptor(TreeAdaptor adaptor) {
this.adaptor = adaptor;
}
public TreeAdaptor getTreeAdaptor() {
return adaptor;
}
public String[] getTokenNames() { return MessageFilterParser.tokenNames; }
public String getGrammarFileName() { return "MessageFilter.g"; }
/**
Creates a new parser that parses the given input string.
*/
public static MessageFilterParser createParser(String input) {
ANTLRStringStream inputStream = new ANTLRStringStream(input);
MessageFilterLexer lexer = new MessageFilterLexer(inputStream);
CommonTokenStream tokens = new CommonTokenStream(lexer);
return new MessageFilterParser(tokens);
}
@Override
public void reportError(RecognitionException e) {
// if we've already reported an error and have not matched a token
// yet successfully, don't report any errors.
if ( state.errorRecovery ) {
return;
}
state.syntaxErrors++; // don't count spurious
state.errorRecovery = true;
throwParsingError(this.getTokenNames(), e);
}
// A slight modification of #displayRecognitionError(String[], RecognitionException)
private void throwParsingError(String[] tokenNames, RecognitionException e) {
String hdr = getErrorHeader(e);
String msg = getErrorMessage(e, tokenNames);
throw new MessageFilterParsingException(String.format("%s %s", hdr, msg), e);
}
public static class filter_return extends ParserRuleReturnScope {
CommonTree tree;
public Object getTree() { return tree; }
};
// $ANTLR start "filter"
// MessageFilter.g:102:1: filter : (a= boolean_expr -> $a) ( OR b= boolean_expr -> ^( OR $filter $b) )* ( EOF )? ;
public final filter_return filter() throws RecognitionException {
filter_return retval = new filter_return();
retval.start = input.LT(1);
CommonTree root_0 = null;
Token OR1=null;
Token EOF2=null;
boolean_expr_return a =null;
boolean_expr_return b =null;
CommonTree OR1_tree=null;
CommonTree EOF2_tree=null;
RewriteRuleTokenStream stream_EOF=new RewriteRuleTokenStream(adaptor,"token EOF");
RewriteRuleTokenStream stream_OR=new RewriteRuleTokenStream(adaptor,"token OR");
RewriteRuleSubtreeStream stream_boolean_expr=new RewriteRuleSubtreeStream(adaptor,"rule boolean_expr");
try {
// MessageFilter.g:103:2: ( (a= boolean_expr -> $a) ( OR b= boolean_expr -> ^( OR $filter $b) )* ( EOF )? )
// MessageFilter.g:103:4: (a= boolean_expr -> $a) ( OR b= boolean_expr -> ^( OR $filter $b) )* ( EOF )?
{
// MessageFilter.g:103:4: (a= boolean_expr -> $a)
// MessageFilter.g:103:5: a= boolean_expr
{
pushFollow(FOLLOW_boolean_expr_in_filter323);
a=boolean_expr();
state._fsp--;
stream_boolean_expr.add(a.getTree());
// AST REWRITE
// elements: a
// token labels:
// rule labels: retval, a
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
RewriteRuleSubtreeStream stream_a=new RewriteRuleSubtreeStream(adaptor,"rule a",a!=null?a.tree:null);
root_0 = (CommonTree)adaptor.nil();
// 103:19: -> $a
{
adaptor.addChild(root_0, stream_a.nextTree());
}
retval.tree = root_0;
}
// MessageFilter.g:103:25: ( OR b= boolean_expr -> ^( OR $filter $b) )*
loop1:
do {
int alt1=2;
int LA1_0 = input.LA(1);
if ( (LA1_0==OR) ) {
alt1=1;
}
switch (alt1) {
case 1 :
// MessageFilter.g:103:26: OR b= boolean_expr
{
OR1=(Token)match(input,OR,FOLLOW_OR_in_filter330);
stream_OR.add(OR1);
pushFollow(FOLLOW_boolean_expr_in_filter334);
b=boolean_expr();
state._fsp--;
stream_boolean_expr.add(b.getTree());
// AST REWRITE
// elements: OR, filter, b
// token labels:
// rule labels: retval, b
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
RewriteRuleSubtreeStream stream_b=new RewriteRuleSubtreeStream(adaptor,"rule b",b!=null?b.tree:null);
root_0 = (CommonTree)adaptor.nil();
// 103:44: -> ^( OR $filter $b)
{
// MessageFilter.g:103:47: ^( OR $filter $b)
{
CommonTree root_1 = (CommonTree)adaptor.nil();
root_1 = (CommonTree)adaptor.becomeRoot(
new OrTreeNode(stream_OR.nextToken())
, root_1);
adaptor.addChild(root_1, stream_retval.nextTree());
adaptor.addChild(root_1, stream_b.nextTree());
adaptor.addChild(root_0, root_1);
}
}
retval.tree = root_0;
}
break;
default :
break loop1;
}
} while (true);
// MessageFilter.g:103:79: ( EOF )?
int alt2=2;
int LA2_0 = input.LA(1);
if ( (LA2_0==EOF) ) {
alt2=1;
}
switch (alt2) {
case 1 :
// MessageFilter.g:103:79: EOF
{
EOF2=(Token)match(input,EOF,FOLLOW_EOF_in_filter354);
stream_EOF.add(EOF2);
}
break;
}
}
retval.stop = input.LT(-1);
retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "filter"
public static class boolean_expr_return extends ParserRuleReturnScope {
CommonTree tree;
public Object getTree() { return tree; }
};
// $ANTLR start "boolean_expr"
// MessageFilter.g:106:1: boolean_expr : (a= boolean_factor -> $a) ( AND b= boolean_factor -> ^( AND $boolean_expr $b) )* ;
public final boolean_expr_return boolean_expr() throws RecognitionException {
boolean_expr_return retval = new boolean_expr_return();
retval.start = input.LT(1);
CommonTree root_0 = null;
Token AND3=null;
boolean_factor_return a =null;
boolean_factor_return b =null;
CommonTree AND3_tree=null;
RewriteRuleTokenStream stream_AND=new RewriteRuleTokenStream(adaptor,"token AND");
RewriteRuleSubtreeStream stream_boolean_factor=new RewriteRuleSubtreeStream(adaptor,"rule boolean_factor");
try {
// MessageFilter.g:107:2: ( (a= boolean_factor -> $a) ( AND b= boolean_factor -> ^( AND $boolean_expr $b) )* )
// MessageFilter.g:107:4: (a= boolean_factor -> $a) ( AND b= boolean_factor -> ^( AND $boolean_expr $b) )*
{
// MessageFilter.g:107:4: (a= boolean_factor -> $a)
// MessageFilter.g:107:5: a= boolean_factor
{
pushFollow(FOLLOW_boolean_factor_in_boolean_expr370);
a=boolean_factor();
state._fsp--;
stream_boolean_factor.add(a.getTree());
// AST REWRITE
// elements: a
// token labels:
// rule labels: retval, a
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
RewriteRuleSubtreeStream stream_a=new RewriteRuleSubtreeStream(adaptor,"rule a",a!=null?a.tree:null);
root_0 = (CommonTree)adaptor.nil();
// 107:21: -> $a
{
adaptor.addChild(root_0, stream_a.nextTree());
}
retval.tree = root_0;
}
// MessageFilter.g:107:27: ( AND b= boolean_factor -> ^( AND $boolean_expr $b) )*
loop3:
do {
int alt3=2;
int LA3_0 = input.LA(1);
if ( (LA3_0==AND) ) {
alt3=1;
}
switch (alt3) {
case 1 :
// MessageFilter.g:107:28: AND b= boolean_factor
{
AND3=(Token)match(input,AND,FOLLOW_AND_in_boolean_expr377);
stream_AND.add(AND3);
pushFollow(FOLLOW_boolean_factor_in_boolean_expr381);
b=boolean_factor();
state._fsp--;
stream_boolean_factor.add(b.getTree());
// AST REWRITE
// elements: b, boolean_expr, AND
// token labels:
// rule labels: retval, b
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
RewriteRuleSubtreeStream stream_b=new RewriteRuleSubtreeStream(adaptor,"rule b",b!=null?b.tree:null);
root_0 = (CommonTree)adaptor.nil();
// 107:49: -> ^( AND $boolean_expr $b)
{
// MessageFilter.g:107:52: ^( AND $boolean_expr $b)
{
CommonTree root_1 = (CommonTree)adaptor.nil();
root_1 = (CommonTree)adaptor.becomeRoot(
new AndTreeNode(stream_AND.nextToken())
, root_1);
adaptor.addChild(root_1, stream_retval.nextTree());
adaptor.addChild(root_1, stream_b.nextTree());
adaptor.addChild(root_0, root_1);
}
}
retval.tree = root_0;
}
break;
default :
break loop3;
}
} while (true);
}
retval.stop = input.LT(-1);
retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "boolean_expr"
public static class boolean_factor_return extends ParserRuleReturnScope {
CommonTree tree;
public Object getTree() { return tree; }
};
// $ANTLR start "boolean_factor"
// MessageFilter.g:111:1: boolean_factor : ( predicate | NOT predicate -> ^( NOT predicate ) );
public final boolean_factor_return boolean_factor() throws RecognitionException {
boolean_factor_return retval = new boolean_factor_return();
retval.start = input.LT(1);
CommonTree root_0 = null;
Token NOT5=null;
predicate_return predicate4 =null;
predicate_return predicate6 =null;
CommonTree NOT5_tree=null;
RewriteRuleTokenStream stream_NOT=new RewriteRuleTokenStream(adaptor,"token NOT");
RewriteRuleSubtreeStream stream_predicate=new RewriteRuleSubtreeStream(adaptor,"rule predicate");
try {
// MessageFilter.g:112:2: ( predicate | NOT predicate -> ^( NOT predicate ) )
int alt4=2;
int LA4_0 = input.LA(1);
if ( (LA4_0==EXISTS||LA4_0==FALSE||LA4_0==TRUE||(LA4_0 >= XPATH_FUN_NAME && LA4_0 <= 33)) ) {
alt4=1;
}
else if ( (LA4_0==NOT) ) {
alt4=2;
}
else {
NoViableAltException nvae =
new NoViableAltException("", 4, 0, input);
throw nvae;
}
switch (alt4) {
case 1 :
// MessageFilter.g:112:4: predicate
{
root_0 = (CommonTree)adaptor.nil();
pushFollow(FOLLOW_predicate_in_boolean_factor414);
predicate4=predicate();
state._fsp--;
adaptor.addChild(root_0, predicate4.getTree());
}
break;
case 2 :
// MessageFilter.g:113:6: NOT predicate
{
NOT5=(Token)match(input,NOT,FOLLOW_NOT_in_boolean_factor423);
stream_NOT.add(NOT5);
pushFollow(FOLLOW_predicate_in_boolean_factor425);
predicate6=predicate();
state._fsp--;
stream_predicate.add(predicate6.getTree());
// AST REWRITE
// elements: NOT, predicate
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (CommonTree)adaptor.nil();
// 113:20: -> ^( NOT predicate )
{
// MessageFilter.g:113:23: ^( NOT predicate )
{
CommonTree root_1 = (CommonTree)adaptor.nil();
root_1 = (CommonTree)adaptor.becomeRoot(
new NotTreeNode(stream_NOT.nextToken())
, root_1);
adaptor.addChild(root_1, stream_predicate.nextTree());
adaptor.addChild(root_0, root_1);
}
}
retval.tree = root_0;
}
break;
}
retval.stop = input.LT(-1);
retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "boolean_factor"
public static class predicate_return extends ParserRuleReturnScope {
CommonTree tree;
public Object getTree() { return tree; }
};
// $ANTLR start "predicate"
// MessageFilter.g:116:1: predicate : ( '(' filter ')' -> filter | comparison_function | between_predicate | in_predicate | null_predicate | regex_predicate | exists_predicate | TRUE -> TRUE | FALSE -> FALSE );
public final predicate_return predicate() throws RecognitionException {
predicate_return retval = new predicate_return();
retval.start = input.LT(1);
CommonTree root_0 = null;
Token char_literal7=null;
Token char_literal9=null;
Token TRUE16=null;
Token FALSE17=null;
filter_return filter8 =null;
comparison_function_return comparison_function10 =null;
between_predicate_return between_predicate11 =null;
in_predicate_return in_predicate12 =null;
null_predicate_return null_predicate13 =null;
regex_predicate_return regex_predicate14 =null;
exists_predicate_return exists_predicate15 =null;
CommonTree char_literal7_tree=null;
CommonTree char_literal9_tree=null;
CommonTree TRUE16_tree=null;
CommonTree FALSE17_tree=null;
RewriteRuleTokenStream stream_FALSE=new RewriteRuleTokenStream(adaptor,"token FALSE");
RewriteRuleTokenStream stream_TRUE=new RewriteRuleTokenStream(adaptor,"token TRUE");
RewriteRuleTokenStream stream_33=new RewriteRuleTokenStream(adaptor,"token 33");
RewriteRuleTokenStream stream_34=new RewriteRuleTokenStream(adaptor,"token 34");
RewriteRuleSubtreeStream stream_filter=new RewriteRuleSubtreeStream(adaptor,"rule filter");
try {
// MessageFilter.g:117:2: ( '(' filter ')' -> filter | comparison_function | between_predicate | in_predicate | null_predicate | regex_predicate | exists_predicate | TRUE -> TRUE | FALSE -> FALSE )
int alt5=9;
switch ( input.LA(1) ) {
case 33:
{
alt5=1;
}
break;
case XPATH_FUN_NAME:
{
int LA5_2 = input.LA(2);
if ( (LA5_2==33) ) {
int LA5_6 = input.LA(3);
if ( (LA5_6==STRING) ) {
int LA5_7 = input.LA(4);
if ( (LA5_7==34) ) {
switch ( input.LA(5) ) {
case EQUALS:
case GE:
case GT:
case LE:
case LT:
case NOT_EQUALS:
{
alt5=2;
}
break;
case BETWEEN:
{
alt5=3;
}
break;
case IN:
{
alt5=4;
}
break;
case IS:
{
alt5=5;
}
break;
case MATCHES:
{
alt5=6;
}
break;
case EXISTS:
{
alt5=7;
}
break;
default:
NoViableAltException nvae =
new NoViableAltException("", 5, 8, input);
throw nvae;
}
}
else {
NoViableAltException nvae =
new NoViableAltException("", 5, 7, input);
throw nvae;
}
}
else {
NoViableAltException nvae =
new NoViableAltException("", 5, 6, input);
throw nvae;
}
}
else {
NoViableAltException nvae =
new NoViableAltException("", 5, 2, input);
throw nvae;
}
}
break;
case EXISTS:
{
alt5=7;
}
break;
case TRUE:
{
alt5=8;
}
break;
case FALSE:
{
alt5=9;
}
break;
default:
NoViableAltException nvae =
new NoViableAltException("", 5, 0, input);
throw nvae;
}
switch (alt5) {
case 1 :
// MessageFilter.g:117:4: '(' filter ')'
{
char_literal7=(Token)match(input,33,FOLLOW_33_in_predicate448);
stream_33.add(char_literal7);
pushFollow(FOLLOW_filter_in_predicate450);
filter8=filter();
state._fsp--;
stream_filter.add(filter8.getTree());
char_literal9=(Token)match(input,34,FOLLOW_34_in_predicate452);
stream_34.add(char_literal9);
// AST REWRITE
// elements: filter
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (CommonTree)adaptor.nil();
// 117:19: -> filter
{
adaptor.addChild(root_0, stream_filter.nextTree());
}
retval.tree = root_0;
}
break;
case 2 :
// MessageFilter.g:118:3: comparison_function
{
root_0 = (CommonTree)adaptor.nil();
pushFollow(FOLLOW_comparison_function_in_predicate463);
comparison_function10=comparison_function();
state._fsp--;
adaptor.addChild(root_0, comparison_function10.getTree());
}
break;
case 3 :
// MessageFilter.g:119:3: between_predicate
{
root_0 = (CommonTree)adaptor.nil();
pushFollow(FOLLOW_between_predicate_in_predicate469);
between_predicate11=between_predicate();
state._fsp--;
adaptor.addChild(root_0, between_predicate11.getTree());
}
break;
case 4 :
// MessageFilter.g:120:3: in_predicate
{
root_0 = (CommonTree)adaptor.nil();
pushFollow(FOLLOW_in_predicate_in_predicate475);
in_predicate12=in_predicate();
state._fsp--;
adaptor.addChild(root_0, in_predicate12.getTree());
}
break;
case 5 :
// MessageFilter.g:121:3: null_predicate
{
root_0 = (CommonTree)adaptor.nil();
pushFollow(FOLLOW_null_predicate_in_predicate481);
null_predicate13=null_predicate();
state._fsp--;
adaptor.addChild(root_0, null_predicate13.getTree());
}
break;
case 6 :
// MessageFilter.g:122:3: regex_predicate
{
root_0 = (CommonTree)adaptor.nil();
pushFollow(FOLLOW_regex_predicate_in_predicate487);
regex_predicate14=regex_predicate();
state._fsp--;
adaptor.addChild(root_0, regex_predicate14.getTree());
}
break;
case 7 :
// MessageFilter.g:123:3: exists_predicate
{
root_0 = (CommonTree)adaptor.nil();
pushFollow(FOLLOW_exists_predicate_in_predicate493);
exists_predicate15=exists_predicate();
state._fsp--;
adaptor.addChild(root_0, exists_predicate15.getTree());
}
break;
case 8 :
// MessageFilter.g:124:3: TRUE
{
TRUE16=(Token)match(input,TRUE,FOLLOW_TRUE_in_predicate499);
stream_TRUE.add(TRUE16);
// AST REWRITE
// elements: TRUE
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (CommonTree)adaptor.nil();
// 124:8: -> TRUE
{
adaptor.addChild(root_0,
new TrueValueTreeNode(stream_TRUE.nextToken())
);
}
retval.tree = root_0;
}
break;
case 9 :
// MessageFilter.g:125:3: FALSE
{
FALSE17=(Token)match(input,FALSE,FOLLOW_FALSE_in_predicate511);
stream_FALSE.add(FALSE17);
// AST REWRITE
// elements: FALSE
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (CommonTree)adaptor.nil();
// 125:9: -> FALSE
{
adaptor.addChild(root_0,
new FalseValueTreeNode(stream_FALSE.nextToken())
);
}
retval.tree = root_0;
}
break;
}
retval.stop = input.LT(-1);
retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "predicate"
public static class comparison_function_return extends ParserRuleReturnScope {
CommonTree tree;
public Object getTree() { return tree; }
};
// $ANTLR start "comparison_function"
// MessageFilter.g:128:1: comparison_function : ( path_function EQUALS value_function -> ^( EQUALS path_function value_function ) | path_function NOT_EQUALS value_function -> ^( NOT_EQUALS path_function value_function ) | path_function GT compariable_value_function -> ^( GT path_function compariable_value_function ) | path_function GE compariable_value_function -> ^( GE path_function compariable_value_function ) | path_function LT compariable_value_function -> ^( LT path_function compariable_value_function ) | path_function LE compariable_value_function -> ^( LE path_function compariable_value_function ) );
public final comparison_function_return comparison_function() throws RecognitionException {
comparison_function_return retval = new comparison_function_return();
retval.start = input.LT(1);
CommonTree root_0 = null;
Token EQUALS19=null;
Token NOT_EQUALS22=null;
Token GT25=null;
Token GE28=null;
Token LT31=null;
Token LE34=null;
path_function_return path_function18 =null;
value_function_return value_function20 =null;
path_function_return path_function21 =null;
value_function_return value_function23 =null;
path_function_return path_function24 =null;
compariable_value_function_return compariable_value_function26 =null;
path_function_return path_function27 =null;
compariable_value_function_return compariable_value_function29 =null;
path_function_return path_function30 =null;
compariable_value_function_return compariable_value_function32 =null;
path_function_return path_function33 =null;
compariable_value_function_return compariable_value_function35 =null;
CommonTree EQUALS19_tree=null;
CommonTree NOT_EQUALS22_tree=null;
CommonTree GT25_tree=null;
CommonTree GE28_tree=null;
CommonTree LT31_tree=null;
CommonTree LE34_tree=null;
RewriteRuleTokenStream stream_GE=new RewriteRuleTokenStream(adaptor,"token GE");
RewriteRuleTokenStream stream_GT=new RewriteRuleTokenStream(adaptor,"token GT");
RewriteRuleTokenStream stream_LT=new RewriteRuleTokenStream(adaptor,"token LT");
RewriteRuleTokenStream stream_EQUALS=new RewriteRuleTokenStream(adaptor,"token EQUALS");
RewriteRuleTokenStream stream_NOT_EQUALS=new RewriteRuleTokenStream(adaptor,"token NOT_EQUALS");
RewriteRuleTokenStream stream_LE=new RewriteRuleTokenStream(adaptor,"token LE");
RewriteRuleSubtreeStream stream_compariable_value_function=new RewriteRuleSubtreeStream(adaptor,"rule compariable_value_function");
RewriteRuleSubtreeStream stream_value_function=new RewriteRuleSubtreeStream(adaptor,"rule value_function");
RewriteRuleSubtreeStream stream_path_function=new RewriteRuleSubtreeStream(adaptor,"rule path_function");
try {
// MessageFilter.g:129:2: ( path_function EQUALS value_function -> ^( EQUALS path_function value_function ) | path_function NOT_EQUALS value_function -> ^( NOT_EQUALS path_function value_function ) | path_function GT compariable_value_function -> ^( GT path_function compariable_value_function ) | path_function GE compariable_value_function -> ^( GE path_function compariable_value_function ) | path_function LT compariable_value_function -> ^( LT path_function compariable_value_function ) | path_function LE compariable_value_function -> ^( LE path_function compariable_value_function ) )
int alt6=6;
int LA6_0 = input.LA(1);
if ( (LA6_0==XPATH_FUN_NAME) ) {
int LA6_1 = input.LA(2);
if ( (LA6_1==33) ) {
int LA6_2 = input.LA(3);
if ( (LA6_2==STRING) ) {
int LA6_3 = input.LA(4);
if ( (LA6_3==34) ) {
switch ( input.LA(5) ) {
case EQUALS:
{
alt6=1;
}
break;
case NOT_EQUALS:
{
alt6=2;
}
break;
case GT:
{
alt6=3;
}
break;
case GE:
{
alt6=4;
}
break;
case LT:
{
alt6=5;
}
break;
case LE:
{
alt6=6;
}
break;
default:
NoViableAltException nvae =
new NoViableAltException("", 6, 4, input);
throw nvae;
}
}
else {
NoViableAltException nvae =
new NoViableAltException("", 6, 3, input);
throw nvae;
}
}
else {
NoViableAltException nvae =
new NoViableAltException("", 6, 2, input);
throw nvae;
}
}
else {
NoViableAltException nvae =
new NoViableAltException("", 6, 1, input);
throw nvae;
}
}
else {
NoViableAltException nvae =
new NoViableAltException("", 6, 0, input);
throw nvae;
}
switch (alt6) {
case 1 :
// MessageFilter.g:129:4: path_function EQUALS value_function
{
pushFollow(FOLLOW_path_function_in_comparison_function529);
path_function18=path_function();
state._fsp--;
stream_path_function.add(path_function18.getTree());
EQUALS19=(Token)match(input,EQUALS,FOLLOW_EQUALS_in_comparison_function531);
stream_EQUALS.add(EQUALS19);
pushFollow(FOLLOW_value_function_in_comparison_function533);
value_function20=value_function();
state._fsp--;
stream_value_function.add(value_function20.getTree());
// AST REWRITE
// elements: value_function, path_function, EQUALS
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (CommonTree)adaptor.nil();
// 129:40: -> ^( EQUALS path_function value_function )
{
// MessageFilter.g:129:43: ^( EQUALS path_function value_function )
{
CommonTree root_1 = (CommonTree)adaptor.nil();
root_1 = (CommonTree)adaptor.becomeRoot(
new EqualsTreeNode(stream_EQUALS.nextToken())
, root_1);
adaptor.addChild(root_1, stream_path_function.nextTree());
adaptor.addChild(root_1, stream_value_function.nextTree());
adaptor.addChild(root_0, root_1);
}
}
retval.tree = root_0;
}
break;
case 2 :
// MessageFilter.g:130:3: path_function NOT_EQUALS value_function
{
pushFollow(FOLLOW_path_function_in_comparison_function552);
path_function21=path_function();
state._fsp--;
stream_path_function.add(path_function21.getTree());
NOT_EQUALS22=(Token)match(input,NOT_EQUALS,FOLLOW_NOT_EQUALS_in_comparison_function554);
stream_NOT_EQUALS.add(NOT_EQUALS22);
pushFollow(FOLLOW_value_function_in_comparison_function556);
value_function23=value_function();
state._fsp--;
stream_value_function.add(value_function23.getTree());
// AST REWRITE
// elements: value_function, path_function, NOT_EQUALS
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (CommonTree)adaptor.nil();
// 130:43: -> ^( NOT_EQUALS path_function value_function )
{
// MessageFilter.g:130:46: ^( NOT_EQUALS path_function value_function )
{
CommonTree root_1 = (CommonTree)adaptor.nil();
root_1 = (CommonTree)adaptor.becomeRoot(
new NotEqualsTreeNode(stream_NOT_EQUALS.nextToken())
, root_1);
adaptor.addChild(root_1, stream_path_function.nextTree());
adaptor.addChild(root_1, stream_value_function.nextTree());
adaptor.addChild(root_0, root_1);
}
}
retval.tree = root_0;
}
break;
case 3 :
// MessageFilter.g:131:3: path_function GT compariable_value_function
{
pushFollow(FOLLOW_path_function_in_comparison_function575);
path_function24=path_function();
state._fsp--;
stream_path_function.add(path_function24.getTree());
GT25=(Token)match(input,GT,FOLLOW_GT_in_comparison_function577);
stream_GT.add(GT25);
pushFollow(FOLLOW_compariable_value_function_in_comparison_function579);
compariable_value_function26=compariable_value_function();
state._fsp--;
stream_compariable_value_function.add(compariable_value_function26.getTree());
// AST REWRITE
// elements: path_function, GT, compariable_value_function
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (CommonTree)adaptor.nil();
// 131:47: -> ^( GT path_function compariable_value_function )
{
// MessageFilter.g:131:50: ^( GT path_function compariable_value_function )
{
CommonTree root_1 = (CommonTree)adaptor.nil();
root_1 = (CommonTree)adaptor.becomeRoot(
new ComparableTreeNode(stream_GT.nextToken())
, root_1);
adaptor.addChild(root_1, stream_path_function.nextTree());
adaptor.addChild(root_1, stream_compariable_value_function.nextTree());
adaptor.addChild(root_0, root_1);
}
}
retval.tree = root_0;
}
break;
case 4 :
// MessageFilter.g:132:3: path_function GE compariable_value_function
{
pushFollow(FOLLOW_path_function_in_comparison_function598);
path_function27=path_function();
state._fsp--;
stream_path_function.add(path_function27.getTree());
GE28=(Token)match(input,GE,FOLLOW_GE_in_comparison_function600);
stream_GE.add(GE28);
pushFollow(FOLLOW_compariable_value_function_in_comparison_function602);
compariable_value_function29=compariable_value_function();
state._fsp--;
stream_compariable_value_function.add(compariable_value_function29.getTree());
// AST REWRITE
// elements: compariable_value_function, path_function, GE
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (CommonTree)adaptor.nil();
// 132:47: -> ^( GE path_function compariable_value_function )
{
// MessageFilter.g:132:50: ^( GE path_function compariable_value_function )
{
CommonTree root_1 = (CommonTree)adaptor.nil();
root_1 = (CommonTree)adaptor.becomeRoot(
new ComparableTreeNode(stream_GE.nextToken())
, root_1);
adaptor.addChild(root_1, stream_path_function.nextTree());
adaptor.addChild(root_1, stream_compariable_value_function.nextTree());
adaptor.addChild(root_0, root_1);
}
}
retval.tree = root_0;
}
break;
case 5 :
// MessageFilter.g:133:3: path_function LT compariable_value_function
{
pushFollow(FOLLOW_path_function_in_comparison_function621);
path_function30=path_function();
state._fsp--;
stream_path_function.add(path_function30.getTree());
LT31=(Token)match(input,LT,FOLLOW_LT_in_comparison_function623);
stream_LT.add(LT31);
pushFollow(FOLLOW_compariable_value_function_in_comparison_function625);
compariable_value_function32=compariable_value_function();
state._fsp--;
stream_compariable_value_function.add(compariable_value_function32.getTree());
// AST REWRITE
// elements: path_function, compariable_value_function, LT
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (CommonTree)adaptor.nil();
// 133:47: -> ^( LT path_function compariable_value_function )
{
// MessageFilter.g:133:50: ^( LT path_function compariable_value_function )
{
CommonTree root_1 = (CommonTree)adaptor.nil();
root_1 = (CommonTree)adaptor.becomeRoot(
new ComparableTreeNode(stream_LT.nextToken())
, root_1);
adaptor.addChild(root_1, stream_path_function.nextTree());
adaptor.addChild(root_1, stream_compariable_value_function.nextTree());
adaptor.addChild(root_0, root_1);
}
}
retval.tree = root_0;
}
break;
case 6 :
// MessageFilter.g:134:3: path_function LE compariable_value_function
{
pushFollow(FOLLOW_path_function_in_comparison_function644);
path_function33=path_function();
state._fsp--;
stream_path_function.add(path_function33.getTree());
LE34=(Token)match(input,LE,FOLLOW_LE_in_comparison_function646);
stream_LE.add(LE34);
pushFollow(FOLLOW_compariable_value_function_in_comparison_function648);
compariable_value_function35=compariable_value_function();
state._fsp--;
stream_compariable_value_function.add(compariable_value_function35.getTree());
// AST REWRITE
// elements: compariable_value_function, LE, path_function
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (CommonTree)adaptor.nil();
// 134:47: -> ^( LE path_function compariable_value_function )
{
// MessageFilter.g:134:50: ^( LE path_function compariable_value_function )
{
CommonTree root_1 = (CommonTree)adaptor.nil();
root_1 = (CommonTree)adaptor.becomeRoot(
new ComparableTreeNode(stream_LE.nextToken())
, root_1);
adaptor.addChild(root_1, stream_path_function.nextTree());
adaptor.addChild(root_1, stream_compariable_value_function.nextTree());
adaptor.addChild(root_0, root_1);
}
}
retval.tree = root_0;
}
break;
}
retval.stop = input.LT(-1);
retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "comparison_function"
public static class between_predicate_return extends ParserRuleReturnScope {
CommonTree tree;
public Object getTree() { return tree; }
};
// $ANTLR start "between_predicate"
// MessageFilter.g:137:1: between_predicate : ( path_function BETWEEN '(' NUMBER ',' NUMBER ')' -> ^( BETWEEN path_function NUMBER NUMBER ) | path_function BETWEEN '(' time_millis_function ',' time_millis_function ')' -> ^( BETWEEN path_function time_millis_function time_millis_function ) | path_function BETWEEN '(' time_string_function ',' time_string_function ')' -> ^( BETWEEN path_function time_string_function time_string_function ) );
public final between_predicate_return between_predicate() throws RecognitionException {
between_predicate_return retval = new between_predicate_return();
retval.start = input.LT(1);
CommonTree root_0 = null;
Token BETWEEN37=null;
Token char_literal38=null;
Token NUMBER39=null;
Token char_literal40=null;
Token NUMBER41=null;
Token char_literal42=null;
Token BETWEEN44=null;
Token char_literal45=null;
Token char_literal47=null;
Token char_literal49=null;
Token BETWEEN51=null;
Token char_literal52=null;
Token char_literal54=null;
Token char_literal56=null;
path_function_return path_function36 =null;
path_function_return path_function43 =null;
time_millis_function_return time_millis_function46 =null;
time_millis_function_return time_millis_function48 =null;
path_function_return path_function50 =null;
time_string_function_return time_string_function53 =null;
time_string_function_return time_string_function55 =null;
CommonTree BETWEEN37_tree=null;
CommonTree char_literal38_tree=null;
CommonTree NUMBER39_tree=null;
CommonTree char_literal40_tree=null;
CommonTree NUMBER41_tree=null;
CommonTree char_literal42_tree=null;
CommonTree BETWEEN44_tree=null;
CommonTree char_literal45_tree=null;
CommonTree char_literal47_tree=null;
CommonTree char_literal49_tree=null;
CommonTree BETWEEN51_tree=null;
CommonTree char_literal52_tree=null;
CommonTree char_literal54_tree=null;
CommonTree char_literal56_tree=null;
RewriteRuleTokenStream stream_35=new RewriteRuleTokenStream(adaptor,"token 35");
RewriteRuleTokenStream stream_33=new RewriteRuleTokenStream(adaptor,"token 33");
RewriteRuleTokenStream stream_BETWEEN=new RewriteRuleTokenStream(adaptor,"token BETWEEN");
RewriteRuleTokenStream stream_34=new RewriteRuleTokenStream(adaptor,"token 34");
RewriteRuleTokenStream stream_NUMBER=new RewriteRuleTokenStream(adaptor,"token NUMBER");
RewriteRuleSubtreeStream stream_time_string_function=new RewriteRuleSubtreeStream(adaptor,"rule time_string_function");
RewriteRuleSubtreeStream stream_time_millis_function=new RewriteRuleSubtreeStream(adaptor,"rule time_millis_function");
RewriteRuleSubtreeStream stream_path_function=new RewriteRuleSubtreeStream(adaptor,"rule path_function");
try {
// MessageFilter.g:138:2: ( path_function BETWEEN '(' NUMBER ',' NUMBER ')' -> ^( BETWEEN path_function NUMBER NUMBER ) | path_function BETWEEN '(' time_millis_function ',' time_millis_function ')' -> ^( BETWEEN path_function time_millis_function time_millis_function ) | path_function BETWEEN '(' time_string_function ',' time_string_function ')' -> ^( BETWEEN path_function time_string_function time_string_function ) )
int alt7=3;
int LA7_0 = input.LA(1);
if ( (LA7_0==XPATH_FUN_NAME) ) {
int LA7_1 = input.LA(2);
if ( (LA7_1==33) ) {
int LA7_2 = input.LA(3);
if ( (LA7_2==STRING) ) {
int LA7_3 = input.LA(4);
if ( (LA7_3==34) ) {
int LA7_4 = input.LA(5);
if ( (LA7_4==BETWEEN) ) {
int LA7_5 = input.LA(6);
if ( (LA7_5==33) ) {
switch ( input.LA(7) ) {
case NUMBER:
{
alt7=1;
}
break;
case TIME_MILLIS_FUN_NAME:
case 35:
{
alt7=2;
}
break;
case TIME_STRING_FUN_NAME:
{
alt7=3;
}
break;
default:
NoViableAltException nvae =
new NoViableAltException("", 7, 6, input);
throw nvae;
}
}
else {
NoViableAltException nvae =
new NoViableAltException("", 7, 5, input);
throw nvae;
}
}
else {
NoViableAltException nvae =
new NoViableAltException("", 7, 4, input);
throw nvae;
}
}
else {
NoViableAltException nvae =
new NoViableAltException("", 7, 3, input);
throw nvae;
}
}
else {
NoViableAltException nvae =
new NoViableAltException("", 7, 2, input);
throw nvae;
}
}
else {
NoViableAltException nvae =
new NoViableAltException("", 7, 1, input);
throw nvae;
}
}
else {
NoViableAltException nvae =
new NoViableAltException("", 7, 0, input);
throw nvae;
}
switch (alt7) {
case 1 :
// MessageFilter.g:138:4: path_function BETWEEN '(' NUMBER ',' NUMBER ')'
{
pushFollow(FOLLOW_path_function_in_between_predicate673);
path_function36=path_function();
state._fsp--;
stream_path_function.add(path_function36.getTree());
BETWEEN37=(Token)match(input,BETWEEN,FOLLOW_BETWEEN_in_between_predicate675);
stream_BETWEEN.add(BETWEEN37);
char_literal38=(Token)match(input,33,FOLLOW_33_in_between_predicate677);
stream_33.add(char_literal38);
NUMBER39=(Token)match(input,NUMBER,FOLLOW_NUMBER_in_between_predicate679);
stream_NUMBER.add(NUMBER39);
char_literal40=(Token)match(input,35,FOLLOW_35_in_between_predicate681);
stream_35.add(char_literal40);
NUMBER41=(Token)match(input,NUMBER,FOLLOW_NUMBER_in_between_predicate683);
stream_NUMBER.add(NUMBER41);
char_literal42=(Token)match(input,34,FOLLOW_34_in_between_predicate685);
stream_34.add(char_literal42);
// AST REWRITE
// elements: NUMBER, path_function, NUMBER, BETWEEN
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (CommonTree)adaptor.nil();
// 139:4: -> ^( BETWEEN path_function NUMBER NUMBER )
{
// MessageFilter.g:139:7: ^( BETWEEN path_function NUMBER NUMBER )
{
CommonTree root_1 = (CommonTree)adaptor.nil();
root_1 = (CommonTree)adaptor.becomeRoot(
new BetweenTreeNode(stream_BETWEEN.nextToken())
, root_1);
adaptor.addChild(root_1, stream_path_function.nextTree());
adaptor.addChild(root_1,
new NumberTreeNode(stream_NUMBER.nextToken())
);
adaptor.addChild(root_1,
new NumberTreeNode(stream_NUMBER.nextToken())
);
adaptor.addChild(root_0, root_1);
}
}
retval.tree = root_0;
}
break;
case 2 :
// MessageFilter.g:140:3: path_function BETWEEN '(' time_millis_function ',' time_millis_function ')'
{
pushFollow(FOLLOW_path_function_in_between_predicate716);
path_function43=path_function();
state._fsp--;
stream_path_function.add(path_function43.getTree());
BETWEEN44=(Token)match(input,BETWEEN,FOLLOW_BETWEEN_in_between_predicate718);
stream_BETWEEN.add(BETWEEN44);
char_literal45=(Token)match(input,33,FOLLOW_33_in_between_predicate720);
stream_33.add(char_literal45);
pushFollow(FOLLOW_time_millis_function_in_between_predicate722);
time_millis_function46=time_millis_function();
state._fsp--;
stream_time_millis_function.add(time_millis_function46.getTree());
char_literal47=(Token)match(input,35,FOLLOW_35_in_between_predicate724);
stream_35.add(char_literal47);
pushFollow(FOLLOW_time_millis_function_in_between_predicate726);
time_millis_function48=time_millis_function();
state._fsp--;
stream_time_millis_function.add(time_millis_function48.getTree());
char_literal49=(Token)match(input,34,FOLLOW_34_in_between_predicate728);
stream_34.add(char_literal49);
// AST REWRITE
// elements: time_millis_function, BETWEEN, time_millis_function, path_function
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (CommonTree)adaptor.nil();
// 141:4: -> ^( BETWEEN path_function time_millis_function time_millis_function )
{
// MessageFilter.g:141:7: ^( BETWEEN path_function time_millis_function time_millis_function )
{
CommonTree root_1 = (CommonTree)adaptor.nil();
root_1 = (CommonTree)adaptor.becomeRoot(
new BetweenTimeMillisTreeNode(stream_BETWEEN.nextToken())
, root_1);
adaptor.addChild(root_1, stream_path_function.nextTree());
adaptor.addChild(root_1, stream_time_millis_function.nextTree());
adaptor.addChild(root_1, stream_time_millis_function.nextTree());
adaptor.addChild(root_0, root_1);
}
}
retval.tree = root_0;
}
break;
case 3 :
// MessageFilter.g:142:3: path_function BETWEEN '(' time_string_function ',' time_string_function ')'
{
pushFollow(FOLLOW_path_function_in_between_predicate753);
path_function50=path_function();
state._fsp--;
stream_path_function.add(path_function50.getTree());
BETWEEN51=(Token)match(input,BETWEEN,FOLLOW_BETWEEN_in_between_predicate755);
stream_BETWEEN.add(BETWEEN51);
char_literal52=(Token)match(input,33,FOLLOW_33_in_between_predicate757);
stream_33.add(char_literal52);
pushFollow(FOLLOW_time_string_function_in_between_predicate759);
time_string_function53=time_string_function();
state._fsp--;
stream_time_string_function.add(time_string_function53.getTree());
char_literal54=(Token)match(input,35,FOLLOW_35_in_between_predicate761);
stream_35.add(char_literal54);
pushFollow(FOLLOW_time_string_function_in_between_predicate763);
time_string_function55=time_string_function();
state._fsp--;
stream_time_string_function.add(time_string_function55.getTree());
char_literal56=(Token)match(input,34,FOLLOW_34_in_between_predicate765);
stream_34.add(char_literal56);
// AST REWRITE
// elements: time_string_function, path_function, BETWEEN, time_string_function
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (CommonTree)adaptor.nil();
// 143:4: -> ^( BETWEEN path_function time_string_function time_string_function )
{
// MessageFilter.g:143:7: ^( BETWEEN path_function time_string_function time_string_function )
{
CommonTree root_1 = (CommonTree)adaptor.nil();
root_1 = (CommonTree)adaptor.becomeRoot(
new BetweenTimeStringTreeNode(stream_BETWEEN.nextToken())
, root_1);
adaptor.addChild(root_1, stream_path_function.nextTree());
adaptor.addChild(root_1, stream_time_string_function.nextTree());
adaptor.addChild(root_1, stream_time_string_function.nextTree());
adaptor.addChild(root_0, root_1);
}
}
retval.tree = root_0;
}
break;
}
retval.stop = input.LT(-1);
retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "between_predicate"
public static class in_predicate_return extends ParserRuleReturnScope {
CommonTree tree;
public Object getTree() { return tree; }
};
// $ANTLR start "in_predicate"
// MessageFilter.g:146:1: in_predicate : ( path_function IN '(' STRING ( ',' STRING )* ')' -> ^( IN path_function ( STRING )+ ) | path_function IN '(' NUMBER ( ',' NUMBER )* ')' -> ^( IN path_function ( NUMBER )+ ) );
public final in_predicate_return in_predicate() throws RecognitionException {
in_predicate_return retval = new in_predicate_return();
retval.start = input.LT(1);
CommonTree root_0 = null;
Token IN58=null;
Token char_literal59=null;
Token STRING60=null;
Token char_literal61=null;
Token STRING62=null;
Token char_literal63=null;
Token IN65=null;
Token char_literal66=null;
Token NUMBER67=null;
Token char_literal68=null;
Token NUMBER69=null;
Token char_literal70=null;
path_function_return path_function57 =null;
path_function_return path_function64 =null;
CommonTree IN58_tree=null;
CommonTree char_literal59_tree=null;
CommonTree STRING60_tree=null;
CommonTree char_literal61_tree=null;
CommonTree STRING62_tree=null;
CommonTree char_literal63_tree=null;
CommonTree IN65_tree=null;
CommonTree char_literal66_tree=null;
CommonTree NUMBER67_tree=null;
CommonTree char_literal68_tree=null;
CommonTree NUMBER69_tree=null;
CommonTree char_literal70_tree=null;
RewriteRuleTokenStream stream_IN=new RewriteRuleTokenStream(adaptor,"token IN");
RewriteRuleTokenStream stream_35=new RewriteRuleTokenStream(adaptor,"token 35");
RewriteRuleTokenStream stream_33=new RewriteRuleTokenStream(adaptor,"token 33");
RewriteRuleTokenStream stream_34=new RewriteRuleTokenStream(adaptor,"token 34");
RewriteRuleTokenStream stream_STRING=new RewriteRuleTokenStream(adaptor,"token STRING");
RewriteRuleTokenStream stream_NUMBER=new RewriteRuleTokenStream(adaptor,"token NUMBER");
RewriteRuleSubtreeStream stream_path_function=new RewriteRuleSubtreeStream(adaptor,"rule path_function");
try {
// MessageFilter.g:147:2: ( path_function IN '(' STRING ( ',' STRING )* ')' -> ^( IN path_function ( STRING )+ ) | path_function IN '(' NUMBER ( ',' NUMBER )* ')' -> ^( IN path_function ( NUMBER )+ ) )
int alt10=2;
int LA10_0 = input.LA(1);
if ( (LA10_0==XPATH_FUN_NAME) ) {
int LA10_1 = input.LA(2);
if ( (LA10_1==33) ) {
int LA10_2 = input.LA(3);
if ( (LA10_2==STRING) ) {
int LA10_3 = input.LA(4);
if ( (LA10_3==34) ) {
int LA10_4 = input.LA(5);
if ( (LA10_4==IN) ) {
int LA10_5 = input.LA(6);
if ( (LA10_5==33) ) {
int LA10_6 = input.LA(7);
if ( (LA10_6==STRING) ) {
alt10=1;
}
else if ( (LA10_6==NUMBER) ) {
alt10=2;
}
else {
NoViableAltException nvae =
new NoViableAltException("", 10, 6, input);
throw nvae;
}
}
else {
NoViableAltException nvae =
new NoViableAltException("", 10, 5, input);
throw nvae;
}
}
else {
NoViableAltException nvae =
new NoViableAltException("", 10, 4, input);
throw nvae;
}
}
else {
NoViableAltException nvae =
new NoViableAltException("", 10, 3, input);
throw nvae;
}
}
else {
NoViableAltException nvae =
new NoViableAltException("", 10, 2, input);
throw nvae;
}
}
else {
NoViableAltException nvae =
new NoViableAltException("", 10, 1, input);
throw nvae;
}
}
else {
NoViableAltException nvae =
new NoViableAltException("", 10, 0, input);
throw nvae;
}
switch (alt10) {
case 1 :
// MessageFilter.g:147:4: path_function IN '(' STRING ( ',' STRING )* ')'
{
pushFollow(FOLLOW_path_function_in_in_predicate796);
path_function57=path_function();
state._fsp--;
stream_path_function.add(path_function57.getTree());
IN58=(Token)match(input,IN,FOLLOW_IN_in_in_predicate798);
stream_IN.add(IN58);
char_literal59=(Token)match(input,33,FOLLOW_33_in_in_predicate800);
stream_33.add(char_literal59);
STRING60=(Token)match(input,STRING,FOLLOW_STRING_in_in_predicate802);
stream_STRING.add(STRING60);
// MessageFilter.g:147:32: ( ',' STRING )*
loop8:
do {
int alt8=2;
int LA8_0 = input.LA(1);
if ( (LA8_0==35) ) {
alt8=1;
}
switch (alt8) {
case 1 :
// MessageFilter.g:147:33: ',' STRING
{
char_literal61=(Token)match(input,35,FOLLOW_35_in_in_predicate805);
stream_35.add(char_literal61);
STRING62=(Token)match(input,STRING,FOLLOW_STRING_in_in_predicate807);
stream_STRING.add(STRING62);
}
break;
default :
break loop8;
}
} while (true);
char_literal63=(Token)match(input,34,FOLLOW_34_in_in_predicate811);
stream_34.add(char_literal63);
// AST REWRITE
// elements: IN, STRING, path_function
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (CommonTree)adaptor.nil();
// 147:50: -> ^( IN path_function ( STRING )+ )
{
// MessageFilter.g:147:53: ^( IN path_function ( STRING )+ )
{
CommonTree root_1 = (CommonTree)adaptor.nil();
root_1 = (CommonTree)adaptor.becomeRoot(
new StringInTreeNode(stream_IN.nextToken())
, root_1);
adaptor.addChild(root_1, stream_path_function.nextTree());
if ( !(stream_STRING.hasNext()) ) {
throw new RewriteEarlyExitException();
}
while ( stream_STRING.hasNext() ) {
adaptor.addChild(root_1,
new StringTreeNode(stream_STRING.nextToken())
);
}
stream_STRING.reset();
adaptor.addChild(root_0, root_1);
}
}
retval.tree = root_0;
}
break;
case 2 :
// MessageFilter.g:148:3: path_function IN '(' NUMBER ( ',' NUMBER )* ')'
{
pushFollow(FOLLOW_path_function_in_in_predicate836);
path_function64=path_function();
state._fsp--;
stream_path_function.add(path_function64.getTree());
IN65=(Token)match(input,IN,FOLLOW_IN_in_in_predicate838);
stream_IN.add(IN65);
char_literal66=(Token)match(input,33,FOLLOW_33_in_in_predicate840);
stream_33.add(char_literal66);
NUMBER67=(Token)match(input,NUMBER,FOLLOW_NUMBER_in_in_predicate842);
stream_NUMBER.add(NUMBER67);
// MessageFilter.g:148:31: ( ',' NUMBER )*
loop9:
do {
int alt9=2;
int LA9_0 = input.LA(1);
if ( (LA9_0==35) ) {
alt9=1;
}
switch (alt9) {
case 1 :
// MessageFilter.g:148:32: ',' NUMBER
{
char_literal68=(Token)match(input,35,FOLLOW_35_in_in_predicate845);
stream_35.add(char_literal68);
NUMBER69=(Token)match(input,NUMBER,FOLLOW_NUMBER_in_in_predicate847);
stream_NUMBER.add(NUMBER69);
}
break;
default :
break loop9;
}
} while (true);
char_literal70=(Token)match(input,34,FOLLOW_34_in_in_predicate851);
stream_34.add(char_literal70);
// AST REWRITE
// elements: NUMBER, path_function, IN
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (CommonTree)adaptor.nil();
// 148:49: -> ^( IN path_function ( NUMBER )+ )
{
// MessageFilter.g:148:52: ^( IN path_function ( NUMBER )+ )
{
CommonTree root_1 = (CommonTree)adaptor.nil();
root_1 = (CommonTree)adaptor.becomeRoot(
new NumericInTreeNode(stream_IN.nextToken())
, root_1);
adaptor.addChild(root_1, stream_path_function.nextTree());
if ( !(stream_NUMBER.hasNext()) ) {
throw new RewriteEarlyExitException();
}
while ( stream_NUMBER.hasNext() ) {
adaptor.addChild(root_1,
new NumberTreeNode(stream_NUMBER.nextToken())
);
}
stream_NUMBER.reset();
adaptor.addChild(root_0, root_1);
}
}
retval.tree = root_0;
}
break;
}
retval.stop = input.LT(-1);
retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "in_predicate"
public static class null_predicate_return extends ParserRuleReturnScope {
CommonTree tree;
public Object getTree() { return tree; }
};
// $ANTLR start "null_predicate"
// MessageFilter.g:151:1: null_predicate : path_function IS NULL -> ^( NULL path_function ) ;
public final null_predicate_return null_predicate() throws RecognitionException {
null_predicate_return retval = new null_predicate_return();
retval.start = input.LT(1);
CommonTree root_0 = null;
Token IS72=null;
Token NULL73=null;
path_function_return path_function71 =null;
CommonTree IS72_tree=null;
CommonTree NULL73_tree=null;
RewriteRuleTokenStream stream_IS=new RewriteRuleTokenStream(adaptor,"token IS");
RewriteRuleTokenStream stream_NULL=new RewriteRuleTokenStream(adaptor,"token NULL");
RewriteRuleSubtreeStream stream_path_function=new RewriteRuleSubtreeStream(adaptor,"rule path_function");
try {
// MessageFilter.g:152:2: ( path_function IS NULL -> ^( NULL path_function ) )
// MessageFilter.g:152:4: path_function IS NULL
{
pushFollow(FOLLOW_path_function_in_null_predicate881);
path_function71=path_function();
state._fsp--;
stream_path_function.add(path_function71.getTree());
IS72=(Token)match(input,IS,FOLLOW_IS_in_null_predicate883);
stream_IS.add(IS72);
NULL73=(Token)match(input,NULL,FOLLOW_NULL_in_null_predicate885);
stream_NULL.add(NULL73);
// AST REWRITE
// elements: path_function, NULL
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (CommonTree)adaptor.nil();
// 152:26: -> ^( NULL path_function )
{
// MessageFilter.g:152:29: ^( NULL path_function )
{
CommonTree root_1 = (CommonTree)adaptor.nil();
root_1 = (CommonTree)adaptor.becomeRoot(
new NullTreeNode(stream_NULL.nextToken())
, root_1);
adaptor.addChild(root_1, stream_path_function.nextTree());
adaptor.addChild(root_0, root_1);
}
}
retval.tree = root_0;
}
retval.stop = input.LT(-1);
retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "null_predicate"
public static class regex_predicate_return extends ParserRuleReturnScope {
CommonTree tree;
public Object getTree() { return tree; }
};
// $ANTLR start "regex_predicate"
// MessageFilter.g:155:1: regex_predicate : path_function MATCHES STRING -> ^( MATCHES path_function STRING ) ;
public final regex_predicate_return regex_predicate() throws RecognitionException {
regex_predicate_return retval = new regex_predicate_return();
retval.start = input.LT(1);
CommonTree root_0 = null;
Token MATCHES75=null;
Token STRING76=null;
path_function_return path_function74 =null;
CommonTree MATCHES75_tree=null;
CommonTree STRING76_tree=null;
RewriteRuleTokenStream stream_MATCHES=new RewriteRuleTokenStream(adaptor,"token MATCHES");
RewriteRuleTokenStream stream_STRING=new RewriteRuleTokenStream(adaptor,"token STRING");
RewriteRuleSubtreeStream stream_path_function=new RewriteRuleSubtreeStream(adaptor,"rule path_function");
try {
// MessageFilter.g:156:2: ( path_function MATCHES STRING -> ^( MATCHES path_function STRING ) )
// MessageFilter.g:156:6: path_function MATCHES STRING
{
pushFollow(FOLLOW_path_function_in_regex_predicate909);
path_function74=path_function();
state._fsp--;
stream_path_function.add(path_function74.getTree());
MATCHES75=(Token)match(input,MATCHES,FOLLOW_MATCHES_in_regex_predicate911);
stream_MATCHES.add(MATCHES75);
STRING76=(Token)match(input,STRING,FOLLOW_STRING_in_regex_predicate913);
stream_STRING.add(STRING76);
// AST REWRITE
// elements: MATCHES, path_function, STRING
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (CommonTree)adaptor.nil();
// 156:35: -> ^( MATCHES path_function STRING )
{
// MessageFilter.g:156:38: ^( MATCHES path_function STRING )
{
CommonTree root_1 = (CommonTree)adaptor.nil();
root_1 = (CommonTree)adaptor.becomeRoot(
new MatchesTreeNode(stream_MATCHES.nextToken())
, root_1);
adaptor.addChild(root_1, stream_path_function.nextTree());
adaptor.addChild(root_1,
new StringTreeNode(stream_STRING.nextToken())
);
adaptor.addChild(root_0, root_1);
}
}
retval.tree = root_0;
}
retval.stop = input.LT(-1);
retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "regex_predicate"
public static class exists_predicate_return extends ParserRuleReturnScope {
CommonTree tree;
public Object getTree() { return tree; }
};
// $ANTLR start "exists_predicate"
// MessageFilter.g:159:1: exists_predicate : ( path_function EXISTS -> ^( EXISTS path_function ) | EXISTS path_function -> ^( EXISTS path_function ) );
public final exists_predicate_return exists_predicate() throws RecognitionException {
exists_predicate_return retval = new exists_predicate_return();
retval.start = input.LT(1);
CommonTree root_0 = null;
Token EXISTS78=null;
Token EXISTS79=null;
path_function_return path_function77 =null;
path_function_return path_function80 =null;
CommonTree EXISTS78_tree=null;
CommonTree EXISTS79_tree=null;
RewriteRuleTokenStream stream_EXISTS=new RewriteRuleTokenStream(adaptor,"token EXISTS");
RewriteRuleSubtreeStream stream_path_function=new RewriteRuleSubtreeStream(adaptor,"rule path_function");
try {
// MessageFilter.g:160:2: ( path_function EXISTS -> ^( EXISTS path_function ) | EXISTS path_function -> ^( EXISTS path_function ) )
int alt11=2;
int LA11_0 = input.LA(1);
if ( (LA11_0==XPATH_FUN_NAME) ) {
alt11=1;
}
else if ( (LA11_0==EXISTS) ) {
alt11=2;
}
else {
NoViableAltException nvae =
new NoViableAltException("", 11, 0, input);
throw nvae;
}
switch (alt11) {
case 1 :
// MessageFilter.g:160:4: path_function EXISTS
{
pushFollow(FOLLOW_path_function_in_exists_predicate940);
path_function77=path_function();
state._fsp--;
stream_path_function.add(path_function77.getTree());
EXISTS78=(Token)match(input,EXISTS,FOLLOW_EXISTS_in_exists_predicate942);
stream_EXISTS.add(EXISTS78);
// AST REWRITE
// elements: EXISTS, path_function
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (CommonTree)adaptor.nil();
// 160:25: -> ^( EXISTS path_function )
{
// MessageFilter.g:160:28: ^( EXISTS path_function )
{
CommonTree root_1 = (CommonTree)adaptor.nil();
root_1 = (CommonTree)adaptor.becomeRoot(
new ExistsTreeNode(stream_EXISTS.nextToken())
, root_1);
adaptor.addChild(root_1, stream_path_function.nextTree());
adaptor.addChild(root_0, root_1);
}
}
retval.tree = root_0;
}
break;
case 2 :
// MessageFilter.g:161:3: EXISTS path_function
{
EXISTS79=(Token)match(input,EXISTS,FOLLOW_EXISTS_in_exists_predicate959);
stream_EXISTS.add(EXISTS79);
pushFollow(FOLLOW_path_function_in_exists_predicate961);
path_function80=path_function();
state._fsp--;
stream_path_function.add(path_function80.getTree());
// AST REWRITE
// elements: path_function, EXISTS
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (CommonTree)adaptor.nil();
// 161:24: -> ^( EXISTS path_function )
{
// MessageFilter.g:161:27: ^( EXISTS path_function )
{
CommonTree root_1 = (CommonTree)adaptor.nil();
root_1 = (CommonTree)adaptor.becomeRoot(
new ExistsTreeNode(stream_EXISTS.nextToken())
, root_1);
adaptor.addChild(root_1, stream_path_function.nextTree());
adaptor.addChild(root_0, root_1);
}
}
retval.tree = root_0;
}
break;
}
retval.stop = input.LT(-1);
retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "exists_predicate"
public static class path_function_return extends ParserRuleReturnScope {
CommonTree tree;
public Object getTree() { return tree; }
};
// $ANTLR start "path_function"
// MessageFilter.g:164:1: path_function : XPATH_FUN_NAME '(' STRING ')' -> ^( XPATH_FUN_NAME STRING ) ;
public final path_function_return path_function() throws RecognitionException {
path_function_return retval = new path_function_return();
retval.start = input.LT(1);
CommonTree root_0 = null;
Token XPATH_FUN_NAME81=null;
Token char_literal82=null;
Token STRING83=null;
Token char_literal84=null;
CommonTree XPATH_FUN_NAME81_tree=null;
CommonTree char_literal82_tree=null;
CommonTree STRING83_tree=null;
CommonTree char_literal84_tree=null;
RewriteRuleTokenStream stream_XPATH_FUN_NAME=new RewriteRuleTokenStream(adaptor,"token XPATH_FUN_NAME");
RewriteRuleTokenStream stream_33=new RewriteRuleTokenStream(adaptor,"token 33");
RewriteRuleTokenStream stream_34=new RewriteRuleTokenStream(adaptor,"token 34");
RewriteRuleTokenStream stream_STRING=new RewriteRuleTokenStream(adaptor,"token STRING");
try {
// MessageFilter.g:165:2: ( XPATH_FUN_NAME '(' STRING ')' -> ^( XPATH_FUN_NAME STRING ) )
// MessageFilter.g:165:4: XPATH_FUN_NAME '(' STRING ')'
{
XPATH_FUN_NAME81=(Token)match(input,XPATH_FUN_NAME,FOLLOW_XPATH_FUN_NAME_in_path_function990);
stream_XPATH_FUN_NAME.add(XPATH_FUN_NAME81);
char_literal82=(Token)match(input,33,FOLLOW_33_in_path_function992);
stream_33.add(char_literal82);
STRING83=(Token)match(input,STRING,FOLLOW_STRING_in_path_function994);
stream_STRING.add(STRING83);
char_literal84=(Token)match(input,34,FOLLOW_34_in_path_function996);
stream_34.add(char_literal84);
// AST REWRITE
// elements: XPATH_FUN_NAME, STRING
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (CommonTree)adaptor.nil();
// 165:34: -> ^( XPATH_FUN_NAME STRING )
{
// MessageFilter.g:165:37: ^( XPATH_FUN_NAME STRING )
{
CommonTree root_1 = (CommonTree)adaptor.nil();
root_1 = (CommonTree)adaptor.becomeRoot(
new XPathTreeNode(stream_XPATH_FUN_NAME.nextToken())
, root_1);
adaptor.addChild(root_1,
new StringTreeNode(stream_STRING.nextToken())
);
adaptor.addChild(root_0, root_1);
}
}
retval.tree = root_0;
}
retval.stop = input.LT(-1);
retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "path_function"
public static class value_function_return extends ParserRuleReturnScope {
CommonTree tree;
public Object getTree() { return tree; }
};
// $ANTLR start "value_function"
// MessageFilter.g:168:1: value_function : ( equality_value_function | compariable_value_function );
public final value_function_return value_function() throws RecognitionException {
value_function_return retval = new value_function_return();
retval.start = input.LT(1);
CommonTree root_0 = null;
equality_value_function_return equality_value_function85 =null;
compariable_value_function_return compariable_value_function86 =null;
try {
// MessageFilter.g:169:2: ( equality_value_function | compariable_value_function )
int alt12=2;
int LA12_0 = input.LA(1);
if ( (LA12_0==FALSE||LA12_0==NULL||LA12_0==STRING||LA12_0==TRUE||LA12_0==XPATH_FUN_NAME) ) {
alt12=1;
}
else if ( (LA12_0==EOF||LA12_0==AND||LA12_0==NUMBER||LA12_0==OR||(LA12_0 >= TIME_MILLIS_FUN_NAME && LA12_0 <= TIME_STRING_FUN_NAME)||(LA12_0 >= 34 && LA12_0 <= 35)) ) {
alt12=2;
}
else {
NoViableAltException nvae =
new NoViableAltException("", 12, 0, input);
throw nvae;
}
switch (alt12) {
case 1 :
// MessageFilter.g:169:4: equality_value_function
{
root_0 = (CommonTree)adaptor.nil();
pushFollow(FOLLOW_equality_value_function_in_value_function1022);
equality_value_function85=equality_value_function();
state._fsp--;
adaptor.addChild(root_0, equality_value_function85.getTree());
}
break;
case 2 :
// MessageFilter.g:169:30: compariable_value_function
{
root_0 = (CommonTree)adaptor.nil();
pushFollow(FOLLOW_compariable_value_function_in_value_function1026);
compariable_value_function86=compariable_value_function();
state._fsp--;
adaptor.addChild(root_0, compariable_value_function86.getTree());
}
break;
}
retval.stop = input.LT(-1);
retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "value_function"
public static class equality_value_function_return extends ParserRuleReturnScope {
CommonTree tree;
public Object getTree() { return tree; }
};
// $ANTLR start "equality_value_function"
// MessageFilter.g:172:1: equality_value_function : ( STRING -> STRING | TRUE -> TRUE | FALSE -> FALSE | NULL -> NULL | path_function );
public final equality_value_function_return equality_value_function() throws RecognitionException {
equality_value_function_return retval = new equality_value_function_return();
retval.start = input.LT(1);
CommonTree root_0 = null;
Token STRING87=null;
Token TRUE88=null;
Token FALSE89=null;
Token NULL90=null;
path_function_return path_function91 =null;
CommonTree STRING87_tree=null;
CommonTree TRUE88_tree=null;
CommonTree FALSE89_tree=null;
CommonTree NULL90_tree=null;
RewriteRuleTokenStream stream_FALSE=new RewriteRuleTokenStream(adaptor,"token FALSE");
RewriteRuleTokenStream stream_TRUE=new RewriteRuleTokenStream(adaptor,"token TRUE");
RewriteRuleTokenStream stream_NULL=new RewriteRuleTokenStream(adaptor,"token NULL");
RewriteRuleTokenStream stream_STRING=new RewriteRuleTokenStream(adaptor,"token STRING");
try {
// MessageFilter.g:173:2: ( STRING -> STRING | TRUE -> TRUE | FALSE -> FALSE | NULL -> NULL | path_function )
int alt13=5;
switch ( input.LA(1) ) {
case STRING:
{
alt13=1;
}
break;
case TRUE:
{
alt13=2;
}
break;
case FALSE:
{
alt13=3;
}
break;
case NULL:
{
alt13=4;
}
break;
case XPATH_FUN_NAME:
{
alt13=5;
}
break;
default:
NoViableAltException nvae =
new NoViableAltException("", 13, 0, input);
throw nvae;
}
switch (alt13) {
case 1 :
// MessageFilter.g:173:4: STRING
{
STRING87=(Token)match(input,STRING,FOLLOW_STRING_in_equality_value_function1038);
stream_STRING.add(STRING87);
// AST REWRITE
// elements: STRING
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (CommonTree)adaptor.nil();
// 173:11: -> STRING
{
adaptor.addChild(root_0,
new StringTreeNode(stream_STRING.nextToken())
);
}
retval.tree = root_0;
}
break;
case 2 :
// MessageFilter.g:174:3: TRUE
{
TRUE88=(Token)match(input,TRUE,FOLLOW_TRUE_in_equality_value_function1051);
stream_TRUE.add(TRUE88);
// AST REWRITE
// elements: TRUE
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (CommonTree)adaptor.nil();
// 174:8: -> TRUE
{
adaptor.addChild(root_0,
new TrueValueTreeNode(stream_TRUE.nextToken())
);
}
retval.tree = root_0;
}
break;
case 3 :
// MessageFilter.g:175:3: FALSE
{
FALSE89=(Token)match(input,FALSE,FOLLOW_FALSE_in_equality_value_function1064);
stream_FALSE.add(FALSE89);
// AST REWRITE
// elements: FALSE
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (CommonTree)adaptor.nil();
// 175:9: -> FALSE
{
adaptor.addChild(root_0,
new FalseValueTreeNode(stream_FALSE.nextToken())
);
}
retval.tree = root_0;
}
break;
case 4 :
// MessageFilter.g:176:3: NULL
{
NULL90=(Token)match(input,NULL,FOLLOW_NULL_in_equality_value_function1077);
stream_NULL.add(NULL90);
// AST REWRITE
// elements: NULL
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (CommonTree)adaptor.nil();
// 176:8: -> NULL
{
adaptor.addChild(root_0,
new NullValueTreeNode(stream_NULL.nextToken())
);
}
retval.tree = root_0;
}
break;
case 5 :
// MessageFilter.g:177:3: path_function
{
root_0 = (CommonTree)adaptor.nil();
pushFollow(FOLLOW_path_function_in_equality_value_function1090);
path_function91=path_function();
state._fsp--;
adaptor.addChild(root_0, path_function91.getTree());
}
break;
}
retval.stop = input.LT(-1);
retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "equality_value_function"
public static class compariable_value_function_return extends ParserRuleReturnScope {
CommonTree tree;
public Object getTree() { return tree; }
};
// $ANTLR start "compariable_value_function"
// MessageFilter.g:180:1: compariable_value_function : ( NUMBER -> NUMBER | time_millis_function | time_string_function );
public final compariable_value_function_return compariable_value_function() throws RecognitionException {
compariable_value_function_return retval = new compariable_value_function_return();
retval.start = input.LT(1);
CommonTree root_0 = null;
Token NUMBER92=null;
time_millis_function_return time_millis_function93 =null;
time_string_function_return time_string_function94 =null;
CommonTree NUMBER92_tree=null;
RewriteRuleTokenStream stream_NUMBER=new RewriteRuleTokenStream(adaptor,"token NUMBER");
try {
// MessageFilter.g:181:2: ( NUMBER -> NUMBER | time_millis_function | time_string_function )
int alt14=3;
switch ( input.LA(1) ) {
case NUMBER:
{
alt14=1;
}
break;
case EOF:
case AND:
case OR:
case TIME_MILLIS_FUN_NAME:
case 34:
case 35:
{
alt14=2;
}
break;
case TIME_STRING_FUN_NAME:
{
alt14=3;
}
break;
default:
NoViableAltException nvae =
new NoViableAltException("", 14, 0, input);
throw nvae;
}
switch (alt14) {
case 1 :
// MessageFilter.g:181:4: NUMBER
{
NUMBER92=(Token)match(input,NUMBER,FOLLOW_NUMBER_in_compariable_value_function1102);
stream_NUMBER.add(NUMBER92);
// AST REWRITE
// elements: NUMBER
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (CommonTree)adaptor.nil();
// 181:11: -> NUMBER
{
adaptor.addChild(root_0,
new NumberTreeNode(stream_NUMBER.nextToken())
);
}
retval.tree = root_0;
}
break;
case 2 :
// MessageFilter.g:182:3: time_millis_function
{
root_0 = (CommonTree)adaptor.nil();
pushFollow(FOLLOW_time_millis_function_in_compariable_value_function1114);
time_millis_function93=time_millis_function();
state._fsp--;
adaptor.addChild(root_0, time_millis_function93.getTree());
}
break;
case 3 :
// MessageFilter.g:183:3: time_string_function
{
root_0 = (CommonTree)adaptor.nil();
pushFollow(FOLLOW_time_string_function_in_compariable_value_function1120);
time_string_function94=time_string_function();
state._fsp--;
adaptor.addChild(root_0, time_string_function94.getTree());
}
break;
}
retval.stop = input.LT(-1);
retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "compariable_value_function"
public static class time_millis_function_return extends ParserRuleReturnScope {
CommonTree tree;
public Object getTree() { return tree; }
};
// $ANTLR start "time_millis_function"
// MessageFilter.g:186:1: time_millis_function : ( TIME_MILLIS_FUN_NAME '(' STRING ',' STRING ')' -> ^( TIME_MILLIS_FUN_NAME STRING STRING ) |);
public final time_millis_function_return time_millis_function() throws RecognitionException {
time_millis_function_return retval = new time_millis_function_return();
retval.start = input.LT(1);
CommonTree root_0 = null;
Token TIME_MILLIS_FUN_NAME95=null;
Token char_literal96=null;
Token STRING97=null;
Token char_literal98=null;
Token STRING99=null;
Token char_literal100=null;
CommonTree TIME_MILLIS_FUN_NAME95_tree=null;
CommonTree char_literal96_tree=null;
CommonTree STRING97_tree=null;
CommonTree char_literal98_tree=null;
CommonTree STRING99_tree=null;
CommonTree char_literal100_tree=null;
RewriteRuleTokenStream stream_35=new RewriteRuleTokenStream(adaptor,"token 35");
RewriteRuleTokenStream stream_33=new RewriteRuleTokenStream(adaptor,"token 33");
RewriteRuleTokenStream stream_34=new RewriteRuleTokenStream(adaptor,"token 34");
RewriteRuleTokenStream stream_TIME_MILLIS_FUN_NAME=new RewriteRuleTokenStream(adaptor,"token TIME_MILLIS_FUN_NAME");
RewriteRuleTokenStream stream_STRING=new RewriteRuleTokenStream(adaptor,"token STRING");
try {
// MessageFilter.g:187:2: ( TIME_MILLIS_FUN_NAME '(' STRING ',' STRING ')' -> ^( TIME_MILLIS_FUN_NAME STRING STRING ) |)
int alt15=2;
int LA15_0 = input.LA(1);
if ( (LA15_0==TIME_MILLIS_FUN_NAME) ) {
alt15=1;
}
else if ( (LA15_0==EOF||LA15_0==AND||LA15_0==OR||(LA15_0 >= 34 && LA15_0 <= 35)) ) {
alt15=2;
}
else {
NoViableAltException nvae =
new NoViableAltException("", 15, 0, input);
throw nvae;
}
switch (alt15) {
case 1 :
// MessageFilter.g:187:4: TIME_MILLIS_FUN_NAME '(' STRING ',' STRING ')'
{
TIME_MILLIS_FUN_NAME95=(Token)match(input,TIME_MILLIS_FUN_NAME,FOLLOW_TIME_MILLIS_FUN_NAME_in_time_millis_function1132);
stream_TIME_MILLIS_FUN_NAME.add(TIME_MILLIS_FUN_NAME95);
char_literal96=(Token)match(input,33,FOLLOW_33_in_time_millis_function1134);
stream_33.add(char_literal96);
STRING97=(Token)match(input,STRING,FOLLOW_STRING_in_time_millis_function1136);
stream_STRING.add(STRING97);
char_literal98=(Token)match(input,35,FOLLOW_35_in_time_millis_function1138);
stream_35.add(char_literal98);
STRING99=(Token)match(input,STRING,FOLLOW_STRING_in_time_millis_function1140);
stream_STRING.add(STRING99);
char_literal100=(Token)match(input,34,FOLLOW_34_in_time_millis_function1142);
stream_34.add(char_literal100);
// AST REWRITE
// elements: TIME_MILLIS_FUN_NAME, STRING, STRING
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (CommonTree)adaptor.nil();
// 187:51: -> ^( TIME_MILLIS_FUN_NAME STRING STRING )
{
// MessageFilter.g:187:54: ^( TIME_MILLIS_FUN_NAME STRING STRING )
{
CommonTree root_1 = (CommonTree)adaptor.nil();
root_1 = (CommonTree)adaptor.becomeRoot(
new TimeMillisValueTreeNode(stream_TIME_MILLIS_FUN_NAME.nextToken())
, root_1);
adaptor.addChild(root_1,
new StringTreeNode(stream_STRING.nextToken())
);
adaptor.addChild(root_1,
new StringTreeNode(stream_STRING.nextToken())
);
adaptor.addChild(root_0, root_1);
}
}
retval.tree = root_0;
}
break;
case 2 :
// MessageFilter.g:188:2:
{
root_0 = (CommonTree)adaptor.nil();
}
break;
}
retval.stop = input.LT(-1);
retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "time_millis_function"
public static class time_string_function_return extends ParserRuleReturnScope {
CommonTree tree;
public Object getTree() { return tree; }
};
// $ANTLR start "time_string_function"
// MessageFilter.g:193:1: time_string_function : TIME_STRING_FUN_NAME '(' STRING ',' STRING ',' STRING ')' -> ^( TIME_STRING_FUN_NAME STRING STRING STRING ) ;
public final time_string_function_return time_string_function() throws RecognitionException {
time_string_function_return retval = new time_string_function_return();
retval.start = input.LT(1);
CommonTree root_0 = null;
Token TIME_STRING_FUN_NAME101=null;
Token char_literal102=null;
Token STRING103=null;
Token char_literal104=null;
Token STRING105=null;
Token char_literal106=null;
Token STRING107=null;
Token char_literal108=null;
CommonTree TIME_STRING_FUN_NAME101_tree=null;
CommonTree char_literal102_tree=null;
CommonTree STRING103_tree=null;
CommonTree char_literal104_tree=null;
CommonTree STRING105_tree=null;
CommonTree char_literal106_tree=null;
CommonTree STRING107_tree=null;
CommonTree char_literal108_tree=null;
RewriteRuleTokenStream stream_35=new RewriteRuleTokenStream(adaptor,"token 35");
RewriteRuleTokenStream stream_TIME_STRING_FUN_NAME=new RewriteRuleTokenStream(adaptor,"token TIME_STRING_FUN_NAME");
RewriteRuleTokenStream stream_33=new RewriteRuleTokenStream(adaptor,"token 33");
RewriteRuleTokenStream stream_34=new RewriteRuleTokenStream(adaptor,"token 34");
RewriteRuleTokenStream stream_STRING=new RewriteRuleTokenStream(adaptor,"token STRING");
try {
// MessageFilter.g:194:2: ( TIME_STRING_FUN_NAME '(' STRING ',' STRING ',' STRING ')' -> ^( TIME_STRING_FUN_NAME STRING STRING STRING ) )
// MessageFilter.g:194:5: TIME_STRING_FUN_NAME '(' STRING ',' STRING ',' STRING ')'
{
TIME_STRING_FUN_NAME101=(Token)match(input,TIME_STRING_FUN_NAME,FOLLOW_TIME_STRING_FUN_NAME_in_time_string_function1179);
stream_TIME_STRING_FUN_NAME.add(TIME_STRING_FUN_NAME101);
char_literal102=(Token)match(input,33,FOLLOW_33_in_time_string_function1181);
stream_33.add(char_literal102);
STRING103=(Token)match(input,STRING,FOLLOW_STRING_in_time_string_function1183);
stream_STRING.add(STRING103);
char_literal104=(Token)match(input,35,FOLLOW_35_in_time_string_function1185);
stream_35.add(char_literal104);
STRING105=(Token)match(input,STRING,FOLLOW_STRING_in_time_string_function1187);
stream_STRING.add(STRING105);
char_literal106=(Token)match(input,35,FOLLOW_35_in_time_string_function1189);
stream_35.add(char_literal106);
STRING107=(Token)match(input,STRING,FOLLOW_STRING_in_time_string_function1191);
stream_STRING.add(STRING107);
char_literal108=(Token)match(input,34,FOLLOW_34_in_time_string_function1193);
stream_34.add(char_literal108);
// AST REWRITE
// elements: STRING, TIME_STRING_FUN_NAME, STRING, STRING
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (CommonTree)adaptor.nil();
// 194:63: -> ^( TIME_STRING_FUN_NAME STRING STRING STRING )
{
// MessageFilter.g:194:66: ^( TIME_STRING_FUN_NAME STRING STRING STRING )
{
CommonTree root_1 = (CommonTree)adaptor.nil();
root_1 = (CommonTree)adaptor.becomeRoot(
new TimeStringValueTreeNode(stream_TIME_STRING_FUN_NAME.nextToken())
, root_1);
adaptor.addChild(root_1,
new StringTreeNode(stream_STRING.nextToken())
);
adaptor.addChild(root_1,
new StringTreeNode(stream_STRING.nextToken())
);
adaptor.addChild(root_1,
new StringTreeNode(stream_STRING.nextToken())
);
adaptor.addChild(root_0, root_1);
}
}
retval.tree = root_0;
}
retval.stop = input.LT(-1);
retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "time_string_function"
// Delegated rules
public static final BitSet FOLLOW_boolean_expr_in_filter323 = new BitSet(new long[]{0x0000000002000002L});
public static final BitSet FOLLOW_OR_in_filter330 = new BitSet(new long[]{0x0000000320100A00L});
public static final BitSet FOLLOW_boolean_expr_in_filter334 = new BitSet(new long[]{0x0000000002000002L});
public static final BitSet FOLLOW_EOF_in_filter354 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_boolean_factor_in_boolean_expr370 = new BitSet(new long[]{0x0000000000000012L});
public static final BitSet FOLLOW_AND_in_boolean_expr377 = new BitSet(new long[]{0x0000000320100A00L});
public static final BitSet FOLLOW_boolean_factor_in_boolean_expr381 = new BitSet(new long[]{0x0000000000000012L});
public static final BitSet FOLLOW_predicate_in_boolean_factor414 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_NOT_in_boolean_factor423 = new BitSet(new long[]{0x0000000320000A00L});
public static final BitSet FOLLOW_predicate_in_boolean_factor425 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_33_in_predicate448 = new BitSet(new long[]{0x0000000320100A00L});
public static final BitSet FOLLOW_filter_in_predicate450 = new BitSet(new long[]{0x0000000400000000L});
public static final BitSet FOLLOW_34_in_predicate452 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_comparison_function_in_predicate463 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_between_predicate_in_predicate469 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_in_predicate_in_predicate475 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_null_predicate_in_predicate481 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_regex_predicate_in_predicate487 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_exists_predicate_in_predicate493 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_TRUE_in_predicate499 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_FALSE_in_predicate511 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_path_function_in_comparison_function529 = new BitSet(new long[]{0x0000000000000080L});
public static final BitSet FOLLOW_EQUALS_in_comparison_function531 = new BitSet(new long[]{0x000000013CC00800L});
public static final BitSet FOLLOW_value_function_in_comparison_function533 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_path_function_in_comparison_function552 = new BitSet(new long[]{0x0000000000200000L});
public static final BitSet FOLLOW_NOT_EQUALS_in_comparison_function554 = new BitSet(new long[]{0x000000013CC00800L});
public static final BitSet FOLLOW_value_function_in_comparison_function556 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_path_function_in_comparison_function575 = new BitSet(new long[]{0x0000000000002000L});
public static final BitSet FOLLOW_GT_in_comparison_function577 = new BitSet(new long[]{0x0000000018800000L});
public static final BitSet FOLLOW_compariable_value_function_in_comparison_function579 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_path_function_in_comparison_function598 = new BitSet(new long[]{0x0000000000001000L});
public static final BitSet FOLLOW_GE_in_comparison_function600 = new BitSet(new long[]{0x0000000018800000L});
public static final BitSet FOLLOW_compariable_value_function_in_comparison_function602 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_path_function_in_comparison_function621 = new BitSet(new long[]{0x0000000000040000L});
public static final BitSet FOLLOW_LT_in_comparison_function623 = new BitSet(new long[]{0x0000000018800000L});
public static final BitSet FOLLOW_compariable_value_function_in_comparison_function625 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_path_function_in_comparison_function644 = new BitSet(new long[]{0x0000000000020000L});
public static final BitSet FOLLOW_LE_in_comparison_function646 = new BitSet(new long[]{0x0000000018800000L});
public static final BitSet FOLLOW_compariable_value_function_in_comparison_function648 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_path_function_in_between_predicate673 = new BitSet(new long[]{0x0000000000000020L});
public static final BitSet FOLLOW_BETWEEN_in_between_predicate675 = new BitSet(new long[]{0x0000000200000000L});
public static final BitSet FOLLOW_33_in_between_predicate677 = new BitSet(new long[]{0x0000000000800000L});
public static final BitSet FOLLOW_NUMBER_in_between_predicate679 = new BitSet(new long[]{0x0000000800000000L});
public static final BitSet FOLLOW_35_in_between_predicate681 = new BitSet(new long[]{0x0000000000800000L});
public static final BitSet FOLLOW_NUMBER_in_between_predicate683 = new BitSet(new long[]{0x0000000400000000L});
public static final BitSet FOLLOW_34_in_between_predicate685 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_path_function_in_between_predicate716 = new BitSet(new long[]{0x0000000000000020L});
public static final BitSet FOLLOW_BETWEEN_in_between_predicate718 = new BitSet(new long[]{0x0000000200000000L});
public static final BitSet FOLLOW_33_in_between_predicate720 = new BitSet(new long[]{0x0000000808000000L});
public static final BitSet FOLLOW_time_millis_function_in_between_predicate722 = new BitSet(new long[]{0x0000000800000000L});
public static final BitSet FOLLOW_35_in_between_predicate724 = new BitSet(new long[]{0x0000000408000000L});
public static final BitSet FOLLOW_time_millis_function_in_between_predicate726 = new BitSet(new long[]{0x0000000400000000L});
public static final BitSet FOLLOW_34_in_between_predicate728 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_path_function_in_between_predicate753 = new BitSet(new long[]{0x0000000000000020L});
public static final BitSet FOLLOW_BETWEEN_in_between_predicate755 = new BitSet(new long[]{0x0000000200000000L});
public static final BitSet FOLLOW_33_in_between_predicate757 = new BitSet(new long[]{0x0000000010000000L});
public static final BitSet FOLLOW_time_string_function_in_between_predicate759 = new BitSet(new long[]{0x0000000800000000L});
public static final BitSet FOLLOW_35_in_between_predicate761 = new BitSet(new long[]{0x0000000010000000L});
public static final BitSet FOLLOW_time_string_function_in_between_predicate763 = new BitSet(new long[]{0x0000000400000000L});
public static final BitSet FOLLOW_34_in_between_predicate765 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_path_function_in_in_predicate796 = new BitSet(new long[]{0x0000000000008000L});
public static final BitSet FOLLOW_IN_in_in_predicate798 = new BitSet(new long[]{0x0000000200000000L});
public static final BitSet FOLLOW_33_in_in_predicate800 = new BitSet(new long[]{0x0000000004000000L});
public static final BitSet FOLLOW_STRING_in_in_predicate802 = new BitSet(new long[]{0x0000000C00000000L});
public static final BitSet FOLLOW_35_in_in_predicate805 = new BitSet(new long[]{0x0000000004000000L});
public static final BitSet FOLLOW_STRING_in_in_predicate807 = new BitSet(new long[]{0x0000000C00000000L});
public static final BitSet FOLLOW_34_in_in_predicate811 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_path_function_in_in_predicate836 = new BitSet(new long[]{0x0000000000008000L});
public static final BitSet FOLLOW_IN_in_in_predicate838 = new BitSet(new long[]{0x0000000200000000L});
public static final BitSet FOLLOW_33_in_in_predicate840 = new BitSet(new long[]{0x0000000000800000L});
public static final BitSet FOLLOW_NUMBER_in_in_predicate842 = new BitSet(new long[]{0x0000000C00000000L});
public static final BitSet FOLLOW_35_in_in_predicate845 = new BitSet(new long[]{0x0000000000800000L});
public static final BitSet FOLLOW_NUMBER_in_in_predicate847 = new BitSet(new long[]{0x0000000C00000000L});
public static final BitSet FOLLOW_34_in_in_predicate851 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_path_function_in_null_predicate881 = new BitSet(new long[]{0x0000000000010000L});
public static final BitSet FOLLOW_IS_in_null_predicate883 = new BitSet(new long[]{0x0000000000400000L});
public static final BitSet FOLLOW_NULL_in_null_predicate885 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_path_function_in_regex_predicate909 = new BitSet(new long[]{0x0000000000080000L});
public static final BitSet FOLLOW_MATCHES_in_regex_predicate911 = new BitSet(new long[]{0x0000000004000000L});
public static final BitSet FOLLOW_STRING_in_regex_predicate913 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_path_function_in_exists_predicate940 = new BitSet(new long[]{0x0000000000000200L});
public static final BitSet FOLLOW_EXISTS_in_exists_predicate942 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_EXISTS_in_exists_predicate959 = new BitSet(new long[]{0x0000000100000000L});
public static final BitSet FOLLOW_path_function_in_exists_predicate961 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_XPATH_FUN_NAME_in_path_function990 = new BitSet(new long[]{0x0000000200000000L});
public static final BitSet FOLLOW_33_in_path_function992 = new BitSet(new long[]{0x0000000004000000L});
public static final BitSet FOLLOW_STRING_in_path_function994 = new BitSet(new long[]{0x0000000400000000L});
public static final BitSet FOLLOW_34_in_path_function996 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_equality_value_function_in_value_function1022 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_compariable_value_function_in_value_function1026 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_STRING_in_equality_value_function1038 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_TRUE_in_equality_value_function1051 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_FALSE_in_equality_value_function1064 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_NULL_in_equality_value_function1077 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_path_function_in_equality_value_function1090 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_NUMBER_in_compariable_value_function1102 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_time_millis_function_in_compariable_value_function1114 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_time_string_function_in_compariable_value_function1120 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_TIME_MILLIS_FUN_NAME_in_time_millis_function1132 = new BitSet(new long[]{0x0000000200000000L});
public static final BitSet FOLLOW_33_in_time_millis_function1134 = new BitSet(new long[]{0x0000000004000000L});
public static final BitSet FOLLOW_STRING_in_time_millis_function1136 = new BitSet(new long[]{0x0000000800000000L});
public static final BitSet FOLLOW_35_in_time_millis_function1138 = new BitSet(new long[]{0x0000000004000000L});
public static final BitSet FOLLOW_STRING_in_time_millis_function1140 = new BitSet(new long[]{0x0000000400000000L});
public static final BitSet FOLLOW_34_in_time_millis_function1142 = new BitSet(new long[]{0x0000000000000002L});
public static final BitSet FOLLOW_TIME_STRING_FUN_NAME_in_time_string_function1179 = new BitSet(new long[]{0x0000000200000000L});
public static final BitSet FOLLOW_33_in_time_string_function1181 = new BitSet(new long[]{0x0000000004000000L});
public static final BitSet FOLLOW_STRING_in_time_string_function1183 = new BitSet(new long[]{0x0000000800000000L});
public static final BitSet FOLLOW_35_in_time_string_function1185 = new BitSet(new long[]{0x0000000004000000L});
public static final BitSet FOLLOW_STRING_in_time_string_function1187 = new BitSet(new long[]{0x0000000800000000L});
public static final BitSet FOLLOW_35_in_time_string_function1189 = new BitSet(new long[]{0x0000000004000000L});
public static final BitSet FOLLOW_STRING_in_time_string_function1191 = new BitSet(new long[]{0x0000000400000000L});
public static final BitSet FOLLOW_34_in_time_string_function1193 = new BitSet(new long[]{0x0000000000000002L});
}
| 6,809 |
0 | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/lang/BetweenTimeMillisTreeNode.java | package com.netflix.suro.routing.filter.lang;
import com.netflix.suro.routing.filter.*;
import org.antlr.runtime.Token;
import org.antlr.runtime.tree.Tree;
public class BetweenTimeMillisTreeNode extends MessageFilterBaseTreeNode implements MessageFilterTranslatable {
@Override
public MessageFilter translate() {
ValueTreeNode xpathNode = (ValueTreeNode)getChild(0);
String xpath = (String)xpathNode.getValue();
TimeMillisValueTreeNode lowerBoundNode = (TimeMillisValueTreeNode)getChild(1);
TimeMillisValueTreeNode upperBoundNode = (TimeMillisValueTreeNode)getChild(2);
return MessageFilters.and(
new PathValueMessageFilter(
xpath,
new TimeMillisValuePredicate(lowerBoundNode.getValueFormat(), lowerBoundNode.getValue(), ">=")),
new PathValueMessageFilter(
xpath,
new TimeMillisValuePredicate(upperBoundNode.getValueFormat(), upperBoundNode.getValue(), "<"))
);
}
public BetweenTimeMillisTreeNode(Token t) {
super(t);
}
public BetweenTimeMillisTreeNode(BetweenTimeMillisTreeNode node) {
super(node);
}
public Tree dupNode() {
return new BetweenTimeMillisTreeNode(this);
}
}
| 6,810 |
0 | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/lang/NullValueTreeNode.java | package com.netflix.suro.routing.filter.lang;
import org.antlr.runtime.Token;
import org.antlr.runtime.tree.Tree;
public class NullValueTreeNode extends MessageFilterBaseTreeNode implements ValueTreeNode {
@Override
public Object getValue() {
return null;
}
public NullValueTreeNode(Token t) {
super(t);
}
public NullValueTreeNode(NullValueTreeNode node) {
super(node);
}
public Tree dupNode() {
return new NullValueTreeNode(this);
}
}
| 6,811 |
0 | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/lang/TreeNodeUtil.java | package com.netflix.suro.routing.filter.lang;
import org.antlr.runtime.tree.Tree;
class TreeNodeUtil {
private TreeNodeUtil(){}
public static String getXPath(Tree pathNode) {
ValueTreeNode xpathNode = (ValueTreeNode)pathNode;
return (String)xpathNode.getValue();
}
}
| 6,812 |
0 | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/lang/UnexpectedTokenException.java | package com.netflix.suro.routing.filter.lang;
import com.google.common.base.Joiner;
import org.antlr.runtime.tree.Tree;
public class UnexpectedTokenException extends RuntimeException {
private Tree unexpected;
private String[] expected;
private Joiner joiner = Joiner.on(" or ");
public UnexpectedTokenException(Tree unexpected, String... expected){
this.unexpected = unexpected;
this.expected = expected;
}
@Override
public String toString() {
return String.format(
"Unexpected token %s at %d:%d. Expected: %s",
unexpected.getText(),
unexpected.getLine(),
unexpected.getCharPositionInLine(),
joiner.join(expected));
}
@Override
public String getMessage(){
return toString();
}
}
| 6,813 |
0 | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/lang/NumericInTreeNode.java | package com.netflix.suro.routing.filter.lang;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.netflix.suro.routing.filter.MessageFilter;
import com.netflix.suro.routing.filter.MessageFilters;
import com.netflix.suro.routing.filter.NumericValuePredicate;
import com.netflix.suro.routing.filter.PathValueMessageFilter;
import org.antlr.runtime.Token;
import org.antlr.runtime.tree.Tree;
import java.util.List;
import static com.netflix.suro.routing.filter.lang.TreeNodeUtil.getXPath;
public class NumericInTreeNode extends MessageFilterBaseTreeNode implements MessageFilterTranslatable {
@SuppressWarnings("unchecked")
@Override
public MessageFilter translate() {
final String xpath = getXPath(getChild(0));
List children = getChildren();
return MessageFilters.or(
Lists.transform(children.subList(1, children.size()), new Function<Object, MessageFilter>() {
@Override
public MessageFilter apply(Object node) {
Number value = ((NumberTreeNode) node).getValue();
return new PathValueMessageFilter(xpath, new NumericValuePredicate(value, "="));
}
})
);
}
public NumericInTreeNode(Token t) {
super(t);
}
public NumericInTreeNode(NumericInTreeNode node) {
super(node);
}
public Tree dupNode() {
return new NumericInTreeNode(this);
}
}
| 6,814 |
0 | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/lang/BetweenTimeStringTreeNode.java | package com.netflix.suro.routing.filter.lang;
import com.netflix.suro.routing.filter.*;
import org.antlr.runtime.Token;
import org.antlr.runtime.tree.Tree;
public class BetweenTimeStringTreeNode extends MessageFilterBaseTreeNode implements MessageFilterTranslatable {
@Override
public MessageFilter translate() {
ValueTreeNode xpathNode = (ValueTreeNode)getChild(0);
String xpath = (String)xpathNode.getValue();
TimeStringValueTreeNode lowerBoundNode = (TimeStringValueTreeNode)getChild(1);
TimeStringValueTreeNode upperBoundNode = (TimeStringValueTreeNode)getChild(2);
return MessageFilters.and(
new PathValueMessageFilter(
xpath,
new TimeStringValuePredicate(
lowerBoundNode.getValueTimeFormat(),
lowerBoundNode.getInputTimeFormat(),
lowerBoundNode.getValue(),
">=")),
new PathValueMessageFilter(
xpath,
new TimeStringValuePredicate(
upperBoundNode.getValueTimeFormat(),
upperBoundNode.getInputTimeFormat(),
upperBoundNode.getValue(),
"<"))
);
}
public BetweenTimeStringTreeNode(Token t) {
super(t);
}
public BetweenTimeStringTreeNode(BetweenTimeStringTreeNode node) {
super(node);
}
public Tree dupNode() {
return new BetweenTimeStringTreeNode(this);
}
}
| 6,815 |
0 | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/lang/InvalidFilterException.java | package com.netflix.suro.routing.filter.lang;
/**
* A generic exception representing an invalid filter expression.
*
* @author Nitesh Kant (nkant@netflix.com)
*/
public class InvalidFilterException extends Exception {
private static final long serialVersionUID = -5878696854757828678L;
private Object filter;
public InvalidFilterException(String message, Throwable cause, Object filter) {
super(String.format("Invalid filter %s. Error: %s", filter, message), cause);
this.filter = filter;
}
public InvalidFilterException(Throwable cause, Object filter) {
super(String.format("Invalid filter %s.", filter), cause);
this.filter = filter;
}
}
| 6,816 |
0 | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/lang/TimeMillisValueTreeNode.java | package com.netflix.suro.routing.filter.lang;
import org.antlr.runtime.Token;
import org.antlr.runtime.tree.Tree;
public class TimeMillisValueTreeNode extends MessageFilterBaseTreeNode implements ValueTreeNode {
@Override
public String getValue() {
return (String)((ValueTreeNode)getChild(1)).getValue();
}
public String getValueFormat() {
return (String)((ValueTreeNode)getChild(0)).getValue();
}
public TimeMillisValueTreeNode(Token t) {
super(t);
}
public TimeMillisValueTreeNode(TimeMillisValueTreeNode node) {
super(node);
}
public Tree dupNode() {
return new TimeMillisValueTreeNode(this);
}
}
| 6,817 |
0 | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/lang/NullTreeNode.java | package com.netflix.suro.routing.filter.lang;
import com.netflix.suro.routing.filter.NullValuePredicate;
import com.netflix.suro.routing.filter.PathValueMessageFilter;
import com.netflix.suro.routing.filter.MessageFilter;
import org.antlr.runtime.Token;
import org.antlr.runtime.tree.Tree;
import static com.netflix.suro.routing.filter.lang.TreeNodeUtil.getXPath;
public class NullTreeNode extends MessageFilterBaseTreeNode implements MessageFilterTranslatable {
@Override
public MessageFilter translate() {
String xpath = getXPath(getChild(0));
return new PathValueMessageFilter(xpath, NullValuePredicate.INSTANCE);
}
public NullTreeNode(Token t) {
super(t);
}
public NullTreeNode(NullTreeNode node) {
super(node);
}
public Tree dupNode() {
return new NullTreeNode(this);
}
}
| 6,818 |
0 | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/lang/ValueTreeNode.java | package com.netflix.suro.routing.filter.lang;
public interface ValueTreeNode {
public Object getValue();
}
| 6,819 |
0 | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/lang/XPathTreeNode.java | package com.netflix.suro.routing.filter.lang;
import org.antlr.runtime.Token;
import org.antlr.runtime.tree.Tree;
public class XPathTreeNode extends MessageFilterBaseTreeNode implements ValueTreeNode {
@Override
public Object getValue() {
return getChild(0).getText();
}
public XPathTreeNode(Token t) {
super(t);
}
public XPathTreeNode(XPathTreeNode node) {
super(node);
}
public Tree dupNode() {
return new XPathTreeNode(this);
}
}
| 6,820 |
0 | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/lang/StringInTreeNode.java | package com.netflix.suro.routing.filter.lang;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.netflix.suro.routing.filter.MessageFilters;
import com.netflix.suro.routing.filter.MessageFilter;
import com.netflix.suro.routing.filter.PathValueMessageFilter;
import com.netflix.suro.routing.filter.StringValuePredicate;
import org.antlr.runtime.Token;
import org.antlr.runtime.tree.Tree;
import java.util.List;
import static com.netflix.suro.routing.filter.lang.TreeNodeUtil.getXPath;
public class StringInTreeNode extends MessageFilterBaseTreeNode implements MessageFilterTranslatable {
@SuppressWarnings("unchecked")
@Override
public MessageFilter translate() {
final String xpath = getXPath(getChild(0));
List children = getChildren();
return MessageFilters.or(
Lists.transform(children.subList(1, children.size()), new Function<Object, MessageFilter>() {
@Override
public MessageFilter apply(Object node) {
String value = ((StringTreeNode) node).getValue();
return new PathValueMessageFilter(xpath, new StringValuePredicate(value));
}
})
);
}
public StringInTreeNode(Token t) {
super(t);
}
public StringInTreeNode(StringInTreeNode node) {
super(node);
}
public Tree dupNode() {
return new StringInTreeNode(this);
}
}
| 6,821 |
0 | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/lang/MessageFilterParsingException.java | package com.netflix.suro.routing.filter.lang;
public class MessageFilterParsingException extends RuntimeException {
public MessageFilterParsingException(String msg, Throwable cause){
super(msg, cause);
}
}
| 6,822 |
0 | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/lang/MatchesTreeNode.java | package com.netflix.suro.routing.filter.lang;
import com.netflix.suro.routing.filter.PathValueMessageFilter;
import com.netflix.suro.routing.filter.RegexValuePredicate;
import com.netflix.suro.routing.filter.MessageFilter;
import org.antlr.runtime.Token;
import org.antlr.runtime.tree.Tree;
import static com.netflix.suro.routing.filter.lang.TreeNodeUtil.getXPath;
public class MatchesTreeNode extends MessageFilterBaseTreeNode implements MessageFilterTranslatable {
@Override
public MessageFilter translate() {
String xpath = getXPath(getChild(0));
StringTreeNode valueNode = (StringTreeNode)getChild(1);
return new PathValueMessageFilter(xpath, new RegexValuePredicate(valueNode.getValue(), RegexValuePredicate.MatchPolicy.PARTIAL));
}
public MatchesTreeNode(Token t) {
super(t);
}
public MatchesTreeNode(MatchesTreeNode node) {
super(node);
}
public Tree dupNode() {
return new MatchesTreeNode(this);
}
}
| 6,823 |
0 | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/lang/NotEqualsTreeNode.java | package com.netflix.suro.routing.filter.lang;
import com.netflix.suro.routing.filter.MessageFilters;
import com.netflix.suro.routing.filter.MessageFilter;
import org.antlr.runtime.Token;
import org.antlr.runtime.tree.Tree;
public class NotEqualsTreeNode extends EqualityComparisonBaseTreeNode implements MessageFilterTranslatable {
@Override
public MessageFilter translate() {
return MessageFilters.not(getEqualFilter());
}
public NotEqualsTreeNode(Token t) {
super(t);
}
public NotEqualsTreeNode(NotEqualsTreeNode node) {
super(node);
}
public Tree dupNode() {
return new NotEqualsTreeNode(this);
}
}
| 6,824 |
0 | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/lang/EqualsTreeNode.java | package com.netflix.suro.routing.filter.lang;
import com.netflix.suro.routing.filter.MessageFilter;
import org.antlr.runtime.Token;
import org.antlr.runtime.tree.Tree;
public class EqualsTreeNode extends EqualityComparisonBaseTreeNode implements MessageFilterTranslatable {
@Override
public MessageFilter translate() {
return getEqualFilter();
}
public EqualsTreeNode(Token t) {
super(t);
}
public EqualsTreeNode(EqualsTreeNode node) {
super(node);
}
public Tree dupNode() {
return new EqualsTreeNode(this);
}
}
| 6,825 |
0 | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/lang/TimeStringValueTreeNode.java | package com.netflix.suro.routing.filter.lang;
import org.antlr.runtime.Token;
import org.antlr.runtime.tree.Tree;
public class TimeStringValueTreeNode extends MessageFilterBaseTreeNode implements ValueTreeNode {
@Override
public String getValue() {
return (String)((ValueTreeNode)getChild(2)).getValue();
}
public String getValueTimeFormat() {
return (String)((ValueTreeNode)getChild(1)).getValue();
}
public String getInputTimeFormat() {
return (String)((ValueTreeNode)getChild(0)).getValue();
}
public TimeStringValueTreeNode(Token t) {
super(t);
}
public TimeStringValueTreeNode(TimeStringValueTreeNode node) {
super(node);
}
public Tree dupNode() {
return new TimeStringValueTreeNode(this);
}
}
| 6,826 |
0 | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/lang/NotTreeNode.java | package com.netflix.suro.routing.filter.lang;
import com.netflix.suro.routing.filter.MessageFilters;
import com.netflix.suro.routing.filter.MessageFilter;
import org.antlr.runtime.Token;
import org.antlr.runtime.tree.Tree;
public class NotTreeNode extends MessageFilterBaseTreeNode implements MessageFilterTranslatable {
@Override
public MessageFilter translate() {
MessageFilter filter = ((MessageFilterTranslatable)getChild(0)).translate();
return MessageFilters.not(filter);
}
public NotTreeNode(Token t) {
super(t);
}
public NotTreeNode(NotTreeNode node) {
super(node);
}
public Tree dupNode() {
return new NotTreeNode(this);
}
}
| 6,827 |
0 | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/lang/EqualityComparisonBaseTreeNode.java | package com.netflix.suro.routing.filter.lang;
import com.netflix.suro.routing.filter.*;
import org.antlr.runtime.Token;
import org.antlr.runtime.tree.Tree;
import static com.netflix.suro.routing.filter.lang.MessageFilterParser.*;
import static com.netflix.suro.routing.filter.lang.TreeNodeUtil.getXPath;
public abstract class EqualityComparisonBaseTreeNode extends MessageFilterBaseTreeNode {
public EqualityComparisonBaseTreeNode(Token t) {
super(t);
}
public EqualityComparisonBaseTreeNode(MessageFilterBaseTreeNode node) {
super(node);
}
// TODO this is an ugly workaround. We should really generate ^(NOT ^(Equals...) for NOT_EQUAL
// but I can't get ANTLR to generated nested tree with added node.
protected MessageFilter getEqualFilter() {
String xpath = getXPath(getChild(0));
Tree valueNode = getChild(1);
switch(valueNode.getType()){
case NUMBER:
Number value = (Number)((ValueTreeNode)valueNode).getValue();
return new PathValueMessageFilter(xpath, new NumericValuePredicate(value, "="));
case STRING:
String sValue = (String)((ValueTreeNode)valueNode).getValue();
return new PathValueMessageFilter(xpath, new StringValuePredicate(sValue));
case TRUE:
return new PathValueMessageFilter(xpath, BooleanValuePredicate.TRUE);
case FALSE:
return new PathValueMessageFilter(xpath, BooleanValuePredicate.FALSE);
case NULL:
return new PathValueMessageFilter(xpath, NullValuePredicate.INSTANCE);
case XPATH_FUN_NAME:
String aPath = (String)((ValueTreeNode)valueNode).getValue();
return new PathValueMessageFilter(xpath, new PathValuePredicate(aPath, xpath));
case TIME_MILLIS_FUN_NAME:
TimeMillisValueTreeNode timeNode = (TimeMillisValueTreeNode)valueNode;
return new PathValueMessageFilter(xpath,
new TimeMillisValuePredicate(
timeNode.getValueFormat(),
timeNode.getValue(),
"="));
case TIME_STRING_FUN_NAME:
TimeStringValueTreeNode timeStringNode = (TimeStringValueTreeNode)valueNode;
return new PathValueMessageFilter(xpath,
new TimeStringValuePredicate(
timeStringNode.getValueTimeFormat(),
timeStringNode.getInputTimeFormat(),
timeStringNode.getValue(),
"="));
default:
throw new UnexpectedTokenException(valueNode, "Number", "String", "TRUE", "FALSE");
}
}
}
| 6,828 |
0 | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/lang/StringTreeNode.java | package com.netflix.suro.routing.filter.lang;
import org.antlr.runtime.Token;
import org.antlr.runtime.tree.Tree;
public class StringTreeNode extends MessageFilterBaseTreeNode implements ValueTreeNode {
@Override
public String getValue() {
return getText();
}
public StringTreeNode(Token t) {
super(t);
}
public StringTreeNode(StringTreeNode node) {
super(node);
}
public Tree dupNode() {
return new StringTreeNode(this);
}
}
| 6,829 |
0 | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/lang/TrueValueTreeNode.java | package com.netflix.suro.routing.filter.lang;
import com.netflix.suro.routing.filter.MessageFilters;
import com.netflix.suro.routing.filter.MessageFilter;
import org.antlr.runtime.Token;
import org.antlr.runtime.tree.Tree;
public class TrueValueTreeNode extends MessageFilterBaseTreeNode implements MessageFilterTranslatable {
public TrueValueTreeNode(Token t) {
super(t);
}
public TrueValueTreeNode(TrueValueTreeNode node) {
super(node);
}
public Tree dupNode() {
return new TrueValueTreeNode(this);
}
@Override
public MessageFilter translate() {
return MessageFilters.alwaysTrue();
}
}
| 6,830 |
0 | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/lang/MessageFilterTranslatable.java | package com.netflix.suro.routing.filter.lang;
import com.netflix.suro.routing.filter.MessageFilter;
public interface MessageFilterTranslatable {
public MessageFilter translate();
}
| 6,831 |
0 | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/lang/BetweenTreeNode.java | package com.netflix.suro.routing.filter.lang;
import com.netflix.suro.routing.filter.*;
import org.antlr.runtime.Token;
import org.antlr.runtime.tree.Tree;
public class BetweenTreeNode extends MessageFilterBaseTreeNode implements MessageFilterTranslatable {
@Override
public MessageFilter translate() {
ValueTreeNode xpathNode = (ValueTreeNode)getChild(0);
String xpath = (String)xpathNode.getValue();
ValueTreeNode lowerBoundNode = (ValueTreeNode)getChild(1);
Number lowerBound = (Number)lowerBoundNode.getValue();
ValueTreeNode upperBoundNode = (ValueTreeNode)getChild(2);
Number upperBound = (Number)upperBoundNode.getValue();
return MessageFilters.and(
new PathValueMessageFilter(xpath, new NumericValuePredicate(lowerBound, ">=")),
new PathValueMessageFilter(xpath, new NumericValuePredicate(upperBound, "<"))
);
}
public BetweenTreeNode(Token t) {
super(t);
}
public BetweenTreeNode(BetweenTreeNode node) {
super(node);
}
public Tree dupNode() {
return new BetweenTreeNode(this);
}
}
| 6,832 |
0 | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/lang/MessageFilterBaseTreeNode.java | package com.netflix.suro.routing.filter.lang;
import org.antlr.runtime.Token;
import org.antlr.runtime.tree.CommonTree;
public abstract class MessageFilterBaseTreeNode extends CommonTree {
public MessageFilterBaseTreeNode(Token t) {
super(t);
}
public MessageFilterBaseTreeNode(MessageFilterBaseTreeNode node) {
super(node);
}
public String toString() {
return String.format("%s<%s>", getText(), getClass().getSimpleName());
}
}
| 6,833 |
0 | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/lang/MessageFilterLexer.java | // $ANTLR 3.4 MessageFilter.g 2012-08-22 11:55:59
package com.netflix.suro.routing.filter.lang;
import org.antlr.runtime.*;
@SuppressWarnings({"all", "warnings", "unchecked"})
public class MessageFilterLexer extends Lexer {
public static final int EOF=-1;
public static final int T__33=33;
public static final int T__34=34;
public static final int T__35=35;
public static final int AND=4;
public static final int BETWEEN=5;
public static final int COMMENT=6;
public static final int EQUALS=7;
public static final int ESC_SEQ=8;
public static final int EXISTS=9;
public static final int EXPONENT=10;
public static final int FALSE=11;
public static final int GE=12;
public static final int GT=13;
public static final int HEX_DIGIT=14;
public static final int IN=15;
public static final int IS=16;
public static final int LE=17;
public static final int LT=18;
public static final int MATCHES=19;
public static final int NOT=20;
public static final int NOT_EQUALS=21;
public static final int NULL=22;
public static final int NUMBER=23;
public static final int OCTAL_ESC=24;
public static final int OR=25;
public static final int STRING=26;
public static final int TIME_MILLIS_FUN_NAME=27;
public static final int TIME_STRING_FUN_NAME=28;
public static final int TRUE=29;
public static final int UNICODE_ESC=30;
public static final int WS=31;
public static final int XPATH_FUN_NAME=32;
public void reportError(RecognitionException e) {
// if we've already reported an error and have not matched a token
// yet successfully, don't report any errors.
if ( state.errorRecovery ) {
//System.err.print("[SPURIOUS] ");
return;
}
state.syntaxErrors++; // don't count spurious
state.errorRecovery = true;
throwLexerException(this.getTokenNames(), e);
}
public void throwLexerException(String[] tokenNames, RecognitionException e) {
String hdr = getErrorHeader(e);
String msg = getErrorMessage(e, tokenNames);
throw new MessageFilterParsingException(hdr+" "+msg, e);
}
// delegates
// delegators
public Lexer[] getDelegates() {
return new Lexer[] {};
}
public MessageFilterLexer() {}
public MessageFilterLexer(CharStream input) {
this(input, new RecognizerSharedState());
}
public MessageFilterLexer(CharStream input, RecognizerSharedState state) {
super(input,state);
}
public String getGrammarFileName() { return "MessageFilter.g"; }
// $ANTLR start "AND"
public final void mAND() throws RecognitionException {
try {
int _type = AND;
int _channel = DEFAULT_TOKEN_CHANNEL;
// MessageFilter.g:33:5: ( 'and' )
// MessageFilter.g:33:7: 'and'
{
match("and");
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "AND"
// $ANTLR start "BETWEEN"
public final void mBETWEEN() throws RecognitionException {
try {
int _type = BETWEEN;
int _channel = DEFAULT_TOKEN_CHANNEL;
// MessageFilter.g:34:9: ( 'between' )
// MessageFilter.g:34:11: 'between'
{
match("between");
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "BETWEEN"
// $ANTLR start "EQUALS"
public final void mEQUALS() throws RecognitionException {
try {
int _type = EQUALS;
int _channel = DEFAULT_TOKEN_CHANNEL;
// MessageFilter.g:35:8: ( '=' )
// MessageFilter.g:35:10: '='
{
match('=');
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "EQUALS"
// $ANTLR start "EXISTS"
public final void mEXISTS() throws RecognitionException {
try {
int _type = EXISTS;
int _channel = DEFAULT_TOKEN_CHANNEL;
// MessageFilter.g:36:8: ( 'exists' )
// MessageFilter.g:36:10: 'exists'
{
match("exists");
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "EXISTS"
// $ANTLR start "FALSE"
public final void mFALSE() throws RecognitionException {
try {
int _type = FALSE;
int _channel = DEFAULT_TOKEN_CHANNEL;
// MessageFilter.g:37:7: ( 'false' )
// MessageFilter.g:37:9: 'false'
{
match("false");
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "FALSE"
// $ANTLR start "GE"
public final void mGE() throws RecognitionException {
try {
int _type = GE;
int _channel = DEFAULT_TOKEN_CHANNEL;
// MessageFilter.g:38:4: ( '>=' )
// MessageFilter.g:38:6: '>='
{
match(">=");
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "GE"
// $ANTLR start "GT"
public final void mGT() throws RecognitionException {
try {
int _type = GT;
int _channel = DEFAULT_TOKEN_CHANNEL;
// MessageFilter.g:39:4: ( '>' )
// MessageFilter.g:39:6: '>'
{
match('>');
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "GT"
// $ANTLR start "IN"
public final void mIN() throws RecognitionException {
try {
int _type = IN;
int _channel = DEFAULT_TOKEN_CHANNEL;
// MessageFilter.g:40:4: ( 'in' )
// MessageFilter.g:40:6: 'in'
{
match("in");
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "IN"
// $ANTLR start "IS"
public final void mIS() throws RecognitionException {
try {
int _type = IS;
int _channel = DEFAULT_TOKEN_CHANNEL;
// MessageFilter.g:41:4: ( 'is' )
// MessageFilter.g:41:6: 'is'
{
match("is");
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "IS"
// $ANTLR start "LE"
public final void mLE() throws RecognitionException {
try {
int _type = LE;
int _channel = DEFAULT_TOKEN_CHANNEL;
// MessageFilter.g:42:4: ( '<=' )
// MessageFilter.g:42:6: '<='
{
match("<=");
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "LE"
// $ANTLR start "LT"
public final void mLT() throws RecognitionException {
try {
int _type = LT;
int _channel = DEFAULT_TOKEN_CHANNEL;
// MessageFilter.g:43:4: ( '<' )
// MessageFilter.g:43:6: '<'
{
match('<');
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "LT"
// $ANTLR start "MATCHES"
public final void mMATCHES() throws RecognitionException {
try {
int _type = MATCHES;
int _channel = DEFAULT_TOKEN_CHANNEL;
// MessageFilter.g:44:9: ( '=~' )
// MessageFilter.g:44:11: '=~'
{
match("=~");
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "MATCHES"
// $ANTLR start "NOT"
public final void mNOT() throws RecognitionException {
try {
int _type = NOT;
int _channel = DEFAULT_TOKEN_CHANNEL;
// MessageFilter.g:45:5: ( 'not' )
// MessageFilter.g:45:7: 'not'
{
match("not");
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "NOT"
// $ANTLR start "NOT_EQUALS"
public final void mNOT_EQUALS() throws RecognitionException {
try {
int _type = NOT_EQUALS;
int _channel = DEFAULT_TOKEN_CHANNEL;
// MessageFilter.g:46:12: ( '!=' )
// MessageFilter.g:46:14: '!='
{
match("!=");
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "NOT_EQUALS"
// $ANTLR start "NULL"
public final void mNULL() throws RecognitionException {
try {
int _type = NULL;
int _channel = DEFAULT_TOKEN_CHANNEL;
// MessageFilter.g:47:6: ( 'null' )
// MessageFilter.g:47:8: 'null'
{
match("null");
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "NULL"
// $ANTLR start "OR"
public final void mOR() throws RecognitionException {
try {
int _type = OR;
int _channel = DEFAULT_TOKEN_CHANNEL;
// MessageFilter.g:48:4: ( 'or' )
// MessageFilter.g:48:6: 'or'
{
match("or");
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "OR"
// $ANTLR start "TIME_MILLIS_FUN_NAME"
public final void mTIME_MILLIS_FUN_NAME() throws RecognitionException {
try {
int _type = TIME_MILLIS_FUN_NAME;
int _channel = DEFAULT_TOKEN_CHANNEL;
// MessageFilter.g:49:22: ( 'time-millis' )
// MessageFilter.g:49:24: 'time-millis'
{
match("time-millis");
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "TIME_MILLIS_FUN_NAME"
// $ANTLR start "TIME_STRING_FUN_NAME"
public final void mTIME_STRING_FUN_NAME() throws RecognitionException {
try {
int _type = TIME_STRING_FUN_NAME;
int _channel = DEFAULT_TOKEN_CHANNEL;
// MessageFilter.g:50:22: ( 'time-string' )
// MessageFilter.g:50:24: 'time-string'
{
match("time-string");
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "TIME_STRING_FUN_NAME"
// $ANTLR start "TRUE"
public final void mTRUE() throws RecognitionException {
try {
int _type = TRUE;
int _channel = DEFAULT_TOKEN_CHANNEL;
// MessageFilter.g:51:6: ( 'true' )
// MessageFilter.g:51:8: 'true'
{
match("true");
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "TRUE"
// $ANTLR start "XPATH_FUN_NAME"
public final void mXPATH_FUN_NAME() throws RecognitionException {
try {
int _type = XPATH_FUN_NAME;
int _channel = DEFAULT_TOKEN_CHANNEL;
// MessageFilter.g:52:16: ( 'xpath' )
// MessageFilter.g:52:18: 'xpath'
{
match("xpath");
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "XPATH_FUN_NAME"
// $ANTLR start "T__33"
public final void mT__33() throws RecognitionException {
try {
int _type = T__33;
int _channel = DEFAULT_TOKEN_CHANNEL;
// MessageFilter.g:53:7: ( '(' )
// MessageFilter.g:53:9: '('
{
match('(');
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "T__33"
// $ANTLR start "T__34"
public final void mT__34() throws RecognitionException {
try {
int _type = T__34;
int _channel = DEFAULT_TOKEN_CHANNEL;
// MessageFilter.g:54:7: ( ')' )
// MessageFilter.g:54:9: ')'
{
match(')');
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "T__34"
// $ANTLR start "T__35"
public final void mT__35() throws RecognitionException {
try {
int _type = T__35;
int _channel = DEFAULT_TOKEN_CHANNEL;
// MessageFilter.g:55:7: ( ',' )
// MessageFilter.g:55:9: ','
{
match(',');
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "T__35"
// $ANTLR start "NUMBER"
public final void mNUMBER() throws RecognitionException {
try {
int _type = NUMBER;
int _channel = DEFAULT_TOKEN_CHANNEL;
// MessageFilter.g:198:5: ( ( '+' | '-' )? ( '0' .. '9' )+ ( '.' ( '0' .. '9' )* ( EXPONENT )? )? | ( '+' | '-' )? '.' ( '0' .. '9' )+ ( EXPONENT )? | ( '+' | '-' )? ( '0' .. '9' )+ EXPONENT )
int alt11=3;
alt11 = dfa11.predict(input);
switch (alt11) {
case 1 :
// MessageFilter.g:198:9: ( '+' | '-' )? ( '0' .. '9' )+ ( '.' ( '0' .. '9' )* ( EXPONENT )? )?
{
// MessageFilter.g:198:9: ( '+' | '-' )?
int alt1=2;
int LA1_0 = input.LA(1);
if ( (LA1_0=='+'||LA1_0=='-') ) {
alt1=1;
}
switch (alt1) {
case 1 :
// MessageFilter.g:
{
if ( input.LA(1)=='+'||input.LA(1)=='-' ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;
}
}
break;
}
// MessageFilter.g:198:20: ( '0' .. '9' )+
int cnt2=0;
loop2:
do {
int alt2=2;
int LA2_0 = input.LA(1);
if ( ((LA2_0 >= '0' && LA2_0 <= '9')) ) {
alt2=1;
}
switch (alt2) {
case 1 :
// MessageFilter.g:
{
if ( (input.LA(1) >= '0' && input.LA(1) <= '9') ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;
}
}
break;
default :
if ( cnt2 >= 1 ) break loop2;
EarlyExitException eee =
new EarlyExitException(2, input);
throw eee;
}
cnt2++;
} while (true);
// MessageFilter.g:198:32: ( '.' ( '0' .. '9' )* ( EXPONENT )? )?
int alt5=2;
int LA5_0 = input.LA(1);
if ( (LA5_0=='.') ) {
alt5=1;
}
switch (alt5) {
case 1 :
// MessageFilter.g:198:33: '.' ( '0' .. '9' )* ( EXPONENT )?
{
match('.');
// MessageFilter.g:198:37: ( '0' .. '9' )*
loop3:
do {
int alt3=2;
int LA3_0 = input.LA(1);
if ( ((LA3_0 >= '0' && LA3_0 <= '9')) ) {
alt3=1;
}
switch (alt3) {
case 1 :
// MessageFilter.g:
{
if ( (input.LA(1) >= '0' && input.LA(1) <= '9') ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;
}
}
break;
default :
break loop3;
}
} while (true);
// MessageFilter.g:198:49: ( EXPONENT )?
int alt4=2;
int LA4_0 = input.LA(1);
if ( (LA4_0=='E'||LA4_0=='e') ) {
alt4=1;
}
switch (alt4) {
case 1 :
// MessageFilter.g:198:49: EXPONENT
{
mEXPONENT();
}
break;
}
}
break;
}
}
break;
case 2 :
// MessageFilter.g:199:9: ( '+' | '-' )? '.' ( '0' .. '9' )+ ( EXPONENT )?
{
// MessageFilter.g:199:9: ( '+' | '-' )?
int alt6=2;
int LA6_0 = input.LA(1);
if ( (LA6_0=='+'||LA6_0=='-') ) {
alt6=1;
}
switch (alt6) {
case 1 :
// MessageFilter.g:
{
if ( input.LA(1)=='+'||input.LA(1)=='-' ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;
}
}
break;
}
match('.');
// MessageFilter.g:199:24: ( '0' .. '9' )+
int cnt7=0;
loop7:
do {
int alt7=2;
int LA7_0 = input.LA(1);
if ( ((LA7_0 >= '0' && LA7_0 <= '9')) ) {
alt7=1;
}
switch (alt7) {
case 1 :
// MessageFilter.g:
{
if ( (input.LA(1) >= '0' && input.LA(1) <= '9') ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;
}
}
break;
default :
if ( cnt7 >= 1 ) break loop7;
EarlyExitException eee =
new EarlyExitException(7, input);
throw eee;
}
cnt7++;
} while (true);
// MessageFilter.g:199:36: ( EXPONENT )?
int alt8=2;
int LA8_0 = input.LA(1);
if ( (LA8_0=='E'||LA8_0=='e') ) {
alt8=1;
}
switch (alt8) {
case 1 :
// MessageFilter.g:199:36: EXPONENT
{
mEXPONENT();
}
break;
}
}
break;
case 3 :
// MessageFilter.g:200:9: ( '+' | '-' )? ( '0' .. '9' )+ EXPONENT
{
// MessageFilter.g:200:9: ( '+' | '-' )?
int alt9=2;
int LA9_0 = input.LA(1);
if ( (LA9_0=='+'||LA9_0=='-') ) {
alt9=1;
}
switch (alt9) {
case 1 :
// MessageFilter.g:
{
if ( input.LA(1)=='+'||input.LA(1)=='-' ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;
}
}
break;
}
// MessageFilter.g:200:20: ( '0' .. '9' )+
int cnt10=0;
loop10:
do {
int alt10=2;
int LA10_0 = input.LA(1);
if ( ((LA10_0 >= '0' && LA10_0 <= '9')) ) {
alt10=1;
}
switch (alt10) {
case 1 :
// MessageFilter.g:
{
if ( (input.LA(1) >= '0' && input.LA(1) <= '9') ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;
}
}
break;
default :
if ( cnt10 >= 1 ) break loop10;
EarlyExitException eee =
new EarlyExitException(10, input);
throw eee;
}
cnt10++;
} while (true);
mEXPONENT();
}
break;
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "NUMBER"
// $ANTLR start "COMMENT"
public final void mCOMMENT() throws RecognitionException {
try {
int _type = COMMENT;
int _channel = DEFAULT_TOKEN_CHANNEL;
// MessageFilter.g:204:5: ( '//' (~ ( '\\n' | '\\r' ) )* ( '\\r' )? '\\n' | '/*' ( options {greedy=false; } : . )* '*/' )
int alt15=2;
int LA15_0 = input.LA(1);
if ( (LA15_0=='/') ) {
int LA15_1 = input.LA(2);
if ( (LA15_1=='/') ) {
alt15=1;
}
else if ( (LA15_1=='*') ) {
alt15=2;
}
else {
NoViableAltException nvae =
new NoViableAltException("", 15, 1, input);
throw nvae;
}
}
else {
NoViableAltException nvae =
new NoViableAltException("", 15, 0, input);
throw nvae;
}
switch (alt15) {
case 1 :
// MessageFilter.g:204:9: '//' (~ ( '\\n' | '\\r' ) )* ( '\\r' )? '\\n'
{
match("//");
// MessageFilter.g:204:14: (~ ( '\\n' | '\\r' ) )*
loop12:
do {
int alt12=2;
int LA12_0 = input.LA(1);
if ( ((LA12_0 >= '\u0000' && LA12_0 <= '\t')||(LA12_0 >= '\u000B' && LA12_0 <= '\f')||(LA12_0 >= '\u000E' && LA12_0 <= '\uFFFF')) ) {
alt12=1;
}
switch (alt12) {
case 1 :
// MessageFilter.g:
{
if ( (input.LA(1) >= '\u0000' && input.LA(1) <= '\t')||(input.LA(1) >= '\u000B' && input.LA(1) <= '\f')||(input.LA(1) >= '\u000E' && input.LA(1) <= '\uFFFF') ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;
}
}
break;
default :
break loop12;
}
} while (true);
// MessageFilter.g:204:28: ( '\\r' )?
int alt13=2;
int LA13_0 = input.LA(1);
if ( (LA13_0=='\r') ) {
alt13=1;
}
switch (alt13) {
case 1 :
// MessageFilter.g:204:28: '\\r'
{
match('\r');
}
break;
}
match('\n');
_channel=HIDDEN;
}
break;
case 2 :
// MessageFilter.g:205:9: '/*' ( options {greedy=false; } : . )* '*/'
{
match("/*");
// MessageFilter.g:205:14: ( options {greedy=false; } : . )*
loop14:
do {
int alt14=2;
int LA14_0 = input.LA(1);
if ( (LA14_0=='*') ) {
int LA14_1 = input.LA(2);
if ( (LA14_1=='/') ) {
alt14=2;
}
else if ( ((LA14_1 >= '\u0000' && LA14_1 <= '.')||(LA14_1 >= '0' && LA14_1 <= '\uFFFF')) ) {
alt14=1;
}
}
else if ( ((LA14_0 >= '\u0000' && LA14_0 <= ')')||(LA14_0 >= '+' && LA14_0 <= '\uFFFF')) ) {
alt14=1;
}
switch (alt14) {
case 1 :
// MessageFilter.g:205:42: .
{
matchAny();
}
break;
default :
break loop14;
}
} while (true);
match("*/");
_channel=HIDDEN;
}
break;
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "COMMENT"
// $ANTLR start "WS"
public final void mWS() throws RecognitionException {
try {
int _type = WS;
int _channel = DEFAULT_TOKEN_CHANNEL;
// MessageFilter.g:208:5: ( ( ' ' | '\\t' | '\\r' | '\\n' ) )
// MessageFilter.g:208:9: ( ' ' | '\\t' | '\\r' | '\\n' )
{
if ( (input.LA(1) >= '\t' && input.LA(1) <= '\n')||input.LA(1)=='\r'||input.LA(1)==' ' ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;
}
_channel=HIDDEN;
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "WS"
// $ANTLR start "STRING"
public final void mSTRING() throws RecognitionException {
try {
int _type = STRING;
int _channel = DEFAULT_TOKEN_CHANNEL;
// MessageFilter.g:216:5: ( '\"' ( ESC_SEQ |~ ( '\\\\' | '\"' ) )* '\"' )
// MessageFilter.g:216:8: '\"' ( ESC_SEQ |~ ( '\\\\' | '\"' ) )* '\"'
{
match('\"');
// MessageFilter.g:216:12: ( ESC_SEQ |~ ( '\\\\' | '\"' ) )*
loop16:
do {
int alt16=3;
int LA16_0 = input.LA(1);
if ( (LA16_0=='\\') ) {
alt16=1;
}
else if ( ((LA16_0 >= '\u0000' && LA16_0 <= '!')||(LA16_0 >= '#' && LA16_0 <= '[')||(LA16_0 >= ']' && LA16_0 <= '\uFFFF')) ) {
alt16=2;
}
switch (alt16) {
case 1 :
// MessageFilter.g:216:14: ESC_SEQ
{
mESC_SEQ();
}
break;
case 2 :
// MessageFilter.g:216:24: ~ ( '\\\\' | '\"' )
{
if ( (input.LA(1) >= '\u0000' && input.LA(1) <= '!')||(input.LA(1) >= '#' && input.LA(1) <= '[')||(input.LA(1) >= ']' && input.LA(1) <= '\uFFFF') ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;
}
}
break;
default :
break loop16;
}
} while (true);
match('\"');
setText(getText().substring(1, getText().length()-1));
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "STRING"
// $ANTLR start "HEX_DIGIT"
public final void mHEX_DIGIT() throws RecognitionException {
try {
// MessageFilter.g:221:11: ( ( '0' .. '9' | 'a' .. 'f' | 'A' .. 'F' ) )
// MessageFilter.g:
{
if ( (input.LA(1) >= '0' && input.LA(1) <= '9')||(input.LA(1) >= 'A' && input.LA(1) <= 'F')||(input.LA(1) >= 'a' && input.LA(1) <= 'f') ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;
}
}
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "HEX_DIGIT"
// $ANTLR start "ESC_SEQ"
public final void mESC_SEQ() throws RecognitionException {
try {
// MessageFilter.g:225:5: ( '\\\\' ( 'b' | 't' | 'n' | 'f' | 'r' | '\\\"' | '\\'' | '\\\\' ) | UNICODE_ESC | OCTAL_ESC )
int alt17=3;
int LA17_0 = input.LA(1);
if ( (LA17_0=='\\') ) {
switch ( input.LA(2) ) {
case '\"':
case '\'':
case '\\':
case 'b':
case 'f':
case 'n':
case 'r':
case 't':
{
alt17=1;
}
break;
case 'u':
{
alt17=2;
}
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
{
alt17=3;
}
break;
default:
NoViableAltException nvae =
new NoViableAltException("", 17, 1, input);
throw nvae;
}
}
else {
NoViableAltException nvae =
new NoViableAltException("", 17, 0, input);
throw nvae;
}
switch (alt17) {
case 1 :
// MessageFilter.g:225:9: '\\\\' ( 'b' | 't' | 'n' | 'f' | 'r' | '\\\"' | '\\'' | '\\\\' )
{
match('\\');
if ( input.LA(1)=='\"'||input.LA(1)=='\''||input.LA(1)=='\\'||input.LA(1)=='b'||input.LA(1)=='f'||input.LA(1)=='n'||input.LA(1)=='r'||input.LA(1)=='t' ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;
}
}
break;
case 2 :
// MessageFilter.g:226:9: UNICODE_ESC
{
mUNICODE_ESC();
}
break;
case 3 :
// MessageFilter.g:227:9: OCTAL_ESC
{
mOCTAL_ESC();
}
break;
}
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "ESC_SEQ"
// $ANTLR start "OCTAL_ESC"
public final void mOCTAL_ESC() throws RecognitionException {
try {
// MessageFilter.g:232:5: ( '\\\\' ( '0' .. '3' ) ( '0' .. '7' ) ( '0' .. '7' ) | '\\\\' ( '0' .. '7' ) ( '0' .. '7' ) | '\\\\' ( '0' .. '7' ) )
int alt18=3;
int LA18_0 = input.LA(1);
if ( (LA18_0=='\\') ) {
int LA18_1 = input.LA(2);
if ( ((LA18_1 >= '0' && LA18_1 <= '3')) ) {
int LA18_2 = input.LA(3);
if ( ((LA18_2 >= '0' && LA18_2 <= '7')) ) {
int LA18_4 = input.LA(4);
if ( ((LA18_4 >= '0' && LA18_4 <= '7')) ) {
alt18=1;
}
else {
alt18=2;
}
}
else {
alt18=3;
}
}
else if ( ((LA18_1 >= '4' && LA18_1 <= '7')) ) {
int LA18_3 = input.LA(3);
if ( ((LA18_3 >= '0' && LA18_3 <= '7')) ) {
alt18=2;
}
else {
alt18=3;
}
}
else {
NoViableAltException nvae =
new NoViableAltException("", 18, 1, input);
throw nvae;
}
}
else {
NoViableAltException nvae =
new NoViableAltException("", 18, 0, input);
throw nvae;
}
switch (alt18) {
case 1 :
// MessageFilter.g:232:9: '\\\\' ( '0' .. '3' ) ( '0' .. '7' ) ( '0' .. '7' )
{
match('\\');
if ( (input.LA(1) >= '0' && input.LA(1) <= '3') ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;
}
if ( (input.LA(1) >= '0' && input.LA(1) <= '7') ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;
}
if ( (input.LA(1) >= '0' && input.LA(1) <= '7') ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;
}
}
break;
case 2 :
// MessageFilter.g:233:9: '\\\\' ( '0' .. '7' ) ( '0' .. '7' )
{
match('\\');
if ( (input.LA(1) >= '0' && input.LA(1) <= '7') ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;
}
if ( (input.LA(1) >= '0' && input.LA(1) <= '7') ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;
}
}
break;
case 3 :
// MessageFilter.g:234:9: '\\\\' ( '0' .. '7' )
{
match('\\');
if ( (input.LA(1) >= '0' && input.LA(1) <= '7') ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;
}
}
break;
}
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "OCTAL_ESC"
// $ANTLR start "UNICODE_ESC"
public final void mUNICODE_ESC() throws RecognitionException {
try {
// MessageFilter.g:239:5: ( '\\\\' 'u' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT )
// MessageFilter.g:239:9: '\\\\' 'u' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT
{
match('\\');
match('u');
mHEX_DIGIT();
mHEX_DIGIT();
mHEX_DIGIT();
mHEX_DIGIT();
}
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "UNICODE_ESC"
// $ANTLR start "EXPONENT"
public final void mEXPONENT() throws RecognitionException {
try {
// MessageFilter.g:243:10: ( ( 'e' | 'E' ) ( '+' | '-' )? ( '0' .. '9' )+ )
// MessageFilter.g:243:12: ( 'e' | 'E' ) ( '+' | '-' )? ( '0' .. '9' )+
{
if ( input.LA(1)=='E'||input.LA(1)=='e' ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;
}
// MessageFilter.g:243:22: ( '+' | '-' )?
int alt19=2;
int LA19_0 = input.LA(1);
if ( (LA19_0=='+'||LA19_0=='-') ) {
alt19=1;
}
switch (alt19) {
case 1 :
// MessageFilter.g:
{
if ( input.LA(1)=='+'||input.LA(1)=='-' ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;
}
}
break;
}
// MessageFilter.g:243:33: ( '0' .. '9' )+
int cnt20=0;
loop20:
do {
int alt20=2;
int LA20_0 = input.LA(1);
if ( ((LA20_0 >= '0' && LA20_0 <= '9')) ) {
alt20=1;
}
switch (alt20) {
case 1 :
// MessageFilter.g:
{
if ( (input.LA(1) >= '0' && input.LA(1) <= '9') ) {
input.consume();
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;
}
}
break;
default :
if ( cnt20 >= 1 ) break loop20;
EarlyExitException eee =
new EarlyExitException(20, input);
throw eee;
}
cnt20++;
} while (true);
}
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "EXPONENT"
public void mTokens() throws RecognitionException {
// MessageFilter.g:1:8: ( AND | BETWEEN | EQUALS | EXISTS | FALSE | GE | GT | IN | IS | LE | LT | MATCHES | NOT | NOT_EQUALS | NULL | OR | TIME_MILLIS_FUN_NAME | TIME_STRING_FUN_NAME | TRUE | XPATH_FUN_NAME | T__33 | T__34 | T__35 | NUMBER | COMMENT | WS | STRING )
int alt21=27;
switch ( input.LA(1) ) {
case 'a':
{
alt21=1;
}
break;
case 'b':
{
alt21=2;
}
break;
case '=':
{
int LA21_3 = input.LA(2);
if ( (LA21_3=='~') ) {
alt21=12;
}
else {
alt21=3;
}
}
break;
case 'e':
{
alt21=4;
}
break;
case 'f':
{
alt21=5;
}
break;
case '>':
{
int LA21_6 = input.LA(2);
if ( (LA21_6=='=') ) {
alt21=6;
}
else {
alt21=7;
}
}
break;
case 'i':
{
int LA21_7 = input.LA(2);
if ( (LA21_7=='n') ) {
alt21=8;
}
else if ( (LA21_7=='s') ) {
alt21=9;
}
else {
NoViableAltException nvae =
new NoViableAltException("", 21, 7, input);
throw nvae;
}
}
break;
case '<':
{
int LA21_8 = input.LA(2);
if ( (LA21_8=='=') ) {
alt21=10;
}
else {
alt21=11;
}
}
break;
case 'n':
{
int LA21_9 = input.LA(2);
if ( (LA21_9=='o') ) {
alt21=13;
}
else if ( (LA21_9=='u') ) {
alt21=15;
}
else {
NoViableAltException nvae =
new NoViableAltException("", 21, 9, input);
throw nvae;
}
}
break;
case '!':
{
alt21=14;
}
break;
case 'o':
{
alt21=16;
}
break;
case 't':
{
int LA21_12 = input.LA(2);
if ( (LA21_12=='i') ) {
int LA21_31 = input.LA(3);
if ( (LA21_31=='m') ) {
int LA21_33 = input.LA(4);
if ( (LA21_33=='e') ) {
int LA21_34 = input.LA(5);
if ( (LA21_34=='-') ) {
int LA21_35 = input.LA(6);
if ( (LA21_35=='m') ) {
alt21=17;
}
else if ( (LA21_35=='s') ) {
alt21=18;
}
else {
NoViableAltException nvae =
new NoViableAltException("", 21, 35, input);
throw nvae;
}
}
else {
NoViableAltException nvae =
new NoViableAltException("", 21, 34, input);
throw nvae;
}
}
else {
NoViableAltException nvae =
new NoViableAltException("", 21, 33, input);
throw nvae;
}
}
else {
NoViableAltException nvae =
new NoViableAltException("", 21, 31, input);
throw nvae;
}
}
else if ( (LA21_12=='r') ) {
alt21=19;
}
else {
NoViableAltException nvae =
new NoViableAltException("", 21, 12, input);
throw nvae;
}
}
break;
case 'x':
{
alt21=20;
}
break;
case '(':
{
alt21=21;
}
break;
case ')':
{
alt21=22;
}
break;
case ',':
{
alt21=23;
}
break;
case '+':
case '-':
case '.':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
{
alt21=24;
}
break;
case '/':
{
alt21=25;
}
break;
case '\t':
case '\n':
case '\r':
case ' ':
{
alt21=26;
}
break;
case '\"':
{
alt21=27;
}
break;
default:
NoViableAltException nvae =
new NoViableAltException("", 21, 0, input);
throw nvae;
}
switch (alt21) {
case 1 :
// MessageFilter.g:1:10: AND
{
mAND();
}
break;
case 2 :
// MessageFilter.g:1:14: BETWEEN
{
mBETWEEN();
}
break;
case 3 :
// MessageFilter.g:1:22: EQUALS
{
mEQUALS();
}
break;
case 4 :
// MessageFilter.g:1:29: EXISTS
{
mEXISTS();
}
break;
case 5 :
// MessageFilter.g:1:36: FALSE
{
mFALSE();
}
break;
case 6 :
// MessageFilter.g:1:42: GE
{
mGE();
}
break;
case 7 :
// MessageFilter.g:1:45: GT
{
mGT();
}
break;
case 8 :
// MessageFilter.g:1:48: IN
{
mIN();
}
break;
case 9 :
// MessageFilter.g:1:51: IS
{
mIS();
}
break;
case 10 :
// MessageFilter.g:1:54: LE
{
mLE();
}
break;
case 11 :
// MessageFilter.g:1:57: LT
{
mLT();
}
break;
case 12 :
// MessageFilter.g:1:60: MATCHES
{
mMATCHES();
}
break;
case 13 :
// MessageFilter.g:1:68: NOT
{
mNOT();
}
break;
case 14 :
// MessageFilter.g:1:72: NOT_EQUALS
{
mNOT_EQUALS();
}
break;
case 15 :
// MessageFilter.g:1:83: NULL
{
mNULL();
}
break;
case 16 :
// MessageFilter.g:1:88: OR
{
mOR();
}
break;
case 17 :
// MessageFilter.g:1:91: TIME_MILLIS_FUN_NAME
{
mTIME_MILLIS_FUN_NAME();
}
break;
case 18 :
// MessageFilter.g:1:112: TIME_STRING_FUN_NAME
{
mTIME_STRING_FUN_NAME();
}
break;
case 19 :
// MessageFilter.g:1:133: TRUE
{
mTRUE();
}
break;
case 20 :
// MessageFilter.g:1:138: XPATH_FUN_NAME
{
mXPATH_FUN_NAME();
}
break;
case 21 :
// MessageFilter.g:1:153: T__33
{
mT__33();
}
break;
case 22 :
// MessageFilter.g:1:159: T__34
{
mT__34();
}
break;
case 23 :
// MessageFilter.g:1:165: T__35
{
mT__35();
}
break;
case 24 :
// MessageFilter.g:1:171: NUMBER
{
mNUMBER();
}
break;
case 25 :
// MessageFilter.g:1:178: COMMENT
{
mCOMMENT();
}
break;
case 26 :
// MessageFilter.g:1:186: WS
{
mWS();
}
break;
case 27 :
// MessageFilter.g:1:189: STRING
{
mSTRING();
}
break;
}
}
protected DFA11 dfa11 = new DFA11(this);
static final String DFA11_eotS =
"\2\uffff\1\4\3\uffff";
static final String DFA11_eofS =
"\6\uffff";
static final String DFA11_minS =
"\1\53\1\56\1\60\3\uffff";
static final String DFA11_maxS =
"\2\71\1\145\3\uffff";
static final String DFA11_acceptS =
"\3\uffff\1\2\1\1\1\3";
static final String DFA11_specialS =
"\6\uffff}>";
static final String[] DFA11_transitionS = {
"\1\1\1\uffff\1\1\1\3\1\uffff\12\2",
"\1\3\1\uffff\12\2",
"\12\2\13\uffff\1\5\37\uffff\1\5",
"",
"",
""
};
static final short[] DFA11_eot = DFA.unpackEncodedString(DFA11_eotS);
static final short[] DFA11_eof = DFA.unpackEncodedString(DFA11_eofS);
static final char[] DFA11_min = DFA.unpackEncodedStringToUnsignedChars(DFA11_minS);
static final char[] DFA11_max = DFA.unpackEncodedStringToUnsignedChars(DFA11_maxS);
static final short[] DFA11_accept = DFA.unpackEncodedString(DFA11_acceptS);
static final short[] DFA11_special = DFA.unpackEncodedString(DFA11_specialS);
static final short[][] DFA11_transition;
static {
int numStates = DFA11_transitionS.length;
DFA11_transition = new short[numStates][];
for (int i=0; i<numStates; i++) {
DFA11_transition[i] = DFA.unpackEncodedString(DFA11_transitionS[i]);
}
}
class DFA11 extends DFA {
public DFA11(BaseRecognizer recognizer) {
this.recognizer = recognizer;
this.decisionNumber = 11;
this.eot = DFA11_eot;
this.eof = DFA11_eof;
this.min = DFA11_min;
this.max = DFA11_max;
this.accept = DFA11_accept;
this.special = DFA11_special;
this.transition = DFA11_transition;
}
public String getDescription() {
return "197:1: NUMBER : ( ( '+' | '-' )? ( '0' .. '9' )+ ( '.' ( '0' .. '9' )* ( EXPONENT )? )? | ( '+' | '-' )? '.' ( '0' .. '9' )+ ( EXPONENT )? | ( '+' | '-' )? ( '0' .. '9' )+ EXPONENT );";
}
}
}
| 6,834 |
0 | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/lang/NumberTreeNode.java | package com.netflix.suro.routing.filter.lang;
import org.antlr.runtime.Token;
import org.antlr.runtime.tree.Tree;
public class NumberTreeNode extends MessageFilterBaseTreeNode implements ValueTreeNode {
@Override
public Number getValue() {
return Double.valueOf(getText());
}
public NumberTreeNode(Token t) {
super(t);
}
public NumberTreeNode(NumberTreeNode node) {
super(node);
}
public Tree dupNode() {
return new NumberTreeNode(this);
}
}
| 6,835 |
0 | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/lang/AndTreeNode.java | package com.netflix.suro.routing.filter.lang;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.netflix.suro.routing.filter.MessageFilters;
import com.netflix.suro.routing.filter.MessageFilter;
import org.antlr.runtime.Token;
import org.antlr.runtime.tree.Tree;
public class AndTreeNode extends MessageFilterBaseTreeNode implements MessageFilterTranslatable {
@Override
@SuppressWarnings("unchecked")
public MessageFilter translate() {
return MessageFilters.and(
Lists.transform(getChildren(), new Function<Object, MessageFilter>() {
@Override
public MessageFilter apply(Object input) {
MessageFilterTranslatable node = (MessageFilterTranslatable) input;
return node.translate();
}
})
);
}
public AndTreeNode(Token t) {
super(t);
}
public AndTreeNode(AndTreeNode node) {
super(node);
}
public Tree dupNode() {
return new AndTreeNode(this);
}
}
| 6,836 |
0 | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/lang/ComparableTreeNode.java | package com.netflix.suro.routing.filter.lang;
import com.netflix.suro.routing.filter.*;
import org.antlr.runtime.Token;
import org.antlr.runtime.tree.Tree;
import static com.netflix.suro.routing.filter.lang.TreeNodeUtil.getXPath;
import static com.netflix.suro.routing.filter.lang.MessageFilterParser.*;
public class ComparableTreeNode extends MessageFilterBaseTreeNode implements MessageFilterTranslatable {
@Override
public MessageFilter translate() {
String xpath = getXPath(getChild(0));
Tree valueNode = getChild(1);
switch(valueNode.getType()){
case NUMBER:
Number value = (Number)((ValueTreeNode)valueNode).getValue();
return new PathValueMessageFilter(xpath, new NumericValuePredicate(value, getToken().getText()));
case TIME_MILLIS_FUN_NAME:
TimeMillisValueTreeNode timeValueNode = (TimeMillisValueTreeNode)valueNode;
return new PathValueMessageFilter(
xpath,
new TimeMillisValuePredicate(
timeValueNode.getValueFormat(),
timeValueNode.getValue(),
getToken().getText()));
case TIME_STRING_FUN_NAME:
TimeStringValueTreeNode timeStringNode = (TimeStringValueTreeNode)valueNode;
return new PathValueMessageFilter(
xpath,
new TimeStringValuePredicate(
timeStringNode.getValueTimeFormat(),
timeStringNode.getInputTimeFormat(),
timeStringNode.getValue(),
getToken().getText()));
default:
throw new UnexpectedTokenException(valueNode, "Number", "time-millis", "time-string");
}
}
public ComparableTreeNode(Token t) {
super(t);
}
public ComparableTreeNode(ComparableTreeNode node) {
super(node);
}
public Tree dupNode() {
return new ComparableTreeNode(this);
}
}
| 6,837 |
0 | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/lang/OrTreeNode.java | package com.netflix.suro.routing.filter.lang;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.netflix.suro.routing.filter.MessageFilters;
import com.netflix.suro.routing.filter.MessageFilter;
import org.antlr.runtime.Token;
import org.antlr.runtime.tree.CommonTree;
import org.antlr.runtime.tree.Tree;
public class OrTreeNode extends CommonTree implements MessageFilterTranslatable {
@Override
@SuppressWarnings("unchecked")
public MessageFilter translate() {
return MessageFilters.or(
Lists.transform(getChildren(), new Function<Object, MessageFilter>() {
@Override
public MessageFilter apply(Object input) {
MessageFilterTranslatable node = (MessageFilterTranslatable) input;
return node.translate();
}
})
);
}
public OrTreeNode(Token t) {
super(t);
}
public OrTreeNode(OrTreeNode node) {
super(node);
}
public Tree dupNode() {
return new OrTreeNode(this);
} // for dup'ing type
public String toString() {
return String.format("%s<%s>", token.getText(), getClass().getSimpleName());
}
} | 6,838 |
0 | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/lang/FalseValueTreeNode.java | package com.netflix.suro.routing.filter.lang;
import com.netflix.suro.routing.filter.MessageFilters;
import com.netflix.suro.routing.filter.MessageFilter;
import org.antlr.runtime.Token;
import org.antlr.runtime.tree.Tree;
public class FalseValueTreeNode extends MessageFilterBaseTreeNode implements ValueTreeNode, MessageFilterTranslatable {
@Override
public Object getValue() {
return Boolean.FALSE;
}
public FalseValueTreeNode(Token t) {
super(t);
}
public FalseValueTreeNode(FalseValueTreeNode node) {
super(node);
}
public Tree dupNode() {
return new FalseValueTreeNode(this);
}
@Override
public MessageFilter translate() {
return MessageFilters.alwaysFalse();
}
}
| 6,839 |
0 | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/routing/filter/lang/ExistsTreeNode.java | package com.netflix.suro.routing.filter.lang;
import com.netflix.suro.routing.filter.PathExistsMessageFilter;
import com.netflix.suro.routing.filter.MessageFilter;
import org.antlr.runtime.Token;
import org.antlr.runtime.tree.Tree;
import static com.netflix.suro.routing.filter.lang.TreeNodeUtil.getXPath;
public class ExistsTreeNode extends MessageFilterBaseTreeNode implements MessageFilterTranslatable {
@Override
public MessageFilter translate() {
return new PathExistsMessageFilter(getXPath(getChild(0)));
}
public ExistsTreeNode(Token t) {
super(t);
}
public ExistsTreeNode(ExistsTreeNode node) {
super(node);
}
public Tree dupNode() {
return new ExistsTreeNode(this);
}
}
| 6,840 |
0 | Create_ds/suro/suro-core/src/main/java/com/netflix/suro | Create_ds/suro/suro-core/src/main/java/com/netflix/suro/jackson/DefaultObjectMapper.java | /*
* Copyright 2013 Netflix, Inc.
*
* 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.netflix.suro.jackson;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.jsontype.NamedType;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.guava.GuavaModule;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Singleton;
import com.google.inject.name.Names;
import com.netflix.suro.TypeHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.ByteOrder;
import java.util.Set;
/**
* The default {@link ObjectMapper} used for serializing and de-serializing JSON objects.
*/
@Singleton
public class DefaultObjectMapper extends ObjectMapper {
private static final Logger LOG = LoggerFactory.getLogger(DefaultObjectMapper.class);
public DefaultObjectMapper() {
this(null, null);
}
@Inject
public DefaultObjectMapper(final Injector injector, Set<TypeHolder> crossInjectable)
{
SimpleModule serializerModule = new SimpleModule("SuroServer default serializers");
serializerModule.addSerializer(ByteOrder.class, ToStringSerializer.instance);
serializerModule.addDeserializer(
ByteOrder.class,
new JsonDeserializer<ByteOrder>()
{
@Override
public ByteOrder deserialize(
JsonParser jp, DeserializationContext ctxt
) throws IOException, JsonProcessingException
{
if (ByteOrder.BIG_ENDIAN.toString().equals(jp.getText())) {
return ByteOrder.BIG_ENDIAN;
}
return ByteOrder.LITTLE_ENDIAN;
}
}
);
registerModule(serializerModule);
registerModule(new GuavaModule());
if (injector != null) {
setInjectableValues(new InjectableValues() {
@Override
public Object findInjectableValue(
Object valueId,
DeserializationContext ctxt,
BeanProperty forProperty,
Object beanInstance
) {
LOG.info("Looking for " + valueId);
try {
return injector.getInstance(Key.get(forProperty.getType().getRawClass(), Names.named((String)valueId)));
} catch (Exception e) {
try {
return injector.getInstance(forProperty.getType().getRawClass());
} catch (Exception ex) {
LOG.info("No implementation found, returning null");
}
return null;
}
}
});
}
configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
configure(MapperFeature.AUTO_DETECT_GETTERS, false);
configure(MapperFeature.AUTO_DETECT_CREATORS, false);
configure(MapperFeature.AUTO_DETECT_FIELDS, false);
configure(MapperFeature.AUTO_DETECT_IS_GETTERS, false);
configure(MapperFeature.AUTO_DETECT_SETTERS, false);
configure(SerializationFeature.INDENT_OUTPUT, false);
if (crossInjectable != null) {
for (TypeHolder entry : crossInjectable) {
LOG.info("Registering subtype : " + entry.getName() + " -> " + entry.getRawType().getCanonicalName());
registerSubtypes(new NamedType(entry.getRawType(), entry.getName()));
}
}
}
} | 6,841 |
0 | Create_ds/suro/suro-kafka-consumer/src/test/java/com/netflix/suro/input | Create_ds/suro/suro-kafka-consumer/src/test/java/com/netflix/suro/input/kafka/TestKafkaConsumer.java | package com.netflix.suro.input.kafka;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableMap;
import com.netflix.suro.input.SuroInput;
import com.netflix.suro.jackson.DefaultObjectMapper;
import com.netflix.suro.message.MessageContainer;
import com.netflix.suro.routing.MessageRouter;
import com.netflix.suro.sink.kafka.KafkaServerExternalResource;
import com.netflix.suro.sink.kafka.ZkExternalResource;
import kafka.admin.TopicCommand;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.ByteArraySerializer;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
import org.mockito.ArgumentCaptor;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.*;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
public class TestKafkaConsumer {
public static ZkExternalResource zk = new ZkExternalResource();
public static KafkaServerExternalResource kafkaServer = new KafkaServerExternalResource(zk);
@ClassRule
public static TestRule chain = RuleChain
.outerRule(zk)
.around(kafkaServer);
private static final String TOPIC_NAME = "testkafkaconsumer";
@Test
public void test() throws Exception {
int numPartitions = 6;
int messageCount = 10;
TopicCommand.createTopic(zk.getZkClient(),
new TopicCommand.TopicCommandOptions(new String[]{
"--zookeeper", "dummy", "--create", "--topic", TOPIC_NAME,
"--replication-factor", "2", "--partitions", Integer.toString(numPartitions)}));
ObjectMapper jsonMapper = new DefaultObjectMapper();
sendKafkaMessage(kafkaServer.getBrokerListStr(), TOPIC_NAME, numPartitions, messageCount);
final CountDownLatch latch = new CountDownLatch(numPartitions * messageCount);
MessageRouter router = mock(MessageRouter.class);
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
latch.countDown();
return null;
}
}).when(router).process(any(SuroInput.class), any(MessageContainer.class));
Properties properties = new Properties();
properties.setProperty("group.id", "testkafkaconsumer");
properties.setProperty("zookeeper.connect", zk.getConnectionString());
properties.setProperty("auto.offset.reset", "smallest");
try {
new KafkaConsumer(properties, TOPIC_NAME, numPartitions, router, jsonMapper);
fail("should have failed without timeout");
} catch (Exception e) {
// do nothing
}
properties.setProperty("consumer.timeout.ms", "1000");
KafkaConsumer consumer = new KafkaConsumer(properties, TOPIC_NAME, numPartitions, router, jsonMapper);
KafkaConsumer.MAX_PAUSE = 10000; // for testing
consumer.start();
latch.await(1000 * 5, TimeUnit.MILLISECONDS);
ArgumentCaptor<MessageContainer> msgContainers = ArgumentCaptor.forClass(MessageContainer.class);
verify(router, times(numPartitions * messageCount)).process(any(SuroInput.class), msgContainers.capture());
for (MessageContainer container : msgContainers.getAllValues()) {
assertEquals(container.getRoutingKey(), TOPIC_NAME);
assertTrue(container.getEntity(String.class).startsWith("testMessage"));
}
final CountDownLatch latch1 = new CountDownLatch(numPartitions * messageCount);
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
latch1.countDown();
return null;
}
}).when(router).process(any(SuroInput.class), any(MessageContainer.class));
long pauseTime = 5000;
consumer.setPause(pauseTime);
long start = System.currentTimeMillis();
sendKafkaMessage(kafkaServer.getBrokerListStr(), TOPIC_NAME, numPartitions, messageCount);
latch1.await(1000 * 5 + pauseTime, TimeUnit.MILLISECONDS);
long end = System.currentTimeMillis();
assertTrue(end - start > pauseTime);
msgContainers = ArgumentCaptor.forClass(MessageContainer.class);
verify(router, times(numPartitions * messageCount * 2)).process(any(SuroInput.class), msgContainers.capture());
for (MessageContainer container : msgContainers.getAllValues()) {
assertEquals(container.getRoutingKey(), TOPIC_NAME);
assertTrue(container.getEntity(String.class).startsWith("testMessage"));
}
consumer.shutdown();
}
public static void sendKafkaMessage(String brokerList, String topicName, int partitionCount, int messageCount) throws java.io.IOException, InterruptedException {
KafkaProducer<byte[], byte[]> producer = new KafkaProducer<>
(new ImmutableMap.Builder<String, Object>()
.put("client.id", "kakasink")
.put("bootstrap.servers", brokerList).build(),
new ByteArraySerializer(), new ByteArraySerializer());
for (int i = 0; i < messageCount; ++i) {
for (int j = 0; j < partitionCount; ++j) {
producer.send(new ProducerRecord(topicName, j, null, new String("testMessage1").getBytes()));
}
}
}
}
| 6,842 |
0 | Create_ds/suro/suro-kafka-consumer/src/test/java/com/netflix/suro/sink | Create_ds/suro/suro-kafka-consumer/src/test/java/com/netflix/suro/sink/kafka/ZkExternalResource.java | package com.netflix.suro.sink.kafka;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.exception.ZkMarshallingError;
import org.I0Itec.zkclient.serialize.ZkSerializer;
import org.apache.curator.test.TestingServer;
import org.junit.rules.ExternalResource;
import org.junit.rules.TemporaryFolder;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
public class ZkExternalResource extends ExternalResource {
private TestingServer zkServer;
private ZkClient zkClient;
private TemporaryFolder tempDir = new TemporaryFolder();
@Override
protected void before() throws Throwable {
tempDir.create();
zkServer = new TestingServer();
zkClient = new ZkClient("localhost:" + zkServer.getPort(), 20000, 20000, new ZkSerializer() {
@Override
public byte[] serialize(Object data) throws ZkMarshallingError {
try {
return ((String)data).getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
@Override
public Object deserialize(byte[] bytes) throws ZkMarshallingError {
if (bytes == null)
return null;
try {
return new String(bytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
});
}
@Override
protected void after() {
if (zkServer != null) {
try {
zkServer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
tempDir.delete();
}
public ZkClient getZkClient() {
return zkClient;
}
public int getServerPort() { return zkServer.getPort(); }
public String getConnectionString() { return zkServer.getConnectString(); }
}
| 6,843 |
0 | Create_ds/suro/suro-kafka-consumer/src/test/java/com/netflix/suro/sink | Create_ds/suro/suro-kafka-consumer/src/test/java/com/netflix/suro/sink/kafka/KafkaServerExternalResource.java | package com.netflix.suro.sink.kafka;
import com.google.common.collect.Lists;
import kafka.server.KafkaConfig;
import kafka.server.KafkaServer;
import org.apache.commons.lang.StringUtils;
import org.junit.rules.ExternalResource;
import org.junit.rules.TemporaryFolder;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.List;
import java.util.Properties;
public class KafkaServerExternalResource extends ExternalResource {
public static final int BROKER_ID1 = 0;
public static final int BROKER_ID2 = 1;
//public static final int KAFKA_PORT1 = 2200;
//public static final int KAFKA_PORT2 = 2201;
public static final long TIMEOUT = 10000;
private KafkaConfig config1;
private KafkaConfig config2;
private KafkaServer server1;
private KafkaServer server2;
private List<KafkaServer> servers;
private List<KafkaConfig> configs;
private final ZkExternalResource zk;
private final TemporaryFolder tempDir = new TemporaryFolder();
public KafkaServerExternalResource(ZkExternalResource zk) {
this.zk = zk;
}
private static int getUnusedPort() throws IOException {
ServerSocket ss = new ServerSocket(0);
ss.setReuseAddress(false);
int unusedPort = ss.getLocalPort();
ss.close();
return unusedPort;
}
@Override
protected void before() throws Throwable {
startServer(getUnusedPort(), getUnusedPort());
}
public void startServer(int port1, int port2) throws IOException {
tempDir.create();
config1 = new KafkaConfig(
createBrokerConfig(BROKER_ID1, port1, zk.getServerPort(), tempDir.newFolder().getAbsolutePath()));
server1 = createServer(config1);
config2 = new KafkaConfig(
createBrokerConfig(BROKER_ID2, port2, zk.getServerPort(), tempDir.newFolder().getAbsolutePath()));
server2 = createServer(config2);
servers = Lists.newArrayList(server1, server2);
configs = Lists.newArrayList(config1, config2);
}
@Override
protected void after() {
shutdown();
}
public void shutdown() {
if (server1 != null) {
server1.shutdown();
server1.awaitShutdown();
}
if (server2 != null) {
server2.shutdown();
server2.awaitShutdown();
}
tempDir.delete();
}
public String getBrokerListStr() {
List<String> str = Lists.newArrayList();
for (KafkaConfig config : configs) {
str.add(config.hostName() + ":" + config.port());
}
return StringUtils.join(str, ",");
}
public KafkaServer getServer(int index) {
return servers.get(index);
}
public static KafkaServer createServer(KafkaConfig config) {
KafkaServer server = new KafkaServer(config, kafka.utils.SystemTime$.MODULE$);
server.startup();
return server;
}
public static Properties createBrokerConfig(int nodeId, int port, int zkPort, String dir) {
Properties props = new Properties();
props.put("broker.id", Integer.toString(nodeId));
props.put("brokerId", Integer.toString(nodeId));
props.put("host.name", "localhost");
props.put("port", Integer.toString(port));
props.put("log.dir", dir);
props.put("log.flush.interval.messages", "1");
props.put("zookeeper.connect", "localhost:" + zkPort);
props.put("replica.socket.timeout.ms", "1500");
props.put("hostName", "localhost");
props.put("numPartitions", "1");
return props;
}
}
| 6,844 |
0 | Create_ds/suro/suro-kafka-consumer/src/main/java/com/netflix/suro/input | Create_ds/suro/suro-kafka-consumer/src/main/java/com/netflix/suro/input/kafka/KafkaConsumer.java | package com.netflix.suro.input.kafka;
import com.fasterxml.jackson.annotation.JacksonInject;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.netflix.suro.input.SuroInput;
import com.netflix.suro.message.DefaultMessageContainer;
import com.netflix.suro.message.Message;
import com.netflix.suro.routing.MessageRouter;
import kafka.consumer.*;
import kafka.javaapi.consumer.ConsumerConnector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicLong;
public class KafkaConsumer implements SuroInput {
public static final String TYPE = "kafka";
private static Logger log = LoggerFactory.getLogger(KafkaConsumer.class);
protected final Properties consumerProps;
private final String topic;
private final MessageRouter router;
private final ObjectMapper jsonMapper;
private ConsumerConnector connector;
private ExecutorService executor;
private final int readers;
private List<Future<?>> runners = new ArrayList<Future<?>>();
private volatile boolean running = false;
@JsonCreator
public KafkaConsumer(
@JsonProperty("consumerProps") Properties consumerProps,
@JsonProperty("topic") String topic,
@JsonProperty("readers") int readers,
@JacksonInject MessageRouter router,
@JacksonInject ObjectMapper jsonMapper
) {
Preconditions.checkNotNull(consumerProps);
Preconditions.checkNotNull(topic);
Preconditions.checkNotNull(consumerProps.getProperty("group.id"));
Preconditions.checkNotNull(consumerProps.getProperty("zookeeper.connect"));
String timeoutStr = consumerProps.getProperty("consumer.timeout.ms");
Preconditions.checkNotNull(timeoutStr);
Preconditions.checkArgument(Long.parseLong(timeoutStr) > 0);
this.consumerProps = consumerProps;
this.topic = topic;
this.readers = readers == 0 ? 1 : readers;
this.router = router;
this.jsonMapper = jsonMapper;
}
@Override
public String getId() {
return topic + "-" + consumerProps.getProperty("group.id");
}
private AtomicLong pausedTime = new AtomicLong(0);
public static long MAX_PAUSE = 1000; // not final for the test
@Override
public void start() throws Exception {
executor = Executors.newCachedThreadPool(
new ThreadFactoryBuilder().setNameFormat("KafkaConsumer-%d").build());
connector = Consumer.createJavaConsumerConnector(new ConsumerConfig(consumerProps));
final Map<String, List<KafkaStream<byte[], byte[]>>> streams = connector.createMessageStreams(ImmutableMap.of(topic, readers));
final List<KafkaStream<byte[], byte[]>> streamList = streams.get(topic);
if (streamList == null) {
throw new RuntimeException(topic + " is not valid");
}
running = true;
for (KafkaStream<byte[], byte[]> stream : streamList) {
final ConsumerIterator<byte[], byte[]> iterator = stream.iterator();
runners.add(
executor.submit(new Runnable() {
@Override
public void run() {
while (running) {
try {
long pause = Math.min(pausedTime.get(), MAX_PAUSE);
if (pause > 0) {
Thread.sleep(pause);
pausedTime.set(0);
}
byte[] message = iterator.next().message();
router.process(
KafkaConsumer.this,
new DefaultMessageContainer(new Message(topic, message), jsonMapper));
} catch (ConsumerTimeoutException timeoutException) {
// do nothing
} catch (Exception e) {
log.error("Exception on consuming kafka with topic: " + topic, e);
}
}
}
})
);
}
}
@Override
public void shutdown() {
stop();
connector.shutdown();
}
@Override
public void setPause(long ms) {
pausedTime.addAndGet(ms);
}
private void stop() {
running = false;
try {
for (Future<?> runner : runners) {
runner.get();
}
} catch (InterruptedException e) {
// do nothing
} catch (ExecutionException e) {
log.error("Exception on stopping the task", e);
}
}
@Override
public boolean equals(Object o) {
if (o instanceof KafkaConsumer) {
KafkaConsumer kafkaConsumer = (KafkaConsumer) o;
boolean topicEquals = topic.equals(kafkaConsumer.topic);
if (topicEquals) {
return consumerProps.getProperty("group.id").equals(kafkaConsumer.consumerProps.getProperty("group.id"));
} else {
return false;
}
} else {
return false;
}
}
@Override
public int hashCode() {
return (getId()).hashCode();
}
}
| 6,845 |
0 | Create_ds/avro/lang/java/idl/src/test/java/org/apache/avro | Create_ds/avro/lang/java/idl/src/test/java/org/apache/avro/idl/TestLogicalTypes.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro.idl;
import org.apache.avro.LogicalType;
import org.apache.avro.LogicalTypes;
import org.apache.avro.Schema;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.net.URISyntaxException;
import static java.util.Objects.requireNonNull;
public class TestLogicalTypes {
private Schema logicalTypeFields;
@Before
public void setup() throws IOException, URISyntaxException {
final ClassLoader cl = Thread.currentThread().getContextClassLoader();
IdlFile idlFile = new IdlReader().parse(requireNonNull(cl.getResource("logicalTypes.avdl")).toURI());
logicalTypeFields = idlFile.getNamedSchema("org.apache.avro.test.LogicalTypeFields");
}
@Test
public void testDateBecomesLogicalType() {
Assert.assertEquals(LogicalTypes.date(), logicalTypeOfField("aDate"));
}
@Test
public void testTimeMsBecomesLogicalType() {
Assert.assertEquals(LogicalTypes.timeMillis(), logicalTypeOfField("aTime"));
}
@Test
public void testTimestampMsBecomesLogicalType() {
Assert.assertEquals(LogicalTypes.timestampMillis(), logicalTypeOfField("aTimestamp"));
}
@Test
public void testLocalTimestampMsBecomesLogicalType() {
Assert.assertEquals(LogicalTypes.localTimestampMillis(), logicalTypeOfField("aLocalTimestamp"));
}
@Test
public void testDecimalBecomesLogicalType() {
Assert.assertEquals(LogicalTypes.decimal(6, 2), logicalTypeOfField("pocketMoney"));
}
@Test
public void testUuidBecomesLogicalType() {
Assert.assertEquals(LogicalTypes.uuid(), logicalTypeOfField("identifier"));
}
@Test
public void testAnnotatedLongBecomesLogicalType() {
Assert.assertEquals(LogicalTypes.timestampMicros(), logicalTypeOfField("anotherTimestamp"));
}
@Test
public void testAnnotatedBytesFieldBecomesLogicalType() {
Assert.assertEquals(LogicalTypes.decimal(6, 2), logicalTypeOfField("allowance"));
}
@Test
public void testIncorrectlyAnnotatedBytesFieldHasNoLogicalType() {
Schema fieldSchema = logicalTypeFields.getField("byteArray").schema();
Assert.assertNull(fieldSchema.getLogicalType());
Assert.assertEquals("decimal", fieldSchema.getObjectProp("logicalType"));
Assert.assertEquals(3000000000L, fieldSchema.getObjectProp("precision")); // Not an int, so not a valid precision
Assert.assertEquals(0, fieldSchema.getObjectProp("scale"));
}
private LogicalType logicalTypeOfField(String name) {
return logicalTypeFields.getField(name).schema().getLogicalType();
}
}
| 6,846 |
0 | Create_ds/avro/lang/java/idl/src/test/java/org/apache/avro | Create_ds/avro/lang/java/idl/src/test/java/org/apache/avro/idl/IdlReaderTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro.idl;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.avro.Protocol;
import org.apache.avro.Schema;
import org.junit.Before;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Simple test harness for Idl. This relies on an input/ and output/ directory.
* Inside the input/ directory are .avdl files. Each file should have a
* corresponding .avpr file in output/. When the test runs, it generates and
* stringifies each .avdl file and compares it to the expected output, failing
* if the two differ.
* <p>
* To make it simpler to write these tests, you can run ant -Dtestcase=TestIdl
* -Dtest.idl.mode=write, which will *replace* all expected output.
*/
public class IdlReaderTest {
private static final File TEST_DIR = new File(System.getProperty("test.idl.dir", "src/test/idl"));
private static final File TEST_INPUT_DIR = new File(TEST_DIR, "input").getAbsoluteFile();
private static final File TEST_OUTPUT_DIR = new File(TEST_DIR, "output");
private static final String TEST_MODE = System.getProperty("test.idl.mode", "run");
private static final File EXTRA_TEST_DIR = new File(TEST_DIR, "extra");
private List<GenTest> tests;
@Before
public void loadTests() {
assertTrue(TEST_DIR.exists());
assertTrue(TEST_INPUT_DIR.exists());
assertTrue(TEST_OUTPUT_DIR.exists());
tests = new ArrayList<>();
for (File inF : Objects.requireNonNull(TEST_INPUT_DIR.listFiles())) {
if (!inF.getName().endsWith(".avdl")) {
continue;
}
if (inF.getName().startsWith(".")) {
continue;
}
File outF = new File(TEST_OUTPUT_DIR,
inF.getName().replaceFirst("_schema\\.avdl$", ".avsc").replaceFirst("\\.avdl$", ".avpr"));
tests.add(new GenTest(inF, outF));
}
}
@Test
public void validateProtocolParsingResult() throws IOException {
// runTests already tests the actual parsing; this tests the result object.
IdlFile idlFile = parseExtraIdlFile("protocolSyntax.avdl");
assertEquals(1, idlFile.getNamedSchemas().size());
idlFile.getNamedSchemas().keySet().forEach(System.out::println);
assertNotNull(idlFile.getNamedSchema("communication.Message"));
assertNotNull(idlFile.getNamedSchema("Message"));
assertNotNull(idlFile.getProtocol());
assertNull(idlFile.getMainSchema());
}
@Test
public void validateSchemaParsingResult() throws IOException {
// runTests already tests the actual parsing; this tests the result object.
IdlFile idlFile = parseExtraIdlFile("schemaSyntax.avdl");
assertEquals(1, idlFile.getNamedSchemas().size());
idlFile.getNamedSchemas().keySet().forEach(System.out::println);
assertNotNull(idlFile.getNamedSchema("communication.Message"));
assertNotNull(idlFile.getNamedSchema("Message"));
assertNull(idlFile.getProtocol());
Schema mainSchema = idlFile.getMainSchema();
assertEquals(Schema.Type.ARRAY, mainSchema.getType());
assertEquals(idlFile.getNamedSchema("Message"), mainSchema.getElementType());
}
@Test
public void testDocCommentsAndWarnings() throws Exception {
final IdlFile idlFile = parseExtraIdlFile("../input/comments.avdl");
final Protocol protocol = idlFile.getProtocol();
final List<String> warnings = idlFile.getWarnings();
assertEquals("Documented Enum", protocol.getType("testing.DocumentedEnum").getDoc());
assertEquals("Documented Fixed Type", protocol.getType("testing.DocumentedFixed").getDoc());
final Schema documentedError = protocol.getType("testing.DocumentedError");
assertEquals("Documented Error", documentedError.getDoc());
assertEquals("Documented Reason Field", documentedError.getField("reason").doc());
assertEquals("Default Doc Explanation Field", documentedError.getField("explanation").doc());
final Map<String, Protocol.Message> messages = protocol.getMessages();
final Protocol.Message documentedMethod = messages.get("documentedMethod");
assertEquals("Documented Method", documentedMethod.getDoc());
assertEquals("Documented Parameter", documentedMethod.getRequest().getField("message").doc());
assertEquals("Default Documented Parameter", documentedMethod.getRequest().getField("defMsg").doc());
assertNull(protocol.getType("testing.UndocumentedEnum").getDoc());
assertNull(protocol.getType("testing.UndocumentedFixed").getDoc());
assertNull(protocol.getType("testing.UndocumentedRecord").getDoc());
assertNull(messages.get("undocumentedMethod").getDoc());
final String pattern = "Line %d, char %d: Ignoring out-of-place documentation comment.%n"
+ "Did you mean to use a multiline comment ( /* ... */ ) instead?";
assertEquals(
Arrays.asList(String.format(pattern, 21, 8), String.format(pattern, 21, 45), String.format(pattern, 22, 5),
String.format(pattern, 23, 5), String.format(pattern, 24, 5), String.format(pattern, 25, 5),
String.format(pattern, 26, 7), String.format(pattern, 27, 7), String.format(pattern, 28, 7),
String.format(pattern, 33, 7), String.format(pattern, 34, 7), String.format(pattern, 35, 5),
String.format(pattern, 36, 5), String.format(pattern, 37, 7), String.format(pattern, 42, 7),
String.format(pattern, 43, 7), String.format(pattern, 46, 9), String.format(pattern, 47, 5),
String.format(pattern, 54, 7), String.format(pattern, 55, 7), String.format(pattern, 58, 9),
String.format(pattern, 59, 7), String.format(pattern, 60, 11), String.format(pattern, 61, 11)),
warnings);
}
@SuppressWarnings("SameParameterValue")
private IdlFile parseExtraIdlFile(String fileName) throws IOException {
return new IdlReader().parse(EXTRA_TEST_DIR.toPath().resolve(fileName));
}
@Test
public void runTests() {
if (!"run".equals(TEST_MODE)) {
return;
}
int failed = 0;
for (GenTest t : tests) {
try {
t.run();
} catch (Exception e) {
failed++;
System.err.println("Failed: " + t.testName());
e.printStackTrace(System.err);
}
}
if (failed > 0) {
fail(failed + " tests failed");
}
}
@Test
public void writeTests() throws Exception {
if (!"write".equals(TEST_MODE)) {
return;
}
for (GenTest t : tests) {
t.write();
}
}
/**
* An individual comparison test
*/
private static class GenTest {
private final File in, expectedOut;
public GenTest(File in, File expectedOut) {
this.in = in;
this.expectedOut = expectedOut;
}
private String generate() {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
URL[] newPathURL = new URL[] { cl.getResource("putOnClassPath-test-resource.jar") };
URLClassLoader ucl = new URLClassLoader(newPathURL, cl);
Thread.currentThread().setContextClassLoader(ucl);
try {
IdlReader parser = new IdlReader();
return parser.parse(in.toPath()).outputString();
} catch (IOException e) {
throw new AssertionError(e.getMessage(), e);
} finally {
Thread.currentThread().setContextClassLoader(cl);
}
}
public String testName() {
return this.in.getName();
}
public void run() throws Exception {
String output = generate();
String slurped = slurp(expectedOut);
assertEquals(slurped.trim(), output.replace("\\r", "").trim());
}
public void write() throws Exception {
writeFile(expectedOut, generate());
}
private static String slurp(File f) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(f), StandardCharsets.UTF_8));
String line;
StringBuilder builder = new StringBuilder();
while ((line = in.readLine()) != null) {
builder.append(line);
}
in.close();
ObjectMapper mapper = new ObjectMapper();
JsonNode json = mapper.readTree(builder.toString());
return mapper.writer().writeValueAsString(json);
}
private static void writeFile(File f, String s) throws IOException {
FileWriter w = new FileWriter(f);
w.write(s);
w.close();
}
}
}
| 6,847 |
0 | Create_ds/avro/lang/java/idl/src/test/java/org/apache/avro | Create_ds/avro/lang/java/idl/src/test/java/org/apache/avro/idl/TestSchemas.java | /*
* Copyright 2017 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro.idl;
import org.apache.avro.Schema;
import org.junit.Assert;
import org.junit.Test;
public class TestSchemas {
private static class TestVisitor implements SchemaVisitor<String> {
StringBuilder sb = new StringBuilder();
@Override
public SchemaVisitorAction visitTerminal(Schema terminal) {
sb.append(terminal);
return SchemaVisitorAction.CONTINUE;
}
@Override
public SchemaVisitorAction visitNonTerminal(Schema nonTerminal) {
String n = nonTerminal.getName();
sb.append(n).append('.');
if (n.startsWith("t")) {
return SchemaVisitorAction.TERMINATE;
} else if (n.startsWith("ss")) {
return SchemaVisitorAction.SKIP_SIBLINGS;
} else if (n.startsWith("st")) {
return SchemaVisitorAction.SKIP_SUBTREE;
} else {
return SchemaVisitorAction.CONTINUE;
}
}
@Override
public SchemaVisitorAction afterVisitNonTerminal(Schema nonTerminal) {
sb.append("!");
String n = nonTerminal.getName();
if (n.startsWith("ct")) {
return SchemaVisitorAction.TERMINATE;
} else if (n.startsWith("css")) {
return SchemaVisitorAction.SKIP_SIBLINGS;
} else if (n.startsWith("cst")) {
return SchemaVisitorAction.SKIP_SUBTREE;
} else {
return SchemaVisitorAction.CONTINUE;
}
}
@Override
public String get() {
return sb.toString();
}
}
@Test
public void testVisit1() {
String s1 = "{\"type\": \"record\", \"name\": \"t1\", \"fields\": [" + "{\"name\": \"f1\", \"type\": \"int\"}"
+ "]}";
Assert.assertEquals("t1.", Schemas.visit(new Schema.Parser().parse(s1), new TestVisitor()));
}
@Test
public void testVisit2() {
String s2 = "{\"type\": \"record\", \"name\": \"c1\", \"fields\": [" + "{\"name\": \"f1\", \"type\": \"int\"}"
+ "]}";
Assert.assertEquals("c1.\"int\"!", Schemas.visit(new Schema.Parser().parse(s2), new TestVisitor()));
}
@Test
public void testVisit3() {
String s3 = "{\"type\": \"record\", \"name\": \"ss1\", \"fields\": [" + "{\"name\": \"f1\", \"type\": \"int\"}"
+ "]}";
Assert.assertEquals("ss1.", Schemas.visit(new Schema.Parser().parse(s3), new TestVisitor()));
}
@Test
public void testVisit4() {
String s4 = "{\"type\": \"record\", \"name\": \"st1\", \"fields\": [" + "{\"name\": \"f1\", \"type\": \"int\"}"
+ "]}";
Assert.assertEquals("st1.!", Schemas.visit(new Schema.Parser().parse(s4), new TestVisitor()));
}
@Test
public void testVisit5() {
String s5 = "{\"type\": \"record\", \"name\": \"c1\", \"fields\": ["
+ "{\"name\": \"f1\", \"type\": {\"type\": \"record\", \"name\": \"c2\", \"fields\": "
+ "[{\"name\": \"f11\", \"type\": \"int\"}]}}," + "{\"name\": \"f2\", \"type\": \"long\"}" + "]}";
Assert.assertEquals("c1.c2.\"int\"!\"long\"!", Schemas.visit(new Schema.Parser().parse(s5), new TestVisitor()));
}
@Test
public void testVisit6() {
String s6 = "{\"type\": \"record\", \"name\": \"c1\", \"fields\": ["
+ "{\"name\": \"f1\", \"type\": {\"type\": \"record\", \"name\": \"ss2\", \"fields\": "
+ "[{\"name\": \"f11\", \"type\": \"int\"}]}}," + "{\"name\": \"f2\", \"type\": \"long\"}" + "]}";
Assert.assertEquals("c1.ss2.!", Schemas.visit(new Schema.Parser().parse(s6), new TestVisitor()));
}
@Test
public void testVisit7() {
String s7 = "{\"type\": \"record\", \"name\": \"c1\", \"fields\": ["
+ "{\"name\": \"f1\", \"type\": {\"type\": \"record\", \"name\": \"css2\", \"fields\": "
+ "[{\"name\": \"f11\", \"type\": \"int\"}]}}," + "{\"name\": \"f2\", \"type\": \"long\"}" + "]}";
Assert.assertEquals("c1.css2.\"int\"!!", Schemas.visit(new Schema.Parser().parse(s7), new TestVisitor()));
}
@Test(expected = UnsupportedOperationException.class)
public void testVisit8() {
String s8 = "{\"type\": \"record\", \"name\": \"c1\", \"fields\": ["
+ "{\"name\": \"f1\", \"type\": {\"type\": \"record\", \"name\": \"cst2\", \"fields\": "
+ "[{\"name\": \"f11\", \"type\": \"int\"}]}}," + "{\"name\": \"f2\", \"type\": \"int\"}" + "]}";
Schemas.visit(new Schema.Parser().parse(s8), new TestVisitor());
}
@Test
public void testVisit9() {
String s9 = "{\"type\": \"record\", \"name\": \"c1\", \"fields\": ["
+ "{\"name\": \"f1\", \"type\": {\"type\": \"record\", \"name\": \"ct2\", \"fields\": "
+ "[{\"name\": \"f11\", \"type\": \"int\"}]}}," + "{\"name\": \"f2\", \"type\": \"long\"}" + "]}";
Assert.assertEquals("c1.ct2.\"int\"!", Schemas.visit(new Schema.Parser().parse(s9), new TestVisitor()));
}
@Test(expected = UnsupportedOperationException.class)
public void testVisit10() {
String s10 = "{\"type\": \"record\", \"name\": \"c1\", \"fields\": ["
+ "{\"name\": \"f1\", \"type\": {\"type\": \"record\", \"name\": \"ct2\", \"fields\": "
+ "[{\"name\": \"f11\", \"type\": \"int\"}]}}," + "{\"name\": \"f2\", \"type\": \"int\"}" + "]}";
Schemas.visit(new Schema.Parser().parse(s10), new TestVisitor() {
@Override
public SchemaVisitorAction visitTerminal(Schema terminal) {
return SchemaVisitorAction.SKIP_SUBTREE;
}
});
}
@Test
public void testVisit11() {
String s11 = "{\"type\": \"record\", \"name\": \"c1\", \"fields\": ["
+ "{\"name\": \"f1\", \"type\": {\"type\": \"record\", \"name\": \"c2\", \"fields\": "
+ "[{\"name\": \"f11\", \"type\": \"int\"},{\"name\": \"f12\", \"type\": \"double\"}" + "]}},"
+ "{\"name\": \"f2\", \"type\": \"long\"}" + "]}";
Assert.assertEquals("c1.c2.\"int\".!\"long\".!", Schemas.visit(new Schema.Parser().parse(s11), new TestVisitor() {
@Override
public SchemaVisitorAction visitTerminal(Schema terminal) {
sb.append(terminal).append('.');
return SchemaVisitorAction.SKIP_SIBLINGS;
}
}));
}
@Test
public void testVisit12() {
String s12 = "{\"type\": \"record\", \"name\": \"c1\", \"fields\": ["
+ "{\"name\": \"f1\", \"type\": {\"type\": \"record\", \"name\": \"ct2\", \"fields\": "
+ "[{\"name\": \"f11\", \"type\": \"int\"}]}}," + "{\"name\": \"f2\", \"type\": \"long\"}" + "]}";
Assert.assertEquals("c1.ct2.\"int\".", Schemas.visit(new Schema.Parser().parse(s12), new TestVisitor() {
@Override
public SchemaVisitorAction visitTerminal(Schema terminal) {
sb.append(terminal).append('.');
return SchemaVisitorAction.TERMINATE;
}
}));
}
@Test
public void testVisit13() {
String s12 = "{\"type\": \"int\"}";
Assert.assertEquals("\"int\".", Schemas.visit(new Schema.Parser().parse(s12), new TestVisitor() {
@Override
public SchemaVisitorAction visitTerminal(Schema terminal) {
sb.append(terminal).append('.');
return SchemaVisitorAction.SKIP_SIBLINGS;
}
}));
}
}
| 6,848 |
0 | Create_ds/avro/lang/java/idl/src/test/java/org/apache/avro | Create_ds/avro/lang/java/idl/src/test/java/org/apache/avro/idl/TestReferenceAnnotationNotAllowed.java | /*
* Copyright 2015 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro.idl;
import org.apache.avro.AvroRuntimeException;
import org.junit.Test;
import java.io.IOException;
import java.net.URISyntaxException;
import static java.util.Objects.requireNonNull;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
public class TestReferenceAnnotationNotAllowed {
@Test
public void testReferenceAnnotationNotAllowed() throws IOException, URISyntaxException {
final ClassLoader cl = Thread.currentThread().getContextClassLoader();
try {
new IdlReader().parse(requireNonNull(cl.getResource("AnnotationOnTypeReference.avdl")).toURI());
fail("Compilation should fail: annotations on type references are not allowed.");
} catch (AvroRuntimeException e) {
assertEquals("Type references may not be annotated, at line 29, column 16", e.getMessage());
}
}
}
| 6,849 |
0 | Create_ds/avro/lang/java/idl/src/test/java/org/apache/avro | Create_ds/avro/lang/java/idl/src/test/java/org/apache/avro/idl/TestSchemaResolver.java | /*
* Copyright 2017 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro.idl;
import org.apache.avro.Protocol;
import org.apache.avro.Schema;
import org.apache.avro.SchemaBuilder;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
public class TestSchemaResolver {
@Test
public void testResolving() throws IOException {
Path testIdl = Paths.get(".", "src", "test", "idl", "cycle.avdl").toAbsolutePath();
IdlReader parser = new IdlReader();
IdlFile idlFile = parser.parse(testIdl);
Protocol protocol = idlFile.getProtocol();
System.out.println(protocol);
Assert.assertEquals(5, protocol.getTypes().size());
}
@Test(expected = IllegalArgumentException.class)
public void testIsUnresolvedSchemaError1() {
// No "org.apache.avro.idl.unresolved.name" property
Schema s = SchemaBuilder.record("R").fields().endRecord();
SchemaResolver.getUnresolvedSchemaName(s);
}
@Test(expected = IllegalArgumentException.class)
public void testIsUnresolvedSchemaError2() {
// No "UnresolvedSchema" property
Schema s = SchemaBuilder.record("R").prop("org.apache.avro.idl.unresolved.name", "x").fields().endRecord();
SchemaResolver.getUnresolvedSchemaName(s);
}
@Test(expected = IllegalArgumentException.class)
public void testIsUnresolvedSchemaError3() {
// Namespace not "org.apache.avro.compiler".
Schema s = SchemaBuilder.record("UnresolvedSchema").prop("org.apache.avro.idl.unresolved.name", "x").fields()
.endRecord();
SchemaResolver.getUnresolvedSchemaName(s);
}
@Test(expected = IllegalArgumentException.class)
public void testGetUnresolvedSchemaNameError() {
Schema s = SchemaBuilder.fixed("a").size(10);
SchemaResolver.getUnresolvedSchemaName(s);
}
}
| 6,850 |
0 | Create_ds/avro/lang/java/idl/src/test/java/org/apache/avro | Create_ds/avro/lang/java/idl/src/test/java/org/apache/avro/idl/TestCycle.java | /*
* Copyright 2015 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro.idl;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericDatumReader;
import org.apache.avro.generic.GenericDatumWriter;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.generic.GenericRecordBuilder;
import org.apache.avro.io.BinaryDecoder;
import org.apache.avro.io.BinaryEncoder;
import org.apache.avro.io.DecoderFactory;
import org.apache.avro.io.EncoderFactory;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Collections;
import static java.util.Objects.requireNonNull;
public class TestCycle {
private static final Logger LOG = LoggerFactory.getLogger(TestCycle.class);
@Test
public void testCycleGeneration() throws IOException, URISyntaxException {
final ClassLoader cl = Thread.currentThread().getContextClassLoader();
IdlFile idlFile = new IdlReader().parse(requireNonNull(cl.getResource("input/cycle.avdl")).toURI());
String json = idlFile.outputString();
LOG.info(json);
GenericRecordBuilder rb2 = new GenericRecordBuilder(idlFile.getNamedSchema("SampleNode"));
rb2.set("count", 10);
rb2.set("subNodes", Collections.EMPTY_LIST);
GenericData.Record node = rb2.build();
GenericRecordBuilder mb = new GenericRecordBuilder(idlFile.getNamedSchema("Method"));
mb.set("declaringClass", "Test");
mb.set("methodName", "test");
GenericData.Record method = mb.build();
GenericRecordBuilder spb = new GenericRecordBuilder(idlFile.getNamedSchema("SamplePair"));
spb.set("method", method);
spb.set("node", node);
GenericData.Record sp = spb.build();
GenericRecordBuilder rb = new GenericRecordBuilder(idlFile.getNamedSchema("SampleNode"));
rb.set("count", 10);
rb.set("subNodes", Collections.singletonList(sp));
GenericData.Record record = rb.build();
serDeserRecord(record);
}
private static void serDeserRecord(GenericData.Record data) throws IOException {
ByteArrayOutputStream bab = new ByteArrayOutputStream();
GenericDatumWriter<GenericRecord> writer = new GenericDatumWriter<>(data.getSchema());
final BinaryEncoder directBinaryEncoder = EncoderFactory.get().directBinaryEncoder(bab, null);
writer.write(data, directBinaryEncoder);
directBinaryEncoder.flush();
ByteArrayInputStream bis = new ByteArrayInputStream(bab.toByteArray(), 0, bab.size());
GenericDatumReader<GenericRecord> reader = new GenericDatumReader<>(data.getSchema());
BinaryDecoder directBinaryDecoder = DecoderFactory.get().directBinaryDecoder(bis, null);
GenericData.Record read = (GenericData.Record) reader.read(null, directBinaryDecoder);
Assert.assertEquals(data.toString(), read.toString());
}
}
| 6,851 |
0 | Create_ds/avro/lang/java/idl/src/main/java/org/apache/avro | Create_ds/avro/lang/java/idl/src/main/java/org/apache/avro/idl/ResolvingVisitor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro.idl;
import org.apache.avro.AvroTypeException;
import org.apache.avro.Schema;
import org.apache.avro.Schema.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import static org.apache.avro.Schema.Type.ARRAY;
import static org.apache.avro.Schema.Type.ENUM;
import static org.apache.avro.Schema.Type.FIXED;
import static org.apache.avro.Schema.Type.MAP;
import static org.apache.avro.Schema.Type.RECORD;
import static org.apache.avro.Schema.Type.UNION;
/**
* This visitor creates clone of the visited Schemata, minus the specified
* schema properties, and resolves all unresolved schemas.
*/
public final class ResolvingVisitor implements SchemaVisitor<Schema> {
private static final Set<Schema.Type> CONTAINER_SCHEMA_TYPES = EnumSet.of(RECORD, ARRAY, MAP, UNION);
private static final Set<Schema.Type> NAMED_SCHEMA_TYPES = EnumSet.of(RECORD, ENUM, FIXED);
private final Function<String, Schema> symbolTable;
private final Set<String> schemaPropertiesToRemove;
private final IdentityHashMap<Schema, Schema> replace;
private final Schema root;
public ResolvingVisitor(final Schema root, final Function<String, Schema> symbolTable,
String... schemaPropertiesToRemove) {
this(root, symbolTable, new HashSet<>(Arrays.asList(schemaPropertiesToRemove)));
}
public ResolvingVisitor(final Schema root, final Function<String, Schema> symbolTable,
Set<String> schemaPropertiesToRemove) {
this.replace = new IdentityHashMap<>();
this.symbolTable = symbolTable;
this.schemaPropertiesToRemove = schemaPropertiesToRemove;
this.root = root;
}
public ResolvingVisitor withRoot(Schema root) {
return new ResolvingVisitor(root, symbolTable, schemaPropertiesToRemove);
}
@Override
public SchemaVisitorAction visitTerminal(final Schema terminal) {
Schema.Type type = terminal.getType();
Schema newSchema;
if (CONTAINER_SCHEMA_TYPES.contains(type)) {
if (!replace.containsKey(terminal)) {
throw new IllegalStateException("Schema " + terminal + " must be already processed");
}
return SchemaVisitorAction.CONTINUE;
} else if (type == ENUM) {
newSchema = Schema.createEnum(terminal.getName(), terminal.getDoc(), terminal.getNamespace(),
terminal.getEnumSymbols(), terminal.getEnumDefault());
} else if (type == FIXED) {
newSchema = Schema.createFixed(terminal.getName(), terminal.getDoc(), terminal.getNamespace(),
terminal.getFixedSize());
} else {
newSchema = Schema.create(type);
}
copyProperties(terminal, newSchema);
replace.put(terminal, newSchema);
return SchemaVisitorAction.CONTINUE;
}
public void copyProperties(final Schema first, final Schema second) {
// Logical type
Optional.ofNullable(first.getLogicalType()).ifPresent(logicalType -> logicalType.addToSchema(second));
// Aliases (if applicable)
if (NAMED_SCHEMA_TYPES.contains(first.getType())) {
first.getAliases().forEach(second::addAlias);
}
// Other properties
first.getObjectProps().forEach((name, value) -> {
if (!schemaPropertiesToRemove.contains(name)) {
second.addProp(name, value);
}
});
}
@Override
public SchemaVisitorAction visitNonTerminal(final Schema nt) {
Schema.Type type = nt.getType();
if (type == RECORD) {
if (SchemaResolver.isUnresolvedSchema(nt)) {
// unresolved schema will get a replacement that we already encountered,
// or we will attempt to resolve.
final String unresolvedSchemaName = SchemaResolver.getUnresolvedSchemaName(nt);
Schema resSchema = symbolTable.apply(unresolvedSchemaName);
if (resSchema == null) {
throw new AvroTypeException("Unable to resolve " + unresolvedSchemaName);
}
Schema replacement = replace.computeIfAbsent(resSchema, schema -> {
Schemas.visit(schema, this);
return replace.get(schema);
});
replace.put(nt, replacement);
} else {
// create a fieldless clone. Fields will be added in afterVisitNonTerminal.
Schema newSchema = Schema.createRecord(nt.getName(), nt.getDoc(), nt.getNamespace(), nt.isError());
copyProperties(nt, newSchema);
replace.put(nt, newSchema);
}
}
return SchemaVisitorAction.CONTINUE;
}
@Override
public SchemaVisitorAction afterVisitNonTerminal(final Schema nt) {
Schema.Type type = nt.getType();
Schema newSchema;
switch (type) {
case RECORD:
if (!SchemaResolver.isUnresolvedSchema(nt)) {
newSchema = replace.get(nt);
// Check if we've already handled the replacement schema with a
// reentrant call to visit(...) from within the visitor.
if (!newSchema.hasFields()) {
List<Schema.Field> fields = nt.getFields();
List<Schema.Field> newFields = new ArrayList<>(fields.size());
for (Schema.Field field : fields) {
newFields.add(new Field(field, replace.get(field.schema())));
}
newSchema.setFields(newFields);
}
}
return SchemaVisitorAction.CONTINUE;
case UNION:
List<Schema> types = nt.getTypes();
List<Schema> newTypes = new ArrayList<>(types.size());
for (Schema sch : types) {
newTypes.add(replace.get(sch));
}
newSchema = Schema.createUnion(newTypes);
break;
case ARRAY:
newSchema = Schema.createArray(replace.get(nt.getElementType()));
break;
case MAP:
newSchema = Schema.createMap(replace.get(nt.getValueType()));
break;
default:
throw new IllegalStateException("Illegal type " + type + ", schema " + nt);
}
copyProperties(nt, newSchema);
replace.put(nt, newSchema);
return SchemaVisitorAction.CONTINUE;
}
@Override
public Schema get() {
return replace.get(root);
}
@Override
public String toString() {
return "ResolvingVisitor{symbolTable=" + symbolTable + ", schemaPropertiesToRemove=" + schemaPropertiesToRemove
+ ", replace=" + replace + '}';
}
}
| 6,852 |
0 | Create_ds/avro/lang/java/idl/src/main/java/org/apache/avro | Create_ds/avro/lang/java/idl/src/main/java/org/apache/avro/idl/IdlFile.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro.idl;
import org.apache.avro.Protocol;
import org.apache.avro.Schema;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* A parsed IdlFile. Provides access to the named schemas in the IDL file and
* the protocol containing the schemas.
*/
public class IdlFile {
private final Schema mainSchema;
private final Protocol protocol;
private final String namespace;
private final Map<String, Schema> namedSchemas;
private final List<String> warnings;
IdlFile(Protocol protocol, List<String> warnings) {
this(protocol.getNamespace(), protocol.getTypes(), null, protocol, warnings);
}
IdlFile(String namespace, Schema mainSchema, Iterable<Schema> schemas, List<String> warnings) {
this(namespace, schemas, mainSchema, null, warnings);
}
private IdlFile(String namespace, Iterable<Schema> schemas, Schema mainSchema, Protocol protocol,
List<String> warnings) {
this.namespace = namespace;
this.namedSchemas = new LinkedHashMap<>();
for (Schema namedSchema : schemas) {
this.namedSchemas.put(namedSchema.getFullName(), namedSchema);
}
this.mainSchema = mainSchema;
this.protocol = protocol;
this.warnings = Collections.unmodifiableList(new ArrayList<>(warnings));
}
/**
* The (main) schema defined by the IDL file.
*/
public Schema getMainSchema() {
return mainSchema;
}
/**
* The protocol defined by the IDL file.
*/
public Protocol getProtocol() {
return protocol;
}
public List<String> getWarnings() {
return warnings;
}
public List<String> getWarnings(String importFile) {
return warnings.stream()
.map(warning -> importFile + ' ' + Character.toLowerCase(warning.charAt(0)) + warning.substring(1))
.collect(Collectors.toList());
}
/**
* The default namespace to resolve schema names against.
*/
public String getNamespace() {
return namespace;
}
/**
* The named schemas defined by the IDL file, mapped by their full name.
*/
public Map<String, Schema> getNamedSchemas() {
return Collections.unmodifiableMap(namedSchemas);
}
/**
* Get a named schema defined by the IDL file, by name. The name can be a simple
* name in the default namespace of the IDL file (e.g., the namespace of the
* protocol), or a full name.
*
* @param name the full name of the schema, or a simple name
* @return the schema, or {@code null} if it does not exist
*/
public Schema getNamedSchema(String name) {
Schema result = namedSchemas.get(name);
if (result != null) {
return result;
}
if (namespace != null && !name.contains(".")) {
result = namedSchemas.get(namespace + '.' + name);
}
return result;
}
// Visible for testing
String outputString() {
if (protocol != null) {
return protocol.toString();
}
if (mainSchema != null) {
return mainSchema.toString();
}
if (namedSchemas.isEmpty()) {
return "[]";
} else {
StringBuilder buffer = new StringBuilder();
for (Schema schema : namedSchemas.values()) {
buffer.append(',').append(schema);
}
buffer.append(']').setCharAt(0, '[');
return buffer.toString();
}
}
}
| 6,853 |
0 | Create_ds/avro/lang/java/idl/src/main/java/org/apache/avro | Create_ds/avro/lang/java/idl/src/main/java/org/apache/avro/idl/IdlReader.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro.idl;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.BooleanNode;
import com.fasterxml.jackson.databind.node.DoubleNode;
import com.fasterxml.jackson.databind.node.IntNode;
import com.fasterxml.jackson.databind.node.LongNode;
import com.fasterxml.jackson.databind.node.NullNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;
import org.antlr.v4.runtime.BaseErrorListener;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.Recognizer;
import org.antlr.v4.runtime.Token;
import org.apache.avro.JsonProperties;
import org.apache.avro.LogicalType;
import org.apache.avro.LogicalTypes;
import org.apache.avro.Protocol;
import org.apache.avro.Schema;
import org.apache.avro.SchemaParseException;
import org.apache.avro.idl.IdlParser.ArrayTypeContext;
import org.apache.avro.idl.IdlParser.EnumDeclarationContext;
import org.apache.avro.idl.IdlParser.EnumSymbolContext;
import org.apache.avro.idl.IdlParser.FieldDeclarationContext;
import org.apache.avro.idl.IdlParser.FixedDeclarationContext;
import org.apache.avro.idl.IdlParser.FormalParameterContext;
import org.apache.avro.idl.IdlParser.FullTypeContext;
import org.apache.avro.idl.IdlParser.IdentifierContext;
import org.apache.avro.idl.IdlParser.IdlFileContext;
import org.apache.avro.idl.IdlParser.ImportStatementContext;
import org.apache.avro.idl.IdlParser.JsonArrayContext;
import org.apache.avro.idl.IdlParser.JsonLiteralContext;
import org.apache.avro.idl.IdlParser.JsonObjectContext;
import org.apache.avro.idl.IdlParser.JsonPairContext;
import org.apache.avro.idl.IdlParser.JsonValueContext;
import org.apache.avro.idl.IdlParser.MapTypeContext;
import org.apache.avro.idl.IdlParser.MessageDeclarationContext;
import org.apache.avro.idl.IdlParser.NamespaceDeclarationContext;
import org.apache.avro.idl.IdlParser.NullableTypeContext;
import org.apache.avro.idl.IdlParser.PrimitiveTypeContext;
import org.apache.avro.idl.IdlParser.ProtocolDeclarationBodyContext;
import org.apache.avro.idl.IdlParser.ProtocolDeclarationContext;
import org.apache.avro.idl.IdlParser.RecordBodyContext;
import org.apache.avro.idl.IdlParser.RecordDeclarationContext;
import org.apache.avro.idl.IdlParser.ResultTypeContext;
import org.apache.avro.idl.IdlParser.SchemaPropertyContext;
import org.apache.avro.idl.IdlParser.UnionTypeContext;
import org.apache.avro.idl.IdlParser.VariableDeclarationContext;
import org.apache.avro.util.internal.Accessor;
import org.apache.commons.text.StringEscapeUtils;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Deque;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.util.Collections.singleton;
import static java.util.Collections.unmodifiableMap;
public class IdlReader {
/**
* Simple error listener. Throws a runtime exception because ANTLR does not give
* easy access to the (reasonably readable) error message elsewhere.
*/
private static final BaseErrorListener SIMPLE_AVRO_ERROR_LISTENER = new BaseErrorListener() {
@Override
public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine,
String msg, RecognitionException e) {
throw new SchemaParseException("line " + line + ":" + charPositionInLine + " " + msg);
}
};
private static final String OPTIONAL_NULLABLE_TYPE_PROPERTY = "org.apache.avro.idl.Idl.NullableType.optional";
/**
* Pattern to match the common whitespace indents in a multi-line String.
* Doesn't match a single-line String, fully matches any multi-line String.
* <p>
* To use: match on a {@link String#trim() trimmed} String, and then replace all
* newlines followed by the group "indent" with a newline.
*/
private static final Pattern WS_INDENT = Pattern.compile("(?U).*\\R(?<indent>\\h*).*(?:\\R\\k<indent>.*)*");
/**
* Pattern to match the whitespace indents plus common stars (1 or 2) in a
* multi-line String. If a String fully matches, replace all occurrences of a
* newline followed by whitespace and then the group "stars" with a newline.
* <p>
* Note: partial matches are invalid.
*/
private static final Pattern STAR_INDENT = Pattern.compile("(?U)(?<stars>\\*{1,2}).*(?:\\R\\h*\\k<stars>.*)*");
/**
* Predicate to check for valid names. Should probably be delegated to the
* Schema class.
*/
private static final Predicate<String> VALID_NAME = Pattern.compile("[_\\p{L}][_\\p{L}\\d]*").asPredicate();
private static final Set<String> INVALID_TYPE_NAMES = new HashSet<>(Arrays.asList("boolean", "int", "long", "float",
"double", "bytes", "string", "null", "date", "time_ms", "timestamp_ms", "localtimestamp_ms", "uuid"));
private static final String CLASSPATH_SCHEME = "classpath";
private final Set<URI> readLocations;
private final Map<String, Schema> names;
public IdlReader() {
readLocations = new HashSet<>();
names = new LinkedHashMap<>();
}
public Map<String, Schema> getTypes() {
return unmodifiableMap(names);
}
private Schema namedSchemaOrUnresolved(String fullName) {
Schema schema = names.get(fullName);
if (schema == null) {
schema = SchemaResolver.unresolvedSchema(fullName);
}
return schema;
}
private void setTypes(Map<String, Schema> types) {
names.clear();
for (Schema schema : types.values()) {
addSchema(schema);
}
}
public void addTypes(Map<String, Schema> types) {
for (Schema schema : types.values()) {
addSchema(schema);
}
}
private void addSchema(Schema schema) {
String fullName = schema.getFullName();
if (names.containsKey(fullName)) {
throw new SchemaParseException("Can't redefine: " + fullName);
}
names.put(fullName, schema);
}
public IdlFile parse(Path location) throws IOException {
return parse(location.toUri());
}
IdlFile parse(URI location) throws IOException {
try (InputStream stream = location.toURL().openStream()) {
readLocations.add(location);
URI inputDir = location;
if ("jar".equals(location.getScheme())) {
String jarUriAsString = location.toString();
String pathFromJarRoot = jarUriAsString.substring(jarUriAsString.indexOf("!/") + 2);
inputDir = URI.create(CLASSPATH_SCHEME + ":/" + pathFromJarRoot);
}
inputDir = inputDir.resolve(".");
return parse(inputDir, CharStreams.fromStream(stream, StandardCharsets.UTF_8));
}
}
/**
* Parse an IDL file from a stream. This method cannot handle imports.
*/
public IdlFile parse(InputStream stream) throws IOException {
return parse(null, CharStreams.fromStream(stream, StandardCharsets.UTF_8));
}
private IdlFile parse(URI inputDir, CharStream charStream) {
IdlLexer lexer = new IdlLexer(charStream);
CommonTokenStream tokenStream = new CommonTokenStream(lexer);
IdlParserListener parseListener = new IdlParserListener(inputDir, tokenStream);
IdlParser parser = new IdlParser(tokenStream);
parser.removeErrorListeners();
parser.addErrorListener(SIMPLE_AVRO_ERROR_LISTENER);
parser.addParseListener(parseListener);
parser.setTrace(false);
parser.setBuildParseTree(false);
// Trigger parsing.
parser.idlFile();
return parseListener.getIdlFile();
}
/* Package private to facilitate testing */
static String stripIndents(String docComment) {
Matcher starMatcher = STAR_INDENT.matcher(docComment);
if (starMatcher.matches()) {
return docComment.replaceAll("(?U)(?:^|(\\R)\\h*)\\Q" + starMatcher.group("stars") + "\\E\\h?", "$1");
}
Matcher whitespaceMatcher = WS_INDENT.matcher(docComment);
if (whitespaceMatcher.matches()) {
return docComment.replaceAll("(?U)(\\R)" + whitespaceMatcher.group("indent"), "$1");
}
return docComment;
}
private static SchemaParseException error(String message, Token token) {
return error(message, token, null);
}
private static SchemaParseException error(String message, Token token, Throwable cause) {
SchemaParseException exception = new SchemaParseException(
message + ", at line " + token.getLine() + ", column " + token.getCharPositionInLine());
if (cause != null) {
exception.initCause(cause);
}
return exception;
}
private class IdlParserListener extends IdlBaseListener {
private final URI inputDir;
private final CommonTokenStream tokenStream;
private int hiddenTokensProcessedIndex;
private final List<String> warnings;
private IdlFile result;
private Schema mainSchema;
private Protocol protocol;
private final Deque<String> namespaces;
private final List<String> enumSymbols;
private String enumDefaultSymbol;
private Schema schema;
private String defaultVariableDocComment;
private final List<Schema.Field> fields;
private final Deque<Schema> typeStack;
private final Deque<JsonNode> jsonValues;
private final Deque<SchemaProperties> propertiesStack;
private String messageDocComment;
public IdlParserListener(URI inputDir, CommonTokenStream tokenStream) {
this.inputDir = inputDir;
this.tokenStream = tokenStream;
hiddenTokensProcessedIndex = -1;
warnings = new ArrayList<>();
result = null;
mainSchema = null;
protocol = null;
namespaces = new ArrayDeque<>();
enumSymbols = new ArrayList<>();
enumDefaultSymbol = null;
schema = null;
defaultVariableDocComment = null;
fields = new ArrayList<>();
typeStack = new ArrayDeque<>();
propertiesStack = new ArrayDeque<>();
jsonValues = new ArrayDeque<>();
messageDocComment = null;
}
public IdlFile getIdlFile() {
return result;
}
private String getDocComment(ParserRuleContext ctx) {
int newHiddenTokensProcessedIndex = ctx.start.getTokenIndex();
List<Token> docCommentTokens = tokenStream.getHiddenTokensToLeft(newHiddenTokensProcessedIndex, -1);
int searchEndIndex = newHiddenTokensProcessedIndex;
Token docCommentToken = null;
if (docCommentTokens != null) {
// There's at least one element
docCommentToken = docCommentTokens.get(docCommentTokens.size() - 1);
searchEndIndex = docCommentToken.getTokenIndex() - 1;
}
Set<Integer> allHiddenTokens = singleton(IdlParser.DocComment);
if (searchEndIndex >= 0) {
List<Token> hiddenTokens = tokenStream.getTokens(hiddenTokensProcessedIndex + 1, searchEndIndex,
allHiddenTokens);
if (hiddenTokens != null) {
for (Token token : hiddenTokens) {
warnings.add(String.format(
"Line %d, char %d: Ignoring out-of-place documentation comment.%n"
+ "Did you mean to use a multiline comment ( /* ... */ ) instead?",
token.getLine(), token.getCharPositionInLine() + 1));
}
}
}
hiddenTokensProcessedIndex = newHiddenTokensProcessedIndex;
if (docCommentToken == null) {
return null;
}
String comment = docCommentToken.getText();
String text = comment.substring(3, comment.length() - 2); // Strip /** & */
return stripIndents(text.trim());
}
private void pushNamespace(String namespace) {
namespaces.push(namespace == null ? "" : namespace);
}
private String currentNamespace() {
String namespace = namespaces.peek();
return namespace == null || namespace.isEmpty() ? null : namespace;
}
private void popNamespace() {
namespaces.pop();
}
@Override
public void exitIdlFile(IdlFileContext ctx) {
IdlFile unresolved;
if (protocol == null) {
unresolved = new IdlFile(currentNamespace(), mainSchema, getTypes().values(), warnings);
} else {
unresolved = new IdlFile(protocol, warnings);
}
result = SchemaResolver.resolve(unresolved, OPTIONAL_NULLABLE_TYPE_PROPERTY);
}
@Override
public void enterProtocolDeclaration(ProtocolDeclarationContext ctx) {
propertiesStack.push(new SchemaProperties(null, true, false, false));
}
@Override
public void enterProtocolDeclarationBody(ProtocolDeclarationBodyContext ctx) {
ProtocolDeclarationContext protocolCtx = (ProtocolDeclarationContext) ctx.parent;
SchemaProperties properties = propertiesStack.pop();
String protocolIdentifier = identifier(protocolCtx.name);
pushNamespace(namespace(protocolIdentifier, properties.namespace()));
String protocolName = name(protocolIdentifier);
String docComment = getDocComment(protocolCtx);
String protocolNamespace = currentNamespace();
protocol = properties.copyProperties(new Protocol(protocolName, docComment, protocolNamespace));
}
@Override
public void exitProtocolDeclaration(ProtocolDeclarationContext ctx) {
if (protocol != null)
protocol.setTypes(getTypes().values());
if (!namespaces.isEmpty())
popNamespace();
}
@Override
public void exitNamespaceDeclaration(NamespaceDeclarationContext ctx) {
pushNamespace(namespace("", identifier(ctx.namespace)));
}
@Override
public void exitMainSchemaDeclaration(IdlParser.MainSchemaDeclarationContext ctx) {
mainSchema = typeStack.pop();
assert typeStack.isEmpty();
}
@Override
public void enterSchemaProperty(SchemaPropertyContext ctx) {
assert jsonValues.isEmpty();
}
@Override
public void exitSchemaProperty(SchemaPropertyContext ctx) {
String name = identifier(ctx.name);
JsonNode value = jsonValues.pop();
Token firstToken = ctx.value.start;
propertiesStack.element().addProperty(name, value, firstToken);
super.exitSchemaProperty(ctx);
}
@Override
public void exitImportStatement(ImportStatementContext importContext) {
String importFile = getString(importContext.location);
try {
URI importLocation = findImport(importFile);
if (!readLocations.add(importLocation)) {
// Already imported
return;
}
switch (importContext.importType.getType()) {
case IdlParser.IDL:
// Note that the parse(URI) method uses the same known schema collection
IdlFile idlFile = parse(importLocation);
if (protocol != null && idlFile.getProtocol() != null) {
protocol.getMessages().putAll(idlFile.getProtocol().getMessages());
}
warnings.addAll(idlFile.getWarnings(importFile));
break;
case IdlParser.Protocol:
try (InputStream stream = importLocation.toURL().openStream()) {
Protocol importProtocol = Protocol.parse(stream);
for (Schema s : importProtocol.getTypes()) {
addSchema(s);
}
if (protocol != null) {
protocol.getMessages().putAll(importProtocol.getMessages());
}
}
break;
case IdlParser.Schema:
try (InputStream stream = importLocation.toURL().openStream()) {
Schema.Parser parser = new Schema.Parser();
parser.addTypes(getTypes().values()); // inherit names
parser.parse(stream);
setTypes(parser.getTypes()); // update names
}
break;
}
} catch (IOException e) {
throw error("Error importing " + importFile + ": " + e, importContext.location, e);
}
}
/**
* Best effort guess at the import file location. For locations inside jar
* files, this may result in non-existing URLs.
*/
private URI findImport(String importFile) throws IOException {
URI importLocation = inputDir.resolve(importFile);
String importLocationScheme = importLocation.getScheme();
if (CLASSPATH_SCHEME.equals(importLocationScheme)) {
String resourceName = importLocation.getSchemeSpecificPart().substring(1);
URI resourceLocation = findResource(resourceName);
if (resourceLocation != null) {
return resourceLocation;
}
}
if ("file".equals(importLocationScheme) && Files.exists(Paths.get(importLocation))) {
return importLocation;
}
// The importFile doesn't exist as file relative to the current file. Try to
// load it from the classpath.
URI resourceLocation = findResource(importFile);
if (resourceLocation != null) {
return resourceLocation;
}
// Cannot find the import.
throw new FileNotFoundException(importFile);
}
private URI findResource(String resourceName) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL resourceLocation;
if (classLoader == null) {
resourceLocation = ClassLoader.getSystemResource(resourceName);
} else {
resourceLocation = classLoader.getResource(resourceName);
}
return resourceLocation == null ? null : URI.create(resourceLocation.toExternalForm());
}
@Override
public void enterFixedDeclaration(FixedDeclarationContext ctx) {
propertiesStack.push(new SchemaProperties(currentNamespace(), true, true, false));
}
@Override
public void exitFixedDeclaration(FixedDeclarationContext ctx) {
SchemaProperties properties = propertiesStack.pop();
String doc = getDocComment(ctx);
String identifier = identifier(ctx.name);
String name = name(identifier);
String space = namespace(identifier, properties.namespace());
int size = Integer.decode(ctx.size.getText());
Schema schema = Schema.createFixed(name, doc, space, size);
properties.copyAliases(schema::addAlias);
properties.copyProperties(schema);
addSchema(schema);
}
@Override
public void enterEnumDeclaration(EnumDeclarationContext ctx) {
assert enumSymbols.isEmpty();
assert enumDefaultSymbol == null;
propertiesStack.push(new SchemaProperties(currentNamespace(), true, true, false));
}
@Override
public void exitEnumDeclaration(EnumDeclarationContext ctx) {
String doc = getDocComment(ctx);
SchemaProperties properties = propertiesStack.pop();
String identifier = identifier(ctx.name);
String name = name(identifier);
String space = namespace(identifier, properties.namespace());
Schema schema = Schema.createEnum(name, doc, space, new ArrayList<>(enumSymbols), enumDefaultSymbol);
properties.copyAliases(schema::addAlias);
properties.copyProperties(schema);
enumSymbols.clear();
enumDefaultSymbol = null;
addSchema(schema);
}
@Override
public void enterEnumSymbol(EnumSymbolContext ctx) {
propertiesStack.push(new SchemaProperties(null, false, false, false));
}
@Override
public void exitEnumSymbol(EnumSymbolContext ctx) {
// TODO: implement doc comment & properties for enum symbols.
propertiesStack.pop();
enumSymbols.add(identifier(ctx.name));
}
@Override
public void exitEnumDefault(IdlParser.EnumDefaultContext ctx) {
enumDefaultSymbol = identifier(ctx.defaultSymbolName);
}
@Override
public void enterRecordDeclaration(RecordDeclarationContext ctx) {
assert schema == null;
assert fields.isEmpty();
propertiesStack.push(new SchemaProperties(currentNamespace(), true, true, false));
}
@Override
public void enterRecordBody(RecordBodyContext ctx) {
assert fields.isEmpty();
RecordDeclarationContext recordCtx = (RecordDeclarationContext) ctx.parent;
SchemaProperties properties = propertiesStack.pop();
String doc = getDocComment(recordCtx);
String identifier = identifier(recordCtx.name);
String name = name(identifier);
pushNamespace(namespace(identifier, properties.namespace()));
boolean isError = recordCtx.recordType.getType() == IdlParser.Error;
schema = Schema.createRecord(name, doc, currentNamespace(), isError);
properties.copyAliases(schema::addAlias);
properties.copyProperties(schema);
}
@Override
public void exitRecordDeclaration(RecordDeclarationContext ctx) {
schema.setFields(fields);
fields.clear();
addSchema(schema);
schema = null;
popNamespace();
}
@Override
public void enterFieldDeclaration(FieldDeclarationContext ctx) {
assert typeStack.isEmpty();
defaultVariableDocComment = getDocComment(ctx);
}
@Override
public void exitFieldDeclaration(FieldDeclarationContext ctx) {
typeStack.pop();
defaultVariableDocComment = null;
}
@Override
public void enterVariableDeclaration(VariableDeclarationContext ctx) {
assert jsonValues.isEmpty();
propertiesStack.push(new SchemaProperties(currentNamespace(), false, true, true));
}
@Override
public void exitVariableDeclaration(VariableDeclarationContext ctx) {
String doc = Optional.ofNullable(getDocComment(ctx)).orElse(defaultVariableDocComment);
String fieldName = identifier(ctx.fieldName);
JsonNode defaultValue = jsonValues.poll();
Schema type = typeStack.element();
JsonNode fieldDefault = fixDefaultValue(defaultValue, type);
Schema fieldType = fixOptionalSchema(type, fieldDefault);
SchemaProperties properties = propertiesStack.pop();
boolean validate = SchemaResolver.isFullyResolvedSchema(fieldType);
Schema.Field field = Accessor.createField(fieldName, fieldType, doc, fieldDefault, validate, properties.order());
properties.copyAliases(field::addAlias);
properties.copyProperties(field);
fields.add(field);
}
/**
* When parsing JSON, the parser generates a LongNode or IntNode based on the
* size of the number it encounters. But this may not be expected based on the
* schema. This method fixes that.
*
* @param defaultValue the parsed default value
* @param fieldType the field schema
* @return the default value, now matching the schema
*/
private JsonNode fixDefaultValue(JsonNode defaultValue, Schema fieldType) {
if (!(defaultValue instanceof IntNode)) {
return defaultValue;
}
if (fieldType.getType() == Schema.Type.UNION) {
for (Schema unionedType : fieldType.getTypes()) {
if (unionedType.getType() == Schema.Type.INT) {
break;
} else if (unionedType.getType() == Schema.Type.LONG) {
return new LongNode(defaultValue.longValue());
}
}
return defaultValue;
}
if (fieldType.getType() == Schema.Type.LONG) {
return new LongNode(defaultValue.longValue());
}
return defaultValue;
}
/**
* For "optional schemas" (recognized by the marker property the NullableType
* production adds), ensure the null schema is in the right place.
*
* @param schema a schema
* @param defaultValue the intended default value
* @return the schema, or an optional schema with null in the right place
*/
private Schema fixOptionalSchema(Schema schema, JsonNode defaultValue) {
Object optionalType = schema.getObjectProp(OPTIONAL_NULLABLE_TYPE_PROPERTY);
if (optionalType != null) {
// The schema is a union schema with 2 types: "null" and a non-"null" schema
Schema nullSchema = schema.getTypes().get(0);
Schema nonNullSchema = schema.getTypes().get(1);
boolean nonNullDefault = defaultValue != null && !defaultValue.isNull();
// Note: the resolving visitor we'll use later drops the marker property.
if (nonNullDefault) {
return Schema.createUnion(nonNullSchema, nullSchema);
}
}
return schema;
}
@Override
public void enterMessageDeclaration(MessageDeclarationContext ctx) {
assert typeStack.isEmpty();
assert fields.isEmpty();
assert messageDocComment == null;
propertiesStack.push(new SchemaProperties(currentNamespace(), false, false, false));
messageDocComment = getDocComment(ctx);
}
@Override
public void exitMessageDeclaration(MessageDeclarationContext ctx) {
Schema resultType = typeStack.pop();
Map<String, JsonNode> properties = propertiesStack.pop().properties;
String name = identifier(ctx.name);
Schema request = Schema.createRecord(null, null, null, false, fields);
fields.clear();
Protocol.Message message;
if (ctx.oneway != null) {
if (resultType.getType() == Schema.Type.NULL) {
message = protocol.createMessage(name, messageDocComment, properties, request);
} else {
throw error("One-way message'" + name + "' must return void", ctx.returnType.start);
}
} else {
List<Schema> errorSchemas = new ArrayList<>();
errorSchemas.add(Protocol.SYSTEM_ERROR);
for (IdentifierContext errorContext : ctx.errors) {
errorSchemas.add(namedSchemaOrUnresolved(fullName(currentNamespace(), identifier(errorContext))));
}
message = protocol.createMessage(name, messageDocComment, properties, request, resultType,
Schema.createUnion(errorSchemas));
}
messageDocComment = null;
protocol.getMessages().put(message.getName(), message);
}
@Override
public void enterFormalParameter(FormalParameterContext ctx) {
assert typeStack.size() == 1; // The message return type is on the stack; nothing else.
defaultVariableDocComment = getDocComment(ctx);
}
@Override
public void exitFormalParameter(FormalParameterContext ctx) {
typeStack.pop();
defaultVariableDocComment = null;
}
@Override
public void exitResultType(ResultTypeContext ctx) {
if (typeStack.isEmpty()) {
// if there's no type, we've parsed 'void': use the null type
typeStack.push(Schema.create(Schema.Type.NULL));
}
}
@Override
public void enterFullType(FullTypeContext ctx) {
propertiesStack.push(new SchemaProperties(currentNamespace(), false, false, false));
}
@Override
public void exitFullType(FullTypeContext ctx) {
SchemaProperties properties = propertiesStack.pop();
Schema type = typeStack.element();
if (type.getObjectProp(OPTIONAL_NULLABLE_TYPE_PROPERTY) != null) {
// Optional type: put the properties on the non-null content
properties.copyProperties(type.getTypes().get(1));
} else {
properties.copyProperties(type);
}
}
@Override
public void exitNullableType(NullableTypeContext ctx) {
Schema type;
if (ctx.referenceName == null) {
type = typeStack.pop();
} else {
// propertiesStack is empty within resultType->plainType->nullableType, and
// holds our properties otherwise
if (propertiesStack.isEmpty() || propertiesStack.peek().hasProperties()) {
throw error("Type references may not be annotated", ctx.getParent().getStart());
}
type = namedSchemaOrUnresolved(fullName(currentNamespace(), identifier(ctx.referenceName)));
}
if (ctx.optional != null) {
type = Schema.createUnion(Schema.create(Schema.Type.NULL), type);
// Add a marker property to the union (it will be removed when creating fields)
type.addProp(OPTIONAL_NULLABLE_TYPE_PROPERTY, BooleanNode.TRUE);
}
typeStack.push(type);
}
@Override
public void exitPrimitiveType(PrimitiveTypeContext ctx) {
switch (ctx.typeName.getType()) {
case IdlParser.Boolean:
typeStack.push(Schema.create(Schema.Type.BOOLEAN));
break;
case IdlParser.Int:
typeStack.push(Schema.create(Schema.Type.INT));
break;
case IdlParser.Long:
typeStack.push(Schema.create(Schema.Type.LONG));
break;
case IdlParser.Float:
typeStack.push(Schema.create(Schema.Type.FLOAT));
break;
case IdlParser.Double:
typeStack.push(Schema.create(Schema.Type.DOUBLE));
break;
case IdlParser.Bytes:
typeStack.push(Schema.create(Schema.Type.BYTES));
break;
case IdlParser.String:
typeStack.push(Schema.create(Schema.Type.STRING));
break;
case IdlParser.Null:
typeStack.push(Schema.create(Schema.Type.NULL));
break;
case IdlParser.Date:
typeStack.push(LogicalTypes.date().addToSchema(Schema.create(Schema.Type.INT)));
break;
case IdlParser.Time:
typeStack.push(LogicalTypes.timeMillis().addToSchema(Schema.create(Schema.Type.INT)));
break;
case IdlParser.Timestamp:
typeStack.push(LogicalTypes.timestampMillis().addToSchema(Schema.create(Schema.Type.LONG)));
break;
case IdlParser.LocalTimestamp:
typeStack.push(LogicalTypes.localTimestampMillis().addToSchema(Schema.create(Schema.Type.LONG)));
break;
case IdlParser.UUID:
typeStack.push(LogicalTypes.uuid().addToSchema(Schema.create(Schema.Type.STRING)));
break;
default: // Only option left: decimal
int precision = Integer.decode(ctx.precision.getText());
int scale = ctx.scale == null ? 0 : Integer.decode(ctx.scale.getText());
typeStack.push(LogicalTypes.decimal(precision, scale).addToSchema(Schema.create(Schema.Type.BYTES)));
break;
}
}
@Override
public void exitArrayType(ArrayTypeContext ctx) {
typeStack.push(Schema.createArray(typeStack.pop()));
}
@Override
public void exitMapType(MapTypeContext ctx) {
typeStack.push(Schema.createMap(typeStack.pop()));
}
@Override
public void enterUnionType(UnionTypeContext ctx) {
// push an empty marker union; we'll replace it with the real union upon exit
typeStack.push(Schema.createUnion());
}
@Override
public void exitUnionType(UnionTypeContext ctx) {
List<Schema> types = new ArrayList<>();
Schema type;
while ((type = typeStack.pop()).getType() != Schema.Type.UNION) {
types.add(type);
}
Collections.reverse(types); // Popping the stack works in reverse order
// type is an empty marker union; ignore (drop) it
typeStack.push(Schema.createUnion(types));
}
@Override
public void exitJsonValue(JsonValueContext ctx) {
if (ctx.parent instanceof JsonArrayContext) {
JsonNode value = jsonValues.pop();
assert jsonValues.peek() instanceof ArrayNode;
((ArrayNode) jsonValues.element()).add(value);
}
}
@Override
public void exitJsonLiteral(JsonLiteralContext ctx) {
Token literal = ctx.literal;
switch (literal.getType()) {
case IdlParser.Null:
jsonValues.push(NullNode.getInstance());
break;
case IdlParser.BTrue:
jsonValues.push(BooleanNode.TRUE);
break;
case IdlParser.BFalse:
jsonValues.push(BooleanNode.FALSE);
break;
case IdlParser.IntegerLiteral:
String number = literal.getText().replace("_", "");
char lastChar = number.charAt(number.length() - 1);
boolean coerceToLong = false;
if (lastChar == 'l' || lastChar == 'L') {
coerceToLong = true;
number = number.substring(0, number.length() - 1);
}
long longNumber = Long.decode(number);
int intNumber = (int) longNumber; // Narrowing cast: if too large a number, the two are different
jsonValues.push(coerceToLong || intNumber != longNumber ? new LongNode(longNumber) : new IntNode(intNumber));
break;
case IdlParser.FloatingPointLiteral:
jsonValues.push(new DoubleNode(Double.parseDouble(literal.getText())));
break;
default: // StringLiteral:
jsonValues.push(new TextNode(getString(literal)));
break;
}
}
@Override
public void enterJsonArray(JsonArrayContext ctx) {
jsonValues.push(new ArrayNode(null));
}
@Override
public void enterJsonObject(JsonObjectContext ctx) {
jsonValues.push(new ObjectNode(null));
}
@Override
public void exitJsonPair(JsonPairContext ctx) {
String name = getString(ctx.name);
JsonNode value = jsonValues.pop();
assert jsonValues.peek() instanceof ObjectNode;
((ObjectNode) jsonValues.element()).set(name, value);
}
private String identifier(IdentifierContext ctx) {
return ctx.word.getText().replace("`", "");
}
private String name(String identifier) {
int dotPos = identifier.lastIndexOf('.');
String name = identifier.substring(dotPos + 1);
return validateName(name, true);
}
private String namespace(String identifier, String namespace) {
int dotPos = identifier.lastIndexOf('.');
String ns = dotPos < 0 ? namespace : identifier.substring(0, dotPos);
if (ns == null) {
return null;
}
for (int s = 0, e = ns.indexOf('.'); e > 0; s = e + 1, e = ns.indexOf('.', s)) {
validateName(ns.substring(s, e), false);
}
return ns;
}
private String validateName(String name, boolean isTypeName) {
if (name == null) {
throw new SchemaParseException("Null name");
} else if (!VALID_NAME.test(name)) {
throw new SchemaParseException("Illegal name: " + name);
}
if (isTypeName && INVALID_TYPE_NAMES.contains(name)) {
throw new SchemaParseException("Illegal name: " + name);
}
return name;
}
private String fullName(String namespace, String typeName) {
int dotPos = typeName.lastIndexOf('.');
if (dotPos > -1) {
return typeName;
}
return namespace != null ? namespace + "." + typeName : typeName;
}
private String getString(Token stringToken) {
String stringLiteral = stringToken.getText();
String betweenQuotes = stringLiteral.substring(1, stringLiteral.length() - 1);
return StringEscapeUtils.unescapeJava(betweenQuotes);
}
}
private static class SchemaProperties {
String contextNamespace;
boolean withNamespace;
String namespace;
boolean withAliases;
List<String> aliases;
boolean withOrder;
Schema.Field.Order order;
Map<String, JsonNode> properties;
public SchemaProperties(String contextNamespace, boolean withNamespace, boolean withAliases, boolean withOrder) {
this.contextNamespace = contextNamespace;
this.withNamespace = withNamespace;
this.withAliases = withAliases;
this.aliases = Collections.emptyList();
this.withOrder = withOrder;
this.order = Schema.Field.Order.ASCENDING;
this.properties = new LinkedHashMap<>();
}
public void addProperty(String name, JsonNode value, Token firstValueToken) {
if (withNamespace && "namespace".equals(name)) {
if (value.isTextual()) {
namespace = value.textValue();
} else {
throw error("@namespace(...) must contain a String value", firstValueToken);
}
} else if (withAliases && "aliases".equals(name)) {
if (value.isArray()) {
List<String> result = new ArrayList<>();
Iterator<JsonNode> elements = value.elements();
elements.forEachRemaining(element -> {
if (element.isTextual()) {
result.add(element.textValue());
} else {
throw error("@aliases(...) must contain an array of String values", firstValueToken);
}
});
aliases = result;
} else {
throw error("@aliases(...) must contain an array of String values", firstValueToken);
}
} else if (withOrder && "order".equals(name)) {
if (value.isTextual()) {
String orderValue = value.textValue().toUpperCase(Locale.ROOT);
switch (orderValue) {
case "ASCENDING":
order = Schema.Field.Order.ASCENDING;
break;
case "DESCENDING":
order = Schema.Field.Order.DESCENDING;
break;
case "IGNORE":
order = Schema.Field.Order.IGNORE;
break;
default:
throw error("@order(...) must contain \"ASCENDING\", \"DESCENDING\" or \"IGNORE\"", firstValueToken);
}
} else {
throw error("@order(...) must contain a String value", firstValueToken);
}
} else {
properties.put(name, value);
}
}
public String namespace() {
return namespace == null ? contextNamespace : namespace;
}
public Schema.Field.Order order() {
return order;
}
public void copyAliases(Consumer<String> addAlias) {
aliases.forEach(addAlias);
}
public <T extends JsonProperties> T copyProperties(T jsonProperties) {
properties.forEach(jsonProperties::addProp);
if (jsonProperties instanceof Schema) {
Schema schema = (Schema) jsonProperties;
LogicalType logicalType = LogicalTypes.fromSchemaIgnoreInvalid(schema);
if (logicalType != null) {
logicalType.addToSchema(schema);
}
}
return jsonProperties;
}
public boolean hasProperties() {
return !properties.isEmpty();
}
}
}
| 6,854 |
0 | Create_ds/avro/lang/java/idl/src/main/java/org/apache/avro | Create_ds/avro/lang/java/idl/src/main/java/org/apache/avro/idl/SchemaVisitorAction.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro.idl;
public enum SchemaVisitorAction {
/**
* continue visit.
*/
CONTINUE,
/**
* terminate visit.
*/
TERMINATE,
/**
* when returned from pre non terminal visit method the children of the non
* terminal are skipped. afterVisitNonTerminal for the current schema will not
* be invoked.
*/
SKIP_SUBTREE,
/**
* Skip visiting the siblings of this schema.
*/
SKIP_SIBLINGS
}
| 6,855 |
0 | Create_ds/avro/lang/java/idl/src/main/java/org/apache/avro | Create_ds/avro/lang/java/idl/src/main/java/org/apache/avro/idl/IsResolvedSchemaVisitor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro.idl;
import org.apache.avro.Schema;
/**
* This visitor checks if the current schema is fully resolved.
*/
public final class IsResolvedSchemaVisitor implements SchemaVisitor<Boolean> {
boolean hasUnresolvedParts;
IsResolvedSchemaVisitor() {
hasUnresolvedParts = false;
}
@Override
public SchemaVisitorAction visitTerminal(Schema terminal) {
hasUnresolvedParts = SchemaResolver.isUnresolvedSchema(terminal);
return hasUnresolvedParts ? SchemaVisitorAction.TERMINATE : SchemaVisitorAction.CONTINUE;
}
@Override
public SchemaVisitorAction visitNonTerminal(Schema nonTerminal) {
hasUnresolvedParts = SchemaResolver.isUnresolvedSchema(nonTerminal);
if (hasUnresolvedParts) {
return SchemaVisitorAction.TERMINATE;
}
if (nonTerminal.getType() == Schema.Type.RECORD && !nonTerminal.hasFields()) {
// We're still initializing the type...
return SchemaVisitorAction.SKIP_SUBTREE;
}
return SchemaVisitorAction.CONTINUE;
}
@Override
public SchemaVisitorAction afterVisitNonTerminal(Schema nonTerminal) {
return SchemaVisitorAction.CONTINUE;
}
@Override
public Boolean get() {
return !hasUnresolvedParts;
}
}
| 6,856 |
0 | Create_ds/avro/lang/java/idl/src/main/java/org/apache/avro | Create_ds/avro/lang/java/idl/src/main/java/org/apache/avro/idl/Schemas.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro.idl;
import org.apache.avro.Schema;
import org.apache.avro.Schema.Field;
import java.util.ArrayDeque;
import java.util.Collections;
import java.util.Deque;
import java.util.IdentityHashMap;
import java.util.function.Supplier;
import java.util.stream.Collectors;
/**
* Avro Schema utilities, to traverse...
*/
public final class Schemas {
private Schemas() {
}
/**
* Depth first visit.
*/
public static <T> T visit(final Schema start, final SchemaVisitor<T> visitor) {
// Set of Visited Schemas
IdentityHashMap<Schema, Schema> visited = new IdentityHashMap<>();
// Stack that contains the Schemas to process and afterVisitNonTerminal
// functions.
// Deque<Either<Schema, Supplier<SchemaVisitorAction>>>
// Using Either<...> has a cost we want to avoid...
Deque<Object> dq = new ArrayDeque<>();
dq.push(start);
Object current;
while ((current = dq.poll()) != null) {
if (current instanceof Supplier) {
// We are executing a non-terminal post visit.
@SuppressWarnings("unchecked")
SchemaVisitorAction action = ((Supplier<SchemaVisitorAction>) current).get();
switch (action) {
case CONTINUE:
break;
case SKIP_SIBLINGS:
while (dq.peek() instanceof Schema) {
dq.remove();
}
break;
case TERMINATE:
return visitor.get();
case SKIP_SUBTREE:
default:
throw new UnsupportedOperationException("Invalid action " + action);
}
} else {
Schema schema = (Schema) current;
boolean terminate;
if (visited.containsKey(schema)) {
terminate = visitTerminal(visitor, schema, dq);
} else {
Schema.Type type = schema.getType();
switch (type) {
case ARRAY:
terminate = visitNonTerminal(visitor, schema, dq, Collections.singleton(schema.getElementType()));
visited.put(schema, schema);
break;
case RECORD:
terminate = visitNonTerminal(visitor, schema, dq, () -> schema.getFields().stream().map(Field::schema)
.collect(Collectors.toCollection(ArrayDeque::new)).descendingIterator());
visited.put(schema, schema);
break;
case UNION:
terminate = visitNonTerminal(visitor, schema, dq, schema.getTypes());
visited.put(schema, schema);
break;
case MAP:
terminate = visitNonTerminal(visitor, schema, dq, Collections.singleton(schema.getValueType()));
visited.put(schema, schema);
break;
default:
terminate = visitTerminal(visitor, schema, dq);
break;
}
}
if (terminate) {
return visitor.get();
}
}
}
return visitor.get();
}
private static boolean visitNonTerminal(final SchemaVisitor<?> visitor, final Schema schema, final Deque<Object> dq,
final Iterable<Schema> itSupp) {
SchemaVisitorAction action = visitor.visitNonTerminal(schema);
switch (action) {
case CONTINUE:
dq.push((Supplier<SchemaVisitorAction>) () -> visitor.afterVisitNonTerminal(schema));
itSupp.forEach(dq::push);
break;
case SKIP_SUBTREE:
dq.push((Supplier<SchemaVisitorAction>) () -> visitor.afterVisitNonTerminal(schema));
break;
case SKIP_SIBLINGS:
while (dq.peek() instanceof Schema) {
dq.remove();
}
break;
case TERMINATE:
return true;
default:
throw new UnsupportedOperationException("Invalid action " + action + " for " + schema);
}
return false;
}
private static boolean visitTerminal(final SchemaVisitor<?> visitor, final Schema schema, final Deque<Object> dq) {
SchemaVisitorAction action = visitor.visitTerminal(schema);
switch (action) {
case CONTINUE:
break;
case SKIP_SIBLINGS:
while (dq.peek() instanceof Schema) {
dq.remove();
}
break;
case TERMINATE:
return true;
case SKIP_SUBTREE:
default:
throw new UnsupportedOperationException("Invalid action " + action + " for " + schema);
}
return false;
}
}
| 6,857 |
0 | Create_ds/avro/lang/java/idl/src/main/java/org/apache/avro | Create_ds/avro/lang/java/idl/src/main/java/org/apache/avro/idl/SchemaResolver.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro.idl;
import org.apache.avro.JsonProperties;
import org.apache.avro.Protocol;
import org.apache.avro.Schema;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* Utility class to resolve schemas that are unavailable at the point they are
* referenced in the IDL.
*/
final class SchemaResolver {
private SchemaResolver() {
}
private static final String UR_SCHEMA_ATTR = "org.apache.avro.idl.unresolved.name";
private static final String UR_SCHEMA_NAME = "UnresolvedSchema";
private static final String UR_SCHEMA_NS = "org.apache.avro.compiler";
private static final AtomicInteger COUNTER = new AtomicInteger();
/**
* Create a schema to represent an "unresolved" schema. (used to represent a
* schema whose definition does not exist, yet).
*
* @param name a schema name
* @return an unresolved schema for the given name
*/
static Schema unresolvedSchema(final String name) {
Schema schema = Schema.createRecord(UR_SCHEMA_NAME + '_' + COUNTER.getAndIncrement(), "unresolved schema",
UR_SCHEMA_NS, false, Collections.emptyList());
schema.addProp(UR_SCHEMA_ATTR, name);
return schema;
}
/**
* Is this an unresolved schema.
*
* @param schema a schema
* @return whether the schema is an unresolved schema
*/
static boolean isUnresolvedSchema(final Schema schema) {
return (schema.getType() == Schema.Type.RECORD && schema.getProp(UR_SCHEMA_ATTR) != null && schema.getName() != null
&& schema.getName().startsWith(UR_SCHEMA_NAME) && UR_SCHEMA_NS.equals(schema.getNamespace()));
}
/**
* Get the unresolved schema name.
*
* @param schema an unresolved schema
* @return the name of the unresolved schema
*/
static String getUnresolvedSchemaName(final Schema schema) {
if (!isUnresolvedSchema(schema)) {
throw new IllegalArgumentException("Not a unresolved schema: " + schema);
}
return schema.getProp(UR_SCHEMA_ATTR);
}
/**
* Is this an unresolved schema?
*/
static boolean isFullyResolvedSchema(final Schema schema) {
if (isUnresolvedSchema(schema)) {
return false;
} else {
return Schemas.visit(schema, new IsResolvedSchemaVisitor());
}
}
/**
* Clone all provided schemas while resolving all unreferenced schemas.
*
* @param idlFile a parsed IDL file
* @return a copy of idlFile with all schemas resolved
*/
static IdlFile resolve(final IdlFile idlFile, String... schemaPropertiesToRemove) {
if (idlFile.getProtocol() != null) {
return new IdlFile(resolve(idlFile.getProtocol(), schemaPropertiesToRemove), idlFile.getWarnings());
}
ResolvingVisitor visitor = new ResolvingVisitor(null, idlFile::getNamedSchema, schemaPropertiesToRemove);
Function<Schema, Schema> resolver = schema -> Schemas.visit(schema, visitor.withRoot(schema));
List<Schema> namedSchemata = idlFile.getNamedSchemas().values().stream().map(resolver).collect(Collectors.toList());
Schema mainSchema = Optional.ofNullable(idlFile.getMainSchema()).map(resolver).orElse(null);
return new IdlFile(idlFile.getNamespace(), mainSchema, namedSchemata, idlFile.getWarnings());
}
/**
* Will clone the provided protocol while resolving all unreferenced schemas
*
* @param protocol a parsed protocol
* @return a copy of the protocol with all schemas resolved
*/
static Protocol resolve(final Protocol protocol, String... schemaPropertiesToRemove) {
// Create an empty copy of the protocol
Protocol result = new Protocol(protocol.getName(), protocol.getDoc(), protocol.getNamespace());
protocol.getObjectProps().forEach(((JsonProperties) result)::addProp);
ResolvingVisitor visitor = new ResolvingVisitor(null, protocol::getType, schemaPropertiesToRemove);
Function<Schema, Schema> resolver = schema -> Schemas.visit(schema, visitor.withRoot(schema));
// Resolve all schemata in the protocol.
result.setTypes(protocol.getTypes().stream().map(resolver).collect(Collectors.toList()));
Map<String, Protocol.Message> resultMessages = result.getMessages();
protocol.getMessages().forEach((name, oldValue) -> {
Protocol.Message newValue;
if (oldValue.isOneWay()) {
newValue = result.createMessage(oldValue.getName(), oldValue.getDoc(), oldValue,
resolver.apply(oldValue.getRequest()));
} else {
Schema request = resolver.apply(oldValue.getRequest());
Schema response = resolver.apply(oldValue.getResponse());
Schema errors = resolver.apply(oldValue.getErrors());
newValue = result.createMessage(oldValue.getName(), oldValue.getDoc(), oldValue, request, response, errors);
}
resultMessages.put(name, newValue);
});
return result;
}
}
| 6,858 |
0 | Create_ds/avro/lang/java/idl/src/main/java/org/apache/avro | Create_ds/avro/lang/java/idl/src/main/java/org/apache/avro/idl/SchemaVisitor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro.idl;
import org.apache.avro.Schema;
public interface SchemaVisitor<T> {
/**
* Invoked for schemas that do not have "child" schemas (like string, int …) or
* for a previously encountered schema with children, which will be treated as a
* terminal. (to avoid circular recursion)
*/
SchemaVisitorAction visitTerminal(Schema terminal);
/**
* Invoked for schema with children before proceeding to visit the children.
*/
SchemaVisitorAction visitNonTerminal(Schema nonTerminal);
/**
* Invoked for schemas with children after its children have been visited.
*/
SchemaVisitorAction afterVisitNonTerminal(Schema nonTerminal);
/**
* Invoked when visiting is complete.
*
* @return a value that will be returned by the visit method.
*/
T get();
}
| 6,859 |
0 | Create_ds/avro/lang/java/ipc-netty/src/test/java/org/apache/avro/ipc | Create_ds/avro/lang/java/ipc-netty/src/test/java/org/apache/avro/ipc/netty/TestNettyServerWithCallbacks.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro.ipc.netty;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.avro.AvroRuntimeException;
import org.apache.avro.ipc.CallFuture;
import org.apache.avro.ipc.Callback;
import org.apache.avro.ipc.Responder;
import org.apache.avro.ipc.Server;
import org.apache.avro.ipc.Transceiver;
import org.apache.avro.ipc.specific.SpecificRequestor;
import org.apache.avro.ipc.specific.SpecificResponder;
import org.apache.avro.test.Simple;
import org.apache.avro.test.TestError;
import org.apache.avro.test.TestRecord;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
/**
* Tests asynchronous RPCs with Netty.
*/
public class TestNettyServerWithCallbacks {
private static Server server;
private static Transceiver transceiver;
private static Simple.Callback simpleClient;
private static final AtomicBoolean ackFlag = new AtomicBoolean(false);
private static final AtomicReference<CountDownLatch> ackLatch = new AtomicReference<>(new CountDownLatch(1));
private static Simple simpleService = new SimpleImpl(ackFlag);
@BeforeAll
public static void initializeConnections() throws Exception {
// start server
Responder responder = new SpecificResponder(Simple.class, simpleService);
server = new NettyServer(responder, new InetSocketAddress(0));
server.start();
int serverPort = server.getPort();
System.out.println("server port : " + serverPort);
transceiver = new NettyTransceiver(new InetSocketAddress(serverPort), TestNettyServer.CONNECT_TIMEOUT_MILLIS);
simpleClient = SpecificRequestor.getClient(Simple.Callback.class, transceiver);
}
@AfterAll
public static void tearDownConnections() throws Exception {
if (transceiver != null) {
transceiver.close();
}
if (server != null) {
server.close();
}
}
@Test
void greeting() throws Exception {
// Test synchronous RPC:
assertEquals("Hello, how are you?", simpleClient.hello("how are you?"));
// Test asynchronous RPC (future):
CallFuture<String> future1 = new CallFuture<>();
simpleClient.hello("World!", future1);
assertEquals("Hello, World!", future1.get(2, TimeUnit.SECONDS));
assertNull(future1.getError());
// Test asynchronous RPC (callback):
final CallFuture<String> future2 = new CallFuture<>();
simpleClient.hello("what's up?", new Callback<String>() {
@Override
public void handleResult(String result) {
future2.handleResult(result);
}
@Override
public void handleError(Throwable error) {
future2.handleError(error);
}
});
assertEquals("Hello, what's up?", future2.get(2, TimeUnit.SECONDS));
assertNull(future2.getError());
}
@Test
void echo() throws Exception {
TestRecord record = TestRecord.newBuilder()
.setHash(new org.apache.avro.test.MD5(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8 }))
.setKind(org.apache.avro.test.Kind.FOO).setName("My Record").build();
// Test synchronous RPC:
assertEquals(record, simpleClient.echo(record));
// Test asynchronous RPC (future):
CallFuture<TestRecord> future1 = new CallFuture<>();
simpleClient.echo(record, future1);
assertEquals(record, future1.get(2, TimeUnit.SECONDS));
assertNull(future1.getError());
// Test asynchronous RPC (callback):
final CallFuture<TestRecord> future2 = new CallFuture<>();
simpleClient.echo(record, new Callback<TestRecord>() {
@Override
public void handleResult(TestRecord result) {
future2.handleResult(result);
}
@Override
public void handleError(Throwable error) {
future2.handleError(error);
}
});
assertEquals(record, future2.get(2, TimeUnit.SECONDS));
assertNull(future2.getError());
}
@Test
void add() throws Exception {
// Test synchronous RPC:
assertEquals(8, simpleClient.add(2, 6));
// Test asynchronous RPC (future):
CallFuture<Integer> future1 = new CallFuture<>();
simpleClient.add(8, 8, future1);
assertEquals(Integer.valueOf(16), future1.get(2, TimeUnit.SECONDS));
assertNull(future1.getError());
// Test asynchronous RPC (callback):
final CallFuture<Integer> future2 = new CallFuture<>();
simpleClient.add(512, 256, new Callback<Integer>() {
@Override
public void handleResult(Integer result) {
future2.handleResult(result);
}
@Override
public void handleError(Throwable error) {
future2.handleError(error);
}
});
assertEquals(Integer.valueOf(768), future2.get(2, TimeUnit.SECONDS));
assertNull(future2.getError());
}
@Test
void echoBytes() throws Exception {
ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 });
// Test synchronous RPC:
assertEquals(byteBuffer, simpleClient.echoBytes(byteBuffer));
// Test asynchronous RPC (future):
CallFuture<ByteBuffer> future1 = new CallFuture<>();
simpleClient.echoBytes(byteBuffer, future1);
assertEquals(byteBuffer, future1.get(2, TimeUnit.SECONDS));
assertNull(future1.getError());
// Test asynchronous RPC (callback):
final CallFuture<ByteBuffer> future2 = new CallFuture<>();
simpleClient.echoBytes(byteBuffer, new Callback<ByteBuffer>() {
@Override
public void handleResult(ByteBuffer result) {
future2.handleResult(result);
}
@Override
public void handleError(Throwable error) {
future2.handleError(error);
}
});
assertEquals(byteBuffer, future2.get(2, TimeUnit.SECONDS));
assertNull(future2.getError());
}
@Test
void error() throws IOException, InterruptedException, TimeoutException {
// Test synchronous RPC:
try {
simpleClient.error();
fail("Expected " + TestError.class.getCanonicalName());
} catch (TestError e) {
// Expected
}
// Test asynchronous RPC (future):
CallFuture<Void> future = new CallFuture<>();
simpleClient.error(future);
try {
future.get(2, TimeUnit.SECONDS);
fail("Expected " + TestError.class.getCanonicalName() + " to be thrown");
} catch (ExecutionException e) {
assertTrue(e.getCause() instanceof TestError, "Expected " + TestError.class.getCanonicalName());
}
assertNotNull(future.getError());
assertTrue(future.getError() instanceof TestError, "Expected " + TestError.class.getCanonicalName());
assertNull(future.getResult());
// Test asynchronous RPC (callback):
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<Throwable> errorRef = new AtomicReference<>();
simpleClient.error(new Callback<Void>() {
@Override
public void handleResult(Void result) {
fail("Expected " + TestError.class.getCanonicalName());
}
@Override
public void handleError(Throwable error) {
errorRef.set(error);
latch.countDown();
}
});
assertTrue(latch.await(2, TimeUnit.SECONDS), "Timed out waiting for error");
assertNotNull(errorRef.get());
assertTrue(errorRef.get() instanceof TestError);
}
@Test
void ack() throws Exception {
simpleClient.ack();
ackLatch.get().await(2, TimeUnit.SECONDS);
assertTrue(ackFlag.get(), "Expected ack flag to be set");
ackLatch.set(new CountDownLatch(1));
simpleClient.ack();
ackLatch.get().await(2, TimeUnit.SECONDS);
assertFalse(ackFlag.get(), "Expected ack flag to be cleared");
}
@Test
void sendAfterChannelClose() throws Exception {
// Start up a second server so that closing the server doesn't
// interfere with the other unit tests:
Server server2 = new NettyServer(new SpecificResponder(Simple.class, simpleService), new InetSocketAddress(0));
server2.start();
try {
int serverPort = server2.getPort();
System.out.println("server2 port : " + serverPort);
try (Transceiver transceiver2 = new NettyTransceiver(new InetSocketAddress(serverPort),
TestNettyServer.CONNECT_TIMEOUT_MILLIS)) {
Simple.Callback simpleClient2 = SpecificRequestor.getClient(Simple.Callback.class, transceiver2);
// Verify that connection works:
assertEquals(3, simpleClient2.add(1, 2));
// Try again with callbacks:
CallFuture<Integer> addFuture = new CallFuture<>();
simpleClient2.add(1, 2, addFuture);
assertEquals(Integer.valueOf(3), addFuture.get());
// Shut down server:
server2.close();
Thread.sleep(1000L);
// Send a new RPC, and verify that it throws an Exception that
// can be detected by the client:
boolean ioeCaught = false;
try {
simpleClient2.add(1, 2);
fail("Send after server close should have thrown Exception");
} catch (AvroRuntimeException e) {
ioeCaught = e.getCause() instanceof IOException;
assertTrue(ioeCaught, "Expected IOException");
} catch (Exception e) {
e.printStackTrace();
throw e;
}
assertTrue(ioeCaught, "Expected IOException");
// Send a new RPC with callback, and verify that the correct Exception
// is thrown:
ioeCaught = false;
try {
addFuture = new CallFuture<>();
simpleClient2.add(1, 2, addFuture);
addFuture.get();
fail("Send after server close should have thrown Exception");
} catch (IOException e) {
ioeCaught = true;
} catch (Exception e) {
e.printStackTrace();
throw e;
}
assertTrue(ioeCaught, "Expected IOException");
}
} finally {
server2.close();
}
}
@Test
void cancelPendingRequestsOnTransceiverClose() throws Exception {
// Start up a second server so that closing the server doesn't
// interfere with the other unit tests:
BlockingSimpleImpl blockingSimpleImpl = new BlockingSimpleImpl();
Server server2 = new NettyServer(new SpecificResponder(Simple.class, blockingSimpleImpl), new InetSocketAddress(0));
server2.start();
try {
int serverPort = server2.getPort();
System.out.println("server2 port : " + serverPort);
CallFuture<Integer> addFuture = new CallFuture<>();
try (Transceiver transceiver2 = new NettyTransceiver(new InetSocketAddress(serverPort),
TestNettyServer.CONNECT_TIMEOUT_MILLIS)) {
Simple.Callback simpleClient2 = SpecificRequestor.getClient(Simple.Callback.class, transceiver2);
// The first call has to block for the handshake:
assertEquals(3, simpleClient2.add(1, 2));
// Now acquire the semaphore so that the server will block:
blockingSimpleImpl.acquireRunPermit();
simpleClient2.add(1, 2, addFuture);
}
// When the transceiver is closed, the CallFuture should get
// an IOException
boolean ioeThrown = false;
try {
addFuture.get();
} catch (ExecutionException e) {
ioeThrown = e.getCause() instanceof IOException;
assertTrue(e.getCause() instanceof IOException);
} catch (Exception e) {
e.printStackTrace();
fail("Unexpected Exception: " + e.toString());
}
assertTrue(ioeThrown, "Expected IOException to be thrown");
} finally {
blockingSimpleImpl.releaseRunPermit();
server2.close();
}
}
@Test
@Timeout(20000)
void cancelPendingRequestsAfterChannelCloseByServerShutdown() throws Throwable {
// The purpose of this test is to verify that a client doesn't stay
// blocked when a server is unexpectedly killed (or when for some
// other reason the channel is suddenly closed) while the server
// was in the process of handling a request (thus after it received
// the request, and before it returned the response).
// Start up a second server so that closing the server doesn't
// interfere with the other unit tests:
BlockingSimpleImpl blockingSimpleImpl = new BlockingSimpleImpl();
final Server server2 = new NettyServer(new SpecificResponder(Simple.class, blockingSimpleImpl),
new InetSocketAddress(0));
server2.start();
Transceiver transceiver2 = null;
try {
int serverPort = server2.getPort();
System.out.println("server2 port : " + serverPort);
transceiver2 = new NettyTransceiver(new InetSocketAddress(serverPort), TestNettyServer.CONNECT_TIMEOUT_MILLIS);
final Simple.Callback simpleClient2 = SpecificRequestor.getClient(Simple.Callback.class, transceiver2);
// Acquire the method-enter permit, which will be released by the
// server method once we call it
blockingSimpleImpl.acquireEnterPermit();
// Acquire the run permit, to avoid that the server method returns immediately
blockingSimpleImpl.acquireRunPermit();
// Start client call
Future<?> clientFuture = Executors.newSingleThreadExecutor().submit(() -> {
try {
simpleClient2.add(3, 4);
fail("Expected an exception");
} catch (Exception e) {
e.printStackTrace();
// expected
}
});
// Wait until method is entered on the server side
blockingSimpleImpl.acquireEnterPermit();
// The server side method is now blocked waiting on the run permit
// (= is busy handling the request)
// Stop the server in a separate thread as it blocks the actual thread until the
// server side
// method is running
new Thread(server2::close).start();
// With the server gone, we expect the client to get some exception and exit
// Wait for the client call to exit
try {
clientFuture.get(10, TimeUnit.SECONDS);
} catch (ExecutionException e) {
throw e.getCause();
} catch (TimeoutException e) {
fail("Client request should not be blocked on server shutdown");
}
} finally {
blockingSimpleImpl.releaseRunPermit();
server2.close();
if (transceiver2 != null)
transceiver2.close();
}
}
@Test
void clientReconnectAfterServerRestart() throws Exception {
// Start up a second server so that closing the server doesn't
// interfere with the other unit tests:
SimpleImpl simpleImpl = new BlockingSimpleImpl();
Server server2 = new NettyServer(new SpecificResponder(Simple.class, simpleImpl), new InetSocketAddress(0));
try {
server2.start();
int serverPort = server2.getPort();
System.out.println("server2 port : " + serverPort);
// Initialize a client, and establish a connection to the server:
Transceiver transceiver2 = new NettyTransceiver(new InetSocketAddress(serverPort),
TestNettyServer.CONNECT_TIMEOUT_MILLIS);
Simple.Callback simpleClient2 = SpecificRequestor.getClient(Simple.Callback.class, transceiver2);
assertEquals(3, simpleClient2.add(1, 2));
// Restart the server:
server2.close();
try {
simpleClient2.add(2, -1);
fail("Client should not be able to invoke RPCs " + "because server is no longer running");
} catch (Exception e) {
// Expected since server is no longer running
}
Thread.sleep(2000L);
server2 = new NettyServer(new SpecificResponder(Simple.class, simpleImpl), new InetSocketAddress(serverPort));
server2.start();
// Invoke an RPC using the same client, which should reestablish the
// connection to the server:
assertEquals(3, simpleClient2.add(1, 2));
} finally {
server2.close();
}
}
@Disabled
@Test
void performanceTest() throws Exception {
final int threadCount = 8;
final long runTimeMillis = 10 * 1000L;
ExecutorService threadPool = Executors.newFixedThreadPool(threadCount);
System.out.println("Running performance test for " + runTimeMillis + "ms...");
final AtomicLong rpcCount = new AtomicLong(0L);
final AtomicBoolean runFlag = new AtomicBoolean(true);
final CountDownLatch startLatch = new CountDownLatch(threadCount);
for (int ii = 0; ii < threadCount; ii++) {
threadPool.submit(() -> {
try {
startLatch.countDown();
startLatch.await(2, TimeUnit.SECONDS);
while (runFlag.get()) {
rpcCount.incrementAndGet();
assertEquals("Hello, World!", simpleClient.hello("World!"));
}
} catch (Exception e) {
e.printStackTrace();
}
});
}
startLatch.await(2, TimeUnit.SECONDS);
Thread.sleep(runTimeMillis);
runFlag.set(false);
threadPool.shutdown();
assertTrue(threadPool.awaitTermination(2, TimeUnit.SECONDS), "Timed out shutting down thread pool");
System.out.println("Completed " + rpcCount.get() + " RPCs in " + runTimeMillis + "ms => "
+ (((double) rpcCount.get() / (double) runTimeMillis) * 1000) + " RPCs/sec, "
+ ((double) runTimeMillis / (double) rpcCount.get()) + " ms/RPC.");
}
/**
* Implementation of the Simple interface.
*/
private static class SimpleImpl implements Simple {
private final AtomicBoolean ackFlag;
/**
* Creates a SimpleImpl.
*
* @param ackFlag the AtomicBoolean to toggle when ack() is called.
*/
public SimpleImpl(final AtomicBoolean ackFlag) {
this.ackFlag = ackFlag;
}
@Override
public String hello(String greeting) {
return "Hello, " + greeting;
}
@Override
public TestRecord echo(TestRecord record) {
return record;
}
@Override
public int add(int arg1, int arg2) {
return arg1 + arg2;
}
@Override
public ByteBuffer echoBytes(ByteBuffer data) {
return data;
}
@Override
public void error() throws TestError {
throw TestError.newBuilder().setMessage$("Test Message").build();
}
@Override
synchronized public void ack() {
ackFlag.set(!ackFlag.get());
ackLatch.get().countDown();
}
}
/**
* A SimpleImpl that requires a semaphore permit before executing any method.
*/
private static class BlockingSimpleImpl extends SimpleImpl {
/** Semaphore that is released when the method is entered. */
private final Semaphore enterSemaphore = new Semaphore(1);
/** Semaphore that must be acquired for the method to run and exit. */
private final Semaphore runSemaphore = new Semaphore(1);
/**
* Creates a BlockingSimpleImpl.
*/
public BlockingSimpleImpl() {
super(new AtomicBoolean());
}
@Override
public String hello(String greeting) {
releaseEnterPermit();
acquireRunPermit();
try {
return super.hello(greeting);
} finally {
releaseRunPermit();
}
}
@Override
public TestRecord echo(TestRecord record) {
releaseEnterPermit();
acquireRunPermit();
try {
return super.echo(record);
} finally {
releaseRunPermit();
}
}
@Override
public int add(int arg1, int arg2) {
releaseEnterPermit();
acquireRunPermit();
try {
return super.add(arg1, arg2);
} finally {
releaseRunPermit();
}
}
@Override
public ByteBuffer echoBytes(ByteBuffer data) {
releaseEnterPermit();
acquireRunPermit();
try {
return super.echoBytes(data);
} finally {
releaseRunPermit();
}
}
@Override
public void error() throws TestError {
releaseEnterPermit();
acquireRunPermit();
try {
super.error();
} finally {
releaseRunPermit();
}
}
@Override
public void ack() {
releaseEnterPermit();
acquireRunPermit();
try {
super.ack();
} finally {
releaseRunPermit();
}
}
/**
* Acquires a single permit from the semaphore.
*/
public void acquireRunPermit() {
try {
runSemaphore.acquire();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
/**
* Releases a single permit to the semaphore.
*/
public void releaseRunPermit() {
runSemaphore.release();
}
/**
* Acquires a single permit from the semaphore.
*/
public void acquireEnterPermit() {
try {
enterSemaphore.acquire();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
/**
* Releases a single permit to the semaphore.
*/
public void releaseEnterPermit() {
enterSemaphore.release();
}
}
}
| 6,860 |
0 | Create_ds/avro/lang/java/ipc-netty/src/test/java/org/apache/avro/ipc | Create_ds/avro/lang/java/ipc-netty/src/test/java/org/apache/avro/ipc/netty/TestNettyTransceiverWhenFailsToConnect.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro.ipc.netty;
import org.apache.avro.ipc.Transceiver;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import io.netty.channel.socket.SocketChannel;
/**
* This is a very specific test that verifies that if the NettyTransceiver fails
* to connect it cleans up the netty channel that it has created.
*/
public class TestNettyTransceiverWhenFailsToConnect {
SocketChannel channel = null;
@Test
void nettyTransceiverReleasesNettyChannelOnFailingToConnect() throws Exception {
assertThrows(IOException.class, () -> {
try (ServerSocket serverSocket = new ServerSocket(0)) {
try (Transceiver t = new NettyTransceiver(new InetSocketAddress(serverSocket.getLocalPort()), 0, c -> {
channel = c;
})) {
fail("should have thrown an exception");
}
} finally {
assertTrue(channel == null || channel.isShutdown(), "Channel not shut down");
}
});
}
}
| 6,861 |
0 | Create_ds/avro/lang/java/ipc-netty/src/test/java/org/apache/avro/ipc | Create_ds/avro/lang/java/ipc-netty/src/test/java/org/apache/avro/ipc/netty/TestNettyTransceiverWhenServerStops.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro.ipc.netty;
import org.apache.avro.ipc.Responder;
import org.apache.avro.ipc.specific.SpecificRequestor;
import org.apache.avro.ipc.specific.SpecificResponder;
import org.apache.avro.test.Mail;
import org.apache.avro.test.Message;
import java.net.InetSocketAddress;
import static org.junit.jupiter.api.Assertions.fail;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
public class TestNettyTransceiverWhenServerStops {
// @Test // disable flakey test!
public void testNettyTransceiverWhenServerStops() throws Exception {
Mail mailService = new TestNettyServer.MailImpl();
Responder responder = new SpecificResponder(Mail.class, mailService);
NettyServer server = new NettyServer(responder, new InetSocketAddress(0));
server.start();
int serverPort = server.getPort();
final NettyTransceiver transceiver = new NettyTransceiver(new InetSocketAddress(serverPort), 60000);
final Mail mail = SpecificRequestor.getClient(Mail.class, transceiver);
final AtomicInteger successes = new AtomicInteger();
final AtomicInteger failures = new AtomicInteger();
final AtomicBoolean quitOnFailure = new AtomicBoolean();
List<Thread> threads = new ArrayList<>();
// Start a bunch of client threads that use the transceiver to send messages
for (int i = 0; i < 100; i++) {
Thread thread = new Thread(() -> {
while (true) {
try {
mail.send(createMessage());
successes.incrementAndGet();
} catch (Exception e) {
failures.incrementAndGet();
if (quitOnFailure.get()) {
return;
}
}
}
});
threads.add(thread);
thread.start();
}
// Be sure the threads are running: wait until we get a good deal of successes
while (successes.get() < 10000) {
Thread.sleep(50);
}
// Now stop the server
server.close();
// Server is stopped: successes should not increase anymore: wait until we're in
// that situation
while (true) {
int previousSuccesses = successes.get();
Thread.sleep(500);
if (previousSuccesses == successes.get()) {
break;
}
}
// Start the server again
server.start();
// This part of the test is not solved by the current patch: it shows that when
// you stop/start
// a server, the client requests don't continue immediately but will stay
// blocked until the timeout
// passed to the NettyTransceiver has passed (IIUC)
long now = System.currentTimeMillis();
/*
* System.out.println("Waiting on requests to continue"); int previousSuccesses
* = successes.get(); while (true) { Thread.sleep(500); if (successes.get() >
* previousSuccesses) { break; } if (System.currentTimeMillis() - now > 5000) {
* System.out.println("FYI: requests don't continue immediately..."); break; } }
*/
// Stop our client, we would expect this to go on immediately
System.out.println("Stopping transceiver");
quitOnFailure.set(true);
now = System.currentTimeMillis();
transceiver.close(); // Without the patch, this close seems to hang forever
// Wait for all threads to quit
for (Thread thread : threads) {
thread.join();
}
if (System.currentTimeMillis() - now > 10000) {
fail("Stopping NettyTransceiver and waiting for client threads to quit took too long.");
} else {
System.out.println("Stopping NettyTransceiver and waiting for client threads to quit took "
+ (System.currentTimeMillis() - now) + " ms");
}
}
private Message createMessage() {
Message msg = Message.newBuilder().setTo("wife").setFrom("husband").setBody("I love you!").build();
return msg;
}
}
| 6,862 |
0 | Create_ds/avro/lang/java/ipc-netty/src/test/java/org/apache/avro/ipc | Create_ds/avro/lang/java/ipc-netty/src/test/java/org/apache/avro/ipc/netty/TestNettyServerWithCompression.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro.ipc.netty;
import java.io.IOException;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Disabled;
import io.netty.handler.codec.compression.JdkZlibDecoder;
import io.netty.handler.codec.compression.JdkZlibEncoder;
public class TestNettyServerWithCompression extends TestNettyServer {
@BeforeAll
public static void initializeConnections() throws Exception {
initializeConnections(ch -> {
ch.pipeline().addFirst("deflater", new JdkZlibEncoder(6));
ch.pipeline().addFirst("inflater", new JdkZlibDecoder());
});
}
@Disabled
@Override
public void badRequest() throws IOException {
// this tests in the base class needs to be skipped
// as the decompression/compression algorithms will write the gzip header out
// prior to the stream closing so the stream is not completely empty
}
}
| 6,863 |
0 | Create_ds/avro/lang/java/ipc-netty/src/test/java/org/apache/avro/ipc | Create_ds/avro/lang/java/ipc-netty/src/test/java/org/apache/avro/ipc/netty/TestProtocolNetty.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro.ipc.netty;
import java.net.InetSocketAddress;
import org.apache.avro.TestProtocolSpecific;
import org.apache.avro.ipc.Responder;
import org.apache.avro.ipc.Server;
import org.apache.avro.ipc.Transceiver;
/**
* Protocol test with Netty server and transceiver
*/
public class TestProtocolNetty extends TestProtocolSpecific {
@Override
public Server createServer(Responder testResponder) throws Exception {
return new NettyServer(responder, new InetSocketAddress(0));
}
@Override
public Transceiver createTransceiver() throws Exception {
return new NettyTransceiver(new InetSocketAddress(server.getPort()), 2000);
}
@Override
protected int getExpectedHandshakeCount() {
return REPEATING;
}
}
| 6,864 |
0 | Create_ds/avro/lang/java/ipc-netty/src/test/java/org/apache/avro/ipc | Create_ds/avro/lang/java/ipc-netty/src/test/java/org/apache/avro/ipc/netty/TestNettyServerConcurrentExecution.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro.ipc.netty;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.util.concurrent.CountDownLatch;
import org.apache.avro.ipc.Server;
import org.apache.avro.ipc.Transceiver;
import org.apache.avro.ipc.specific.SpecificRequestor;
import org.apache.avro.ipc.specific.SpecificResponder;
import org.apache.avro.test.Simple;
import org.apache.avro.test.TestError;
import org.apache.avro.test.TestRecord;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Verifies that RPCs executed by different client threads using the same
* NettyTransceiver will execute concurrently. The test follows these steps: 1.
* Execute the {@link #org.apache.avro.test.Simple.add(int, int)} RPC to
* complete the Avro IPC handshake. 2a. In a background thread, wait for the
* waitLatch. 3a. In the main thread, invoke
* {@link #org.apache.avro.test.Simple.hello(String)} with the argument "wait".
* This causes the ClientImpl running on the server to count down the wait
* latch, which will unblock the background thread and allow it to proceed.
* After counting down the latch, this call blocks, waiting for
* {@link #org.apache.avro.test.Simple.ack()} to be invoked. 2b. The background
* thread wakes up because the waitLatch has been counted down. Now we know that
* some thread is executing inside hello(String). Next, execute
* {@link #org.apache.avro.test.Simple.ack()} in the background thread, which
* will allow the thread executing hello(String) to return. 3b. The thread
* executing hello(String) on the server unblocks (since ack() has been called),
* allowing hello(String) to return. 4. If control returns to the main thread,
* we know that two RPCs (hello(String) and ack()) were executing concurrently.
*/
public class TestNettyServerConcurrentExecution {
private Server server;
private Transceiver transceiver;
@AfterEach
public void cleanUpAfter() throws Exception {
try {
if (transceiver != null) {
transceiver.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (server != null) {
server.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
@Timeout(30000)
void test() throws Exception {
final CountDownLatch waitLatch = new CountDownLatch(1);
server = new NettyServer(new SpecificResponder(Simple.class, new SimpleImpl(waitLatch)), new InetSocketAddress(0));
server.start();
transceiver = new NettyTransceiver(new InetSocketAddress(server.getPort()), TestNettyServer.CONNECT_TIMEOUT_MILLIS);
// 1. Create the RPC proxy, and establish the handshake:
final Simple.Callback simpleClient = SpecificRequestor.getClient(Simple.Callback.class, transceiver);
SpecificRequestor.getRemote(simpleClient); // force handshake
/*
* 2a. In a background thread, wait for the Client.hello("wait") call to be
* received by the server, then: 2b. Execute the Client.ack() RPC, which will
* unblock the Client.hello("wait") call, allowing it to return to the main
* thread.
*/
new Thread() {
@Override
public void run() {
setName(TestNettyServerConcurrentExecution.class.getSimpleName() + "Ack Thread");
try {
// Step 2a:
waitLatch.await();
// Step 2b:
simpleClient.ack();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
/*
* 3. Execute the Client.hello("wait") RPC, which will block until the
* Client.ack() call has completed in the background thread.
*/
String response = simpleClient.hello("wait");
// 4. If control reaches here, both RPCs have executed concurrently
assertEquals("wait", response);
Thread.sleep(2000);
}
/**
* Implementation of the Simple interface for use with this unit test. If
* {@link #hello(String)} is called with "wait" as its argument,
* {@link #waitLatch} will be counted down, and {@link #hello(String)} will
* block until {@link #ack()} has been invoked.
*/
private static class SimpleImpl implements Simple {
private final CountDownLatch waitLatch;
private final CountDownLatch ackLatch = new CountDownLatch(1);
/**
* Creates a SimpleImpl that uses the given CountDownLatch.
*
* @param waitLatch the CountDownLatch to use in {@link #hello(String)}.
*/
public SimpleImpl(final CountDownLatch waitLatch) {
this.waitLatch = waitLatch;
}
@Override
public int add(int arg1, int arg2) {
// Step 1:
System.out.println("Adding " + arg1 + "+" + arg2);
return arg1 + arg2;
}
@Override
public String hello(String greeting) {
if (greeting.equals("wait")) {
try {
// Step 3a:
waitLatch.countDown();
// Step 3b:
ackLatch.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return e.toString();
}
}
return greeting;
}
@Override
public void ack() {
// Step 2b:
ackLatch.countDown();
}
// All RPCs below this line are irrelevant to this test:
@Override
public TestRecord echo(TestRecord record) {
return record;
}
@Override
public ByteBuffer echoBytes(ByteBuffer data) {
return data;
}
@Override
public void error() throws TestError {
throw new TestError("TestError");
}
}
}
| 6,865 |
0 | Create_ds/avro/lang/java/ipc-netty/src/test/java/org/apache/avro/ipc | Create_ds/avro/lang/java/ipc-netty/src/test/java/org/apache/avro/ipc/netty/TestNettyServerWithSSL.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro.ipc.netty;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.security.KeyStore;
import java.security.Security;
import java.security.cert.X509Certificate;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import io.netty.handler.ssl.SslHandler;
import org.junit.jupiter.api.BeforeAll;
public class TestNettyServerWithSSL extends TestNettyServer {
private static final String TEST_CERTIFICATE = "servercert.p12";
private static final String TEST_CERTIFICATE_FILEPASS = "serverpass.txt";
@BeforeAll
public static void initializeConnections() throws Exception {
initializeConnections(ch -> {
SSLEngine sslEngine = createServerSSLContext().createSSLEngine();
sslEngine.setUseClientMode(false);
SslHandler handler = new SslHandler(sslEngine, false);
ch.pipeline().addLast("SSL", handler);
}, ch -> {
try {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[] { new BogusTrustManager() }, null);
SSLEngine sslEngine = sslContext.createSSLEngine();
sslEngine.setUseClientMode(true);
SslHandler handler = new SslHandler(sslEngine, false);
ch.pipeline().addLast("SSL", handler);
} catch (Exception e) {
e.printStackTrace();
}
});
}
/**
* Bogus trust manager accepting any certificate
*/
private static class BogusTrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] certs, String s) {
// nothing
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String s) {
// nothing
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
private static SSLContext createServerSSLContext() {
try {
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(TestNettyServer.class.getResource(TEST_CERTIFICATE).openStream(), getPass());
// Set up key manager factory to use our key store
KeyManagerFactory kmf = KeyManagerFactory.getInstance(getAlgorithm());
kmf.init(ks, getPass());
SSLContext serverContext = SSLContext.getInstance("TLS");
serverContext.init(kmf.getKeyManagers(), null, null);
return serverContext;
} catch (Exception e) {
throw new Error("Failed to initialize the server-side SSLContext", e);
}
}
private static char[] getPass() {
final File passFile = new File(TestNettyServer.class.getResource(TEST_CERTIFICATE_FILEPASS).getPath());
try {
final String pass = Files.readAllLines(passFile.toPath()).get(0);
return pass.toCharArray();
} catch (IOException e) {
throw new Error("Failed to open pass file", e);
}
}
private static String getAlgorithm() {
String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
if (algorithm == null) {
algorithm = "SunX509";
}
return algorithm;
}
}
| 6,866 |
0 | Create_ds/avro/lang/java/ipc-netty/src/test/java/org/apache/avro/ipc | Create_ds/avro/lang/java/ipc-netty/src/test/java/org/apache/avro/ipc/netty/TestNettyServer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro.ipc.netty;
import java.io.IOException;
import java.io.OutputStream;
import io.netty.channel.socket.SocketChannel;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import org.apache.avro.ipc.Responder;
import org.apache.avro.ipc.Server;
import org.apache.avro.ipc.Transceiver;
import org.apache.avro.ipc.specific.SpecificRequestor;
import org.apache.avro.ipc.specific.SpecificResponder;
import org.apache.avro.test.Mail;
import org.apache.avro.test.Message;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class TestNettyServer {
private static final Logger LOG = LoggerFactory.getLogger(TestNettyServer.class.getName());
static final int CONNECT_TIMEOUT_MILLIS = 2000; // 2 sec
protected static Server server;
protected static Transceiver transceiver;
protected static Mail proxy;
protected static MailImpl mailService;
protected static Consumer<SocketChannel> channelInitializer;
public static class MailImpl implements Mail {
private CountDownLatch allMessages = new CountDownLatch(5);
// in this simple example just return details of the message
public String send(Message message) {
return "Sent message to [" + message.getTo() + "] from [" + message.getFrom() + "] with body ["
+ message.getBody() + "]";
}
public void fireandforget(Message message) {
allMessages.countDown();
}
private void awaitMessages() throws InterruptedException {
allMessages.await(2, TimeUnit.SECONDS);
}
private void assertAllMessagesReceived() {
assertEquals(0, allMessages.getCount());
}
public void reset() {
allMessages = new CountDownLatch(5);
}
}
public static void initializeConnections(Consumer<SocketChannel> initializer) throws Exception {
initializeConnections(initializer, initializer);
}
public static void initializeConnections(Consumer<SocketChannel> serverInitializer,
Consumer<SocketChannel> transceiverInitializer) throws Exception {
LOG.info("starting server...");
channelInitializer = transceiverInitializer;
mailService = new MailImpl();
Responder responder = new SpecificResponder(Mail.class, mailService);
server = new NettyServer(responder, new InetSocketAddress(0), serverInitializer);
server.start();
int serverPort = server.getPort();
LOG.info("server port : {}", serverPort);
transceiver = new NettyTransceiver(new InetSocketAddress(serverPort), CONNECT_TIMEOUT_MILLIS,
transceiverInitializer, null);
proxy = SpecificRequestor.getClient(Mail.class, transceiver);
}
@BeforeAll
public static void initializeConnections() throws Exception {
initializeConnections(null);
}
@AfterAll
public static void tearDownConnections() throws Exception {
transceiver.close();
server.close();
}
@Test
void requestResponse() throws Exception {
for (int x = 0; x < 5; x++) {
verifyResponse(proxy.send(createMessage()));
}
}
private void verifyResponse(String result) {
assertEquals("Sent message to [wife] from [husband] with body [I love you!]", result);
}
@Test
void oneway() throws Exception {
for (int x = 0; x < 5; x++) {
proxy.fireandforget(createMessage());
}
mailService.awaitMessages();
mailService.assertAllMessagesReceived();
}
@Test
void mixtureOfRequests() throws Exception {
mailService.reset();
for (int x = 0; x < 5; x++) {
Message createMessage = createMessage();
proxy.fireandforget(createMessage);
verifyResponse(proxy.send(createMessage));
}
mailService.awaitMessages();
mailService.assertAllMessagesReceived();
}
@Test
void connectionsCount() throws Exception {
// It happens on a regular basis that the server still has a connection
// that is in the process of being terminated (previous test?).
// We wait for that to happen because otherwise this test will fail.
assertNumberOfConnectionsOnServer(1, 1000);
Transceiver transceiver2 = new NettyTransceiver(new InetSocketAddress(server.getPort()), CONNECT_TIMEOUT_MILLIS,
channelInitializer);
Mail proxy2 = SpecificRequestor.getClient(Mail.class, transceiver2);
proxy.fireandforget(createMessage());
proxy2.fireandforget(createMessage());
assertNumberOfConnectionsOnServer(2, 0);
transceiver2.close();
// Check the active connections with some retries as closing at the client
// side might not take effect on the server side immediately
assertNumberOfConnectionsOnServer(1, 5000);
}
/**
* Assert for the number of server connections. This does repeated checks (with
* timeout) if it not matches at first because closing at the client side might
* not take effect on the server side immediately.
*
* @param wantedNumberOfConnections How many do we want to have
* @param maxWaitMs Within how much time (0= immediately)
*/
private static void assertNumberOfConnectionsOnServer(int wantedNumberOfConnections, long maxWaitMs)
throws InterruptedException {
int numActiveConnections = ((NettyServer) server).getNumActiveConnections();
if (numActiveConnections == wantedNumberOfConnections) {
return; // We're good.
}
long startMs = System.currentTimeMillis();
long waited = 0;
if (maxWaitMs > 0) {
boolean timeOut = false;
while (numActiveConnections != wantedNumberOfConnections && !timeOut) {
LOG.info("Server still has {} active connections (want {}, waiting for {}ms); retrying...",
numActiveConnections, wantedNumberOfConnections, waited);
Thread.sleep(100);
numActiveConnections = ((NettyServer) server).getNumActiveConnections();
waited = System.currentTimeMillis() - startMs;
timeOut = waited > maxWaitMs;
}
LOG.info("Server has {} active connections", numActiveConnections);
}
assertEquals(wantedNumberOfConnections, numActiveConnections,
"Not the expected number of connections after a wait of " + waited + " ms");
}
private Message createMessage() {
Message msg = Message.newBuilder().setTo("wife").setFrom("husband").setBody("I love you!").build();
return msg;
}
// send a malformed request (HTTP) to the NettyServer port
@Test
void badRequest() throws IOException {
int port = server.getPort();
String msg = "GET /status HTTP/1.1\n\n";
InetSocketAddress sockAddr = new InetSocketAddress("127.0.0.1", port);
try (Socket sock = new Socket()) {
sock.connect(sockAddr);
OutputStream out = sock.getOutputStream();
out.write(msg.getBytes(StandardCharsets.UTF_8));
out.flush();
byte[] buf = new byte[2048];
int bytesRead = sock.getInputStream().read(buf);
assertEquals(bytesRead, -1);
}
}
}
| 6,867 |
0 | Create_ds/avro/lang/java/ipc-netty/src/main/java/org/apache/avro/ipc | Create_ds/avro/lang/java/ipc-netty/src/main/java/org/apache/avro/ipc/netty/NettyTransportCodec.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro.ipc.netty;
import static io.netty.buffer.Unpooled.wrappedBuffer;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import org.apache.avro.AvroRuntimeException;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.MessageToMessageEncoder;
/**
* Data structure, encoder and decoder classes for the Netty transport.
*/
public class NettyTransportCodec {
/**
* Transport protocol data structure when using Netty.
*/
public static class NettyDataPack {
private int serial; // to track each call in client side
private List<ByteBuffer> datas;
public NettyDataPack() {
}
public NettyDataPack(int serial, List<ByteBuffer> datas) {
this.serial = serial;
this.datas = datas;
}
public void setSerial(int serial) {
this.serial = serial;
}
public int getSerial() {
return serial;
}
public void setDatas(List<ByteBuffer> datas) {
this.datas = datas;
}
public List<ByteBuffer> getDatas() {
return datas;
}
}
/**
* Protocol encoder which converts NettyDataPack which contains the Responder's
* output List<ByteBuffer> to ChannelBuffer needed by Netty.
*/
public static class NettyFrameEncoder extends MessageToMessageEncoder<NettyDataPack> {
/**
* encode msg to ChannelBuffer
*
* @param msg NettyDataPack from NettyServerAvroHandler/NettyClientAvroHandler
* in the pipeline
* @return encoded ChannelBuffer
*/
@Override
protected void encode(ChannelHandlerContext ctx, NettyDataPack dataPack, List<Object> out) throws Exception {
List<ByteBuffer> origs = dataPack.getDatas();
List<ByteBuffer> bbs = new ArrayList<>(origs.size() * 2 + 1);
bbs.add(getPackHeader(dataPack)); // prepend a pack header including serial number and list size
for (ByteBuffer b : origs) {
bbs.add(getLengthHeader(b)); // for each buffer prepend length field
bbs.add(b);
}
out.add(wrappedBuffer(bbs.toArray(new ByteBuffer[0])));
}
private ByteBuffer getPackHeader(NettyDataPack dataPack) {
ByteBuffer header = ByteBuffer.allocate(8);
header.putInt(dataPack.getSerial());
header.putInt(dataPack.getDatas().size());
((Buffer) header).flip();
return header;
}
private ByteBuffer getLengthHeader(ByteBuffer buf) {
ByteBuffer header = ByteBuffer.allocate(4);
header.putInt(buf.limit());
((Buffer) header).flip();
return header;
}
}
/**
* Protocol decoder which converts Netty's ChannelBuffer to NettyDataPack which
* contains a List<ByteBuffer> needed by Avro Responder.
*/
public static class NettyFrameDecoder extends ByteToMessageDecoder {
private boolean packHeaderRead = false;
private int listSize;
private NettyDataPack dataPack;
private final long maxMem;
private static final long SIZEOF_REF = 8L; // mem usage of 64-bit pointer
public NettyFrameDecoder() {
maxMem = Runtime.getRuntime().maxMemory();
}
/**
* decode buffer to NettyDataPack
*/
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
if (!in.isReadable()) {
return;
}
if (!packHeaderRead) {
if (decodePackHeader(ctx, in)) {
packHeaderRead = true;
}
} else {
if (decodePackBody(ctx, in)) {
packHeaderRead = false; // reset state
out.add(dataPack);
}
}
}
private boolean decodePackHeader(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {
if (buffer.readableBytes() < 8) {
return false;
}
int serial = buffer.readInt();
int listSize = buffer.readInt();
// Sanity check to reduce likelihood of invalid requests being honored.
// Only allow 10% of available memory to go towards this list (too much!)
if (listSize * SIZEOF_REF > 0.1 * maxMem) {
throw new AvroRuntimeException(
"Excessively large list allocation " + "request detected: " + listSize + " items! Connection closed.");
}
this.listSize = listSize;
dataPack = new NettyDataPack(serial, new ArrayList<>(listSize));
return true;
}
private boolean decodePackBody(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {
if (buffer.readableBytes() < 4) {
return false;
}
buffer.markReaderIndex();
int length = buffer.readInt();
if (buffer.readableBytes() < length) {
buffer.resetReaderIndex();
return false;
}
ByteBuffer bb = ByteBuffer.allocate(length);
buffer.readBytes(bb);
((Buffer) bb).flip();
dataPack.getDatas().add(bb);
return dataPack.getDatas().size() == listSize;
}
}
}
| 6,868 |
0 | Create_ds/avro/lang/java/ipc-netty/src/main/java/org/apache/avro/ipc | Create_ds/avro/lang/java/ipc-netty/src/main/java/org/apache/avro/ipc/netty/NettyTransceiver.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro.ipc.netty;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Consumer;
import org.apache.avro.Protocol;
import org.apache.avro.ipc.CallFuture;
import org.apache.avro.ipc.Callback;
import org.apache.avro.ipc.Transceiver;
import org.apache.avro.ipc.netty.NettyTransportCodec.NettyDataPack;
import org.apache.avro.ipc.netty.NettyTransportCodec.NettyFrameDecoder;
import org.apache.avro.ipc.netty.NettyTransportCodec.NettyFrameEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A Netty-based {@link Transceiver} implementation.
*/
public class NettyTransceiver extends Transceiver {
/** If not specified, the default connection timeout will be used (60 sec). */
public static final int DEFAULT_CONNECTION_TIMEOUT_MILLIS = 60 * 1000;
public static final String NETTY_CONNECT_TIMEOUT_OPTION = "connectTimeoutMillis";
public static final String NETTY_TCP_NODELAY_OPTION = "tcpNoDelay";
public static final String NETTY_KEEPALIVE_OPTION = "keepAlive";
public static final boolean DEFAULT_TCP_NODELAY_VALUE = true;
private static final Logger LOG = LoggerFactory.getLogger(NettyTransceiver.class.getName());
private final AtomicInteger serialGenerator = new AtomicInteger(0);
private final Map<Integer, Callback<List<ByteBuffer>>> requests = new ConcurrentHashMap<>();
private final Integer connectTimeoutMillis;
private final Bootstrap bootstrap;
private final InetSocketAddress remoteAddr;
private final EventLoopGroup workerGroup;
volatile ChannelFuture channelFuture;
volatile boolean stopping;
private final Object channelFutureLock = new Object();
/**
* Read lock must be acquired whenever using non-final state. Write lock must be
* acquired whenever modifying state.
*/
private final ReentrantReadWriteLock stateLock = new ReentrantReadWriteLock();
private Channel channel; // Synchronized on stateLock
private Protocol remote; // Synchronized on stateLock
NettyTransceiver() {
connectTimeoutMillis = 0;
bootstrap = null;
remoteAddr = null;
channelFuture = null;
workerGroup = null;
}
/**
* Creates a NettyTransceiver, and attempts to connect to the given address.
* {@link #DEFAULT_CONNECTION_TIMEOUT_MILLIS} is used for the connection
* timeout.
*
* @param addr the address to connect to.
* @throws IOException if an error occurs connecting to the given address.
*/
public NettyTransceiver(InetSocketAddress addr) throws IOException {
this(addr, DEFAULT_CONNECTION_TIMEOUT_MILLIS);
}
/**
* Creates a NettyTransceiver, and attempts to connect to the given address.
*
* @param addr the address to connect to.
* @param connectTimeoutMillis maximum amount of time to wait for connection
* establishment in milliseconds, or null to use
* {@link #DEFAULT_CONNECTION_TIMEOUT_MILLIS}.
* @throws IOException if an error occurs connecting to the given address.
*/
public NettyTransceiver(InetSocketAddress addr, Integer connectTimeoutMillis) throws IOException {
this(addr, connectTimeoutMillis, null, null);
}
/**
* Creates a NettyTransceiver, and attempts to connect to the given address.
*
* @param addr the address to connect to.
* @param initializer Consumer function to apply initial setup to the
* SocketChannel. Useablet to set things like SSL
* requirements, compression, etc...
* @throws IOException if an error occurs connecting to the given address.
*/
public NettyTransceiver(InetSocketAddress addr, final Consumer<SocketChannel> initializer) throws IOException {
this(addr, DEFAULT_CONNECTION_TIMEOUT_MILLIS, initializer, null);
}
/**
* Creates a NettyTransceiver, and attempts to connect to the given address.
*
* @param addr the address to connect to.
* @param connectTimeoutMillis maximum amount of time to wait for connection
* establishment in milliseconds, or null to use
* {@link #DEFAULT_CONNECTION_TIMEOUT_MILLIS}.
* @param initializer Consumer function to apply initial setup to the
* SocketChannel. Usable to set things like SSL
* requirements, compression, etc...
* @throws IOException if an error occurs connecting to the given address.
*/
public NettyTransceiver(InetSocketAddress addr, Integer connectTimeoutMillis,
final Consumer<SocketChannel> initializer) throws IOException {
this(addr, connectTimeoutMillis, initializer, null);
}
/**
* Creates a NettyTransceiver, and attempts to connect to the given address.
*
* @param addr the address to connect to.
* @param connectTimeoutMillis maximum amount of time to wait for connection
* establishment in milliseconds, or null to use
* {@link #DEFAULT_CONNECTION_TIMEOUT_MILLIS}.
* @param initializer Consumer function to apply initial setup to the
* SocketChannel. Usable to set things like SSL
* requirements, compression, etc...
* @param bootStrapInitialzier Consumer function to apply initial setup to the
* Bootstrap. Usable to set things like tcp
* connection properties, nagle algorithm, etc...
* @throws IOException if an error occurs connecting to the given address.
*/
public NettyTransceiver(InetSocketAddress addr, Integer connectTimeoutMillis,
final Consumer<SocketChannel> initializer, final Consumer<Bootstrap> bootStrapInitialzier) throws IOException {
// Set up.
if (connectTimeoutMillis == null) {
connectTimeoutMillis = DEFAULT_CONNECTION_TIMEOUT_MILLIS;
}
this.connectTimeoutMillis = connectTimeoutMillis;
workerGroup = new NioEventLoopGroup(new NettyTransceiverThreadFactory("avro"));
bootstrap = new Bootstrap().group(workerGroup).channel(NioSocketChannel.class)
.option(ChannelOption.SO_KEEPALIVE, true).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMillis)
.option(ChannelOption.TCP_NODELAY, DEFAULT_TCP_NODELAY_VALUE).handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
if (initializer != null) {
initializer.accept(ch);
}
ch.pipeline().addLast("frameDecoder", new NettyFrameDecoder())
.addLast("frameEncoder", new NettyFrameEncoder()).addLast("handler", createNettyClientAvroHandler());
}
});
if (bootStrapInitialzier != null) {
bootStrapInitialzier.accept(bootstrap);
}
remoteAddr = addr;
// Make a new connection.
stateLock.readLock().lock();
try {
getChannel();
} catch (Throwable e) {
// must attempt to clean up any allocated channel future
if (channelFuture != null) {
channelFuture.channel().close();
}
workerGroup.shutdownGracefully();
if (e instanceof IOException)
throw (IOException) e;
if (e instanceof RuntimeException)
throw (RuntimeException) e;
// all that's left is Error
throw (Error) e;
} finally {
stateLock.readLock().unlock();
}
}
/**
* Creates a Netty ChannelUpstreamHandler for handling events on the Netty
* client channel.
*
* @return the ChannelUpstreamHandler to use.
*/
protected ChannelInboundHandler createNettyClientAvroHandler() {
return new NettyClientAvroHandler();
}
/**
* Tests whether the given channel is ready for writing.
*
* @return true if the channel is open and ready; false otherwise.
*/
private static boolean isChannelReady(Channel channel) {
return (channel != null) && channel.isOpen() && channel.isActive();
}
/**
* Gets the Netty channel. If the channel is not connected, first attempts to
* connect. NOTE: The stateLock read lock *must* be acquired before calling this
* method.
*
* @return the Netty channel
* @throws IOException if an error occurs connecting the channel.
*/
private Channel getChannel() throws IOException {
if (!isChannelReady(channel)) {
// Need to reconnect
// Upgrade to write lock
stateLock.readLock().unlock();
stateLock.writeLock().lock();
try {
if (!isChannelReady(channel)) {
synchronized (channelFutureLock) {
if (!stopping) {
LOG.debug("Connecting to {}", remoteAddr);
channelFuture = bootstrap.connect(remoteAddr);
}
}
if (channelFuture != null) {
try {
channelFuture.await(connectTimeoutMillis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // Reset interrupt flag
throw new IOException("Interrupted while connecting to " + remoteAddr);
}
synchronized (channelFutureLock) {
if (!channelFuture.isSuccess()) {
remote = null;
throw new IOException("Error connecting to " + remoteAddr, channelFuture.cause());
}
channel = channelFuture.channel();
channelFuture = null;
}
}
}
} finally {
// Downgrade to read lock:
stateLock.readLock().lock();
stateLock.writeLock().unlock();
}
}
return channel;
}
/**
* Closes the connection to the remote peer if connected.
*
* @param awaitCompletion if true, will block until the close has
* completed.
* @param cancelPendingRequests if true, will drain the requests map and send an
* IOException to all Callbacks.
* @param cause if non-null and cancelPendingRequests is true,
* this Throwable will be passed to all Callbacks.
*/
private void disconnect(boolean awaitCompletion, boolean cancelPendingRequests, Throwable cause) {
Channel channelToClose = null;
Map<Integer, Callback<List<ByteBuffer>>> requestsToCancel = null;
boolean stateReadLockHeld = stateLock.getReadHoldCount() != 0;
ChannelFuture channelFutureToCancel = null;
synchronized (channelFutureLock) {
if (stopping && channelFuture != null) {
channelFutureToCancel = channelFuture;
channelFuture = null;
}
}
if (channelFutureToCancel != null) {
channelFutureToCancel.cancel(true);
}
if (stateReadLockHeld) {
stateLock.readLock().unlock();
}
stateLock.writeLock().lock();
try {
if (channel != null) {
if (cause != null) {
LOG.debug("Disconnecting from {}", remoteAddr, cause);
} else {
LOG.debug("Disconnecting from {}", remoteAddr);
}
channelToClose = channel;
channel = null;
remote = null;
if (cancelPendingRequests) {
// Remove all pending requests (will be canceled after relinquishing
// write lock).
requestsToCancel = new ConcurrentHashMap<>(requests);
requests.clear();
}
}
} finally {
if (stateReadLockHeld) {
stateLock.readLock().lock();
}
stateLock.writeLock().unlock();
}
// Cancel any pending requests by sending errors to the callbacks:
if ((requestsToCancel != null) && !requestsToCancel.isEmpty()) {
LOG.debug("Removing {} pending request(s)", requestsToCancel.size());
for (Callback<List<ByteBuffer>> request : requestsToCancel.values()) {
request.handleError(cause != null ? cause : new IOException(getClass().getSimpleName() + " closed"));
}
}
// Close the channel:
if (channelToClose != null) {
ChannelFuture closeFuture = channelToClose.close();
if (awaitCompletion && (closeFuture != null)) {
try {
closeFuture.await(connectTimeoutMillis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // Reset interrupt flag
LOG.warn("Interrupted while disconnecting", e);
}
}
}
}
/**
* Netty channels are thread-safe, so there is no need to acquire locks. This
* method is a no-op.
*/
@Override
public void lockChannel() {
}
/**
* Netty channels are thread-safe, so there is no need to acquire locks. This
* method is a no-op.
*/
@Override
public void unlockChannel() {
}
/**
* Closes this transceiver and disconnects from the remote peer. Cancels all
* pending RPCs, sends an IOException to all pending callbacks, and blocks until
* the close has completed.
*/
@Override
public void close() {
close(true);
}
/**
* Closes this transceiver and disconnects from the remote peer. Cancels all
* pending RPCs and sends an IOException to all pending callbacks.
*
* @param awaitCompletion if true, will block until the close has completed.
*/
public void close(boolean awaitCompletion) {
try {
// Close the connection:
stopping = true;
disconnect(awaitCompletion, true, null);
} finally {
// Shut down all thread pools to exit.
if (workerGroup != null) {
workerGroup.shutdownGracefully();
}
}
}
@Override
public String getRemoteName() throws IOException {
stateLock.readLock().lock();
try {
return getChannel().remoteAddress().toString();
} finally {
stateLock.readLock().unlock();
}
}
/**
* Override as non-synchronized method because the method is thread safe.
*/
@Override
public List<ByteBuffer> transceive(List<ByteBuffer> request) throws IOException {
try {
CallFuture<List<ByteBuffer>> transceiverFuture = new CallFuture<>();
transceive(request, transceiverFuture);
return transceiverFuture.get();
} catch (InterruptedException | ExecutionException e) {
LOG.debug("failed to get the response", e);
return null;
}
}
@Override
public void transceive(List<ByteBuffer> request, Callback<List<ByteBuffer>> callback) throws IOException {
stateLock.readLock().lock();
try {
int serial = serialGenerator.incrementAndGet();
NettyDataPack dataPack = new NettyDataPack(serial, request);
requests.put(serial, callback);
writeDataPack(dataPack);
} finally {
stateLock.readLock().unlock();
}
}
@Override
public void writeBuffers(List<ByteBuffer> buffers) throws IOException {
ChannelFuture writeFuture;
stateLock.readLock().lock();
try {
writeFuture = writeDataPack(new NettyDataPack(serialGenerator.incrementAndGet(), buffers));
} finally {
stateLock.readLock().unlock();
}
if (!writeFuture.isDone()) {
try {
writeFuture.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // Reset interrupt flag
throw new IOException("Interrupted while writing Netty data pack", e);
}
}
if (!writeFuture.isSuccess()) {
throw new IOException("Error writing buffers", writeFuture.cause());
}
}
/**
* Writes a NettyDataPack, reconnecting to the remote peer if necessary. NOTE:
* The stateLock read lock *must* be acquired before calling this method.
*
* @param dataPack the data pack to write.
* @return the Netty ChannelFuture for the write operation.
* @throws IOException if an error occurs connecting to the remote peer.
*/
private ChannelFuture writeDataPack(NettyDataPack dataPack) throws IOException {
return getChannel().writeAndFlush(dataPack);
}
@Override
public List<ByteBuffer> readBuffers() throws IOException {
throw new UnsupportedOperationException();
}
@Override
public Protocol getRemote() {
stateLock.readLock().lock();
try {
return remote;
} finally {
stateLock.readLock().unlock();
}
}
@Override
public boolean isConnected() {
stateLock.readLock().lock();
try {
return remote != null;
} finally {
stateLock.readLock().unlock();
}
}
@Override
public void setRemote(Protocol protocol) {
stateLock.writeLock().lock();
try {
this.remote = protocol;
} finally {
stateLock.writeLock().unlock();
}
}
/**
* A ChannelFutureListener for channel write operations that notifies a
* {@link Callback} if an error occurs while writing to the channel.
*/
protected static class WriteFutureListener implements ChannelFutureListener {
protected final Callback<List<ByteBuffer>> callback;
/**
* Creates a WriteFutureListener that notifies the given callback if an error
* occurs writing data to the channel.
*
* @param callback the callback to notify, or null to skip notification.
*/
public WriteFutureListener(Callback<List<ByteBuffer>> callback) {
this.callback = callback;
}
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (!future.isSuccess() && (callback != null)) {
callback.handleError(new IOException("Error writing buffers", future.cause()));
}
}
}
/**
* Avro client handler for the Netty transport
*/
protected class NettyClientAvroHandler extends SimpleChannelInboundHandler<NettyDataPack> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, NettyDataPack dataPack) throws Exception {
Callback<List<ByteBuffer>> callback = requests.get(dataPack.getSerial());
if (callback == null) {
throw new RuntimeException("Missing previous call info");
}
try {
callback.handleResult(dataPack.getDatas());
} finally {
requests.remove(dataPack.getSerial());
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) {
disconnect(false, true, e);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
if (!ctx.channel().isOpen()) {
LOG.info("Connection to {} disconnected.", ctx.channel().remoteAddress());
disconnect(false, true, null);
}
super.channelInactive(ctx);
}
}
/**
* Creates threads with unique names based on a specified name prefix.
*/
protected static class NettyTransceiverThreadFactory implements ThreadFactory {
private final AtomicInteger threadId = new AtomicInteger(0);
private final String prefix;
/**
* Creates a NettyTransceiverThreadFactory that creates threads with the
* specified name.
*
* @param prefix the name prefix to use for all threads created by this
* ThreadFactory. A unique ID will be appended to this prefix to
* form the final thread name.
*/
public NettyTransceiverThreadFactory(String prefix) {
this.prefix = prefix;
}
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setName(prefix + " " + threadId.incrementAndGet());
return thread;
}
}
}
| 6,869 |
0 | Create_ds/avro/lang/java/ipc-netty/src/main/java/org/apache/avro/ipc | Create_ds/avro/lang/java/ipc-netty/src/main/java/org/apache/avro/ipc/netty/NettyServer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro.ipc.netty;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import org.apache.avro.ipc.Responder;
import org.apache.avro.ipc.Server;
import org.apache.avro.ipc.netty.NettyTransportCodec.NettyDataPack;
import org.apache.avro.ipc.netty.NettyTransportCodec.NettyFrameDecoder;
import org.apache.avro.ipc.netty.NettyTransportCodec.NettyFrameEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.DefaultEventLoopGroup;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A Netty-based RPC {@link Server} implementation.
*/
public class NettyServer implements Server {
private static final Logger LOG = LoggerFactory.getLogger(NettyServer.class.getName());
private final Responder responder;
private final Channel serverChannel;
private final EventLoopGroup bossGroup;
private final EventLoopGroup workerGroup;
private final EventLoopGroup callerGroup;
private final CountDownLatch closed = new CountDownLatch(1);
private final AtomicInteger activeCount = new AtomicInteger(0);
public NettyServer(Responder responder, InetSocketAddress addr) throws InterruptedException {
this(responder, addr, null);
}
public NettyServer(Responder responder, InetSocketAddress addr, final Consumer<SocketChannel> initializer)
throws InterruptedException {
this(responder, addr, initializer, null, null, null, null);
}
public NettyServer(Responder responder, InetSocketAddress addr, final Consumer<SocketChannel> initializer,
final Consumer<ServerBootstrap> bootStrapInitialzier) throws InterruptedException {
this(responder, addr, initializer, bootStrapInitialzier, null, null, null);
}
public NettyServer(Responder responder, InetSocketAddress addr, final Consumer<SocketChannel> initializer,
final Consumer<ServerBootstrap> bootStrapInitialzier, EventLoopGroup bossGroup, EventLoopGroup workerGroup,
EventLoopGroup callerGroup) throws InterruptedException {
this.bossGroup = bossGroup == null ? new NioEventLoopGroup(1) : bossGroup;
this.workerGroup = workerGroup == null ? new NioEventLoopGroup(10) : workerGroup;
this.callerGroup = callerGroup == null ? new DefaultEventLoopGroup(16) : callerGroup;
this.responder = responder;
ServerBootstrap bootstrap = new ServerBootstrap().group(this.bossGroup, this.workerGroup)
.channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
if (initializer != null) {
initializer.accept(ch);
}
ch.pipeline().addLast("frameDecoder", new NettyFrameDecoder())
.addLast("frameEncoder", new NettyFrameEncoder()).addLast("handler", new NettyServerAvroHandler());
}
}).option(ChannelOption.SO_BACKLOG, 1024).childOption(ChannelOption.TCP_NODELAY, true)
.childOption(ChannelOption.SO_KEEPALIVE, true);
if (bootStrapInitialzier != null) {
bootStrapInitialzier.accept(bootstrap);
}
serverChannel = bootstrap.bind(addr).sync().channel();
}
@Override
public void start() {
// No-op.
}
@Override
public void close() {
workerGroup.shutdownGracefully().syncUninterruptibly();
bossGroup.shutdownGracefully().syncUninterruptibly();
try {
serverChannel.closeFuture().sync();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
closed.countDown();
}
@Override
public int getPort() {
return ((InetSocketAddress) serverChannel.localAddress()).getPort();
}
@Override
public void join() throws InterruptedException {
closed.await();
}
/**
*
* @return The number of clients currently connected to this server.
*/
public int getNumActiveConnections() {
return activeCount.get();
}
/**
* Avro server handler for the Netty transport
*/
class NettyServerAvroHandler extends SimpleChannelInboundHandler<NettyDataPack> {
private NettyTransceiver connectionMetadata = new NettyTransceiver();
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
activeCount.incrementAndGet();
super.channelActive(ctx);
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, final NettyDataPack dataPack) throws Exception {
callerGroup.submit(new Runnable() {
@Override
public void run() {
List<ByteBuffer> req = dataPack.getDatas();
try {
List<ByteBuffer> res = responder.respond(req, connectionMetadata);
// response will be null for oneway messages.
if (res != null) {
dataPack.setDatas(res);
ctx.channel().writeAndFlush(dataPack);
}
} catch (IOException e) {
LOG.warn("unexpected error");
}
}
});
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) {
LOG.warn("Unexpected exception from downstream.", e);
ctx.close().syncUninterruptibly();
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
LOG.info("Connection to {} disconnected.", ctx.channel().remoteAddress());
activeCount.decrementAndGet();
super.channelInactive(ctx);
}
}
}
| 6,870 |
0 | Create_ds/avro/lang/java/tools/src/test/java/org/apache/avro | Create_ds/avro/lang/java/tools/src/test/java/org/apache/avro/tool/TestRpcReceiveAndSendTools.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro.tool;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Arrays;
import org.junit.jupiter.api.Test;
public class TestRpcReceiveAndSendTools {
/**
* Starts a server (using the tool) and sends a single message to it.
*/
@Test
void serveAndSend() throws Exception {
String protocolFile = System.getProperty("share.dir", "../../../share") + "/test/schemas/simple.avpr";
ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
PrintStream p1 = new PrintStream(baos1);
RpcReceiveTool receive = new RpcReceiveTool();
receive.run1(null, p1, System.err,
Arrays.asList("http://0.0.0.0:0/", protocolFile, "hello", "-data", "\"Hello!\""));
ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
PrintStream p2 = new PrintStream(baos2);
RpcSendTool send = new RpcSendTool();
send.run(null, p2, System.err, Arrays.asList("http://127.0.0.1:" + receive.server.getPort() + "/", protocolFile,
"hello", "-data", "{ \"greeting\": \"Hi!\" }"));
receive.run2(System.err);
assertTrue(baos1.toString("UTF-8").replace("\r", "").endsWith("hello\t{\"greeting\":\"Hi!\"}\n"));
assertEquals("\"Hello!\"\n", baos2.toString("UTF-8").replace("\r", ""));
}
}
| 6,871 |
0 | Create_ds/avro/lang/java/tools/src/test/java/org/apache/avro | Create_ds/avro/lang/java/tools/src/test/java/org/apache/avro/tool/TestRecordCountTool.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro.tool;
import org.apache.avro.Schema;
import org.apache.avro.Schema.Type;
import org.apache.avro.file.DataFileWriter;
import org.apache.avro.generic.GenericDatumWriter;
import org.junit.Rule;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.rules.TestName;
import java.io.ByteArrayOutputStream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class TestRecordCountTool {
@Rule
public TestName name = new TestName();
@TempDir
public File temporaryFolder;
private File generateData(int numRecords) throws Exception {
final File tempFile = File.createTempFile("junit", null, temporaryFolder);
Schema schema = Schema.create(Type.STRING);
try (DataFileWriter<Object> writer = new DataFileWriter<>(new GenericDatumWriter<>(schema))) {
writer.create(schema, tempFile);
// ~10 records per block
writer.setSyncInterval(60);
for (int i = 0; i < numRecords; i++) {
writer.append("foobar");
}
}
return tempFile;
}
@Test
void fileDoesNotExist() throws Exception {
assertThrows(FileNotFoundException.class, () -> {
List<String> args = Collections.singletonList(new File(temporaryFolder, "nonExistingFile").getAbsolutePath());
int returnCode = new RecordCountTool().run(System.in, System.out, System.err, args);
assertEquals(1, returnCode);
});
}
@Test
void basic() throws Exception {
final List<Integer> inputSizes = IntStream.range(0, 20).boxed().collect(Collectors.toList());
for (Integer inputSize : inputSizes) {
File inputFile = generateData(inputSize);
List<String> args = Collections.singletonList(inputFile.getAbsolutePath());
final ByteArrayOutputStream out = new ByteArrayOutputStream();
int returnCode = new RecordCountTool().run(System.in, new PrintStream(out), System.err, args);
assertEquals(0, returnCode);
assertEquals(inputSize.toString() + System.lineSeparator(), out.toString());
}
}
@Test
void multipleFiles() throws Exception {
File f1 = generateData(20);
File f2 = generateData(200);
List<String> args = Arrays.asList(f1.getAbsolutePath(), f2.getAbsolutePath());
final ByteArrayOutputStream out = new ByteArrayOutputStream();
int returnCode = new RecordCountTool().run(System.in, new PrintStream(out), System.err, args);
assertEquals(0, returnCode);
assertEquals("220" + System.lineSeparator(), out.toString());
}
}
| 6,872 |
0 | Create_ds/avro/lang/java/tools/src/test/java/org/apache/avro | Create_ds/avro/lang/java/tools/src/test/java/org/apache/avro/tool/TestIdlTool.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro.tool;
import org.junit.jupiter.api.Test;
import java.io.BufferedReader;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class TestIdlTool {
@Test
public void testWriteIdlAsSchema() throws Exception {
String idl = "src/test/idl/schema.avdl";
String protocol = "src/test/idl/schema.avsc";
String outfile = "target/test-schema.avsc";
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
List<String> arglist = Arrays.asList(idl, outfile);
new IdlTool().run(null, null, new PrintStream(buffer), arglist);
assertEquals(readFileAsString(protocol), readFileAsString(outfile));
String warnings = readPrintStreamBuffer(buffer);
assertEquals("Warning: Line 1, char 1: Ignoring out-of-place documentation comment."
+ "\nDid you mean to use a multiline comment ( /* ... */ ) instead?", warnings);
}
@Test
void writeIdlAsProtocol() throws Exception {
String idl = "src/test/idl/protocol.avdl";
String protocol = "src/test/idl/protocol.avpr";
String outfile = "target/test-protocol.avpr";
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
List<String> arglist = Arrays.asList(idl, outfile);
new IdlTool().run(null, null, new PrintStream(buffer), arglist);
assertEquals(readFileAsString(protocol), readFileAsString(outfile));
String warnings = readPrintStreamBuffer(buffer);
assertEquals("Warning: Line 1, char 1: Ignoring out-of-place documentation comment."
+ "\nDid you mean to use a multiline comment ( /* ... */ ) instead?", warnings);
}
@Test
public void testWriteIdlAsProtocolUsingJavaCC() throws Exception {
String idl = "src/test/idl/protocol.avdl";
String protocol = "src/test/idl/protocol.avpr";
String outfile = "target/test-protocol.avpr";
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
List<String> arglist = Arrays.asList("--useJavaCC", idl, outfile);
new IdlTool().run(null, null, new PrintStream(buffer), arglist);
assertEquals(readFileAsString(protocol), readFileAsString(outfile));
String warnings = readPrintStreamBuffer(buffer);
assertEquals(
"Warning: Found documentation comment at line 19, column 1. Ignoring previous one at line 1, column 1: "
+ "\"Licensed to the Apache Software Foundation (ASF) under one\n"
+ "or more contributor license agreements. See the NOTICE file\n"
+ "distributed with this work for additional information\n"
+ "regarding copyright ownership. The ASF licenses this file\n"
+ "to you under the Apache License, Version 2.0 (the\n"
+ "\"License\"); you may not use this file except in compliance\n"
+ "with the License. You may obtain a copy of the License at\n"
+ "\n https://www.apache.org/licenses/LICENSE-2.0\n\n"
+ "Unless required by applicable law or agreed to in writing, software\n"
+ "distributed under the License is distributed on an \"AS IS\" BASIS,\n"
+ "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n"
+ "See the License for the specific language governing permissions and\n"
+ "limitations under the License.\"\nDid you mean to use a multiline comment ( /* ... */ ) instead?",
warnings);
}
private String readFileAsString(String filePath) throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
return reader.lines().collect(Collectors.joining("\n"));
}
}
private String readPrintStreamBuffer(ByteArrayOutputStream buffer) {
BufferedReader reader = new BufferedReader(
new InputStreamReader(new ByteArrayInputStream(buffer.toByteArray()), Charset.defaultCharset()));
return reader.lines().collect(Collectors.joining("\n"));
}
}
| 6,873 |
0 | Create_ds/avro/lang/java/tools/src/test/java/org/apache/avro | Create_ds/avro/lang/java/tools/src/test/java/org/apache/avro/tool/TestIdlToSchemataTool.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro.tool;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
public class TestIdlToSchemataTool {
@Test
void splitIdlIntoSchemata() throws Exception {
String idl = "src/test/idl/protocol.avdl";
String outdir = "target/test-split";
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
List<String> arglist = Arrays.asList(idl, outdir);
new IdlToSchemataTool().run(null, null, new PrintStream(buffer), arglist);
String[] files = new File(outdir).list();
assertEquals(4, files.length);
String warnings = readPrintStreamBuffer(buffer);
assertEquals("Warning: Line 1, char 1: Ignoring out-of-place documentation comment."
+ "\nDid you mean to use a multiline comment ( /* ... */ ) instead?", warnings);
}
@Test
public void testSplitIdlIntoSchemataUsingJavaCC() throws Exception {
String idl = "src/test/idl/protocol.avdl";
String outdir = "target/test-split";
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
List<String> arglist = Arrays.asList("--useJavaCC", idl, outdir);
new IdlToSchemataTool().run(null, null, new PrintStream(buffer), arglist);
String[] files = new File(outdir).list();
assertEquals(4, files.length);
String warnings = readPrintStreamBuffer(buffer);
assertEquals(
"Warning: Found documentation comment at line 19, column 1. Ignoring previous one at line 1, column 1: "
+ "\"Licensed to the Apache Software Foundation (ASF) under one\n"
+ "or more contributor license agreements. See the NOTICE file\n"
+ "distributed with this work for additional information\n"
+ "regarding copyright ownership. The ASF licenses this file\n"
+ "to you under the Apache License, Version 2.0 (the\n"
+ "\"License\"); you may not use this file except in compliance\n"
+ "with the License. You may obtain a copy of the License at\n"
+ "\n https://www.apache.org/licenses/LICENSE-2.0\n\n"
+ "Unless required by applicable law or agreed to in writing, software\n"
+ "distributed under the License is distributed on an \"AS IS\" BASIS,\n"
+ "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n"
+ "See the License for the specific language governing permissions and\n"
+ "limitations under the License.\"\nDid you mean to use a multiline comment ( /* ... */ ) instead?",
warnings);
}
private String readPrintStreamBuffer(ByteArrayOutputStream buffer) {
BufferedReader reader = new BufferedReader(
new InputStreamReader(new ByteArrayInputStream(buffer.toByteArray()), Charset.defaultCharset()));
return reader.lines().collect(Collectors.joining("\n"));
}
}
| 6,874 |
0 | Create_ds/avro/lang/java/tools/src/test/java/org/apache/avro | Create_ds/avro/lang/java/tools/src/test/java/org/apache/avro/tool/TestMain.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro.tool;
import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.Test;
public class TestMain {
/** Make sure that tool descriptions fit in 80 characters. */
@Test
void toolDescriptionLength() {
Main m = new Main();
for (Tool t : m.tools.values()) {
// System.out.println(t.getName() + ": " + t.getShortDescription().length());
if (m.maxLen + 2 + t.getShortDescription().length() > 80) {
fail("Tool description too long: " + t.getName());
}
}
}
/**
* Make sure that the tool name is not too long, otherwise space for description
* is too short because they are rebalanced in the CLI.
*/
@Test
void toolNameLength() {
// 13 chosen for backwards compatibility
final int MAX_NAME_LENGTH = 13;
Main m = new Main();
for (Tool t : m.tools.values()) {
if (t.getName().length() > MAX_NAME_LENGTH) {
fail("Tool name too long (" + t.getName().length() + "): " + t.getName() + ". Max length is: "
+ MAX_NAME_LENGTH);
}
}
}
}
| 6,875 |
0 | Create_ds/avro/lang/java/tools/src/test/java/org/apache/avro | Create_ds/avro/lang/java/tools/src/test/java/org/apache/avro/tool/TestJsonToFromBinaryFragmentTools.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro.tool;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.avro.Schema;
import org.apache.avro.Schema.Type;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
/**
* Tests both {@link JsonToBinaryFragmentTool} and
* {@link BinaryFragmentToJsonTool}.
*/
public class TestJsonToFromBinaryFragmentTools {
private static final String STRING_SCHEMA = Schema.create(Type.STRING).toString();
private static final String UTF8 = "utf-8";
private static final String AVRO = "ZLong string implies readable length encoding.";
private static final String JSON = "\"Long string implies readable length encoding.\"\n";
@TempDir
public File DIR;
@Test
void binaryToJson() throws Exception {
binaryToJson(AVRO, JSON, STRING_SCHEMA);
}
@Test
void jsonToBinary() throws Exception {
jsonToBinary(JSON, AVRO, STRING_SCHEMA);
}
@Test
void multiBinaryToJson() throws Exception {
binaryToJson(AVRO + AVRO + AVRO, JSON + JSON + JSON, STRING_SCHEMA);
}
@Test
void multiJsonToBinary() throws Exception {
jsonToBinary(JSON + JSON + JSON, AVRO + AVRO + AVRO, STRING_SCHEMA);
}
@Test
void binaryToNoPrettyJson() throws Exception {
binaryToJson(AVRO, JSON, "--no-pretty", STRING_SCHEMA);
}
@Test
void multiBinaryToNoPrettyJson() throws Exception {
binaryToJson(AVRO + AVRO + AVRO, JSON + JSON + JSON, "--no-pretty", STRING_SCHEMA);
}
@Test
void binaryToJsonSchemaFile() throws Exception {
binaryToJson(AVRO, JSON, "--schema-file", schemaFile(DIR));
}
@Test
void jsonToBinarySchemaFile() throws Exception {
jsonToBinary(JSON, AVRO, "--schema-file", schemaFile(DIR));
}
private void binaryToJson(String avro, String json, String... options) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream p = new PrintStream(new BufferedOutputStream(baos));
List<String> args = new ArrayList<>(Arrays.asList(options));
args.add("-");
new BinaryFragmentToJsonTool().run(new ByteArrayInputStream(avro.getBytes(StandardCharsets.UTF_8)), // stdin
p, // stdout
null, // stderr
args);
System.out.println(baos.toString(UTF8).replace("\r", ""));
assertEquals(json, baos.toString(UTF8).replace("\r", ""));
}
private void jsonToBinary(String json, String avro, String... options) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream p = new PrintStream(new BufferedOutputStream(baos));
List<String> args = new ArrayList<>(Arrays.asList(options));
args.add("-");
new JsonToBinaryFragmentTool().run(new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)), // stdin
p, // stdout
null, // stderr
args);
assertEquals(avro, baos.toString(UTF8));
}
private static String schemaFile(File dir) throws IOException {
File schemaFile = new File(dir, "String.avsc");
try (FileWriter fw = new FileWriter(schemaFile)) {
fw.append(STRING_SCHEMA);
}
return schemaFile.toString();
}
}
| 6,876 |
0 | Create_ds/avro/lang/java/tools/src/test/java/org/apache/avro | Create_ds/avro/lang/java/tools/src/test/java/org/apache/avro/tool/TestRpcProtocolTool.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro.tool;
import org.apache.avro.Protocol;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Collections;
/**
*
*/
public class TestRpcProtocolTool {
@ParameterizedTest
@ValueSource(strings = { "http", "avro" })
void rpcProtocol(String uriScheme) throws Exception {
String protocolFile = System.getProperty("share.dir", "../../../share") + "/test/schemas/simple.avpr";
Protocol simpleProtocol = Protocol.parse(new File(protocolFile));
// start a simple server
ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
PrintStream p1 = new PrintStream(baos1);
RpcReceiveTool receive = new RpcReceiveTool();
receive.run1(null, p1, System.err,
Arrays.asList(uriScheme + "://0.0.0.0:0/", protocolFile, "hello", "-data", "\"Hello!\""));
// run the actual test
ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
PrintStream p2 = new PrintStream(baos2, true, "UTF-8");
RpcProtocolTool testObject = new RpcProtocolTool();
testObject.run(null, p2, System.err,
Collections.singletonList(uriScheme + "://127.0.0.1:" + receive.server.getPort() + "/"));
p2.flush();
Assertions.assertEquals(simpleProtocol, Protocol.parse(baos2.toString("UTF-8")),
"Expected the simple.avpr protocol to be echoed to standout");
receive.server.close(); // force the server to finish
}
}
| 6,877 |
0 | Create_ds/avro/lang/java/tools/src/test/java/org/apache/avro | Create_ds/avro/lang/java/tools/src/test/java/org/apache/avro/tool/TestConcatTool.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro.tool;
import static java.util.Arrays.asList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.avro.Schema;
import org.apache.avro.Schema.Type;
import org.apache.avro.file.CodecFactory;
import org.apache.avro.file.DataFileConstants;
import org.apache.avro.file.DataFileStream;
import org.apache.avro.file.DataFileWriter;
import org.apache.avro.generic.GenericDatumReader;
import org.apache.avro.generic.GenericDatumWriter;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.util.Utf8;
import org.junit.Rule;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.rules.TestName;
public class TestConcatTool {
private static final int ROWS_IN_INPUT_FILES = 100000;
private static final CodecFactory DEFLATE = CodecFactory.deflateCodec(9);
@Rule
public TestName name = new TestName();
@TempDir
public File INPUT_DIR;
@TempDir
public File OUTPUT_DIR;
private Object aDatum(Type ofType, int forRow) {
switch (ofType) {
case STRING:
return String.valueOf(forRow % 100);
case INT:
return forRow;
default:
throw new AssertionError("I can't generate data for this type");
}
}
private File generateData(String file, Type type, Map<String, String> metadata, CodecFactory codec) throws Exception {
File inputFile = new File(INPUT_DIR, file);
Schema schema = Schema.create(type);
try (DataFileWriter<Object> writer = new DataFileWriter<>(new GenericDatumWriter<>(schema))) {
for (Entry<String, String> metadatum : metadata.entrySet()) {
writer.setMeta(metadatum.getKey(), metadatum.getValue());
}
writer.setCodec(codec);
writer.create(schema, inputFile);
for (int i = 0; i < ROWS_IN_INPUT_FILES; i++) {
writer.append(aDatum(type, i));
}
}
return inputFile;
}
private CodecFactory getCodec(File output) throws Exception {
try (DataFileStream<GenericRecord> reader = new DataFileStream<>(new FileInputStream(output),
new GenericDatumReader<>())) {
String codec = reader.getMetaString(DataFileConstants.CODEC);
return codec == null ? CodecFactory.nullCodec() : CodecFactory.fromString(codec);
}
}
private int numRowsInFile(File output) throws Exception {
int rowcount = 0;
try (DataFileStream<Utf8> reader = new DataFileStream<>(new FileInputStream(output), new GenericDatumReader<>())) {
for (Utf8 ignored : reader) {
++rowcount;
}
}
return rowcount;
}
@Test
void dirConcat() throws Exception {
Map<String, String> metadata = new HashMap<>();
for (int i = 0; i < 3; i++) {
generateData(name.getMethodName() + "-" + i + ".avro", Type.STRING, metadata, DEFLATE);
}
File output = new File(OUTPUT_DIR, name.getMethodName() + ".avro");
List<String> args = asList(INPUT_DIR.getAbsolutePath(), output.getAbsolutePath());
int returnCode = new ConcatTool().run(System.in, System.out, System.err, args);
assertEquals(0, returnCode);
assertEquals(ROWS_IN_INPUT_FILES * 3, numRowsInFile(output));
}
@Test
void globPatternConcat() throws Exception {
Map<String, String> metadata = new HashMap<>();
for (int i = 0; i < 3; i++) {
generateData(name.getMethodName() + "-" + i + ".avro", Type.STRING, metadata, DEFLATE);
}
File output = new File(OUTPUT_DIR, name.getMethodName() + ".avro");
List<String> args = asList(new File(INPUT_DIR, "/*").getAbsolutePath(), output.getAbsolutePath());
int returnCode = new ConcatTool().run(System.in, System.out, System.err, args);
assertEquals(0, returnCode);
assertEquals(ROWS_IN_INPUT_FILES * 3, numRowsInFile(output));
}
@Test
void fileDoesNotExist() throws Exception {
assertThrows(FileNotFoundException.class, () -> {
File output = new File(INPUT_DIR, name.getMethodName() + ".avro");
List<String> args = asList(new File(INPUT_DIR, "/doNotExist").getAbsolutePath(), output.getAbsolutePath());
new ConcatTool().run(System.in, System.out, System.err, args);
});
}
@Test
void concat() throws Exception {
Map<String, String> metadata = new HashMap<>();
metadata.put("myMetaKey", "myMetaValue");
File input1 = generateData(name.getMethodName() + "-1.avro", Type.STRING, metadata, DEFLATE);
File input2 = generateData(name.getMethodName() + "-2.avro", Type.STRING, metadata, DEFLATE);
File input3 = generateData(name.getMethodName() + "-3.avro", Type.STRING, metadata, DEFLATE);
File output = new File(OUTPUT_DIR, name.getMethodName() + ".avro");
List<String> args = asList(input1.getAbsolutePath(), input2.getAbsolutePath(), input3.getAbsolutePath(),
output.getAbsolutePath());
int returnCode = new ConcatTool().run(System.in, System.out, System.err, args);
assertEquals(0, returnCode);
assertEquals(ROWS_IN_INPUT_FILES * 3, numRowsInFile(output));
assertEquals(getCodec(input1).getClass(), getCodec(output).getClass());
}
@Test
void differentSchemasFail() throws Exception {
Map<String, String> metadata = new HashMap<>();
metadata.put("myMetaKey", "myMetaValue");
File input1 = generateData(name.getMethodName() + "-1.avro", Type.STRING, metadata, DEFLATE);
File input2 = generateData(name.getMethodName() + "-2.avro", Type.INT, metadata, DEFLATE);
File output = new File(OUTPUT_DIR, name.getMethodName() + ".avro");
List<String> args = asList(input1.getAbsolutePath(), input2.getAbsolutePath(), output.getAbsolutePath());
int returnCode = new ConcatTool().run(System.in, System.out, System.err, args);
assertEquals(1, returnCode);
}
@Test
void differentMetadataFail() throws Exception {
Map<String, String> metadata1 = new HashMap<>();
metadata1.put("myMetaKey", "myMetaValue");
Map<String, String> metadata2 = new HashMap<>();
metadata2.put("myOtherMetaKey", "myOtherMetaValue");
File input1 = generateData(name.getMethodName() + "-1.avro", Type.STRING, metadata1, DEFLATE);
File input2 = generateData(name.getMethodName() + "-2.avro", Type.STRING, metadata2, DEFLATE);
File output = new File(OUTPUT_DIR, name.getMethodName() + ".avro");
List<String> args = asList(input1.getAbsolutePath(), input2.getAbsolutePath(), output.getAbsolutePath());
int returnCode = new ConcatTool().run(System.in, System.out, System.err, args);
assertEquals(2, returnCode);
}
@Test
void differentCodecFail() throws Exception {
Map<String, String> metadata = new HashMap<>();
metadata.put("myMetaKey", "myMetaValue");
File input1 = generateData(name.getMethodName() + "-1.avro", Type.STRING, metadata, DEFLATE);
File input2 = generateData(name.getMethodName() + "-2.avro", Type.STRING, metadata, CodecFactory.nullCodec());
File output = new File(OUTPUT_DIR, name.getMethodName() + ".avro");
List<String> args = asList(input1.getAbsolutePath(), input2.getAbsolutePath(), output.getAbsolutePath());
int returnCode = new ConcatTool().run(System.in, System.out, System.err, args);
assertEquals(3, returnCode);
}
@Test
void helpfulMessageWhenNoArgsGiven() throws Exception {
int returnCode;
try (ByteArrayOutputStream buffer = new ByteArrayOutputStream(1024)) {
try (PrintStream out = new PrintStream(buffer)) {
returnCode = new ConcatTool().run(System.in, out, System.err, Collections.emptyList());
}
assertTrue(buffer.toString().trim().length() > 200, "should have lots of help");
}
assertEquals(0, returnCode);
}
}
| 6,878 |
0 | Create_ds/avro/lang/java/tools/src/test/java/org/apache/avro | Create_ds/avro/lang/java/tools/src/test/java/org/apache/avro/tool/TestDataFileTools.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro.tool;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.apache.avro.AvroRuntimeException;
import org.apache.avro.AvroTypeException;
import org.apache.avro.Schema;
import org.apache.avro.Schema.Type;
import org.apache.avro.file.DataFileReader;
import org.apache.avro.file.DataFileWriter;
import org.apache.avro.generic.GenericDatumReader;
import org.apache.avro.generic.GenericDatumWriter;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
@SuppressWarnings("deprecation")
public class TestDataFileTools {
static final int COUNT = 15;
static File sampleFile;
static String jsonData;
static Schema schema;
static File schemaFile;
private static final String KEY_NEEDING_ESCAPES = "trn\\\r\t\n";
private static final String ESCAPED_KEY = "trn\\\\\\r\\t\\n";
@TempDir
public static File DIR;
@BeforeAll
public static void writeSampleFile() throws IOException {
sampleFile = new File(DIR, TestDataFileTools.class.getName() + ".avro");
schema = Schema.create(Type.INT);
schemaFile = new File(DIR, "schema-temp.schema");
try (FileWriter fw = new FileWriter(schemaFile)) {
fw.append(schema.toString());
}
StringBuilder builder = new StringBuilder();
try (DataFileWriter<Object> writer = new DataFileWriter<>(new GenericDatumWriter<>(schema))) {
writer.setMeta(KEY_NEEDING_ESCAPES, "");
writer.create(schema, sampleFile);
for (int i = 0; i < COUNT; ++i) {
builder.append(Integer.toString(i));
builder.append("\n");
writer.append(i);
}
}
jsonData = builder.toString();
}
private String run(Tool tool, String... args) throws Exception {
return run(tool, null, args);
}
private String run(Tool tool, InputStream stdin, String... args) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream p = new PrintStream(baos);
tool.run(stdin, p, // stdout
null, // stderr
Arrays.asList(args));
return baos.toString("UTF-8").replace("\r", "");
}
@Test
void read() throws Exception {
assertEquals(jsonData, run(new DataFileReadTool(), sampleFile.getPath()));
}
@Test
void readStdin() throws Exception {
FileInputStream stdin = new FileInputStream(sampleFile);
assertEquals(jsonData, run(new DataFileReadTool(), stdin, "-"));
}
@Test
void readToJsonPretty() throws Exception {
assertEquals(jsonData, run(new DataFileReadTool(), "--pretty", sampleFile.getPath()));
}
@Test
void readWithReaderSchema() throws Exception {
assertEquals(jsonData, run(new DataFileReadTool(), "--reader-schema", "\"long\"", sampleFile.getPath()));
}
@Test
void readWithIncompatibleReaderSchema() throws Exception {
assertThrows(AvroTypeException.class, () -> {
// Fails: an int can't be read as a string.
run(new DataFileReadTool(), "--reader-schema", "\"string\"", sampleFile.getPath());
});
}
@Test
void readWithReaderSchemaFile() throws Exception {
File readerSchemaFile = new File(DIR, "reader-schema-temp.schema");
try (FileWriter fw = new FileWriter(readerSchemaFile)) {
fw.append("\"long\"");
}
assertEquals(jsonData,
run(new DataFileReadTool(), "--reader-schema-file", readerSchemaFile.getPath(), sampleFile.getPath()));
}
@Test
void readHeadDefaultCount() throws Exception {
String expectedJson = jsonData.substring(0, 20); // first 10 numbers
assertEquals(expectedJson, run(new DataFileReadTool(), "--head", sampleFile.getPath()));
}
@Test
void readHeadEquals3Count() throws Exception {
String expectedJson = jsonData.substring(0, 6); // first 3 numbers
assertEquals(expectedJson, run(new DataFileReadTool(), "--head=3", sampleFile.getPath()));
}
@Test
void readHeadSpace5Count() throws Exception {
String expectedJson = jsonData.substring(0, 10); // first 5 numbers
assertEquals(expectedJson, run(new DataFileReadTool(), "--head", "5", sampleFile.getPath()));
}
@Test
void readHeadLongCount() throws Exception {
assertEquals(jsonData, run(new DataFileReadTool(), "--head=3000000000", sampleFile.getPath()));
}
@Test
void readHeadEqualsZeroCount() throws Exception {
assertEquals("\n", run(new DataFileReadTool(), "--head=0", sampleFile.getPath()));
}
@Test
void readHeadNegativeCount() throws Exception {
assertThrows(AvroRuntimeException.class, () -> {
assertEquals("\n", run(new DataFileReadTool(), "--head=-5", sampleFile.getPath()));
});
}
@Test
void getMeta() throws Exception {
String output = run(new DataFileGetMetaTool(), sampleFile.getPath());
assertTrue(output.contains("avro.schema\t" + schema.toString() + "\n"), output);
assertTrue(output.contains(ESCAPED_KEY + "\t\n"), output);
}
@Test
void getMetaForSingleKey() throws Exception {
assertEquals(schema.toString() + "\n",
run(new DataFileGetMetaTool(), sampleFile.getPath(), "--key", "avro.schema"));
}
@Test
void getSchema() throws Exception {
assertEquals(schema.toString() + "\n", run(new DataFileGetSchemaTool(), sampleFile.getPath()));
}
@Test
void writeWithDeflate() throws Exception {
testWrite("deflate", Arrays.asList("--codec", "deflate"), "deflate");
}
@Test
void write() throws Exception {
testWrite("plain", Collections.emptyList(), "null");
}
public void testWrite(String name, List<String> extra, String expectedCodec) throws Exception {
testWrite(name, extra, expectedCodec, "-schema", schema.toString());
testWrite(name, extra, expectedCodec, "-schema-file", schemaFile.toString());
}
public void testWrite(String name, List<String> extra, String expectedCodec, String... extraArgs) throws Exception {
File outFile = new File(DIR, TestDataFileTools.class + ".testWrite." + name + ".avro");
try (FileOutputStream fout = new FileOutputStream(outFile)) {
try (PrintStream out = new PrintStream(fout)) {
List<String> args = new ArrayList<>();
Collections.addAll(args, extraArgs);
args.add("-");
args.addAll(extra);
new DataFileWriteTool().run(new ByteArrayInputStream(jsonData.getBytes("UTF-8")), new PrintStream(out), // stdout
null, // stderr
args);
}
}
// Read it back, and make sure it's valid.
GenericDatumReader<Object> reader = new GenericDatumReader<>();
try (DataFileReader<Object> fileReader = new DataFileReader<>(outFile, reader)) {
int i = 0;
for (Object datum : fileReader) {
assertEquals(i, datum);
i++;
}
assertEquals(COUNT, i);
assertEquals(schema, fileReader.getSchema());
String codecStr = fileReader.getMetaString("avro.codec");
if (null == codecStr) {
codecStr = "null";
}
assertEquals(expectedCodec, codecStr);
}
}
@Test
void failureOnWritingPartialJSONValues() throws Exception {
assertThrows(IOException.class, () -> {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream out = new PrintStream(baos);
new DataFileWriteTool().run(new ByteArrayInputStream("{".getBytes("UTF-8")), new PrintStream(out), // stdout
null, // stderr
Arrays.asList("-schema", "{ \"type\":\"record\", \"fields\":" + "[{\"name\":\"foo\", \"type\":\"string\"}], "
+ "\"name\":\"boring\" }", "-"));
});
}
@Test
void writingZeroJsonValues() throws Exception {
File outFile = writeToAvroFile("zerojsonvalues", schema.toString(), "");
assertEquals(0, countRecords(outFile));
}
private int countRecords(File outFile) throws IOException {
GenericDatumReader<Object> reader = new GenericDatumReader<>();
try (DataFileReader<Object> fileReader = new DataFileReader<>(outFile, reader)) {
int i = 0;
for (@SuppressWarnings("unused")
Object datum : fileReader) {
i++;
}
return i;
}
}
@Test
void differentSeparatorsBetweenJsonRecords() throws Exception {
File outFile = writeToAvroFile("separators", "{ \"type\":\"array\", \"items\":\"int\" }",
"[] [] []\n[][3] ");
assertEquals(5, countRecords(outFile));
}
public File writeToAvroFile(String testName, String schema, String json) throws Exception {
File outFile = new File(DIR, TestDataFileTools.class + "." + testName + ".avro");
try (FileOutputStream fout = new FileOutputStream(outFile)) {
try (PrintStream out = new PrintStream(fout)) {
new DataFileWriteTool().run(new ByteArrayInputStream(json.getBytes("UTF-8")), new PrintStream(out), // stdout
null, // stderr
Arrays.asList("-schema", schema, "-"));
}
}
return outFile;
}
@Test
void defaultCodec() throws Exception {
// The default codec for fromjson is null
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream err = new PrintStream(baos);
new DataFileWriteTool().run(new ByteArrayInputStream(jsonData.getBytes()), null, err, Collections.emptyList());
assertTrue(baos.toString().contains("Compression codec (default: null)"));
}
}
| 6,879 |
0 | Create_ds/avro/lang/java/tools/src/test/java/org/apache/avro | Create_ds/avro/lang/java/tools/src/test/java/org/apache/avro/tool/TestToTrevniTool.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro.tool;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Iterator;
import org.apache.avro.Schema;
import org.apache.avro.file.DataFileWriter;
import org.apache.avro.generic.GenericDatumWriter;
import org.apache.avro.util.RandomData;
import org.apache.trevni.avro.AvroColumnReader;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
public class TestToTrevniTool {
private static final long SEED = System.currentTimeMillis();
private static final int COUNT = Integer.parseInt(System.getProperty("test.count", "200"));
@TempDir
private Path dataDir;
private static final File SCHEMA_FILE = new File("../../../share/test/schemas/weather.avsc");
private String run(String... args) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream p = new PrintStream(baos);
new ToTrevniTool().run(null, p, null, Arrays.asList(args));
return baos.toString("UTF-8").replace("\r", "");
}
@Test
void test() throws Exception {
Schema schema = new Schema.Parser().parse(SCHEMA_FILE);
DataFileWriter<Object> writer = new DataFileWriter<>(new GenericDatumWriter<>());
File avroFile = dataDir.resolve("random.avro").toFile();
writer.create(schema, avroFile);
for (Object datum : new RandomData(schema, COUNT, SEED))
writer.append(datum);
writer.close();
File trevniFile = dataDir.resolve("random.trv").toFile();
run(avroFile.toString(), trevniFile.toString());
AvroColumnReader<Object> reader = new AvroColumnReader<>(new AvroColumnReader.Params(trevniFile));
Iterator<Object> found = reader.iterator();
for (Object expected : new RandomData(schema, COUNT, SEED))
assertEquals(expected, found.next());
reader.close();
}
}
| 6,880 |
0 | Create_ds/avro/lang/java/tools/src/test/java/org/apache/avro | Create_ds/avro/lang/java/tools/src/test/java/org/apache/avro/tool/TestCatTool.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro.tool;
import static java.util.Arrays.asList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.avro.Schema;
import org.apache.avro.Schema.Type;
import org.apache.avro.file.CodecFactory;
import org.apache.avro.file.DataFileStream;
import org.apache.avro.file.DataFileWriter;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericDatumReader;
import org.apache.avro.generic.GenericDatumWriter;
import org.apache.avro.generic.GenericRecord;
import org.junit.Rule;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.rules.TestName;
public class TestCatTool {
@Rule
public TestName name = new TestName();
@TempDir
public File DIR;
private static final int ROWS_IN_INPUT_FILES = 100000;
private static final int OFFSET = 1000;
private static final int LIMIT_WITHIN_INPUT_BOUNDS = 100;
private static final int LIMIT_OUT_OF_INPUT_BOUNDS = 100001;
private static final double SAMPLERATE = .01;
private static final double SAMPLERATE_TOO_SMALL = .00000001;
private final Schema INTSCHEMA = new Schema.Parser().parse("{\"type\":\"record\", " + "\"name\":\"myRecord\", "
+ "\"fields\":[ " + "{\"name\":\"value\",\"type\":\"int\"} " + "]}");
private final Schema STRINGSCHEMA = new Schema.Parser().parse("{\"type\":\"record\", " + "\"name\":\"myRecord\", "
+ "\"fields\":[ {\"name\":\"value\",\"type\":\"string\"} " + "]}");
private static final CodecFactory DEFLATE = CodecFactory.deflateCodec(9);
private static final CodecFactory SNAPPY = CodecFactory.snappyCodec();
private GenericRecord aDatum(Type ofType, int forRow) {
GenericRecord record;
switch (ofType) {
case STRING:
record = new GenericData.Record(STRINGSCHEMA);
record.put("value", String.valueOf(forRow % 100));
return record;
case INT:
record = new GenericData.Record(INTSCHEMA);
record.put("value", forRow);
return record;
default:
throw new AssertionError("I can't generate data for this type");
}
}
private File generateData(String file, Type type, Map<String, String> metadata, CodecFactory codec) throws Exception {
File inputFile = new File(DIR, file);
inputFile.deleteOnExit();
Schema schema = null;
if (type.equals(Schema.Type.INT)) {
schema = INTSCHEMA;
}
if (type.equals(Schema.Type.STRING)) {
schema = STRINGSCHEMA;
}
DataFileWriter<Object> writer = new DataFileWriter<>(new GenericDatumWriter<>(schema));
for (Entry<String, String> metadatum : metadata.entrySet()) {
writer.setMeta(metadatum.getKey(), metadatum.getValue());
}
writer.setCodec(codec);
writer.create(schema, inputFile);
for (int i = 0; i < ROWS_IN_INPUT_FILES; i++) {
writer.append(aDatum(type, i));
}
writer.close();
return inputFile;
}
private int getFirstIntDatum(File file) throws Exception {
DataFileStream<GenericRecord> reader = new DataFileStream<>(new FileInputStream(file), new GenericDatumReader<>());
int result = (Integer) reader.next().get(0);
System.out.println(result);
reader.close();
return result;
}
private int numRowsInFile(File output) throws Exception {
DataFileStream<GenericRecord> reader = new DataFileStream<>(new FileInputStream(output),
new GenericDatumReader<>());
Iterator<GenericRecord> rows = reader.iterator();
int rowcount = 0;
while (rows.hasNext()) {
++rowcount;
rows.next();
}
reader.close();
return rowcount;
}
@Test
void cat() throws Exception {
Map<String, String> metadata = new HashMap<>();
metadata.put("myMetaKey", "myMetaValue");
File input1 = generateData("input1.avro", Type.INT, metadata, DEFLATE);
File input2 = generateData("input2.avro", Type.INT, metadata, SNAPPY);
File input3 = generateData("input3.avro", Type.INT, metadata, DEFLATE);
File output = new File(DIR, name.getMethodName() + ".avro");
output.deleteOnExit();
// file input
List<String> args = asList(input1.getAbsolutePath(), input2.getAbsolutePath(), input3.getAbsolutePath(), "--offset",
String.valueOf(OFFSET), "--limit", String.valueOf(LIMIT_WITHIN_INPUT_BOUNDS), "--samplerate",
String.valueOf(SAMPLERATE), output.getAbsolutePath());
int returnCode = new CatTool().run(System.in, System.out, System.err, args);
assertEquals(0, returnCode);
assertEquals(LIMIT_WITHIN_INPUT_BOUNDS, numRowsInFile(output));
// folder input
args = asList(input1.getParentFile().getAbsolutePath(), output.getAbsolutePath(), "--offset",
String.valueOf(OFFSET), "--limit", String.valueOf(LIMIT_WITHIN_INPUT_BOUNDS));
returnCode = new CatTool().run(System.in, System.out, System.err, args);
assertEquals(0, returnCode);
assertEquals(LIMIT_WITHIN_INPUT_BOUNDS, numRowsInFile(output));
// glob input
args = asList(new File(input1.getParentFile(), "/*").getAbsolutePath(), output.getAbsolutePath(), "--offset",
String.valueOf(OFFSET), "--limit", String.valueOf(LIMIT_WITHIN_INPUT_BOUNDS));
returnCode = new CatTool().run(System.in, System.out, System.err, args);
assertEquals(0, returnCode);
assertEquals(LIMIT_WITHIN_INPUT_BOUNDS, numRowsInFile(output));
}
@Test
void limitOutOfBounds() throws Exception {
Map<String, String> metadata = new HashMap<>();
metadata.put("myMetaKey", "myMetaValue");
File input1 = generateData("input1.avro", Type.INT, metadata, DEFLATE);
File output = new File(DIR, name.getMethodName() + ".avro");
output.deleteOnExit();
List<String> args = asList(input1.getAbsolutePath(), "--offset=" + String.valueOf(OFFSET),
"--limit=" + String.valueOf(LIMIT_OUT_OF_INPUT_BOUNDS), output.getAbsolutePath());
int returnCode = new CatTool().run(System.in, System.out, System.err, args);
assertEquals(0, returnCode);
assertEquals(ROWS_IN_INPUT_FILES - OFFSET, numRowsInFile(output));
}
@Test
void samplerateAccuracy() throws Exception {
Map<String, String> metadata = new HashMap<>();
metadata.put("myMetaKey", "myMetaValue");
File input1 = generateData("input1.avro", Type.INT, metadata, DEFLATE);
File output = new File(DIR, name.getMethodName() + ".avro");
output.deleteOnExit();
List<String> args = asList(input1.getAbsolutePath(), output.getAbsolutePath(), "--offset", String.valueOf(OFFSET),
"--samplerate", String.valueOf(SAMPLERATE));
int returnCode = new CatTool().run(System.in, System.out, System.err, args);
assertEquals(0, returnCode);
assertTrue((ROWS_IN_INPUT_FILES - OFFSET) * SAMPLERATE - numRowsInFile(output) < 2,
"Outputsize is not roughly (Inputsize - Offset) * samplerate");
assertTrue((ROWS_IN_INPUT_FILES - OFFSET) * SAMPLERATE - numRowsInFile(output) > -2, "");
}
@Test
void offSetAccuracy() throws Exception {
Map<String, String> metadata = new HashMap<>();
metadata.put("myMetaKey", "myMetaValue");
File input1 = generateData("input1.avro", Type.INT, metadata, DEFLATE);
File output = new File(DIR, name.getMethodName() + ".avro");
output.deleteOnExit();
List<String> args = asList(input1.getAbsolutePath(), "--offset", String.valueOf(OFFSET), "--limit",
String.valueOf(LIMIT_WITHIN_INPUT_BOUNDS), "--samplerate", String.valueOf(SAMPLERATE),
output.getAbsolutePath());
int returnCode = new CatTool().run(System.in, System.out, System.err, args);
assertEquals(0, returnCode);
assertEquals(OFFSET, getFirstIntDatum(output), "output does not start at offset");
}
@Test
void offsetBiggerThanInput() throws Exception {
Map<String, String> metadata = new HashMap<>();
metadata.put("myMetaKey", "myMetaValue");
File input1 = generateData("input1.avro", Type.INT, metadata, DEFLATE);
File output = new File(DIR, name.getMethodName() + ".avro");
output.deleteOnExit();
List<String> args = asList(input1.getAbsolutePath(), "--offset", String.valueOf(ROWS_IN_INPUT_FILES + 1),
output.getAbsolutePath());
int returnCode = new CatTool().run(System.in, System.out, System.err, args);
assertEquals(0, returnCode);
assertEquals(0, numRowsInFile(output), "output is not empty");
}
@Test
void samplerateSmallerThanInput() throws Exception {
Map<String, String> metadata = new HashMap<>();
metadata.put("myMetaKey", "myMetaValue");
File input1 = generateData("input1.avro", Type.INT, metadata, DEFLATE);
File output = new File(DIR, name.getMethodName() + ".avro");
output.deleteOnExit();
List<String> args = asList(input1.getAbsolutePath(), output.getAbsolutePath(),
"--offset=" + Integer.toString(OFFSET), "--samplerate=" + Double.toString(SAMPLERATE_TOO_SMALL));
int returnCode = new CatTool().run(System.in, System.out, System.err, args);
assertEquals(0, returnCode);
assertEquals(OFFSET, getFirstIntDatum(output), "output should only contain the record at offset");
}
@Test
void differentSchemasFail() throws Exception {
assertThrows(IOException.class, () -> {
Map<String, String> metadata = new HashMap<>();
metadata.put("myMetaKey", "myMetaValue");
File input1 = generateData("input1.avro", Type.STRING, metadata, DEFLATE);
File input2 = generateData("input2.avro", Type.INT, metadata, DEFLATE);
File output = new File(DIR, name.getMethodName() + ".avro");
output.deleteOnExit();
List<String> args = asList(input1.getAbsolutePath(), input2.getAbsolutePath(), output.getAbsolutePath());
new CatTool().run(System.in, System.out, System.err, args);
});
}
@Test
void helpfulMessageWhenNoArgsGiven() throws Exception {
ByteArrayOutputStream buffer = new ByteArrayOutputStream(1024);
int returnCode;
try (PrintStream out = new PrintStream(buffer)) {
returnCode = new CatTool().run(System.in, out, System.err, Collections.emptyList());
}
assertEquals(0, returnCode);
assertTrue(buffer.toString().trim().length() > 200, "should have lots of help");
}
}
| 6,881 |
0 | Create_ds/avro/lang/java/tools/src/test/java/org/apache/avro | Create_ds/avro/lang/java/tools/src/test/java/org/apache/avro/tool/TestTextFileTools.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro.tool;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;
import org.apache.avro.Schema;
import org.apache.avro.Schema.Type;
import org.apache.avro.file.DataFileReader;
import org.apache.avro.generic.GenericDatumReader;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
@SuppressWarnings("deprecation")
public class TestTextFileTools {
private static final int COUNT = Integer.parseInt(System.getProperty("test.count", "10"));
private static final byte[] LINE_SEP = System.getProperty("line.separator").getBytes(StandardCharsets.UTF_8);
private static File linesFile;
private static ByteBuffer[] lines;
static Schema schema;
@TempDir
public static File DIR;
@BeforeAll
public static void writeRandomFile() throws IOException {
schema = Schema.create(Type.BYTES);
lines = new ByteBuffer[COUNT];
linesFile = new File(DIR, "random.lines");
OutputStream out = new BufferedOutputStream(new FileOutputStream(linesFile));
Random rand = new Random();
for (int j = 0; j < COUNT; j++) {
byte[] line = new byte[rand.nextInt(512)];
System.out.println("Creating line = " + line.length);
for (int i = 0; i < line.length; i++) {
int b = rand.nextInt(256);
while (b == '\n' || b == '\r')
b = rand.nextInt(256);
line[i] = (byte) b;
}
out.write(line);
out.write(LINE_SEP);
lines[j] = ByteBuffer.wrap(line);
}
out.close();
}
private void fromText(String name, String... args) throws Exception {
File avroFile = new File(DIR, name + ".avro");
ArrayList<String> arglist = new ArrayList<>(Arrays.asList(args));
arglist.add(linesFile.toString());
arglist.add(avroFile.toString());
new FromTextTool().run(null, null, null, arglist);
// Read it back, and make sure it's valid.
DataFileReader<ByteBuffer> file = new DataFileReader<>(avroFile, new GenericDatumReader<>());
int i = 0;
for (ByteBuffer line : file) {
System.out.println("Reading line = " + line.remaining());
assertEquals(line, lines[i]);
i++;
}
assertEquals(COUNT, i);
file.close();
}
@Test
void fromText() throws Exception {
fromText("null", "--codec", "null");
fromText("deflate", "--codec", "deflate");
fromText("snappy", "--codec", "snappy");
}
@AfterAll
public static void testToText() throws Exception {
toText("null");
toText("deflate");
toText("snappy");
}
private static void toText(String name) throws Exception {
File avroFile = new File(DIR, name + ".avro");
File outFile = new File(DIR, name + ".lines");
ArrayList<String> arglist = new ArrayList<>();
arglist.add(avroFile.toString());
arglist.add(outFile.toString());
new ToTextTool().run(null, null, null, arglist);
// Read it back, and make sure it's valid.
try (InputStream orig = new BufferedInputStream(new FileInputStream(linesFile))) {
try (InputStream after = new BufferedInputStream(new FileInputStream(outFile))) {
int b;
while ((b = orig.read()) != -1) {
assertEquals(b, after.read());
}
assertEquals(-1, after.read());
}
}
}
@Test
void defaultCodec() throws Exception {
// The default codec for fromtext is deflate
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream err = new PrintStream(baos);
new FromTextTool().run(null, null, err, Collections.emptyList());
assertTrue(baos.toString().contains("Compression codec (default: deflate)"));
}
}
| 6,882 |
0 | Create_ds/avro/lang/java/tools/src/test/java/org/apache/avro | Create_ds/avro/lang/java/tools/src/test/java/org/apache/avro/tool/TestRecodecTool.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro.tool;
import static java.util.Arrays.asList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.File;
import java.io.FileInputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collections;
import org.apache.avro.Schema;
import org.apache.avro.Schema.Type;
import org.apache.avro.file.DataFileReader;
import org.apache.avro.file.DataFileWriter;
import org.apache.avro.generic.GenericDatumReader;
import org.apache.avro.generic.GenericDatumWriter;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
public class TestRecodecTool {
@TempDir
public File DIR;
@Test
void recodec() throws Exception {
String metaKey = "myMetaKey";
String metaValue = "myMetaValue";
File inputFile = new File(DIR, "input.avro");
Schema schema = Schema.create(Type.STRING);
DataFileWriter<String> writer = new DataFileWriter<>(new GenericDatumWriter<String>(schema));
writer.setMeta(metaKey, metaValue).create(schema, inputFile);
// We write some garbage which should be quite compressible by deflate,
// but is complicated enough that deflate-9 will work better than deflate-1.
// These values were plucked from thin air and worked on the first try, so
// don't read too much into them.
for (int i = 0; i < 100000; i++) {
writer.append("" + i % 100);
}
writer.close();
File defaultOutputFile = new File(DIR, "default-output.avro");
File nullOutputFile = new File(DIR, "null-output.avro");
File deflateDefaultOutputFile = new File(DIR, "deflate-default-output.avro");
File deflate1OutputFile = new File(DIR, "deflate-1-output.avro");
File deflate9OutputFile = new File(DIR, "deflate-9-output.avro");
new RecodecTool().run(new FileInputStream(inputFile), new PrintStream(defaultOutputFile), null, new ArrayList<>());
new RecodecTool().run(new FileInputStream(inputFile), new PrintStream(nullOutputFile), null,
Collections.singletonList("--codec=null"));
new RecodecTool().run(new FileInputStream(inputFile), new PrintStream(deflateDefaultOutputFile), null,
Collections.singletonList("--codec=deflate"));
new RecodecTool().run(new FileInputStream(inputFile), new PrintStream(deflate1OutputFile), null,
asList("--codec=deflate", "--level=1"));
new RecodecTool().run(new FileInputStream(inputFile), new PrintStream(deflate9OutputFile), null,
asList("--codec=deflate", "--level=9"));
// We assume that metadata copying is orthogonal to codec selection, and
// so only test it for a single file.
try (DataFileReader<Void> reader = new DataFileReader<Void>(defaultOutputFile, new GenericDatumReader<>())) {
assertEquals(metaValue, reader.getMetaString(metaKey));
}
// The "default" codec should be the same as null.
assertEquals(defaultOutputFile.length(), nullOutputFile.length());
// All of the deflated files should be smaller than the null file.
assertLessThan(deflateDefaultOutputFile.length(), nullOutputFile.length());
assertLessThan(deflate1OutputFile.length(), nullOutputFile.length());
assertLessThan(deflate9OutputFile.length(), nullOutputFile.length());
// The "level 9" file should be smaller than the "level 1" file.
assertLessThan(deflate9OutputFile.length(), deflate1OutputFile.length());
}
private static void assertLessThan(long less, long more) {
if (less >= more) {
fail("Expected " + less + " to be less than " + more);
}
}
}
| 6,883 |
0 | Create_ds/avro/lang/java/tools/src/test/java/org/apache/avro | Create_ds/avro/lang/java/tools/src/test/java/org/apache/avro/tool/TestSpecificCompilerTool.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro.tool;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.BufferedReader;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
/**
* Verifies that the SpecificCompilerTool generates Java source properly
*/
public class TestSpecificCompilerTool {
// where test input/expected output comes from
private static final File TEST_DIR = new File(System.getProperty("test.compile.schema.dir", "src/test/compiler"));
// where test input comes from
private static final File TEST_INPUT_DIR = new File(TEST_DIR, "input");
// where test expected output comes from
private static final File TEST_EXPECTED_OUTPUT_DIR = new File(TEST_DIR, "output");
private static final File TEST_EXPECTED_POSITION = new File(TEST_EXPECTED_OUTPUT_DIR, "Position.java");
private static final File TEST_EXPECTED_PLAYER = new File(TEST_EXPECTED_OUTPUT_DIR, "Player.java");
private static final File TEST_EXPECTED_NO_SETTERS = new File(TEST_EXPECTED_OUTPUT_DIR, "NoSettersTest.java");
private static final File TEST_EXPECTED_OPTIONAL_GETTERS_FOR_NULLABLE_FIELDS = new File(TEST_EXPECTED_OUTPUT_DIR,
"OptionalGettersNullableFieldsTest.java");
private static final File TEST_EXPECTED_OPTIONAL_GETTERS_FOR_ALL_FIELDS = new File(TEST_EXPECTED_OUTPUT_DIR,
"OptionalGettersAllFieldsTest.java");
private static final File TEST_EXPECTED_ADD_EXTRA_OPTIONAL_GETTERS = new File(TEST_EXPECTED_OUTPUT_DIR,
"AddExtraOptionalGettersTest.java");
private static final File TEST_EXPECTED_STRING_OUTPUT_DIR = new File(TEST_DIR, "output-string");
private static final File TEST_EXPECTED_STRING_POSITION = new File(TEST_EXPECTED_STRING_OUTPUT_DIR,
"avro/examples/baseball/Position.java");
private static final File TEST_EXPECTED_STRING_PLAYER = new File(TEST_EXPECTED_STRING_OUTPUT_DIR,
"avro/examples/baseball/Player.java");
private static final File TEST_EXPECTED_STRING_NULL_SAFE_ANNOTATIONS_TEST = new File(TEST_EXPECTED_STRING_OUTPUT_DIR,
"avro/examples/baseball/NullSafeAnnotationsFieldsTest.java");
private static final File TEST_EXPECTED_STRING_FIELDTEST = new File(TEST_EXPECTED_STRING_OUTPUT_DIR,
"avro/examples/baseball/FieldTest.java");
private static final File TEST_EXPECTED_STRING_PROTO = new File(TEST_EXPECTED_STRING_OUTPUT_DIR,
"avro/examples/baseball/Proto.java");
// where test output goes
private static final File TEST_OUTPUT_DIR = new File("target/compiler/output");
private static final File TEST_OUTPUT_PLAYER = new File(TEST_OUTPUT_DIR, "avro/examples/baseball/Player.java");
private static final File TEST_OUTPUT_POSITION = new File(TEST_OUTPUT_DIR, "avro/examples/baseball/Position.java");
private static final File TEST_OUTPUT_NO_SETTERS = new File(TEST_OUTPUT_DIR,
"avro/examples/baseball/NoSettersTest.java");
private static final File TEST_OUTPUT_OPTIONAL_GETTERS_NULLABLE_FIELDS = new File(TEST_OUTPUT_DIR,
"avro/examples/baseball/OptionalGettersNullableFieldsTest.java");
private static final File TEST_OUTPUT_OPTIONAL_GETTERS_ALL_FIELDS = new File(TEST_OUTPUT_DIR,
"avro/examples/baseball/OptionalGettersAllFieldsTest.java");
private static final File TEST_OUTPUT_ADD_EXTRA_OPTIONAL_GETTERS = new File(TEST_OUTPUT_DIR,
"avro/examples/baseball/AddExtraOptionalGettersTest.java");
private static final File TEST_OUTPUT_STRING_DIR = new File("target/compiler/output-string");
private static final File TEST_OUTPUT_STRING_PLAYER = new File(TEST_OUTPUT_STRING_DIR,
"avro/examples/baseball/Player.java");
private static final File TEST_OUTPUT_STRING_POSITION = new File(TEST_OUTPUT_STRING_DIR,
"avro/examples/baseball/Position.java");
private static final File TEST_OUTPUT_STRING_FIELDTEST = new File(TEST_OUTPUT_STRING_DIR,
"avro/examples/baseball/FieldTest.java");
private static final File TEST_OUTPUT_STRING_NULL_SAFE_ANNOTATIONS_TEST = new File(TEST_OUTPUT_STRING_DIR,
"avro/examples/baseball/NullSafeAnnotationsFieldsTest.java");
private static final File TEST_OUTPUT_STRING_PROTO = new File(TEST_OUTPUT_STRING_DIR,
"avro/examples/baseball/Proto.java");
@BeforeEach
public void setUp() {
TEST_OUTPUT_DIR.delete();
}
@Test
void compileSchemaWithExcludedSetters() throws Exception {
TEST_OUTPUT_NO_SETTERS.delete();
doCompile(new String[] { "-encoding", "UTF-8", "-noSetters", "schema",
TEST_INPUT_DIR.toString() + "/nosetterstest.avsc", TEST_OUTPUT_DIR.getPath() });
assertFileMatch(TEST_EXPECTED_NO_SETTERS, TEST_OUTPUT_NO_SETTERS);
}
@Test
void compileSchemaWithOptionalGettersForNullableFieldsOnly() throws Exception {
TEST_OUTPUT_OPTIONAL_GETTERS_NULLABLE_FIELDS.delete();
doCompile(new String[] { "-encoding", "UTF-8", "-optionalGetters", "only_nullable_fields", "schema",
TEST_INPUT_DIR.toString() + "/optionalgettersnullablefieldstest.avsc", TEST_OUTPUT_DIR.getPath() });
assertFileMatch(TEST_EXPECTED_OPTIONAL_GETTERS_FOR_NULLABLE_FIELDS, TEST_OUTPUT_OPTIONAL_GETTERS_NULLABLE_FIELDS);
}
@Test
void compileSchemaWithNullSafeAnnotationsFields() throws Exception {
TEST_OUTPUT_STRING_NULL_SAFE_ANNOTATIONS_TEST.delete();
doCompile(new String[] { "-encoding", "UTF-8", "-nullSafeAnnotations", "-string", "schema",
TEST_INPUT_DIR.toString() + "/nullsafeannotationsfieldstest.avsc", TEST_OUTPUT_STRING_DIR.getPath() });
assertFileMatch(TEST_EXPECTED_STRING_NULL_SAFE_ANNOTATIONS_TEST, TEST_OUTPUT_STRING_NULL_SAFE_ANNOTATIONS_TEST);
}
@Test
void compileSchemaWithOptionalGettersForAllFields() throws Exception {
TEST_OUTPUT_OPTIONAL_GETTERS_ALL_FIELDS.delete();
doCompile(new String[] { "-encoding", "UTF-8", "-optionalGetters", "all_fields", "schema",
TEST_INPUT_DIR.toString() + "/optionalgettersallfieldstest.avsc", TEST_OUTPUT_DIR.getPath() });
assertFileMatch(TEST_EXPECTED_OPTIONAL_GETTERS_FOR_ALL_FIELDS, TEST_OUTPUT_OPTIONAL_GETTERS_ALL_FIELDS);
}
@Test
void compileSchemaWithAddExtraOptionalGetters() throws Exception {
TEST_OUTPUT_ADD_EXTRA_OPTIONAL_GETTERS.delete();
doCompile(new String[] { "-encoding", "UTF-8", "-addExtraOptionalGetters", "schema",
TEST_INPUT_DIR.toString() + "/addextraoptionalgetterstest.avsc", TEST_OUTPUT_DIR.getPath() });
assertFileMatch(TEST_EXPECTED_ADD_EXTRA_OPTIONAL_GETTERS, TEST_OUTPUT_ADD_EXTRA_OPTIONAL_GETTERS);
}
@Test
void compileSchemaSingleFile() throws Exception {
doCompile(new String[] { "-encoding", "UTF-8", "schema", TEST_INPUT_DIR.toString() + "/position.avsc",
TEST_OUTPUT_DIR.getPath() });
assertFileMatch(TEST_EXPECTED_POSITION, TEST_OUTPUT_POSITION);
}
@Test
void compileSchemaTwoFiles() throws Exception {
doCompile(new String[] { "-encoding", "UTF-8", "schema", TEST_INPUT_DIR.toString() + "/position.avsc",
TEST_INPUT_DIR.toString() + "/player.avsc", TEST_OUTPUT_DIR.getPath() });
assertFileMatch(TEST_EXPECTED_POSITION, TEST_OUTPUT_POSITION);
assertFileMatch(TEST_EXPECTED_PLAYER, TEST_OUTPUT_PLAYER);
}
@Test
void compileSchemaFileAndDirectory() throws Exception {
doCompile(new String[] { "-encoding", "UTF-8", "schema", TEST_INPUT_DIR.toString() + "/position.avsc",
TEST_INPUT_DIR.toString(), TEST_OUTPUT_DIR.getPath() });
assertFileMatch(TEST_EXPECTED_POSITION, TEST_OUTPUT_POSITION);
assertFileMatch(TEST_EXPECTED_PLAYER, TEST_OUTPUT_PLAYER);
}
@Test
void compileSchemasUsingString() throws Exception {
doCompile(new String[] { "-encoding", "UTF-8", "-string", "schema", TEST_INPUT_DIR.toString() + "/position.avsc",
TEST_INPUT_DIR.toString() + "/player.avsc", TEST_OUTPUT_STRING_DIR.getPath() });
assertFileMatch(TEST_EXPECTED_STRING_POSITION, TEST_OUTPUT_STRING_POSITION);
assertFileMatch(TEST_EXPECTED_STRING_PLAYER, TEST_OUTPUT_STRING_PLAYER);
}
@Test
void compileSchemasWithVariousFieldTypes() throws Exception {
doCompile(new String[] { "-encoding", "UTF-8", "-string", "schema", TEST_INPUT_DIR.toString() + "/fieldtest.avsc",
TEST_INPUT_DIR.toString() + "/fieldtest.avsc", TEST_OUTPUT_STRING_DIR.getPath() });
assertFileMatch(TEST_EXPECTED_STRING_FIELDTEST, TEST_OUTPUT_STRING_FIELDTEST);
}
@Test
void orderingOfFlags() throws Exception {
// Order of Flags as per initial implementation
doCompile(new String[] { "-encoding", "UTF-8", "-string", "-bigDecimal", "schema",
TEST_INPUT_DIR.toString() + "/fieldtest.avsc", TEST_INPUT_DIR.toString() + "/fieldtest.avsc",
TEST_OUTPUT_STRING_DIR.getPath() });
assertFileMatch(TEST_EXPECTED_STRING_FIELDTEST, TEST_OUTPUT_STRING_FIELDTEST);
// Change order of encoding and string
doCompile(new String[] { "-string", "-encoding", "UTF-8", "-bigDecimal", "schema",
TEST_INPUT_DIR.toString() + "/fieldtest.avsc", TEST_INPUT_DIR.toString() + "/fieldtest.avsc",
TEST_OUTPUT_STRING_DIR.getPath() });
assertFileMatch(TEST_EXPECTED_STRING_FIELDTEST, TEST_OUTPUT_STRING_FIELDTEST);
// Change order of -string and -bigDecimal
doCompile(new String[] { "-bigDecimal", "-encoding", "UTF-8", "-string", "schema",
TEST_INPUT_DIR.toString() + "/fieldtest.avsc", TEST_INPUT_DIR.toString() + "/fieldtest.avsc",
TEST_OUTPUT_STRING_DIR.getPath() });
assertFileMatch(TEST_EXPECTED_STRING_FIELDTEST, TEST_OUTPUT_STRING_FIELDTEST);
// Keep encoding at the end
doCompile(new String[] { "-bigDecimal", "-string", "-encoding", "UTF-8", "schema",
TEST_INPUT_DIR.toString() + "/fieldtest.avsc", TEST_INPUT_DIR.toString() + "/fieldtest.avsc",
TEST_OUTPUT_STRING_DIR.getPath() });
assertFileMatch(TEST_EXPECTED_STRING_FIELDTEST, TEST_OUTPUT_STRING_FIELDTEST);
}
@Test
void compileProtocol() throws Exception {
doCompile(new String[] { "-encoding", "UTF-8", "protocol", TEST_INPUT_DIR.toString() + "/proto.avpr",
TEST_OUTPUT_STRING_DIR.getPath() });
assertFileMatch(TEST_EXPECTED_STRING_PROTO, TEST_OUTPUT_STRING_PROTO);
}
// Runs the actual compiler tool with the given input args
private void doCompile(String[] args) throws Exception {
SpecificCompilerTool tool = new SpecificCompilerTool();
tool.run(null, null, null, Arrays.asList((args)));
}
/**
* Verify that the generated Java files match the expected. This approach has
* room for improvement, since we're currently just verify that the text
* matches, which can be brittle if the code generation formatting or method
* ordering changes for example. A better approach would be to compile the
* sources and do a deeper comparison.
*
* See
* https://download.oracle.com/javase/6/docs/api/javax/tools/JavaCompiler.html
*/
private static void assertFileMatch(File expected, File found) throws IOException {
assertEquals(readFile(expected), readFile(found),
"Found file: " + found + " does not match expected file: " + expected);
}
/**
* Not the best implementation, but does the job. Building full strings of the
* file content and comparing provides nice diffs via JUnit when failures occur.
*/
private static String readFile(File file) throws IOException {
BufferedReader reader = new BufferedReader(
new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
String line = null;
boolean first = true;
while ((line = reader.readLine()) != null) {
if (!first) {
sb.append("\n");
first = false;
}
sb.append(line);
}
reader.close();
return sb.toString();
}
}
| 6,884 |
0 | Create_ds/avro/lang/java/tools/src/test/java/org/apache/avro | Create_ds/avro/lang/java/tools/src/test/java/org/apache/avro/tool/TestUtil.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro.tool;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.lang.reflect.Method;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import joptsimple.OptionSpec;
import org.apache.avro.file.Codec;
import org.apache.avro.file.CodecFactory;
import org.apache.avro.file.ZstandardCodec;
import org.junit.Rule;
import org.junit.jupiter.api.Test;
import org.junit.rules.TestName;
public class TestUtil {
@Rule
public TestName name = new TestName();
private void zstandardCompressionLevel(int level) throws Exception {
OptionParser optParser = new OptionParser();
OptionSpec<String> codecOpt = Util.compressionCodecOption(optParser);
OptionSpec<Integer> levelOpt = Util.compressionLevelOption(optParser);
OptionSet opts = optParser.parse(new String[] { "--codec", "zstandard", "--level", String.valueOf(level) });
CodecFactory codecFactory = Util.codecFactory(opts, codecOpt, levelOpt);
Method createInstance = CodecFactory.class.getDeclaredMethod("createInstance");
createInstance.setAccessible(true);
Codec codec = (ZstandardCodec) createInstance.invoke(codecFactory);
assertEquals(String.format("zstandard[%d]", level), codec.toString());
}
@Test
void codecFactoryZstandardCompressionLevel() throws Exception {
zstandardCompressionLevel(1);
zstandardCompressionLevel(CodecFactory.DEFAULT_ZSTANDARD_LEVEL);
}
}
| 6,885 |
0 | Create_ds/avro/lang/java/tools/src/test/java/org/apache/avro | Create_ds/avro/lang/java/tools/src/test/java/org/apache/avro/tool/TestTetherTool.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro.tool;
import static java.util.Arrays.asList;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.FileWriter;
import org.apache.avro.Schema;
import org.apache.avro.file.DataFileStream;
import org.apache.avro.io.DatumReader;
import org.apache.avro.mapred.Pair;
import org.apache.avro.mapred.WordCountUtil;
import org.apache.avro.specific.SpecificDatumReader;
import org.apache.avro.util.Utf8;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapred.JobConf;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
public class TestTetherTool {
@TempDir
public File INPUT_DIR;
@TempDir
public File OUTPUT_DIR;
/**
* Test that the tether tool works with the mapreduce example
* <p>
* TODO: How can we ensure that when we run, the WordCountTether example has
* been properly compiled?
*/
@Test
void test() throws Exception {
// Create the schema files.
Schema outscheme = new Pair<Utf8, Long>(new Utf8(""), 0L).getSchema();
// we need to write the schemas to a file
File midscfile = new File(INPUT_DIR.getPath(), "midschema.avpr");
try (FileWriter hf = new FileWriter(midscfile)) {
hf.write(outscheme.toString());
}
JobConf job = new JobConf();
String inputPathStr = INPUT_DIR.getPath();
String outputPathStr = OUTPUT_DIR.getPath();
Path outputPath = new Path(outputPathStr);
outputPath.getFileSystem(job).delete(outputPath, true);
// create the input file
WordCountUtil.writeLinesFile(inputPathStr + "/lines.avro");
// create a string of the arguments
String execargs = "-classpath " + System.getProperty("java.class.path");
execargs += " org.apache.avro.mapred.tether.WordCountTask";
// Create a list of the arguments to pass to the tull run method
java.util.List<String> runargs = new java.util.ArrayList<>();
runargs.addAll(java.util.Arrays.asList("--program", "java"));
runargs.addAll(asList("--exec_args", '"' + execargs + '"'));
runargs.addAll(asList("--exec_cached", "false"));
runargs.addAll(asList("--in", inputPathStr));
runargs.addAll(asList("--out", outputPath.toString()));
runargs.addAll(asList("--outschema", midscfile.toString()));
TetherTool tool = new TetherTool();
tool.run(null, null, System.err, runargs);
// TODO:: We should probably do some validation
// validate the output
int numWords = 0;
DatumReader<Pair<Utf8, Long>> reader = new SpecificDatumReader<>();
try (InputStream cin = new BufferedInputStream(new FileInputStream(outputPathStr + "/part-00000.avro"));
DataFileStream<Pair<Utf8, Long>> counts = new DataFileStream<>(cin, reader)) {
for (Pair<Utf8, Long> wc : counts) {
Assertions.assertEquals(WordCountUtil.COUNTS.get(wc.key().toString()), wc.value(), wc.key().toString());
numWords++;
}
}
Assertions.assertEquals(WordCountUtil.COUNTS.size(), numWords);
}
}
| 6,886 |
0 | Create_ds/avro/lang/java/tools/src/test/java/org/apache/avro | Create_ds/avro/lang/java/tools/src/test/java/org/apache/avro/tool/TestDataFileRepairTool.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro.tool;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.Arrays;
import org.apache.avro.Schema;
import org.apache.avro.file.DataFileConstants;
import org.apache.avro.file.DataFileReader;
import org.apache.avro.file.DataFileWriter;
import org.apache.avro.generic.GenericDatumReader;
import org.apache.avro.generic.GenericDatumWriter;
import org.apache.avro.io.BinaryData;
import org.apache.avro.util.Utf8;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
public class TestDataFileRepairTool {
@TempDir
public static File DIR;
private static final Schema SCHEMA = Schema.create(Schema.Type.STRING);
private static File corruptBlockFile;
private static File corruptRecordFile;
private File repairedFile;
@BeforeAll
public static void writeCorruptFile() throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
long pos;
// Write a data file
try (DataFileWriter<Utf8> w = new DataFileWriter<>(new GenericDatumWriter<>(SCHEMA))) {
w.create(SCHEMA, baos);
w.append(new Utf8("apple"));
w.append(new Utf8("banana"));
w.append(new Utf8("celery"));
w.sync();
w.append(new Utf8("date"));
w.append(new Utf8("endive"));
w.append(new Utf8("fig"));
pos = w.sync();
w.append(new Utf8("guava"));
w.append(new Utf8("hazelnut"));
}
byte[] original = baos.toByteArray();
// Corrupt the second block by inserting some zero bytes before the sync marker
int corruptPosition = (int) pos - DataFileConstants.SYNC_SIZE;
int corruptedBytes = 3;
byte[] corrupted = new byte[original.length + corruptedBytes];
System.arraycopy(original, 0, corrupted, 0, corruptPosition);
System.arraycopy(original, corruptPosition, corrupted, corruptPosition + corruptedBytes,
original.length - corruptPosition);
corruptBlockFile = new File(DIR, "corruptBlock.avro");
corruptBlockFile.deleteOnExit();
try (FileOutputStream out = new FileOutputStream(corruptBlockFile)) {
out.write(corrupted);
}
// Corrupt the "endive" record by changing the length of the string to be
// negative
corruptPosition = (int) pos - DataFileConstants.SYNC_SIZE - (1 + "fig".length() + 1 + "endive".length());
corrupted = new byte[original.length];
System.arraycopy(original, 0, corrupted, 0, original.length);
BinaryData.encodeLong(-1, corrupted, corruptPosition);
corruptRecordFile = new File(DIR, "corruptRecord.avro");
corruptRecordFile.deleteOnExit();
try (FileOutputStream out = new FileOutputStream(corruptRecordFile)) {
out.write(corrupted);
}
}
@BeforeEach
public void setUp() {
repairedFile = new File(DIR, "repaired.avro");
}
private String run(Tool tool, String... args) throws Exception {
return run(tool, null, args);
}
private String run(Tool tool, InputStream stdin, String... args) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
PrintStream stdout = new PrintStream(out);
tool.run(stdin, stdout, System.err, Arrays.asList(args));
return out.toString("UTF-8").replace("\r", "");
}
@Test
void reportCorruptBlock() throws Exception {
String output = run(new DataFileRepairTool(), "-o", "report", corruptBlockFile.getPath());
assertTrue(output.contains("Number of blocks: 2 Number of corrupt blocks: 1"), output);
assertTrue(output.contains("Number of records: 5 Number of corrupt records: 0"), output);
}
@Test
void reportCorruptRecord() throws Exception {
String output = run(new DataFileRepairTool(), "-o", "report", corruptRecordFile.getPath());
assertTrue(output.contains("Number of blocks: 3 Number of corrupt blocks: 1"), output);
assertTrue(output.contains("Number of records: 8 Number of corrupt records: 2"), output);
}
@Test
void repairAllCorruptBlock() throws Exception {
String output = run(new DataFileRepairTool(), "-o", "all", corruptBlockFile.getPath(), repairedFile.getPath());
assertTrue(output.contains("Number of blocks: 2 Number of corrupt blocks: 1"), output);
assertTrue(output.contains("Number of records: 5 Number of corrupt records: 0"), output);
checkFileContains(repairedFile, "apple", "banana", "celery", "guava", "hazelnut");
}
@Test
void repairAllCorruptRecord() throws Exception {
String output = run(new DataFileRepairTool(), "-o", "all", corruptRecordFile.getPath(), repairedFile.getPath());
assertTrue(output.contains("Number of blocks: 3 Number of corrupt blocks: 1"), output);
assertTrue(output.contains("Number of records: 8 Number of corrupt records: 2"), output);
checkFileContains(repairedFile, "apple", "banana", "celery", "date", "guava", "hazelnut");
}
@Test
void repairPriorCorruptBlock() throws Exception {
String output = run(new DataFileRepairTool(), "-o", "prior", corruptBlockFile.getPath(), repairedFile.getPath());
assertTrue(output.contains("Number of blocks: 2 Number of corrupt blocks: 1"), output);
assertTrue(output.contains("Number of records: 5 Number of corrupt records: 0"), output);
checkFileContains(repairedFile, "apple", "banana", "celery");
}
@Test
void repairPriorCorruptRecord() throws Exception {
String output = run(new DataFileRepairTool(), "-o", "prior", corruptRecordFile.getPath(), repairedFile.getPath());
assertTrue(output.contains("Number of blocks: 3 Number of corrupt blocks: 1"), output);
assertTrue(output.contains("Number of records: 8 Number of corrupt records: 2"), output);
checkFileContains(repairedFile, "apple", "banana", "celery", "date");
}
@Test
void repairAfterCorruptBlock() throws Exception {
String output = run(new DataFileRepairTool(), "-o", "after", corruptBlockFile.getPath(), repairedFile.getPath());
assertTrue(output.contains("Number of blocks: 2 Number of corrupt blocks: 1"), output);
assertTrue(output.contains("Number of records: 5 Number of corrupt records: 0"), output);
checkFileContains(repairedFile, "guava", "hazelnut");
}
@Test
void repairAfterCorruptRecord() throws Exception {
String output = run(new DataFileRepairTool(), "-o", "after", corruptRecordFile.getPath(), repairedFile.getPath());
assertTrue(output.contains("Number of blocks: 3 Number of corrupt blocks: 1"), output);
assertTrue(output.contains("Number of records: 8 Number of corrupt records: 2"), output);
checkFileContains(repairedFile, "guava", "hazelnut");
}
private void checkFileContains(File repairedFile, String... lines) throws IOException {
DataFileReader<Object> r = new DataFileReader<>(repairedFile, new GenericDatumReader<>(SCHEMA));
for (String line : lines) {
assertEquals(line, r.next().toString());
}
assertFalse(r.hasNext());
r.close();
}
}
| 6,887 |
0 | Create_ds/avro/lang/java/tools/src/test/java/org/apache/avro | Create_ds/avro/lang/java/tools/src/test/java/org/apache/avro/tool/TestCreateRandomFileTool.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro.tool;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Iterator;
import org.apache.avro.Schema;
import org.apache.avro.file.DataFileReader;
import org.apache.avro.file.DataFileStream;
import org.apache.avro.generic.GenericDatumReader;
import org.apache.avro.util.RandomData;
import org.apache.trevni.TestUtil;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class TestCreateRandomFileTool {
private static final String COUNT = System.getProperty("test.count", "200");
@TempDir
private Path dataDir;
private static final File SCHEMA_FILE = new File("../../../share/test/schemas/weather.avsc");
private final Schema.Parser schemaParser = new Schema.Parser();
private static final long SEED = System.currentTimeMillis();
private ByteArrayOutputStream out;
private ByteArrayOutputStream err;
@BeforeEach
public void before() {
out = new ByteArrayOutputStream();
err = new ByteArrayOutputStream();
}
@AfterEach
public void after() throws Exception {
out.close();
err.close();
}
private int run(List<String> args) throws Exception {
PrintStream output = new PrintStream(out);
PrintStream saveOut = System.out;
PrintStream error = new PrintStream(err);
PrintStream saveErr = System.err;
try {
System.setOut(output);
System.setErr(error);
return new CreateRandomFileTool().run(null, output, error, args);
} finally {
System.setOut(saveOut);
System.setErr(saveErr);
}
}
private void check(String... extraArgs) throws Exception {
ArrayList<String> args = new ArrayList<>();
File outFile = dataDir.resolve("random.avro").toFile();
args.addAll(Arrays.asList(outFile.toString(), "--count", COUNT, "--schema-file", SCHEMA_FILE.toString(), "--seed",
Long.toString(SEED)));
args.addAll(Arrays.asList(extraArgs));
run(args);
DataFileReader<Object> reader = new DataFileReader<>(outFile, new GenericDatumReader<>());
Iterator<Object> found = reader.iterator();
for (Object expected : new RandomData(schemaParser.parse(SCHEMA_FILE), Integer.parseInt(COUNT), SEED))
assertEquals(expected, found.next());
reader.close();
}
private void checkMissingCount(String... extraArgs) throws Exception {
ArrayList<String> args = new ArrayList<>();
File outFile = dataDir.resolve("random.avro").toFile();
args.addAll(
Arrays.asList(outFile.toString(), "--schema-file", SCHEMA_FILE.toString(), "--seed", Long.toString(SEED)));
args.addAll(Arrays.asList(extraArgs));
run(args);
assertTrue(err.toString().contains("Need count (--count)"));
}
@Test
void simple() throws Exception {
check();
}
@Test
void codec() throws Exception {
check("--codec", "snappy");
}
@Test
void missingCountParameter() throws Exception {
checkMissingCount();
}
@Test
void stdOut() throws Exception {
TestUtil.resetRandomSeed();
run(Arrays.asList("-", "--count", COUNT, "--schema-file", SCHEMA_FILE.toString(), "--seed", Long.toString(SEED)));
byte[] file = out.toByteArray();
DataFileStream<Object> reader = new DataFileStream<>(new ByteArrayInputStream(file), new GenericDatumReader<>());
Iterator<Object> found = reader.iterator();
for (Object expected : new RandomData(schemaParser.parse(SCHEMA_FILE), Integer.parseInt(COUNT), SEED))
assertEquals(expected, found.next());
reader.close();
}
@Test
void defaultCodec() throws Exception {
// The default codec for random is deflate
run(Collections.emptyList());
assertTrue(err.toString().contains("Compression codec (default: deflate)"));
}
}
| 6,888 |
0 | Create_ds/avro/lang/java/tools/src/test/compiler | Create_ds/avro/lang/java/tools/src/test/compiler/output-string/Position.java | /**
* Autogenerated by Avro
*
* DO NOT EDIT DIRECTLY
*/
package avro.examples.baseball;
@org.apache.avro.specific.AvroGenerated
public enum Position implements org.apache.avro.generic.GenericEnumSymbol<Position> {
P, C, B1, B2, B3, SS, LF, CF, RF, DH ;
public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"enum\",\"name\":\"Position\",\"namespace\":\"avro.examples.baseball\",\"symbols\":[\"P\",\"C\",\"B1\",\"B2\",\"B3\",\"SS\",\"LF\",\"CF\",\"RF\",\"DH\"]}");
public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; }
public org.apache.avro.Schema getSchema() { return SCHEMA$; }
}
| 6,889 |
0 | Create_ds/avro/lang/java/tools/src/test/compiler/output-string/avro/examples | Create_ds/avro/lang/java/tools/src/test/compiler/output-string/avro/examples/baseball/NullSafeAnnotationsFieldsTest.java | /**
* Autogenerated by Avro
*
* DO NOT EDIT DIRECTLY
*/
package avro.examples.baseball;
import org.apache.avro.generic.GenericArray;
import org.apache.avro.specific.SpecificData;
import org.apache.avro.util.Utf8;
import org.apache.avro.message.BinaryMessageEncoder;
import org.apache.avro.message.BinaryMessageDecoder;
import org.apache.avro.message.SchemaStore;
/** Test that @org.jetbrains.annotations.Nullable and @org.jetbrains.annotations.NotNull annotations are created for all fields */
@org.apache.avro.specific.AvroGenerated
public class NullSafeAnnotationsFieldsTest extends org.apache.avro.specific.SpecificRecordBase implements org.apache.avro.specific.SpecificRecord {
private static final long serialVersionUID = 2020521726426674816L;
public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"record\",\"name\":\"NullSafeAnnotationsFieldsTest\",\"namespace\":\"avro.examples.baseball\",\"doc\":\"Test that @org.jetbrains.annotations.Nullable and @org.jetbrains.annotations.NotNull annotations are created for all fields\",\"fields\":[{\"name\":\"name\",\"type\":{\"type\":\"string\",\"avro.java.string\":\"String\"}},{\"name\":\"nullable_name\",\"type\":[{\"type\":\"string\",\"avro.java.string\":\"String\"},\"null\"]},{\"name\":\"favorite_number\",\"type\":\"int\"},{\"name\":\"nullable_favorite_number\",\"type\":[\"int\",\"null\"]}]}");
public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; }
private static final SpecificData MODEL$ = new SpecificData();
private static final BinaryMessageEncoder<NullSafeAnnotationsFieldsTest> ENCODER =
new BinaryMessageEncoder<>(MODEL$, SCHEMA$);
private static final BinaryMessageDecoder<NullSafeAnnotationsFieldsTest> DECODER =
new BinaryMessageDecoder<>(MODEL$, SCHEMA$);
/**
* Return the BinaryMessageEncoder instance used by this class.
* @return the message encoder used by this class
*/
public static BinaryMessageEncoder<NullSafeAnnotationsFieldsTest> getEncoder() {
return ENCODER;
}
/**
* Return the BinaryMessageDecoder instance used by this class.
* @return the message decoder used by this class
*/
public static BinaryMessageDecoder<NullSafeAnnotationsFieldsTest> getDecoder() {
return DECODER;
}
/**
* Create a new BinaryMessageDecoder instance for this class that uses the specified {@link SchemaStore}.
* @param resolver a {@link SchemaStore} used to find schemas by fingerprint
* @return a BinaryMessageDecoder instance for this class backed by the given SchemaStore
*/
public static BinaryMessageDecoder<NullSafeAnnotationsFieldsTest> createDecoder(SchemaStore resolver) {
return new BinaryMessageDecoder<>(MODEL$, SCHEMA$, resolver);
}
/**
* Serializes this NullSafeAnnotationsFieldsTest to a ByteBuffer.
* @return a buffer holding the serialized data for this instance
* @throws java.io.IOException if this instance could not be serialized
*/
public java.nio.ByteBuffer toByteBuffer() throws java.io.IOException {
return ENCODER.encode(this);
}
/**
* Deserializes a NullSafeAnnotationsFieldsTest from a ByteBuffer.
* @param b a byte buffer holding serialized data for an instance of this class
* @return a NullSafeAnnotationsFieldsTest instance decoded from the given buffer
* @throws java.io.IOException if the given bytes could not be deserialized into an instance of this class
*/
public static NullSafeAnnotationsFieldsTest fromByteBuffer(
java.nio.ByteBuffer b) throws java.io.IOException {
return DECODER.decode(b);
}
private java.lang.String name;
private java.lang.String nullable_name;
private int favorite_number;
private java.lang.Integer nullable_favorite_number;
/**
* Default constructor. Note that this does not initialize fields
* to their default values from the schema. If that is desired then
* one should use <code>newBuilder()</code>.
*/
public NullSafeAnnotationsFieldsTest() {}
/**
* All-args constructor.
* @param name The new value for name
* @param nullable_name The new value for nullable_name
* @param favorite_number The new value for favorite_number
* @param nullable_favorite_number The new value for nullable_favorite_number
*/
public NullSafeAnnotationsFieldsTest(@org.jetbrains.annotations.NotNull java.lang.String name, @org.jetbrains.annotations.Nullable java.lang.String nullable_name, @org.jetbrains.annotations.NotNull java.lang.Integer favorite_number, @org.jetbrains.annotations.Nullable java.lang.Integer nullable_favorite_number) {
this.name = name;
this.nullable_name = nullable_name;
this.favorite_number = favorite_number;
this.nullable_favorite_number = nullable_favorite_number;
}
@Override
public org.apache.avro.specific.SpecificData getSpecificData() { return MODEL$; }
@Override
public org.apache.avro.Schema getSchema() { return SCHEMA$; }
// Used by DatumWriter. Applications should not call.
@Override
public java.lang.Object get(int field$) {
switch (field$) {
case 0: return name;
case 1: return nullable_name;
case 2: return favorite_number;
case 3: return nullable_favorite_number;
default: throw new IndexOutOfBoundsException("Invalid index: " + field$);
}
}
// Used by DatumReader. Applications should not call.
@Override
@SuppressWarnings(value="unchecked")
public void put(int field$, java.lang.Object value$) {
switch (field$) {
case 0: name = value$ != null ? value$.toString() : null; break;
case 1: nullable_name = value$ != null ? value$.toString() : null; break;
case 2: favorite_number = (java.lang.Integer)value$; break;
case 3: nullable_favorite_number = (java.lang.Integer)value$; break;
default: throw new IndexOutOfBoundsException("Invalid index: " + field$);
}
}
/**
* Gets the value of the 'name' field.
* @return The value of the 'name' field.
*/
@org.jetbrains.annotations.NotNull
public java.lang.String getName() {
return name;
}
/**
* Sets the value of the 'name' field.
* @param value the value to set.
*/
public void setName(@org.jetbrains.annotations.NotNull java.lang.String value) {
this.name = value;
}
/**
* Gets the value of the 'nullable_name' field.
* @return The value of the 'nullable_name' field.
*/
@org.jetbrains.annotations.Nullable
public java.lang.String getNullableName() {
return nullable_name;
}
/**
* Sets the value of the 'nullable_name' field.
* @param value the value to set.
*/
public void setNullableName(@org.jetbrains.annotations.Nullable java.lang.String value) {
this.nullable_name = value;
}
/**
* Gets the value of the 'favorite_number' field.
* @return The value of the 'favorite_number' field.
*/
@org.jetbrains.annotations.NotNull
public int getFavoriteNumber() {
return favorite_number;
}
/**
* Sets the value of the 'favorite_number' field.
* @param value the value to set.
*/
public void setFavoriteNumber(@org.jetbrains.annotations.NotNull int value) {
this.favorite_number = value;
}
/**
* Gets the value of the 'nullable_favorite_number' field.
* @return The value of the 'nullable_favorite_number' field.
*/
@org.jetbrains.annotations.Nullable
public java.lang.Integer getNullableFavoriteNumber() {
return nullable_favorite_number;
}
/**
* Sets the value of the 'nullable_favorite_number' field.
* @param value the value to set.
*/
public void setNullableFavoriteNumber(@org.jetbrains.annotations.Nullable java.lang.Integer value) {
this.nullable_favorite_number = value;
}
/**
* Creates a new NullSafeAnnotationsFieldsTest RecordBuilder.
* @return A new NullSafeAnnotationsFieldsTest RecordBuilder
*/
public static avro.examples.baseball.NullSafeAnnotationsFieldsTest.Builder newBuilder() {
return new avro.examples.baseball.NullSafeAnnotationsFieldsTest.Builder();
}
/**
* Creates a new NullSafeAnnotationsFieldsTest RecordBuilder by copying an existing Builder.
* @param other The existing builder to copy.
* @return A new NullSafeAnnotationsFieldsTest RecordBuilder
*/
public static avro.examples.baseball.NullSafeAnnotationsFieldsTest.Builder newBuilder(avro.examples.baseball.NullSafeAnnotationsFieldsTest.Builder other) {
if (other == null) {
return new avro.examples.baseball.NullSafeAnnotationsFieldsTest.Builder();
} else {
return new avro.examples.baseball.NullSafeAnnotationsFieldsTest.Builder(other);
}
}
/**
* Creates a new NullSafeAnnotationsFieldsTest RecordBuilder by copying an existing NullSafeAnnotationsFieldsTest instance.
* @param other The existing instance to copy.
* @return A new NullSafeAnnotationsFieldsTest RecordBuilder
*/
public static avro.examples.baseball.NullSafeAnnotationsFieldsTest.Builder newBuilder(avro.examples.baseball.NullSafeAnnotationsFieldsTest other) {
if (other == null) {
return new avro.examples.baseball.NullSafeAnnotationsFieldsTest.Builder();
} else {
return new avro.examples.baseball.NullSafeAnnotationsFieldsTest.Builder(other);
}
}
/**
* RecordBuilder for NullSafeAnnotationsFieldsTest instances.
*/
@org.apache.avro.specific.AvroGenerated
public static class Builder extends org.apache.avro.specific.SpecificRecordBuilderBase<NullSafeAnnotationsFieldsTest>
implements org.apache.avro.data.RecordBuilder<NullSafeAnnotationsFieldsTest> {
private java.lang.String name;
private java.lang.String nullable_name;
private int favorite_number;
private java.lang.Integer nullable_favorite_number;
/** Creates a new Builder */
private Builder() {
super(SCHEMA$, MODEL$);
}
/**
* Creates a Builder by copying an existing Builder.
* @param other The existing Builder to copy.
*/
private Builder(avro.examples.baseball.NullSafeAnnotationsFieldsTest.Builder other) {
super(other);
if (isValidValue(fields()[0], other.name)) {
this.name = data().deepCopy(fields()[0].schema(), other.name);
fieldSetFlags()[0] = other.fieldSetFlags()[0];
}
if (isValidValue(fields()[1], other.nullable_name)) {
this.nullable_name = data().deepCopy(fields()[1].schema(), other.nullable_name);
fieldSetFlags()[1] = other.fieldSetFlags()[1];
}
if (isValidValue(fields()[2], other.favorite_number)) {
this.favorite_number = data().deepCopy(fields()[2].schema(), other.favorite_number);
fieldSetFlags()[2] = other.fieldSetFlags()[2];
}
if (isValidValue(fields()[3], other.nullable_favorite_number)) {
this.nullable_favorite_number = data().deepCopy(fields()[3].schema(), other.nullable_favorite_number);
fieldSetFlags()[3] = other.fieldSetFlags()[3];
}
}
/**
* Creates a Builder by copying an existing NullSafeAnnotationsFieldsTest instance
* @param other The existing instance to copy.
*/
private Builder(avro.examples.baseball.NullSafeAnnotationsFieldsTest other) {
super(SCHEMA$, MODEL$);
if (isValidValue(fields()[0], other.name)) {
this.name = data().deepCopy(fields()[0].schema(), other.name);
fieldSetFlags()[0] = true;
}
if (isValidValue(fields()[1], other.nullable_name)) {
this.nullable_name = data().deepCopy(fields()[1].schema(), other.nullable_name);
fieldSetFlags()[1] = true;
}
if (isValidValue(fields()[2], other.favorite_number)) {
this.favorite_number = data().deepCopy(fields()[2].schema(), other.favorite_number);
fieldSetFlags()[2] = true;
}
if (isValidValue(fields()[3], other.nullable_favorite_number)) {
this.nullable_favorite_number = data().deepCopy(fields()[3].schema(), other.nullable_favorite_number);
fieldSetFlags()[3] = true;
}
}
/**
* Gets the value of the 'name' field.
* @return The value.
*/
public java.lang.String getName() {
return name;
}
/**
* Sets the value of the 'name' field.
* @param value The value of 'name'.
* @return This builder.
*/
public avro.examples.baseball.NullSafeAnnotationsFieldsTest.Builder setName(@org.jetbrains.annotations.NotNull java.lang.String value) {
validate(fields()[0], value);
this.name = value;
fieldSetFlags()[0] = true;
return this;
}
/**
* Checks whether the 'name' field has been set.
* @return True if the 'name' field has been set, false otherwise.
*/
public boolean hasName() {
return fieldSetFlags()[0];
}
/**
* Clears the value of the 'name' field.
* @return This builder.
*/
public avro.examples.baseball.NullSafeAnnotationsFieldsTest.Builder clearName() {
name = null;
fieldSetFlags()[0] = false;
return this;
}
/**
* Gets the value of the 'nullable_name' field.
* @return The value.
*/
public java.lang.String getNullableName() {
return nullable_name;
}
/**
* Sets the value of the 'nullable_name' field.
* @param value The value of 'nullable_name'.
* @return This builder.
*/
public avro.examples.baseball.NullSafeAnnotationsFieldsTest.Builder setNullableName(@org.jetbrains.annotations.Nullable java.lang.String value) {
validate(fields()[1], value);
this.nullable_name = value;
fieldSetFlags()[1] = true;
return this;
}
/**
* Checks whether the 'nullable_name' field has been set.
* @return True if the 'nullable_name' field has been set, false otherwise.
*/
public boolean hasNullableName() {
return fieldSetFlags()[1];
}
/**
* Clears the value of the 'nullable_name' field.
* @return This builder.
*/
public avro.examples.baseball.NullSafeAnnotationsFieldsTest.Builder clearNullableName() {
nullable_name = null;
fieldSetFlags()[1] = false;
return this;
}
/**
* Gets the value of the 'favorite_number' field.
* @return The value.
*/
public int getFavoriteNumber() {
return favorite_number;
}
/**
* Sets the value of the 'favorite_number' field.
* @param value The value of 'favorite_number'.
* @return This builder.
*/
public avro.examples.baseball.NullSafeAnnotationsFieldsTest.Builder setFavoriteNumber(@org.jetbrains.annotations.NotNull int value) {
validate(fields()[2], value);
this.favorite_number = value;
fieldSetFlags()[2] = true;
return this;
}
/**
* Checks whether the 'favorite_number' field has been set.
* @return True if the 'favorite_number' field has been set, false otherwise.
*/
public boolean hasFavoriteNumber() {
return fieldSetFlags()[2];
}
/**
* Clears the value of the 'favorite_number' field.
* @return This builder.
*/
public avro.examples.baseball.NullSafeAnnotationsFieldsTest.Builder clearFavoriteNumber() {
fieldSetFlags()[2] = false;
return this;
}
/**
* Gets the value of the 'nullable_favorite_number' field.
* @return The value.
*/
public java.lang.Integer getNullableFavoriteNumber() {
return nullable_favorite_number;
}
/**
* Sets the value of the 'nullable_favorite_number' field.
* @param value The value of 'nullable_favorite_number'.
* @return This builder.
*/
public avro.examples.baseball.NullSafeAnnotationsFieldsTest.Builder setNullableFavoriteNumber(@org.jetbrains.annotations.Nullable java.lang.Integer value) {
validate(fields()[3], value);
this.nullable_favorite_number = value;
fieldSetFlags()[3] = true;
return this;
}
/**
* Checks whether the 'nullable_favorite_number' field has been set.
* @return True if the 'nullable_favorite_number' field has been set, false otherwise.
*/
public boolean hasNullableFavoriteNumber() {
return fieldSetFlags()[3];
}
/**
* Clears the value of the 'nullable_favorite_number' field.
* @return This builder.
*/
public avro.examples.baseball.NullSafeAnnotationsFieldsTest.Builder clearNullableFavoriteNumber() {
nullable_favorite_number = null;
fieldSetFlags()[3] = false;
return this;
}
@Override
@SuppressWarnings("unchecked")
public NullSafeAnnotationsFieldsTest build() {
try {
NullSafeAnnotationsFieldsTest record = new NullSafeAnnotationsFieldsTest();
record.name = fieldSetFlags()[0] ? this.name : (java.lang.String) defaultValue(fields()[0]);
record.nullable_name = fieldSetFlags()[1] ? this.nullable_name : (java.lang.String) defaultValue(fields()[1]);
record.favorite_number = fieldSetFlags()[2] ? this.favorite_number : (java.lang.Integer) defaultValue(fields()[2]);
record.nullable_favorite_number = fieldSetFlags()[3] ? this.nullable_favorite_number : (java.lang.Integer) defaultValue(fields()[3]);
return record;
} catch (org.apache.avro.AvroMissingFieldException e) {
throw e;
} catch (java.lang.Exception e) {
throw new org.apache.avro.AvroRuntimeException(e);
}
}
}
@SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumWriter<NullSafeAnnotationsFieldsTest>
WRITER$ = (org.apache.avro.io.DatumWriter<NullSafeAnnotationsFieldsTest>)MODEL$.createDatumWriter(SCHEMA$);
@Override public void writeExternal(java.io.ObjectOutput out)
throws java.io.IOException {
WRITER$.write(this, SpecificData.getEncoder(out));
}
@SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumReader<NullSafeAnnotationsFieldsTest>
READER$ = (org.apache.avro.io.DatumReader<NullSafeAnnotationsFieldsTest>)MODEL$.createDatumReader(SCHEMA$);
@Override public void readExternal(java.io.ObjectInput in)
throws java.io.IOException {
READER$.read(this, SpecificData.getDecoder(in));
}
@Override protected boolean hasCustomCoders() { return true; }
@Override public void customEncode(org.apache.avro.io.Encoder out)
throws java.io.IOException
{
out.writeString(this.name);
if (this.nullable_name == null) {
out.writeIndex(1);
out.writeNull();
} else {
out.writeIndex(0);
out.writeString(this.nullable_name);
}
out.writeInt(this.favorite_number);
if (this.nullable_favorite_number == null) {
out.writeIndex(1);
out.writeNull();
} else {
out.writeIndex(0);
out.writeInt(this.nullable_favorite_number);
}
}
@Override public void customDecode(org.apache.avro.io.ResolvingDecoder in)
throws java.io.IOException
{
org.apache.avro.Schema.Field[] fieldOrder = in.readFieldOrderIfDiff();
if (fieldOrder == null) {
this.name = in.readString();
if (in.readIndex() != 0) {
in.readNull();
this.nullable_name = null;
} else {
this.nullable_name = in.readString();
}
this.favorite_number = in.readInt();
if (in.readIndex() != 0) {
in.readNull();
this.nullable_favorite_number = null;
} else {
this.nullable_favorite_number = in.readInt();
}
} else {
for (int i = 0; i < 4; i++) {
switch (fieldOrder[i].pos()) {
case 0:
this.name = in.readString();
break;
case 1:
if (in.readIndex() != 0) {
in.readNull();
this.nullable_name = null;
} else {
this.nullable_name = in.readString();
}
break;
case 2:
this.favorite_number = in.readInt();
break;
case 3:
if (in.readIndex() != 0) {
in.readNull();
this.nullable_favorite_number = null;
} else {
this.nullable_favorite_number = in.readInt();
}
break;
default:
throw new java.io.IOException("Corrupt ResolvingDecoder.");
}
}
}
}
}
| 6,890 |
0 | Create_ds/avro/lang/java/tools/src/test/compiler/output-string/avro/examples | Create_ds/avro/lang/java/tools/src/test/compiler/output-string/avro/examples/baseball/Position.java | /**
* Autogenerated by Avro
*
* DO NOT EDIT DIRECTLY
*/
package avro.examples.baseball;
@org.apache.avro.specific.AvroGenerated
public enum Position implements org.apache.avro.generic.GenericEnumSymbol<Position> {
P, C, B1, B2, B3, SS, LF, CF, RF, DH ;
public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"enum\",\"name\":\"Position\",\"namespace\":\"avro.examples.baseball\",\"symbols\":[\"P\",\"C\",\"B1\",\"B2\",\"B3\",\"SS\",\"LF\",\"CF\",\"RF\",\"DH\"]}");
public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; }
@Override
public org.apache.avro.Schema getSchema() { return SCHEMA$; }
}
| 6,891 |
0 | Create_ds/avro/lang/java/tools/src/test/compiler/output-string/avro/examples | Create_ds/avro/lang/java/tools/src/test/compiler/output-string/avro/examples/baseball/Player.java | /**
* Autogenerated by Avro
*
* DO NOT EDIT DIRECTLY
*/
package avro.examples.baseball;
import org.apache.avro.generic.GenericArray;
import org.apache.avro.specific.SpecificData;
import org.apache.avro.util.Utf8;
import org.apache.avro.message.BinaryMessageEncoder;
import org.apache.avro.message.BinaryMessageDecoder;
import org.apache.avro.message.SchemaStore;
/** 選手 is Japanese for player. */
@org.apache.avro.specific.AvroGenerated
public class Player extends org.apache.avro.specific.SpecificRecordBase implements org.apache.avro.specific.SpecificRecord {
private static final long serialVersionUID = 3865593031278745715L;
public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"record\",\"name\":\"Player\",\"namespace\":\"avro.examples.baseball\",\"doc\":\"選手 is Japanese for player.\",\"fields\":[{\"name\":\"number\",\"type\":\"int\",\"doc\":\"The number of the player\"},{\"name\":\"first_name\",\"type\":{\"type\":\"string\",\"avro.java.string\":\"String\"}},{\"name\":\"last_name\",\"type\":{\"type\":\"string\",\"avro.java.string\":\"String\"}},{\"name\":\"position\",\"type\":{\"type\":\"array\",\"items\":{\"type\":\"enum\",\"name\":\"Position\",\"symbols\":[\"P\",\"C\",\"B1\",\"B2\",\"B3\",\"SS\",\"LF\",\"CF\",\"RF\",\"DH\"]}}}]}");
public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; }
private static final SpecificData MODEL$ = new SpecificData();
private static final BinaryMessageEncoder<Player> ENCODER =
new BinaryMessageEncoder<>(MODEL$, SCHEMA$);
private static final BinaryMessageDecoder<Player> DECODER =
new BinaryMessageDecoder<>(MODEL$, SCHEMA$);
/**
* Return the BinaryMessageEncoder instance used by this class.
* @return the message encoder used by this class
*/
public static BinaryMessageEncoder<Player> getEncoder() {
return ENCODER;
}
/**
* Return the BinaryMessageDecoder instance used by this class.
* @return the message decoder used by this class
*/
public static BinaryMessageDecoder<Player> getDecoder() {
return DECODER;
}
/**
* Create a new BinaryMessageDecoder instance for this class that uses the specified {@link SchemaStore}.
* @param resolver a {@link SchemaStore} used to find schemas by fingerprint
* @return a BinaryMessageDecoder instance for this class backed by the given SchemaStore
*/
public static BinaryMessageDecoder<Player> createDecoder(SchemaStore resolver) {
return new BinaryMessageDecoder<>(MODEL$, SCHEMA$, resolver);
}
/**
* Serializes this Player to a ByteBuffer.
* @return a buffer holding the serialized data for this instance
* @throws java.io.IOException if this instance could not be serialized
*/
public java.nio.ByteBuffer toByteBuffer() throws java.io.IOException {
return ENCODER.encode(this);
}
/**
* Deserializes a Player from a ByteBuffer.
* @param b a byte buffer holding serialized data for an instance of this class
* @return a Player instance decoded from the given buffer
* @throws java.io.IOException if the given bytes could not be deserialized into an instance of this class
*/
public static Player fromByteBuffer(
java.nio.ByteBuffer b) throws java.io.IOException {
return DECODER.decode(b);
}
/** The number of the player */
private int number;
private java.lang.String first_name;
private java.lang.String last_name;
private java.util.List<avro.examples.baseball.Position> position;
/**
* Default constructor. Note that this does not initialize fields
* to their default values from the schema. If that is desired then
* one should use <code>newBuilder()</code>.
*/
public Player() {}
/**
* All-args constructor.
* @param number The number of the player
* @param first_name The new value for first_name
* @param last_name The new value for last_name
* @param position The new value for position
*/
public Player(java.lang.Integer number, java.lang.String first_name, java.lang.String last_name, java.util.List<avro.examples.baseball.Position> position) {
this.number = number;
this.first_name = first_name;
this.last_name = last_name;
this.position = position;
}
@Override
public org.apache.avro.specific.SpecificData getSpecificData() { return MODEL$; }
@Override
public org.apache.avro.Schema getSchema() { return SCHEMA$; }
// Used by DatumWriter. Applications should not call.
@Override
public java.lang.Object get(int field$) {
switch (field$) {
case 0: return number;
case 1: return first_name;
case 2: return last_name;
case 3: return position;
default: throw new IndexOutOfBoundsException("Invalid index: " + field$);
}
}
// Used by DatumReader. Applications should not call.
@Override
@SuppressWarnings(value="unchecked")
public void put(int field$, java.lang.Object value$) {
switch (field$) {
case 0: number = (java.lang.Integer)value$; break;
case 1: first_name = value$ != null ? value$.toString() : null; break;
case 2: last_name = value$ != null ? value$.toString() : null; break;
case 3: position = (java.util.List<avro.examples.baseball.Position>)value$; break;
default: throw new IndexOutOfBoundsException("Invalid index: " + field$);
}
}
/**
* Gets the value of the 'number' field.
* @return The number of the player
*/
public int getNumber() {
return number;
}
/**
* Sets the value of the 'number' field.
* The number of the player
* @param value the value to set.
*/
public void setNumber(int value) {
this.number = value;
}
/**
* Gets the value of the 'first_name' field.
* @return The value of the 'first_name' field.
*/
public java.lang.String getFirstName() {
return first_name;
}
/**
* Sets the value of the 'first_name' field.
* @param value the value to set.
*/
public void setFirstName(java.lang.String value) {
this.first_name = value;
}
/**
* Gets the value of the 'last_name' field.
* @return The value of the 'last_name' field.
*/
public java.lang.String getLastName() {
return last_name;
}
/**
* Sets the value of the 'last_name' field.
* @param value the value to set.
*/
public void setLastName(java.lang.String value) {
this.last_name = value;
}
/**
* Gets the value of the 'position' field.
* @return The value of the 'position' field.
*/
public java.util.List<avro.examples.baseball.Position> getPosition() {
return position;
}
/**
* Sets the value of the 'position' field.
* @param value the value to set.
*/
public void setPosition(java.util.List<avro.examples.baseball.Position> value) {
this.position = value;
}
/**
* Creates a new Player RecordBuilder.
* @return A new Player RecordBuilder
*/
public static avro.examples.baseball.Player.Builder newBuilder() {
return new avro.examples.baseball.Player.Builder();
}
/**
* Creates a new Player RecordBuilder by copying an existing Builder.
* @param other The existing builder to copy.
* @return A new Player RecordBuilder
*/
public static avro.examples.baseball.Player.Builder newBuilder(avro.examples.baseball.Player.Builder other) {
if (other == null) {
return new avro.examples.baseball.Player.Builder();
} else {
return new avro.examples.baseball.Player.Builder(other);
}
}
/**
* Creates a new Player RecordBuilder by copying an existing Player instance.
* @param other The existing instance to copy.
* @return A new Player RecordBuilder
*/
public static avro.examples.baseball.Player.Builder newBuilder(avro.examples.baseball.Player other) {
if (other == null) {
return new avro.examples.baseball.Player.Builder();
} else {
return new avro.examples.baseball.Player.Builder(other);
}
}
/**
* RecordBuilder for Player instances.
*/
@org.apache.avro.specific.AvroGenerated
public static class Builder extends org.apache.avro.specific.SpecificRecordBuilderBase<Player>
implements org.apache.avro.data.RecordBuilder<Player> {
/** The number of the player */
private int number;
private java.lang.String first_name;
private java.lang.String last_name;
private java.util.List<avro.examples.baseball.Position> position;
/** Creates a new Builder */
private Builder() {
super(SCHEMA$, MODEL$);
}
/**
* Creates a Builder by copying an existing Builder.
* @param other The existing Builder to copy.
*/
private Builder(avro.examples.baseball.Player.Builder other) {
super(other);
if (isValidValue(fields()[0], other.number)) {
this.number = data().deepCopy(fields()[0].schema(), other.number);
fieldSetFlags()[0] = other.fieldSetFlags()[0];
}
if (isValidValue(fields()[1], other.first_name)) {
this.first_name = data().deepCopy(fields()[1].schema(), other.first_name);
fieldSetFlags()[1] = other.fieldSetFlags()[1];
}
if (isValidValue(fields()[2], other.last_name)) {
this.last_name = data().deepCopy(fields()[2].schema(), other.last_name);
fieldSetFlags()[2] = other.fieldSetFlags()[2];
}
if (isValidValue(fields()[3], other.position)) {
this.position = data().deepCopy(fields()[3].schema(), other.position);
fieldSetFlags()[3] = other.fieldSetFlags()[3];
}
}
/**
* Creates a Builder by copying an existing Player instance
* @param other The existing instance to copy.
*/
private Builder(avro.examples.baseball.Player other) {
super(SCHEMA$, MODEL$);
if (isValidValue(fields()[0], other.number)) {
this.number = data().deepCopy(fields()[0].schema(), other.number);
fieldSetFlags()[0] = true;
}
if (isValidValue(fields()[1], other.first_name)) {
this.first_name = data().deepCopy(fields()[1].schema(), other.first_name);
fieldSetFlags()[1] = true;
}
if (isValidValue(fields()[2], other.last_name)) {
this.last_name = data().deepCopy(fields()[2].schema(), other.last_name);
fieldSetFlags()[2] = true;
}
if (isValidValue(fields()[3], other.position)) {
this.position = data().deepCopy(fields()[3].schema(), other.position);
fieldSetFlags()[3] = true;
}
}
/**
* Gets the value of the 'number' field.
* The number of the player
* @return The value.
*/
public int getNumber() {
return number;
}
/**
* Sets the value of the 'number' field.
* The number of the player
* @param value The value of 'number'.
* @return This builder.
*/
public avro.examples.baseball.Player.Builder setNumber(int value) {
validate(fields()[0], value);
this.number = value;
fieldSetFlags()[0] = true;
return this;
}
/**
* Checks whether the 'number' field has been set.
* The number of the player
* @return True if the 'number' field has been set, false otherwise.
*/
public boolean hasNumber() {
return fieldSetFlags()[0];
}
/**
* Clears the value of the 'number' field.
* The number of the player
* @return This builder.
*/
public avro.examples.baseball.Player.Builder clearNumber() {
fieldSetFlags()[0] = false;
return this;
}
/**
* Gets the value of the 'first_name' field.
* @return The value.
*/
public java.lang.String getFirstName() {
return first_name;
}
/**
* Sets the value of the 'first_name' field.
* @param value The value of 'first_name'.
* @return This builder.
*/
public avro.examples.baseball.Player.Builder setFirstName(java.lang.String value) {
validate(fields()[1], value);
this.first_name = value;
fieldSetFlags()[1] = true;
return this;
}
/**
* Checks whether the 'first_name' field has been set.
* @return True if the 'first_name' field has been set, false otherwise.
*/
public boolean hasFirstName() {
return fieldSetFlags()[1];
}
/**
* Clears the value of the 'first_name' field.
* @return This builder.
*/
public avro.examples.baseball.Player.Builder clearFirstName() {
first_name = null;
fieldSetFlags()[1] = false;
return this;
}
/**
* Gets the value of the 'last_name' field.
* @return The value.
*/
public java.lang.String getLastName() {
return last_name;
}
/**
* Sets the value of the 'last_name' field.
* @param value The value of 'last_name'.
* @return This builder.
*/
public avro.examples.baseball.Player.Builder setLastName(java.lang.String value) {
validate(fields()[2], value);
this.last_name = value;
fieldSetFlags()[2] = true;
return this;
}
/**
* Checks whether the 'last_name' field has been set.
* @return True if the 'last_name' field has been set, false otherwise.
*/
public boolean hasLastName() {
return fieldSetFlags()[2];
}
/**
* Clears the value of the 'last_name' field.
* @return This builder.
*/
public avro.examples.baseball.Player.Builder clearLastName() {
last_name = null;
fieldSetFlags()[2] = false;
return this;
}
/**
* Gets the value of the 'position' field.
* @return The value.
*/
public java.util.List<avro.examples.baseball.Position> getPosition() {
return position;
}
/**
* Sets the value of the 'position' field.
* @param value The value of 'position'.
* @return This builder.
*/
public avro.examples.baseball.Player.Builder setPosition(java.util.List<avro.examples.baseball.Position> value) {
validate(fields()[3], value);
this.position = value;
fieldSetFlags()[3] = true;
return this;
}
/**
* Checks whether the 'position' field has been set.
* @return True if the 'position' field has been set, false otherwise.
*/
public boolean hasPosition() {
return fieldSetFlags()[3];
}
/**
* Clears the value of the 'position' field.
* @return This builder.
*/
public avro.examples.baseball.Player.Builder clearPosition() {
position = null;
fieldSetFlags()[3] = false;
return this;
}
@Override
@SuppressWarnings("unchecked")
public Player build() {
try {
Player record = new Player();
record.number = fieldSetFlags()[0] ? this.number : (java.lang.Integer) defaultValue(fields()[0]);
record.first_name = fieldSetFlags()[1] ? this.first_name : (java.lang.String) defaultValue(fields()[1]);
record.last_name = fieldSetFlags()[2] ? this.last_name : (java.lang.String) defaultValue(fields()[2]);
record.position = fieldSetFlags()[3] ? this.position : (java.util.List<avro.examples.baseball.Position>) defaultValue(fields()[3]);
return record;
} catch (org.apache.avro.AvroMissingFieldException e) {
throw e;
} catch (java.lang.Exception e) {
throw new org.apache.avro.AvroRuntimeException(e);
}
}
}
@SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumWriter<Player>
WRITER$ = (org.apache.avro.io.DatumWriter<Player>)MODEL$.createDatumWriter(SCHEMA$);
@Override public void writeExternal(java.io.ObjectOutput out)
throws java.io.IOException {
WRITER$.write(this, SpecificData.getEncoder(out));
}
@SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumReader<Player>
READER$ = (org.apache.avro.io.DatumReader<Player>)MODEL$.createDatumReader(SCHEMA$);
@Override public void readExternal(java.io.ObjectInput in)
throws java.io.IOException {
READER$.read(this, SpecificData.getDecoder(in));
}
@Override protected boolean hasCustomCoders() { return true; }
@Override public void customEncode(org.apache.avro.io.Encoder out)
throws java.io.IOException
{
out.writeInt(this.number);
out.writeString(this.first_name);
out.writeString(this.last_name);
long size0 = this.position.size();
out.writeArrayStart();
out.setItemCount(size0);
long actualSize0 = 0;
for (avro.examples.baseball.Position e0: this.position) {
actualSize0++;
out.startItem();
out.writeEnum(e0.ordinal());
}
out.writeArrayEnd();
if (actualSize0 != size0)
throw new java.util.ConcurrentModificationException("Array-size written was " + size0 + ", but element count was " + actualSize0 + ".");
}
@Override public void customDecode(org.apache.avro.io.ResolvingDecoder in)
throws java.io.IOException
{
org.apache.avro.Schema.Field[] fieldOrder = in.readFieldOrderIfDiff();
if (fieldOrder == null) {
this.number = in.readInt();
this.first_name = in.readString();
this.last_name = in.readString();
long size0 = in.readArrayStart();
java.util.List<avro.examples.baseball.Position> a0 = this.position;
if (a0 == null) {
a0 = new SpecificData.Array<avro.examples.baseball.Position>((int)size0, SCHEMA$.getField("position").schema());
this.position = a0;
} else a0.clear();
SpecificData.Array<avro.examples.baseball.Position> ga0 = (a0 instanceof SpecificData.Array ? (SpecificData.Array<avro.examples.baseball.Position>)a0 : null);
for ( ; 0 < size0; size0 = in.arrayNext()) {
for ( ; size0 != 0; size0--) {
avro.examples.baseball.Position e0 = (ga0 != null ? ga0.peek() : null);
e0 = avro.examples.baseball.Position.values()[in.readEnum()];
a0.add(e0);
}
}
} else {
for (int i = 0; i < 4; i++) {
switch (fieldOrder[i].pos()) {
case 0:
this.number = in.readInt();
break;
case 1:
this.first_name = in.readString();
break;
case 2:
this.last_name = in.readString();
break;
case 3:
long size0 = in.readArrayStart();
java.util.List<avro.examples.baseball.Position> a0 = this.position;
if (a0 == null) {
a0 = new SpecificData.Array<avro.examples.baseball.Position>((int)size0, SCHEMA$.getField("position").schema());
this.position = a0;
} else a0.clear();
SpecificData.Array<avro.examples.baseball.Position> ga0 = (a0 instanceof SpecificData.Array ? (SpecificData.Array<avro.examples.baseball.Position>)a0 : null);
for ( ; 0 < size0; size0 = in.arrayNext()) {
for ( ; size0 != 0; size0--) {
avro.examples.baseball.Position e0 = (ga0 != null ? ga0.peek() : null);
e0 = avro.examples.baseball.Position.values()[in.readEnum()];
a0.add(e0);
}
}
break;
default:
throw new java.io.IOException("Corrupt ResolvingDecoder.");
}
}
}
}
}
| 6,892 |
0 | Create_ds/avro/lang/java/tools/src/test/compiler/output-string/avro/examples | Create_ds/avro/lang/java/tools/src/test/compiler/output-string/avro/examples/baseball/Proto.java | /**
* Autogenerated by Avro
*
* DO NOT EDIT DIRECTLY
*/
package avro.examples.baseball;
/** This is protocol */
@org.apache.avro.specific.AvroGenerated
public interface Proto {
public static final org.apache.avro.Protocol PROTOCOL = org.apache.avro.Protocol.parse("{\"protocol\":\"Proto\",\"namespace\":\"avro.examples.baseball\",\"doc\":\"This is protocol\",\"types\":[],\"messages\":{\"bar\":{\"doc\":\"method 'bar' does nothing */\",\"request\":[],\"response\":\"null\"}}}");
/**
* method 'bar' does nothing */
*/
void bar();
/** This is protocol */
@org.apache.avro.specific.AvroGenerated
public interface Callback extends Proto {
public static final org.apache.avro.Protocol PROTOCOL = avro.examples.baseball.Proto.PROTOCOL;
/**
* method 'bar' does nothing */
* @throws java.io.IOException The async call could not be completed.
*/
void bar(org.apache.avro.ipc.Callback<java.lang.Void> callback) throws java.io.IOException;
}
} | 6,893 |
0 | Create_ds/avro/lang/java/tools/src/test/compiler/output-string/avro/examples | Create_ds/avro/lang/java/tools/src/test/compiler/output-string/avro/examples/baseball/FieldTest.java | /**
* Autogenerated by Avro
*
* DO NOT EDIT DIRECTLY
*/
package avro.examples.baseball;
import org.apache.avro.generic.GenericArray;
import org.apache.avro.specific.SpecificData;
import org.apache.avro.util.Utf8;
import org.apache.avro.message.BinaryMessageEncoder;
import org.apache.avro.message.BinaryMessageDecoder;
import org.apache.avro.message.SchemaStore;
/** Test various field types */
@org.apache.avro.specific.AvroGenerated
public class FieldTest extends org.apache.avro.specific.SpecificRecordBase implements org.apache.avro.specific.SpecificRecord {
private static final long serialVersionUID = 4609235620572341636L;
public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"record\",\"name\":\"FieldTest\",\"namespace\":\"avro.examples.baseball\",\"doc\":\"Test various field types\",\"fields\":[{\"name\":\"number\",\"type\":\"int\",\"doc\":\"The number of the player\"},{\"name\":\"last_name\",\"type\":{\"type\":\"string\",\"avro.java.string\":\"String\"}},{\"name\":\"timestamp\",\"type\":{\"type\":\"long\",\"logicalType\":\"timestamp-millis\"}},{\"name\":\"timestampMicros\",\"type\":{\"type\":\"long\",\"logicalType\":\"timestamp-micros\"}},{\"name\":\"timeMillis\",\"type\":{\"type\":\"int\",\"logicalType\":\"time-millis\"}},{\"name\":\"timeMicros\",\"type\":{\"type\":\"long\",\"logicalType\":\"time-micros\"}}]}");
public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; }
private static final SpecificData MODEL$ = new SpecificData();
static {
MODEL$.addLogicalTypeConversion(new org.apache.avro.data.TimeConversions.TimestampMillisConversion());
MODEL$.addLogicalTypeConversion(new org.apache.avro.data.TimeConversions.TimeMicrosConversion());
MODEL$.addLogicalTypeConversion(new org.apache.avro.data.TimeConversions.TimestampMicrosConversion());
MODEL$.addLogicalTypeConversion(new org.apache.avro.data.TimeConversions.TimeMillisConversion());
}
private static final BinaryMessageEncoder<FieldTest> ENCODER =
new BinaryMessageEncoder<>(MODEL$, SCHEMA$);
private static final BinaryMessageDecoder<FieldTest> DECODER =
new BinaryMessageDecoder<>(MODEL$, SCHEMA$);
/**
* Return the BinaryMessageEncoder instance used by this class.
* @return the message encoder used by this class
*/
public static BinaryMessageEncoder<FieldTest> getEncoder() {
return ENCODER;
}
/**
* Return the BinaryMessageDecoder instance used by this class.
* @return the message decoder used by this class
*/
public static BinaryMessageDecoder<FieldTest> getDecoder() {
return DECODER;
}
/**
* Create a new BinaryMessageDecoder instance for this class that uses the specified {@link SchemaStore}.
* @param resolver a {@link SchemaStore} used to find schemas by fingerprint
* @return a BinaryMessageDecoder instance for this class backed by the given SchemaStore
*/
public static BinaryMessageDecoder<FieldTest> createDecoder(SchemaStore resolver) {
return new BinaryMessageDecoder<>(MODEL$, SCHEMA$, resolver);
}
/**
* Serializes this FieldTest to a ByteBuffer.
* @return a buffer holding the serialized data for this instance
* @throws java.io.IOException if this instance could not be serialized
*/
public java.nio.ByteBuffer toByteBuffer() throws java.io.IOException {
return ENCODER.encode(this);
}
/**
* Deserializes a FieldTest from a ByteBuffer.
* @param b a byte buffer holding serialized data for an instance of this class
* @return a FieldTest instance decoded from the given buffer
* @throws java.io.IOException if the given bytes could not be deserialized into an instance of this class
*/
public static FieldTest fromByteBuffer(
java.nio.ByteBuffer b) throws java.io.IOException {
return DECODER.decode(b);
}
/** The number of the player */
private int number;
private java.lang.String last_name;
private java.time.Instant timestamp;
private java.time.Instant timestampMicros;
private java.time.LocalTime timeMillis;
private java.time.LocalTime timeMicros;
/**
* Default constructor. Note that this does not initialize fields
* to their default values from the schema. If that is desired then
* one should use <code>newBuilder()</code>.
*/
public FieldTest() {}
/**
* All-args constructor.
* @param number The number of the player
* @param last_name The new value for last_name
* @param timestamp The new value for timestamp
* @param timestampMicros The new value for timestampMicros
* @param timeMillis The new value for timeMillis
* @param timeMicros The new value for timeMicros
*/
public FieldTest(java.lang.Integer number, java.lang.String last_name, java.time.Instant timestamp, java.time.Instant timestampMicros, java.time.LocalTime timeMillis, java.time.LocalTime timeMicros) {
this.number = number;
this.last_name = last_name;
this.timestamp = timestamp.truncatedTo(java.time.temporal.ChronoUnit.MILLIS);
this.timestampMicros = timestampMicros.truncatedTo(java.time.temporal.ChronoUnit.MICROS);
this.timeMillis = timeMillis.truncatedTo(java.time.temporal.ChronoUnit.MILLIS);
this.timeMicros = timeMicros.truncatedTo(java.time.temporal.ChronoUnit.MICROS);
}
@Override
public org.apache.avro.specific.SpecificData getSpecificData() { return MODEL$; }
@Override
public org.apache.avro.Schema getSchema() { return SCHEMA$; }
// Used by DatumWriter. Applications should not call.
@Override
public java.lang.Object get(int field$) {
switch (field$) {
case 0: return number;
case 1: return last_name;
case 2: return timestamp;
case 3: return timestampMicros;
case 4: return timeMillis;
case 5: return timeMicros;
default: throw new IndexOutOfBoundsException("Invalid index: " + field$);
}
}
private static final org.apache.avro.Conversion<?>[] conversions =
new org.apache.avro.Conversion<?>[] {
null,
null,
new org.apache.avro.data.TimeConversions.TimestampMillisConversion(),
new org.apache.avro.data.TimeConversions.TimestampMicrosConversion(),
new org.apache.avro.data.TimeConversions.TimeMillisConversion(),
new org.apache.avro.data.TimeConversions.TimeMicrosConversion(),
null
};
@Override
public org.apache.avro.Conversion<?> getConversion(int field) {
return conversions[field];
}
// Used by DatumReader. Applications should not call.
@Override
@SuppressWarnings(value="unchecked")
public void put(int field$, java.lang.Object value$) {
switch (field$) {
case 0: number = (java.lang.Integer)value$; break;
case 1: last_name = value$ != null ? value$.toString() : null; break;
case 2: timestamp = (java.time.Instant)value$; break;
case 3: timestampMicros = (java.time.Instant)value$; break;
case 4: timeMillis = (java.time.LocalTime)value$; break;
case 5: timeMicros = (java.time.LocalTime)value$; break;
default: throw new IndexOutOfBoundsException("Invalid index: " + field$);
}
}
/**
* Gets the value of the 'number' field.
* @return The number of the player
*/
public int getNumber() {
return number;
}
/**
* Sets the value of the 'number' field.
* The number of the player
* @param value the value to set.
*/
public void setNumber(int value) {
this.number = value;
}
/**
* Gets the value of the 'last_name' field.
* @return The value of the 'last_name' field.
*/
public java.lang.String getLastName() {
return last_name;
}
/**
* Sets the value of the 'last_name' field.
* @param value the value to set.
*/
public void setLastName(java.lang.String value) {
this.last_name = value;
}
/**
* Gets the value of the 'timestamp' field.
* @return The value of the 'timestamp' field.
*/
public java.time.Instant getTimestamp() {
return timestamp;
}
/**
* Sets the value of the 'timestamp' field.
* @param value the value to set.
*/
public void setTimestamp(java.time.Instant value) {
this.timestamp = value.truncatedTo(java.time.temporal.ChronoUnit.MILLIS);
}
/**
* Gets the value of the 'timestampMicros' field.
* @return The value of the 'timestampMicros' field.
*/
public java.time.Instant getTimestampMicros() {
return timestampMicros;
}
/**
* Sets the value of the 'timestampMicros' field.
* @param value the value to set.
*/
public void setTimestampMicros(java.time.Instant value) {
this.timestampMicros = value.truncatedTo(java.time.temporal.ChronoUnit.MICROS);
}
/**
* Gets the value of the 'timeMillis' field.
* @return The value of the 'timeMillis' field.
*/
public java.time.LocalTime getTimeMillis() {
return timeMillis;
}
/**
* Sets the value of the 'timeMillis' field.
* @param value the value to set.
*/
public void setTimeMillis(java.time.LocalTime value) {
this.timeMillis = value.truncatedTo(java.time.temporal.ChronoUnit.MILLIS);
}
/**
* Gets the value of the 'timeMicros' field.
* @return The value of the 'timeMicros' field.
*/
public java.time.LocalTime getTimeMicros() {
return timeMicros;
}
/**
* Sets the value of the 'timeMicros' field.
* @param value the value to set.
*/
public void setTimeMicros(java.time.LocalTime value) {
this.timeMicros = value.truncatedTo(java.time.temporal.ChronoUnit.MICROS);
}
/**
* Creates a new FieldTest RecordBuilder.
* @return A new FieldTest RecordBuilder
*/
public static avro.examples.baseball.FieldTest.Builder newBuilder() {
return new avro.examples.baseball.FieldTest.Builder();
}
/**
* Creates a new FieldTest RecordBuilder by copying an existing Builder.
* @param other The existing builder to copy.
* @return A new FieldTest RecordBuilder
*/
public static avro.examples.baseball.FieldTest.Builder newBuilder(avro.examples.baseball.FieldTest.Builder other) {
if (other == null) {
return new avro.examples.baseball.FieldTest.Builder();
} else {
return new avro.examples.baseball.FieldTest.Builder(other);
}
}
/**
* Creates a new FieldTest RecordBuilder by copying an existing FieldTest instance.
* @param other The existing instance to copy.
* @return A new FieldTest RecordBuilder
*/
public static avro.examples.baseball.FieldTest.Builder newBuilder(avro.examples.baseball.FieldTest other) {
if (other == null) {
return new avro.examples.baseball.FieldTest.Builder();
} else {
return new avro.examples.baseball.FieldTest.Builder(other);
}
}
/**
* RecordBuilder for FieldTest instances.
*/
@org.apache.avro.specific.AvroGenerated
public static class Builder extends org.apache.avro.specific.SpecificRecordBuilderBase<FieldTest>
implements org.apache.avro.data.RecordBuilder<FieldTest> {
/** The number of the player */
private int number;
private java.lang.String last_name;
private java.time.Instant timestamp;
private java.time.Instant timestampMicros;
private java.time.LocalTime timeMillis;
private java.time.LocalTime timeMicros;
/** Creates a new Builder */
private Builder() {
super(SCHEMA$, MODEL$);
}
/**
* Creates a Builder by copying an existing Builder.
* @param other The existing Builder to copy.
*/
private Builder(avro.examples.baseball.FieldTest.Builder other) {
super(other);
if (isValidValue(fields()[0], other.number)) {
this.number = data().deepCopy(fields()[0].schema(), other.number);
fieldSetFlags()[0] = other.fieldSetFlags()[0];
}
if (isValidValue(fields()[1], other.last_name)) {
this.last_name = data().deepCopy(fields()[1].schema(), other.last_name);
fieldSetFlags()[1] = other.fieldSetFlags()[1];
}
if (isValidValue(fields()[2], other.timestamp)) {
this.timestamp = data().deepCopy(fields()[2].schema(), other.timestamp);
fieldSetFlags()[2] = other.fieldSetFlags()[2];
}
if (isValidValue(fields()[3], other.timestampMicros)) {
this.timestampMicros = data().deepCopy(fields()[3].schema(), other.timestampMicros);
fieldSetFlags()[3] = other.fieldSetFlags()[3];
}
if (isValidValue(fields()[4], other.timeMillis)) {
this.timeMillis = data().deepCopy(fields()[4].schema(), other.timeMillis);
fieldSetFlags()[4] = other.fieldSetFlags()[4];
}
if (isValidValue(fields()[5], other.timeMicros)) {
this.timeMicros = data().deepCopy(fields()[5].schema(), other.timeMicros);
fieldSetFlags()[5] = other.fieldSetFlags()[5];
}
}
/**
* Creates a Builder by copying an existing FieldTest instance
* @param other The existing instance to copy.
*/
private Builder(avro.examples.baseball.FieldTest other) {
super(SCHEMA$, MODEL$);
if (isValidValue(fields()[0], other.number)) {
this.number = data().deepCopy(fields()[0].schema(), other.number);
fieldSetFlags()[0] = true;
}
if (isValidValue(fields()[1], other.last_name)) {
this.last_name = data().deepCopy(fields()[1].schema(), other.last_name);
fieldSetFlags()[1] = true;
}
if (isValidValue(fields()[2], other.timestamp)) {
this.timestamp = data().deepCopy(fields()[2].schema(), other.timestamp);
fieldSetFlags()[2] = true;
}
if (isValidValue(fields()[3], other.timestampMicros)) {
this.timestampMicros = data().deepCopy(fields()[3].schema(), other.timestampMicros);
fieldSetFlags()[3] = true;
}
if (isValidValue(fields()[4], other.timeMillis)) {
this.timeMillis = data().deepCopy(fields()[4].schema(), other.timeMillis);
fieldSetFlags()[4] = true;
}
if (isValidValue(fields()[5], other.timeMicros)) {
this.timeMicros = data().deepCopy(fields()[5].schema(), other.timeMicros);
fieldSetFlags()[5] = true;
}
}
/**
* Gets the value of the 'number' field.
* The number of the player
* @return The value.
*/
public int getNumber() {
return number;
}
/**
* Sets the value of the 'number' field.
* The number of the player
* @param value The value of 'number'.
* @return This builder.
*/
public avro.examples.baseball.FieldTest.Builder setNumber(int value) {
validate(fields()[0], value);
this.number = value;
fieldSetFlags()[0] = true;
return this;
}
/**
* Checks whether the 'number' field has been set.
* The number of the player
* @return True if the 'number' field has been set, false otherwise.
*/
public boolean hasNumber() {
return fieldSetFlags()[0];
}
/**
* Clears the value of the 'number' field.
* The number of the player
* @return This builder.
*/
public avro.examples.baseball.FieldTest.Builder clearNumber() {
fieldSetFlags()[0] = false;
return this;
}
/**
* Gets the value of the 'last_name' field.
* @return The value.
*/
public java.lang.String getLastName() {
return last_name;
}
/**
* Sets the value of the 'last_name' field.
* @param value The value of 'last_name'.
* @return This builder.
*/
public avro.examples.baseball.FieldTest.Builder setLastName(java.lang.String value) {
validate(fields()[1], value);
this.last_name = value;
fieldSetFlags()[1] = true;
return this;
}
/**
* Checks whether the 'last_name' field has been set.
* @return True if the 'last_name' field has been set, false otherwise.
*/
public boolean hasLastName() {
return fieldSetFlags()[1];
}
/**
* Clears the value of the 'last_name' field.
* @return This builder.
*/
public avro.examples.baseball.FieldTest.Builder clearLastName() {
last_name = null;
fieldSetFlags()[1] = false;
return this;
}
/**
* Gets the value of the 'timestamp' field.
* @return The value.
*/
public java.time.Instant getTimestamp() {
return timestamp;
}
/**
* Sets the value of the 'timestamp' field.
* @param value The value of 'timestamp'.
* @return This builder.
*/
public avro.examples.baseball.FieldTest.Builder setTimestamp(java.time.Instant value) {
validate(fields()[2], value);
this.timestamp = value.truncatedTo(java.time.temporal.ChronoUnit.MILLIS);
fieldSetFlags()[2] = true;
return this;
}
/**
* Checks whether the 'timestamp' field has been set.
* @return True if the 'timestamp' field has been set, false otherwise.
*/
public boolean hasTimestamp() {
return fieldSetFlags()[2];
}
/**
* Clears the value of the 'timestamp' field.
* @return This builder.
*/
public avro.examples.baseball.FieldTest.Builder clearTimestamp() {
fieldSetFlags()[2] = false;
return this;
}
/**
* Gets the value of the 'timestampMicros' field.
* @return The value.
*/
public java.time.Instant getTimestampMicros() {
return timestampMicros;
}
/**
* Sets the value of the 'timestampMicros' field.
* @param value The value of 'timestampMicros'.
* @return This builder.
*/
public avro.examples.baseball.FieldTest.Builder setTimestampMicros(java.time.Instant value) {
validate(fields()[3], value);
this.timestampMicros = value.truncatedTo(java.time.temporal.ChronoUnit.MICROS);
fieldSetFlags()[3] = true;
return this;
}
/**
* Checks whether the 'timestampMicros' field has been set.
* @return True if the 'timestampMicros' field has been set, false otherwise.
*/
public boolean hasTimestampMicros() {
return fieldSetFlags()[3];
}
/**
* Clears the value of the 'timestampMicros' field.
* @return This builder.
*/
public avro.examples.baseball.FieldTest.Builder clearTimestampMicros() {
fieldSetFlags()[3] = false;
return this;
}
/**
* Gets the value of the 'timeMillis' field.
* @return The value.
*/
public java.time.LocalTime getTimeMillis() {
return timeMillis;
}
/**
* Sets the value of the 'timeMillis' field.
* @param value The value of 'timeMillis'.
* @return This builder.
*/
public avro.examples.baseball.FieldTest.Builder setTimeMillis(java.time.LocalTime value) {
validate(fields()[4], value);
this.timeMillis = value.truncatedTo(java.time.temporal.ChronoUnit.MILLIS);
fieldSetFlags()[4] = true;
return this;
}
/**
* Checks whether the 'timeMillis' field has been set.
* @return True if the 'timeMillis' field has been set, false otherwise.
*/
public boolean hasTimeMillis() {
return fieldSetFlags()[4];
}
/**
* Clears the value of the 'timeMillis' field.
* @return This builder.
*/
public avro.examples.baseball.FieldTest.Builder clearTimeMillis() {
fieldSetFlags()[4] = false;
return this;
}
/**
* Gets the value of the 'timeMicros' field.
* @return The value.
*/
public java.time.LocalTime getTimeMicros() {
return timeMicros;
}
/**
* Sets the value of the 'timeMicros' field.
* @param value The value of 'timeMicros'.
* @return This builder.
*/
public avro.examples.baseball.FieldTest.Builder setTimeMicros(java.time.LocalTime value) {
validate(fields()[5], value);
this.timeMicros = value.truncatedTo(java.time.temporal.ChronoUnit.MICROS);
fieldSetFlags()[5] = true;
return this;
}
/**
* Checks whether the 'timeMicros' field has been set.
* @return True if the 'timeMicros' field has been set, false otherwise.
*/
public boolean hasTimeMicros() {
return fieldSetFlags()[5];
}
/**
* Clears the value of the 'timeMicros' field.
* @return This builder.
*/
public avro.examples.baseball.FieldTest.Builder clearTimeMicros() {
fieldSetFlags()[5] = false;
return this;
}
@Override
@SuppressWarnings("unchecked")
public FieldTest build() {
try {
FieldTest record = new FieldTest();
record.number = fieldSetFlags()[0] ? this.number : (java.lang.Integer) defaultValue(fields()[0]);
record.last_name = fieldSetFlags()[1] ? this.last_name : (java.lang.String) defaultValue(fields()[1]);
record.timestamp = fieldSetFlags()[2] ? this.timestamp : (java.time.Instant) defaultValue(fields()[2]);
record.timestampMicros = fieldSetFlags()[3] ? this.timestampMicros : (java.time.Instant) defaultValue(fields()[3]);
record.timeMillis = fieldSetFlags()[4] ? this.timeMillis : (java.time.LocalTime) defaultValue(fields()[4]);
record.timeMicros = fieldSetFlags()[5] ? this.timeMicros : (java.time.LocalTime) defaultValue(fields()[5]);
return record;
} catch (org.apache.avro.AvroMissingFieldException e) {
throw e;
} catch (java.lang.Exception e) {
throw new org.apache.avro.AvroRuntimeException(e);
}
}
}
@SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumWriter<FieldTest>
WRITER$ = (org.apache.avro.io.DatumWriter<FieldTest>)MODEL$.createDatumWriter(SCHEMA$);
@Override public void writeExternal(java.io.ObjectOutput out)
throws java.io.IOException {
WRITER$.write(this, SpecificData.getEncoder(out));
}
@SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumReader<FieldTest>
READER$ = (org.apache.avro.io.DatumReader<FieldTest>)MODEL$.createDatumReader(SCHEMA$);
@Override public void readExternal(java.io.ObjectInput in)
throws java.io.IOException {
READER$.read(this, SpecificData.getDecoder(in));
}
}
| 6,894 |
0 | Create_ds/avro/lang/java/tools/src/test/compiler | Create_ds/avro/lang/java/tools/src/test/compiler/output/Position.java | /**
* Autogenerated by Avro
*
* DO NOT EDIT DIRECTLY
*/
package avro.examples.baseball;
@org.apache.avro.specific.AvroGenerated
public enum Position implements org.apache.avro.generic.GenericEnumSymbol<Position> {
P, C, B1, B2, B3, SS, LF, CF, RF, DH ;
public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"enum\",\"name\":\"Position\",\"namespace\":\"avro.examples.baseball\",\"symbols\":[\"P\",\"C\",\"B1\",\"B2\",\"B3\",\"SS\",\"LF\",\"CF\",\"RF\",\"DH\"]}");
public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; }
@Override
public org.apache.avro.Schema getSchema() { return SCHEMA$; }
}
| 6,895 |
0 | Create_ds/avro/lang/java/tools/src/test/compiler | Create_ds/avro/lang/java/tools/src/test/compiler/output/OptionalGettersAllFieldsTest.java | /**
* Autogenerated by Avro
*
* DO NOT EDIT DIRECTLY
*/
package avro.examples.baseball;
import org.apache.avro.generic.GenericArray;
import org.apache.avro.specific.SpecificData;
import org.apache.avro.util.Utf8;
import org.apache.avro.message.BinaryMessageEncoder;
import org.apache.avro.message.BinaryMessageDecoder;
import org.apache.avro.message.SchemaStore;
import java.util.Optional;
/** Test that optional getters are created for all fields */
@org.apache.avro.specific.AvroGenerated
public class OptionalGettersAllFieldsTest extends org.apache.avro.specific.SpecificRecordBase implements org.apache.avro.specific.SpecificRecord {
private static final long serialVersionUID = 874861432798554536L;
public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"record\",\"name\":\"OptionalGettersAllFieldsTest\",\"namespace\":\"avro.examples.baseball\",\"doc\":\"Test that optional getters are created for all fields\",\"fields\":[{\"name\":\"name\",\"type\":\"string\"},{\"name\":\"nullable_name\",\"type\":[\"string\",\"null\"]},{\"name\":\"favorite_number\",\"type\":[\"int\"]},{\"name\":\"nullable_favorite_number\",\"type\":[\"int\",\"null\"]}]}");
public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; }
private static final SpecificData MODEL$ = new SpecificData();
private static final BinaryMessageEncoder<OptionalGettersAllFieldsTest> ENCODER =
new BinaryMessageEncoder<>(MODEL$, SCHEMA$);
private static final BinaryMessageDecoder<OptionalGettersAllFieldsTest> DECODER =
new BinaryMessageDecoder<>(MODEL$, SCHEMA$);
/**
* Return the BinaryMessageEncoder instance used by this class.
* @return the message encoder used by this class
*/
public static BinaryMessageEncoder<OptionalGettersAllFieldsTest> getEncoder() {
return ENCODER;
}
/**
* Return the BinaryMessageDecoder instance used by this class.
* @return the message decoder used by this class
*/
public static BinaryMessageDecoder<OptionalGettersAllFieldsTest> getDecoder() {
return DECODER;
}
/**
* Create a new BinaryMessageDecoder instance for this class that uses the specified {@link SchemaStore}.
* @param resolver a {@link SchemaStore} used to find schemas by fingerprint
* @return a BinaryMessageDecoder instance for this class backed by the given SchemaStore
*/
public static BinaryMessageDecoder<OptionalGettersAllFieldsTest> createDecoder(SchemaStore resolver) {
return new BinaryMessageDecoder<>(MODEL$, SCHEMA$, resolver);
}
/**
* Serializes this OptionalGettersAllFieldsTest to a ByteBuffer.
* @return a buffer holding the serialized data for this instance
* @throws java.io.IOException if this instance could not be serialized
*/
public java.nio.ByteBuffer toByteBuffer() throws java.io.IOException {
return ENCODER.encode(this);
}
/**
* Deserializes a OptionalGettersAllFieldsTest from a ByteBuffer.
* @param b a byte buffer holding serialized data for an instance of this class
* @return a OptionalGettersAllFieldsTest instance decoded from the given buffer
* @throws java.io.IOException if the given bytes could not be deserialized into an instance of this class
*/
public static OptionalGettersAllFieldsTest fromByteBuffer(
java.nio.ByteBuffer b) throws java.io.IOException {
return DECODER.decode(b);
}
private java.lang.CharSequence name;
private java.lang.CharSequence nullable_name;
private java.lang.Object favorite_number;
private java.lang.Integer nullable_favorite_number;
/**
* Default constructor. Note that this does not initialize fields
* to their default values from the schema. If that is desired then
* one should use <code>newBuilder()</code>.
*/
public OptionalGettersAllFieldsTest() {}
/**
* All-args constructor.
* @param name The new value for name
* @param nullable_name The new value for nullable_name
* @param favorite_number The new value for favorite_number
* @param nullable_favorite_number The new value for nullable_favorite_number
*/
public OptionalGettersAllFieldsTest(java.lang.CharSequence name, java.lang.CharSequence nullable_name, java.lang.Object favorite_number, java.lang.Integer nullable_favorite_number) {
this.name = name;
this.nullable_name = nullable_name;
this.favorite_number = favorite_number;
this.nullable_favorite_number = nullable_favorite_number;
}
@Override
public org.apache.avro.specific.SpecificData getSpecificData() { return MODEL$; }
@Override
public org.apache.avro.Schema getSchema() { return SCHEMA$; }
// Used by DatumWriter. Applications should not call.
@Override
public java.lang.Object get(int field$) {
switch (field$) {
case 0: return name;
case 1: return nullable_name;
case 2: return favorite_number;
case 3: return nullable_favorite_number;
default: throw new IndexOutOfBoundsException("Invalid index: " + field$);
}
}
// Used by DatumReader. Applications should not call.
@Override
@SuppressWarnings(value="unchecked")
public void put(int field$, java.lang.Object value$) {
switch (field$) {
case 0: name = (java.lang.CharSequence)value$; break;
case 1: nullable_name = (java.lang.CharSequence)value$; break;
case 2: favorite_number = value$; break;
case 3: nullable_favorite_number = (java.lang.Integer)value$; break;
default: throw new IndexOutOfBoundsException("Invalid index: " + field$);
}
}
/**
* Gets the value of the 'name' field as an Optional<java.lang.CharSequence>.
* @return The value wrapped in an Optional<java.lang.CharSequence>.
*/
public Optional<java.lang.CharSequence> getName() {
return Optional.<java.lang.CharSequence>ofNullable(name);
}
/**
* Sets the value of the 'name' field.
* @param value the value to set.
*/
public void setName(java.lang.CharSequence value) {
this.name = value;
}
/**
* Gets the value of the 'nullable_name' field as an Optional<java.lang.CharSequence>.
* @return The value wrapped in an Optional<java.lang.CharSequence>.
*/
public Optional<java.lang.CharSequence> getNullableName() {
return Optional.<java.lang.CharSequence>ofNullable(nullable_name);
}
/**
* Sets the value of the 'nullable_name' field.
* @param value the value to set.
*/
public void setNullableName(java.lang.CharSequence value) {
this.nullable_name = value;
}
/**
* Gets the value of the 'favorite_number' field as an Optional<java.lang.Object>.
* @return The value wrapped in an Optional<java.lang.Object>.
*/
public Optional<java.lang.Object> getFavoriteNumber() {
return Optional.<java.lang.Object>ofNullable(favorite_number);
}
/**
* Sets the value of the 'favorite_number' field.
* @param value the value to set.
*/
public void setFavoriteNumber(java.lang.Object value) {
this.favorite_number = value;
}
/**
* Gets the value of the 'nullable_favorite_number' field as an Optional<java.lang.Integer>.
* @return The value wrapped in an Optional<java.lang.Integer>.
*/
public Optional<java.lang.Integer> getNullableFavoriteNumber() {
return Optional.<java.lang.Integer>ofNullable(nullable_favorite_number);
}
/**
* Sets the value of the 'nullable_favorite_number' field.
* @param value the value to set.
*/
public void setNullableFavoriteNumber(java.lang.Integer value) {
this.nullable_favorite_number = value;
}
/**
* Creates a new OptionalGettersAllFieldsTest RecordBuilder.
* @return A new OptionalGettersAllFieldsTest RecordBuilder
*/
public static avro.examples.baseball.OptionalGettersAllFieldsTest.Builder newBuilder() {
return new avro.examples.baseball.OptionalGettersAllFieldsTest.Builder();
}
/**
* Creates a new OptionalGettersAllFieldsTest RecordBuilder by copying an existing Builder.
* @param other The existing builder to copy.
* @return A new OptionalGettersAllFieldsTest RecordBuilder
*/
public static avro.examples.baseball.OptionalGettersAllFieldsTest.Builder newBuilder(avro.examples.baseball.OptionalGettersAllFieldsTest.Builder other) {
if (other == null) {
return new avro.examples.baseball.OptionalGettersAllFieldsTest.Builder();
} else {
return new avro.examples.baseball.OptionalGettersAllFieldsTest.Builder(other);
}
}
/**
* Creates a new OptionalGettersAllFieldsTest RecordBuilder by copying an existing OptionalGettersAllFieldsTest instance.
* @param other The existing instance to copy.
* @return A new OptionalGettersAllFieldsTest RecordBuilder
*/
public static avro.examples.baseball.OptionalGettersAllFieldsTest.Builder newBuilder(avro.examples.baseball.OptionalGettersAllFieldsTest other) {
if (other == null) {
return new avro.examples.baseball.OptionalGettersAllFieldsTest.Builder();
} else {
return new avro.examples.baseball.OptionalGettersAllFieldsTest.Builder(other);
}
}
/**
* RecordBuilder for OptionalGettersAllFieldsTest instances.
*/
@org.apache.avro.specific.AvroGenerated
public static class Builder extends org.apache.avro.specific.SpecificRecordBuilderBase<OptionalGettersAllFieldsTest>
implements org.apache.avro.data.RecordBuilder<OptionalGettersAllFieldsTest> {
private java.lang.CharSequence name;
private java.lang.CharSequence nullable_name;
private java.lang.Object favorite_number;
private java.lang.Integer nullable_favorite_number;
/** Creates a new Builder */
private Builder() {
super(SCHEMA$, MODEL$);
}
/**
* Creates a Builder by copying an existing Builder.
* @param other The existing Builder to copy.
*/
private Builder(avro.examples.baseball.OptionalGettersAllFieldsTest.Builder other) {
super(other);
if (isValidValue(fields()[0], other.name)) {
this.name = data().deepCopy(fields()[0].schema(), other.name);
fieldSetFlags()[0] = other.fieldSetFlags()[0];
}
if (isValidValue(fields()[1], other.nullable_name)) {
this.nullable_name = data().deepCopy(fields()[1].schema(), other.nullable_name);
fieldSetFlags()[1] = other.fieldSetFlags()[1];
}
if (isValidValue(fields()[2], other.favorite_number)) {
this.favorite_number = data().deepCopy(fields()[2].schema(), other.favorite_number);
fieldSetFlags()[2] = other.fieldSetFlags()[2];
}
if (isValidValue(fields()[3], other.nullable_favorite_number)) {
this.nullable_favorite_number = data().deepCopy(fields()[3].schema(), other.nullable_favorite_number);
fieldSetFlags()[3] = other.fieldSetFlags()[3];
}
}
/**
* Creates a Builder by copying an existing OptionalGettersAllFieldsTest instance
* @param other The existing instance to copy.
*/
private Builder(avro.examples.baseball.OptionalGettersAllFieldsTest other) {
super(SCHEMA$, MODEL$);
if (isValidValue(fields()[0], other.name)) {
this.name = data().deepCopy(fields()[0].schema(), other.name);
fieldSetFlags()[0] = true;
}
if (isValidValue(fields()[1], other.nullable_name)) {
this.nullable_name = data().deepCopy(fields()[1].schema(), other.nullable_name);
fieldSetFlags()[1] = true;
}
if (isValidValue(fields()[2], other.favorite_number)) {
this.favorite_number = data().deepCopy(fields()[2].schema(), other.favorite_number);
fieldSetFlags()[2] = true;
}
if (isValidValue(fields()[3], other.nullable_favorite_number)) {
this.nullable_favorite_number = data().deepCopy(fields()[3].schema(), other.nullable_favorite_number);
fieldSetFlags()[3] = true;
}
}
/**
* Gets the value of the 'name' field.
* @return The value.
*/
public java.lang.CharSequence getName() {
return name;
}
/**
* Sets the value of the 'name' field.
* @param value The value of 'name'.
* @return This builder.
*/
public avro.examples.baseball.OptionalGettersAllFieldsTest.Builder setName(java.lang.CharSequence value) {
validate(fields()[0], value);
this.name = value;
fieldSetFlags()[0] = true;
return this;
}
/**
* Checks whether the 'name' field has been set.
* @return True if the 'name' field has been set, false otherwise.
*/
public boolean hasName() {
return fieldSetFlags()[0];
}
/**
* Clears the value of the 'name' field.
* @return This builder.
*/
public avro.examples.baseball.OptionalGettersAllFieldsTest.Builder clearName() {
name = null;
fieldSetFlags()[0] = false;
return this;
}
/**
* Gets the value of the 'nullable_name' field.
* @return The value.
*/
public java.lang.CharSequence getNullableName() {
return nullable_name;
}
/**
* Sets the value of the 'nullable_name' field.
* @param value The value of 'nullable_name'.
* @return This builder.
*/
public avro.examples.baseball.OptionalGettersAllFieldsTest.Builder setNullableName(java.lang.CharSequence value) {
validate(fields()[1], value);
this.nullable_name = value;
fieldSetFlags()[1] = true;
return this;
}
/**
* Checks whether the 'nullable_name' field has been set.
* @return True if the 'nullable_name' field has been set, false otherwise.
*/
public boolean hasNullableName() {
return fieldSetFlags()[1];
}
/**
* Clears the value of the 'nullable_name' field.
* @return This builder.
*/
public avro.examples.baseball.OptionalGettersAllFieldsTest.Builder clearNullableName() {
nullable_name = null;
fieldSetFlags()[1] = false;
return this;
}
/**
* Gets the value of the 'favorite_number' field.
* @return The value.
*/
public java.lang.Object getFavoriteNumber() {
return favorite_number;
}
/**
* Sets the value of the 'favorite_number' field.
* @param value The value of 'favorite_number'.
* @return This builder.
*/
public avro.examples.baseball.OptionalGettersAllFieldsTest.Builder setFavoriteNumber(java.lang.Object value) {
validate(fields()[2], value);
this.favorite_number = value;
fieldSetFlags()[2] = true;
return this;
}
/**
* Checks whether the 'favorite_number' field has been set.
* @return True if the 'favorite_number' field has been set, false otherwise.
*/
public boolean hasFavoriteNumber() {
return fieldSetFlags()[2];
}
/**
* Clears the value of the 'favorite_number' field.
* @return This builder.
*/
public avro.examples.baseball.OptionalGettersAllFieldsTest.Builder clearFavoriteNumber() {
favorite_number = null;
fieldSetFlags()[2] = false;
return this;
}
/**
* Gets the value of the 'nullable_favorite_number' field.
* @return The value.
*/
public java.lang.Integer getNullableFavoriteNumber() {
return nullable_favorite_number;
}
/**
* Sets the value of the 'nullable_favorite_number' field.
* @param value The value of 'nullable_favorite_number'.
* @return This builder.
*/
public avro.examples.baseball.OptionalGettersAllFieldsTest.Builder setNullableFavoriteNumber(java.lang.Integer value) {
validate(fields()[3], value);
this.nullable_favorite_number = value;
fieldSetFlags()[3] = true;
return this;
}
/**
* Checks whether the 'nullable_favorite_number' field has been set.
* @return True if the 'nullable_favorite_number' field has been set, false otherwise.
*/
public boolean hasNullableFavoriteNumber() {
return fieldSetFlags()[3];
}
/**
* Clears the value of the 'nullable_favorite_number' field.
* @return This builder.
*/
public avro.examples.baseball.OptionalGettersAllFieldsTest.Builder clearNullableFavoriteNumber() {
nullable_favorite_number = null;
fieldSetFlags()[3] = false;
return this;
}
@Override
@SuppressWarnings("unchecked")
public OptionalGettersAllFieldsTest build() {
try {
OptionalGettersAllFieldsTest record = new OptionalGettersAllFieldsTest();
record.name = fieldSetFlags()[0] ? this.name : (java.lang.CharSequence) defaultValue(fields()[0]);
record.nullable_name = fieldSetFlags()[1] ? this.nullable_name : (java.lang.CharSequence) defaultValue(fields()[1]);
record.favorite_number = fieldSetFlags()[2] ? this.favorite_number : defaultValue(fields()[2]);
record.nullable_favorite_number = fieldSetFlags()[3] ? this.nullable_favorite_number : (java.lang.Integer) defaultValue(fields()[3]);
return record;
} catch (org.apache.avro.AvroMissingFieldException e) {
throw e;
} catch (java.lang.Exception e) {
throw new org.apache.avro.AvroRuntimeException(e);
}
}
}
@SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumWriter<OptionalGettersAllFieldsTest>
WRITER$ = (org.apache.avro.io.DatumWriter<OptionalGettersAllFieldsTest>)MODEL$.createDatumWriter(SCHEMA$);
@Override public void writeExternal(java.io.ObjectOutput out)
throws java.io.IOException {
WRITER$.write(this, SpecificData.getEncoder(out));
}
@SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumReader<OptionalGettersAllFieldsTest>
READER$ = (org.apache.avro.io.DatumReader<OptionalGettersAllFieldsTest>)MODEL$.createDatumReader(SCHEMA$);
@Override public void readExternal(java.io.ObjectInput in)
throws java.io.IOException {
READER$.read(this, SpecificData.getDecoder(in));
}
}
| 6,896 |
0 | Create_ds/avro/lang/java/tools/src/test/compiler | Create_ds/avro/lang/java/tools/src/test/compiler/output/Player.java | /**
* Autogenerated by Avro
*
* DO NOT EDIT DIRECTLY
*/
package avro.examples.baseball;
import org.apache.avro.generic.GenericArray;
import org.apache.avro.specific.SpecificData;
import org.apache.avro.util.Utf8;
import org.apache.avro.message.BinaryMessageEncoder;
import org.apache.avro.message.BinaryMessageDecoder;
import org.apache.avro.message.SchemaStore;
/** 選手 is Japanese for player. */
@org.apache.avro.specific.AvroGenerated
public class Player extends org.apache.avro.specific.SpecificRecordBase implements org.apache.avro.specific.SpecificRecord {
private static final long serialVersionUID = 3865593031278745715L;
public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"record\",\"name\":\"Player\",\"namespace\":\"avro.examples.baseball\",\"doc\":\"選手 is Japanese for player.\",\"fields\":[{\"name\":\"number\",\"type\":\"int\",\"doc\":\"The number of the player\"},{\"name\":\"first_name\",\"type\":\"string\"},{\"name\":\"last_name\",\"type\":\"string\"},{\"name\":\"position\",\"type\":{\"type\":\"array\",\"items\":{\"type\":\"enum\",\"name\":\"Position\",\"symbols\":[\"P\",\"C\",\"B1\",\"B2\",\"B3\",\"SS\",\"LF\",\"CF\",\"RF\",\"DH\"]}}}]}");
public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; }
private static final SpecificData MODEL$ = new SpecificData();
private static final BinaryMessageEncoder<Player> ENCODER =
new BinaryMessageEncoder<>(MODEL$, SCHEMA$);
private static final BinaryMessageDecoder<Player> DECODER =
new BinaryMessageDecoder<>(MODEL$, SCHEMA$);
/**
* Return the BinaryMessageEncoder instance used by this class.
* @return the message encoder used by this class
*/
public static BinaryMessageEncoder<Player> getEncoder() {
return ENCODER;
}
/**
* Return the BinaryMessageDecoder instance used by this class.
* @return the message decoder used by this class
*/
public static BinaryMessageDecoder<Player> getDecoder() {
return DECODER;
}
/**
* Create a new BinaryMessageDecoder instance for this class that uses the specified {@link SchemaStore}.
* @param resolver a {@link SchemaStore} used to find schemas by fingerprint
* @return a BinaryMessageDecoder instance for this class backed by the given SchemaStore
*/
public static BinaryMessageDecoder<Player> createDecoder(SchemaStore resolver) {
return new BinaryMessageDecoder<>(MODEL$, SCHEMA$, resolver);
}
/**
* Serializes this Player to a ByteBuffer.
* @return a buffer holding the serialized data for this instance
* @throws java.io.IOException if this instance could not be serialized
*/
public java.nio.ByteBuffer toByteBuffer() throws java.io.IOException {
return ENCODER.encode(this);
}
/**
* Deserializes a Player from a ByteBuffer.
* @param b a byte buffer holding serialized data for an instance of this class
* @return a Player instance decoded from the given buffer
* @throws java.io.IOException if the given bytes could not be deserialized into an instance of this class
*/
public static Player fromByteBuffer(
java.nio.ByteBuffer b) throws java.io.IOException {
return DECODER.decode(b);
}
/** The number of the player */
private int number;
private java.lang.CharSequence first_name;
private java.lang.CharSequence last_name;
private java.util.List<avro.examples.baseball.Position> position;
/**
* Default constructor. Note that this does not initialize fields
* to their default values from the schema. If that is desired then
* one should use <code>newBuilder()</code>.
*/
public Player() {}
/**
* All-args constructor.
* @param number The number of the player
* @param first_name The new value for first_name
* @param last_name The new value for last_name
* @param position The new value for position
*/
public Player(java.lang.Integer number, java.lang.CharSequence first_name, java.lang.CharSequence last_name, java.util.List<avro.examples.baseball.Position> position) {
this.number = number;
this.first_name = first_name;
this.last_name = last_name;
this.position = position;
}
@Override
public org.apache.avro.specific.SpecificData getSpecificData() { return MODEL$; }
@Override
public org.apache.avro.Schema getSchema() { return SCHEMA$; }
// Used by DatumWriter. Applications should not call.
@Override
public java.lang.Object get(int field$) {
switch (field$) {
case 0: return number;
case 1: return first_name;
case 2: return last_name;
case 3: return position;
default: throw new IndexOutOfBoundsException("Invalid index: " + field$);
}
}
// Used by DatumReader. Applications should not call.
@Override
@SuppressWarnings(value="unchecked")
public void put(int field$, java.lang.Object value$) {
switch (field$) {
case 0: number = (java.lang.Integer)value$; break;
case 1: first_name = (java.lang.CharSequence)value$; break;
case 2: last_name = (java.lang.CharSequence)value$; break;
case 3: position = (java.util.List<avro.examples.baseball.Position>)value$; break;
default: throw new IndexOutOfBoundsException("Invalid index: " + field$);
}
}
/**
* Gets the value of the 'number' field.
* @return The number of the player
*/
public int getNumber() {
return number;
}
/**
* Sets the value of the 'number' field.
* The number of the player
* @param value the value to set.
*/
public void setNumber(int value) {
this.number = value;
}
/**
* Gets the value of the 'first_name' field.
* @return The value of the 'first_name' field.
*/
public java.lang.CharSequence getFirstName() {
return first_name;
}
/**
* Sets the value of the 'first_name' field.
* @param value the value to set.
*/
public void setFirstName(java.lang.CharSequence value) {
this.first_name = value;
}
/**
* Gets the value of the 'last_name' field.
* @return The value of the 'last_name' field.
*/
public java.lang.CharSequence getLastName() {
return last_name;
}
/**
* Sets the value of the 'last_name' field.
* @param value the value to set.
*/
public void setLastName(java.lang.CharSequence value) {
this.last_name = value;
}
/**
* Gets the value of the 'position' field.
* @return The value of the 'position' field.
*/
public java.util.List<avro.examples.baseball.Position> getPosition() {
return position;
}
/**
* Sets the value of the 'position' field.
* @param value the value to set.
*/
public void setPosition(java.util.List<avro.examples.baseball.Position> value) {
this.position = value;
}
/**
* Creates a new Player RecordBuilder.
* @return A new Player RecordBuilder
*/
public static avro.examples.baseball.Player.Builder newBuilder() {
return new avro.examples.baseball.Player.Builder();
}
/**
* Creates a new Player RecordBuilder by copying an existing Builder.
* @param other The existing builder to copy.
* @return A new Player RecordBuilder
*/
public static avro.examples.baseball.Player.Builder newBuilder(avro.examples.baseball.Player.Builder other) {
if (other == null) {
return new avro.examples.baseball.Player.Builder();
} else {
return new avro.examples.baseball.Player.Builder(other);
}
}
/**
* Creates a new Player RecordBuilder by copying an existing Player instance.
* @param other The existing instance to copy.
* @return A new Player RecordBuilder
*/
public static avro.examples.baseball.Player.Builder newBuilder(avro.examples.baseball.Player other) {
if (other == null) {
return new avro.examples.baseball.Player.Builder();
} else {
return new avro.examples.baseball.Player.Builder(other);
}
}
/**
* RecordBuilder for Player instances.
*/
@org.apache.avro.specific.AvroGenerated
public static class Builder extends org.apache.avro.specific.SpecificRecordBuilderBase<Player>
implements org.apache.avro.data.RecordBuilder<Player> {
/** The number of the player */
private int number;
private java.lang.CharSequence first_name;
private java.lang.CharSequence last_name;
private java.util.List<avro.examples.baseball.Position> position;
/** Creates a new Builder */
private Builder() {
super(SCHEMA$, MODEL$);
}
/**
* Creates a Builder by copying an existing Builder.
* @param other The existing Builder to copy.
*/
private Builder(avro.examples.baseball.Player.Builder other) {
super(other);
if (isValidValue(fields()[0], other.number)) {
this.number = data().deepCopy(fields()[0].schema(), other.number);
fieldSetFlags()[0] = other.fieldSetFlags()[0];
}
if (isValidValue(fields()[1], other.first_name)) {
this.first_name = data().deepCopy(fields()[1].schema(), other.first_name);
fieldSetFlags()[1] = other.fieldSetFlags()[1];
}
if (isValidValue(fields()[2], other.last_name)) {
this.last_name = data().deepCopy(fields()[2].schema(), other.last_name);
fieldSetFlags()[2] = other.fieldSetFlags()[2];
}
if (isValidValue(fields()[3], other.position)) {
this.position = data().deepCopy(fields()[3].schema(), other.position);
fieldSetFlags()[3] = other.fieldSetFlags()[3];
}
}
/**
* Creates a Builder by copying an existing Player instance
* @param other The existing instance to copy.
*/
private Builder(avro.examples.baseball.Player other) {
super(SCHEMA$, MODEL$);
if (isValidValue(fields()[0], other.number)) {
this.number = data().deepCopy(fields()[0].schema(), other.number);
fieldSetFlags()[0] = true;
}
if (isValidValue(fields()[1], other.first_name)) {
this.first_name = data().deepCopy(fields()[1].schema(), other.first_name);
fieldSetFlags()[1] = true;
}
if (isValidValue(fields()[2], other.last_name)) {
this.last_name = data().deepCopy(fields()[2].schema(), other.last_name);
fieldSetFlags()[2] = true;
}
if (isValidValue(fields()[3], other.position)) {
this.position = data().deepCopy(fields()[3].schema(), other.position);
fieldSetFlags()[3] = true;
}
}
/**
* Gets the value of the 'number' field.
* The number of the player
* @return The value.
*/
public int getNumber() {
return number;
}
/**
* Sets the value of the 'number' field.
* The number of the player
* @param value The value of 'number'.
* @return This builder.
*/
public avro.examples.baseball.Player.Builder setNumber(int value) {
validate(fields()[0], value);
this.number = value;
fieldSetFlags()[0] = true;
return this;
}
/**
* Checks whether the 'number' field has been set.
* The number of the player
* @return True if the 'number' field has been set, false otherwise.
*/
public boolean hasNumber() {
return fieldSetFlags()[0];
}
/**
* Clears the value of the 'number' field.
* The number of the player
* @return This builder.
*/
public avro.examples.baseball.Player.Builder clearNumber() {
fieldSetFlags()[0] = false;
return this;
}
/**
* Gets the value of the 'first_name' field.
* @return The value.
*/
public java.lang.CharSequence getFirstName() {
return first_name;
}
/**
* Sets the value of the 'first_name' field.
* @param value The value of 'first_name'.
* @return This builder.
*/
public avro.examples.baseball.Player.Builder setFirstName(java.lang.CharSequence value) {
validate(fields()[1], value);
this.first_name = value;
fieldSetFlags()[1] = true;
return this;
}
/**
* Checks whether the 'first_name' field has been set.
* @return True if the 'first_name' field has been set, false otherwise.
*/
public boolean hasFirstName() {
return fieldSetFlags()[1];
}
/**
* Clears the value of the 'first_name' field.
* @return This builder.
*/
public avro.examples.baseball.Player.Builder clearFirstName() {
first_name = null;
fieldSetFlags()[1] = false;
return this;
}
/**
* Gets the value of the 'last_name' field.
* @return The value.
*/
public java.lang.CharSequence getLastName() {
return last_name;
}
/**
* Sets the value of the 'last_name' field.
* @param value The value of 'last_name'.
* @return This builder.
*/
public avro.examples.baseball.Player.Builder setLastName(java.lang.CharSequence value) {
validate(fields()[2], value);
this.last_name = value;
fieldSetFlags()[2] = true;
return this;
}
/**
* Checks whether the 'last_name' field has been set.
* @return True if the 'last_name' field has been set, false otherwise.
*/
public boolean hasLastName() {
return fieldSetFlags()[2];
}
/**
* Clears the value of the 'last_name' field.
* @return This builder.
*/
public avro.examples.baseball.Player.Builder clearLastName() {
last_name = null;
fieldSetFlags()[2] = false;
return this;
}
/**
* Gets the value of the 'position' field.
* @return The value.
*/
public java.util.List<avro.examples.baseball.Position> getPosition() {
return position;
}
/**
* Sets the value of the 'position' field.
* @param value The value of 'position'.
* @return This builder.
*/
public avro.examples.baseball.Player.Builder setPosition(java.util.List<avro.examples.baseball.Position> value) {
validate(fields()[3], value);
this.position = value;
fieldSetFlags()[3] = true;
return this;
}
/**
* Checks whether the 'position' field has been set.
* @return True if the 'position' field has been set, false otherwise.
*/
public boolean hasPosition() {
return fieldSetFlags()[3];
}
/**
* Clears the value of the 'position' field.
* @return This builder.
*/
public avro.examples.baseball.Player.Builder clearPosition() {
position = null;
fieldSetFlags()[3] = false;
return this;
}
@Override
@SuppressWarnings("unchecked")
public Player build() {
try {
Player record = new Player();
record.number = fieldSetFlags()[0] ? this.number : (java.lang.Integer) defaultValue(fields()[0]);
record.first_name = fieldSetFlags()[1] ? this.first_name : (java.lang.CharSequence) defaultValue(fields()[1]);
record.last_name = fieldSetFlags()[2] ? this.last_name : (java.lang.CharSequence) defaultValue(fields()[2]);
record.position = fieldSetFlags()[3] ? this.position : (java.util.List<avro.examples.baseball.Position>) defaultValue(fields()[3]);
return record;
} catch (org.apache.avro.AvroMissingFieldException e) {
throw e;
} catch (java.lang.Exception e) {
throw new org.apache.avro.AvroRuntimeException(e);
}
}
}
@SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumWriter<Player>
WRITER$ = (org.apache.avro.io.DatumWriter<Player>)MODEL$.createDatumWriter(SCHEMA$);
@Override public void writeExternal(java.io.ObjectOutput out)
throws java.io.IOException {
WRITER$.write(this, SpecificData.getEncoder(out));
}
@SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumReader<Player>
READER$ = (org.apache.avro.io.DatumReader<Player>)MODEL$.createDatumReader(SCHEMA$);
@Override public void readExternal(java.io.ObjectInput in)
throws java.io.IOException {
READER$.read(this, SpecificData.getDecoder(in));
}
@Override protected boolean hasCustomCoders() { return true; }
@Override public void customEncode(org.apache.avro.io.Encoder out)
throws java.io.IOException
{
out.writeInt(this.number);
out.writeString(this.first_name);
out.writeString(this.last_name);
long size0 = this.position.size();
out.writeArrayStart();
out.setItemCount(size0);
long actualSize0 = 0;
for (avro.examples.baseball.Position e0: this.position) {
actualSize0++;
out.startItem();
out.writeEnum(e0.ordinal());
}
out.writeArrayEnd();
if (actualSize0 != size0)
throw new java.util.ConcurrentModificationException("Array-size written was " + size0 + ", but element count was " + actualSize0 + ".");
}
@Override public void customDecode(org.apache.avro.io.ResolvingDecoder in)
throws java.io.IOException
{
org.apache.avro.Schema.Field[] fieldOrder = in.readFieldOrderIfDiff();
if (fieldOrder == null) {
this.number = in.readInt();
this.first_name = in.readString(this.first_name instanceof Utf8 ? (Utf8)this.first_name : null);
this.last_name = in.readString(this.last_name instanceof Utf8 ? (Utf8)this.last_name : null);
long size0 = in.readArrayStart();
java.util.List<avro.examples.baseball.Position> a0 = this.position;
if (a0 == null) {
a0 = new SpecificData.Array<avro.examples.baseball.Position>((int)size0, SCHEMA$.getField("position").schema());
this.position = a0;
} else a0.clear();
SpecificData.Array<avro.examples.baseball.Position> ga0 = (a0 instanceof SpecificData.Array ? (SpecificData.Array<avro.examples.baseball.Position>)a0 : null);
for ( ; 0 < size0; size0 = in.arrayNext()) {
for ( ; size0 != 0; size0--) {
avro.examples.baseball.Position e0 = (ga0 != null ? ga0.peek() : null);
e0 = avro.examples.baseball.Position.values()[in.readEnum()];
a0.add(e0);
}
}
} else {
for (int i = 0; i < 4; i++) {
switch (fieldOrder[i].pos()) {
case 0:
this.number = in.readInt();
break;
case 1:
this.first_name = in.readString(this.first_name instanceof Utf8 ? (Utf8)this.first_name : null);
break;
case 2:
this.last_name = in.readString(this.last_name instanceof Utf8 ? (Utf8)this.last_name : null);
break;
case 3:
long size0 = in.readArrayStart();
java.util.List<avro.examples.baseball.Position> a0 = this.position;
if (a0 == null) {
a0 = new SpecificData.Array<avro.examples.baseball.Position>((int)size0, SCHEMA$.getField("position").schema());
this.position = a0;
} else a0.clear();
SpecificData.Array<avro.examples.baseball.Position> ga0 = (a0 instanceof SpecificData.Array ? (SpecificData.Array<avro.examples.baseball.Position>)a0 : null);
for ( ; 0 < size0; size0 = in.arrayNext()) {
for ( ; size0 != 0; size0--) {
avro.examples.baseball.Position e0 = (ga0 != null ? ga0.peek() : null);
e0 = avro.examples.baseball.Position.values()[in.readEnum()];
a0.add(e0);
}
}
break;
default:
throw new java.io.IOException("Corrupt ResolvingDecoder.");
}
}
}
}
}
| 6,897 |
0 | Create_ds/avro/lang/java/tools/src/test/compiler | Create_ds/avro/lang/java/tools/src/test/compiler/output/AddExtraOptionalGettersTest.java | /**
* Autogenerated by Avro
*
* DO NOT EDIT DIRECTLY
*/
package avro.examples.baseball;
import org.apache.avro.generic.GenericArray;
import org.apache.avro.specific.SpecificData;
import org.apache.avro.util.Utf8;
import org.apache.avro.message.BinaryMessageEncoder;
import org.apache.avro.message.BinaryMessageDecoder;
import org.apache.avro.message.SchemaStore;
import java.util.Optional;
/** Test that extra optional getters are added */
@org.apache.avro.specific.AvroGenerated
public class AddExtraOptionalGettersTest extends org.apache.avro.specific.SpecificRecordBase implements org.apache.avro.specific.SpecificRecord {
private static final long serialVersionUID = -3300987256178011215L;
public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"record\",\"name\":\"AddExtraOptionalGettersTest\",\"namespace\":\"avro.examples.baseball\",\"doc\":\"Test that extra optional getters are added\",\"fields\":[{\"name\":\"name\",\"type\":\"string\"},{\"name\":\"favorite_number\",\"type\":[\"int\",\"null\"]}]}");
public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; }
private static final SpecificData MODEL$ = new SpecificData();
private static final BinaryMessageEncoder<AddExtraOptionalGettersTest> ENCODER =
new BinaryMessageEncoder<>(MODEL$, SCHEMA$);
private static final BinaryMessageDecoder<AddExtraOptionalGettersTest> DECODER =
new BinaryMessageDecoder<>(MODEL$, SCHEMA$);
/**
* Return the BinaryMessageEncoder instance used by this class.
* @return the message encoder used by this class
*/
public static BinaryMessageEncoder<AddExtraOptionalGettersTest> getEncoder() {
return ENCODER;
}
/**
* Return the BinaryMessageDecoder instance used by this class.
* @return the message decoder used by this class
*/
public static BinaryMessageDecoder<AddExtraOptionalGettersTest> getDecoder() {
return DECODER;
}
/**
* Create a new BinaryMessageDecoder instance for this class that uses the specified {@link SchemaStore}.
* @param resolver a {@link SchemaStore} used to find schemas by fingerprint
* @return a BinaryMessageDecoder instance for this class backed by the given SchemaStore
*/
public static BinaryMessageDecoder<AddExtraOptionalGettersTest> createDecoder(SchemaStore resolver) {
return new BinaryMessageDecoder<>(MODEL$, SCHEMA$, resolver);
}
/**
* Serializes this AddExtraOptionalGettersTest to a ByteBuffer.
* @return a buffer holding the serialized data for this instance
* @throws java.io.IOException if this instance could not be serialized
*/
public java.nio.ByteBuffer toByteBuffer() throws java.io.IOException {
return ENCODER.encode(this);
}
/**
* Deserializes a AddExtraOptionalGettersTest from a ByteBuffer.
* @param b a byte buffer holding serialized data for an instance of this class
* @return a AddExtraOptionalGettersTest instance decoded from the given buffer
* @throws java.io.IOException if the given bytes could not be deserialized into an instance of this class
*/
public static AddExtraOptionalGettersTest fromByteBuffer(
java.nio.ByteBuffer b) throws java.io.IOException {
return DECODER.decode(b);
}
private java.lang.CharSequence name;
private java.lang.Integer favorite_number;
/**
* Default constructor. Note that this does not initialize fields
* to their default values from the schema. If that is desired then
* one should use <code>newBuilder()</code>.
*/
public AddExtraOptionalGettersTest() {}
/**
* All-args constructor.
* @param name The new value for name
* @param favorite_number The new value for favorite_number
*/
public AddExtraOptionalGettersTest(java.lang.CharSequence name, java.lang.Integer favorite_number) {
this.name = name;
this.favorite_number = favorite_number;
}
@Override
public org.apache.avro.specific.SpecificData getSpecificData() { return MODEL$; }
@Override
public org.apache.avro.Schema getSchema() { return SCHEMA$; }
// Used by DatumWriter. Applications should not call.
@Override
public java.lang.Object get(int field$) {
switch (field$) {
case 0: return name;
case 1: return favorite_number;
default: throw new IndexOutOfBoundsException("Invalid index: " + field$);
}
}
// Used by DatumReader. Applications should not call.
@Override
@SuppressWarnings(value="unchecked")
public void put(int field$, java.lang.Object value$) {
switch (field$) {
case 0: name = (java.lang.CharSequence)value$; break;
case 1: favorite_number = (java.lang.Integer)value$; break;
default: throw new IndexOutOfBoundsException("Invalid index: " + field$);
}
}
/**
* Gets the value of the 'name' field.
* @return The value of the 'name' field.
*/
public java.lang.CharSequence getName() {
return name;
}
/**
* Gets the value of the 'name' field as an Optional<java.lang.CharSequence>.
* @return The value wrapped in an Optional<java.lang.CharSequence>.
*/
public Optional<java.lang.CharSequence> getOptionalName() {
return Optional.<java.lang.CharSequence>ofNullable(name);
}
/**
* Sets the value of the 'name' field.
* @param value the value to set.
*/
public void setName(java.lang.CharSequence value) {
this.name = value;
}
/**
* Gets the value of the 'favorite_number' field.
* @return The value of the 'favorite_number' field.
*/
public java.lang.Integer getFavoriteNumber() {
return favorite_number;
}
/**
* Gets the value of the 'favorite_number' field as an Optional<java.lang.Integer>.
* @return The value wrapped in an Optional<java.lang.Integer>.
*/
public Optional<java.lang.Integer> getOptionalFavoriteNumber() {
return Optional.<java.lang.Integer>ofNullable(favorite_number);
}
/**
* Sets the value of the 'favorite_number' field.
* @param value the value to set.
*/
public void setFavoriteNumber(java.lang.Integer value) {
this.favorite_number = value;
}
/**
* Creates a new AddExtraOptionalGettersTest RecordBuilder.
* @return A new AddExtraOptionalGettersTest RecordBuilder
*/
public static avro.examples.baseball.AddExtraOptionalGettersTest.Builder newBuilder() {
return new avro.examples.baseball.AddExtraOptionalGettersTest.Builder();
}
/**
* Creates a new AddExtraOptionalGettersTest RecordBuilder by copying an existing Builder.
* @param other The existing builder to copy.
* @return A new AddExtraOptionalGettersTest RecordBuilder
*/
public static avro.examples.baseball.AddExtraOptionalGettersTest.Builder newBuilder(avro.examples.baseball.AddExtraOptionalGettersTest.Builder other) {
if (other == null) {
return new avro.examples.baseball.AddExtraOptionalGettersTest.Builder();
} else {
return new avro.examples.baseball.AddExtraOptionalGettersTest.Builder(other);
}
}
/**
* Creates a new AddExtraOptionalGettersTest RecordBuilder by copying an existing AddExtraOptionalGettersTest instance.
* @param other The existing instance to copy.
* @return A new AddExtraOptionalGettersTest RecordBuilder
*/
public static avro.examples.baseball.AddExtraOptionalGettersTest.Builder newBuilder(avro.examples.baseball.AddExtraOptionalGettersTest other) {
if (other == null) {
return new avro.examples.baseball.AddExtraOptionalGettersTest.Builder();
} else {
return new avro.examples.baseball.AddExtraOptionalGettersTest.Builder(other);
}
}
/**
* RecordBuilder for AddExtraOptionalGettersTest instances.
*/
@org.apache.avro.specific.AvroGenerated
public static class Builder extends org.apache.avro.specific.SpecificRecordBuilderBase<AddExtraOptionalGettersTest>
implements org.apache.avro.data.RecordBuilder<AddExtraOptionalGettersTest> {
private java.lang.CharSequence name;
private java.lang.Integer favorite_number;
/** Creates a new Builder */
private Builder() {
super(SCHEMA$, MODEL$);
}
/**
* Creates a Builder by copying an existing Builder.
* @param other The existing Builder to copy.
*/
private Builder(avro.examples.baseball.AddExtraOptionalGettersTest.Builder other) {
super(other);
if (isValidValue(fields()[0], other.name)) {
this.name = data().deepCopy(fields()[0].schema(), other.name);
fieldSetFlags()[0] = other.fieldSetFlags()[0];
}
if (isValidValue(fields()[1], other.favorite_number)) {
this.favorite_number = data().deepCopy(fields()[1].schema(), other.favorite_number);
fieldSetFlags()[1] = other.fieldSetFlags()[1];
}
}
/**
* Creates a Builder by copying an existing AddExtraOptionalGettersTest instance
* @param other The existing instance to copy.
*/
private Builder(avro.examples.baseball.AddExtraOptionalGettersTest other) {
super(SCHEMA$, MODEL$);
if (isValidValue(fields()[0], other.name)) {
this.name = data().deepCopy(fields()[0].schema(), other.name);
fieldSetFlags()[0] = true;
}
if (isValidValue(fields()[1], other.favorite_number)) {
this.favorite_number = data().deepCopy(fields()[1].schema(), other.favorite_number);
fieldSetFlags()[1] = true;
}
}
/**
* Gets the value of the 'name' field.
* @return The value.
*/
public java.lang.CharSequence getName() {
return name;
}
/**
* Gets the value of the 'name' field as an Optional<java.lang.CharSequence>.
* @return The value wrapped in an Optional<java.lang.CharSequence>.
*/
public Optional<java.lang.CharSequence> getOptionalName() {
return Optional.<java.lang.CharSequence>ofNullable(name);
}
/**
* Sets the value of the 'name' field.
* @param value The value of 'name'.
* @return This builder.
*/
public avro.examples.baseball.AddExtraOptionalGettersTest.Builder setName(java.lang.CharSequence value) {
validate(fields()[0], value);
this.name = value;
fieldSetFlags()[0] = true;
return this;
}
/**
* Checks whether the 'name' field has been set.
* @return True if the 'name' field has been set, false otherwise.
*/
public boolean hasName() {
return fieldSetFlags()[0];
}
/**
* Clears the value of the 'name' field.
* @return This builder.
*/
public avro.examples.baseball.AddExtraOptionalGettersTest.Builder clearName() {
name = null;
fieldSetFlags()[0] = false;
return this;
}
/**
* Gets the value of the 'favorite_number' field.
* @return The value.
*/
public java.lang.Integer getFavoriteNumber() {
return favorite_number;
}
/**
* Gets the value of the 'favorite_number' field as an Optional<java.lang.Integer>.
* @return The value wrapped in an Optional<java.lang.Integer>.
*/
public Optional<java.lang.Integer> getOptionalFavoriteNumber() {
return Optional.<java.lang.Integer>ofNullable(favorite_number);
}
/**
* Sets the value of the 'favorite_number' field.
* @param value The value of 'favorite_number'.
* @return This builder.
*/
public avro.examples.baseball.AddExtraOptionalGettersTest.Builder setFavoriteNumber(java.lang.Integer value) {
validate(fields()[1], value);
this.favorite_number = value;
fieldSetFlags()[1] = true;
return this;
}
/**
* Checks whether the 'favorite_number' field has been set.
* @return True if the 'favorite_number' field has been set, false otherwise.
*/
public boolean hasFavoriteNumber() {
return fieldSetFlags()[1];
}
/**
* Clears the value of the 'favorite_number' field.
* @return This builder.
*/
public avro.examples.baseball.AddExtraOptionalGettersTest.Builder clearFavoriteNumber() {
favorite_number = null;
fieldSetFlags()[1] = false;
return this;
}
@Override
@SuppressWarnings("unchecked")
public AddExtraOptionalGettersTest build() {
try {
AddExtraOptionalGettersTest record = new AddExtraOptionalGettersTest();
record.name = fieldSetFlags()[0] ? this.name : (java.lang.CharSequence) defaultValue(fields()[0]);
record.favorite_number = fieldSetFlags()[1] ? this.favorite_number : (java.lang.Integer) defaultValue(fields()[1]);
return record;
} catch (org.apache.avro.AvroMissingFieldException e) {
throw e;
} catch (java.lang.Exception e) {
throw new org.apache.avro.AvroRuntimeException(e);
}
}
}
@SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumWriter<AddExtraOptionalGettersTest>
WRITER$ = (org.apache.avro.io.DatumWriter<AddExtraOptionalGettersTest>)MODEL$.createDatumWriter(SCHEMA$);
@Override public void writeExternal(java.io.ObjectOutput out)
throws java.io.IOException {
WRITER$.write(this, SpecificData.getEncoder(out));
}
@SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumReader<AddExtraOptionalGettersTest>
READER$ = (org.apache.avro.io.DatumReader<AddExtraOptionalGettersTest>)MODEL$.createDatumReader(SCHEMA$);
@Override public void readExternal(java.io.ObjectInput in)
throws java.io.IOException {
READER$.read(this, SpecificData.getDecoder(in));
}
@Override protected boolean hasCustomCoders() { return true; }
@Override public void customEncode(org.apache.avro.io.Encoder out)
throws java.io.IOException
{
out.writeString(this.name);
if (this.favorite_number == null) {
out.writeIndex(1);
out.writeNull();
} else {
out.writeIndex(0);
out.writeInt(this.favorite_number);
}
}
@Override public void customDecode(org.apache.avro.io.ResolvingDecoder in)
throws java.io.IOException
{
org.apache.avro.Schema.Field[] fieldOrder = in.readFieldOrderIfDiff();
if (fieldOrder == null) {
this.name = in.readString(this.name instanceof Utf8 ? (Utf8)this.name : null);
if (in.readIndex() != 0) {
in.readNull();
this.favorite_number = null;
} else {
this.favorite_number = in.readInt();
}
} else {
for (int i = 0; i < 2; i++) {
switch (fieldOrder[i].pos()) {
case 0:
this.name = in.readString(this.name instanceof Utf8 ? (Utf8)this.name : null);
break;
case 1:
if (in.readIndex() != 0) {
in.readNull();
this.favorite_number = null;
} else {
this.favorite_number = in.readInt();
}
break;
default:
throw new java.io.IOException("Corrupt ResolvingDecoder.");
}
}
}
}
}
| 6,898 |
0 | Create_ds/avro/lang/java/tools/src/test/compiler | Create_ds/avro/lang/java/tools/src/test/compiler/output/OptionalGettersNullableFieldsTest.java | /**
* Autogenerated by Avro
*
* DO NOT EDIT DIRECTLY
*/
package avro.examples.baseball;
import org.apache.avro.generic.GenericArray;
import org.apache.avro.specific.SpecificData;
import org.apache.avro.util.Utf8;
import org.apache.avro.message.BinaryMessageEncoder;
import org.apache.avro.message.BinaryMessageDecoder;
import org.apache.avro.message.SchemaStore;
import java.util.Optional;
/** Test that optional getters are created only for nullable fields */
@org.apache.avro.specific.AvroGenerated
public class OptionalGettersNullableFieldsTest extends org.apache.avro.specific.SpecificRecordBase implements org.apache.avro.specific.SpecificRecord {
private static final long serialVersionUID = -6919829133416680993L;
public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"record\",\"name\":\"OptionalGettersNullableFieldsTest\",\"namespace\":\"avro.examples.baseball\",\"doc\":\"Test that optional getters are created only for nullable fields\",\"fields\":[{\"name\":\"name\",\"type\":\"string\"},{\"name\":\"nullable_name\",\"type\":[\"string\",\"null\"]},{\"name\":\"favorite_number\",\"type\":[\"int\"]},{\"name\":\"nullable_favorite_number\",\"type\":[\"int\",\"null\"]},{\"name\":\"nullable_array\",\"type\":[{\"type\":\"array\",\"items\":\"string\"},\"null\"]}]}");
public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; }
private static final SpecificData MODEL$ = new SpecificData();
private static final BinaryMessageEncoder<OptionalGettersNullableFieldsTest> ENCODER =
new BinaryMessageEncoder<>(MODEL$, SCHEMA$);
private static final BinaryMessageDecoder<OptionalGettersNullableFieldsTest> DECODER =
new BinaryMessageDecoder<>(MODEL$, SCHEMA$);
/**
* Return the BinaryMessageEncoder instance used by this class.
* @return the message encoder used by this class
*/
public static BinaryMessageEncoder<OptionalGettersNullableFieldsTest> getEncoder() {
return ENCODER;
}
/**
* Return the BinaryMessageDecoder instance used by this class.
* @return the message decoder used by this class
*/
public static BinaryMessageDecoder<OptionalGettersNullableFieldsTest> getDecoder() {
return DECODER;
}
/**
* Create a new BinaryMessageDecoder instance for this class that uses the specified {@link SchemaStore}.
* @param resolver a {@link SchemaStore} used to find schemas by fingerprint
* @return a BinaryMessageDecoder instance for this class backed by the given SchemaStore
*/
public static BinaryMessageDecoder<OptionalGettersNullableFieldsTest> createDecoder(SchemaStore resolver) {
return new BinaryMessageDecoder<>(MODEL$, SCHEMA$, resolver);
}
/**
* Serializes this OptionalGettersNullableFieldsTest to a ByteBuffer.
* @return a buffer holding the serialized data for this instance
* @throws java.io.IOException if this instance could not be serialized
*/
public java.nio.ByteBuffer toByteBuffer() throws java.io.IOException {
return ENCODER.encode(this);
}
/**
* Deserializes a OptionalGettersNullableFieldsTest from a ByteBuffer.
* @param b a byte buffer holding serialized data for an instance of this class
* @return a OptionalGettersNullableFieldsTest instance decoded from the given buffer
* @throws java.io.IOException if the given bytes could not be deserialized into an instance of this class
*/
public static OptionalGettersNullableFieldsTest fromByteBuffer(
java.nio.ByteBuffer b) throws java.io.IOException {
return DECODER.decode(b);
}
private java.lang.CharSequence name;
private java.lang.CharSequence nullable_name;
private java.lang.Object favorite_number;
private java.lang.Integer nullable_favorite_number;
private java.util.List<java.lang.CharSequence> nullable_array;
/**
* Default constructor. Note that this does not initialize fields
* to their default values from the schema. If that is desired then
* one should use <code>newBuilder()</code>.
*/
public OptionalGettersNullableFieldsTest() {}
/**
* All-args constructor.
* @param name The new value for name
* @param nullable_name The new value for nullable_name
* @param favorite_number The new value for favorite_number
* @param nullable_favorite_number The new value for nullable_favorite_number
* @param nullable_array The new value for nullable_array
*/
public OptionalGettersNullableFieldsTest(java.lang.CharSequence name, java.lang.CharSequence nullable_name, java.lang.Object favorite_number, java.lang.Integer nullable_favorite_number, java.util.List<java.lang.CharSequence> nullable_array) {
this.name = name;
this.nullable_name = nullable_name;
this.favorite_number = favorite_number;
this.nullable_favorite_number = nullable_favorite_number;
this.nullable_array = nullable_array;
}
@Override
public org.apache.avro.specific.SpecificData getSpecificData() { return MODEL$; }
@Override
public org.apache.avro.Schema getSchema() { return SCHEMA$; }
// Used by DatumWriter. Applications should not call.
@Override
public java.lang.Object get(int field$) {
switch (field$) {
case 0: return name;
case 1: return nullable_name;
case 2: return favorite_number;
case 3: return nullable_favorite_number;
case 4: return nullable_array;
default: throw new IndexOutOfBoundsException("Invalid index: " + field$);
}
}
// Used by DatumReader. Applications should not call.
@Override
@SuppressWarnings(value="unchecked")
public void put(int field$, java.lang.Object value$) {
switch (field$) {
case 0: name = (java.lang.CharSequence)value$; break;
case 1: nullable_name = (java.lang.CharSequence)value$; break;
case 2: favorite_number = value$; break;
case 3: nullable_favorite_number = (java.lang.Integer)value$; break;
case 4: nullable_array = (java.util.List<java.lang.CharSequence>)value$; break;
default: throw new IndexOutOfBoundsException("Invalid index: " + field$);
}
}
/**
* Gets the value of the 'name' field.
* @return The value of the 'name' field.
*/
public java.lang.CharSequence getName() {
return name;
}
/**
* Sets the value of the 'name' field.
* @param value the value to set.
*/
public void setName(java.lang.CharSequence value) {
this.name = value;
}
/**
* Gets the value of the 'nullable_name' field as an Optional<java.lang.CharSequence>.
* @return The value wrapped in an Optional<java.lang.CharSequence>.
*/
public Optional<java.lang.CharSequence> getNullableName() {
return Optional.<java.lang.CharSequence>ofNullable(nullable_name);
}
/**
* Sets the value of the 'nullable_name' field.
* @param value the value to set.
*/
public void setNullableName(java.lang.CharSequence value) {
this.nullable_name = value;
}
/**
* Gets the value of the 'favorite_number' field.
* @return The value of the 'favorite_number' field.
*/
public java.lang.Object getFavoriteNumber() {
return favorite_number;
}
/**
* Sets the value of the 'favorite_number' field.
* @param value the value to set.
*/
public void setFavoriteNumber(java.lang.Object value) {
this.favorite_number = value;
}
/**
* Gets the value of the 'nullable_favorite_number' field as an Optional<java.lang.Integer>.
* @return The value wrapped in an Optional<java.lang.Integer>.
*/
public Optional<java.lang.Integer> getNullableFavoriteNumber() {
return Optional.<java.lang.Integer>ofNullable(nullable_favorite_number);
}
/**
* Sets the value of the 'nullable_favorite_number' field.
* @param value the value to set.
*/
public void setNullableFavoriteNumber(java.lang.Integer value) {
this.nullable_favorite_number = value;
}
/**
* Gets the value of the 'nullable_array' field as an Optional<java.util.List<java.lang.CharSequence>>.
* @return The value wrapped in an Optional<java.util.List<java.lang.CharSequence>>.
*/
public Optional<java.util.List<java.lang.CharSequence>> getNullableArray() {
return Optional.<java.util.List<java.lang.CharSequence>>ofNullable(nullable_array);
}
/**
* Sets the value of the 'nullable_array' field.
* @param value the value to set.
*/
public void setNullableArray(java.util.List<java.lang.CharSequence> value) {
this.nullable_array = value;
}
/**
* Creates a new OptionalGettersNullableFieldsTest RecordBuilder.
* @return A new OptionalGettersNullableFieldsTest RecordBuilder
*/
public static avro.examples.baseball.OptionalGettersNullableFieldsTest.Builder newBuilder() {
return new avro.examples.baseball.OptionalGettersNullableFieldsTest.Builder();
}
/**
* Creates a new OptionalGettersNullableFieldsTest RecordBuilder by copying an existing Builder.
* @param other The existing builder to copy.
* @return A new OptionalGettersNullableFieldsTest RecordBuilder
*/
public static avro.examples.baseball.OptionalGettersNullableFieldsTest.Builder newBuilder(avro.examples.baseball.OptionalGettersNullableFieldsTest.Builder other) {
if (other == null) {
return new avro.examples.baseball.OptionalGettersNullableFieldsTest.Builder();
} else {
return new avro.examples.baseball.OptionalGettersNullableFieldsTest.Builder(other);
}
}
/**
* Creates a new OptionalGettersNullableFieldsTest RecordBuilder by copying an existing OptionalGettersNullableFieldsTest instance.
* @param other The existing instance to copy.
* @return A new OptionalGettersNullableFieldsTest RecordBuilder
*/
public static avro.examples.baseball.OptionalGettersNullableFieldsTest.Builder newBuilder(avro.examples.baseball.OptionalGettersNullableFieldsTest other) {
if (other == null) {
return new avro.examples.baseball.OptionalGettersNullableFieldsTest.Builder();
} else {
return new avro.examples.baseball.OptionalGettersNullableFieldsTest.Builder(other);
}
}
/**
* RecordBuilder for OptionalGettersNullableFieldsTest instances.
*/
@org.apache.avro.specific.AvroGenerated
public static class Builder extends org.apache.avro.specific.SpecificRecordBuilderBase<OptionalGettersNullableFieldsTest>
implements org.apache.avro.data.RecordBuilder<OptionalGettersNullableFieldsTest> {
private java.lang.CharSequence name;
private java.lang.CharSequence nullable_name;
private java.lang.Object favorite_number;
private java.lang.Integer nullable_favorite_number;
private java.util.List<java.lang.CharSequence> nullable_array;
/** Creates a new Builder */
private Builder() {
super(SCHEMA$, MODEL$);
}
/**
* Creates a Builder by copying an existing Builder.
* @param other The existing Builder to copy.
*/
private Builder(avro.examples.baseball.OptionalGettersNullableFieldsTest.Builder other) {
super(other);
if (isValidValue(fields()[0], other.name)) {
this.name = data().deepCopy(fields()[0].schema(), other.name);
fieldSetFlags()[0] = other.fieldSetFlags()[0];
}
if (isValidValue(fields()[1], other.nullable_name)) {
this.nullable_name = data().deepCopy(fields()[1].schema(), other.nullable_name);
fieldSetFlags()[1] = other.fieldSetFlags()[1];
}
if (isValidValue(fields()[2], other.favorite_number)) {
this.favorite_number = data().deepCopy(fields()[2].schema(), other.favorite_number);
fieldSetFlags()[2] = other.fieldSetFlags()[2];
}
if (isValidValue(fields()[3], other.nullable_favorite_number)) {
this.nullable_favorite_number = data().deepCopy(fields()[3].schema(), other.nullable_favorite_number);
fieldSetFlags()[3] = other.fieldSetFlags()[3];
}
if (isValidValue(fields()[4], other.nullable_array)) {
this.nullable_array = data().deepCopy(fields()[4].schema(), other.nullable_array);
fieldSetFlags()[4] = other.fieldSetFlags()[4];
}
}
/**
* Creates a Builder by copying an existing OptionalGettersNullableFieldsTest instance
* @param other The existing instance to copy.
*/
private Builder(avro.examples.baseball.OptionalGettersNullableFieldsTest other) {
super(SCHEMA$, MODEL$);
if (isValidValue(fields()[0], other.name)) {
this.name = data().deepCopy(fields()[0].schema(), other.name);
fieldSetFlags()[0] = true;
}
if (isValidValue(fields()[1], other.nullable_name)) {
this.nullable_name = data().deepCopy(fields()[1].schema(), other.nullable_name);
fieldSetFlags()[1] = true;
}
if (isValidValue(fields()[2], other.favorite_number)) {
this.favorite_number = data().deepCopy(fields()[2].schema(), other.favorite_number);
fieldSetFlags()[2] = true;
}
if (isValidValue(fields()[3], other.nullable_favorite_number)) {
this.nullable_favorite_number = data().deepCopy(fields()[3].schema(), other.nullable_favorite_number);
fieldSetFlags()[3] = true;
}
if (isValidValue(fields()[4], other.nullable_array)) {
this.nullable_array = data().deepCopy(fields()[4].schema(), other.nullable_array);
fieldSetFlags()[4] = true;
}
}
/**
* Gets the value of the 'name' field.
* @return The value.
*/
public java.lang.CharSequence getName() {
return name;
}
/**
* Sets the value of the 'name' field.
* @param value The value of 'name'.
* @return This builder.
*/
public avro.examples.baseball.OptionalGettersNullableFieldsTest.Builder setName(java.lang.CharSequence value) {
validate(fields()[0], value);
this.name = value;
fieldSetFlags()[0] = true;
return this;
}
/**
* Checks whether the 'name' field has been set.
* @return True if the 'name' field has been set, false otherwise.
*/
public boolean hasName() {
return fieldSetFlags()[0];
}
/**
* Clears the value of the 'name' field.
* @return This builder.
*/
public avro.examples.baseball.OptionalGettersNullableFieldsTest.Builder clearName() {
name = null;
fieldSetFlags()[0] = false;
return this;
}
/**
* Gets the value of the 'nullable_name' field.
* @return The value.
*/
public java.lang.CharSequence getNullableName() {
return nullable_name;
}
/**
* Sets the value of the 'nullable_name' field.
* @param value The value of 'nullable_name'.
* @return This builder.
*/
public avro.examples.baseball.OptionalGettersNullableFieldsTest.Builder setNullableName(java.lang.CharSequence value) {
validate(fields()[1], value);
this.nullable_name = value;
fieldSetFlags()[1] = true;
return this;
}
/**
* Checks whether the 'nullable_name' field has been set.
* @return True if the 'nullable_name' field has been set, false otherwise.
*/
public boolean hasNullableName() {
return fieldSetFlags()[1];
}
/**
* Clears the value of the 'nullable_name' field.
* @return This builder.
*/
public avro.examples.baseball.OptionalGettersNullableFieldsTest.Builder clearNullableName() {
nullable_name = null;
fieldSetFlags()[1] = false;
return this;
}
/**
* Gets the value of the 'favorite_number' field.
* @return The value.
*/
public java.lang.Object getFavoriteNumber() {
return favorite_number;
}
/**
* Sets the value of the 'favorite_number' field.
* @param value The value of 'favorite_number'.
* @return This builder.
*/
public avro.examples.baseball.OptionalGettersNullableFieldsTest.Builder setFavoriteNumber(java.lang.Object value) {
validate(fields()[2], value);
this.favorite_number = value;
fieldSetFlags()[2] = true;
return this;
}
/**
* Checks whether the 'favorite_number' field has been set.
* @return True if the 'favorite_number' field has been set, false otherwise.
*/
public boolean hasFavoriteNumber() {
return fieldSetFlags()[2];
}
/**
* Clears the value of the 'favorite_number' field.
* @return This builder.
*/
public avro.examples.baseball.OptionalGettersNullableFieldsTest.Builder clearFavoriteNumber() {
favorite_number = null;
fieldSetFlags()[2] = false;
return this;
}
/**
* Gets the value of the 'nullable_favorite_number' field.
* @return The value.
*/
public java.lang.Integer getNullableFavoriteNumber() {
return nullable_favorite_number;
}
/**
* Sets the value of the 'nullable_favorite_number' field.
* @param value The value of 'nullable_favorite_number'.
* @return This builder.
*/
public avro.examples.baseball.OptionalGettersNullableFieldsTest.Builder setNullableFavoriteNumber(java.lang.Integer value) {
validate(fields()[3], value);
this.nullable_favorite_number = value;
fieldSetFlags()[3] = true;
return this;
}
/**
* Checks whether the 'nullable_favorite_number' field has been set.
* @return True if the 'nullable_favorite_number' field has been set, false otherwise.
*/
public boolean hasNullableFavoriteNumber() {
return fieldSetFlags()[3];
}
/**
* Clears the value of the 'nullable_favorite_number' field.
* @return This builder.
*/
public avro.examples.baseball.OptionalGettersNullableFieldsTest.Builder clearNullableFavoriteNumber() {
nullable_favorite_number = null;
fieldSetFlags()[3] = false;
return this;
}
/**
* Gets the value of the 'nullable_array' field.
* @return The value.
*/
public java.util.List<java.lang.CharSequence> getNullableArray() {
return nullable_array;
}
/**
* Sets the value of the 'nullable_array' field.
* @param value The value of 'nullable_array'.
* @return This builder.
*/
public avro.examples.baseball.OptionalGettersNullableFieldsTest.Builder setNullableArray(java.util.List<java.lang.CharSequence> value) {
validate(fields()[4], value);
this.nullable_array = value;
fieldSetFlags()[4] = true;
return this;
}
/**
* Checks whether the 'nullable_array' field has been set.
* @return True if the 'nullable_array' field has been set, false otherwise.
*/
public boolean hasNullableArray() {
return fieldSetFlags()[4];
}
/**
* Clears the value of the 'nullable_array' field.
* @return This builder.
*/
public avro.examples.baseball.OptionalGettersNullableFieldsTest.Builder clearNullableArray() {
nullable_array = null;
fieldSetFlags()[4] = false;
return this;
}
@Override
@SuppressWarnings("unchecked")
public OptionalGettersNullableFieldsTest build() {
try {
OptionalGettersNullableFieldsTest record = new OptionalGettersNullableFieldsTest();
record.name = fieldSetFlags()[0] ? this.name : (java.lang.CharSequence) defaultValue(fields()[0]);
record.nullable_name = fieldSetFlags()[1] ? this.nullable_name : (java.lang.CharSequence) defaultValue(fields()[1]);
record.favorite_number = fieldSetFlags()[2] ? this.favorite_number : defaultValue(fields()[2]);
record.nullable_favorite_number = fieldSetFlags()[3] ? this.nullable_favorite_number : (java.lang.Integer) defaultValue(fields()[3]);
record.nullable_array = fieldSetFlags()[4] ? this.nullable_array : (java.util.List<java.lang.CharSequence>) defaultValue(fields()[4]);
return record;
} catch (org.apache.avro.AvroMissingFieldException e) {
throw e;
} catch (java.lang.Exception e) {
throw new org.apache.avro.AvroRuntimeException(e);
}
}
}
@SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumWriter<OptionalGettersNullableFieldsTest>
WRITER$ = (org.apache.avro.io.DatumWriter<OptionalGettersNullableFieldsTest>)MODEL$.createDatumWriter(SCHEMA$);
@Override public void writeExternal(java.io.ObjectOutput out)
throws java.io.IOException {
WRITER$.write(this, SpecificData.getEncoder(out));
}
@SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumReader<OptionalGettersNullableFieldsTest>
READER$ = (org.apache.avro.io.DatumReader<OptionalGettersNullableFieldsTest>)MODEL$.createDatumReader(SCHEMA$);
@Override public void readExternal(java.io.ObjectInput in)
throws java.io.IOException {
READER$.read(this, SpecificData.getDecoder(in));
}
}
| 6,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.