id
int32
0
165k
repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
sequence
docstring
stringlengths
3
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
105
339
1,000
outbrain/ob1k
ob1k-concurrent/src/main/java/com/outbrain/ob1k/concurrent/ComposableFutures.java
ComposableFutures.toObservable
public static <T> Observable<T> toObservable(final FutureProvider<T> provider) { return Observable.create(new FutureProviderToStreamHandler<>(provider)); }
java
public static <T> Observable<T> toObservable(final FutureProvider<T> provider) { return Observable.create(new FutureProviderToStreamHandler<>(provider)); }
[ "public", "static", "<", "T", ">", "Observable", "<", "T", ">", "toObservable", "(", "final", "FutureProvider", "<", "T", ">", "provider", ")", "{", "return", "Observable", ".", "create", "(", "new", "FutureProviderToStreamHandler", "<>", "(", "provider", ")", ")", ";", "}" ]
creates new observable given future provider, translating the future results into stream. the sequence will be evaluated on subscribe. @param provider the future provider for translation @param <T> the stream type @return the stream
[ "creates", "new", "observable", "given", "future", "provider", "translating", "the", "future", "results", "into", "stream", ".", "the", "sequence", "will", "be", "evaluated", "on", "subscribe", "." ]
9e43ab39230c5787065053da0f766d822d0fe4e7
https://github.com/outbrain/ob1k/blob/9e43ab39230c5787065053da0f766d822d0fe4e7/ob1k-concurrent/src/main/java/com/outbrain/ob1k/concurrent/ComposableFutures.java#L704-L706
1,001
outbrain/ob1k
ob1k-security/src/main/java/com/outbrain/ob1k/security/server/AuthenticationCookie.java
AuthenticationCookie.fromDelimitedString
public static AuthenticationCookie fromDelimitedString(final String delimitedString) { Preconditions.checkArgument(delimitedString != null && delimitedString.length() > 0, "delimitedString cannot be empty"); final String[] cookieElements = delimitedString.split(DELIMITER); Preconditions.checkArgument(cookieElements.length == 4, "delimitedString should contain exactly 4 elements"); return new AuthenticationCookie( cookieElements[0], DateTime.parse(cookieElements[1], DATE_TIME_FORMATTER), cookieElements[2], cookieElements[3]); }
java
public static AuthenticationCookie fromDelimitedString(final String delimitedString) { Preconditions.checkArgument(delimitedString != null && delimitedString.length() > 0, "delimitedString cannot be empty"); final String[] cookieElements = delimitedString.split(DELIMITER); Preconditions.checkArgument(cookieElements.length == 4, "delimitedString should contain exactly 4 elements"); return new AuthenticationCookie( cookieElements[0], DateTime.parse(cookieElements[1], DATE_TIME_FORMATTER), cookieElements[2], cookieElements[3]); }
[ "public", "static", "AuthenticationCookie", "fromDelimitedString", "(", "final", "String", "delimitedString", ")", "{", "Preconditions", ".", "checkArgument", "(", "delimitedString", "!=", "null", "&&", "delimitedString", ".", "length", "(", ")", ">", "0", ",", "\"delimitedString cannot be empty\"", ")", ";", "final", "String", "[", "]", "cookieElements", "=", "delimitedString", ".", "split", "(", "DELIMITER", ")", ";", "Preconditions", ".", "checkArgument", "(", "cookieElements", ".", "length", "==", "4", ",", "\"delimitedString should contain exactly 4 elements\"", ")", ";", "return", "new", "AuthenticationCookie", "(", "cookieElements", "[", "0", "]", ",", "DateTime", ".", "parse", "(", "cookieElements", "[", "1", "]", ",", "DATE_TIME_FORMATTER", ")", ",", "cookieElements", "[", "2", "]", ",", "cookieElements", "[", "3", "]", ")", ";", "}" ]
Converted the given delimited string into an Authentication cookie. Expected a string in the format username;creationTime;appId;authenticatorId
[ "Converted", "the", "given", "delimited", "string", "into", "an", "Authentication", "cookie", ".", "Expected", "a", "string", "in", "the", "format", "username", ";", "creationTime", ";", "appId", ";", "authenticatorId" ]
9e43ab39230c5787065053da0f766d822d0fe4e7
https://github.com/outbrain/ob1k/blob/9e43ab39230c5787065053da0f766d822d0fe4e7/ob1k-security/src/main/java/com/outbrain/ob1k/security/server/AuthenticationCookie.java#L38-L50
1,002
outbrain/ob1k
ob1k-http/src/main/java/com/outbrain/ob1k/http/HttpClient.java
HttpClient.get
public RequestBuilder get(final String url) { checkNotNull(url, "url may not be null"); final AsyncHttpClient.BoundRequestBuilder ningRequestBuilder = asyncHttpClient.prepareGet(url); return createNewRequestBuilder(url, ningRequestBuilder); }
java
public RequestBuilder get(final String url) { checkNotNull(url, "url may not be null"); final AsyncHttpClient.BoundRequestBuilder ningRequestBuilder = asyncHttpClient.prepareGet(url); return createNewRequestBuilder(url, ningRequestBuilder); }
[ "public", "RequestBuilder", "get", "(", "final", "String", "url", ")", "{", "checkNotNull", "(", "url", ",", "\"url may not be null\"", ")", ";", "final", "AsyncHttpClient", ".", "BoundRequestBuilder", "ningRequestBuilder", "=", "asyncHttpClient", ".", "prepareGet", "(", "url", ")", ";", "return", "createNewRequestBuilder", "(", "url", ",", "ningRequestBuilder", ")", ";", "}" ]
Http get request @param url url for the request @return request builder
[ "Http", "get", "request" ]
9e43ab39230c5787065053da0f766d822d0fe4e7
https://github.com/outbrain/ob1k/blob/9e43ab39230c5787065053da0f766d822d0fe4e7/ob1k-http/src/main/java/com/outbrain/ob1k/http/HttpClient.java#L67-L72
1,003
outbrain/ob1k
ob1k-http/src/main/java/com/outbrain/ob1k/http/HttpClient.java
HttpClient.post
public RequestBuilder post(final String url) { checkNotNull(url, "url may not be null"); final AsyncHttpClient.BoundRequestBuilder ningRequestBuilder = asyncHttpClient.preparePost(url); return createNewRequestBuilder(url, ningRequestBuilder); }
java
public RequestBuilder post(final String url) { checkNotNull(url, "url may not be null"); final AsyncHttpClient.BoundRequestBuilder ningRequestBuilder = asyncHttpClient.preparePost(url); return createNewRequestBuilder(url, ningRequestBuilder); }
[ "public", "RequestBuilder", "post", "(", "final", "String", "url", ")", "{", "checkNotNull", "(", "url", ",", "\"url may not be null\"", ")", ";", "final", "AsyncHttpClient", ".", "BoundRequestBuilder", "ningRequestBuilder", "=", "asyncHttpClient", ".", "preparePost", "(", "url", ")", ";", "return", "createNewRequestBuilder", "(", "url", ",", "ningRequestBuilder", ")", ";", "}" ]
Http post request @param url url for the request @return request builder
[ "Http", "post", "request" ]
9e43ab39230c5787065053da0f766d822d0fe4e7
https://github.com/outbrain/ob1k/blob/9e43ab39230c5787065053da0f766d822d0fe4e7/ob1k-http/src/main/java/com/outbrain/ob1k/http/HttpClient.java#L80-L85
1,004
outbrain/ob1k
ob1k-http/src/main/java/com/outbrain/ob1k/http/HttpClient.java
HttpClient.put
public RequestBuilder put(final String url) { checkNotNull(url, "url may not be null"); final AsyncHttpClient.BoundRequestBuilder ningRequestBuilder = asyncHttpClient.preparePut(url); return createNewRequestBuilder(url, ningRequestBuilder); }
java
public RequestBuilder put(final String url) { checkNotNull(url, "url may not be null"); final AsyncHttpClient.BoundRequestBuilder ningRequestBuilder = asyncHttpClient.preparePut(url); return createNewRequestBuilder(url, ningRequestBuilder); }
[ "public", "RequestBuilder", "put", "(", "final", "String", "url", ")", "{", "checkNotNull", "(", "url", ",", "\"url may not be null\"", ")", ";", "final", "AsyncHttpClient", ".", "BoundRequestBuilder", "ningRequestBuilder", "=", "asyncHttpClient", ".", "preparePut", "(", "url", ")", ";", "return", "createNewRequestBuilder", "(", "url", ",", "ningRequestBuilder", ")", ";", "}" ]
Http put request @param url url for the request @return request builder
[ "Http", "put", "request" ]
9e43ab39230c5787065053da0f766d822d0fe4e7
https://github.com/outbrain/ob1k/blob/9e43ab39230c5787065053da0f766d822d0fe4e7/ob1k-http/src/main/java/com/outbrain/ob1k/http/HttpClient.java#L93-L98
1,005
outbrain/ob1k
ob1k-http/src/main/java/com/outbrain/ob1k/http/HttpClient.java
HttpClient.delete
public RequestBuilder delete(final String url) { checkNotNull(url, "url may not be null"); final AsyncHttpClient.BoundRequestBuilder ningRequestBuilder = asyncHttpClient.prepareDelete(url); return createNewRequestBuilder(url, ningRequestBuilder); }
java
public RequestBuilder delete(final String url) { checkNotNull(url, "url may not be null"); final AsyncHttpClient.BoundRequestBuilder ningRequestBuilder = asyncHttpClient.prepareDelete(url); return createNewRequestBuilder(url, ningRequestBuilder); }
[ "public", "RequestBuilder", "delete", "(", "final", "String", "url", ")", "{", "checkNotNull", "(", "url", ",", "\"url may not be null\"", ")", ";", "final", "AsyncHttpClient", ".", "BoundRequestBuilder", "ningRequestBuilder", "=", "asyncHttpClient", ".", "prepareDelete", "(", "url", ")", ";", "return", "createNewRequestBuilder", "(", "url", ",", "ningRequestBuilder", ")", ";", "}" ]
Http delete request @param url url for the request @return request builder
[ "Http", "delete", "request" ]
9e43ab39230c5787065053da0f766d822d0fe4e7
https://github.com/outbrain/ob1k/blob/9e43ab39230c5787065053da0f766d822d0fe4e7/ob1k-http/src/main/java/com/outbrain/ob1k/http/HttpClient.java#L106-L111
1,006
outbrain/ob1k
ob1k-http/src/main/java/com/outbrain/ob1k/http/HttpClient.java
HttpClient.head
public RequestBuilder head(final String url) { checkNotNull(url, "url may not be null"); final AsyncHttpClient.BoundRequestBuilder ningRequestBuilder = asyncHttpClient.prepareHead(url); return createNewRequestBuilder(url, ningRequestBuilder); }
java
public RequestBuilder head(final String url) { checkNotNull(url, "url may not be null"); final AsyncHttpClient.BoundRequestBuilder ningRequestBuilder = asyncHttpClient.prepareHead(url); return createNewRequestBuilder(url, ningRequestBuilder); }
[ "public", "RequestBuilder", "head", "(", "final", "String", "url", ")", "{", "checkNotNull", "(", "url", ",", "\"url may not be null\"", ")", ";", "final", "AsyncHttpClient", ".", "BoundRequestBuilder", "ningRequestBuilder", "=", "asyncHttpClient", ".", "prepareHead", "(", "url", ")", ";", "return", "createNewRequestBuilder", "(", "url", ",", "ningRequestBuilder", ")", ";", "}" ]
Http head request @param url url for the request @return request builder
[ "Http", "head", "request" ]
9e43ab39230c5787065053da0f766d822d0fe4e7
https://github.com/outbrain/ob1k/blob/9e43ab39230c5787065053da0f766d822d0fe4e7/ob1k-http/src/main/java/com/outbrain/ob1k/http/HttpClient.java#L119-L124
1,007
outbrain/ob1k
ob1k-core/src/main/java/com/outbrain/ob1k/server/netty/HttpStaticFileServerHandler.java
HttpStaticFileServerHandler.acceptInboundMessage
@Override public boolean acceptInboundMessage(final Object msg) throws Exception { if (!(msg instanceof FullHttpRequest)) return false; final FullHttpRequest request = (FullHttpRequest) msg; final String uri = request.getUri(); return pathResolver.isStaticPath(uri); }
java
@Override public boolean acceptInboundMessage(final Object msg) throws Exception { if (!(msg instanceof FullHttpRequest)) return false; final FullHttpRequest request = (FullHttpRequest) msg; final String uri = request.getUri(); return pathResolver.isStaticPath(uri); }
[ "@", "Override", "public", "boolean", "acceptInboundMessage", "(", "final", "Object", "msg", ")", "throws", "Exception", "{", "if", "(", "!", "(", "msg", "instanceof", "FullHttpRequest", ")", ")", "return", "false", ";", "final", "FullHttpRequest", "request", "=", "(", "FullHttpRequest", ")", "msg", ";", "final", "String", "uri", "=", "request", ".", "getUri", "(", ")", ";", "return", "pathResolver", ".", "isStaticPath", "(", "uri", ")", ";", "}" ]
here to make sure that the message is not released twice by the dispatcherHandler and by this handler
[ "here", "to", "make", "sure", "that", "the", "message", "is", "not", "released", "twice", "by", "the", "dispatcherHandler", "and", "by", "this", "handler" ]
9e43ab39230c5787065053da0f766d822d0fe4e7
https://github.com/outbrain/ob1k/blob/9e43ab39230c5787065053da0f766d822d0fe4e7/ob1k-core/src/main/java/com/outbrain/ob1k/server/netty/HttpStaticFileServerHandler.java#L92-L100
1,008
outbrain/ob1k
ob1k-core/src/main/java/com/outbrain/ob1k/server/netty/HttpStaticFileServerHandler.java
HttpStaticFileServerHandler.setDateHeader
private static void setDateHeader(final FullHttpResponse response) { final SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US); dateFormatter.setTimeZone(TimeZone.getTimeZone(HTTP_DATE_GMT_TIMEZONE)); final Calendar time = new GregorianCalendar(); response.headers().set(DATE, dateFormatter.format(time.getTime())); }
java
private static void setDateHeader(final FullHttpResponse response) { final SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US); dateFormatter.setTimeZone(TimeZone.getTimeZone(HTTP_DATE_GMT_TIMEZONE)); final Calendar time = new GregorianCalendar(); response.headers().set(DATE, dateFormatter.format(time.getTime())); }
[ "private", "static", "void", "setDateHeader", "(", "final", "FullHttpResponse", "response", ")", "{", "final", "SimpleDateFormat", "dateFormatter", "=", "new", "SimpleDateFormat", "(", "HTTP_DATE_FORMAT", ",", "Locale", ".", "US", ")", ";", "dateFormatter", ".", "setTimeZone", "(", "TimeZone", ".", "getTimeZone", "(", "HTTP_DATE_GMT_TIMEZONE", ")", ")", ";", "final", "Calendar", "time", "=", "new", "GregorianCalendar", "(", ")", ";", "response", ".", "headers", "(", ")", ".", "set", "(", "DATE", ",", "dateFormatter", ".", "format", "(", "time", ".", "getTime", "(", ")", ")", ")", ";", "}" ]
Sets the Date header for the HTTP response @param response HTTP response
[ "Sets", "the", "Date", "header", "for", "the", "HTTP", "response" ]
9e43ab39230c5787065053da0f766d822d0fe4e7
https://github.com/outbrain/ob1k/blob/9e43ab39230c5787065053da0f766d822d0fe4e7/ob1k-core/src/main/java/com/outbrain/ob1k/server/netty/HttpStaticFileServerHandler.java#L213-L219
1,009
cdapio/tigon
tigon-api/src/main/java/co/cask/tigon/internal/lang/Reflections.java
Reflections.isResolved
public static boolean isResolved(Type type) { if (type instanceof GenericArrayType) { return isResolved(((GenericArrayType) type).getGenericComponentType()); } if (type instanceof ParameterizedType) { for (Type t : ((ParameterizedType) type).getActualTypeArguments()) { if (!isResolved(t)) { return false; } } return true; } return type instanceof Class; }
java
public static boolean isResolved(Type type) { if (type instanceof GenericArrayType) { return isResolved(((GenericArrayType) type).getGenericComponentType()); } if (type instanceof ParameterizedType) { for (Type t : ((ParameterizedType) type).getActualTypeArguments()) { if (!isResolved(t)) { return false; } } return true; } return type instanceof Class; }
[ "public", "static", "boolean", "isResolved", "(", "Type", "type", ")", "{", "if", "(", "type", "instanceof", "GenericArrayType", ")", "{", "return", "isResolved", "(", "(", "(", "GenericArrayType", ")", "type", ")", ".", "getGenericComponentType", "(", ")", ")", ";", "}", "if", "(", "type", "instanceof", "ParameterizedType", ")", "{", "for", "(", "Type", "t", ":", "(", "(", "ParameterizedType", ")", "type", ")", ".", "getActualTypeArguments", "(", ")", ")", "{", "if", "(", "!", "isResolved", "(", "t", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}", "return", "type", "instanceof", "Class", ";", "}" ]
Checks if the given type is fully resolved.
[ "Checks", "if", "the", "given", "type", "is", "fully", "resolved", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-api/src/main/java/co/cask/tigon/internal/lang/Reflections.java#L38-L51
1,010
cdapio/tigon
tigon-api/src/main/java/co/cask/tigon/internal/lang/Reflections.java
Reflections.visit
public static void visit(Object instance, TypeToken<?> inspectType, Visitor firstVisitor, Visitor... moreVisitors) { try { List<Visitor> visitors = ImmutableList.<Visitor>builder().add(firstVisitor).add(moreVisitors).build(); for (TypeToken<?> type : inspectType.getTypes().classes()) { if (Object.class.equals(type.getRawType())) { break; } for (Field field : type.getRawType().getDeclaredFields()) { if (!field.isAccessible()) { field.setAccessible(true); } for (Visitor visitor : visitors) { visitor.visit(instance, inspectType, type, field); } } for (Method method : type.getRawType().getDeclaredMethods()) { if (!method.isAccessible()) { method.setAccessible(true); } for (Visitor visitor : visitors) { visitor.visit(instance, inspectType, type, method); } } } } catch (Exception e) { throw Throwables.propagate(e); } }
java
public static void visit(Object instance, TypeToken<?> inspectType, Visitor firstVisitor, Visitor... moreVisitors) { try { List<Visitor> visitors = ImmutableList.<Visitor>builder().add(firstVisitor).add(moreVisitors).build(); for (TypeToken<?> type : inspectType.getTypes().classes()) { if (Object.class.equals(type.getRawType())) { break; } for (Field field : type.getRawType().getDeclaredFields()) { if (!field.isAccessible()) { field.setAccessible(true); } for (Visitor visitor : visitors) { visitor.visit(instance, inspectType, type, field); } } for (Method method : type.getRawType().getDeclaredMethods()) { if (!method.isAccessible()) { method.setAccessible(true); } for (Visitor visitor : visitors) { visitor.visit(instance, inspectType, type, method); } } } } catch (Exception e) { throw Throwables.propagate(e); } }
[ "public", "static", "void", "visit", "(", "Object", "instance", ",", "TypeToken", "<", "?", ">", "inspectType", ",", "Visitor", "firstVisitor", ",", "Visitor", "...", "moreVisitors", ")", "{", "try", "{", "List", "<", "Visitor", ">", "visitors", "=", "ImmutableList", ".", "<", "Visitor", ">", "builder", "(", ")", ".", "add", "(", "firstVisitor", ")", ".", "add", "(", "moreVisitors", ")", ".", "build", "(", ")", ";", "for", "(", "TypeToken", "<", "?", ">", "type", ":", "inspectType", ".", "getTypes", "(", ")", ".", "classes", "(", ")", ")", "{", "if", "(", "Object", ".", "class", ".", "equals", "(", "type", ".", "getRawType", "(", ")", ")", ")", "{", "break", ";", "}", "for", "(", "Field", "field", ":", "type", ".", "getRawType", "(", ")", ".", "getDeclaredFields", "(", ")", ")", "{", "if", "(", "!", "field", ".", "isAccessible", "(", ")", ")", "{", "field", ".", "setAccessible", "(", "true", ")", ";", "}", "for", "(", "Visitor", "visitor", ":", "visitors", ")", "{", "visitor", ".", "visit", "(", "instance", ",", "inspectType", ",", "type", ",", "field", ")", ";", "}", "}", "for", "(", "Method", "method", ":", "type", ".", "getRawType", "(", ")", ".", "getDeclaredMethods", "(", ")", ")", "{", "if", "(", "!", "method", ".", "isAccessible", "(", ")", ")", "{", "method", ".", "setAccessible", "(", "true", ")", ";", "}", "for", "(", "Visitor", "visitor", ":", "visitors", ")", "{", "visitor", ".", "visit", "(", "instance", ",", "inspectType", ",", "type", ",", "method", ")", ";", "}", "}", "}", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "Throwables", ".", "propagate", "(", "e", ")", ";", "}", "}" ]
Inspect all members in the given type. Fields and Methods that are given to Visitor are always having accessible flag being set.
[ "Inspect", "all", "members", "in", "the", "given", "type", ".", "Fields", "and", "Methods", "that", "are", "given", "to", "Visitor", "are", "always", "having", "accessible", "flag", "being", "set", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-api/src/main/java/co/cask/tigon/internal/lang/Reflections.java#L58-L89
1,011
cdapio/tigon
tigon-queue/src/main/java/co/cask/tigon/data/transaction/queue/QueueEntryRow.java
QueueEntryRow.getQueueRowPrefix
public static byte[] getQueueRowPrefix(QueueName queueName) { if (queueName.isStream()) { // NOTE: stream is uniquely identified by table name return Bytes.EMPTY_BYTE_ARRAY; } String flowlet = queueName.getThirdComponent(); String output = queueName.getSimpleName(); byte[] idWithinFlow = (flowlet + "/" + output).getBytes(Charsets.US_ASCII); return getQueueRowPrefix(idWithinFlow); }
java
public static byte[] getQueueRowPrefix(QueueName queueName) { if (queueName.isStream()) { // NOTE: stream is uniquely identified by table name return Bytes.EMPTY_BYTE_ARRAY; } String flowlet = queueName.getThirdComponent(); String output = queueName.getSimpleName(); byte[] idWithinFlow = (flowlet + "/" + output).getBytes(Charsets.US_ASCII); return getQueueRowPrefix(idWithinFlow); }
[ "public", "static", "byte", "[", "]", "getQueueRowPrefix", "(", "QueueName", "queueName", ")", "{", "if", "(", "queueName", ".", "isStream", "(", ")", ")", "{", "// NOTE: stream is uniquely identified by table name", "return", "Bytes", ".", "EMPTY_BYTE_ARRAY", ";", "}", "String", "flowlet", "=", "queueName", ".", "getThirdComponent", "(", ")", ";", "String", "output", "=", "queueName", ".", "getSimpleName", "(", ")", ";", "byte", "[", "]", "idWithinFlow", "=", "(", "flowlet", "+", "\"/\"", "+", "output", ")", ".", "getBytes", "(", "Charsets", ".", "US_ASCII", ")", ";", "return", "getQueueRowPrefix", "(", "idWithinFlow", ")", ";", "}" ]
Returns a byte array representing prefix of a queue. The prefix is formed by first two bytes of MD5 of the queue name followed by the queue name.
[ "Returns", "a", "byte", "array", "representing", "prefix", "of", "a", "queue", ".", "The", "prefix", "is", "formed", "by", "first", "two", "bytes", "of", "MD5", "of", "the", "queue", "name", "followed", "by", "the", "queue", "name", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-queue/src/main/java/co/cask/tigon/data/transaction/queue/QueueEntryRow.java#L50-L60
1,012
cdapio/tigon
tigon-queue/src/main/java/co/cask/tigon/data/transaction/queue/QueueEntryRow.java
QueueEntryRow.getQueueRowPrefix
private static byte[] getQueueRowPrefix(byte[] queueIdWithinFlow) { byte[] bytes = new byte[queueIdWithinFlow.length + 1]; Hashing.md5().hashBytes(queueIdWithinFlow).writeBytesTo(bytes, 0, 1); System.arraycopy(queueIdWithinFlow, 0, bytes, 1, queueIdWithinFlow.length); return bytes; }
java
private static byte[] getQueueRowPrefix(byte[] queueIdWithinFlow) { byte[] bytes = new byte[queueIdWithinFlow.length + 1]; Hashing.md5().hashBytes(queueIdWithinFlow).writeBytesTo(bytes, 0, 1); System.arraycopy(queueIdWithinFlow, 0, bytes, 1, queueIdWithinFlow.length); return bytes; }
[ "private", "static", "byte", "[", "]", "getQueueRowPrefix", "(", "byte", "[", "]", "queueIdWithinFlow", ")", "{", "byte", "[", "]", "bytes", "=", "new", "byte", "[", "queueIdWithinFlow", ".", "length", "+", "1", "]", ";", "Hashing", ".", "md5", "(", ")", ".", "hashBytes", "(", "queueIdWithinFlow", ")", ".", "writeBytesTo", "(", "bytes", ",", "0", ",", "1", ")", ";", "System", ".", "arraycopy", "(", "queueIdWithinFlow", ",", "0", ",", "bytes", ",", "1", ",", "queueIdWithinFlow", ".", "length", ")", ";", "return", "bytes", ";", "}" ]
Returns a byte array representing prefix of a queue. The prefix is formed by first byte of MD5 of the queue name followed by the queue name.
[ "Returns", "a", "byte", "array", "representing", "prefix", "of", "a", "queue", ".", "The", "prefix", "is", "formed", "by", "first", "byte", "of", "MD5", "of", "the", "queue", "name", "followed", "by", "the", "queue", "name", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-queue/src/main/java/co/cask/tigon/data/transaction/queue/QueueEntryRow.java#L66-L72
1,013
cdapio/tigon
tigon-queue/src/main/java/co/cask/tigon/data/transaction/queue/QueueEntryRow.java
QueueEntryRow.isCommittedProcessed
public static boolean isCommittedProcessed(byte[] stateBytes, Transaction tx) { long writePointer = Bytes.toLong(stateBytes, 0, Longs.BYTES); if (!tx.isVisible(writePointer)) { return false; } byte state = stateBytes[Longs.BYTES + Ints.BYTES]; return state == ConsumerEntryState.PROCESSED.getState(); }
java
public static boolean isCommittedProcessed(byte[] stateBytes, Transaction tx) { long writePointer = Bytes.toLong(stateBytes, 0, Longs.BYTES); if (!tx.isVisible(writePointer)) { return false; } byte state = stateBytes[Longs.BYTES + Ints.BYTES]; return state == ConsumerEntryState.PROCESSED.getState(); }
[ "public", "static", "boolean", "isCommittedProcessed", "(", "byte", "[", "]", "stateBytes", ",", "Transaction", "tx", ")", "{", "long", "writePointer", "=", "Bytes", ".", "toLong", "(", "stateBytes", ",", "0", ",", "Longs", ".", "BYTES", ")", ";", "if", "(", "!", "tx", ".", "isVisible", "(", "writePointer", ")", ")", "{", "return", "false", ";", "}", "byte", "state", "=", "stateBytes", "[", "Longs", ".", "BYTES", "+", "Ints", ".", "BYTES", "]", ";", "return", "state", "==", "ConsumerEntryState", ".", "PROCESSED", ".", "getState", "(", ")", ";", "}" ]
For a queue entry consumer state, serialized to byte array, return whether it is processed and committed.
[ "For", "a", "queue", "entry", "consumer", "state", "serialized", "to", "byte", "array", "return", "whether", "it", "is", "processed", "and", "committed", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-queue/src/main/java/co/cask/tigon/data/transaction/queue/QueueEntryRow.java#L320-L327
1,014
cdapio/tigon
tigon-yarn/src/main/java/co/cask/tigon/conf/Configuration.java
Configuration.getAlternateNames
private String[] getAlternateNames(String name) { String oldName, altNames[] = null; DeprecatedKeyInfo keyInfo = deprecatedKeyMap.get(name); if (keyInfo == null) { altNames = (reverseDeprecatedKeyMap.get(name) != null) ? new String [] {reverseDeprecatedKeyMap.get(name)} : null; if (altNames != null && altNames.length > 0) { //To help look for other new configs for this deprecated config keyInfo = deprecatedKeyMap.get(altNames[0]); } } if (keyInfo != null && keyInfo.newKeys.length > 0) { List<String> list = new ArrayList<String>(); if (altNames != null) { list.addAll(Arrays.asList(altNames)); } list.addAll(Arrays.asList(keyInfo.newKeys)); altNames = list.toArray(new String[list.size()]); } return altNames; }
java
private String[] getAlternateNames(String name) { String oldName, altNames[] = null; DeprecatedKeyInfo keyInfo = deprecatedKeyMap.get(name); if (keyInfo == null) { altNames = (reverseDeprecatedKeyMap.get(name) != null) ? new String [] {reverseDeprecatedKeyMap.get(name)} : null; if (altNames != null && altNames.length > 0) { //To help look for other new configs for this deprecated config keyInfo = deprecatedKeyMap.get(altNames[0]); } } if (keyInfo != null && keyInfo.newKeys.length > 0) { List<String> list = new ArrayList<String>(); if (altNames != null) { list.addAll(Arrays.asList(altNames)); } list.addAll(Arrays.asList(keyInfo.newKeys)); altNames = list.toArray(new String[list.size()]); } return altNames; }
[ "private", "String", "[", "]", "getAlternateNames", "(", "String", "name", ")", "{", "String", "oldName", ",", "altNames", "[", "]", "=", "null", ";", "DeprecatedKeyInfo", "keyInfo", "=", "deprecatedKeyMap", ".", "get", "(", "name", ")", ";", "if", "(", "keyInfo", "==", "null", ")", "{", "altNames", "=", "(", "reverseDeprecatedKeyMap", ".", "get", "(", "name", ")", "!=", "null", ")", "?", "new", "String", "[", "]", "{", "reverseDeprecatedKeyMap", ".", "get", "(", "name", ")", "}", ":", "null", ";", "if", "(", "altNames", "!=", "null", "&&", "altNames", ".", "length", ">", "0", ")", "{", "//To help look for other new configs for this deprecated config", "keyInfo", "=", "deprecatedKeyMap", ".", "get", "(", "altNames", "[", "0", "]", ")", ";", "}", "}", "if", "(", "keyInfo", "!=", "null", "&&", "keyInfo", ".", "newKeys", ".", "length", ">", "0", ")", "{", "List", "<", "String", ">", "list", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "if", "(", "altNames", "!=", "null", ")", "{", "list", ".", "addAll", "(", "Arrays", ".", "asList", "(", "altNames", ")", ")", ";", "}", "list", ".", "addAll", "(", "Arrays", ".", "asList", "(", "keyInfo", ".", "newKeys", ")", ")", ";", "altNames", "=", "list", ".", "toArray", "(", "new", "String", "[", "list", ".", "size", "(", ")", "]", ")", ";", "}", "return", "altNames", ";", "}" ]
Returns the alternate name for a key if the property name is deprecated or if deprecates a property name. @param name property name. @return alternate name.
[ "Returns", "the", "alternate", "name", "for", "a", "key", "if", "the", "property", "name", "is", "deprecated", "or", "if", "deprecates", "a", "property", "name", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-yarn/src/main/java/co/cask/tigon/conf/Configuration.java#L255-L275
1,015
cdapio/tigon
tigon-yarn/src/main/java/co/cask/tigon/conf/Configuration.java
Configuration.getRange
public IntegerRanges getRange(String name) { String valueString = get(name); Preconditions.checkNotNull(valueString); return new IntegerRanges(valueString); }
java
public IntegerRanges getRange(String name) { String valueString = get(name); Preconditions.checkNotNull(valueString); return new IntegerRanges(valueString); }
[ "public", "IntegerRanges", "getRange", "(", "String", "name", ")", "{", "String", "valueString", "=", "get", "(", "name", ")", ";", "Preconditions", ".", "checkNotNull", "(", "valueString", ")", ";", "return", "new", "IntegerRanges", "(", "valueString", ")", ";", "}" ]
Parse the given attribute as a set of integer ranges. @param name the attribute name @throws NullPointerException if the configuration property does not exist @return a new set of ranges from the configured value
[ "Parse", "the", "given", "attribute", "as", "a", "set", "of", "integer", "ranges", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-yarn/src/main/java/co/cask/tigon/conf/Configuration.java#L1138-L1142
1,016
cdapio/tigon
tigon-yarn/src/main/java/co/cask/tigon/conf/Configuration.java
Configuration.getValByRegex
public Map<String, String> getValByRegex(String regex) { Pattern p = Pattern.compile(regex); Map<String, String> result = new HashMap<String, String>(); Matcher m; for (Map.Entry<Object, Object> item: getProps().entrySet()) { if (item.getKey() instanceof String && item.getValue() instanceof String) { m = p.matcher((String) item.getKey()); if (m.find()) { // match result.put((String) item.getKey(), (String) item.getValue()); } } } return result; }
java
public Map<String, String> getValByRegex(String regex) { Pattern p = Pattern.compile(regex); Map<String, String> result = new HashMap<String, String>(); Matcher m; for (Map.Entry<Object, Object> item: getProps().entrySet()) { if (item.getKey() instanceof String && item.getValue() instanceof String) { m = p.matcher((String) item.getKey()); if (m.find()) { // match result.put((String) item.getKey(), (String) item.getValue()); } } } return result; }
[ "public", "Map", "<", "String", ",", "String", ">", "getValByRegex", "(", "String", "regex", ")", "{", "Pattern", "p", "=", "Pattern", ".", "compile", "(", "regex", ")", ";", "Map", "<", "String", ",", "String", ">", "result", "=", "new", "HashMap", "<", "String", ",", "String", ">", "(", ")", ";", "Matcher", "m", ";", "for", "(", "Map", ".", "Entry", "<", "Object", ",", "Object", ">", "item", ":", "getProps", "(", ")", ".", "entrySet", "(", ")", ")", "{", "if", "(", "item", ".", "getKey", "(", ")", "instanceof", "String", "&&", "item", ".", "getValue", "(", ")", "instanceof", "String", ")", "{", "m", "=", "p", ".", "matcher", "(", "(", "String", ")", "item", ".", "getKey", "(", ")", ")", ";", "if", "(", "m", ".", "find", "(", ")", ")", "{", "// match", "result", ".", "put", "(", "(", "String", ")", "item", ".", "getKey", "(", ")", ",", "(", "String", ")", "item", ".", "getValue", "(", ")", ")", ";", "}", "}", "}", "return", "result", ";", "}" ]
get keys matching the the regex. @param regex @return Map<String,String> with matching keys
[ "get", "keys", "matching", "the", "the", "regex", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-yarn/src/main/java/co/cask/tigon/conf/Configuration.java#L1886-L1902
1,017
cdapio/tigon
tigon-flow/src/main/java/co/cask/tigon/internal/app/runtime/AbstractProgramController.java
AbstractProgramController.error
protected final <V> void error(Throwable t, SettableFuture<V> future) { state.set(State.ERROR); if (future != null) { future.setException(t); } caller.error(t); }
java
protected final <V> void error(Throwable t, SettableFuture<V> future) { state.set(State.ERROR); if (future != null) { future.setException(t); } caller.error(t); }
[ "protected", "final", "<", "V", ">", "void", "error", "(", "Throwable", "t", ",", "SettableFuture", "<", "V", ">", "future", ")", "{", "state", ".", "set", "(", "State", ".", "ERROR", ")", ";", "if", "(", "future", "!=", "null", ")", "{", "future", ".", "setException", "(", "t", ")", ";", "}", "caller", ".", "error", "(", "t", ")", ";", "}" ]
Force this controller into error state. @param t The
[ "Force", "this", "controller", "into", "error", "state", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-flow/src/main/java/co/cask/tigon/internal/app/runtime/AbstractProgramController.java#L185-L191
1,018
cdapio/tigon
tigon-flow/src/main/java/co/cask/tigon/internal/app/runtime/AbstractProgramController.java
AbstractProgramController.started
protected final void started() { if (!state.compareAndSet(State.STARTING, State.ALIVE)) { LOG.info("Program already started {} {}", programName, runId); return; } LOG.info("Program started: {} {}", programName, runId); executor(State.ALIVE).execute(new Runnable() { @Override public void run() { state.set(State.ALIVE); caller.alive(); } }); }
java
protected final void started() { if (!state.compareAndSet(State.STARTING, State.ALIVE)) { LOG.info("Program already started {} {}", programName, runId); return; } LOG.info("Program started: {} {}", programName, runId); executor(State.ALIVE).execute(new Runnable() { @Override public void run() { state.set(State.ALIVE); caller.alive(); } }); }
[ "protected", "final", "void", "started", "(", ")", "{", "if", "(", "!", "state", ".", "compareAndSet", "(", "State", ".", "STARTING", ",", "State", ".", "ALIVE", ")", ")", "{", "LOG", ".", "info", "(", "\"Program already started {} {}\"", ",", "programName", ",", "runId", ")", ";", "return", ";", "}", "LOG", ".", "info", "(", "\"Program started: {} {}\"", ",", "programName", ",", "runId", ")", ";", "executor", "(", "State", ".", "ALIVE", ")", ".", "execute", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "state", ".", "set", "(", "State", ".", "ALIVE", ")", ";", "caller", ".", "alive", "(", ")", ";", "}", "}", ")", ";", "}" ]
Children call this method to signal the program is started.
[ "Children", "call", "this", "method", "to", "signal", "the", "program", "is", "started", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-flow/src/main/java/co/cask/tigon/internal/app/runtime/AbstractProgramController.java#L196-L209
1,019
cdapio/tigon
tigon-flow/src/main/java/co/cask/tigon/internal/app/runtime/distributed/AbstractProgramTwillRunnable.java
AbstractProgramTwillRunnable.createProgramArguments
private Arguments createProgramArguments(TwillContext context, Map<String, String> configs) { Map<String, String> args = ImmutableMap.<String, String>builder() .put(ProgramOptionConstants.INSTANCE_ID, Integer.toString(context.getInstanceId())) .put(ProgramOptionConstants.INSTANCES, Integer.toString(context.getInstanceCount())) .put(ProgramOptionConstants.RUN_ID, context.getApplicationRunId().getId()) .putAll(Maps.filterKeys(configs, Predicates.not(Predicates.in(ImmutableSet.of("hConf", "cConf"))))) .build(); return new BasicArguments(args); }
java
private Arguments createProgramArguments(TwillContext context, Map<String, String> configs) { Map<String, String> args = ImmutableMap.<String, String>builder() .put(ProgramOptionConstants.INSTANCE_ID, Integer.toString(context.getInstanceId())) .put(ProgramOptionConstants.INSTANCES, Integer.toString(context.getInstanceCount())) .put(ProgramOptionConstants.RUN_ID, context.getApplicationRunId().getId()) .putAll(Maps.filterKeys(configs, Predicates.not(Predicates.in(ImmutableSet.of("hConf", "cConf"))))) .build(); return new BasicArguments(args); }
[ "private", "Arguments", "createProgramArguments", "(", "TwillContext", "context", ",", "Map", "<", "String", ",", "String", ">", "configs", ")", "{", "Map", "<", "String", ",", "String", ">", "args", "=", "ImmutableMap", ".", "<", "String", ",", "String", ">", "builder", "(", ")", ".", "put", "(", "ProgramOptionConstants", ".", "INSTANCE_ID", ",", "Integer", ".", "toString", "(", "context", ".", "getInstanceId", "(", ")", ")", ")", ".", "put", "(", "ProgramOptionConstants", ".", "INSTANCES", ",", "Integer", ".", "toString", "(", "context", ".", "getInstanceCount", "(", ")", ")", ")", ".", "put", "(", "ProgramOptionConstants", ".", "RUN_ID", ",", "context", ".", "getApplicationRunId", "(", ")", ".", "getId", "(", ")", ")", ".", "putAll", "(", "Maps", ".", "filterKeys", "(", "configs", ",", "Predicates", ".", "not", "(", "Predicates", ".", "in", "(", "ImmutableSet", ".", "of", "(", "\"hConf\"", ",", "\"cConf\"", ")", ")", ")", ")", ")", ".", "build", "(", ")", ";", "return", "new", "BasicArguments", "(", "args", ")", ";", "}" ]
Creates program arguments. It includes all configurations from the specification, excluding hConf and cConf.
[ "Creates", "program", "arguments", ".", "It", "includes", "all", "configurations", "from", "the", "specification", "excluding", "hConf", "and", "cConf", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-flow/src/main/java/co/cask/tigon/internal/app/runtime/distributed/AbstractProgramTwillRunnable.java#L276-L285
1,020
cdapio/tigon
tigon-api/src/main/java/co/cask/tigon/internal/io/AbstractSchemaGenerator.java
AbstractSchemaGenerator.doGenerate
@SuppressWarnings("unchecked") protected final Schema doGenerate(TypeToken<?> typeToken, Set<String> knownRecords, boolean acceptRecursion) throws UnsupportedTypeException { Type type = typeToken.getType(); Class<?> rawType = typeToken.getRawType(); if (SIMPLE_SCHEMAS.containsKey(rawType)) { return SIMPLE_SCHEMAS.get(rawType); } // Enum type, simply use all the enum constants for ENUM schema. if (rawType.isEnum()) { return Schema.enumWith((Class<Enum<?>>) rawType); } // Java array, use ARRAY schema. if (rawType.isArray()) { Schema componentSchema = doGenerate(TypeToken.of(rawType.getComponentType()), knownRecords, acceptRecursion); if (rawType.getComponentType().isPrimitive()) { return Schema.arrayOf(componentSchema); } return Schema.arrayOf(Schema.unionOf(componentSchema, Schema.of(Schema.Type.NULL))); } if (!(type instanceof Class || type instanceof ParameterizedType)) { throw new UnsupportedTypeException("Type " + type + " is not supported. " + "Only Class or ParameterizedType are supported."); } // Any parameterized Collection class would be represented by ARRAY schema. if (Collection.class.isAssignableFrom(rawType)) { if (!(type instanceof ParameterizedType)) { throw new UnsupportedTypeException("Only supports parameterized Collection type."); } TypeToken<?> componentType = typeToken.resolveType(((ParameterizedType) type).getActualTypeArguments()[0]); Schema componentSchema = doGenerate(componentType, knownRecords, acceptRecursion); return Schema.arrayOf(Schema.unionOf(componentSchema, Schema.of(Schema.Type.NULL))); } // Java Map, use MAP schema. if (Map.class.isAssignableFrom(rawType)) { if (!(type instanceof ParameterizedType)) { throw new UnsupportedTypeException("Only supports parameterized Map type."); } Type[] typeArgs = ((ParameterizedType) type).getActualTypeArguments(); TypeToken<?> keyType = typeToken.resolveType(typeArgs[0]); TypeToken<?> valueType = typeToken.resolveType(typeArgs[1]); Schema valueSchema = doGenerate(valueType, knownRecords, acceptRecursion); return Schema.mapOf(doGenerate(keyType, knownRecords, acceptRecursion), Schema.unionOf(valueSchema, Schema.of(Schema.Type.NULL))); } // Any Java class, class name as the record name. String recordName = typeToken.getRawType().getName(); if (knownRecords.contains(recordName)) { // Record already seen before if (acceptRecursion) { // simply create a reference RECORD schema by the name. return Schema.recordOf(recordName); } else { throw new UnsupportedTypeException("Recursive type not supported for class " + recordName); } } // Delegate to child class to generate RECORD schema. return generateRecord(typeToken, knownRecords, acceptRecursion); }
java
@SuppressWarnings("unchecked") protected final Schema doGenerate(TypeToken<?> typeToken, Set<String> knownRecords, boolean acceptRecursion) throws UnsupportedTypeException { Type type = typeToken.getType(); Class<?> rawType = typeToken.getRawType(); if (SIMPLE_SCHEMAS.containsKey(rawType)) { return SIMPLE_SCHEMAS.get(rawType); } // Enum type, simply use all the enum constants for ENUM schema. if (rawType.isEnum()) { return Schema.enumWith((Class<Enum<?>>) rawType); } // Java array, use ARRAY schema. if (rawType.isArray()) { Schema componentSchema = doGenerate(TypeToken.of(rawType.getComponentType()), knownRecords, acceptRecursion); if (rawType.getComponentType().isPrimitive()) { return Schema.arrayOf(componentSchema); } return Schema.arrayOf(Schema.unionOf(componentSchema, Schema.of(Schema.Type.NULL))); } if (!(type instanceof Class || type instanceof ParameterizedType)) { throw new UnsupportedTypeException("Type " + type + " is not supported. " + "Only Class or ParameterizedType are supported."); } // Any parameterized Collection class would be represented by ARRAY schema. if (Collection.class.isAssignableFrom(rawType)) { if (!(type instanceof ParameterizedType)) { throw new UnsupportedTypeException("Only supports parameterized Collection type."); } TypeToken<?> componentType = typeToken.resolveType(((ParameterizedType) type).getActualTypeArguments()[0]); Schema componentSchema = doGenerate(componentType, knownRecords, acceptRecursion); return Schema.arrayOf(Schema.unionOf(componentSchema, Schema.of(Schema.Type.NULL))); } // Java Map, use MAP schema. if (Map.class.isAssignableFrom(rawType)) { if (!(type instanceof ParameterizedType)) { throw new UnsupportedTypeException("Only supports parameterized Map type."); } Type[] typeArgs = ((ParameterizedType) type).getActualTypeArguments(); TypeToken<?> keyType = typeToken.resolveType(typeArgs[0]); TypeToken<?> valueType = typeToken.resolveType(typeArgs[1]); Schema valueSchema = doGenerate(valueType, knownRecords, acceptRecursion); return Schema.mapOf(doGenerate(keyType, knownRecords, acceptRecursion), Schema.unionOf(valueSchema, Schema.of(Schema.Type.NULL))); } // Any Java class, class name as the record name. String recordName = typeToken.getRawType().getName(); if (knownRecords.contains(recordName)) { // Record already seen before if (acceptRecursion) { // simply create a reference RECORD schema by the name. return Schema.recordOf(recordName); } else { throw new UnsupportedTypeException("Recursive type not supported for class " + recordName); } } // Delegate to child class to generate RECORD schema. return generateRecord(typeToken, knownRecords, acceptRecursion); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "protected", "final", "Schema", "doGenerate", "(", "TypeToken", "<", "?", ">", "typeToken", ",", "Set", "<", "String", ">", "knownRecords", ",", "boolean", "acceptRecursion", ")", "throws", "UnsupportedTypeException", "{", "Type", "type", "=", "typeToken", ".", "getType", "(", ")", ";", "Class", "<", "?", ">", "rawType", "=", "typeToken", ".", "getRawType", "(", ")", ";", "if", "(", "SIMPLE_SCHEMAS", ".", "containsKey", "(", "rawType", ")", ")", "{", "return", "SIMPLE_SCHEMAS", ".", "get", "(", "rawType", ")", ";", "}", "// Enum type, simply use all the enum constants for ENUM schema.", "if", "(", "rawType", ".", "isEnum", "(", ")", ")", "{", "return", "Schema", ".", "enumWith", "(", "(", "Class", "<", "Enum", "<", "?", ">", ">", ")", "rawType", ")", ";", "}", "// Java array, use ARRAY schema.", "if", "(", "rawType", ".", "isArray", "(", ")", ")", "{", "Schema", "componentSchema", "=", "doGenerate", "(", "TypeToken", ".", "of", "(", "rawType", ".", "getComponentType", "(", ")", ")", ",", "knownRecords", ",", "acceptRecursion", ")", ";", "if", "(", "rawType", ".", "getComponentType", "(", ")", ".", "isPrimitive", "(", ")", ")", "{", "return", "Schema", ".", "arrayOf", "(", "componentSchema", ")", ";", "}", "return", "Schema", ".", "arrayOf", "(", "Schema", ".", "unionOf", "(", "componentSchema", ",", "Schema", ".", "of", "(", "Schema", ".", "Type", ".", "NULL", ")", ")", ")", ";", "}", "if", "(", "!", "(", "type", "instanceof", "Class", "||", "type", "instanceof", "ParameterizedType", ")", ")", "{", "throw", "new", "UnsupportedTypeException", "(", "\"Type \"", "+", "type", "+", "\" is not supported. \"", "+", "\"Only Class or ParameterizedType are supported.\"", ")", ";", "}", "// Any parameterized Collection class would be represented by ARRAY schema.", "if", "(", "Collection", ".", "class", ".", "isAssignableFrom", "(", "rawType", ")", ")", "{", "if", "(", "!", "(", "type", "instanceof", "ParameterizedType", ")", ")", "{", "throw", "new", "UnsupportedTypeException", "(", "\"Only supports parameterized Collection type.\"", ")", ";", "}", "TypeToken", "<", "?", ">", "componentType", "=", "typeToken", ".", "resolveType", "(", "(", "(", "ParameterizedType", ")", "type", ")", ".", "getActualTypeArguments", "(", ")", "[", "0", "]", ")", ";", "Schema", "componentSchema", "=", "doGenerate", "(", "componentType", ",", "knownRecords", ",", "acceptRecursion", ")", ";", "return", "Schema", ".", "arrayOf", "(", "Schema", ".", "unionOf", "(", "componentSchema", ",", "Schema", ".", "of", "(", "Schema", ".", "Type", ".", "NULL", ")", ")", ")", ";", "}", "// Java Map, use MAP schema.", "if", "(", "Map", ".", "class", ".", "isAssignableFrom", "(", "rawType", ")", ")", "{", "if", "(", "!", "(", "type", "instanceof", "ParameterizedType", ")", ")", "{", "throw", "new", "UnsupportedTypeException", "(", "\"Only supports parameterized Map type.\"", ")", ";", "}", "Type", "[", "]", "typeArgs", "=", "(", "(", "ParameterizedType", ")", "type", ")", ".", "getActualTypeArguments", "(", ")", ";", "TypeToken", "<", "?", ">", "keyType", "=", "typeToken", ".", "resolveType", "(", "typeArgs", "[", "0", "]", ")", ";", "TypeToken", "<", "?", ">", "valueType", "=", "typeToken", ".", "resolveType", "(", "typeArgs", "[", "1", "]", ")", ";", "Schema", "valueSchema", "=", "doGenerate", "(", "valueType", ",", "knownRecords", ",", "acceptRecursion", ")", ";", "return", "Schema", ".", "mapOf", "(", "doGenerate", "(", "keyType", ",", "knownRecords", ",", "acceptRecursion", ")", ",", "Schema", ".", "unionOf", "(", "valueSchema", ",", "Schema", ".", "of", "(", "Schema", ".", "Type", ".", "NULL", ")", ")", ")", ";", "}", "// Any Java class, class name as the record name.", "String", "recordName", "=", "typeToken", ".", "getRawType", "(", ")", ".", "getName", "(", ")", ";", "if", "(", "knownRecords", ".", "contains", "(", "recordName", ")", ")", "{", "// Record already seen before", "if", "(", "acceptRecursion", ")", "{", "// simply create a reference RECORD schema by the name.", "return", "Schema", ".", "recordOf", "(", "recordName", ")", ";", "}", "else", "{", "throw", "new", "UnsupportedTypeException", "(", "\"Recursive type not supported for class \"", "+", "recordName", ")", ";", "}", "}", "// Delegate to child class to generate RECORD schema.", "return", "generateRecord", "(", "typeToken", ",", "knownRecords", ",", "acceptRecursion", ")", ";", "}" ]
Actual schema generation. It recursively resolves container types. @param typeToken Encapsulate the Java type for generating a {@link Schema}. @param knownRecords Set of record names that has the schema already generated. It is used for recursive class field references. @param acceptRecursion Whether to tolerate type recursion. If false, will throw UnsupportedTypeException if a recursive type is encountered. @return A {@link Schema} representing the given java {@link java.lang.reflect.Type}. @throws UnsupportedTypeException Indicates schema generation is not support for the given java {@link java.lang.reflect.Type}.
[ "Actual", "schema", "generation", ".", "It", "recursively", "resolves", "container", "types", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-api/src/main/java/co/cask/tigon/internal/io/AbstractSchemaGenerator.java#L99-L167
1,021
cdapio/tigon
tigon-flow/src/main/java/co/cask/tigon/internal/app/runtime/flow/ConsumerSupplier.java
ConsumerSupplier.open
void open(int groupSize) { try { close(); ConsumerConfig config = consumerConfig; if (groupSize != config.getGroupSize()) { config = new ConsumerConfig(consumerConfig.getGroupId(), consumerConfig.getInstanceId(), groupSize, consumerConfig.getDequeueStrategy(), consumerConfig.getHashKey()); } if (queueName.isQueue()) { QueueConsumer queueConsumer = dataFabricFacade.createConsumer(queueName, config, numGroups); consumerConfig = queueConsumer.getConfig(); consumer = queueConsumer; } } catch (Exception e) { throw Throwables.propagate(e); } }
java
void open(int groupSize) { try { close(); ConsumerConfig config = consumerConfig; if (groupSize != config.getGroupSize()) { config = new ConsumerConfig(consumerConfig.getGroupId(), consumerConfig.getInstanceId(), groupSize, consumerConfig.getDequeueStrategy(), consumerConfig.getHashKey()); } if (queueName.isQueue()) { QueueConsumer queueConsumer = dataFabricFacade.createConsumer(queueName, config, numGroups); consumerConfig = queueConsumer.getConfig(); consumer = queueConsumer; } } catch (Exception e) { throw Throwables.propagate(e); } }
[ "void", "open", "(", "int", "groupSize", ")", "{", "try", "{", "close", "(", ")", ";", "ConsumerConfig", "config", "=", "consumerConfig", ";", "if", "(", "groupSize", "!=", "config", ".", "getGroupSize", "(", ")", ")", "{", "config", "=", "new", "ConsumerConfig", "(", "consumerConfig", ".", "getGroupId", "(", ")", ",", "consumerConfig", ".", "getInstanceId", "(", ")", ",", "groupSize", ",", "consumerConfig", ".", "getDequeueStrategy", "(", ")", ",", "consumerConfig", ".", "getHashKey", "(", ")", ")", ";", "}", "if", "(", "queueName", ".", "isQueue", "(", ")", ")", "{", "QueueConsumer", "queueConsumer", "=", "dataFabricFacade", ".", "createConsumer", "(", "queueName", ",", "config", ",", "numGroups", ")", ";", "consumerConfig", "=", "queueConsumer", ".", "getConfig", "(", ")", ";", "consumer", "=", "queueConsumer", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "Throwables", ".", "propagate", "(", "e", ")", ";", "}", "}" ]
Updates number of instances for the consumer group that this instance belongs to. It'll close existing consumer and create a new one with the new group size. @param groupSize New group size.
[ "Updates", "number", "of", "instances", "for", "the", "consumer", "group", "that", "this", "instance", "belongs", "to", ".", "It", "ll", "close", "existing", "consumer", "and", "create", "a", "new", "one", "with", "the", "new", "group", "size", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-flow/src/main/java/co/cask/tigon/internal/app/runtime/flow/ConsumerSupplier.java#L75-L94
1,022
cdapio/tigon
tigon-flow/src/main/java/co/cask/tigon/internal/app/runtime/flow/ConsumerSupplier.java
ConsumerSupplier.close
@Override public void close() throws IOException { try { if (consumer != null && consumer instanceof Closeable) { // Call close in a new transaction. // TODO (terence): Actually need to coordinates with other flowlets to drain the queue. TransactionContext txContext = dataFabricFacade.createTransactionManager(); txContext.start(); try { ((Closeable) consumer).close(); txContext.finish(); } catch (TransactionFailureException e) { LOG.warn("Fail to commit transaction when closing consumer."); txContext.abort(); } } } catch (Exception e) { LOG.warn("Fail to close queue consumer.", e); } consumer = null; }
java
@Override public void close() throws IOException { try { if (consumer != null && consumer instanceof Closeable) { // Call close in a new transaction. // TODO (terence): Actually need to coordinates with other flowlets to drain the queue. TransactionContext txContext = dataFabricFacade.createTransactionManager(); txContext.start(); try { ((Closeable) consumer).close(); txContext.finish(); } catch (TransactionFailureException e) { LOG.warn("Fail to commit transaction when closing consumer."); txContext.abort(); } } } catch (Exception e) { LOG.warn("Fail to close queue consumer.", e); } consumer = null; }
[ "@", "Override", "public", "void", "close", "(", ")", "throws", "IOException", "{", "try", "{", "if", "(", "consumer", "!=", "null", "&&", "consumer", "instanceof", "Closeable", ")", "{", "// Call close in a new transaction.", "// TODO (terence): Actually need to coordinates with other flowlets to drain the queue.", "TransactionContext", "txContext", "=", "dataFabricFacade", ".", "createTransactionManager", "(", ")", ";", "txContext", ".", "start", "(", ")", ";", "try", "{", "(", "(", "Closeable", ")", "consumer", ")", ".", "close", "(", ")", ";", "txContext", ".", "finish", "(", ")", ";", "}", "catch", "(", "TransactionFailureException", "e", ")", "{", "LOG", ".", "warn", "(", "\"Fail to commit transaction when closing consumer.\"", ")", ";", "txContext", ".", "abort", "(", ")", ";", "}", "}", "}", "catch", "(", "Exception", "e", ")", "{", "LOG", ".", "warn", "(", "\"Fail to close queue consumer.\"", ",", "e", ")", ";", "}", "consumer", "=", "null", ";", "}" ]
Close the current consumer if there is one.
[ "Close", "the", "current", "consumer", "if", "there", "is", "one", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-flow/src/main/java/co/cask/tigon/internal/app/runtime/flow/ConsumerSupplier.java#L103-L123
1,023
cdapio/tigon
tigon-api/src/main/java/co/cask/tigon/internal/io/Schema.java
Schema.isCompatible
public boolean isCompatible(Schema target) { if (equals(target)) { return true; } Multimap<String, String> recordCompared = HashMultimap.create(); return checkCompatible(target, recordCompared); }
java
public boolean isCompatible(Schema target) { if (equals(target)) { return true; } Multimap<String, String> recordCompared = HashMultimap.create(); return checkCompatible(target, recordCompared); }
[ "public", "boolean", "isCompatible", "(", "Schema", "target", ")", "{", "if", "(", "equals", "(", "target", ")", ")", "{", "return", "true", ";", "}", "Multimap", "<", "String", ",", "String", ">", "recordCompared", "=", "HashMultimap", ".", "create", "(", ")", ";", "return", "checkCompatible", "(", "target", ",", "recordCompared", ")", ";", "}" ]
Checks if the given target schema is compatible with this schema, meaning datum being written with this schema could be projected correctly into the given target schema. TODO: Add link to document of the target type projection. @param target Schema to check for compatibility to this target @return {@code true} if the schemas are compatible, {@code false} otherwise.
[ "Checks", "if", "the", "given", "target", "schema", "is", "compatible", "with", "this", "schema", "meaning", "datum", "being", "written", "with", "this", "schema", "could", "be", "projected", "correctly", "into", "the", "given", "target", "schema", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-api/src/main/java/co/cask/tigon/internal/io/Schema.java#L443-L449
1,024
cdapio/tigon
tigon-api/src/main/java/co/cask/tigon/internal/io/Schema.java
Schema.createIndex
private <V> BiMap<V, Integer> createIndex(Set<V> values) { if (values == null) { return null; } ImmutableBiMap.Builder<V, Integer> builder = ImmutableBiMap.builder(); int idx = 0; for (V value : values) { builder.put(value, idx++); } return builder.build(); }
java
private <V> BiMap<V, Integer> createIndex(Set<V> values) { if (values == null) { return null; } ImmutableBiMap.Builder<V, Integer> builder = ImmutableBiMap.builder(); int idx = 0; for (V value : values) { builder.put(value, idx++); } return builder.build(); }
[ "private", "<", "V", ">", "BiMap", "<", "V", ",", "Integer", ">", "createIndex", "(", "Set", "<", "V", ">", "values", ")", "{", "if", "(", "values", "==", "null", ")", "{", "return", "null", ";", "}", "ImmutableBiMap", ".", "Builder", "<", "V", ",", "Integer", ">", "builder", "=", "ImmutableBiMap", ".", "builder", "(", ")", ";", "int", "idx", "=", "0", ";", "for", "(", "V", "value", ":", "values", ")", "{", "builder", ".", "put", "(", "value", ",", "idx", "++", ")", ";", "}", "return", "builder", ".", "build", "(", ")", ";", "}" ]
Creates a map of indexes based on the iteration order of the given set. @param values Set of values to create index on @return A map from the values to indexes in the set iteration order.
[ "Creates", "a", "map", "of", "indexes", "based", "on", "the", "iteration", "order", "of", "the", "given", "set", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-api/src/main/java/co/cask/tigon/internal/io/Schema.java#L534-L545
1,025
cdapio/tigon
tigon-api/src/main/java/co/cask/tigon/internal/io/Schema.java
Schema.populateRecordFields
private Map<String, Field> populateRecordFields(Map<String, Field> fields) { if (fields == null) { return null; } Map<String, Schema> knownRecordSchemas = Maps.newHashMap(); knownRecordSchemas.put(recordName, this); ImmutableMap.Builder<String, Field> builder = ImmutableMap.builder(); for (Map.Entry<String, Field> fieldEntry : fields.entrySet()) { String fieldName = fieldEntry.getKey(); Field field = fieldEntry.getValue(); Schema fieldSchema = resolveSchema(field.getSchema(), knownRecordSchemas); if (fieldSchema == field.getSchema()) { builder.put(fieldName, field); } else { builder.put(fieldName, Field.of(fieldName, fieldSchema)); } } return builder.build(); }
java
private Map<String, Field> populateRecordFields(Map<String, Field> fields) { if (fields == null) { return null; } Map<String, Schema> knownRecordSchemas = Maps.newHashMap(); knownRecordSchemas.put(recordName, this); ImmutableMap.Builder<String, Field> builder = ImmutableMap.builder(); for (Map.Entry<String, Field> fieldEntry : fields.entrySet()) { String fieldName = fieldEntry.getKey(); Field field = fieldEntry.getValue(); Schema fieldSchema = resolveSchema(field.getSchema(), knownRecordSchemas); if (fieldSchema == field.getSchema()) { builder.put(fieldName, field); } else { builder.put(fieldName, Field.of(fieldName, fieldSchema)); } } return builder.build(); }
[ "private", "Map", "<", "String", ",", "Field", ">", "populateRecordFields", "(", "Map", "<", "String", ",", "Field", ">", "fields", ")", "{", "if", "(", "fields", "==", "null", ")", "{", "return", "null", ";", "}", "Map", "<", "String", ",", "Schema", ">", "knownRecordSchemas", "=", "Maps", ".", "newHashMap", "(", ")", ";", "knownRecordSchemas", ".", "put", "(", "recordName", ",", "this", ")", ";", "ImmutableMap", ".", "Builder", "<", "String", ",", "Field", ">", "builder", "=", "ImmutableMap", ".", "builder", "(", ")", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "Field", ">", "fieldEntry", ":", "fields", ".", "entrySet", "(", ")", ")", "{", "String", "fieldName", "=", "fieldEntry", ".", "getKey", "(", ")", ";", "Field", "field", "=", "fieldEntry", ".", "getValue", "(", ")", ";", "Schema", "fieldSchema", "=", "resolveSchema", "(", "field", ".", "getSchema", "(", ")", ",", "knownRecordSchemas", ")", ";", "if", "(", "fieldSchema", "==", "field", ".", "getSchema", "(", ")", ")", "{", "builder", ".", "put", "(", "fieldName", ",", "field", ")", ";", "}", "else", "{", "builder", ".", "put", "(", "fieldName", ",", "Field", ".", "of", "(", "fieldName", ",", "fieldSchema", ")", ")", ";", "}", "}", "return", "builder", ".", "build", "(", ")", ";", "}" ]
Resolves all field schemas. @param fields All the fields that need to be resolved. @return A {@link java.util.Map} which has all the field schemas resolved. @see #resolveSchema(Schema, java.util.Map)
[ "Resolves", "all", "field", "schemas", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-api/src/main/java/co/cask/tigon/internal/io/Schema.java#L554-L576
1,026
cdapio/tigon
tigon-api/src/main/java/co/cask/tigon/internal/io/Schema.java
Schema.resolveSchema
private Schema resolveSchema(final Schema schema, final Map<String, Schema> knownRecordSchemas) { switch (schema.getType()) { case ARRAY: Schema componentSchema = resolveSchema(schema.getComponentSchema(), knownRecordSchemas); return (componentSchema == schema.getComponentSchema()) ? schema : Schema.arrayOf(componentSchema); case MAP: Map.Entry<Schema, Schema> entry = schema.getMapSchema(); Schema keySchema = resolveSchema(entry.getKey(), knownRecordSchemas); Schema valueSchema = resolveSchema(entry.getValue(), knownRecordSchemas); return (keySchema == entry.getKey() && valueSchema == entry.getValue()) ? schema : Schema.mapOf(keySchema, valueSchema); case UNION: ImmutableList.Builder<Schema> schemaBuilder = ImmutableList.builder(); boolean changed = false; for (Schema input : schema.getUnionSchemas()) { Schema output = resolveSchema(input, knownRecordSchemas); if (output != input) { changed = true; } schemaBuilder.add(output); } return changed ? Schema.unionOf(schemaBuilder.build()) : schema; case RECORD: if (schema.fields == null) { // It is a named record that refers to previously defined record Schema knownSchema = knownRecordSchemas.get(schema.recordName); Preconditions.checkArgument(knownSchema != null, "Undefined schema %s", schema.recordName); return knownSchema; } else { // It is a concrete schema knownRecordSchemas.put(schema.recordName, schema); return schema; } } return schema; }
java
private Schema resolveSchema(final Schema schema, final Map<String, Schema> knownRecordSchemas) { switch (schema.getType()) { case ARRAY: Schema componentSchema = resolveSchema(schema.getComponentSchema(), knownRecordSchemas); return (componentSchema == schema.getComponentSchema()) ? schema : Schema.arrayOf(componentSchema); case MAP: Map.Entry<Schema, Schema> entry = schema.getMapSchema(); Schema keySchema = resolveSchema(entry.getKey(), knownRecordSchemas); Schema valueSchema = resolveSchema(entry.getValue(), knownRecordSchemas); return (keySchema == entry.getKey() && valueSchema == entry.getValue()) ? schema : Schema.mapOf(keySchema, valueSchema); case UNION: ImmutableList.Builder<Schema> schemaBuilder = ImmutableList.builder(); boolean changed = false; for (Schema input : schema.getUnionSchemas()) { Schema output = resolveSchema(input, knownRecordSchemas); if (output != input) { changed = true; } schemaBuilder.add(output); } return changed ? Schema.unionOf(schemaBuilder.build()) : schema; case RECORD: if (schema.fields == null) { // It is a named record that refers to previously defined record Schema knownSchema = knownRecordSchemas.get(schema.recordName); Preconditions.checkArgument(knownSchema != null, "Undefined schema %s", schema.recordName); return knownSchema; } else { // It is a concrete schema knownRecordSchemas.put(schema.recordName, schema); return schema; } } return schema; }
[ "private", "Schema", "resolveSchema", "(", "final", "Schema", "schema", ",", "final", "Map", "<", "String", ",", "Schema", ">", "knownRecordSchemas", ")", "{", "switch", "(", "schema", ".", "getType", "(", ")", ")", "{", "case", "ARRAY", ":", "Schema", "componentSchema", "=", "resolveSchema", "(", "schema", ".", "getComponentSchema", "(", ")", ",", "knownRecordSchemas", ")", ";", "return", "(", "componentSchema", "==", "schema", ".", "getComponentSchema", "(", ")", ")", "?", "schema", ":", "Schema", ".", "arrayOf", "(", "componentSchema", ")", ";", "case", "MAP", ":", "Map", ".", "Entry", "<", "Schema", ",", "Schema", ">", "entry", "=", "schema", ".", "getMapSchema", "(", ")", ";", "Schema", "keySchema", "=", "resolveSchema", "(", "entry", ".", "getKey", "(", ")", ",", "knownRecordSchemas", ")", ";", "Schema", "valueSchema", "=", "resolveSchema", "(", "entry", ".", "getValue", "(", ")", ",", "knownRecordSchemas", ")", ";", "return", "(", "keySchema", "==", "entry", ".", "getKey", "(", ")", "&&", "valueSchema", "==", "entry", ".", "getValue", "(", ")", ")", "?", "schema", ":", "Schema", ".", "mapOf", "(", "keySchema", ",", "valueSchema", ")", ";", "case", "UNION", ":", "ImmutableList", ".", "Builder", "<", "Schema", ">", "schemaBuilder", "=", "ImmutableList", ".", "builder", "(", ")", ";", "boolean", "changed", "=", "false", ";", "for", "(", "Schema", "input", ":", "schema", ".", "getUnionSchemas", "(", ")", ")", "{", "Schema", "output", "=", "resolveSchema", "(", "input", ",", "knownRecordSchemas", ")", ";", "if", "(", "output", "!=", "input", ")", "{", "changed", "=", "true", ";", "}", "schemaBuilder", ".", "add", "(", "output", ")", ";", "}", "return", "changed", "?", "Schema", ".", "unionOf", "(", "schemaBuilder", ".", "build", "(", ")", ")", ":", "schema", ";", "case", "RECORD", ":", "if", "(", "schema", ".", "fields", "==", "null", ")", "{", "// It is a named record that refers to previously defined record", "Schema", "knownSchema", "=", "knownRecordSchemas", ".", "get", "(", "schema", ".", "recordName", ")", ";", "Preconditions", ".", "checkArgument", "(", "knownSchema", "!=", "null", ",", "\"Undefined schema %s\"", ",", "schema", ".", "recordName", ")", ";", "return", "knownSchema", ";", "}", "else", "{", "// It is a concrete schema", "knownRecordSchemas", ".", "put", "(", "schema", ".", "recordName", ",", "schema", ")", ";", "return", "schema", ";", "}", "}", "return", "schema", ";", "}" ]
This method is to recursively resolves all name only record schema in the given schema. @param schema The schema needs to be resolved. @param knownRecordSchemas The mapping of the already resolved record schemas. @return A {@link Schema} that is structurally the same as the input schema, but with all name only record schemas resolved to full schemas (i.e. with fields sets). If nothing in the given schema needs to be resolved, the same schema instance would be returned, otherwise, a new instance would be returned.
[ "This", "method", "is", "to", "recursively", "resolves", "all", "name", "only", "record", "schema", "in", "the", "given", "schema", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-api/src/main/java/co/cask/tigon/internal/io/Schema.java#L588-L623
1,027
cdapio/tigon
tigon-api/src/main/java/co/cask/tigon/internal/io/Schema.java
Schema.buildString
private String buildString() { if (type.isSimpleType()) { return '"' + type.name().toLowerCase() + '"'; } StringBuilder builder = new StringBuilder(); JsonWriter writer = new JsonWriter(CharStreams.asWriter(builder)); try { new SchemaTypeAdapter().write(writer, this); writer.close(); return builder.toString(); } catch (IOException e) { // It should never throw IOException on the StringBuilder Writer, if it does, something very wrong. throw Throwables.propagate(e); } }
java
private String buildString() { if (type.isSimpleType()) { return '"' + type.name().toLowerCase() + '"'; } StringBuilder builder = new StringBuilder(); JsonWriter writer = new JsonWriter(CharStreams.asWriter(builder)); try { new SchemaTypeAdapter().write(writer, this); writer.close(); return builder.toString(); } catch (IOException e) { // It should never throw IOException on the StringBuilder Writer, if it does, something very wrong. throw Throwables.propagate(e); } }
[ "private", "String", "buildString", "(", ")", "{", "if", "(", "type", ".", "isSimpleType", "(", ")", ")", "{", "return", "'", "'", "+", "type", ".", "name", "(", ")", ".", "toLowerCase", "(", ")", "+", "'", "'", ";", "}", "StringBuilder", "builder", "=", "new", "StringBuilder", "(", ")", ";", "JsonWriter", "writer", "=", "new", "JsonWriter", "(", "CharStreams", ".", "asWriter", "(", "builder", ")", ")", ";", "try", "{", "new", "SchemaTypeAdapter", "(", ")", ".", "write", "(", "writer", ",", "this", ")", ";", "writer", ".", "close", "(", ")", ";", "return", "builder", ".", "toString", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "// It should never throw IOException on the StringBuilder Writer, if it does, something very wrong.", "throw", "Throwables", ".", "propagate", "(", "e", ")", ";", "}", "}" ]
Helper method to encode this schema into json string. @return A json string representing this schema.
[ "Helper", "method", "to", "encode", "this", "schema", "into", "json", "string", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-api/src/main/java/co/cask/tigon/internal/io/Schema.java#L630-L644
1,028
cdapio/tigon
tigon-flow/src/main/java/co/cask/tigon/internal/app/runtime/distributed/DistributedFlowletInstanceUpdater.java
DistributedFlowletInstanceUpdater.waitForInstances
private void waitForInstances(String flowletId, int expectedInstances) throws InterruptedException, TimeoutException { int numRunningFlowlets = getNumberOfProvisionedInstances(flowletId); int secondsWaited = 0; while (numRunningFlowlets != expectedInstances) { LOG.debug("waiting for {} instances of {} before suspending flowlets", expectedInstances, flowletId); TimeUnit.SECONDS.sleep(SECONDS_PER_WAIT); secondsWaited += SECONDS_PER_WAIT; if (secondsWaited > MAX_WAIT_SECONDS) { String errmsg = String.format("waited %d seconds for instances of %s to reach expected count of %d, but %d are running", secondsWaited, flowletId, expectedInstances, numRunningFlowlets); LOG.error(errmsg); throw new TimeoutException(errmsg); } numRunningFlowlets = getNumberOfProvisionedInstances(flowletId); } }
java
private void waitForInstances(String flowletId, int expectedInstances) throws InterruptedException, TimeoutException { int numRunningFlowlets = getNumberOfProvisionedInstances(flowletId); int secondsWaited = 0; while (numRunningFlowlets != expectedInstances) { LOG.debug("waiting for {} instances of {} before suspending flowlets", expectedInstances, flowletId); TimeUnit.SECONDS.sleep(SECONDS_PER_WAIT); secondsWaited += SECONDS_PER_WAIT; if (secondsWaited > MAX_WAIT_SECONDS) { String errmsg = String.format("waited %d seconds for instances of %s to reach expected count of %d, but %d are running", secondsWaited, flowletId, expectedInstances, numRunningFlowlets); LOG.error(errmsg); throw new TimeoutException(errmsg); } numRunningFlowlets = getNumberOfProvisionedInstances(flowletId); } }
[ "private", "void", "waitForInstances", "(", "String", "flowletId", ",", "int", "expectedInstances", ")", "throws", "InterruptedException", ",", "TimeoutException", "{", "int", "numRunningFlowlets", "=", "getNumberOfProvisionedInstances", "(", "flowletId", ")", ";", "int", "secondsWaited", "=", "0", ";", "while", "(", "numRunningFlowlets", "!=", "expectedInstances", ")", "{", "LOG", ".", "debug", "(", "\"waiting for {} instances of {} before suspending flowlets\"", ",", "expectedInstances", ",", "flowletId", ")", ";", "TimeUnit", ".", "SECONDS", ".", "sleep", "(", "SECONDS_PER_WAIT", ")", ";", "secondsWaited", "+=", "SECONDS_PER_WAIT", ";", "if", "(", "secondsWaited", ">", "MAX_WAIT_SECONDS", ")", "{", "String", "errmsg", "=", "String", ".", "format", "(", "\"waited %d seconds for instances of %s to reach expected count of %d, but %d are running\"", ",", "secondsWaited", ",", "flowletId", ",", "expectedInstances", ",", "numRunningFlowlets", ")", ";", "LOG", ".", "error", "(", "errmsg", ")", ";", "throw", "new", "TimeoutException", "(", "errmsg", ")", ";", "}", "numRunningFlowlets", "=", "getNumberOfProvisionedInstances", "(", "flowletId", ")", ";", "}", "}" ]
it cannot change instances without being in the suspended state.
[ "it", "cannot", "change", "instances", "without", "being", "in", "the", "suspended", "state", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-flow/src/main/java/co/cask/tigon/internal/app/runtime/distributed/DistributedFlowletInstanceUpdater.java#L75-L91
1,029
cdapio/tigon
tigon-queue/src/main/java/co/cask/tigon/data/util/hbase/HBaseTableUtil.java
HBaseTableUtil.setDefaultConfiguration
private void setDefaultConfiguration(HTableDescriptor tableDescriptor, Configuration conf) { String compression = conf.get(CFG_HBASE_TABLE_COMPRESSION, DEFAULT_COMPRESSION_TYPE.name()); CompressionType compressionAlgo = CompressionType.valueOf(compression); for (HColumnDescriptor hcd : tableDescriptor.getColumnFamilies()) { setCompression(hcd, compressionAlgo); setBloomFilter(hcd, BloomType.ROW); } }
java
private void setDefaultConfiguration(HTableDescriptor tableDescriptor, Configuration conf) { String compression = conf.get(CFG_HBASE_TABLE_COMPRESSION, DEFAULT_COMPRESSION_TYPE.name()); CompressionType compressionAlgo = CompressionType.valueOf(compression); for (HColumnDescriptor hcd : tableDescriptor.getColumnFamilies()) { setCompression(hcd, compressionAlgo); setBloomFilter(hcd, BloomType.ROW); } }
[ "private", "void", "setDefaultConfiguration", "(", "HTableDescriptor", "tableDescriptor", ",", "Configuration", "conf", ")", "{", "String", "compression", "=", "conf", ".", "get", "(", "CFG_HBASE_TABLE_COMPRESSION", ",", "DEFAULT_COMPRESSION_TYPE", ".", "name", "(", ")", ")", ";", "CompressionType", "compressionAlgo", "=", "CompressionType", ".", "valueOf", "(", "compression", ")", ";", "for", "(", "HColumnDescriptor", "hcd", ":", "tableDescriptor", ".", "getColumnFamilies", "(", ")", ")", "{", "setCompression", "(", "hcd", ",", "compressionAlgo", ")", ";", "setBloomFilter", "(", "hcd", ",", "BloomType", ".", "ROW", ")", ";", "}", "}" ]
which doesn't support certain compression type
[ "which", "doesn", "t", "support", "certain", "compression", "type" ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-queue/src/main/java/co/cask/tigon/data/util/hbase/HBaseTableUtil.java#L183-L190
1,030
cdapio/tigon
tigon-queue/src/main/java/co/cask/tigon/data/util/hbase/HBaseTableUtil.java
HBaseTableUtil.getCoprocessorInfo
public static Map<String, CoprocessorInfo> getCoprocessorInfo(HTableDescriptor tableDescriptor) { Map<String, CoprocessorInfo> info = Maps.newHashMap(); // Extract information about existing data janitor coprocessor // The following logic is copied from RegionCoprocessorHost in HBase for (Map.Entry<ImmutableBytesWritable, ImmutableBytesWritable> entry: tableDescriptor.getValues().entrySet()) { String key = Bytes.toString(entry.getKey().get()).trim(); String spec = Bytes.toString(entry.getValue().get()).trim(); if (!HConstants.CP_HTD_ATTR_KEY_PATTERN.matcher(key).matches()) { continue; } try { Matcher matcher = HConstants.CP_HTD_ATTR_VALUE_PATTERN.matcher(spec); if (!matcher.matches()) { continue; } String className = matcher.group(2).trim(); Path path = matcher.group(1).trim().isEmpty() ? null : new Path(matcher.group(1).trim()); int priority = matcher.group(3).trim().isEmpty() ? Coprocessor.PRIORITY_USER : Integer.valueOf(matcher.group(3)); String cfgSpec = null; try { cfgSpec = matcher.group(4); } catch (IndexOutOfBoundsException ex) { // ignore } Map<String, String> properties = Maps.newHashMap(); if (cfgSpec != null) { cfgSpec = cfgSpec.substring(cfgSpec.indexOf('|') + 1); // do an explicit deep copy of the passed configuration Matcher m = HConstants.CP_HTD_ATTR_VALUE_PARAM_PATTERN.matcher(cfgSpec); while (m.find()) { properties.put(m.group(1), m.group(2)); } } info.put(className, new CoprocessorInfo(className, path, priority, properties)); } catch (Exception ex) { LOG.warn("Coprocessor attribute '{}' has invalid coprocessor specification '{}'", key, spec, ex); } } return info; }
java
public static Map<String, CoprocessorInfo> getCoprocessorInfo(HTableDescriptor tableDescriptor) { Map<String, CoprocessorInfo> info = Maps.newHashMap(); // Extract information about existing data janitor coprocessor // The following logic is copied from RegionCoprocessorHost in HBase for (Map.Entry<ImmutableBytesWritable, ImmutableBytesWritable> entry: tableDescriptor.getValues().entrySet()) { String key = Bytes.toString(entry.getKey().get()).trim(); String spec = Bytes.toString(entry.getValue().get()).trim(); if (!HConstants.CP_HTD_ATTR_KEY_PATTERN.matcher(key).matches()) { continue; } try { Matcher matcher = HConstants.CP_HTD_ATTR_VALUE_PATTERN.matcher(spec); if (!matcher.matches()) { continue; } String className = matcher.group(2).trim(); Path path = matcher.group(1).trim().isEmpty() ? null : new Path(matcher.group(1).trim()); int priority = matcher.group(3).trim().isEmpty() ? Coprocessor.PRIORITY_USER : Integer.valueOf(matcher.group(3)); String cfgSpec = null; try { cfgSpec = matcher.group(4); } catch (IndexOutOfBoundsException ex) { // ignore } Map<String, String> properties = Maps.newHashMap(); if (cfgSpec != null) { cfgSpec = cfgSpec.substring(cfgSpec.indexOf('|') + 1); // do an explicit deep copy of the passed configuration Matcher m = HConstants.CP_HTD_ATTR_VALUE_PARAM_PATTERN.matcher(cfgSpec); while (m.find()) { properties.put(m.group(1), m.group(2)); } } info.put(className, new CoprocessorInfo(className, path, priority, properties)); } catch (Exception ex) { LOG.warn("Coprocessor attribute '{}' has invalid coprocessor specification '{}'", key, spec, ex); } } return info; }
[ "public", "static", "Map", "<", "String", ",", "CoprocessorInfo", ">", "getCoprocessorInfo", "(", "HTableDescriptor", "tableDescriptor", ")", "{", "Map", "<", "String", ",", "CoprocessorInfo", ">", "info", "=", "Maps", ".", "newHashMap", "(", ")", ";", "// Extract information about existing data janitor coprocessor", "// The following logic is copied from RegionCoprocessorHost in HBase", "for", "(", "Map", ".", "Entry", "<", "ImmutableBytesWritable", ",", "ImmutableBytesWritable", ">", "entry", ":", "tableDescriptor", ".", "getValues", "(", ")", ".", "entrySet", "(", ")", ")", "{", "String", "key", "=", "Bytes", ".", "toString", "(", "entry", ".", "getKey", "(", ")", ".", "get", "(", ")", ")", ".", "trim", "(", ")", ";", "String", "spec", "=", "Bytes", ".", "toString", "(", "entry", ".", "getValue", "(", ")", ".", "get", "(", ")", ")", ".", "trim", "(", ")", ";", "if", "(", "!", "HConstants", ".", "CP_HTD_ATTR_KEY_PATTERN", ".", "matcher", "(", "key", ")", ".", "matches", "(", ")", ")", "{", "continue", ";", "}", "try", "{", "Matcher", "matcher", "=", "HConstants", ".", "CP_HTD_ATTR_VALUE_PATTERN", ".", "matcher", "(", "spec", ")", ";", "if", "(", "!", "matcher", ".", "matches", "(", ")", ")", "{", "continue", ";", "}", "String", "className", "=", "matcher", ".", "group", "(", "2", ")", ".", "trim", "(", ")", ";", "Path", "path", "=", "matcher", ".", "group", "(", "1", ")", ".", "trim", "(", ")", ".", "isEmpty", "(", ")", "?", "null", ":", "new", "Path", "(", "matcher", ".", "group", "(", "1", ")", ".", "trim", "(", ")", ")", ";", "int", "priority", "=", "matcher", ".", "group", "(", "3", ")", ".", "trim", "(", ")", ".", "isEmpty", "(", ")", "?", "Coprocessor", ".", "PRIORITY_USER", ":", "Integer", ".", "valueOf", "(", "matcher", ".", "group", "(", "3", ")", ")", ";", "String", "cfgSpec", "=", "null", ";", "try", "{", "cfgSpec", "=", "matcher", ".", "group", "(", "4", ")", ";", "}", "catch", "(", "IndexOutOfBoundsException", "ex", ")", "{", "// ignore", "}", "Map", "<", "String", ",", "String", ">", "properties", "=", "Maps", ".", "newHashMap", "(", ")", ";", "if", "(", "cfgSpec", "!=", "null", ")", "{", "cfgSpec", "=", "cfgSpec", ".", "substring", "(", "cfgSpec", ".", "indexOf", "(", "'", "'", ")", "+", "1", ")", ";", "// do an explicit deep copy of the passed configuration", "Matcher", "m", "=", "HConstants", ".", "CP_HTD_ATTR_VALUE_PARAM_PATTERN", ".", "matcher", "(", "cfgSpec", ")", ";", "while", "(", "m", ".", "find", "(", ")", ")", "{", "properties", ".", "put", "(", "m", ".", "group", "(", "1", ")", ",", "m", ".", "group", "(", "2", ")", ")", ";", "}", "}", "info", ".", "put", "(", "className", ",", "new", "CoprocessorInfo", "(", "className", ",", "path", ",", "priority", ",", "properties", ")", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "LOG", ".", "warn", "(", "\"Coprocessor attribute '{}' has invalid coprocessor specification '{}'\"", ",", "key", ",", "spec", ",", "ex", ")", ";", "}", "}", "return", "info", ";", "}" ]
Returns information for all coprocessor configured for the table. @return a Map from coprocessor class name to CoprocessorInfo
[ "Returns", "information", "for", "all", "coprocessor", "configured", "for", "the", "table", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-queue/src/main/java/co/cask/tigon/data/util/hbase/HBaseTableUtil.java#L341-L387
1,031
cdapio/tigon
tigon-flow/src/main/java/co/cask/tigon/internal/app/runtime/flow/ReflectionProcessMethod.java
ReflectionProcessMethod.invoke
private void invoke(Method method, Object event, InputContext inputContext) throws Exception { if (needContext) { method.invoke(flowlet, event, inputContext); } else { method.invoke(flowlet, event); } }
java
private void invoke(Method method, Object event, InputContext inputContext) throws Exception { if (needContext) { method.invoke(flowlet, event, inputContext); } else { method.invoke(flowlet, event); } }
[ "private", "void", "invoke", "(", "Method", "method", ",", "Object", "event", ",", "InputContext", "inputContext", ")", "throws", "Exception", "{", "if", "(", "needContext", ")", "{", "method", ".", "invoke", "(", "flowlet", ",", "event", ",", "inputContext", ")", ";", "}", "else", "{", "method", ".", "invoke", "(", "flowlet", ",", "event", ")", ";", "}", "}" ]
Calls the user process method.
[ "Calls", "the", "user", "process", "method", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-flow/src/main/java/co/cask/tigon/internal/app/runtime/flow/ReflectionProcessMethod.java#L120-L126
1,032
cdapio/tigon
tigon-yarn/src/main/java/co/cask/tigon/conf/CConfiguration.java
CConfiguration.create
public static CConfiguration create() { // Create a new configuration instance, but do NOT initialize with // the Hadoop default properties. CConfiguration conf = new CConfiguration(); conf.addResource("tigon-default.xml"); conf.addResource("tigon-site.xml"); return conf; }
java
public static CConfiguration create() { // Create a new configuration instance, but do NOT initialize with // the Hadoop default properties. CConfiguration conf = new CConfiguration(); conf.addResource("tigon-default.xml"); conf.addResource("tigon-site.xml"); return conf; }
[ "public", "static", "CConfiguration", "create", "(", ")", "{", "// Create a new configuration instance, but do NOT initialize with", "// the Hadoop default properties.", "CConfiguration", "conf", "=", "new", "CConfiguration", "(", ")", ";", "conf", ".", "addResource", "(", "\"tigon-default.xml\"", ")", ";", "conf", ".", "addResource", "(", "\"tigon-site.xml\"", ")", ";", "return", "conf", ";", "}" ]
Creates an instance of configuration. @return an instance of CConfiguration.
[ "Creates", "an", "instance", "of", "configuration", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-yarn/src/main/java/co/cask/tigon/conf/CConfiguration.java#L48-L55
1,033
cdapio/tigon
tigon-queue/src/main/java/co/cask/tigon/data/lib/hbase/AbstractHBaseDataSetAdmin.java
AbstractHBaseDataSetAdmin.upgradeTable
protected void upgradeTable(String tableNameStr) throws IOException { byte[] tableName = Bytes.toBytes(tableNameStr); HTableDescriptor tableDescriptor = getAdmin().getTableDescriptor(tableName); // Upgrade any table properties if necessary boolean needUpgrade = upgradeTable(tableDescriptor); // Get the Tigon version from the table ProjectInfo.Version version = new ProjectInfo.Version(tableDescriptor.getValue(TIGON_VERSION)); if (!needUpgrade && version.compareTo(ProjectInfo.getVersion()) >= 0) { // If the table has greater than or same version, no need to upgrade. LOG.info("Table '{}' was upgraded with same or newer version '{}'. Current version is '{}'", tableNameStr, version, ProjectInfo.getVersion()); return; } // Generate the coprocessor jar CoprocessorJar coprocessorJar = createCoprocessorJar(); Location jarLocation = coprocessorJar.getJarLocation(); // Check if coprocessor upgrade is needed Map<String, HBaseTableUtil.CoprocessorInfo> coprocessorInfo = HBaseTableUtil.getCoprocessorInfo(tableDescriptor); // For all required coprocessors, check if they've need to be upgraded. for (Class<? extends Coprocessor> coprocessor : coprocessorJar.getCoprocessors()) { HBaseTableUtil.CoprocessorInfo info = coprocessorInfo.get(coprocessor.getName()); if (info != null) { // The same coprocessor has been configured, check by the file name hash to see if they are the same. if (!jarLocation.getName().equals(info.getPath().getName())) { needUpgrade = true; // Remove old one and add the new one. tableDescriptor.removeCoprocessor(info.getClassName()); addCoprocessor(tableDescriptor, coprocessor, jarLocation, coprocessorJar.getPriority(coprocessor)); } } else { // The coprocessor is missing from the table, add it. needUpgrade = true; addCoprocessor(tableDescriptor, coprocessor, jarLocation, coprocessorJar.getPriority(coprocessor)); } } // Removes all old coprocessors Set<String> coprocessorNames = ImmutableSet.copyOf(Iterables.transform(coprocessorJar.coprocessors, CLASS_TO_NAME)); for (String remove : Sets.difference(coprocessorInfo.keySet(), coprocessorNames)) { needUpgrade = true; tableDescriptor.removeCoprocessor(remove); } if (!needUpgrade) { LOG.info("No upgrade needed for table '{}'", tableNameStr); return; } // Add the current version as table properties only if the table needs upgrade tableDescriptor.setValue(TIGON_VERSION, ProjectInfo.getVersion().toString()); LOG.info("Upgrading table '{}'...", tableNameStr); boolean enableTable = false; try { getAdmin().disableTable(tableName); enableTable = true; } catch (TableNotEnabledException e) { LOG.debug("Table '{}' not enabled when try to disable it.", tableNameStr); } getAdmin().modifyTable(tableName, tableDescriptor); if (enableTable) { getAdmin().enableTable(tableName); } LOG.info("Table '{}' upgrade completed.", tableNameStr); }
java
protected void upgradeTable(String tableNameStr) throws IOException { byte[] tableName = Bytes.toBytes(tableNameStr); HTableDescriptor tableDescriptor = getAdmin().getTableDescriptor(tableName); // Upgrade any table properties if necessary boolean needUpgrade = upgradeTable(tableDescriptor); // Get the Tigon version from the table ProjectInfo.Version version = new ProjectInfo.Version(tableDescriptor.getValue(TIGON_VERSION)); if (!needUpgrade && version.compareTo(ProjectInfo.getVersion()) >= 0) { // If the table has greater than or same version, no need to upgrade. LOG.info("Table '{}' was upgraded with same or newer version '{}'. Current version is '{}'", tableNameStr, version, ProjectInfo.getVersion()); return; } // Generate the coprocessor jar CoprocessorJar coprocessorJar = createCoprocessorJar(); Location jarLocation = coprocessorJar.getJarLocation(); // Check if coprocessor upgrade is needed Map<String, HBaseTableUtil.CoprocessorInfo> coprocessorInfo = HBaseTableUtil.getCoprocessorInfo(tableDescriptor); // For all required coprocessors, check if they've need to be upgraded. for (Class<? extends Coprocessor> coprocessor : coprocessorJar.getCoprocessors()) { HBaseTableUtil.CoprocessorInfo info = coprocessorInfo.get(coprocessor.getName()); if (info != null) { // The same coprocessor has been configured, check by the file name hash to see if they are the same. if (!jarLocation.getName().equals(info.getPath().getName())) { needUpgrade = true; // Remove old one and add the new one. tableDescriptor.removeCoprocessor(info.getClassName()); addCoprocessor(tableDescriptor, coprocessor, jarLocation, coprocessorJar.getPriority(coprocessor)); } } else { // The coprocessor is missing from the table, add it. needUpgrade = true; addCoprocessor(tableDescriptor, coprocessor, jarLocation, coprocessorJar.getPriority(coprocessor)); } } // Removes all old coprocessors Set<String> coprocessorNames = ImmutableSet.copyOf(Iterables.transform(coprocessorJar.coprocessors, CLASS_TO_NAME)); for (String remove : Sets.difference(coprocessorInfo.keySet(), coprocessorNames)) { needUpgrade = true; tableDescriptor.removeCoprocessor(remove); } if (!needUpgrade) { LOG.info("No upgrade needed for table '{}'", tableNameStr); return; } // Add the current version as table properties only if the table needs upgrade tableDescriptor.setValue(TIGON_VERSION, ProjectInfo.getVersion().toString()); LOG.info("Upgrading table '{}'...", tableNameStr); boolean enableTable = false; try { getAdmin().disableTable(tableName); enableTable = true; } catch (TableNotEnabledException e) { LOG.debug("Table '{}' not enabled when try to disable it.", tableNameStr); } getAdmin().modifyTable(tableName, tableDescriptor); if (enableTable) { getAdmin().enableTable(tableName); } LOG.info("Table '{}' upgrade completed.", tableNameStr); }
[ "protected", "void", "upgradeTable", "(", "String", "tableNameStr", ")", "throws", "IOException", "{", "byte", "[", "]", "tableName", "=", "Bytes", ".", "toBytes", "(", "tableNameStr", ")", ";", "HTableDescriptor", "tableDescriptor", "=", "getAdmin", "(", ")", ".", "getTableDescriptor", "(", "tableName", ")", ";", "// Upgrade any table properties if necessary", "boolean", "needUpgrade", "=", "upgradeTable", "(", "tableDescriptor", ")", ";", "// Get the Tigon version from the table", "ProjectInfo", ".", "Version", "version", "=", "new", "ProjectInfo", ".", "Version", "(", "tableDescriptor", ".", "getValue", "(", "TIGON_VERSION", ")", ")", ";", "if", "(", "!", "needUpgrade", "&&", "version", ".", "compareTo", "(", "ProjectInfo", ".", "getVersion", "(", ")", ")", ">=", "0", ")", "{", "// If the table has greater than or same version, no need to upgrade.", "LOG", ".", "info", "(", "\"Table '{}' was upgraded with same or newer version '{}'. Current version is '{}'\"", ",", "tableNameStr", ",", "version", ",", "ProjectInfo", ".", "getVersion", "(", ")", ")", ";", "return", ";", "}", "// Generate the coprocessor jar", "CoprocessorJar", "coprocessorJar", "=", "createCoprocessorJar", "(", ")", ";", "Location", "jarLocation", "=", "coprocessorJar", ".", "getJarLocation", "(", ")", ";", "// Check if coprocessor upgrade is needed", "Map", "<", "String", ",", "HBaseTableUtil", ".", "CoprocessorInfo", ">", "coprocessorInfo", "=", "HBaseTableUtil", ".", "getCoprocessorInfo", "(", "tableDescriptor", ")", ";", "// For all required coprocessors, check if they've need to be upgraded.", "for", "(", "Class", "<", "?", "extends", "Coprocessor", ">", "coprocessor", ":", "coprocessorJar", ".", "getCoprocessors", "(", ")", ")", "{", "HBaseTableUtil", ".", "CoprocessorInfo", "info", "=", "coprocessorInfo", ".", "get", "(", "coprocessor", ".", "getName", "(", ")", ")", ";", "if", "(", "info", "!=", "null", ")", "{", "// The same coprocessor has been configured, check by the file name hash to see if they are the same.", "if", "(", "!", "jarLocation", ".", "getName", "(", ")", ".", "equals", "(", "info", ".", "getPath", "(", ")", ".", "getName", "(", ")", ")", ")", "{", "needUpgrade", "=", "true", ";", "// Remove old one and add the new one.", "tableDescriptor", ".", "removeCoprocessor", "(", "info", ".", "getClassName", "(", ")", ")", ";", "addCoprocessor", "(", "tableDescriptor", ",", "coprocessor", ",", "jarLocation", ",", "coprocessorJar", ".", "getPriority", "(", "coprocessor", ")", ")", ";", "}", "}", "else", "{", "// The coprocessor is missing from the table, add it.", "needUpgrade", "=", "true", ";", "addCoprocessor", "(", "tableDescriptor", ",", "coprocessor", ",", "jarLocation", ",", "coprocessorJar", ".", "getPriority", "(", "coprocessor", ")", ")", ";", "}", "}", "// Removes all old coprocessors", "Set", "<", "String", ">", "coprocessorNames", "=", "ImmutableSet", ".", "copyOf", "(", "Iterables", ".", "transform", "(", "coprocessorJar", ".", "coprocessors", ",", "CLASS_TO_NAME", ")", ")", ";", "for", "(", "String", "remove", ":", "Sets", ".", "difference", "(", "coprocessorInfo", ".", "keySet", "(", ")", ",", "coprocessorNames", ")", ")", "{", "needUpgrade", "=", "true", ";", "tableDescriptor", ".", "removeCoprocessor", "(", "remove", ")", ";", "}", "if", "(", "!", "needUpgrade", ")", "{", "LOG", ".", "info", "(", "\"No upgrade needed for table '{}'\"", ",", "tableNameStr", ")", ";", "return", ";", "}", "// Add the current version as table properties only if the table needs upgrade", "tableDescriptor", ".", "setValue", "(", "TIGON_VERSION", ",", "ProjectInfo", ".", "getVersion", "(", ")", ".", "toString", "(", ")", ")", ";", "LOG", ".", "info", "(", "\"Upgrading table '{}'...\"", ",", "tableNameStr", ")", ";", "boolean", "enableTable", "=", "false", ";", "try", "{", "getAdmin", "(", ")", ".", "disableTable", "(", "tableName", ")", ";", "enableTable", "=", "true", ";", "}", "catch", "(", "TableNotEnabledException", "e", ")", "{", "LOG", ".", "debug", "(", "\"Table '{}' not enabled when try to disable it.\"", ",", "tableNameStr", ")", ";", "}", "getAdmin", "(", ")", ".", "modifyTable", "(", "tableName", ",", "tableDescriptor", ")", ";", "if", "(", "enableTable", ")", "{", "getAdmin", "(", ")", ".", "enableTable", "(", "tableName", ")", ";", "}", "LOG", ".", "info", "(", "\"Table '{}' upgrade completed.\"", ",", "tableNameStr", ")", ";", "}" ]
Performs upgrade on a given HBase table. @param tableNameStr The HBase table name that upgrade will be performed on. @throws java.io.IOException If upgrade failed.
[ "Performs", "upgrade", "on", "a", "given", "HBase", "table", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-queue/src/main/java/co/cask/tigon/data/lib/hbase/AbstractHBaseDataSetAdmin.java#L115-L188
1,034
cdapio/tigon
tigon-yarn/src/main/java/co/cask/tigon/io/Locations.java
Locations.mkdirsIfNotExists
public static void mkdirsIfNotExists(Location location) throws IOException { // Need to check && mkdir && check to deal with race condition if (!location.isDirectory() && !location.mkdirs() && !location.isDirectory()) { throw new IOException("Failed to create directory at " + location.toURI()); } }
java
public static void mkdirsIfNotExists(Location location) throws IOException { // Need to check && mkdir && check to deal with race condition if (!location.isDirectory() && !location.mkdirs() && !location.isDirectory()) { throw new IOException("Failed to create directory at " + location.toURI()); } }
[ "public", "static", "void", "mkdirsIfNotExists", "(", "Location", "location", ")", "throws", "IOException", "{", "// Need to check && mkdir && check to deal with race condition", "if", "(", "!", "location", ".", "isDirectory", "(", ")", "&&", "!", "location", ".", "mkdirs", "(", ")", "&&", "!", "location", ".", "isDirectory", "(", ")", ")", "{", "throw", "new", "IOException", "(", "\"Failed to create directory at \"", "+", "location", ".", "toURI", "(", ")", ")", ";", "}", "}" ]
Create the directory represented by the location if not exists. @param location the location for the directory. @throws java.io.IOException If the location cannot be created
[ "Create", "the", "directory", "represented", "by", "the", "location", "if", "not", "exists", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-yarn/src/main/java/co/cask/tigon/io/Locations.java#L117-L122
1,035
cdapio/tigon
tigon-yarn/src/main/java/co/cask/tigon/lang/jar/BundleJarUtil.java
BundleJarUtil.getManifest
public static Manifest getManifest(Location jarLocation) throws IOException { URI uri = jarLocation.toURI(); // Small optimization if the location is local if ("file".equals(uri.getScheme())) { JarFile jarFile = new JarFile(new File(uri)); try { return jarFile.getManifest(); } finally { jarFile.close(); } } // Otherwise, need to search it with JarInputStream JarInputStream is = new JarInputStream(new BufferedInputStream(jarLocation.getInputStream())); try { // This only looks at the first entry, which if is created with jar util, then it'll be there. Manifest manifest = is.getManifest(); if (manifest != null) { return manifest; } // Otherwise, slow path. Need to goes through the entries JarEntry jarEntry = is.getNextJarEntry(); while (jarEntry != null) { if (JarFile.MANIFEST_NAME.equals(jarEntry.getName())) { return new Manifest(is); } jarEntry = is.getNextJarEntry(); } } finally { is.close(); } return null; }
java
public static Manifest getManifest(Location jarLocation) throws IOException { URI uri = jarLocation.toURI(); // Small optimization if the location is local if ("file".equals(uri.getScheme())) { JarFile jarFile = new JarFile(new File(uri)); try { return jarFile.getManifest(); } finally { jarFile.close(); } } // Otherwise, need to search it with JarInputStream JarInputStream is = new JarInputStream(new BufferedInputStream(jarLocation.getInputStream())); try { // This only looks at the first entry, which if is created with jar util, then it'll be there. Manifest manifest = is.getManifest(); if (manifest != null) { return manifest; } // Otherwise, slow path. Need to goes through the entries JarEntry jarEntry = is.getNextJarEntry(); while (jarEntry != null) { if (JarFile.MANIFEST_NAME.equals(jarEntry.getName())) { return new Manifest(is); } jarEntry = is.getNextJarEntry(); } } finally { is.close(); } return null; }
[ "public", "static", "Manifest", "getManifest", "(", "Location", "jarLocation", ")", "throws", "IOException", "{", "URI", "uri", "=", "jarLocation", ".", "toURI", "(", ")", ";", "// Small optimization if the location is local", "if", "(", "\"file\"", ".", "equals", "(", "uri", ".", "getScheme", "(", ")", ")", ")", "{", "JarFile", "jarFile", "=", "new", "JarFile", "(", "new", "File", "(", "uri", ")", ")", ";", "try", "{", "return", "jarFile", ".", "getManifest", "(", ")", ";", "}", "finally", "{", "jarFile", ".", "close", "(", ")", ";", "}", "}", "// Otherwise, need to search it with JarInputStream", "JarInputStream", "is", "=", "new", "JarInputStream", "(", "new", "BufferedInputStream", "(", "jarLocation", ".", "getInputStream", "(", ")", ")", ")", ";", "try", "{", "// This only looks at the first entry, which if is created with jar util, then it'll be there.", "Manifest", "manifest", "=", "is", ".", "getManifest", "(", ")", ";", "if", "(", "manifest", "!=", "null", ")", "{", "return", "manifest", ";", "}", "// Otherwise, slow path. Need to goes through the entries", "JarEntry", "jarEntry", "=", "is", ".", "getNextJarEntry", "(", ")", ";", "while", "(", "jarEntry", "!=", "null", ")", "{", "if", "(", "JarFile", ".", "MANIFEST_NAME", ".", "equals", "(", "jarEntry", ".", "getName", "(", ")", ")", ")", "{", "return", "new", "Manifest", "(", "is", ")", ";", "}", "jarEntry", "=", "is", ".", "getNextJarEntry", "(", ")", ";", "}", "}", "finally", "{", "is", ".", "close", "(", ")", ";", "}", "return", "null", ";", "}" ]
Load the manifest inside the given jar. @param jarLocation Location of the jar file. @return The manifest inside the jar file or {@code null} if no manifest inside the jar file. @throws java.io.IOException if failed to load the manifest.
[ "Load", "the", "manifest", "inside", "the", "given", "jar", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-yarn/src/main/java/co/cask/tigon/lang/jar/BundleJarUtil.java#L52-L88
1,036
cdapio/tigon
tigon-queue/src/main/java/co/cask/tigon/data/transaction/queue/hbase/HBaseQueueProducer.java
HBaseQueueProducer.persist
protected int persist(Iterable<QueueEntry> entries, Transaction transaction) throws IOException { long writePointer = transaction.getWritePointer(); byte[] rowKeyPrefix = Bytes.add(queueRowPrefix, Bytes.toBytes(writePointer)); int count = 0; List<Put> puts = Lists.newArrayList(); int bytes = 0; for (QueueEntry entry : entries) { // Row key = queue_name + writePointer + counter byte[] rowKey = Bytes.add(rowKeyPrefix, Bytes.toBytes(count++)); rowKey = HBaseQueueAdmin.ROW_KEY_DISTRIBUTOR.getDistributedKey(rowKey); rollbackKeys.add(rowKey); // No need to write ts=writePointer, as the row key already contains the writePointer Put put = new Put(rowKey); put.add(QueueEntryRow.COLUMN_FAMILY, QueueEntryRow.DATA_COLUMN, entry.getData()); put.add(QueueEntryRow.COLUMN_FAMILY, QueueEntryRow.META_COLUMN, QueueEntry.serializeHashKeys(entry.getHashKeys())); puts.add(put); bytes += entry.getData().length; } hTable.put(puts); hTable.flushCommits(); return bytes; }
java
protected int persist(Iterable<QueueEntry> entries, Transaction transaction) throws IOException { long writePointer = transaction.getWritePointer(); byte[] rowKeyPrefix = Bytes.add(queueRowPrefix, Bytes.toBytes(writePointer)); int count = 0; List<Put> puts = Lists.newArrayList(); int bytes = 0; for (QueueEntry entry : entries) { // Row key = queue_name + writePointer + counter byte[] rowKey = Bytes.add(rowKeyPrefix, Bytes.toBytes(count++)); rowKey = HBaseQueueAdmin.ROW_KEY_DISTRIBUTOR.getDistributedKey(rowKey); rollbackKeys.add(rowKey); // No need to write ts=writePointer, as the row key already contains the writePointer Put put = new Put(rowKey); put.add(QueueEntryRow.COLUMN_FAMILY, QueueEntryRow.DATA_COLUMN, entry.getData()); put.add(QueueEntryRow.COLUMN_FAMILY, QueueEntryRow.META_COLUMN, QueueEntry.serializeHashKeys(entry.getHashKeys())); puts.add(put); bytes += entry.getData().length; } hTable.put(puts); hTable.flushCommits(); return bytes; }
[ "protected", "int", "persist", "(", "Iterable", "<", "QueueEntry", ">", "entries", ",", "Transaction", "transaction", ")", "throws", "IOException", "{", "long", "writePointer", "=", "transaction", ".", "getWritePointer", "(", ")", ";", "byte", "[", "]", "rowKeyPrefix", "=", "Bytes", ".", "add", "(", "queueRowPrefix", ",", "Bytes", ".", "toBytes", "(", "writePointer", ")", ")", ";", "int", "count", "=", "0", ";", "List", "<", "Put", ">", "puts", "=", "Lists", ".", "newArrayList", "(", ")", ";", "int", "bytes", "=", "0", ";", "for", "(", "QueueEntry", "entry", ":", "entries", ")", "{", "// Row key = queue_name + writePointer + counter", "byte", "[", "]", "rowKey", "=", "Bytes", ".", "add", "(", "rowKeyPrefix", ",", "Bytes", ".", "toBytes", "(", "count", "++", ")", ")", ";", "rowKey", "=", "HBaseQueueAdmin", ".", "ROW_KEY_DISTRIBUTOR", ".", "getDistributedKey", "(", "rowKey", ")", ";", "rollbackKeys", ".", "add", "(", "rowKey", ")", ";", "// No need to write ts=writePointer, as the row key already contains the writePointer", "Put", "put", "=", "new", "Put", "(", "rowKey", ")", ";", "put", ".", "add", "(", "QueueEntryRow", ".", "COLUMN_FAMILY", ",", "QueueEntryRow", ".", "DATA_COLUMN", ",", "entry", ".", "getData", "(", ")", ")", ";", "put", ".", "add", "(", "QueueEntryRow", ".", "COLUMN_FAMILY", ",", "QueueEntryRow", ".", "META_COLUMN", ",", "QueueEntry", ".", "serializeHashKeys", "(", "entry", ".", "getHashKeys", "(", ")", ")", ")", ";", "puts", ".", "add", "(", "put", ")", ";", "bytes", "+=", "entry", ".", "getData", "(", ")", ".", "length", ";", "}", "hTable", ".", "put", "(", "puts", ")", ";", "hTable", ".", "flushCommits", "(", ")", ";", "return", "bytes", ";", "}" ]
Persist queue entries into HBase.
[ "Persist", "queue", "entries", "into", "HBase", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-queue/src/main/java/co/cask/tigon/data/transaction/queue/hbase/HBaseQueueProducer.java#L65-L95
1,037
cdapio/tigon
tigon-queue/src/main/java/co/cask/tigon/data/security/HBaseTokenUtils.java
HBaseTokenUtils.obtainToken
public static Credentials obtainToken(Configuration hConf, Credentials credentials) { if (!User.isHBaseSecurityEnabled(hConf)) { return credentials; } try { Class c = Class.forName("org.apache.hadoop.hbase.security.token.TokenUtil"); Method method = c.getMethod("obtainToken", Configuration.class); Token<? extends TokenIdentifier> token = castToken(method.invoke(null, hConf)); credentials.addToken(token.getService(), token); return credentials; } catch (Exception e) { LOG.error("Failed to get secure token for HBase.", e); throw Throwables.propagate(e); } }
java
public static Credentials obtainToken(Configuration hConf, Credentials credentials) { if (!User.isHBaseSecurityEnabled(hConf)) { return credentials; } try { Class c = Class.forName("org.apache.hadoop.hbase.security.token.TokenUtil"); Method method = c.getMethod("obtainToken", Configuration.class); Token<? extends TokenIdentifier> token = castToken(method.invoke(null, hConf)); credentials.addToken(token.getService(), token); return credentials; } catch (Exception e) { LOG.error("Failed to get secure token for HBase.", e); throw Throwables.propagate(e); } }
[ "public", "static", "Credentials", "obtainToken", "(", "Configuration", "hConf", ",", "Credentials", "credentials", ")", "{", "if", "(", "!", "User", ".", "isHBaseSecurityEnabled", "(", "hConf", ")", ")", "{", "return", "credentials", ";", "}", "try", "{", "Class", "c", "=", "Class", ".", "forName", "(", "\"org.apache.hadoop.hbase.security.token.TokenUtil\"", ")", ";", "Method", "method", "=", "c", ".", "getMethod", "(", "\"obtainToken\"", ",", "Configuration", ".", "class", ")", ";", "Token", "<", "?", "extends", "TokenIdentifier", ">", "token", "=", "castToken", "(", "method", ".", "invoke", "(", "null", ",", "hConf", ")", ")", ";", "credentials", ".", "addToken", "(", "token", ".", "getService", "(", ")", ",", "token", ")", ";", "return", "credentials", ";", "}", "catch", "(", "Exception", "e", ")", "{", "LOG", ".", "error", "(", "\"Failed to get secure token for HBase.\"", ",", "e", ")", ";", "throw", "Throwables", ".", "propagate", "(", "e", ")", ";", "}", "}" ]
Gets a HBase delegation token and stores it in the given Credentials. @return the same Credentials instance as the one given in parameter.
[ "Gets", "a", "HBase", "delegation", "token", "and", "stores", "it", "in", "the", "given", "Credentials", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-queue/src/main/java/co/cask/tigon/data/security/HBaseTokenUtils.java#L42-L60
1,038
cdapio/tigon
tigon-flow/src/main/java/co/cask/tigon/internal/app/runtime/flow/FlowletProcessDriver.java
FlowletProcessDriver.suspend
public void suspend() { if (suspension.compareAndSet(null, new CountDownLatch(1))) { try { suspendBarrier.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (BrokenBarrierException e) { LOG.error("Exception during suspend: " + flowletContext, e); } } }
java
public void suspend() { if (suspension.compareAndSet(null, new CountDownLatch(1))) { try { suspendBarrier.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (BrokenBarrierException e) { LOG.error("Exception during suspend: " + flowletContext, e); } } }
[ "public", "void", "suspend", "(", ")", "{", "if", "(", "suspension", ".", "compareAndSet", "(", "null", ",", "new", "CountDownLatch", "(", "1", ")", ")", ")", "{", "try", "{", "suspendBarrier", ".", "await", "(", ")", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "Thread", ".", "currentThread", "(", ")", ".", "interrupt", "(", ")", ";", "}", "catch", "(", "BrokenBarrierException", "e", ")", "{", "LOG", ".", "error", "(", "\"Exception during suspend: \"", "+", "flowletContext", ",", "e", ")", ";", "}", "}", "}" ]
Suspend the running of flowlet. This method will block until the flowlet running thread actually suspended.
[ "Suspend", "the", "running", "of", "flowlet", ".", "This", "method", "will", "block", "until", "the", "flowlet", "running", "thread", "actually", "suspended", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-flow/src/main/java/co/cask/tigon/internal/app/runtime/flow/FlowletProcessDriver.java#L122-L132
1,039
cdapio/tigon
tigon-flow/src/main/java/co/cask/tigon/internal/app/runtime/flow/FlowletProcessDriver.java
FlowletProcessDriver.resume
public void resume() { CountDownLatch latch = suspension.getAndSet(null); if (latch != null) { suspendBarrier.reset(); latch.countDown(); } }
java
public void resume() { CountDownLatch latch = suspension.getAndSet(null); if (latch != null) { suspendBarrier.reset(); latch.countDown(); } }
[ "public", "void", "resume", "(", ")", "{", "CountDownLatch", "latch", "=", "suspension", ".", "getAndSet", "(", "null", ")", ";", "if", "(", "latch", "!=", "null", ")", "{", "suspendBarrier", ".", "reset", "(", ")", ";", "latch", ".", "countDown", "(", ")", ";", "}", "}" ]
Resume the running of flowlet.
[ "Resume", "the", "running", "of", "flowlet", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-flow/src/main/java/co/cask/tigon/internal/app/runtime/flow/FlowletProcessDriver.java#L137-L143
1,040
cdapio/tigon
tigon-flow/src/main/java/co/cask/tigon/internal/app/runtime/flow/FlowletProcessDriver.java
FlowletProcessDriver.postProcess
private void postProcess(ProcessMethodCallback callback, TransactionContext txContext, InputDatum input, ProcessMethod.ProcessResult result) { InputContext inputContext = input.getInputContext(); Throwable failureCause = null; FailureReason.Type failureType = FailureReason.Type.IO_ERROR; try { if (result.isSuccess()) { // If it is a retry input, force the dequeued entries into current transaction. if (input.getRetry() > 0) { input.reclaim(); } txContext.finish(); } else { failureCause = result.getCause(); failureType = FailureReason.Type.USER; txContext.abort(); } } catch (Throwable e) { LOG.error("Transaction operation failed: {}", e.getMessage(), e); failureType = FailureReason.Type.IO_ERROR; if (failureCause == null) { failureCause = e; } try { if (result.isSuccess()) { txContext.abort(); } } catch (Throwable ex) { LOG.error("Fail to abort transaction: {}", inputContext, ex); } } try { if (failureCause == null) { callback.onSuccess(result.getEvent(), inputContext); } else { callback.onFailure(result.getEvent(), inputContext, new FailureReason(failureType, failureCause.getMessage(), failureCause), createInputAcknowledger(input)); } } catch (Throwable t) { LOG.error("Failed to invoke callback.", t); } }
java
private void postProcess(ProcessMethodCallback callback, TransactionContext txContext, InputDatum input, ProcessMethod.ProcessResult result) { InputContext inputContext = input.getInputContext(); Throwable failureCause = null; FailureReason.Type failureType = FailureReason.Type.IO_ERROR; try { if (result.isSuccess()) { // If it is a retry input, force the dequeued entries into current transaction. if (input.getRetry() > 0) { input.reclaim(); } txContext.finish(); } else { failureCause = result.getCause(); failureType = FailureReason.Type.USER; txContext.abort(); } } catch (Throwable e) { LOG.error("Transaction operation failed: {}", e.getMessage(), e); failureType = FailureReason.Type.IO_ERROR; if (failureCause == null) { failureCause = e; } try { if (result.isSuccess()) { txContext.abort(); } } catch (Throwable ex) { LOG.error("Fail to abort transaction: {}", inputContext, ex); } } try { if (failureCause == null) { callback.onSuccess(result.getEvent(), inputContext); } else { callback.onFailure(result.getEvent(), inputContext, new FailureReason(failureType, failureCause.getMessage(), failureCause), createInputAcknowledger(input)); } } catch (Throwable t) { LOG.error("Failed to invoke callback.", t); } }
[ "private", "void", "postProcess", "(", "ProcessMethodCallback", "callback", ",", "TransactionContext", "txContext", ",", "InputDatum", "input", ",", "ProcessMethod", ".", "ProcessResult", "result", ")", "{", "InputContext", "inputContext", "=", "input", ".", "getInputContext", "(", ")", ";", "Throwable", "failureCause", "=", "null", ";", "FailureReason", ".", "Type", "failureType", "=", "FailureReason", ".", "Type", ".", "IO_ERROR", ";", "try", "{", "if", "(", "result", ".", "isSuccess", "(", ")", ")", "{", "// If it is a retry input, force the dequeued entries into current transaction.", "if", "(", "input", ".", "getRetry", "(", ")", ">", "0", ")", "{", "input", ".", "reclaim", "(", ")", ";", "}", "txContext", ".", "finish", "(", ")", ";", "}", "else", "{", "failureCause", "=", "result", ".", "getCause", "(", ")", ";", "failureType", "=", "FailureReason", ".", "Type", ".", "USER", ";", "txContext", ".", "abort", "(", ")", ";", "}", "}", "catch", "(", "Throwable", "e", ")", "{", "LOG", ".", "error", "(", "\"Transaction operation failed: {}\"", ",", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "failureType", "=", "FailureReason", ".", "Type", ".", "IO_ERROR", ";", "if", "(", "failureCause", "==", "null", ")", "{", "failureCause", "=", "e", ";", "}", "try", "{", "if", "(", "result", ".", "isSuccess", "(", ")", ")", "{", "txContext", ".", "abort", "(", ")", ";", "}", "}", "catch", "(", "Throwable", "ex", ")", "{", "LOG", ".", "error", "(", "\"Fail to abort transaction: {}\"", ",", "inputContext", ",", "ex", ")", ";", "}", "}", "try", "{", "if", "(", "failureCause", "==", "null", ")", "{", "callback", ".", "onSuccess", "(", "result", ".", "getEvent", "(", ")", ",", "inputContext", ")", ";", "}", "else", "{", "callback", ".", "onFailure", "(", "result", ".", "getEvent", "(", ")", ",", "inputContext", ",", "new", "FailureReason", "(", "failureType", ",", "failureCause", ".", "getMessage", "(", ")", ",", "failureCause", ")", ",", "createInputAcknowledger", "(", "input", ")", ")", ";", "}", "}", "catch", "(", "Throwable", "t", ")", "{", "LOG", ".", "error", "(", "\"Failed to invoke callback.\"", ",", "t", ")", ";", "}", "}" ]
Process the process result. This method never throws.
[ "Process", "the", "process", "result", ".", "This", "method", "never", "throws", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-flow/src/main/java/co/cask/tigon/internal/app/runtime/flow/FlowletProcessDriver.java#L314-L357
1,041
cdapio/tigon
tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java
Bytes.putBytes
public static int putBytes(byte[] tgtBytes, int tgtOffset, byte[] srcBytes, int srcOffset, int srcLength) { System.arraycopy(srcBytes, srcOffset, tgtBytes, tgtOffset, srcLength); return tgtOffset + srcLength; }
java
public static int putBytes(byte[] tgtBytes, int tgtOffset, byte[] srcBytes, int srcOffset, int srcLength) { System.arraycopy(srcBytes, srcOffset, tgtBytes, tgtOffset, srcLength); return tgtOffset + srcLength; }
[ "public", "static", "int", "putBytes", "(", "byte", "[", "]", "tgtBytes", ",", "int", "tgtOffset", ",", "byte", "[", "]", "srcBytes", ",", "int", "srcOffset", ",", "int", "srcLength", ")", "{", "System", ".", "arraycopy", "(", "srcBytes", ",", "srcOffset", ",", "tgtBytes", ",", "tgtOffset", ",", "srcLength", ")", ";", "return", "tgtOffset", "+", "srcLength", ";", "}" ]
Put bytes at the specified byte array position. @param tgtBytes the byte array @param tgtOffset position in the array @param srcBytes array to write out @param srcOffset source offset @param srcLength source length @return incremented offset
[ "Put", "bytes", "at", "the", "specified", "byte", "array", "position", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java#L108-L112
1,042
cdapio/tigon
tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java
Bytes.toBytes
public static byte[] toBytes(ByteBuffer bb) { int length = bb.limit(); byte [] result = new byte[length]; System.arraycopy(bb.array(), bb.arrayOffset(), result, 0, length); return result; }
java
public static byte[] toBytes(ByteBuffer bb) { int length = bb.limit(); byte [] result = new byte[length]; System.arraycopy(bb.array(), bb.arrayOffset(), result, 0, length); return result; }
[ "public", "static", "byte", "[", "]", "toBytes", "(", "ByteBuffer", "bb", ")", "{", "int", "length", "=", "bb", ".", "limit", "(", ")", ";", "byte", "[", "]", "result", "=", "new", "byte", "[", "length", "]", ";", "System", ".", "arraycopy", "(", "bb", ".", "array", "(", ")", ",", "bb", ".", "arrayOffset", "(", ")", ",", "result", ",", "0", ",", "length", ")", ";", "return", "result", ";", "}" ]
Returns a new byte array, copied from the passed ByteBuffer. @param bb A ByteBuffer @return the byte array
[ "Returns", "a", "new", "byte", "array", "copied", "from", "the", "passed", "ByteBuffer", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java#L131-L136
1,043
cdapio/tigon
tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java
Bytes.toStringBinary
public static String toStringBinary(ByteBuffer buf) { if (buf == null) { return "null"; } return toStringBinary(buf.array(), buf.arrayOffset(), buf.limit()); }
java
public static String toStringBinary(ByteBuffer buf) { if (buf == null) { return "null"; } return toStringBinary(buf.array(), buf.arrayOffset(), buf.limit()); }
[ "public", "static", "String", "toStringBinary", "(", "ByteBuffer", "buf", ")", "{", "if", "(", "buf", "==", "null", ")", "{", "return", "\"null\"", ";", "}", "return", "toStringBinary", "(", "buf", ".", "array", "(", ")", ",", "buf", ".", "arrayOffset", "(", ")", ",", "buf", ".", "limit", "(", ")", ")", ";", "}" ]
Converts the given byte buffer, from its array offset to its limit, to a string. The position and the mark are ignored. @param buf a byte buffer @return a string representation of the buffer's binary contents
[ "Converts", "the", "given", "byte", "buffer", "from", "its", "array", "offset", "to", "its", "limit", "to", "a", "string", ".", "The", "position", "and", "the", "mark", "are", "ignored", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java#L214-L219
1,044
cdapio/tigon
tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java
Bytes.toLong
public static long toLong(byte[] bytes, int offset, final int length) { if (length != SIZEOF_LONG || offset + length > bytes.length) { throw explainWrongLengthOrOffset(bytes, offset, length, SIZEOF_LONG); } long l = 0; for (int i = offset; i < offset + length; i++) { l <<= 8; l ^= bytes[i] & 0xFF; } return l; }
java
public static long toLong(byte[] bytes, int offset, final int length) { if (length != SIZEOF_LONG || offset + length > bytes.length) { throw explainWrongLengthOrOffset(bytes, offset, length, SIZEOF_LONG); } long l = 0; for (int i = offset; i < offset + length; i++) { l <<= 8; l ^= bytes[i] & 0xFF; } return l; }
[ "public", "static", "long", "toLong", "(", "byte", "[", "]", "bytes", ",", "int", "offset", ",", "final", "int", "length", ")", "{", "if", "(", "length", "!=", "SIZEOF_LONG", "||", "offset", "+", "length", ">", "bytes", ".", "length", ")", "{", "throw", "explainWrongLengthOrOffset", "(", "bytes", ",", "offset", ",", "length", ",", "SIZEOF_LONG", ")", ";", "}", "long", "l", "=", "0", ";", "for", "(", "int", "i", "=", "offset", ";", "i", "<", "offset", "+", "length", ";", "i", "++", ")", "{", "l", "<<=", "8", ";", "l", "^=", "bytes", "[", "i", "]", "&", "0xFF", ";", "}", "return", "l", ";", "}" ]
Converts a byte array to a long value. @param bytes array of bytes @param offset offset into array @param length length of data (must be {@link #SIZEOF_LONG}) @return the long value @throws IllegalArgumentException if length is not {@link #SIZEOF_LONG} or if there's not enough room in the array at the offset indicated.
[ "Converts", "a", "byte", "array", "to", "a", "long", "value", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java#L394-L404
1,045
cdapio/tigon
tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java
Bytes.putLong
public static int putLong(byte[] bytes, int offset, long val) { if (bytes.length - offset < SIZEOF_LONG) { throw new IllegalArgumentException("Not enough room to put a long at" + " offset " + offset + " in a " + bytes.length + " byte array"); } for (int i = offset + 7; i > offset; i--) { bytes[i] = (byte) val; val >>>= 8; } bytes[offset] = (byte) val; return offset + SIZEOF_LONG; }
java
public static int putLong(byte[] bytes, int offset, long val) { if (bytes.length - offset < SIZEOF_LONG) { throw new IllegalArgumentException("Not enough room to put a long at" + " offset " + offset + " in a " + bytes.length + " byte array"); } for (int i = offset + 7; i > offset; i--) { bytes[i] = (byte) val; val >>>= 8; } bytes[offset] = (byte) val; return offset + SIZEOF_LONG; }
[ "public", "static", "int", "putLong", "(", "byte", "[", "]", "bytes", ",", "int", "offset", ",", "long", "val", ")", "{", "if", "(", "bytes", ".", "length", "-", "offset", "<", "SIZEOF_LONG", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Not enough room to put a long at\"", "+", "\" offset \"", "+", "offset", "+", "\" in a \"", "+", "bytes", ".", "length", "+", "\" byte array\"", ")", ";", "}", "for", "(", "int", "i", "=", "offset", "+", "7", ";", "i", ">", "offset", ";", "i", "--", ")", "{", "bytes", "[", "i", "]", "=", "(", "byte", ")", "val", ";", "val", ">>>=", "8", ";", "}", "bytes", "[", "offset", "]", "=", "(", "byte", ")", "val", ";", "return", "offset", "+", "SIZEOF_LONG", ";", "}" ]
Put a long value out to the specified byte array position. @param bytes the byte array @param offset position in the array @param val long to write out @return incremented offset @throws IllegalArgumentException if the byte array given doesn't have enough room at the offset specified.
[ "Put", "a", "long", "value", "out", "to", "the", "specified", "byte", "array", "position", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java#L430-L441
1,046
cdapio/tigon
tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java
Bytes.putFloat
public static int putFloat(byte [] bytes, int offset, float f) { return putInt(bytes, offset, Float.floatToRawIntBits(f)); }
java
public static int putFloat(byte [] bytes, int offset, float f) { return putInt(bytes, offset, Float.floatToRawIntBits(f)); }
[ "public", "static", "int", "putFloat", "(", "byte", "[", "]", "bytes", ",", "int", "offset", ",", "float", "f", ")", "{", "return", "putInt", "(", "bytes", ",", "offset", ",", "Float", ".", "floatToRawIntBits", "(", "f", ")", ")", ";", "}" ]
Put a float value out to the specified byte array position. @param bytes byte array @param offset offset to write to @param f float value @return New offset in <code>bytes</code>
[ "Put", "a", "float", "value", "out", "to", "the", "specified", "byte", "array", "position", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java#L469-L471
1,047
cdapio/tigon
tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java
Bytes.putDouble
public static int putDouble(byte [] bytes, int offset, double d) { return putLong(bytes, offset, Double.doubleToLongBits(d)); }
java
public static int putDouble(byte [] bytes, int offset, double d) { return putLong(bytes, offset, Double.doubleToLongBits(d)); }
[ "public", "static", "int", "putDouble", "(", "byte", "[", "]", "bytes", ",", "int", "offset", ",", "double", "d", ")", "{", "return", "putLong", "(", "bytes", ",", "offset", ",", "Double", ".", "doubleToLongBits", "(", "d", ")", ")", ";", "}" ]
Put a double value out to the specified byte array position. @param bytes byte array @param offset offset to write to @param d value @return New offset into array <code>bytes</code>
[ "Put", "a", "double", "value", "out", "to", "the", "specified", "byte", "array", "position", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java#L508-L510
1,048
cdapio/tigon
tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java
Bytes.toBytes
public static byte[] toBytes(int val) { byte [] b = new byte[4]; for (int i = 3; i > 0; i--) { b[i] = (byte) val; val >>>= 8; } b[0] = (byte) val; return b; }
java
public static byte[] toBytes(int val) { byte [] b = new byte[4]; for (int i = 3; i > 0; i--) { b[i] = (byte) val; val >>>= 8; } b[0] = (byte) val; return b; }
[ "public", "static", "byte", "[", "]", "toBytes", "(", "int", "val", ")", "{", "byte", "[", "]", "b", "=", "new", "byte", "[", "4", "]", ";", "for", "(", "int", "i", "=", "3", ";", "i", ">", "0", ";", "i", "--", ")", "{", "b", "[", "i", "]", "=", "(", "byte", ")", "val", ";", "val", ">>>=", "8", ";", "}", "b", "[", "0", "]", "=", "(", "byte", ")", "val", ";", "return", "b", ";", "}" ]
Convert an int value to a byte array. @param val value @return the byte array
[ "Convert", "an", "int", "value", "to", "a", "byte", "array", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java#L529-L537
1,049
cdapio/tigon
tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java
Bytes.putInt
public static int putInt(byte[] bytes, int offset, int val) { if (bytes.length - offset < SIZEOF_INT) { throw new IllegalArgumentException("Not enough room to put an int at" + " offset " + offset + " in a " + bytes.length + " byte array"); } for (int i = offset + 3; i > offset; i--) { bytes[i] = (byte) val; val >>>= 8; } bytes[offset] = (byte) val; return offset + SIZEOF_INT; }
java
public static int putInt(byte[] bytes, int offset, int val) { if (bytes.length - offset < SIZEOF_INT) { throw new IllegalArgumentException("Not enough room to put an int at" + " offset " + offset + " in a " + bytes.length + " byte array"); } for (int i = offset + 3; i > offset; i--) { bytes[i] = (byte) val; val >>>= 8; } bytes[offset] = (byte) val; return offset + SIZEOF_INT; }
[ "public", "static", "int", "putInt", "(", "byte", "[", "]", "bytes", ",", "int", "offset", ",", "int", "val", ")", "{", "if", "(", "bytes", ".", "length", "-", "offset", "<", "SIZEOF_INT", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Not enough room to put an int at\"", "+", "\" offset \"", "+", "offset", "+", "\" in a \"", "+", "bytes", ".", "length", "+", "\" byte array\"", ")", ";", "}", "for", "(", "int", "i", "=", "offset", "+", "3", ";", "i", ">", "offset", ";", "i", "--", ")", "{", "bytes", "[", "i", "]", "=", "(", "byte", ")", "val", ";", "val", ">>>=", "8", ";", "}", "bytes", "[", "offset", "]", "=", "(", "byte", ")", "val", ";", "return", "offset", "+", "SIZEOF_INT", ";", "}" ]
Put an int value out to the specified byte array position. @param bytes the byte array @param offset position in the array @param val int to write out @return incremented offset @throws IllegalArgumentException if the byte array given doesn't have enough room at the offset specified.
[ "Put", "an", "int", "value", "out", "to", "the", "specified", "byte", "array", "position", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java#L588-L599
1,050
cdapio/tigon
tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java
Bytes.toShort
public static short toShort(byte[] bytes, int offset, final int length) { if (length != SIZEOF_SHORT || offset + length > bytes.length) { throw explainWrongLengthOrOffset(bytes, offset, length, SIZEOF_SHORT); } short n = 0; n ^= bytes[offset] & 0xFF; n <<= 8; n ^= bytes[offset + 1] & 0xFF; return n; }
java
public static short toShort(byte[] bytes, int offset, final int length) { if (length != SIZEOF_SHORT || offset + length > bytes.length) { throw explainWrongLengthOrOffset(bytes, offset, length, SIZEOF_SHORT); } short n = 0; n ^= bytes[offset] & 0xFF; n <<= 8; n ^= bytes[offset + 1] & 0xFF; return n; }
[ "public", "static", "short", "toShort", "(", "byte", "[", "]", "bytes", ",", "int", "offset", ",", "final", "int", "length", ")", "{", "if", "(", "length", "!=", "SIZEOF_SHORT", "||", "offset", "+", "length", ">", "bytes", ".", "length", ")", "{", "throw", "explainWrongLengthOrOffset", "(", "bytes", ",", "offset", ",", "length", ",", "SIZEOF_SHORT", ")", ";", "}", "short", "n", "=", "0", ";", "n", "^=", "bytes", "[", "offset", "]", "&", "0xFF", ";", "n", "<<=", "8", ";", "n", "^=", "bytes", "[", "offset", "+", "1", "]", "&", "0xFF", ";", "return", "n", ";", "}" ]
Converts a byte array to a short value. @param bytes byte array @param offset offset into array @param length length, has to be {@link #SIZEOF_SHORT} @return the short value @throws IllegalArgumentException if length is not {@link #SIZEOF_SHORT} or if there's not enough room in the array at the offset indicated.
[ "Converts", "a", "byte", "array", "to", "a", "short", "value", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java#L642-L651
1,051
cdapio/tigon
tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java
Bytes.getBytes
public static byte[] getBytes(ByteBuffer buf) { int savedPos = buf.position(); byte [] newBytes = new byte[buf.remaining()]; buf.get(newBytes); buf.position(savedPos); return newBytes; }
java
public static byte[] getBytes(ByteBuffer buf) { int savedPos = buf.position(); byte [] newBytes = new byte[buf.remaining()]; buf.get(newBytes); buf.position(savedPos); return newBytes; }
[ "public", "static", "byte", "[", "]", "getBytes", "(", "ByteBuffer", "buf", ")", "{", "int", "savedPos", "=", "buf", ".", "position", "(", ")", ";", "byte", "[", "]", "newBytes", "=", "new", "byte", "[", "buf", ".", "remaining", "(", ")", "]", ";", "buf", ".", "get", "(", "newBytes", ")", ";", "buf", ".", "position", "(", "savedPos", ")", ";", "return", "newBytes", ";", "}" ]
This method will get a sequence of bytes from pos -> limit, but will restore pos after. @param buf @return byte array
[ "This", "method", "will", "get", "a", "sequence", "of", "bytes", "from", "pos", "-", ">", "limit", "but", "will", "restore", "pos", "after", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java#L659-L665
1,052
cdapio/tigon
tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java
Bytes.putShort
public static int putShort(byte[] bytes, int offset, short val) { if (bytes.length - offset < SIZEOF_SHORT) { throw new IllegalArgumentException("Not enough room to put a short at" + " offset " + offset + " in a " + bytes.length + " byte array"); } bytes[offset + 1] = (byte) val; val >>= 8; bytes[offset] = (byte) val; return offset + SIZEOF_SHORT; }
java
public static int putShort(byte[] bytes, int offset, short val) { if (bytes.length - offset < SIZEOF_SHORT) { throw new IllegalArgumentException("Not enough room to put a short at" + " offset " + offset + " in a " + bytes.length + " byte array"); } bytes[offset + 1] = (byte) val; val >>= 8; bytes[offset] = (byte) val; return offset + SIZEOF_SHORT; }
[ "public", "static", "int", "putShort", "(", "byte", "[", "]", "bytes", ",", "int", "offset", ",", "short", "val", ")", "{", "if", "(", "bytes", ".", "length", "-", "offset", "<", "SIZEOF_SHORT", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Not enough room to put a short at\"", "+", "\" offset \"", "+", "offset", "+", "\" in a \"", "+", "bytes", ".", "length", "+", "\" byte array\"", ")", ";", "}", "bytes", "[", "offset", "+", "1", "]", "=", "(", "byte", ")", "val", ";", "val", ">>=", "8", ";", "bytes", "[", "offset", "]", "=", "(", "byte", ")", "val", ";", "return", "offset", "+", "SIZEOF_SHORT", ";", "}" ]
Put a short value out to the specified byte array position. @param bytes the byte array @param offset position in the array @param val short to write out @return incremented offset @throws IllegalArgumentException if the byte array given doesn't have enough room at the offset specified.
[ "Put", "a", "short", "value", "out", "to", "the", "specified", "byte", "array", "position", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java#L676-L685
1,053
cdapio/tigon
tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java
Bytes.toBytes
public static byte[] toBytes(BigDecimal val) { byte[] valueBytes = val.unscaledValue().toByteArray(); byte[] result = new byte[valueBytes.length + SIZEOF_INT]; int offset = putInt(result, 0, val.scale()); putBytes(result, offset, valueBytes, 0, valueBytes.length); return result; }
java
public static byte[] toBytes(BigDecimal val) { byte[] valueBytes = val.unscaledValue().toByteArray(); byte[] result = new byte[valueBytes.length + SIZEOF_INT]; int offset = putInt(result, 0, val.scale()); putBytes(result, offset, valueBytes, 0, valueBytes.length); return result; }
[ "public", "static", "byte", "[", "]", "toBytes", "(", "BigDecimal", "val", ")", "{", "byte", "[", "]", "valueBytes", "=", "val", ".", "unscaledValue", "(", ")", ".", "toByteArray", "(", ")", ";", "byte", "[", "]", "result", "=", "new", "byte", "[", "valueBytes", ".", "length", "+", "SIZEOF_INT", "]", ";", "int", "offset", "=", "putInt", "(", "result", ",", "0", ",", "val", ".", "scale", "(", ")", ")", ";", "putBytes", "(", "result", ",", "offset", ",", "valueBytes", ",", "0", ",", "valueBytes", ".", "length", ")", ";", "return", "result", ";", "}" ]
Convert a BigDecimal value to a byte array. @param val @return the byte array
[ "Convert", "a", "BigDecimal", "value", "to", "a", "byte", "array", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java#L693-L699
1,054
cdapio/tigon
tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java
Bytes.toBigDecimal
public static BigDecimal toBigDecimal(byte[] bytes, int offset, final int length) { if (bytes == null || length < SIZEOF_INT + 1 || (offset + length > bytes.length)) { return null; } int scale = toInt(bytes, offset); byte[] tcBytes = new byte[length - SIZEOF_INT]; System.arraycopy(bytes, offset + SIZEOF_INT, tcBytes, 0, length - SIZEOF_INT); return new BigDecimal(new BigInteger(tcBytes), scale); }
java
public static BigDecimal toBigDecimal(byte[] bytes, int offset, final int length) { if (bytes == null || length < SIZEOF_INT + 1 || (offset + length > bytes.length)) { return null; } int scale = toInt(bytes, offset); byte[] tcBytes = new byte[length - SIZEOF_INT]; System.arraycopy(bytes, offset + SIZEOF_INT, tcBytes, 0, length - SIZEOF_INT); return new BigDecimal(new BigInteger(tcBytes), scale); }
[ "public", "static", "BigDecimal", "toBigDecimal", "(", "byte", "[", "]", "bytes", ",", "int", "offset", ",", "final", "int", "length", ")", "{", "if", "(", "bytes", "==", "null", "||", "length", "<", "SIZEOF_INT", "+", "1", "||", "(", "offset", "+", "length", ">", "bytes", ".", "length", ")", ")", "{", "return", "null", ";", "}", "int", "scale", "=", "toInt", "(", "bytes", ",", "offset", ")", ";", "byte", "[", "]", "tcBytes", "=", "new", "byte", "[", "length", "-", "SIZEOF_INT", "]", ";", "System", ".", "arraycopy", "(", "bytes", ",", "offset", "+", "SIZEOF_INT", ",", "tcBytes", ",", "0", ",", "length", "-", "SIZEOF_INT", ")", ";", "return", "new", "BigDecimal", "(", "new", "BigInteger", "(", "tcBytes", ")", ",", "scale", ")", ";", "}" ]
Converts a byte array to a BigDecimal value. @param bytes @param offset @param length @return the char value
[ "Converts", "a", "byte", "array", "to", "a", "BigDecimal", "value", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java#L720-L730
1,055
cdapio/tigon
tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java
Bytes.putBigDecimal
public static int putBigDecimal(byte[] bytes, int offset, BigDecimal val) { if (bytes == null) { return offset; } byte[] valueBytes = val.unscaledValue().toByteArray(); byte[] result = new byte[valueBytes.length + SIZEOF_INT]; offset = putInt(result, offset, val.scale()); return putBytes(result, offset, valueBytes, 0, valueBytes.length); }
java
public static int putBigDecimal(byte[] bytes, int offset, BigDecimal val) { if (bytes == null) { return offset; } byte[] valueBytes = val.unscaledValue().toByteArray(); byte[] result = new byte[valueBytes.length + SIZEOF_INT]; offset = putInt(result, offset, val.scale()); return putBytes(result, offset, valueBytes, 0, valueBytes.length); }
[ "public", "static", "int", "putBigDecimal", "(", "byte", "[", "]", "bytes", ",", "int", "offset", ",", "BigDecimal", "val", ")", "{", "if", "(", "bytes", "==", "null", ")", "{", "return", "offset", ";", "}", "byte", "[", "]", "valueBytes", "=", "val", ".", "unscaledValue", "(", ")", ".", "toByteArray", "(", ")", ";", "byte", "[", "]", "result", "=", "new", "byte", "[", "valueBytes", ".", "length", "+", "SIZEOF_INT", "]", ";", "offset", "=", "putInt", "(", "result", ",", "offset", ",", "val", ".", "scale", "(", ")", ")", ";", "return", "putBytes", "(", "result", ",", "offset", ",", "valueBytes", ",", "0", ",", "valueBytes", ".", "length", ")", ";", "}" ]
Put a BigDecimal value out to the specified byte array position. @param bytes the byte array @param offset position in the array @param val BigDecimal to write out @return incremented offset
[ "Put", "a", "BigDecimal", "value", "out", "to", "the", "specified", "byte", "array", "position", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java#L740-L749
1,056
cdapio/tigon
tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java
Bytes.startsWith
public static boolean startsWith(byte[] bytes, byte[] prefix) { return bytes != null && prefix != null && bytes.length >= prefix.length && LexicographicalComparerHolder.BEST_COMPARER. compareTo(bytes, 0, prefix.length, prefix, 0, prefix.length) == 0; }
java
public static boolean startsWith(byte[] bytes, byte[] prefix) { return bytes != null && prefix != null && bytes.length >= prefix.length && LexicographicalComparerHolder.BEST_COMPARER. compareTo(bytes, 0, prefix.length, prefix, 0, prefix.length) == 0; }
[ "public", "static", "boolean", "startsWith", "(", "byte", "[", "]", "bytes", ",", "byte", "[", "]", "prefix", ")", "{", "return", "bytes", "!=", "null", "&&", "prefix", "!=", "null", "&&", "bytes", ".", "length", ">=", "prefix", ".", "length", "&&", "LexicographicalComparerHolder", ".", "BEST_COMPARER", ".", "compareTo", "(", "bytes", ",", "0", ",", "prefix", ".", "length", ",", "prefix", ",", "0", ",", "prefix", ".", "length", ")", "==", "0", ";", "}" ]
Return true if the byte array on the right is a prefix of the byte array on the left.
[ "Return", "true", "if", "the", "byte", "array", "on", "the", "right", "is", "a", "prefix", "of", "the", "byte", "array", "on", "the", "left", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java#L912-L917
1,057
cdapio/tigon
tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java
Bytes.hashBytes
public static int hashBytes(byte[] bytes, int offset, int length) { int hash = 1; for (int i = offset; i < offset + length; i++) { hash = (31 * hash) + bytes[i]; } return hash; }
java
public static int hashBytes(byte[] bytes, int offset, int length) { int hash = 1; for (int i = offset; i < offset + length; i++) { hash = (31 * hash) + bytes[i]; } return hash; }
[ "public", "static", "int", "hashBytes", "(", "byte", "[", "]", "bytes", ",", "int", "offset", ",", "int", "length", ")", "{", "int", "hash", "=", "1", ";", "for", "(", "int", "i", "=", "offset", ";", "i", "<", "offset", "+", "length", ";", "i", "++", ")", "{", "hash", "=", "(", "31", "*", "hash", ")", "+", "bytes", "[", "i", "]", ";", "}", "return", "hash", ";", "}" ]
Compute hash for binary data.
[ "Compute", "hash", "for", "binary", "data", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java#L941-L947
1,058
cdapio/tigon
tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java
Bytes.add
public static byte [] add(final byte [] a, final byte [] b, final byte [] c) { byte [] result = new byte[a.length + b.length + c.length]; System.arraycopy(a, 0, result, 0, a.length); System.arraycopy(b, 0, result, a.length, b.length); System.arraycopy(c, 0, result, a.length + b.length, c.length); return result; }
java
public static byte [] add(final byte [] a, final byte [] b, final byte [] c) { byte [] result = new byte[a.length + b.length + c.length]; System.arraycopy(a, 0, result, 0, a.length); System.arraycopy(b, 0, result, a.length, b.length); System.arraycopy(c, 0, result, a.length + b.length, c.length); return result; }
[ "public", "static", "byte", "[", "]", "add", "(", "final", "byte", "[", "]", "a", ",", "final", "byte", "[", "]", "b", ",", "final", "byte", "[", "]", "c", ")", "{", "byte", "[", "]", "result", "=", "new", "byte", "[", "a", ".", "length", "+", "b", ".", "length", "+", "c", ".", "length", "]", ";", "System", ".", "arraycopy", "(", "a", ",", "0", ",", "result", ",", "0", ",", "a", ".", "length", ")", ";", "System", ".", "arraycopy", "(", "b", ",", "0", ",", "result", ",", "a", ".", "length", ",", "b", ".", "length", ")", ";", "System", ".", "arraycopy", "(", "c", ",", "0", ",", "result", ",", "a", ".", "length", "+", "b", ".", "length", ",", "c", ".", "length", ")", ";", "return", "result", ";", "}" ]
Concatenate three byte arrays. @param a first third @param b second third @param c third third @return New array made from a, b and c
[ "Concatenate", "three", "byte", "arrays", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java#L997-L1003
1,059
cdapio/tigon
tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java
Bytes.split
public static byte[][] split(final byte[] a, final byte[] b, boolean inclusive, final int num) { byte[][] ret = new byte[num + 2][]; int i = 0; Iterable<byte[]> iter = iterateOnSplits(a, b, inclusive, num); if (iter == null) { return null; } for (byte[] elem : iter) { ret[i++] = elem; } return ret; }
java
public static byte[][] split(final byte[] a, final byte[] b, boolean inclusive, final int num) { byte[][] ret = new byte[num + 2][]; int i = 0; Iterable<byte[]> iter = iterateOnSplits(a, b, inclusive, num); if (iter == null) { return null; } for (byte[] elem : iter) { ret[i++] = elem; } return ret; }
[ "public", "static", "byte", "[", "]", "[", "]", "split", "(", "final", "byte", "[", "]", "a", ",", "final", "byte", "[", "]", "b", ",", "boolean", "inclusive", ",", "final", "int", "num", ")", "{", "byte", "[", "]", "[", "]", "ret", "=", "new", "byte", "[", "num", "+", "2", "]", "[", "", "]", ";", "int", "i", "=", "0", ";", "Iterable", "<", "byte", "[", "]", ">", "iter", "=", "iterateOnSplits", "(", "a", ",", "b", ",", "inclusive", ",", "num", ")", ";", "if", "(", "iter", "==", "null", ")", "{", "return", "null", ";", "}", "for", "(", "byte", "[", "]", "elem", ":", "iter", ")", "{", "ret", "[", "i", "++", "]", "=", "elem", ";", "}", "return", "ret", ";", "}" ]
Split passed range. Expensive operation relatively. Uses BigInteger math. Useful splitting ranges for MapReduce jobs. @param a Beginning of range @param b End of range @param inclusive Whether the end of range is prefix-inclusive or is considered an exclusive boundary. Automatic splits are generally exclusive and manual splits with an explicit range utilize an inclusive end of range. @param num Number of times to split range. Pass 1 if you want to split the range in two; i.e. one split. @return Array of dividing values
[ "Split", "passed", "range", ".", "Expensive", "operation", "relatively", ".", "Uses", "BigInteger", "math", ".", "Useful", "splitting", "ranges", "for", "MapReduce", "jobs", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java#L1111-L1123
1,060
cdapio/tigon
tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java
Bytes.iterateOnSplits
public static Iterable<byte[]> iterateOnSplits(final byte[] a, final byte[] b, final int num) { return iterateOnSplits(a, b, false, num); }
java
public static Iterable<byte[]> iterateOnSplits(final byte[] a, final byte[] b, final int num) { return iterateOnSplits(a, b, false, num); }
[ "public", "static", "Iterable", "<", "byte", "[", "]", ">", "iterateOnSplits", "(", "final", "byte", "[", "]", "a", ",", "final", "byte", "[", "]", "b", ",", "final", "int", "num", ")", "{", "return", "iterateOnSplits", "(", "a", ",", "b", ",", "false", ",", "num", ")", ";", "}" ]
Iterate over keys within the passed range, splitting at an [a,b) boundary.
[ "Iterate", "over", "keys", "within", "the", "passed", "range", "splitting", "at", "an", "[", "a", "b", ")", "boundary", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java#L1128-L1130
1,061
cdapio/tigon
tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java
Bytes.iterateOnSplits
public static Iterable<byte[]> iterateOnSplits(final byte[] a, final byte[]b, boolean inclusive, final int num) { byte [] aPadded; byte [] bPadded; if (a.length < b.length) { aPadded = padTail(a, b.length - a.length); bPadded = b; } else if (b.length < a.length) { aPadded = a; bPadded = padTail(b, a.length - b.length); } else { aPadded = a; bPadded = b; } if (compareTo(aPadded, bPadded) >= 0) { throw new IllegalArgumentException("b <= a"); } if (num <= 0) { throw new IllegalArgumentException("num cannot be < 0"); } byte [] prependHeader = {1, 0}; final BigInteger startBI = new BigInteger(add(prependHeader, aPadded)); final BigInteger stopBI = new BigInteger(add(prependHeader, bPadded)); BigInteger diffBI = stopBI.subtract(startBI); if (inclusive) { diffBI = diffBI.add(BigInteger.ONE); } final BigInteger splitsBI = BigInteger.valueOf(num + 1); if (diffBI.compareTo(splitsBI) < 0) { return null; } final BigInteger intervalBI; try { intervalBI = diffBI.divide(splitsBI); } catch (Exception e) { return null; } final Iterator<byte[]> iterator = new Iterator<byte[]>() { private int i = -1; @Override public boolean hasNext() { return this.i < num + 1; } @Override public byte[] next() { this.i++; if (this.i == 0) { return a; } if (this.i == num + 1) { return b; } BigInteger curBI = startBI.add(intervalBI.multiply(BigInteger.valueOf(this.i))); byte [] padded = curBI.toByteArray(); if (padded[1] == 0) { padded = tail(padded, padded.length - 2); } else { padded = tail(padded, padded.length - 1); } return padded; } @Override public void remove() { throw new UnsupportedOperationException(); } }; return new Iterable<byte[]>() { @Override public Iterator<byte[]> iterator() { return iterator; } }; }
java
public static Iterable<byte[]> iterateOnSplits(final byte[] a, final byte[]b, boolean inclusive, final int num) { byte [] aPadded; byte [] bPadded; if (a.length < b.length) { aPadded = padTail(a, b.length - a.length); bPadded = b; } else if (b.length < a.length) { aPadded = a; bPadded = padTail(b, a.length - b.length); } else { aPadded = a; bPadded = b; } if (compareTo(aPadded, bPadded) >= 0) { throw new IllegalArgumentException("b <= a"); } if (num <= 0) { throw new IllegalArgumentException("num cannot be < 0"); } byte [] prependHeader = {1, 0}; final BigInteger startBI = new BigInteger(add(prependHeader, aPadded)); final BigInteger stopBI = new BigInteger(add(prependHeader, bPadded)); BigInteger diffBI = stopBI.subtract(startBI); if (inclusive) { diffBI = diffBI.add(BigInteger.ONE); } final BigInteger splitsBI = BigInteger.valueOf(num + 1); if (diffBI.compareTo(splitsBI) < 0) { return null; } final BigInteger intervalBI; try { intervalBI = diffBI.divide(splitsBI); } catch (Exception e) { return null; } final Iterator<byte[]> iterator = new Iterator<byte[]>() { private int i = -1; @Override public boolean hasNext() { return this.i < num + 1; } @Override public byte[] next() { this.i++; if (this.i == 0) { return a; } if (this.i == num + 1) { return b; } BigInteger curBI = startBI.add(intervalBI.multiply(BigInteger.valueOf(this.i))); byte [] padded = curBI.toByteArray(); if (padded[1] == 0) { padded = tail(padded, padded.length - 2); } else { padded = tail(padded, padded.length - 1); } return padded; } @Override public void remove() { throw new UnsupportedOperationException(); } }; return new Iterable<byte[]>() { @Override public Iterator<byte[]> iterator() { return iterator; } }; }
[ "public", "static", "Iterable", "<", "byte", "[", "]", ">", "iterateOnSplits", "(", "final", "byte", "[", "]", "a", ",", "final", "byte", "[", "]", "b", ",", "boolean", "inclusive", ",", "final", "int", "num", ")", "{", "byte", "[", "]", "aPadded", ";", "byte", "[", "]", "bPadded", ";", "if", "(", "a", ".", "length", "<", "b", ".", "length", ")", "{", "aPadded", "=", "padTail", "(", "a", ",", "b", ".", "length", "-", "a", ".", "length", ")", ";", "bPadded", "=", "b", ";", "}", "else", "if", "(", "b", ".", "length", "<", "a", ".", "length", ")", "{", "aPadded", "=", "a", ";", "bPadded", "=", "padTail", "(", "b", ",", "a", ".", "length", "-", "b", ".", "length", ")", ";", "}", "else", "{", "aPadded", "=", "a", ";", "bPadded", "=", "b", ";", "}", "if", "(", "compareTo", "(", "aPadded", ",", "bPadded", ")", ">=", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"b <= a\"", ")", ";", "}", "if", "(", "num", "<=", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"num cannot be < 0\"", ")", ";", "}", "byte", "[", "]", "prependHeader", "=", "{", "1", ",", "0", "}", ";", "final", "BigInteger", "startBI", "=", "new", "BigInteger", "(", "add", "(", "prependHeader", ",", "aPadded", ")", ")", ";", "final", "BigInteger", "stopBI", "=", "new", "BigInteger", "(", "add", "(", "prependHeader", ",", "bPadded", ")", ")", ";", "BigInteger", "diffBI", "=", "stopBI", ".", "subtract", "(", "startBI", ")", ";", "if", "(", "inclusive", ")", "{", "diffBI", "=", "diffBI", ".", "add", "(", "BigInteger", ".", "ONE", ")", ";", "}", "final", "BigInteger", "splitsBI", "=", "BigInteger", ".", "valueOf", "(", "num", "+", "1", ")", ";", "if", "(", "diffBI", ".", "compareTo", "(", "splitsBI", ")", "<", "0", ")", "{", "return", "null", ";", "}", "final", "BigInteger", "intervalBI", ";", "try", "{", "intervalBI", "=", "diffBI", ".", "divide", "(", "splitsBI", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "return", "null", ";", "}", "final", "Iterator", "<", "byte", "[", "]", ">", "iterator", "=", "new", "Iterator", "<", "byte", "[", "]", ">", "(", ")", "{", "private", "int", "i", "=", "-", "1", ";", "@", "Override", "public", "boolean", "hasNext", "(", ")", "{", "return", "this", ".", "i", "<", "num", "+", "1", ";", "}", "@", "Override", "public", "byte", "[", "]", "next", "(", ")", "{", "this", ".", "i", "++", ";", "if", "(", "this", ".", "i", "==", "0", ")", "{", "return", "a", ";", "}", "if", "(", "this", ".", "i", "==", "num", "+", "1", ")", "{", "return", "b", ";", "}", "BigInteger", "curBI", "=", "startBI", ".", "add", "(", "intervalBI", ".", "multiply", "(", "BigInteger", ".", "valueOf", "(", "this", ".", "i", ")", ")", ")", ";", "byte", "[", "]", "padded", "=", "curBI", ".", "toByteArray", "(", ")", ";", "if", "(", "padded", "[", "1", "]", "==", "0", ")", "{", "padded", "=", "tail", "(", "padded", ",", "padded", ".", "length", "-", "2", ")", ";", "}", "else", "{", "padded", "=", "tail", "(", "padded", ",", "padded", ".", "length", "-", "1", ")", ";", "}", "return", "padded", ";", "}", "@", "Override", "public", "void", "remove", "(", ")", "{", "throw", "new", "UnsupportedOperationException", "(", ")", ";", "}", "}", ";", "return", "new", "Iterable", "<", "byte", "[", "]", ">", "(", ")", "{", "@", "Override", "public", "Iterator", "<", "byte", "[", "]", ">", "iterator", "(", ")", "{", "return", "iterator", ";", "}", "}", ";", "}" ]
Iterate over keys within the passed range.
[ "Iterate", "over", "keys", "within", "the", "passed", "range", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java#L1135-L1213
1,062
cdapio/tigon
tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java
Bytes.toByteArrays
public static byte [][] toByteArrays(final String [] t) { byte [][] result = new byte[t.length][]; for (int i = 0; i < t.length; i++) { result[i] = Bytes.toBytes(t[i]); } return result; }
java
public static byte [][] toByteArrays(final String [] t) { byte [][] result = new byte[t.length][]; for (int i = 0; i < t.length; i++) { result[i] = Bytes.toBytes(t[i]); } return result; }
[ "public", "static", "byte", "[", "]", "[", "]", "toByteArrays", "(", "final", "String", "[", "]", "t", ")", "{", "byte", "[", "]", "[", "]", "result", "=", "new", "byte", "[", "t", ".", "length", "]", "[", "", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "t", ".", "length", ";", "i", "++", ")", "{", "result", "[", "i", "]", "=", "Bytes", ".", "toBytes", "(", "t", "[", "i", "]", ")", ";", "}", "return", "result", ";", "}" ]
Returns an array of byte arrays made from passed array of Text. @param t operands @return Array of byte arrays made from passed array of Text
[ "Returns", "an", "array", "of", "byte", "arrays", "made", "from", "passed", "array", "of", "Text", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java#L1233-L1239
1,063
cdapio/tigon
tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java
Bytes.writeStringFixedSize
public static void writeStringFixedSize(final DataOutput out, String s, int size) throws IOException { byte[] b = toBytes(s); if (b.length > size) { throw new IOException("Trying to write " + b.length + " bytes (" + toStringBinary(b) + ") into a field of length " + size); } out.writeBytes(s); for (int i = 0; i < size - s.length(); ++i) { out.writeByte(0); } }
java
public static void writeStringFixedSize(final DataOutput out, String s, int size) throws IOException { byte[] b = toBytes(s); if (b.length > size) { throw new IOException("Trying to write " + b.length + " bytes (" + toStringBinary(b) + ") into a field of length " + size); } out.writeBytes(s); for (int i = 0; i < size - s.length(); ++i) { out.writeByte(0); } }
[ "public", "static", "void", "writeStringFixedSize", "(", "final", "DataOutput", "out", ",", "String", "s", ",", "int", "size", ")", "throws", "IOException", "{", "byte", "[", "]", "b", "=", "toBytes", "(", "s", ")", ";", "if", "(", "b", ".", "length", ">", "size", ")", "{", "throw", "new", "IOException", "(", "\"Trying to write \"", "+", "b", ".", "length", "+", "\" bytes (\"", "+", "toStringBinary", "(", "b", ")", "+", "\") into a field of length \"", "+", "size", ")", ";", "}", "out", ".", "writeBytes", "(", "s", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "size", "-", "s", ".", "length", "(", ")", ";", "++", "i", ")", "{", "out", ".", "writeByte", "(", "0", ")", ";", "}", "}" ]
Writes a string as a fixed-size field, padded with zeros.
[ "Writes", "a", "string", "as", "a", "fixed", "-", "size", "field", "padded", "with", "zeros", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-api/src/main/java/co/cask/tigon/api/common/Bytes.java#L1356-L1368
1,064
cdapio/tigon
tigon-hbase-compat-0.94/src/main/java/co/cask/tigon/data/transaction/queue/hbase/HBase94QueueConsumer.java
HBase94QueueConsumer.createFilter
private Filter createFilter() { return new FilterList(FilterList.Operator.MUST_PASS_ONE, processedStateFilter, new SingleColumnValueFilter( QueueEntryRow.COLUMN_FAMILY, stateColumnName, CompareFilter.CompareOp.GREATER, new BinaryPrefixComparator(Bytes.toBytes(transaction.getReadPointer())) )); }
java
private Filter createFilter() { return new FilterList(FilterList.Operator.MUST_PASS_ONE, processedStateFilter, new SingleColumnValueFilter( QueueEntryRow.COLUMN_FAMILY, stateColumnName, CompareFilter.CompareOp.GREATER, new BinaryPrefixComparator(Bytes.toBytes(transaction.getReadPointer())) )); }
[ "private", "Filter", "createFilter", "(", ")", "{", "return", "new", "FilterList", "(", "FilterList", ".", "Operator", ".", "MUST_PASS_ONE", ",", "processedStateFilter", ",", "new", "SingleColumnValueFilter", "(", "QueueEntryRow", ".", "COLUMN_FAMILY", ",", "stateColumnName", ",", "CompareFilter", ".", "CompareOp", ".", "GREATER", ",", "new", "BinaryPrefixComparator", "(", "Bytes", ".", "toBytes", "(", "transaction", ".", "getReadPointer", "(", ")", ")", ")", ")", ")", ";", "}" ]
Creates a HBase filter that will filter out rows that that has committed state = PROCESSED.
[ "Creates", "a", "HBase", "filter", "that", "will", "filter", "out", "rows", "that", "that", "has", "committed", "state", "=", "PROCESSED", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-hbase-compat-0.94/src/main/java/co/cask/tigon/data/transaction/queue/hbase/HBase94QueueConsumer.java#L66-L71
1,065
cdapio/tigon
tigon-sql/src/main/java/co/cask/tigon/sql/io/MethodsDriver.java
MethodsDriver.invokeMethods
public void invokeMethods(String queryName, GDATDecoder decoder) throws InvocationTargetException, IllegalAccessException { for (MethodInvoker methodInvoker : methodListMap.get(queryName)) { // Reset the position to 0 of the underlying ByteBuffer before calling MethodInvoker.invoke() decoder.reset(); methodInvoker.invoke(decoder); } }
java
public void invokeMethods(String queryName, GDATDecoder decoder) throws InvocationTargetException, IllegalAccessException { for (MethodInvoker methodInvoker : methodListMap.get(queryName)) { // Reset the position to 0 of the underlying ByteBuffer before calling MethodInvoker.invoke() decoder.reset(); methodInvoker.invoke(decoder); } }
[ "public", "void", "invokeMethods", "(", "String", "queryName", ",", "GDATDecoder", "decoder", ")", "throws", "InvocationTargetException", ",", "IllegalAccessException", "{", "for", "(", "MethodInvoker", "methodInvoker", ":", "methodListMap", ".", "get", "(", "queryName", ")", ")", "{", "// Reset the position to 0 of the underlying ByteBuffer before calling MethodInvoker.invoke()", "decoder", ".", "reset", "(", ")", ";", "methodInvoker", ".", "invoke", "(", "decoder", ")", ";", "}", "}" ]
This function invokes all the methods associated with the provided query name @param queryName Name of query @param decoder {@link co.cask.tigon.sql.io.GDATDecoder} object for the incoming GDAT format data record @throws InvocationTargetException thrown by {@link java.lang.reflect.Method}.invoke() @throws IllegalAccessException thrown by {@link java.lang.reflect.Method}.invoke()
[ "This", "function", "invokes", "all", "the", "methods", "associated", "with", "the", "provided", "query", "name" ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-sql/src/main/java/co/cask/tigon/sql/io/MethodsDriver.java#L100-L107
1,066
cdapio/tigon
tigon-sql/src/main/java/co/cask/tigon/sql/flowlet/GDATRecordQueue.java
GDATRecordQueue.getNext
public Map.Entry<String, GDATDecoder> getNext() { Map.Entry<String, GDATDecoder> element = dataQueue.poll(); pendingRecords.add(element); return element; }
java
public Map.Entry<String, GDATDecoder> getNext() { Map.Entry<String, GDATDecoder> element = dataQueue.poll(); pendingRecords.add(element); return element; }
[ "public", "Map", ".", "Entry", "<", "String", ",", "GDATDecoder", ">", "getNext", "(", ")", "{", "Map", ".", "Entry", "<", "String", ",", "GDATDecoder", ">", "element", "=", "dataQueue", ".", "poll", "(", ")", ";", "pendingRecords", ".", "add", "(", "element", ")", ";", "return", "element", ";", "}" ]
This function returns the next entry in the data queue and adds it to a queue of pending items. This pendingRecords serves as a place holder for all the items of the current transaction. @return The next entry in the data queue.
[ "This", "function", "returns", "the", "next", "entry", "in", "the", "data", "queue", "and", "adds", "it", "to", "a", "queue", "of", "pending", "items", ".", "This", "pendingRecords", "serves", "as", "a", "place", "holder", "for", "all", "the", "items", "of", "the", "current", "transaction", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-sql/src/main/java/co/cask/tigon/sql/flowlet/GDATRecordQueue.java#L48-L52
1,067
cdapio/tigon
tigon-queue/src/main/java/co/cask/tigon/data/transaction/queue/hbase/HBaseQueueAdmin.java
HBaseQueueAdmin.getActualTableName
public String getActualTableName(QueueName queueName) { if (queueName.isQueue()) { // <tigon namespace>.system.queue.<account>.<flow> return getTableNameForFlow(queueName.getFirstComponent(), queueName.getSecondComponent()); } else { throw new IllegalArgumentException("'" + queueName + "' is not a valid name for a queue."); } }
java
public String getActualTableName(QueueName queueName) { if (queueName.isQueue()) { // <tigon namespace>.system.queue.<account>.<flow> return getTableNameForFlow(queueName.getFirstComponent(), queueName.getSecondComponent()); } else { throw new IllegalArgumentException("'" + queueName + "' is not a valid name for a queue."); } }
[ "public", "String", "getActualTableName", "(", "QueueName", "queueName", ")", "{", "if", "(", "queueName", ".", "isQueue", "(", ")", ")", "{", "// <tigon namespace>.system.queue.<account>.<flow>", "return", "getTableNameForFlow", "(", "queueName", ".", "getFirstComponent", "(", ")", ",", "queueName", ".", "getSecondComponent", "(", ")", ")", ";", "}", "else", "{", "throw", "new", "IllegalArgumentException", "(", "\"'\"", "+", "queueName", "+", "\"' is not a valid name for a queue.\"", ")", ";", "}", "}" ]
This determines the actual table name from the table name prefix and the name of the queue. @param queueName The name of the queue. @return the full name of the table that holds this queue.
[ "This", "determines", "the", "actual", "table", "name", "from", "the", "table", "name", "prefix", "and", "the", "name", "of", "the", "queue", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-queue/src/main/java/co/cask/tigon/data/transaction/queue/hbase/HBaseQueueAdmin.java#L136-L143
1,068
cdapio/tigon
tigon-flow/src/main/java/co/cask/tigon/internal/app/runtime/flow/FlowUtils.java
FlowUtils.generateConsumerGroupId
public static long generateConsumerGroupId(String flowId, String flowletId) { return Hashing.md5().newHasher() .putString(flowId) .putString(flowletId).hash().asLong(); }
java
public static long generateConsumerGroupId(String flowId, String flowletId) { return Hashing.md5().newHasher() .putString(flowId) .putString(flowletId).hash().asLong(); }
[ "public", "static", "long", "generateConsumerGroupId", "(", "String", "flowId", ",", "String", "flowletId", ")", "{", "return", "Hashing", ".", "md5", "(", ")", ".", "newHasher", "(", ")", ".", "putString", "(", "flowId", ")", ".", "putString", "(", "flowletId", ")", ".", "hash", "(", ")", ".", "asLong", "(", ")", ";", "}" ]
Generates a queue consumer groupId for the given flowlet in the given program id.
[ "Generates", "a", "queue", "consumer", "groupId", "for", "the", "given", "flowlet", "in", "the", "given", "program", "id", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-flow/src/main/java/co/cask/tigon/internal/app/runtime/flow/FlowUtils.java#L57-L61
1,069
cdapio/tigon
tigon-flow/src/main/java/co/cask/tigon/internal/app/runtime/flow/FlowUtils.java
FlowUtils.configureQueue
public static Multimap<String, QueueName> configureQueue(Program program, FlowSpecification flowSpec, QueueAdmin queueAdmin) { // Generate all queues specifications Table<QueueSpecificationGenerator.Node, String, Set<QueueSpecification>> queueSpecs = new SimpleQueueSpecificationGenerator().create(flowSpec); // For each queue in the flow, gather a map of consumer groupId to number of instances Table<QueueName, Long, Integer> queueConfigs = HashBasedTable.create(); // For storing result from flowletId to queue. ImmutableSetMultimap.Builder<String, QueueName> resultBuilder = ImmutableSetMultimap.builder(); // Loop through each flowlet for (Map.Entry<String, FlowletDefinition> entry : flowSpec.getFlowlets().entrySet()) { String flowletId = entry.getKey(); long groupId = FlowUtils.generateConsumerGroupId(program, flowletId); int instances = entry.getValue().getInstances(); // For each queue that the flowlet is a consumer, store the number of instances for this flowlet for (QueueSpecification queueSpec : Iterables.concat(queueSpecs.column(flowletId).values())) { queueConfigs.put(queueSpec.getQueueName(), groupId, instances); resultBuilder.put(flowletId, queueSpec.getQueueName()); } } try { // For each queue in the flow, configure it through QueueAdmin for (Map.Entry<QueueName, Map<Long, Integer>> row : queueConfigs.rowMap().entrySet()) { LOG.info("Queue config for {} : {}", row.getKey(), row.getValue()); queueAdmin.configureGroups(row.getKey(), row.getValue()); } return resultBuilder.build(); } catch (Exception e) { LOG.error("Failed to configure queues", e); throw Throwables.propagate(e); } }
java
public static Multimap<String, QueueName> configureQueue(Program program, FlowSpecification flowSpec, QueueAdmin queueAdmin) { // Generate all queues specifications Table<QueueSpecificationGenerator.Node, String, Set<QueueSpecification>> queueSpecs = new SimpleQueueSpecificationGenerator().create(flowSpec); // For each queue in the flow, gather a map of consumer groupId to number of instances Table<QueueName, Long, Integer> queueConfigs = HashBasedTable.create(); // For storing result from flowletId to queue. ImmutableSetMultimap.Builder<String, QueueName> resultBuilder = ImmutableSetMultimap.builder(); // Loop through each flowlet for (Map.Entry<String, FlowletDefinition> entry : flowSpec.getFlowlets().entrySet()) { String flowletId = entry.getKey(); long groupId = FlowUtils.generateConsumerGroupId(program, flowletId); int instances = entry.getValue().getInstances(); // For each queue that the flowlet is a consumer, store the number of instances for this flowlet for (QueueSpecification queueSpec : Iterables.concat(queueSpecs.column(flowletId).values())) { queueConfigs.put(queueSpec.getQueueName(), groupId, instances); resultBuilder.put(flowletId, queueSpec.getQueueName()); } } try { // For each queue in the flow, configure it through QueueAdmin for (Map.Entry<QueueName, Map<Long, Integer>> row : queueConfigs.rowMap().entrySet()) { LOG.info("Queue config for {} : {}", row.getKey(), row.getValue()); queueAdmin.configureGroups(row.getKey(), row.getValue()); } return resultBuilder.build(); } catch (Exception e) { LOG.error("Failed to configure queues", e); throw Throwables.propagate(e); } }
[ "public", "static", "Multimap", "<", "String", ",", "QueueName", ">", "configureQueue", "(", "Program", "program", ",", "FlowSpecification", "flowSpec", ",", "QueueAdmin", "queueAdmin", ")", "{", "// Generate all queues specifications", "Table", "<", "QueueSpecificationGenerator", ".", "Node", ",", "String", ",", "Set", "<", "QueueSpecification", ">", ">", "queueSpecs", "=", "new", "SimpleQueueSpecificationGenerator", "(", ")", ".", "create", "(", "flowSpec", ")", ";", "// For each queue in the flow, gather a map of consumer groupId to number of instances", "Table", "<", "QueueName", ",", "Long", ",", "Integer", ">", "queueConfigs", "=", "HashBasedTable", ".", "create", "(", ")", ";", "// For storing result from flowletId to queue.", "ImmutableSetMultimap", ".", "Builder", "<", "String", ",", "QueueName", ">", "resultBuilder", "=", "ImmutableSetMultimap", ".", "builder", "(", ")", ";", "// Loop through each flowlet", "for", "(", "Map", ".", "Entry", "<", "String", ",", "FlowletDefinition", ">", "entry", ":", "flowSpec", ".", "getFlowlets", "(", ")", ".", "entrySet", "(", ")", ")", "{", "String", "flowletId", "=", "entry", ".", "getKey", "(", ")", ";", "long", "groupId", "=", "FlowUtils", ".", "generateConsumerGroupId", "(", "program", ",", "flowletId", ")", ";", "int", "instances", "=", "entry", ".", "getValue", "(", ")", ".", "getInstances", "(", ")", ";", "// For each queue that the flowlet is a consumer, store the number of instances for this flowlet", "for", "(", "QueueSpecification", "queueSpec", ":", "Iterables", ".", "concat", "(", "queueSpecs", ".", "column", "(", "flowletId", ")", ".", "values", "(", ")", ")", ")", "{", "queueConfigs", ".", "put", "(", "queueSpec", ".", "getQueueName", "(", ")", ",", "groupId", ",", "instances", ")", ";", "resultBuilder", ".", "put", "(", "flowletId", ",", "queueSpec", ".", "getQueueName", "(", ")", ")", ";", "}", "}", "try", "{", "// For each queue in the flow, configure it through QueueAdmin", "for", "(", "Map", ".", "Entry", "<", "QueueName", ",", "Map", "<", "Long", ",", "Integer", ">", ">", "row", ":", "queueConfigs", ".", "rowMap", "(", ")", ".", "entrySet", "(", ")", ")", "{", "LOG", ".", "info", "(", "\"Queue config for {} : {}\"", ",", "row", ".", "getKey", "(", ")", ",", "row", ".", "getValue", "(", ")", ")", ";", "queueAdmin", ".", "configureGroups", "(", "row", ".", "getKey", "(", ")", ",", "row", ".", "getValue", "(", ")", ")", ";", "}", "return", "resultBuilder", ".", "build", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "LOG", ".", "error", "(", "\"Failed to configure queues\"", ",", "e", ")", ";", "throw", "Throwables", ".", "propagate", "(", "e", ")", ";", "}", "}" ]
Configures all queues being used in a flow. @return A Multimap from flowletId to QueueName where the flowlet is a consumer of.
[ "Configures", "all", "queues", "being", "used", "in", "a", "flow", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-flow/src/main/java/co/cask/tigon/internal/app/runtime/flow/FlowUtils.java#L68-L104
1,070
cdapio/tigon
tigon-sql/src/main/java/co/cask/tigon/sql/io/MethodInvoker.java
MethodInvoker.invoke
public void invoke(Decoder decoder) throws InvocationTargetException, IllegalAccessException { try { method.invoke(callingObject, pojoCreator.decode(decoder)); } catch (IOException e) { LOG.error("Skipping invocation of method {}. Cannot instantiate parameter object of type {}", getMethodName(), methodParameterClass.getName(), e); } }
java
public void invoke(Decoder decoder) throws InvocationTargetException, IllegalAccessException { try { method.invoke(callingObject, pojoCreator.decode(decoder)); } catch (IOException e) { LOG.error("Skipping invocation of method {}. Cannot instantiate parameter object of type {}", getMethodName(), methodParameterClass.getName(), e); } }
[ "public", "void", "invoke", "(", "Decoder", "decoder", ")", "throws", "InvocationTargetException", ",", "IllegalAccessException", "{", "try", "{", "method", ".", "invoke", "(", "callingObject", ",", "pojoCreator", ".", "decode", "(", "decoder", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "LOG", ".", "error", "(", "\"Skipping invocation of method {}. Cannot instantiate parameter object of type {}\"", ",", "getMethodName", "(", ")", ",", "methodParameterClass", ".", "getName", "(", ")", ",", "e", ")", ";", "}", "}" ]
This method instantiates an object of the method parameter type using the incoming decoder object and then invokes the associated method. @param decoder The {@link co.cask.tigon.io.Decoder} object for the incoming data record @throws InvocationTargetException thrown by {@link java.lang.reflect.Method}.invoke() @throws IllegalAccessException thrown by {@link java.lang.reflect.Method}.invoke()
[ "This", "method", "instantiates", "an", "object", "of", "the", "method", "parameter", "type", "using", "the", "incoming", "decoder", "object", "and", "then", "invokes", "the", "associated", "method", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-sql/src/main/java/co/cask/tigon/sql/io/MethodInvoker.java#L76-L83
1,071
cdapio/tigon
tigon-sql/src/main/java/co/cask/tigon/sql/io/GDATEncoder.java
GDATEncoder.writeLengthToStream
private void writeLengthToStream(int length, OutputStream out) throws IOException { sharedByteBuffer.clear(); sharedByteBuffer.order(ByteOrder.BIG_ENDIAN).putInt(length); sharedByteBuffer.flip(); out.write(sharedByteBuffer.array(), 0, Ints.BYTES); sharedByteBuffer.order(byteOrder); }
java
private void writeLengthToStream(int length, OutputStream out) throws IOException { sharedByteBuffer.clear(); sharedByteBuffer.order(ByteOrder.BIG_ENDIAN).putInt(length); sharedByteBuffer.flip(); out.write(sharedByteBuffer.array(), 0, Ints.BYTES); sharedByteBuffer.order(byteOrder); }
[ "private", "void", "writeLengthToStream", "(", "int", "length", ",", "OutputStream", "out", ")", "throws", "IOException", "{", "sharedByteBuffer", ".", "clear", "(", ")", ";", "sharedByteBuffer", ".", "order", "(", "ByteOrder", ".", "BIG_ENDIAN", ")", ".", "putInt", "(", "length", ")", ";", "sharedByteBuffer", ".", "flip", "(", ")", ";", "out", ".", "write", "(", "sharedByteBuffer", ".", "array", "(", ")", ",", "0", ",", "Ints", ".", "BYTES", ")", ";", "sharedByteBuffer", ".", "order", "(", "byteOrder", ")", ";", "}" ]
Write Length in Big Endian Order as per GDAT format specification.
[ "Write", "Length", "in", "Big", "Endian", "Order", "as", "per", "GDAT", "format", "specification", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-sql/src/main/java/co/cask/tigon/sql/io/GDATEncoder.java#L75-L81
1,072
cdapio/tigon
tigon-queue/src/main/java/co/cask/tigon/data/queue/QueueName.java
QueueName.from
public static QueueName from(byte[] bytes) { return new QueueName(URI.create(new String(bytes, Charsets.US_ASCII))); }
java
public static QueueName from(byte[] bytes) { return new QueueName(URI.create(new String(bytes, Charsets.US_ASCII))); }
[ "public", "static", "QueueName", "from", "(", "byte", "[", "]", "bytes", ")", "{", "return", "new", "QueueName", "(", "URI", ".", "create", "(", "new", "String", "(", "bytes", ",", "Charsets", ".", "US_ASCII", ")", ")", ")", ";", "}" ]
Constructs this class from byte array of queue URI. @param bytes respresenting URI @return An instance of {@link QueueName}
[ "Constructs", "this", "class", "from", "byte", "array", "of", "queue", "URI", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-queue/src/main/java/co/cask/tigon/data/queue/QueueName.java#L69-L71
1,073
cdapio/tigon
tigon-queue/src/main/java/co/cask/tigon/data/queue/QueueName.java
QueueName.fromStream
public static QueueName fromStream(String stream) { URI uri = URI.create(String.format("stream:///%s", stream)); return new QueueName(uri); }
java
public static QueueName fromStream(String stream) { URI uri = URI.create(String.format("stream:///%s", stream)); return new QueueName(uri); }
[ "public", "static", "QueueName", "fromStream", "(", "String", "stream", ")", "{", "URI", "uri", "=", "URI", ".", "create", "(", "String", ".", "format", "(", "\"stream:///%s\"", ",", "stream", ")", ")", ";", "return", "new", "QueueName", "(", "uri", ")", ";", "}" ]
Generates an QueueName for the stream. @param stream connected to flow @return An {@link QueueName} with schema as stream
[ "Generates", "an", "QueueName", "for", "the", "stream", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-queue/src/main/java/co/cask/tigon/data/queue/QueueName.java#L90-L93
1,074
cdapio/tigon
tigon-yarn/src/main/java/co/cask/tigon/internal/io/FieldAccessorGenerator.java
FieldAccessorGenerator.generateGetter
private void generateGetter(Field field) { if (isPrivate) { invokeReflection(getMethod(Object.class, "get", Object.class), getterSignature()); } else { directGetter(field); } if (field.getType().isPrimitive()) { primitiveGetter(field); } }
java
private void generateGetter(Field field) { if (isPrivate) { invokeReflection(getMethod(Object.class, "get", Object.class), getterSignature()); } else { directGetter(field); } if (field.getType().isPrimitive()) { primitiveGetter(field); } }
[ "private", "void", "generateGetter", "(", "Field", "field", ")", "{", "if", "(", "isPrivate", ")", "{", "invokeReflection", "(", "getMethod", "(", "Object", ".", "class", ",", "\"get\"", ",", "Object", ".", "class", ")", ",", "getterSignature", "(", ")", ")", ";", "}", "else", "{", "directGetter", "(", "field", ")", ";", "}", "if", "(", "field", ".", "getType", "(", ")", ".", "isPrimitive", "(", ")", ")", "{", "primitiveGetter", "(", "field", ")", ";", "}", "}" ]
Generates the getter method and optionally the primitive getter. @param field The reflection field object.
[ "Generates", "the", "getter", "method", "and", "optionally", "the", "primitive", "getter", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-yarn/src/main/java/co/cask/tigon/internal/io/FieldAccessorGenerator.java#L161-L171
1,075
cdapio/tigon
tigon-yarn/src/main/java/co/cask/tigon/internal/io/FieldAccessorGenerator.java
FieldAccessorGenerator.generateSetter
private void generateSetter(Field field) { if (isPrivate) { invokeReflection(getMethod(void.class, "set", Object.class, Object.class), setterSignature()); } else { directSetter(field); } if (field.getType().isPrimitive()) { primitiveSetter(field); } }
java
private void generateSetter(Field field) { if (isPrivate) { invokeReflection(getMethod(void.class, "set", Object.class, Object.class), setterSignature()); } else { directSetter(field); } if (field.getType().isPrimitive()) { primitiveSetter(field); } }
[ "private", "void", "generateSetter", "(", "Field", "field", ")", "{", "if", "(", "isPrivate", ")", "{", "invokeReflection", "(", "getMethod", "(", "void", ".", "class", ",", "\"set\"", ",", "Object", ".", "class", ",", "Object", ".", "class", ")", ",", "setterSignature", "(", ")", ")", ";", "}", "else", "{", "directSetter", "(", "field", ")", ";", "}", "if", "(", "field", ".", "getType", "(", ")", ".", "isPrimitive", "(", ")", ")", "{", "primitiveSetter", "(", "field", ")", ";", "}", "}" ]
Generates the setter method and optionally the primitive setter. @param field The reflection field object.
[ "Generates", "the", "setter", "method", "and", "optionally", "the", "primitive", "setter", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-yarn/src/main/java/co/cask/tigon/internal/io/FieldAccessorGenerator.java#L177-L187
1,076
cdapio/tigon
tigon-yarn/src/main/java/co/cask/tigon/internal/io/FieldAccessorGenerator.java
FieldAccessorGenerator.invokeReflection
private void invokeReflection(Method method, String signature) { GeneratorAdapter mg = new GeneratorAdapter(Opcodes.ACC_PUBLIC, method, signature, new Type[0], classWriter); /** * try { * // Call method * } catch (IllegalAccessException e) { * throw Throwables.propagate(e); * } */ Label beginTry = mg.newLabel(); Label endTry = mg.newLabel(); Label catchHandle = mg.newLabel(); mg.visitTryCatchBlock(beginTry, endTry, catchHandle, Type.getInternalName(IllegalAccessException.class)); mg.mark(beginTry); mg.loadThis(); mg.getField(Type.getObjectType(className), "field", Type.getType(Field.class)); mg.loadArgs(); mg.invokeVirtual(Type.getType(Field.class), method); mg.mark(endTry); mg.returnValue(); mg.mark(catchHandle); int exception = mg.newLocal(Type.getType(IllegalAccessException.class)); mg.storeLocal(exception); mg.loadLocal(exception); mg.invokeStatic(Type.getType(Throwables.class), getMethod(RuntimeException.class, "propagate", Throwable.class)); mg.throwException(); mg.endMethod(); }
java
private void invokeReflection(Method method, String signature) { GeneratorAdapter mg = new GeneratorAdapter(Opcodes.ACC_PUBLIC, method, signature, new Type[0], classWriter); /** * try { * // Call method * } catch (IllegalAccessException e) { * throw Throwables.propagate(e); * } */ Label beginTry = mg.newLabel(); Label endTry = mg.newLabel(); Label catchHandle = mg.newLabel(); mg.visitTryCatchBlock(beginTry, endTry, catchHandle, Type.getInternalName(IllegalAccessException.class)); mg.mark(beginTry); mg.loadThis(); mg.getField(Type.getObjectType(className), "field", Type.getType(Field.class)); mg.loadArgs(); mg.invokeVirtual(Type.getType(Field.class), method); mg.mark(endTry); mg.returnValue(); mg.mark(catchHandle); int exception = mg.newLocal(Type.getType(IllegalAccessException.class)); mg.storeLocal(exception); mg.loadLocal(exception); mg.invokeStatic(Type.getType(Throwables.class), getMethod(RuntimeException.class, "propagate", Throwable.class)); mg.throwException(); mg.endMethod(); }
[ "private", "void", "invokeReflection", "(", "Method", "method", ",", "String", "signature", ")", "{", "GeneratorAdapter", "mg", "=", "new", "GeneratorAdapter", "(", "Opcodes", ".", "ACC_PUBLIC", ",", "method", ",", "signature", ",", "new", "Type", "[", "0", "]", ",", "classWriter", ")", ";", "/**\n * try {\n * // Call method\n * } catch (IllegalAccessException e) {\n * throw Throwables.propagate(e);\n * }\n */", "Label", "beginTry", "=", "mg", ".", "newLabel", "(", ")", ";", "Label", "endTry", "=", "mg", ".", "newLabel", "(", ")", ";", "Label", "catchHandle", "=", "mg", ".", "newLabel", "(", ")", ";", "mg", ".", "visitTryCatchBlock", "(", "beginTry", ",", "endTry", ",", "catchHandle", ",", "Type", ".", "getInternalName", "(", "IllegalAccessException", ".", "class", ")", ")", ";", "mg", ".", "mark", "(", "beginTry", ")", ";", "mg", ".", "loadThis", "(", ")", ";", "mg", ".", "getField", "(", "Type", ".", "getObjectType", "(", "className", ")", ",", "\"field\"", ",", "Type", ".", "getType", "(", "Field", ".", "class", ")", ")", ";", "mg", ".", "loadArgs", "(", ")", ";", "mg", ".", "invokeVirtual", "(", "Type", ".", "getType", "(", "Field", ".", "class", ")", ",", "method", ")", ";", "mg", ".", "mark", "(", "endTry", ")", ";", "mg", ".", "returnValue", "(", ")", ";", "mg", ".", "mark", "(", "catchHandle", ")", ";", "int", "exception", "=", "mg", ".", "newLocal", "(", "Type", ".", "getType", "(", "IllegalAccessException", ".", "class", ")", ")", ";", "mg", ".", "storeLocal", "(", "exception", ")", ";", "mg", ".", "loadLocal", "(", "exception", ")", ";", "mg", ".", "invokeStatic", "(", "Type", ".", "getType", "(", "Throwables", ".", "class", ")", ",", "getMethod", "(", "RuntimeException", ".", "class", ",", "\"propagate\"", ",", "Throwable", ".", "class", ")", ")", ";", "mg", ".", "throwException", "(", ")", ";", "mg", ".", "endMethod", "(", ")", ";", "}" ]
Generates the try-catch block that wrap around the given reflection method call. @param method The method to be called within the try-catch block.
[ "Generates", "the", "try", "-", "catch", "block", "that", "wrap", "around", "the", "given", "reflection", "method", "call", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-yarn/src/main/java/co/cask/tigon/internal/io/FieldAccessorGenerator.java#L193-L222
1,077
cdapio/tigon
tigon-yarn/src/main/java/co/cask/tigon/internal/io/FieldAccessorGenerator.java
FieldAccessorGenerator.directGetter
private void directGetter(Field field) { GeneratorAdapter mg = new GeneratorAdapter(Opcodes.ACC_PUBLIC, getMethod(Object.class, "get", Object.class), getterSignature(), new Type[0], classWriter); // Simply access by field // return ((classType)object).fieldName; mg.loadArg(0); mg.checkCast(Type.getType(field.getDeclaringClass())); mg.getField(Type.getType(field.getDeclaringClass()), field.getName(), Type.getType(field.getType())); if (field.getType().isPrimitive()) { mg.valueOf(Type.getType(field.getType())); } mg.returnValue(); mg.endMethod(); }
java
private void directGetter(Field field) { GeneratorAdapter mg = new GeneratorAdapter(Opcodes.ACC_PUBLIC, getMethod(Object.class, "get", Object.class), getterSignature(), new Type[0], classWriter); // Simply access by field // return ((classType)object).fieldName; mg.loadArg(0); mg.checkCast(Type.getType(field.getDeclaringClass())); mg.getField(Type.getType(field.getDeclaringClass()), field.getName(), Type.getType(field.getType())); if (field.getType().isPrimitive()) { mg.valueOf(Type.getType(field.getType())); } mg.returnValue(); mg.endMethod(); }
[ "private", "void", "directGetter", "(", "Field", "field", ")", "{", "GeneratorAdapter", "mg", "=", "new", "GeneratorAdapter", "(", "Opcodes", ".", "ACC_PUBLIC", ",", "getMethod", "(", "Object", ".", "class", ",", "\"get\"", ",", "Object", ".", "class", ")", ",", "getterSignature", "(", ")", ",", "new", "Type", "[", "0", "]", ",", "classWriter", ")", ";", "// Simply access by field", "// return ((classType)object).fieldName;", "mg", ".", "loadArg", "(", "0", ")", ";", "mg", ".", "checkCast", "(", "Type", ".", "getType", "(", "field", ".", "getDeclaringClass", "(", ")", ")", ")", ";", "mg", ".", "getField", "(", "Type", ".", "getType", "(", "field", ".", "getDeclaringClass", "(", ")", ")", ",", "field", ".", "getName", "(", ")", ",", "Type", ".", "getType", "(", "field", ".", "getType", "(", ")", ")", ")", ";", "if", "(", "field", ".", "getType", "(", ")", ".", "isPrimitive", "(", ")", ")", "{", "mg", ".", "valueOf", "(", "Type", ".", "getType", "(", "field", ".", "getType", "(", ")", ")", ")", ";", "}", "mg", ".", "returnValue", "(", ")", ";", "mg", ".", "endMethod", "(", ")", ";", "}" ]
Generates a getter that get the value by directly accessing the class field. @param field The reflection field object.
[ "Generates", "a", "getter", "that", "get", "the", "value", "by", "directly", "accessing", "the", "class", "field", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-yarn/src/main/java/co/cask/tigon/internal/io/FieldAccessorGenerator.java#L228-L241
1,078
cdapio/tigon
tigon-yarn/src/main/java/co/cask/tigon/internal/io/FieldAccessorGenerator.java
FieldAccessorGenerator.directSetter
private void directSetter(Field field) { GeneratorAdapter mg = new GeneratorAdapter(Opcodes.ACC_PUBLIC, getMethod(void.class, "set", Object.class, Object.class), setterSignature(), new Type[0], classWriter); // Simply access by field // ((classType)object).fieldName = (valueType)value; mg.loadArg(0); mg.checkCast(Type.getType(field.getDeclaringClass())); mg.loadArg(1); if (field.getType().isPrimitive()) { mg.unbox(Type.getType(field.getType())); } else { mg.checkCast(Type.getType(field.getType())); } mg.putField(Type.getType(field.getDeclaringClass()), field.getName(), Type.getType(field.getType())); mg.returnValue(); mg.endMethod(); }
java
private void directSetter(Field field) { GeneratorAdapter mg = new GeneratorAdapter(Opcodes.ACC_PUBLIC, getMethod(void.class, "set", Object.class, Object.class), setterSignature(), new Type[0], classWriter); // Simply access by field // ((classType)object).fieldName = (valueType)value; mg.loadArg(0); mg.checkCast(Type.getType(field.getDeclaringClass())); mg.loadArg(1); if (field.getType().isPrimitive()) { mg.unbox(Type.getType(field.getType())); } else { mg.checkCast(Type.getType(field.getType())); } mg.putField(Type.getType(field.getDeclaringClass()), field.getName(), Type.getType(field.getType())); mg.returnValue(); mg.endMethod(); }
[ "private", "void", "directSetter", "(", "Field", "field", ")", "{", "GeneratorAdapter", "mg", "=", "new", "GeneratorAdapter", "(", "Opcodes", ".", "ACC_PUBLIC", ",", "getMethod", "(", "void", ".", "class", ",", "\"set\"", ",", "Object", ".", "class", ",", "Object", ".", "class", ")", ",", "setterSignature", "(", ")", ",", "new", "Type", "[", "0", "]", ",", "classWriter", ")", ";", "// Simply access by field", "// ((classType)object).fieldName = (valueType)value;", "mg", ".", "loadArg", "(", "0", ")", ";", "mg", ".", "checkCast", "(", "Type", ".", "getType", "(", "field", ".", "getDeclaringClass", "(", ")", ")", ")", ";", "mg", ".", "loadArg", "(", "1", ")", ";", "if", "(", "field", ".", "getType", "(", ")", ".", "isPrimitive", "(", ")", ")", "{", "mg", ".", "unbox", "(", "Type", ".", "getType", "(", "field", ".", "getType", "(", ")", ")", ")", ";", "}", "else", "{", "mg", ".", "checkCast", "(", "Type", ".", "getType", "(", "field", ".", "getType", "(", ")", ")", ")", ";", "}", "mg", ".", "putField", "(", "Type", ".", "getType", "(", "field", ".", "getDeclaringClass", "(", ")", ")", ",", "field", ".", "getName", "(", ")", ",", "Type", ".", "getType", "(", "field", ".", "getType", "(", ")", ")", ")", ";", "mg", ".", "returnValue", "(", ")", ";", "mg", ".", "endMethod", "(", ")", ";", "}" ]
Generates a setter that set the value by directly accessing the class field. @param field The reflection field object.
[ "Generates", "a", "setter", "that", "set", "the", "value", "by", "directly", "accessing", "the", "class", "field", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-yarn/src/main/java/co/cask/tigon/internal/io/FieldAccessorGenerator.java#L247-L264
1,079
cdapio/tigon
tigon-queue/src/main/java/co/cask/tigon/data/transaction/coprocessor/DefaultTransactionStateCacheSupplier.java
DefaultTransactionStateCacheSupplier.get
@Override public TransactionStateCache get() { if (instance == null) { synchronized (lock) { if (instance == null) { instance = new DefaultTransactionStateCache(namespace); instance.setConf(conf); instance.start(); } } } return instance; }
java
@Override public TransactionStateCache get() { if (instance == null) { synchronized (lock) { if (instance == null) { instance = new DefaultTransactionStateCache(namespace); instance.setConf(conf); instance.start(); } } } return instance; }
[ "@", "Override", "public", "TransactionStateCache", "get", "(", ")", "{", "if", "(", "instance", "==", "null", ")", "{", "synchronized", "(", "lock", ")", "{", "if", "(", "instance", "==", "null", ")", "{", "instance", "=", "new", "DefaultTransactionStateCache", "(", "namespace", ")", ";", "instance", ".", "setConf", "(", "conf", ")", ";", "instance", ".", "start", "(", ")", ";", "}", "}", "}", "return", "instance", ";", "}" ]
Returns a singleton instance of the transaction state cache, performing lazy initialization if necessary. @return A shared instance of the transaction state cache.
[ "Returns", "a", "singleton", "instance", "of", "the", "transaction", "state", "cache", "performing", "lazy", "initialization", "if", "necessary", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-queue/src/main/java/co/cask/tigon/data/transaction/coprocessor/DefaultTransactionStateCacheSupplier.java#L40-L52
1,080
cdapio/tigon
tigon-api/src/main/java/co/cask/tigon/internal/io/SchemaHash.java
SchemaHash.updateHash
private MessageDigest updateHash(MessageDigest md5, Schema schema, Set<String> knownRecords) { // Don't use enum.ordinal() as ordering in enum could change switch (schema.getType()) { case NULL: md5.update((byte) 0); break; case BOOLEAN: md5.update((byte) 1); break; case INT: md5.update((byte) 2); break; case LONG: md5.update((byte) 3); break; case FLOAT: md5.update((byte) 4); break; case DOUBLE: md5.update((byte) 5); break; case BYTES: md5.update((byte) 6); break; case STRING: md5.update((byte) 7); break; case ENUM: md5.update((byte) 8); for (String value : schema.getEnumValues()) { md5.update(Charsets.UTF_8.encode(value)); } break; case ARRAY: md5.update((byte) 9); updateHash(md5, schema.getComponentSchema(), knownRecords); break; case MAP: md5.update((byte) 10); updateHash(md5, schema.getMapSchema().getKey(), knownRecords); updateHash(md5, schema.getMapSchema().getValue(), knownRecords); break; case RECORD: md5.update((byte) 11); boolean notKnown = knownRecords.add(schema.getRecordName()); for (Schema.Field field : schema.getFields()) { md5.update(Charsets.UTF_8.encode(field.getName())); if (notKnown) { updateHash(md5, field.getSchema(), knownRecords); } } break; case UNION: md5.update((byte) 12); for (Schema unionSchema : schema.getUnionSchemas()) { updateHash(md5, unionSchema, knownRecords); } break; } return md5; }
java
private MessageDigest updateHash(MessageDigest md5, Schema schema, Set<String> knownRecords) { // Don't use enum.ordinal() as ordering in enum could change switch (schema.getType()) { case NULL: md5.update((byte) 0); break; case BOOLEAN: md5.update((byte) 1); break; case INT: md5.update((byte) 2); break; case LONG: md5.update((byte) 3); break; case FLOAT: md5.update((byte) 4); break; case DOUBLE: md5.update((byte) 5); break; case BYTES: md5.update((byte) 6); break; case STRING: md5.update((byte) 7); break; case ENUM: md5.update((byte) 8); for (String value : schema.getEnumValues()) { md5.update(Charsets.UTF_8.encode(value)); } break; case ARRAY: md5.update((byte) 9); updateHash(md5, schema.getComponentSchema(), knownRecords); break; case MAP: md5.update((byte) 10); updateHash(md5, schema.getMapSchema().getKey(), knownRecords); updateHash(md5, schema.getMapSchema().getValue(), knownRecords); break; case RECORD: md5.update((byte) 11); boolean notKnown = knownRecords.add(schema.getRecordName()); for (Schema.Field field : schema.getFields()) { md5.update(Charsets.UTF_8.encode(field.getName())); if (notKnown) { updateHash(md5, field.getSchema(), knownRecords); } } break; case UNION: md5.update((byte) 12); for (Schema unionSchema : schema.getUnionSchemas()) { updateHash(md5, unionSchema, knownRecords); } break; } return md5; }
[ "private", "MessageDigest", "updateHash", "(", "MessageDigest", "md5", ",", "Schema", "schema", ",", "Set", "<", "String", ">", "knownRecords", ")", "{", "// Don't use enum.ordinal() as ordering in enum could change", "switch", "(", "schema", ".", "getType", "(", ")", ")", "{", "case", "NULL", ":", "md5", ".", "update", "(", "(", "byte", ")", "0", ")", ";", "break", ";", "case", "BOOLEAN", ":", "md5", ".", "update", "(", "(", "byte", ")", "1", ")", ";", "break", ";", "case", "INT", ":", "md5", ".", "update", "(", "(", "byte", ")", "2", ")", ";", "break", ";", "case", "LONG", ":", "md5", ".", "update", "(", "(", "byte", ")", "3", ")", ";", "break", ";", "case", "FLOAT", ":", "md5", ".", "update", "(", "(", "byte", ")", "4", ")", ";", "break", ";", "case", "DOUBLE", ":", "md5", ".", "update", "(", "(", "byte", ")", "5", ")", ";", "break", ";", "case", "BYTES", ":", "md5", ".", "update", "(", "(", "byte", ")", "6", ")", ";", "break", ";", "case", "STRING", ":", "md5", ".", "update", "(", "(", "byte", ")", "7", ")", ";", "break", ";", "case", "ENUM", ":", "md5", ".", "update", "(", "(", "byte", ")", "8", ")", ";", "for", "(", "String", "value", ":", "schema", ".", "getEnumValues", "(", ")", ")", "{", "md5", ".", "update", "(", "Charsets", ".", "UTF_8", ".", "encode", "(", "value", ")", ")", ";", "}", "break", ";", "case", "ARRAY", ":", "md5", ".", "update", "(", "(", "byte", ")", "9", ")", ";", "updateHash", "(", "md5", ",", "schema", ".", "getComponentSchema", "(", ")", ",", "knownRecords", ")", ";", "break", ";", "case", "MAP", ":", "md5", ".", "update", "(", "(", "byte", ")", "10", ")", ";", "updateHash", "(", "md5", ",", "schema", ".", "getMapSchema", "(", ")", ".", "getKey", "(", ")", ",", "knownRecords", ")", ";", "updateHash", "(", "md5", ",", "schema", ".", "getMapSchema", "(", ")", ".", "getValue", "(", ")", ",", "knownRecords", ")", ";", "break", ";", "case", "RECORD", ":", "md5", ".", "update", "(", "(", "byte", ")", "11", ")", ";", "boolean", "notKnown", "=", "knownRecords", ".", "add", "(", "schema", ".", "getRecordName", "(", ")", ")", ";", "for", "(", "Schema", ".", "Field", "field", ":", "schema", ".", "getFields", "(", ")", ")", "{", "md5", ".", "update", "(", "Charsets", ".", "UTF_8", ".", "encode", "(", "field", ".", "getName", "(", ")", ")", ")", ";", "if", "(", "notKnown", ")", "{", "updateHash", "(", "md5", ",", "field", ".", "getSchema", "(", ")", ",", "knownRecords", ")", ";", "}", "}", "break", ";", "case", "UNION", ":", "md5", ".", "update", "(", "(", "byte", ")", "12", ")", ";", "for", "(", "Schema", "unionSchema", ":", "schema", ".", "getUnionSchemas", "(", ")", ")", "{", "updateHash", "(", "md5", ",", "unionSchema", ",", "knownRecords", ")", ";", "}", "break", ";", "}", "return", "md5", ";", "}" ]
Updates md5 based on the given schema. @param md5 {@link java.security.MessageDigest} to update. @param schema {@link Schema} for updating the md5. @param knownRecords bytes to use for updating the md5 for records that're seen before. @return The same {@link java.security.MessageDigest} in the parameter.
[ "Updates", "md5", "based", "on", "the", "given", "schema", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-api/src/main/java/co/cask/tigon/internal/io/SchemaHash.java#L108-L168
1,081
cdapio/tigon
tigon-yarn/src/main/java/co/cask/tigon/internal/io/DatumWriterGenerator.java
DatumWriterGenerator.getEncodeMethod
private Method getEncodeMethod(TypeToken<?> outputType, Schema schema) { String key = String.format("%s%s", normalizeTypeName(outputType), schema.getSchemaHash()); Method method = encodeMethods.get(key); if (method != null) { return method; } // Generate the encode method (value, encoder, schema, set) TypeToken<?> callOutputType = getCallTypeToken(outputType, schema); String methodName = String.format("encode%s", key); method = getMethod(void.class, methodName, callOutputType.getRawType(), Encoder.class, Schema.class, Set.class); // Put the method into map first before generating the body in order to support recursive data type. encodeMethods.put(key, method); String methodSignature = Signatures.getMethodSignature(method, new TypeToken[]{ callOutputType, null, null, new TypeToken<Set<Object>>() { }}); GeneratorAdapter mg = new GeneratorAdapter(Opcodes.ACC_PRIVATE, method, methodSignature, new Type[]{Type.getType(IOException.class)}, classWriter); generateEncodeBody(mg, schema, outputType, 0, 1, 2, 3); mg.returnValue(); mg.endMethod(); return method; }
java
private Method getEncodeMethod(TypeToken<?> outputType, Schema schema) { String key = String.format("%s%s", normalizeTypeName(outputType), schema.getSchemaHash()); Method method = encodeMethods.get(key); if (method != null) { return method; } // Generate the encode method (value, encoder, schema, set) TypeToken<?> callOutputType = getCallTypeToken(outputType, schema); String methodName = String.format("encode%s", key); method = getMethod(void.class, methodName, callOutputType.getRawType(), Encoder.class, Schema.class, Set.class); // Put the method into map first before generating the body in order to support recursive data type. encodeMethods.put(key, method); String methodSignature = Signatures.getMethodSignature(method, new TypeToken[]{ callOutputType, null, null, new TypeToken<Set<Object>>() { }}); GeneratorAdapter mg = new GeneratorAdapter(Opcodes.ACC_PRIVATE, method, methodSignature, new Type[]{Type.getType(IOException.class)}, classWriter); generateEncodeBody(mg, schema, outputType, 0, 1, 2, 3); mg.returnValue(); mg.endMethod(); return method; }
[ "private", "Method", "getEncodeMethod", "(", "TypeToken", "<", "?", ">", "outputType", ",", "Schema", "schema", ")", "{", "String", "key", "=", "String", ".", "format", "(", "\"%s%s\"", ",", "normalizeTypeName", "(", "outputType", ")", ",", "schema", ".", "getSchemaHash", "(", ")", ")", ";", "Method", "method", "=", "encodeMethods", ".", "get", "(", "key", ")", ";", "if", "(", "method", "!=", "null", ")", "{", "return", "method", ";", "}", "// Generate the encode method (value, encoder, schema, set)", "TypeToken", "<", "?", ">", "callOutputType", "=", "getCallTypeToken", "(", "outputType", ",", "schema", ")", ";", "String", "methodName", "=", "String", ".", "format", "(", "\"encode%s\"", ",", "key", ")", ";", "method", "=", "getMethod", "(", "void", ".", "class", ",", "methodName", ",", "callOutputType", ".", "getRawType", "(", ")", ",", "Encoder", ".", "class", ",", "Schema", ".", "class", ",", "Set", ".", "class", ")", ";", "// Put the method into map first before generating the body in order to support recursive data type.", "encodeMethods", ".", "put", "(", "key", ",", "method", ")", ";", "String", "methodSignature", "=", "Signatures", ".", "getMethodSignature", "(", "method", ",", "new", "TypeToken", "[", "]", "{", "callOutputType", ",", "null", ",", "null", ",", "new", "TypeToken", "<", "Set", "<", "Object", ">", ">", "(", ")", "{", "}", "}", ")", ";", "GeneratorAdapter", "mg", "=", "new", "GeneratorAdapter", "(", "Opcodes", ".", "ACC_PRIVATE", ",", "method", ",", "methodSignature", ",", "new", "Type", "[", "]", "{", "Type", ".", "getType", "(", "IOException", ".", "class", ")", "}", ",", "classWriter", ")", ";", "generateEncodeBody", "(", "mg", ",", "schema", ",", "outputType", ",", "0", ",", "1", ",", "2", ",", "3", ")", ";", "mg", ".", "returnValue", "(", ")", ";", "mg", ".", "endMethod", "(", ")", ";", "return", "method", ";", "}" ]
Returns the encode method for the given type and schema. The same method will be returned if the same type and schema has been passed to the method before. @param outputType Type information of the data type for output @param schema Schema to use for output. @return A method for encoding the given output type and schema.
[ "Returns", "the", "encode", "method", "for", "the", "given", "type", "and", "schema", ".", "The", "same", "method", "will", "be", "returned", "if", "the", "same", "type", "and", "schema", "has", "been", "passed", "to", "the", "method", "before", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-yarn/src/main/java/co/cask/tigon/internal/io/DatumWriterGenerator.java#L285-L312
1,082
cdapio/tigon
tigon-yarn/src/main/java/co/cask/tigon/internal/io/DatumWriterGenerator.java
DatumWriterGenerator.generateEncodeBody
private void generateEncodeBody(GeneratorAdapter mg, Schema schema, TypeToken<?> outputType, int value, int encoder, int schemaLocal, int seenRefs) { Schema.Type schemaType = schema.getType(); switch (schemaType) { case NULL: break; case BOOLEAN: encodeSimple(mg, outputType, schema, "writeBool", value, encoder); break; case INT: case LONG: case FLOAT: case DOUBLE: case BYTES: case STRING: String encodeMethod = "write" + schemaType.name().charAt(0) + schemaType.name().substring(1).toLowerCase(); encodeSimple(mg, outputType, schema, encodeMethod, value, encoder); break; case ENUM: encodeEnum(mg, outputType, value, encoder, schemaLocal); break; case ARRAY: if (Collection.class.isAssignableFrom(outputType.getRawType())) { Preconditions.checkArgument(outputType.getType() instanceof ParameterizedType, "Only support parameterized collection type."); TypeToken<?> componentType = TypeToken.of(((ParameterizedType) outputType.getType()) .getActualTypeArguments()[0]); encodeCollection(mg, componentType, schema.getComponentSchema(), value, encoder, schemaLocal, seenRefs); } else if (outputType.isArray()) { TypeToken<?> componentType = outputType.getComponentType(); encodeArray(mg, componentType, schema.getComponentSchema(), value, encoder, schemaLocal, seenRefs); } break; case MAP: Preconditions.checkArgument(Map.class.isAssignableFrom(outputType.getRawType()), "Only %s type is supported.", Map.class.getName()); Preconditions.checkArgument(outputType.getType() instanceof ParameterizedType, "Only support parameterized map type."); java.lang.reflect.Type[] mapArgs = ((ParameterizedType) outputType.getType()).getActualTypeArguments(); Map.Entry<Schema, Schema> mapSchema = schema.getMapSchema(); encodeMap(mg, TypeToken.of(mapArgs[0]), TypeToken.of(mapArgs[1]), mapSchema.getKey(), mapSchema.getValue(), value, encoder, schemaLocal, seenRefs); break; case RECORD: encodeRecord(mg, schema, outputType, value, encoder, schemaLocal, seenRefs); break; case UNION: encodeUnion(mg, outputType, schema, value, encoder, schemaLocal, seenRefs); break; } }
java
private void generateEncodeBody(GeneratorAdapter mg, Schema schema, TypeToken<?> outputType, int value, int encoder, int schemaLocal, int seenRefs) { Schema.Type schemaType = schema.getType(); switch (schemaType) { case NULL: break; case BOOLEAN: encodeSimple(mg, outputType, schema, "writeBool", value, encoder); break; case INT: case LONG: case FLOAT: case DOUBLE: case BYTES: case STRING: String encodeMethod = "write" + schemaType.name().charAt(0) + schemaType.name().substring(1).toLowerCase(); encodeSimple(mg, outputType, schema, encodeMethod, value, encoder); break; case ENUM: encodeEnum(mg, outputType, value, encoder, schemaLocal); break; case ARRAY: if (Collection.class.isAssignableFrom(outputType.getRawType())) { Preconditions.checkArgument(outputType.getType() instanceof ParameterizedType, "Only support parameterized collection type."); TypeToken<?> componentType = TypeToken.of(((ParameterizedType) outputType.getType()) .getActualTypeArguments()[0]); encodeCollection(mg, componentType, schema.getComponentSchema(), value, encoder, schemaLocal, seenRefs); } else if (outputType.isArray()) { TypeToken<?> componentType = outputType.getComponentType(); encodeArray(mg, componentType, schema.getComponentSchema(), value, encoder, schemaLocal, seenRefs); } break; case MAP: Preconditions.checkArgument(Map.class.isAssignableFrom(outputType.getRawType()), "Only %s type is supported.", Map.class.getName()); Preconditions.checkArgument(outputType.getType() instanceof ParameterizedType, "Only support parameterized map type."); java.lang.reflect.Type[] mapArgs = ((ParameterizedType) outputType.getType()).getActualTypeArguments(); Map.Entry<Schema, Schema> mapSchema = schema.getMapSchema(); encodeMap(mg, TypeToken.of(mapArgs[0]), TypeToken.of(mapArgs[1]), mapSchema.getKey(), mapSchema.getValue(), value, encoder, schemaLocal, seenRefs); break; case RECORD: encodeRecord(mg, schema, outputType, value, encoder, schemaLocal, seenRefs); break; case UNION: encodeUnion(mg, outputType, schema, value, encoder, schemaLocal, seenRefs); break; } }
[ "private", "void", "generateEncodeBody", "(", "GeneratorAdapter", "mg", ",", "Schema", "schema", ",", "TypeToken", "<", "?", ">", "outputType", ",", "int", "value", ",", "int", "encoder", ",", "int", "schemaLocal", ",", "int", "seenRefs", ")", "{", "Schema", ".", "Type", "schemaType", "=", "schema", ".", "getType", "(", ")", ";", "switch", "(", "schemaType", ")", "{", "case", "NULL", ":", "break", ";", "case", "BOOLEAN", ":", "encodeSimple", "(", "mg", ",", "outputType", ",", "schema", ",", "\"writeBool\"", ",", "value", ",", "encoder", ")", ";", "break", ";", "case", "INT", ":", "case", "LONG", ":", "case", "FLOAT", ":", "case", "DOUBLE", ":", "case", "BYTES", ":", "case", "STRING", ":", "String", "encodeMethod", "=", "\"write\"", "+", "schemaType", ".", "name", "(", ")", ".", "charAt", "(", "0", ")", "+", "schemaType", ".", "name", "(", ")", ".", "substring", "(", "1", ")", ".", "toLowerCase", "(", ")", ";", "encodeSimple", "(", "mg", ",", "outputType", ",", "schema", ",", "encodeMethod", ",", "value", ",", "encoder", ")", ";", "break", ";", "case", "ENUM", ":", "encodeEnum", "(", "mg", ",", "outputType", ",", "value", ",", "encoder", ",", "schemaLocal", ")", ";", "break", ";", "case", "ARRAY", ":", "if", "(", "Collection", ".", "class", ".", "isAssignableFrom", "(", "outputType", ".", "getRawType", "(", ")", ")", ")", "{", "Preconditions", ".", "checkArgument", "(", "outputType", ".", "getType", "(", ")", "instanceof", "ParameterizedType", ",", "\"Only support parameterized collection type.\"", ")", ";", "TypeToken", "<", "?", ">", "componentType", "=", "TypeToken", ".", "of", "(", "(", "(", "ParameterizedType", ")", "outputType", ".", "getType", "(", ")", ")", ".", "getActualTypeArguments", "(", ")", "[", "0", "]", ")", ";", "encodeCollection", "(", "mg", ",", "componentType", ",", "schema", ".", "getComponentSchema", "(", ")", ",", "value", ",", "encoder", ",", "schemaLocal", ",", "seenRefs", ")", ";", "}", "else", "if", "(", "outputType", ".", "isArray", "(", ")", ")", "{", "TypeToken", "<", "?", ">", "componentType", "=", "outputType", ".", "getComponentType", "(", ")", ";", "encodeArray", "(", "mg", ",", "componentType", ",", "schema", ".", "getComponentSchema", "(", ")", ",", "value", ",", "encoder", ",", "schemaLocal", ",", "seenRefs", ")", ";", "}", "break", ";", "case", "MAP", ":", "Preconditions", ".", "checkArgument", "(", "Map", ".", "class", ".", "isAssignableFrom", "(", "outputType", ".", "getRawType", "(", ")", ")", ",", "\"Only %s type is supported.\"", ",", "Map", ".", "class", ".", "getName", "(", ")", ")", ";", "Preconditions", ".", "checkArgument", "(", "outputType", ".", "getType", "(", ")", "instanceof", "ParameterizedType", ",", "\"Only support parameterized map type.\"", ")", ";", "java", ".", "lang", ".", "reflect", ".", "Type", "[", "]", "mapArgs", "=", "(", "(", "ParameterizedType", ")", "outputType", ".", "getType", "(", ")", ")", ".", "getActualTypeArguments", "(", ")", ";", "Map", ".", "Entry", "<", "Schema", ",", "Schema", ">", "mapSchema", "=", "schema", ".", "getMapSchema", "(", ")", ";", "encodeMap", "(", "mg", ",", "TypeToken", ".", "of", "(", "mapArgs", "[", "0", "]", ")", ",", "TypeToken", ".", "of", "(", "mapArgs", "[", "1", "]", ")", ",", "mapSchema", ".", "getKey", "(", ")", ",", "mapSchema", ".", "getValue", "(", ")", ",", "value", ",", "encoder", ",", "schemaLocal", ",", "seenRefs", ")", ";", "break", ";", "case", "RECORD", ":", "encodeRecord", "(", "mg", ",", "schema", ",", "outputType", ",", "value", ",", "encoder", ",", "schemaLocal", ",", "seenRefs", ")", ";", "break", ";", "case", "UNION", ":", "encodeUnion", "(", "mg", ",", "outputType", ",", "schema", ",", "value", ",", "encoder", ",", "schemaLocal", ",", "seenRefs", ")", ";", "break", ";", "}", "}" ]
Generates the encode method body, with the binary encoder given in the local variable. @param mg Method generator for generating method code body @param schema Schema of the data to be encoded.
[ "Generates", "the", "encode", "method", "body", "with", "the", "binary", "encoder", "given", "in", "the", "local", "variable", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-yarn/src/main/java/co/cask/tigon/internal/io/DatumWriterGenerator.java#L319-L373
1,083
cdapio/tigon
tigon-yarn/src/main/java/co/cask/tigon/internal/io/DatumWriterGenerator.java
DatumWriterGenerator.encodeInt
private void encodeInt(GeneratorAdapter mg, int intValue, int encoder) { mg.loadArg(encoder); mg.push(intValue); mg.invokeInterface(Type.getType(Encoder.class), getMethod(Encoder.class, "writeInt", int.class)); mg.pop(); }
java
private void encodeInt(GeneratorAdapter mg, int intValue, int encoder) { mg.loadArg(encoder); mg.push(intValue); mg.invokeInterface(Type.getType(Encoder.class), getMethod(Encoder.class, "writeInt", int.class)); mg.pop(); }
[ "private", "void", "encodeInt", "(", "GeneratorAdapter", "mg", ",", "int", "intValue", ",", "int", "encoder", ")", "{", "mg", ".", "loadArg", "(", "encoder", ")", ";", "mg", ".", "push", "(", "intValue", ")", ";", "mg", ".", "invokeInterface", "(", "Type", ".", "getType", "(", "Encoder", ".", "class", ")", ",", "getMethod", "(", "Encoder", ".", "class", ",", "\"writeInt\"", ",", "int", ".", "class", ")", ")", ";", "mg", ".", "pop", "(", ")", ";", "}" ]
Generates method body for encoding an compile time int value. @param mg Method body generator @param intValue The integer constant value to encode @param encoder Method argument index of the encoder
[ "Generates", "method", "body", "for", "encoding", "an", "compile", "time", "int", "value", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-yarn/src/main/java/co/cask/tigon/internal/io/DatumWriterGenerator.java#L381-L386
1,084
cdapio/tigon
tigon-yarn/src/main/java/co/cask/tigon/internal/io/DatumWriterGenerator.java
DatumWriterGenerator.encodeSimple
private void encodeSimple(GeneratorAdapter mg, TypeToken<?> type, Schema schema, String encodeMethod, int value, int encoder) { // encoder.writeXXX(value); TypeToken<?> encodeType = type; mg.loadArg(encoder); mg.loadArg(value); if (Primitives.isWrapperType(encodeType.getRawType())) { encodeType = TypeToken.of(Primitives.unwrap(encodeType.getRawType())); mg.unbox(Type.getType(encodeType.getRawType())); // A special case since INT type represents (byte, char, short and int). if (schema.getType() == Schema.Type.INT && !int.class.equals(encodeType.getRawType())) { encodeType = TypeToken.of(int.class); } } else if (schema.getType() == Schema.Type.STRING && !String.class.equals(encodeType.getRawType())) { // For non-string object that has a String schema, invoke toString(). mg.invokeVirtual(Type.getType(encodeType.getRawType()), getMethod(String.class, "toString")); encodeType = TypeToken.of(String.class); } else if (schema.getType() == Schema.Type.BYTES && UUID.class.equals(encodeType.getRawType())) { // Special case UUID, encode as byte array // ByteBuffer buf = ByteBuffer.allocate(Longs.BYTES * 2) // .putLong(uuid.getMostSignificantBits()) // .putLong(uuid.getLeastSignificantBits()); // encoder.writeBytes((ByteBuffer) buf.flip()); Type byteBufferType = Type.getType(ByteBuffer.class); Type uuidType = Type.getType(UUID.class); mg.push(Longs.BYTES * 2); mg.invokeStatic(byteBufferType, getMethod(ByteBuffer.class, "allocate", int.class)); mg.swap(); mg.invokeVirtual(uuidType, getMethod(long.class, "getMostSignificantBits")); mg.invokeVirtual(byteBufferType, getMethod(ByteBuffer.class, "putLong", long.class)); mg.loadArg(value); mg.invokeVirtual(uuidType, getMethod(long.class, "getLeastSignificantBits")); mg.invokeVirtual(byteBufferType, getMethod(ByteBuffer.class, "putLong", long.class)); mg.invokeVirtual(Type.getType(Buffer.class), getMethod(Buffer.class, "flip")); mg.checkCast(byteBufferType); encodeType = TypeToken.of(ByteBuffer.class); } mg.invokeInterface(Type.getType(Encoder.class), getMethod(Encoder.class, encodeMethod, encodeType.getRawType())); mg.pop(); }
java
private void encodeSimple(GeneratorAdapter mg, TypeToken<?> type, Schema schema, String encodeMethod, int value, int encoder) { // encoder.writeXXX(value); TypeToken<?> encodeType = type; mg.loadArg(encoder); mg.loadArg(value); if (Primitives.isWrapperType(encodeType.getRawType())) { encodeType = TypeToken.of(Primitives.unwrap(encodeType.getRawType())); mg.unbox(Type.getType(encodeType.getRawType())); // A special case since INT type represents (byte, char, short and int). if (schema.getType() == Schema.Type.INT && !int.class.equals(encodeType.getRawType())) { encodeType = TypeToken.of(int.class); } } else if (schema.getType() == Schema.Type.STRING && !String.class.equals(encodeType.getRawType())) { // For non-string object that has a String schema, invoke toString(). mg.invokeVirtual(Type.getType(encodeType.getRawType()), getMethod(String.class, "toString")); encodeType = TypeToken.of(String.class); } else if (schema.getType() == Schema.Type.BYTES && UUID.class.equals(encodeType.getRawType())) { // Special case UUID, encode as byte array // ByteBuffer buf = ByteBuffer.allocate(Longs.BYTES * 2) // .putLong(uuid.getMostSignificantBits()) // .putLong(uuid.getLeastSignificantBits()); // encoder.writeBytes((ByteBuffer) buf.flip()); Type byteBufferType = Type.getType(ByteBuffer.class); Type uuidType = Type.getType(UUID.class); mg.push(Longs.BYTES * 2); mg.invokeStatic(byteBufferType, getMethod(ByteBuffer.class, "allocate", int.class)); mg.swap(); mg.invokeVirtual(uuidType, getMethod(long.class, "getMostSignificantBits")); mg.invokeVirtual(byteBufferType, getMethod(ByteBuffer.class, "putLong", long.class)); mg.loadArg(value); mg.invokeVirtual(uuidType, getMethod(long.class, "getLeastSignificantBits")); mg.invokeVirtual(byteBufferType, getMethod(ByteBuffer.class, "putLong", long.class)); mg.invokeVirtual(Type.getType(Buffer.class), getMethod(Buffer.class, "flip")); mg.checkCast(byteBufferType); encodeType = TypeToken.of(ByteBuffer.class); } mg.invokeInterface(Type.getType(Encoder.class), getMethod(Encoder.class, encodeMethod, encodeType.getRawType())); mg.pop(); }
[ "private", "void", "encodeSimple", "(", "GeneratorAdapter", "mg", ",", "TypeToken", "<", "?", ">", "type", ",", "Schema", "schema", ",", "String", "encodeMethod", ",", "int", "value", ",", "int", "encoder", ")", "{", "// encoder.writeXXX(value);", "TypeToken", "<", "?", ">", "encodeType", "=", "type", ";", "mg", ".", "loadArg", "(", "encoder", ")", ";", "mg", ".", "loadArg", "(", "value", ")", ";", "if", "(", "Primitives", ".", "isWrapperType", "(", "encodeType", ".", "getRawType", "(", ")", ")", ")", "{", "encodeType", "=", "TypeToken", ".", "of", "(", "Primitives", ".", "unwrap", "(", "encodeType", ".", "getRawType", "(", ")", ")", ")", ";", "mg", ".", "unbox", "(", "Type", ".", "getType", "(", "encodeType", ".", "getRawType", "(", ")", ")", ")", ";", "// A special case since INT type represents (byte, char, short and int).", "if", "(", "schema", ".", "getType", "(", ")", "==", "Schema", ".", "Type", ".", "INT", "&&", "!", "int", ".", "class", ".", "equals", "(", "encodeType", ".", "getRawType", "(", ")", ")", ")", "{", "encodeType", "=", "TypeToken", ".", "of", "(", "int", ".", "class", ")", ";", "}", "}", "else", "if", "(", "schema", ".", "getType", "(", ")", "==", "Schema", ".", "Type", ".", "STRING", "&&", "!", "String", ".", "class", ".", "equals", "(", "encodeType", ".", "getRawType", "(", ")", ")", ")", "{", "// For non-string object that has a String schema, invoke toString().", "mg", ".", "invokeVirtual", "(", "Type", ".", "getType", "(", "encodeType", ".", "getRawType", "(", ")", ")", ",", "getMethod", "(", "String", ".", "class", ",", "\"toString\"", ")", ")", ";", "encodeType", "=", "TypeToken", ".", "of", "(", "String", ".", "class", ")", ";", "}", "else", "if", "(", "schema", ".", "getType", "(", ")", "==", "Schema", ".", "Type", ".", "BYTES", "&&", "UUID", ".", "class", ".", "equals", "(", "encodeType", ".", "getRawType", "(", ")", ")", ")", "{", "// Special case UUID, encode as byte array", "// ByteBuffer buf = ByteBuffer.allocate(Longs.BYTES * 2)", "// .putLong(uuid.getMostSignificantBits())", "// .putLong(uuid.getLeastSignificantBits());", "// encoder.writeBytes((ByteBuffer) buf.flip());", "Type", "byteBufferType", "=", "Type", ".", "getType", "(", "ByteBuffer", ".", "class", ")", ";", "Type", "uuidType", "=", "Type", ".", "getType", "(", "UUID", ".", "class", ")", ";", "mg", ".", "push", "(", "Longs", ".", "BYTES", "*", "2", ")", ";", "mg", ".", "invokeStatic", "(", "byteBufferType", ",", "getMethod", "(", "ByteBuffer", ".", "class", ",", "\"allocate\"", ",", "int", ".", "class", ")", ")", ";", "mg", ".", "swap", "(", ")", ";", "mg", ".", "invokeVirtual", "(", "uuidType", ",", "getMethod", "(", "long", ".", "class", ",", "\"getMostSignificantBits\"", ")", ")", ";", "mg", ".", "invokeVirtual", "(", "byteBufferType", ",", "getMethod", "(", "ByteBuffer", ".", "class", ",", "\"putLong\"", ",", "long", ".", "class", ")", ")", ";", "mg", ".", "loadArg", "(", "value", ")", ";", "mg", ".", "invokeVirtual", "(", "uuidType", ",", "getMethod", "(", "long", ".", "class", ",", "\"getLeastSignificantBits\"", ")", ")", ";", "mg", ".", "invokeVirtual", "(", "byteBufferType", ",", "getMethod", "(", "ByteBuffer", ".", "class", ",", "\"putLong\"", ",", "long", ".", "class", ")", ")", ";", "mg", ".", "invokeVirtual", "(", "Type", ".", "getType", "(", "Buffer", ".", "class", ")", ",", "getMethod", "(", "Buffer", ".", "class", ",", "\"flip\"", ")", ")", ";", "mg", ".", "checkCast", "(", "byteBufferType", ")", ";", "encodeType", "=", "TypeToken", ".", "of", "(", "ByteBuffer", ".", "class", ")", ";", "}", "mg", ".", "invokeInterface", "(", "Type", ".", "getType", "(", "Encoder", ".", "class", ")", ",", "getMethod", "(", "Encoder", ".", "class", ",", "encodeMethod", ",", "encodeType", ".", "getRawType", "(", ")", ")", ")", ";", "mg", ".", "pop", "(", ")", ";", "}" ]
Generates method body for encoding simple schema type by calling corresponding write method in Encoder. @param mg Method body generator @param type Data type to encode @param encodeMethod Name of the encode method to invoke on the given encoder. @param value Argument index of the value to encode. @param encoder Method argument index of the encoder
[ "Generates", "method", "body", "for", "encoding", "simple", "schema", "type", "by", "calling", "corresponding", "write", "method", "in", "Encoder", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-yarn/src/main/java/co/cask/tigon/internal/io/DatumWriterGenerator.java#L396-L442
1,085
cdapio/tigon
tigon-yarn/src/main/java/co/cask/tigon/internal/io/DatumWriterGenerator.java
DatumWriterGenerator.encodeEnum
private void encodeEnum(GeneratorAdapter mg, TypeToken<?> outputType, int value, int encoder, int schemaLocal) { // encoder.writeInt(this.schema.getEnumIndex(value.name())); mg.loadArg(encoder); mg.loadArg(schemaLocal); mg.loadArg(value); mg.invokeVirtual(Type.getType(outputType.getRawType()), getMethod(String.class, "name")); mg.invokeVirtual(Type.getType(Schema.class), getMethod(int.class, "getEnumIndex", String.class)); mg.invokeInterface(Type.getType(Encoder.class), getMethod(Encoder.class, "writeInt", int.class)); mg.pop(); }
java
private void encodeEnum(GeneratorAdapter mg, TypeToken<?> outputType, int value, int encoder, int schemaLocal) { // encoder.writeInt(this.schema.getEnumIndex(value.name())); mg.loadArg(encoder); mg.loadArg(schemaLocal); mg.loadArg(value); mg.invokeVirtual(Type.getType(outputType.getRawType()), getMethod(String.class, "name")); mg.invokeVirtual(Type.getType(Schema.class), getMethod(int.class, "getEnumIndex", String.class)); mg.invokeInterface(Type.getType(Encoder.class), getMethod(Encoder.class, "writeInt", int.class)); mg.pop(); }
[ "private", "void", "encodeEnum", "(", "GeneratorAdapter", "mg", ",", "TypeToken", "<", "?", ">", "outputType", ",", "int", "value", ",", "int", "encoder", ",", "int", "schemaLocal", ")", "{", "// encoder.writeInt(this.schema.getEnumIndex(value.name()));", "mg", ".", "loadArg", "(", "encoder", ")", ";", "mg", ".", "loadArg", "(", "schemaLocal", ")", ";", "mg", ".", "loadArg", "(", "value", ")", ";", "mg", ".", "invokeVirtual", "(", "Type", ".", "getType", "(", "outputType", ".", "getRawType", "(", ")", ")", ",", "getMethod", "(", "String", ".", "class", ",", "\"name\"", ")", ")", ";", "mg", ".", "invokeVirtual", "(", "Type", ".", "getType", "(", "Schema", ".", "class", ")", ",", "getMethod", "(", "int", ".", "class", ",", "\"getEnumIndex\"", ",", "String", ".", "class", ")", ")", ";", "mg", ".", "invokeInterface", "(", "Type", ".", "getType", "(", "Encoder", ".", "class", ")", ",", "getMethod", "(", "Encoder", ".", "class", ",", "\"writeInt\"", ",", "int", ".", "class", ")", ")", ";", "mg", ".", "pop", "(", ")", ";", "}" ]
Generates method body for encoding enum value. @param mg Method body generator @param outputType @param value @param encoder @param schemaLocal
[ "Generates", "method", "body", "for", "encoding", "enum", "value", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-yarn/src/main/java/co/cask/tigon/internal/io/DatumWriterGenerator.java#L452-L463
1,086
cdapio/tigon
tigon-yarn/src/main/java/co/cask/tigon/internal/io/DatumWriterGenerator.java
DatumWriterGenerator.getCallTypeToken
private TypeToken<?> getCallTypeToken(TypeToken<?> outputType, Schema schema) { Schema.Type schemaType = schema.getType(); if (schemaType == Schema.Type.RECORD || schemaType == Schema.Type.UNION) { return TypeToken.of(Object.class); } if (schemaType == Schema.Type.ARRAY && outputType.isArray()) { return getArrayType(getCallTypeToken(outputType.getComponentType(), schema.getComponentSchema())); } return outputType; }
java
private TypeToken<?> getCallTypeToken(TypeToken<?> outputType, Schema schema) { Schema.Type schemaType = schema.getType(); if (schemaType == Schema.Type.RECORD || schemaType == Schema.Type.UNION) { return TypeToken.of(Object.class); } if (schemaType == Schema.Type.ARRAY && outputType.isArray()) { return getArrayType(getCallTypeToken(outputType.getComponentType(), schema.getComponentSchema())); } return outputType; }
[ "private", "TypeToken", "<", "?", ">", "getCallTypeToken", "(", "TypeToken", "<", "?", ">", "outputType", ",", "Schema", "schema", ")", "{", "Schema", ".", "Type", "schemaType", "=", "schema", ".", "getType", "(", ")", ";", "if", "(", "schemaType", "==", "Schema", ".", "Type", ".", "RECORD", "||", "schemaType", "==", "Schema", ".", "Type", ".", "UNION", ")", "{", "return", "TypeToken", ".", "of", "(", "Object", ".", "class", ")", ";", "}", "if", "(", "schemaType", "==", "Schema", ".", "Type", ".", "ARRAY", "&&", "outputType", ".", "isArray", "(", ")", ")", "{", "return", "getArrayType", "(", "getCallTypeToken", "(", "outputType", ".", "getComponentType", "(", ")", ",", "schema", ".", "getComponentSchema", "(", ")", ")", ")", ";", "}", "return", "outputType", ";", "}" ]
Returns the type to be used on the encode method. This is needed to work with private classes that the generated DatumWriter doesn't have access to. @param outputType Type information of the data type for output @param schema Schema to use for output. @return The type information to be used for encode method.
[ "Returns", "the", "type", "to", "be", "used", "on", "the", "encode", "method", ".", "This", "is", "needed", "to", "work", "with", "private", "classes", "that", "the", "generated", "DatumWriter", "doesn", "t", "have", "access", "to", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-yarn/src/main/java/co/cask/tigon/internal/io/DatumWriterGenerator.java#L903-L914
1,087
cdapio/tigon
tigon-flow/src/main/java/co/cask/tigon/internal/app/runtime/distributed/FlowTwillProgramController.java
FlowTwillProgramController.changeInstances
private synchronized void changeInstances(String flowletId, int newInstanceCount, int oldInstanceCount) throws Exception { instanceUpdater.update(flowletId, newInstanceCount, oldInstanceCount); }
java
private synchronized void changeInstances(String flowletId, int newInstanceCount, int oldInstanceCount) throws Exception { instanceUpdater.update(flowletId, newInstanceCount, oldInstanceCount); }
[ "private", "synchronized", "void", "changeInstances", "(", "String", "flowletId", ",", "int", "newInstanceCount", ",", "int", "oldInstanceCount", ")", "throws", "Exception", "{", "instanceUpdater", ".", "update", "(", "flowletId", ",", "newInstanceCount", ",", "oldInstanceCount", ")", ";", "}" ]
Change the number of instances of the running flowlet. Notice that this method needs to be synchronized as change of instances involves multiple steps that need to be completed all at once. @param flowletId Name of the flowlet. @param newInstanceCount New instance count. @param oldInstanceCount Old instance count. @throws java.util.concurrent.ExecutionException @throws InterruptedException
[ "Change", "the", "number", "of", "instances", "of", "the", "running", "flowlet", ".", "Notice", "that", "this", "method", "needs", "to", "be", "synchronized", "as", "change", "of", "instances", "involves", "multiple", "steps", "that", "need", "to", "be", "completed", "all", "at", "once", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-flow/src/main/java/co/cask/tigon/internal/app/runtime/distributed/FlowTwillProgramController.java#L73-L76
1,088
cdapio/tigon
tigon-yarn/src/main/java/co/cask/tigon/internal/guava/ClassPath.java
ClassPath.getTopLevelClasses
public ImmutableSet<ClassInfo> getTopLevelClasses() { return FluentIterable.from(resources).filter(ClassInfo.class).filter(IS_TOP_LEVEL).toImmutableSet(); }
java
public ImmutableSet<ClassInfo> getTopLevelClasses() { return FluentIterable.from(resources).filter(ClassInfo.class).filter(IS_TOP_LEVEL).toImmutableSet(); }
[ "public", "ImmutableSet", "<", "ClassInfo", ">", "getTopLevelClasses", "(", ")", "{", "return", "FluentIterable", ".", "from", "(", "resources", ")", ".", "filter", "(", "ClassInfo", ".", "class", ")", ".", "filter", "(", "IS_TOP_LEVEL", ")", ".", "toImmutableSet", "(", ")", ";", "}" ]
Returns all top level classes loadable from the current class path.
[ "Returns", "all", "top", "level", "classes", "loadable", "from", "the", "current", "class", "path", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-yarn/src/main/java/co/cask/tigon/internal/guava/ClassPath.java#L161-L163
1,089
cdapio/tigon
tigon-flow/src/main/java/co/cask/tigon/internal/app/runtime/flow/FlowletProgramRunner.java
FlowletProgramRunner.createServiceHook
private Service createServiceHook(String flowletName, Iterable<ConsumerSupplier<?>> consumerSuppliers, AtomicReference<FlowletProgramController> controller) { final List<String> streams = Lists.newArrayList(); for (ConsumerSupplier<?> consumerSupplier : consumerSuppliers) { QueueName queueName = consumerSupplier.getQueueName(); if (queueName.isStream()) { streams.add(queueName.getSimpleName()); } } // If no stream, returns a no-op Service if (streams.isEmpty()) { return new AbstractService() { @Override protected void doStart() { notifyStarted(); } @Override protected void doStop() { notifyStopped(); } }; } return new FlowletServiceHook(flowletName, streams, controller); }
java
private Service createServiceHook(String flowletName, Iterable<ConsumerSupplier<?>> consumerSuppliers, AtomicReference<FlowletProgramController> controller) { final List<String> streams = Lists.newArrayList(); for (ConsumerSupplier<?> consumerSupplier : consumerSuppliers) { QueueName queueName = consumerSupplier.getQueueName(); if (queueName.isStream()) { streams.add(queueName.getSimpleName()); } } // If no stream, returns a no-op Service if (streams.isEmpty()) { return new AbstractService() { @Override protected void doStart() { notifyStarted(); } @Override protected void doStop() { notifyStopped(); } }; } return new FlowletServiceHook(flowletName, streams, controller); }
[ "private", "Service", "createServiceHook", "(", "String", "flowletName", ",", "Iterable", "<", "ConsumerSupplier", "<", "?", ">", ">", "consumerSuppliers", ",", "AtomicReference", "<", "FlowletProgramController", ">", "controller", ")", "{", "final", "List", "<", "String", ">", "streams", "=", "Lists", ".", "newArrayList", "(", ")", ";", "for", "(", "ConsumerSupplier", "<", "?", ">", "consumerSupplier", ":", "consumerSuppliers", ")", "{", "QueueName", "queueName", "=", "consumerSupplier", ".", "getQueueName", "(", ")", ";", "if", "(", "queueName", ".", "isStream", "(", ")", ")", "{", "streams", ".", "add", "(", "queueName", ".", "getSimpleName", "(", ")", ")", ";", "}", "}", "// If no stream, returns a no-op Service", "if", "(", "streams", ".", "isEmpty", "(", ")", ")", "{", "return", "new", "AbstractService", "(", ")", "{", "@", "Override", "protected", "void", "doStart", "(", ")", "{", "notifyStarted", "(", ")", ";", "}", "@", "Override", "protected", "void", "doStop", "(", ")", "{", "notifyStopped", "(", ")", ";", "}", "}", ";", "}", "return", "new", "FlowletServiceHook", "(", "flowletName", ",", "streams", ",", "controller", ")", ";", "}" ]
Create a initializer to be executed during the flowlet driver initialization.
[ "Create", "a", "initializer", "to", "be", "executed", "during", "the", "flowlet", "driver", "initialization", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-flow/src/main/java/co/cask/tigon/internal/app/runtime/flow/FlowletProgramRunner.java#L569-L594
1,090
cdapio/tigon
tigon-flow/src/main/java/co/cask/tigon/flow/DeployClient.java
DeployClient.getManifestWithMainClass
public static Manifest getManifestWithMainClass(Class<?> klass) { Manifest manifest = new Manifest(); manifest.getMainAttributes().put(ManifestFields.MANIFEST_VERSION, "1.0"); manifest.getMainAttributes().put(ManifestFields.MAIN_CLASS, klass.getName()); return manifest; }
java
public static Manifest getManifestWithMainClass(Class<?> klass) { Manifest manifest = new Manifest(); manifest.getMainAttributes().put(ManifestFields.MANIFEST_VERSION, "1.0"); manifest.getMainAttributes().put(ManifestFields.MAIN_CLASS, klass.getName()); return manifest; }
[ "public", "static", "Manifest", "getManifestWithMainClass", "(", "Class", "<", "?", ">", "klass", ")", "{", "Manifest", "manifest", "=", "new", "Manifest", "(", ")", ";", "manifest", ".", "getMainAttributes", "(", ")", ".", "put", "(", "ManifestFields", ".", "MANIFEST_VERSION", ",", "\"1.0\"", ")", ";", "manifest", ".", "getMainAttributes", "(", ")", ".", "put", "(", "ManifestFields", ".", "MAIN_CLASS", ",", "klass", ".", "getName", "(", ")", ")", ";", "return", "manifest", ";", "}" ]
Given a class generates a manifest file with main-class as class. @param klass to set as Main-Class in manifest file. @return An instance {@link java.util.jar.Manifest}
[ "Given", "a", "class", "generates", "a", "manifest", "file", "with", "main", "-", "class", "as", "class", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-flow/src/main/java/co/cask/tigon/flow/DeployClient.java#L91-L96
1,091
cdapio/tigon
tigon-flow/src/main/java/co/cask/tigon/flow/DeployClient.java
DeployClient.fromPosixArray
public static Map<String, String> fromPosixArray(Iterable<String> args) { Map<String, String> kvMap = Maps.newHashMap(); for (String arg : args) { kvMap.putAll(Splitter.on("--").omitEmptyStrings().trimResults().withKeyValueSeparator("=").split(arg)); } return kvMap; }
java
public static Map<String, String> fromPosixArray(Iterable<String> args) { Map<String, String> kvMap = Maps.newHashMap(); for (String arg : args) { kvMap.putAll(Splitter.on("--").omitEmptyStrings().trimResults().withKeyValueSeparator("=").split(arg)); } return kvMap; }
[ "public", "static", "Map", "<", "String", ",", "String", ">", "fromPosixArray", "(", "Iterable", "<", "String", ">", "args", ")", "{", "Map", "<", "String", ",", "String", ">", "kvMap", "=", "Maps", ".", "newHashMap", "(", ")", ";", "for", "(", "String", "arg", ":", "args", ")", "{", "kvMap", ".", "putAll", "(", "Splitter", ".", "on", "(", "\"--\"", ")", ".", "omitEmptyStrings", "(", ")", ".", "trimResults", "(", ")", ".", "withKeyValueSeparator", "(", "\"=\"", ")", ".", "split", "(", "arg", ")", ")", ";", "}", "return", "kvMap", ";", "}" ]
Converts a POSIX compliant program argument array to a String-to-String Map. @param args Array of Strings where each element is a POSIX compliant program argument (Ex: "--os=Linux" ). @return Map of argument Keys and Values (Ex: Key = "os" and Value = "Linux").
[ "Converts", "a", "POSIX", "compliant", "program", "argument", "array", "to", "a", "String", "-", "to", "-", "String", "Map", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-flow/src/main/java/co/cask/tigon/flow/DeployClient.java#L103-L109
1,092
cdapio/tigon
tigon-queue/src/main/java/co/cask/tigon/data/util/hbase/ConfigurationTable.java
ConfigurationTable.read
public CConfiguration read(Type type, String namespace) throws IOException { String tableName = getTableName(namespace); CConfiguration conf = null; HTable table = null; try { table = new HTable(hbaseConf, tableName); Get get = new Get(Bytes.toBytes(type.name())); get.addFamily(FAMILY); Result result = table.get(get); int propertyCnt = 0; if (result != null && !result.isEmpty()) { conf = CConfiguration.create(); conf.clear(); Map<byte[], byte[]> kvs = result.getFamilyMap(FAMILY); for (Map.Entry<byte[], byte[]> e : kvs.entrySet()) { conf.set(Bytes.toString(e.getKey()), Bytes.toString(e.getValue())); propertyCnt++; } } LOG.info("Read " + propertyCnt + " properties from configuration table = " + tableName + ", row = " + type.name()); } catch (TableNotFoundException e) { // it's expected that this may occur when tables are created before Tigon has started LOG.warn("Configuration table " + tableName + " does not yet exist."); } finally { if (table != null) { try { table.close(); } catch (IOException ioe) { LOG.error("Error closing HTable for " + tableName, ioe); } } } return conf; }
java
public CConfiguration read(Type type, String namespace) throws IOException { String tableName = getTableName(namespace); CConfiguration conf = null; HTable table = null; try { table = new HTable(hbaseConf, tableName); Get get = new Get(Bytes.toBytes(type.name())); get.addFamily(FAMILY); Result result = table.get(get); int propertyCnt = 0; if (result != null && !result.isEmpty()) { conf = CConfiguration.create(); conf.clear(); Map<byte[], byte[]> kvs = result.getFamilyMap(FAMILY); for (Map.Entry<byte[], byte[]> e : kvs.entrySet()) { conf.set(Bytes.toString(e.getKey()), Bytes.toString(e.getValue())); propertyCnt++; } } LOG.info("Read " + propertyCnt + " properties from configuration table = " + tableName + ", row = " + type.name()); } catch (TableNotFoundException e) { // it's expected that this may occur when tables are created before Tigon has started LOG.warn("Configuration table " + tableName + " does not yet exist."); } finally { if (table != null) { try { table.close(); } catch (IOException ioe) { LOG.error("Error closing HTable for " + tableName, ioe); } } } return conf; }
[ "public", "CConfiguration", "read", "(", "Type", "type", ",", "String", "namespace", ")", "throws", "IOException", "{", "String", "tableName", "=", "getTableName", "(", "namespace", ")", ";", "CConfiguration", "conf", "=", "null", ";", "HTable", "table", "=", "null", ";", "try", "{", "table", "=", "new", "HTable", "(", "hbaseConf", ",", "tableName", ")", ";", "Get", "get", "=", "new", "Get", "(", "Bytes", ".", "toBytes", "(", "type", ".", "name", "(", ")", ")", ")", ";", "get", ".", "addFamily", "(", "FAMILY", ")", ";", "Result", "result", "=", "table", ".", "get", "(", "get", ")", ";", "int", "propertyCnt", "=", "0", ";", "if", "(", "result", "!=", "null", "&&", "!", "result", ".", "isEmpty", "(", ")", ")", "{", "conf", "=", "CConfiguration", ".", "create", "(", ")", ";", "conf", ".", "clear", "(", ")", ";", "Map", "<", "byte", "[", "]", ",", "byte", "[", "]", ">", "kvs", "=", "result", ".", "getFamilyMap", "(", "FAMILY", ")", ";", "for", "(", "Map", ".", "Entry", "<", "byte", "[", "]", ",", "byte", "[", "]", ">", "e", ":", "kvs", ".", "entrySet", "(", ")", ")", "{", "conf", ".", "set", "(", "Bytes", ".", "toString", "(", "e", ".", "getKey", "(", ")", ")", ",", "Bytes", ".", "toString", "(", "e", ".", "getValue", "(", ")", ")", ")", ";", "propertyCnt", "++", ";", "}", "}", "LOG", ".", "info", "(", "\"Read \"", "+", "propertyCnt", "+", "\" properties from configuration table = \"", "+", "tableName", "+", "\", row = \"", "+", "type", ".", "name", "(", ")", ")", ";", "}", "catch", "(", "TableNotFoundException", "e", ")", "{", "// it's expected that this may occur when tables are created before Tigon has started", "LOG", ".", "warn", "(", "\"Configuration table \"", "+", "tableName", "+", "\" does not yet exist.\"", ")", ";", "}", "finally", "{", "if", "(", "table", "!=", "null", ")", "{", "try", "{", "table", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "ioe", ")", "{", "LOG", ".", "error", "(", "\"Error closing HTable for \"", "+", "tableName", ",", "ioe", ")", ";", "}", "}", "}", "return", "conf", ";", "}" ]
Reads the given configuration type from the HBase table, looking for the HBase table name under the given "namespace". @param type Type of configuration to read in @param namespace Namespace to use in constructing the table name (should be the same as root.namespace) @return The {@link CConfiguration} instance populated with the stored values, or {@code null} if no row was found for the given type. @throws java.io.IOException If an error occurs while attempting to read the table or the table does not exist.
[ "Reads", "the", "given", "configuration", "type", "from", "the", "HBase", "table", "looking", "for", "the", "HBase", "table", "name", "under", "the", "given", "namespace", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-queue/src/main/java/co/cask/tigon/data/util/hbase/ConfigurationTable.java#L127-L162
1,093
cdapio/tigon
tigon-yarn/src/main/java/co/cask/tigon/logging/AbstractLoggingContext.java
AbstractLoggingContext.setSystemTag
protected final void setSystemTag(String name, String value) { systemTags.put(name, new SystemTagImpl(name, value)); }
java
protected final void setSystemTag(String name, String value) { systemTags.put(name, new SystemTagImpl(name, value)); }
[ "protected", "final", "void", "setSystemTag", "(", "String", "name", ",", "String", "value", ")", "{", "systemTags", ".", "put", "(", "name", ",", "new", "SystemTagImpl", "(", "name", ",", "value", ")", ")", ";", "}" ]
Sets system tag. @param name tag name @param value tag value
[ "Sets", "system", "tag", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-yarn/src/main/java/co/cask/tigon/logging/AbstractLoggingContext.java#L39-L41
1,094
cdapio/tigon
tigon-common/src/main/java/co/cask/tigon/utils/Networks.java
Networks.getRandomPort
public static int getRandomPort() { try { ServerSocket socket = new ServerSocket(0); try { return socket.getLocalPort(); } finally { socket.close(); } } catch (IOException e) { return -1; } }
java
public static int getRandomPort() { try { ServerSocket socket = new ServerSocket(0); try { return socket.getLocalPort(); } finally { socket.close(); } } catch (IOException e) { return -1; } }
[ "public", "static", "int", "getRandomPort", "(", ")", "{", "try", "{", "ServerSocket", "socket", "=", "new", "ServerSocket", "(", "0", ")", ";", "try", "{", "return", "socket", ".", "getLocalPort", "(", ")", ";", "}", "finally", "{", "socket", ".", "close", "(", ")", ";", "}", "}", "catch", "(", "IOException", "e", ")", "{", "return", "-", "1", ";", "}", "}" ]
Find a random free port in localhost for binding. @return A port number or -1 for failure.
[ "Find", "a", "random", "free", "port", "in", "localhost", "for", "binding", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-common/src/main/java/co/cask/tigon/utils/Networks.java#L32-L43
1,095
cdapio/tigon
tigon-queue/src/main/java/co/cask/tigon/data/transaction/queue/hbase/coprocessor/ConsumerConfigCache.java
ConsumerConfigCache.updateCache
public synchronized void updateCache() { Map<byte[], QueueConsumerConfig> newCache = Maps.newTreeMap(Bytes.BYTES_COMPARATOR); long now = System.currentTimeMillis(); HTable table = null; try { table = new HTable(hConf, configTableName); Scan scan = new Scan(); scan.addFamily(QueueEntryRow.COLUMN_FAMILY); ResultScanner scanner = table.getScanner(scan); int configCnt = 0; for (Result result : scanner) { if (!result.isEmpty()) { NavigableMap<byte[], byte[]> familyMap = result.getFamilyMap(QueueEntryRow.COLUMN_FAMILY); if (familyMap != null) { configCnt++; Map<ConsumerInstance, byte[]> consumerInstances = new HashMap<ConsumerInstance, byte[]>(); // Gather the startRow of all instances across all consumer groups. int numGroups = 0; Long groupId = null; for (Map.Entry<byte[], byte[]> entry : familyMap.entrySet()) { long gid = Bytes.toLong(entry.getKey()); int instanceId = Bytes.toInt(entry.getKey(), LONG_BYTES); consumerInstances.put(new ConsumerInstance(gid, instanceId), entry.getValue()); // Columns are sorted by groupId, hence if it change, then numGroups would get +1 if (groupId == null || groupId != gid) { numGroups++; groupId = gid; } } byte[] queueName = result.getRow(); newCache.put(queueName, new QueueConsumerConfig(consumerInstances, numGroups)); } } } long elapsed = System.currentTimeMillis() - now; this.configCache = newCache; this.lastUpdated = now; if (LOG.isDebugEnabled()) { LOG.debug("Updated consumer config cache with {} entries, took {} msec", configCnt, elapsed); } } catch (IOException ioe) { LOG.warn("Error updating queue consumer config cache: {}", ioe.getMessage()); } finally { if (table != null) { try { table.close(); } catch (IOException ioe) { LOG.error("Error closing table {}", Bytes.toString(configTableName), ioe); } } } }
java
public synchronized void updateCache() { Map<byte[], QueueConsumerConfig> newCache = Maps.newTreeMap(Bytes.BYTES_COMPARATOR); long now = System.currentTimeMillis(); HTable table = null; try { table = new HTable(hConf, configTableName); Scan scan = new Scan(); scan.addFamily(QueueEntryRow.COLUMN_FAMILY); ResultScanner scanner = table.getScanner(scan); int configCnt = 0; for (Result result : scanner) { if (!result.isEmpty()) { NavigableMap<byte[], byte[]> familyMap = result.getFamilyMap(QueueEntryRow.COLUMN_FAMILY); if (familyMap != null) { configCnt++; Map<ConsumerInstance, byte[]> consumerInstances = new HashMap<ConsumerInstance, byte[]>(); // Gather the startRow of all instances across all consumer groups. int numGroups = 0; Long groupId = null; for (Map.Entry<byte[], byte[]> entry : familyMap.entrySet()) { long gid = Bytes.toLong(entry.getKey()); int instanceId = Bytes.toInt(entry.getKey(), LONG_BYTES); consumerInstances.put(new ConsumerInstance(gid, instanceId), entry.getValue()); // Columns are sorted by groupId, hence if it change, then numGroups would get +1 if (groupId == null || groupId != gid) { numGroups++; groupId = gid; } } byte[] queueName = result.getRow(); newCache.put(queueName, new QueueConsumerConfig(consumerInstances, numGroups)); } } } long elapsed = System.currentTimeMillis() - now; this.configCache = newCache; this.lastUpdated = now; if (LOG.isDebugEnabled()) { LOG.debug("Updated consumer config cache with {} entries, took {} msec", configCnt, elapsed); } } catch (IOException ioe) { LOG.warn("Error updating queue consumer config cache: {}", ioe.getMessage()); } finally { if (table != null) { try { table.close(); } catch (IOException ioe) { LOG.error("Error closing table {}", Bytes.toString(configTableName), ioe); } } } }
[ "public", "synchronized", "void", "updateCache", "(", ")", "{", "Map", "<", "byte", "[", "]", ",", "QueueConsumerConfig", ">", "newCache", "=", "Maps", ".", "newTreeMap", "(", "Bytes", ".", "BYTES_COMPARATOR", ")", ";", "long", "now", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "HTable", "table", "=", "null", ";", "try", "{", "table", "=", "new", "HTable", "(", "hConf", ",", "configTableName", ")", ";", "Scan", "scan", "=", "new", "Scan", "(", ")", ";", "scan", ".", "addFamily", "(", "QueueEntryRow", ".", "COLUMN_FAMILY", ")", ";", "ResultScanner", "scanner", "=", "table", ".", "getScanner", "(", "scan", ")", ";", "int", "configCnt", "=", "0", ";", "for", "(", "Result", "result", ":", "scanner", ")", "{", "if", "(", "!", "result", ".", "isEmpty", "(", ")", ")", "{", "NavigableMap", "<", "byte", "[", "]", ",", "byte", "[", "]", ">", "familyMap", "=", "result", ".", "getFamilyMap", "(", "QueueEntryRow", ".", "COLUMN_FAMILY", ")", ";", "if", "(", "familyMap", "!=", "null", ")", "{", "configCnt", "++", ";", "Map", "<", "ConsumerInstance", ",", "byte", "[", "]", ">", "consumerInstances", "=", "new", "HashMap", "<", "ConsumerInstance", ",", "byte", "[", "]", ">", "(", ")", ";", "// Gather the startRow of all instances across all consumer groups.", "int", "numGroups", "=", "0", ";", "Long", "groupId", "=", "null", ";", "for", "(", "Map", ".", "Entry", "<", "byte", "[", "]", ",", "byte", "[", "]", ">", "entry", ":", "familyMap", ".", "entrySet", "(", ")", ")", "{", "long", "gid", "=", "Bytes", ".", "toLong", "(", "entry", ".", "getKey", "(", ")", ")", ";", "int", "instanceId", "=", "Bytes", ".", "toInt", "(", "entry", ".", "getKey", "(", ")", ",", "LONG_BYTES", ")", ";", "consumerInstances", ".", "put", "(", "new", "ConsumerInstance", "(", "gid", ",", "instanceId", ")", ",", "entry", ".", "getValue", "(", ")", ")", ";", "// Columns are sorted by groupId, hence if it change, then numGroups would get +1", "if", "(", "groupId", "==", "null", "||", "groupId", "!=", "gid", ")", "{", "numGroups", "++", ";", "groupId", "=", "gid", ";", "}", "}", "byte", "[", "]", "queueName", "=", "result", ".", "getRow", "(", ")", ";", "newCache", ".", "put", "(", "queueName", ",", "new", "QueueConsumerConfig", "(", "consumerInstances", ",", "numGroups", ")", ")", ";", "}", "}", "}", "long", "elapsed", "=", "System", ".", "currentTimeMillis", "(", ")", "-", "now", ";", "this", ".", "configCache", "=", "newCache", ";", "this", ".", "lastUpdated", "=", "now", ";", "if", "(", "LOG", ".", "isDebugEnabled", "(", ")", ")", "{", "LOG", ".", "debug", "(", "\"Updated consumer config cache with {} entries, took {} msec\"", ",", "configCnt", ",", "elapsed", ")", ";", "}", "}", "catch", "(", "IOException", "ioe", ")", "{", "LOG", ".", "warn", "(", "\"Error updating queue consumer config cache: {}\"", ",", "ioe", ".", "getMessage", "(", ")", ")", ";", "}", "finally", "{", "if", "(", "table", "!=", "null", ")", "{", "try", "{", "table", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "ioe", ")", "{", "LOG", ".", "error", "(", "\"Error closing table {}\"", ",", "Bytes", ".", "toString", "(", "configTableName", ")", ",", "ioe", ")", ";", "}", "}", "}", "}" ]
This forces an immediate update of the config cache. It should only be called from the refresh thread or from tests, to avoid having to add a sleep for the duration of the refresh interval. This method is synchronized to protect from race conditions if called directly from a test. Otherwise this is only called from the refresh thread, and there will not be concurrent invocations.
[ "This", "forces", "an", "immediate", "update", "of", "the", "config", "cache", ".", "It", "should", "only", "be", "called", "from", "the", "refresh", "thread", "or", "from", "tests", "to", "avoid", "having", "to", "add", "a", "sleep", "for", "the", "duration", "of", "the", "refresh", "interval", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-queue/src/main/java/co/cask/tigon/data/transaction/queue/hbase/coprocessor/ConsumerConfigCache.java#L112-L165
1,096
cdapio/tigon
tigon-yarn/src/main/java/co/cask/tigon/lang/PropertyFieldSetter.java
PropertyFieldSetter.setValue
@SuppressWarnings("unchecked") private void setValue(Object instance, Field field, String value) throws IllegalAccessException { if (!field.isAccessible()) { field.setAccessible(true); } Class<?> fieldType = field.getType(); // Currently only String, primitive (or boxed type) and Enum type are supported. if (String.class.equals(fieldType)) { field.set(instance, value); return; } if (fieldType.isEnum()) { field.set(instance, Enum.valueOf((Class<? extends Enum>) fieldType, value)); return; } if (fieldType.isPrimitive()) { fieldType = com.google.common.primitives.Primitives.wrap(fieldType); } try { // All box type has the valueOf(String) method. field.set(instance, fieldType.getMethod("valueOf", String.class).invoke(null, value)); } catch (NoSuchMethodException e) { // Should never happen, as boxed type always have the valueOf(String) method. throw Throwables.propagate(e); } catch (InvocationTargetException e) { // Also should never happen, as calling method on Java bootstrap classes should always succeed. throw Throwables.propagate(e); } }
java
@SuppressWarnings("unchecked") private void setValue(Object instance, Field field, String value) throws IllegalAccessException { if (!field.isAccessible()) { field.setAccessible(true); } Class<?> fieldType = field.getType(); // Currently only String, primitive (or boxed type) and Enum type are supported. if (String.class.equals(fieldType)) { field.set(instance, value); return; } if (fieldType.isEnum()) { field.set(instance, Enum.valueOf((Class<? extends Enum>) fieldType, value)); return; } if (fieldType.isPrimitive()) { fieldType = com.google.common.primitives.Primitives.wrap(fieldType); } try { // All box type has the valueOf(String) method. field.set(instance, fieldType.getMethod("valueOf", String.class).invoke(null, value)); } catch (NoSuchMethodException e) { // Should never happen, as boxed type always have the valueOf(String) method. throw Throwables.propagate(e); } catch (InvocationTargetException e) { // Also should never happen, as calling method on Java bootstrap classes should always succeed. throw Throwables.propagate(e); } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "private", "void", "setValue", "(", "Object", "instance", ",", "Field", "field", ",", "String", "value", ")", "throws", "IllegalAccessException", "{", "if", "(", "!", "field", ".", "isAccessible", "(", ")", ")", "{", "field", ".", "setAccessible", "(", "true", ")", ";", "}", "Class", "<", "?", ">", "fieldType", "=", "field", ".", "getType", "(", ")", ";", "// Currently only String, primitive (or boxed type) and Enum type are supported.", "if", "(", "String", ".", "class", ".", "equals", "(", "fieldType", ")", ")", "{", "field", ".", "set", "(", "instance", ",", "value", ")", ";", "return", ";", "}", "if", "(", "fieldType", ".", "isEnum", "(", ")", ")", "{", "field", ".", "set", "(", "instance", ",", "Enum", ".", "valueOf", "(", "(", "Class", "<", "?", "extends", "Enum", ">", ")", "fieldType", ",", "value", ")", ")", ";", "return", ";", "}", "if", "(", "fieldType", ".", "isPrimitive", "(", ")", ")", "{", "fieldType", "=", "com", ".", "google", ".", "common", ".", "primitives", ".", "Primitives", ".", "wrap", "(", "fieldType", ")", ";", "}", "try", "{", "// All box type has the valueOf(String) method.", "field", ".", "set", "(", "instance", ",", "fieldType", ".", "getMethod", "(", "\"valueOf\"", ",", "String", ".", "class", ")", ".", "invoke", "(", "null", ",", "value", ")", ")", ";", "}", "catch", "(", "NoSuchMethodException", "e", ")", "{", "// Should never happen, as boxed type always have the valueOf(String) method.", "throw", "Throwables", ".", "propagate", "(", "e", ")", ";", "}", "catch", "(", "InvocationTargetException", "e", ")", "{", "// Also should never happen, as calling method on Java bootstrap classes should always succeed.", "throw", "Throwables", ".", "propagate", "(", "e", ")", ";", "}", "}" ]
Sets the value of the field in the given instance by converting the value from String to the field type. Currently only allows primitive types, boxed types, String and Enum.
[ "Sets", "the", "value", "of", "the", "field", "in", "the", "given", "instance", "by", "converting", "the", "value", "from", "String", "to", "the", "field", "type", ".", "Currently", "only", "allows", "primitive", "types", "boxed", "types", "String", "and", "Enum", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-yarn/src/main/java/co/cask/tigon/lang/PropertyFieldSetter.java#L55-L87
1,097
cdapio/tigon
tigon-sql/src/main/java/co/cask/tigon/sql/manager/ProcessInitiator.java
ProcessInitiator.startUp
@Override protected void startUp() { try { startRTS(); } catch (Exception e) { throw new IllegalArgumentException("Cannot initiate RTS. Missing or bad arguments"); } try { startHFTA(); } catch (Exception e) { throw new IllegalArgumentException("Cannot initiate HFTA processes. Missing or bad arguments"); } try { startGSEXIT(); } catch (Exception e) { throw new IllegalArgumentException("Cannot initiate GSEXIT processes. Missing or bad arguments"); } }
java
@Override protected void startUp() { try { startRTS(); } catch (Exception e) { throw new IllegalArgumentException("Cannot initiate RTS. Missing or bad arguments"); } try { startHFTA(); } catch (Exception e) { throw new IllegalArgumentException("Cannot initiate HFTA processes. Missing or bad arguments"); } try { startGSEXIT(); } catch (Exception e) { throw new IllegalArgumentException("Cannot initiate GSEXIT processes. Missing or bad arguments"); } }
[ "@", "Override", "protected", "void", "startUp", "(", ")", "{", "try", "{", "startRTS", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Cannot initiate RTS. Missing or bad arguments\"", ")", ";", "}", "try", "{", "startHFTA", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Cannot initiate HFTA processes. Missing or bad arguments\"", ")", ";", "}", "try", "{", "startGSEXIT", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Cannot initiate GSEXIT processes. Missing or bad arguments\"", ")", ";", "}", "}" ]
Sequentially invokes the required Streaming Engine processes.
[ "Sequentially", "invokes", "the", "required", "Streaming", "Engine", "processes", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-sql/src/main/java/co/cask/tigon/sql/manager/ProcessInitiator.java#L58-L75
1,098
cdapio/tigon
tigon-sql/src/main/java/co/cask/tigon/sql/manager/ProcessInitiator.java
ProcessInitiator.startRTS
public void startRTS() throws IOException { List<HubDataSource> dataSources = hubDataStore.getHubDataSources(); List<String> com = Lists.newArrayList(); com.add(getHostPort(hubDataStore.getHubAddress())); com.add(hubDataStore.getInstanceName()); for (HubDataSource source : dataSources) { com.add(source.getName()); } ExternalProgramExecutor executorService = new ExternalProgramExecutor( "RTS", new File(binLocation, "rts"), com.toArray(new String[com.size()])); rtsExecutor.add(executorService); LOG.info("Starting RTS : {}", executorService); executorService.startAndWait(); }
java
public void startRTS() throws IOException { List<HubDataSource> dataSources = hubDataStore.getHubDataSources(); List<String> com = Lists.newArrayList(); com.add(getHostPort(hubDataStore.getHubAddress())); com.add(hubDataStore.getInstanceName()); for (HubDataSource source : dataSources) { com.add(source.getName()); } ExternalProgramExecutor executorService = new ExternalProgramExecutor( "RTS", new File(binLocation, "rts"), com.toArray(new String[com.size()])); rtsExecutor.add(executorService); LOG.info("Starting RTS : {}", executorService); executorService.startAndWait(); }
[ "public", "void", "startRTS", "(", ")", "throws", "IOException", "{", "List", "<", "HubDataSource", ">", "dataSources", "=", "hubDataStore", ".", "getHubDataSources", "(", ")", ";", "List", "<", "String", ">", "com", "=", "Lists", ".", "newArrayList", "(", ")", ";", "com", ".", "add", "(", "getHostPort", "(", "hubDataStore", ".", "getHubAddress", "(", ")", ")", ")", ";", "com", ".", "add", "(", "hubDataStore", ".", "getInstanceName", "(", ")", ")", ";", "for", "(", "HubDataSource", "source", ":", "dataSources", ")", "{", "com", ".", "add", "(", "source", ".", "getName", "(", ")", ")", ";", "}", "ExternalProgramExecutor", "executorService", "=", "new", "ExternalProgramExecutor", "(", "\"RTS\"", ",", "new", "File", "(", "binLocation", ",", "\"rts\"", ")", ",", "com", ".", "toArray", "(", "new", "String", "[", "com", ".", "size", "(", ")", "]", ")", ")", ";", "rtsExecutor", ".", "add", "(", "executorService", ")", ";", "LOG", ".", "info", "(", "\"Starting RTS : {}\"", ",", "executorService", ")", ";", "executorService", ".", "startAndWait", "(", ")", ";", "}" ]
Starts RTS process. @throws IOException
[ "Starts", "RTS", "process", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-sql/src/main/java/co/cask/tigon/sql/manager/ProcessInitiator.java#L95-L108
1,099
cdapio/tigon
tigon-sql/src/main/java/co/cask/tigon/sql/manager/ProcessInitiator.java
ProcessInitiator.startHFTA
public void startHFTA() throws IOException { int hftaCount = MetaInformationParser.getHFTACount(new File(this.hubDataStore.getBinaryLocation().toURI())); for (int i = 0; i < hftaCount; i++) { List<String> com = Lists.newArrayList(); com.add(getHostPort(hubDataStore.getHubAddress())); com.add(hubDataStore.getInstanceName()); ExternalProgramExecutor executorService = new ExternalProgramExecutor( "HFTA-" + i, new File(binLocation, "hfta_" + i), com.toArray(new String[com.size()])); hftaExecutor.add(executorService); LOG.info("Starting HFTA : {}", executorService); executorService.startAndWait(); } }
java
public void startHFTA() throws IOException { int hftaCount = MetaInformationParser.getHFTACount(new File(this.hubDataStore.getBinaryLocation().toURI())); for (int i = 0; i < hftaCount; i++) { List<String> com = Lists.newArrayList(); com.add(getHostPort(hubDataStore.getHubAddress())); com.add(hubDataStore.getInstanceName()); ExternalProgramExecutor executorService = new ExternalProgramExecutor( "HFTA-" + i, new File(binLocation, "hfta_" + i), com.toArray(new String[com.size()])); hftaExecutor.add(executorService); LOG.info("Starting HFTA : {}", executorService); executorService.startAndWait(); } }
[ "public", "void", "startHFTA", "(", ")", "throws", "IOException", "{", "int", "hftaCount", "=", "MetaInformationParser", ".", "getHFTACount", "(", "new", "File", "(", "this", ".", "hubDataStore", ".", "getBinaryLocation", "(", ")", ".", "toURI", "(", ")", ")", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "hftaCount", ";", "i", "++", ")", "{", "List", "<", "String", ">", "com", "=", "Lists", ".", "newArrayList", "(", ")", ";", "com", ".", "add", "(", "getHostPort", "(", "hubDataStore", ".", "getHubAddress", "(", ")", ")", ")", ";", "com", ".", "add", "(", "hubDataStore", ".", "getInstanceName", "(", ")", ")", ";", "ExternalProgramExecutor", "executorService", "=", "new", "ExternalProgramExecutor", "(", "\"HFTA-\"", "+", "i", ",", "new", "File", "(", "binLocation", ",", "\"hfta_\"", "+", "i", ")", ",", "com", ".", "toArray", "(", "new", "String", "[", "com", ".", "size", "(", ")", "]", ")", ")", ";", "hftaExecutor", ".", "add", "(", "executorService", ")", ";", "LOG", ".", "info", "(", "\"Starting HFTA : {}\"", ",", "executorService", ")", ";", "executorService", ".", "startAndWait", "(", ")", ";", "}", "}" ]
Starts HFTA processes. @throws IOException
[ "Starts", "HFTA", "processes", "." ]
5be6dffd7c79519d1211bb08f75be7dcfbbad392
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-sql/src/main/java/co/cask/tigon/sql/manager/ProcessInitiator.java#L114-L126