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
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
27,800
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/common/pathelement/TransposePathElement.java
TransposePathElement.innerParse
private static TransposePathElement innerParse( String originalKey, String meat ) { char first = meat.charAt( 0 ); if ( Character.isDigit( first ) ) { // loop until we find a comma or end of string StringBuilder sb = new StringBuilder().append( first ); for ( int index = 1; index < meat.length(); index++ ) { char c = meat.charAt( index ); // when we find a / the first comma, stop looking for integers, and just assume the rest is a String path if( ',' == c ) { int upLevel; try { upLevel = Integer.valueOf( sb.toString() ); } catch ( NumberFormatException nfe ) { // I don't know how this exception would get thrown, as all the chars were checked by isDigit, but oh well throw new SpecException( "@ path element with non/mixed numeric key is not valid, key=" + originalKey ); } return new TransposePathElement( originalKey, upLevel, meat.substring( index + 1 ) ); } else if ( Character.isDigit( c ) ) { sb.append( c ); } else { throw new SpecException( "@ path element with non/mixed numeric key is not valid, key=" + originalKey ); } } // if we got out of the for loop, then the whole thing was a number. return new TransposePathElement( originalKey, Integer.valueOf( sb.toString() ), null ); } else { return new TransposePathElement( originalKey, 0, meat ); } }
java
private static TransposePathElement innerParse( String originalKey, String meat ) { char first = meat.charAt( 0 ); if ( Character.isDigit( first ) ) { // loop until we find a comma or end of string StringBuilder sb = new StringBuilder().append( first ); for ( int index = 1; index < meat.length(); index++ ) { char c = meat.charAt( index ); // when we find a / the first comma, stop looking for integers, and just assume the rest is a String path if( ',' == c ) { int upLevel; try { upLevel = Integer.valueOf( sb.toString() ); } catch ( NumberFormatException nfe ) { // I don't know how this exception would get thrown, as all the chars were checked by isDigit, but oh well throw new SpecException( "@ path element with non/mixed numeric key is not valid, key=" + originalKey ); } return new TransposePathElement( originalKey, upLevel, meat.substring( index + 1 ) ); } else if ( Character.isDigit( c ) ) { sb.append( c ); } else { throw new SpecException( "@ path element with non/mixed numeric key is not valid, key=" + originalKey ); } } // if we got out of the for loop, then the whole thing was a number. return new TransposePathElement( originalKey, Integer.valueOf( sb.toString() ), null ); } else { return new TransposePathElement( originalKey, 0, meat ); } }
[ "private", "static", "TransposePathElement", "innerParse", "(", "String", "originalKey", ",", "String", "meat", ")", "{", "char", "first", "=", "meat", ".", "charAt", "(", "0", ")", ";", "if", "(", "Character", ".", "isDigit", "(", "first", ")", ")", "{", "// loop until we find a comma or end of string", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ".", "append", "(", "first", ")", ";", "for", "(", "int", "index", "=", "1", ";", "index", "<", "meat", ".", "length", "(", ")", ";", "index", "++", ")", "{", "char", "c", "=", "meat", ".", "charAt", "(", "index", ")", ";", "// when we find a / the first comma, stop looking for integers, and just assume the rest is a String path", "if", "(", "'", "'", "==", "c", ")", "{", "int", "upLevel", ";", "try", "{", "upLevel", "=", "Integer", ".", "valueOf", "(", "sb", ".", "toString", "(", ")", ")", ";", "}", "catch", "(", "NumberFormatException", "nfe", ")", "{", "// I don't know how this exception would get thrown, as all the chars were checked by isDigit, but oh well", "throw", "new", "SpecException", "(", "\"@ path element with non/mixed numeric key is not valid, key=\"", "+", "originalKey", ")", ";", "}", "return", "new", "TransposePathElement", "(", "originalKey", ",", "upLevel", ",", "meat", ".", "substring", "(", "index", "+", "1", ")", ")", ";", "}", "else", "if", "(", "Character", ".", "isDigit", "(", "c", ")", ")", "{", "sb", ".", "append", "(", "c", ")", ";", "}", "else", "{", "throw", "new", "SpecException", "(", "\"@ path element with non/mixed numeric key is not valid, key=\"", "+", "originalKey", ")", ";", "}", "}", "// if we got out of the for loop, then the whole thing was a number.", "return", "new", "TransposePathElement", "(", "originalKey", ",", "Integer", ".", "valueOf", "(", "sb", ".", "toString", "(", ")", ")", ",", "null", ")", ";", "}", "else", "{", "return", "new", "TransposePathElement", "(", "originalKey", ",", "0", ",", "meat", ")", ";", "}", "}" ]
Parse the core of the TransposePathElement key, once basic errors have been checked and syntax has been handled. @param originalKey The original text for reference. @param meat The string to actually parse into a TransposePathElement @return TransposePathElement
[ "Parse", "the", "core", "of", "the", "TransposePathElement", "key", "once", "basic", "errors", "have", "been", "checked", "and", "syntax", "has", "been", "handled", "." ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/common/pathelement/TransposePathElement.java#L120-L157
27,801
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/common/pathelement/TransposePathElement.java
TransposePathElement.objectEvaluate
public Optional<Object> objectEvaluate( WalkedPath walkedPath ) { // Grap the data we need from however far up the tree we are supposed to go PathStep pathStep = walkedPath.elementFromEnd( upLevel ); if ( pathStep == null ) { return Optional.empty(); } Object treeRef = pathStep.getTreeRef(); // Now walk down from that level using the subPathReader if ( subPathReader == null ) { return Optional.of( treeRef ); } else { return subPathReader.read( treeRef, walkedPath ); } }
java
public Optional<Object> objectEvaluate( WalkedPath walkedPath ) { // Grap the data we need from however far up the tree we are supposed to go PathStep pathStep = walkedPath.elementFromEnd( upLevel ); if ( pathStep == null ) { return Optional.empty(); } Object treeRef = pathStep.getTreeRef(); // Now walk down from that level using the subPathReader if ( subPathReader == null ) { return Optional.of( treeRef ); } else { return subPathReader.read( treeRef, walkedPath ); } }
[ "public", "Optional", "<", "Object", ">", "objectEvaluate", "(", "WalkedPath", "walkedPath", ")", "{", "// Grap the data we need from however far up the tree we are supposed to go", "PathStep", "pathStep", "=", "walkedPath", ".", "elementFromEnd", "(", "upLevel", ")", ";", "if", "(", "pathStep", "==", "null", ")", "{", "return", "Optional", ".", "empty", "(", ")", ";", "}", "Object", "treeRef", "=", "pathStep", ".", "getTreeRef", "(", ")", ";", "// Now walk down from that level using the subPathReader", "if", "(", "subPathReader", "==", "null", ")", "{", "return", "Optional", ".", "of", "(", "treeRef", ")", ";", "}", "else", "{", "return", "subPathReader", ".", "read", "(", "treeRef", ",", "walkedPath", ")", ";", "}", "}" ]
This method is used when the TransposePathElement is used on the LFH as data. Aka, normal "evaluate" returns either a Number or a String. @param walkedPath WalkedPath to evaluate against @return The data specified by this TransposePathElement.
[ "This", "method", "is", "used", "when", "the", "TransposePathElement", "is", "used", "on", "the", "LFH", "as", "data", "." ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/common/pathelement/TransposePathElement.java#L187-L204
27,802
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/shiftr/spec/ShiftrLeafSpec.java
ShiftrLeafSpec.apply
@Override public boolean apply( String inputKey, Optional<Object> inputOptional, WalkedPath walkedPath, Map<String,Object> output, Map<String, Object> context){ Object input = inputOptional.get(); MatchedElement thisLevel = pathElement.match( inputKey, walkedPath ); if ( thisLevel == null ) { return false; } Object data; boolean realChild = false; // by default don't block further Shiftr matches if ( this.pathElement instanceof DollarPathElement || this.pathElement instanceof HashPathElement ) { // The data is already encoded in the thisLevel object created by the pathElement.match called above data = thisLevel.getCanonicalForm(); } else if ( this.pathElement instanceof AtPathElement ) { // The data is our parent's data data = input; } else if ( this.pathElement instanceof TransposePathElement ) { // We try to walk down the tree to find the value / data we want TransposePathElement tpe = (TransposePathElement) this.pathElement; // Note the data found may not be a String, thus we have to call the special objectEvaluate Optional<Object> evaledData = tpe.objectEvaluate( walkedPath ); if ( evaledData.isPresent() ) { data = evaledData.get(); } else { // if we could not find the value we want looking down the tree, bail return false; } } else { // the data is the input data = input; // tell our parent that we matched and no further processing for this inputKey should be done realChild = true; } // Add our the LiteralPathElement for this level, so that write path References can use it as &(0,0) walkedPath.add( input, thisLevel ); // Write out the data for ( PathEvaluatingTraversal outputPath : shiftrWriters ) { outputPath.write( data, output, walkedPath ); } walkedPath.removeLast(); if ( realChild ) { // we were a "real" child, so increment the matchCount of our parent walkedPath.lastElement().getMatchedElement().incrementHashCount(); } return realChild; }
java
@Override public boolean apply( String inputKey, Optional<Object> inputOptional, WalkedPath walkedPath, Map<String,Object> output, Map<String, Object> context){ Object input = inputOptional.get(); MatchedElement thisLevel = pathElement.match( inputKey, walkedPath ); if ( thisLevel == null ) { return false; } Object data; boolean realChild = false; // by default don't block further Shiftr matches if ( this.pathElement instanceof DollarPathElement || this.pathElement instanceof HashPathElement ) { // The data is already encoded in the thisLevel object created by the pathElement.match called above data = thisLevel.getCanonicalForm(); } else if ( this.pathElement instanceof AtPathElement ) { // The data is our parent's data data = input; } else if ( this.pathElement instanceof TransposePathElement ) { // We try to walk down the tree to find the value / data we want TransposePathElement tpe = (TransposePathElement) this.pathElement; // Note the data found may not be a String, thus we have to call the special objectEvaluate Optional<Object> evaledData = tpe.objectEvaluate( walkedPath ); if ( evaledData.isPresent() ) { data = evaledData.get(); } else { // if we could not find the value we want looking down the tree, bail return false; } } else { // the data is the input data = input; // tell our parent that we matched and no further processing for this inputKey should be done realChild = true; } // Add our the LiteralPathElement for this level, so that write path References can use it as &(0,0) walkedPath.add( input, thisLevel ); // Write out the data for ( PathEvaluatingTraversal outputPath : shiftrWriters ) { outputPath.write( data, output, walkedPath ); } walkedPath.removeLast(); if ( realChild ) { // we were a "real" child, so increment the matchCount of our parent walkedPath.lastElement().getMatchedElement().incrementHashCount(); } return realChild; }
[ "@", "Override", "public", "boolean", "apply", "(", "String", "inputKey", ",", "Optional", "<", "Object", ">", "inputOptional", ",", "WalkedPath", "walkedPath", ",", "Map", "<", "String", ",", "Object", ">", "output", ",", "Map", "<", "String", ",", "Object", ">", "context", ")", "{", "Object", "input", "=", "inputOptional", ".", "get", "(", ")", ";", "MatchedElement", "thisLevel", "=", "pathElement", ".", "match", "(", "inputKey", ",", "walkedPath", ")", ";", "if", "(", "thisLevel", "==", "null", ")", "{", "return", "false", ";", "}", "Object", "data", ";", "boolean", "realChild", "=", "false", ";", "// by default don't block further Shiftr matches", "if", "(", "this", ".", "pathElement", "instanceof", "DollarPathElement", "||", "this", ".", "pathElement", "instanceof", "HashPathElement", ")", "{", "// The data is already encoded in the thisLevel object created by the pathElement.match called above", "data", "=", "thisLevel", ".", "getCanonicalForm", "(", ")", ";", "}", "else", "if", "(", "this", ".", "pathElement", "instanceof", "AtPathElement", ")", "{", "// The data is our parent's data", "data", "=", "input", ";", "}", "else", "if", "(", "this", ".", "pathElement", "instanceof", "TransposePathElement", ")", "{", "// We try to walk down the tree to find the value / data we want", "TransposePathElement", "tpe", "=", "(", "TransposePathElement", ")", "this", ".", "pathElement", ";", "// Note the data found may not be a String, thus we have to call the special objectEvaluate", "Optional", "<", "Object", ">", "evaledData", "=", "tpe", ".", "objectEvaluate", "(", "walkedPath", ")", ";", "if", "(", "evaledData", ".", "isPresent", "(", ")", ")", "{", "data", "=", "evaledData", ".", "get", "(", ")", ";", "}", "else", "{", "// if we could not find the value we want looking down the tree, bail", "return", "false", ";", "}", "}", "else", "{", "// the data is the input", "data", "=", "input", ";", "// tell our parent that we matched and no further processing for this inputKey should be done", "realChild", "=", "true", ";", "}", "// Add our the LiteralPathElement for this level, so that write path References can use it as &(0,0)", "walkedPath", ".", "add", "(", "input", ",", "thisLevel", ")", ";", "// Write out the data", "for", "(", "PathEvaluatingTraversal", "outputPath", ":", "shiftrWriters", ")", "{", "outputPath", ".", "write", "(", "data", ",", "output", ",", "walkedPath", ")", ";", "}", "walkedPath", ".", "removeLast", "(", ")", ";", "if", "(", "realChild", ")", "{", "// we were a \"real\" child, so increment the matchCount of our parent", "walkedPath", ".", "lastElement", "(", ")", ".", "getMatchedElement", "(", ")", ".", "incrementHashCount", "(", ")", ";", "}", "return", "realChild", ";", "}" ]
If this Spec matches the inputkey, then do the work of outputting data and return true. @return true if this this spec "handles" the inputkey such that no sibling specs need to see it
[ "If", "this", "Spec", "matches", "the", "inputkey", "then", "do", "the", "work", "of", "outputting", "data", "and", "return", "true", "." ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/shiftr/spec/ShiftrLeafSpec.java#L90-L150
27,803
bazaarvoice/jolt
cli/src/main/java/com/bazaarvoice/jolt/JoltCli.java
JoltCli.runJolt
protected static boolean runJolt( String[] args ) { ArgumentParser parser = ArgumentParsers.newArgumentParser( "jolt" ); Subparsers subparsers = parser.addSubparsers().help( "transform: given a Jolt transform spec, runs the specified transforms on the input data.\n" + "diffy: diff two JSON documents.\n" + "sort: sort a JSON document alphabetically for human readability." ); for ( Map.Entry<String, JoltCliProcessor> entry : JOLT_CLI_PROCESSOR_MAP.entrySet() ) { entry.getValue().intializeSubCommand( subparsers ); } Namespace ns; try { ns = parser.parseArgs( args ); } catch ( ArgumentParserException e ) { parser.handleError( e ); return false; } JoltCliProcessor joltToolProcessor = JOLT_CLI_PROCESSOR_MAP.get( args[0] ); if ( joltToolProcessor != null ) { return joltToolProcessor.process( ns ); } else { // TODO: error message, print usage. although I don't think it will ever get to this point. return false; } }
java
protected static boolean runJolt( String[] args ) { ArgumentParser parser = ArgumentParsers.newArgumentParser( "jolt" ); Subparsers subparsers = parser.addSubparsers().help( "transform: given a Jolt transform spec, runs the specified transforms on the input data.\n" + "diffy: diff two JSON documents.\n" + "sort: sort a JSON document alphabetically for human readability." ); for ( Map.Entry<String, JoltCliProcessor> entry : JOLT_CLI_PROCESSOR_MAP.entrySet() ) { entry.getValue().intializeSubCommand( subparsers ); } Namespace ns; try { ns = parser.parseArgs( args ); } catch ( ArgumentParserException e ) { parser.handleError( e ); return false; } JoltCliProcessor joltToolProcessor = JOLT_CLI_PROCESSOR_MAP.get( args[0] ); if ( joltToolProcessor != null ) { return joltToolProcessor.process( ns ); } else { // TODO: error message, print usage. although I don't think it will ever get to this point. return false; } }
[ "protected", "static", "boolean", "runJolt", "(", "String", "[", "]", "args", ")", "{", "ArgumentParser", "parser", "=", "ArgumentParsers", ".", "newArgumentParser", "(", "\"jolt\"", ")", ";", "Subparsers", "subparsers", "=", "parser", ".", "addSubparsers", "(", ")", ".", "help", "(", "\"transform: given a Jolt transform spec, runs the specified transforms on the input data.\\n\"", "+", "\"diffy: diff two JSON documents.\\n\"", "+", "\"sort: sort a JSON document alphabetically for human readability.\"", ")", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "JoltCliProcessor", ">", "entry", ":", "JOLT_CLI_PROCESSOR_MAP", ".", "entrySet", "(", ")", ")", "{", "entry", ".", "getValue", "(", ")", ".", "intializeSubCommand", "(", "subparsers", ")", ";", "}", "Namespace", "ns", ";", "try", "{", "ns", "=", "parser", ".", "parseArgs", "(", "args", ")", ";", "}", "catch", "(", "ArgumentParserException", "e", ")", "{", "parser", ".", "handleError", "(", "e", ")", ";", "return", "false", ";", "}", "JoltCliProcessor", "joltToolProcessor", "=", "JOLT_CLI_PROCESSOR_MAP", ".", "get", "(", "args", "[", "0", "]", ")", ";", "if", "(", "joltToolProcessor", "!=", "null", ")", "{", "return", "joltToolProcessor", ".", "process", "(", "ns", ")", ";", "}", "else", "{", "// TODO: error message, print usage. although I don't think it will ever get to this point.", "return", "false", ";", "}", "}" ]
The logic for running DiffyTool has been captured in a helper method that returns a boolean to facilitate unit testing. Since System.exit terminates the JVM it would not be practical to test the main method. @param args the arguments from the command line input @return true if two inputs were read with no differences, false if differences were found or an error was encountered
[ "The", "logic", "for", "running", "DiffyTool", "has", "been", "captured", "in", "a", "helper", "method", "that", "returns", "a", "boolean", "to", "facilitate", "unit", "testing", ".", "Since", "System", ".", "exit", "terminates", "the", "JVM", "it", "would", "not", "be", "practical", "to", "test", "the", "main", "method", "." ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/cli/src/main/java/com/bazaarvoice/jolt/JoltCli.java#L52-L77
27,804
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/common/PathEvaluatingTraversal.java
PathEvaluatingTraversal.write
public void write( Object data, Map<String, Object> output, WalkedPath walkedPath ) { List<String> evaledPaths = evaluate( walkedPath ); if ( evaledPaths != null ) { traversr.set( output, evaledPaths, data ); } }
java
public void write( Object data, Map<String, Object> output, WalkedPath walkedPath ) { List<String> evaledPaths = evaluate( walkedPath ); if ( evaledPaths != null ) { traversr.set( output, evaledPaths, data ); } }
[ "public", "void", "write", "(", "Object", "data", ",", "Map", "<", "String", ",", "Object", ">", "output", ",", "WalkedPath", "walkedPath", ")", "{", "List", "<", "String", ">", "evaledPaths", "=", "evaluate", "(", "walkedPath", ")", ";", "if", "(", "evaledPaths", "!=", "null", ")", "{", "traversr", ".", "set", "(", "output", ",", "evaledPaths", ",", "data", ")", ";", "}", "}" ]
Use the supplied WalkedPath, in the evaluation of each of our PathElements to build a concrete output path. Then use that output path to write the given data to the output. @param data data to write @param output data structure we are going to write the data to @param walkedPath reference used to lookup reference values like "&1(2)"
[ "Use", "the", "supplied", "WalkedPath", "in", "the", "evaluation", "of", "each", "of", "our", "PathElements", "to", "build", "a", "concrete", "output", "path", ".", "Then", "use", "that", "output", "path", "to", "write", "the", "given", "data", "to", "the", "output", "." ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/common/PathEvaluatingTraversal.java#L98-L103
27,805
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/common/PathEvaluatingTraversal.java
PathEvaluatingTraversal.getCanonicalForm
public String getCanonicalForm() { StringBuilder buf = new StringBuilder(); for ( PathElement pe : elements ) { buf.append( "." ).append( pe.getCanonicalForm() ); } return buf.substring( 1 ); // strip the leading "." }
java
public String getCanonicalForm() { StringBuilder buf = new StringBuilder(); for ( PathElement pe : elements ) { buf.append( "." ).append( pe.getCanonicalForm() ); } return buf.substring( 1 ); // strip the leading "." }
[ "public", "String", "getCanonicalForm", "(", ")", "{", "StringBuilder", "buf", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "PathElement", "pe", ":", "elements", ")", "{", "buf", ".", "append", "(", "\".\"", ")", ".", "append", "(", "pe", ".", "getCanonicalForm", "(", ")", ")", ";", "}", "return", "buf", ".", "substring", "(", "1", ")", ";", "// strip the leading \".\"", "}" ]
Testing method.
[ "Testing", "method", "." ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/common/PathEvaluatingTraversal.java#L151-L159
27,806
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/utils/JoltUtils.java
JoltUtils.navigateSafe
@Deprecated public static <T> T navigateSafe(final T defaultValue, final Object source, final Object... paths) { return navigateOrDefault( defaultValue, source, paths ); }
java
@Deprecated public static <T> T navigateSafe(final T defaultValue, final Object source, final Object... paths) { return navigateOrDefault( defaultValue, source, paths ); }
[ "@", "Deprecated", "public", "static", "<", "T", ">", "T", "navigateSafe", "(", "final", "T", "defaultValue", ",", "final", "Object", "source", ",", "final", "Object", "...", "paths", ")", "{", "return", "navigateOrDefault", "(", "defaultValue", ",", "source", ",", "paths", ")", ";", "}" ]
Use navigateOrDefault which is a much better name.
[ "Use", "navigateOrDefault", "which", "is", "a", "much", "better", "name", "." ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/utils/JoltUtils.java#L236-L239
27,807
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/utils/JoltUtils.java
JoltUtils.isVacantJson
public static boolean isVacantJson(final Object obj) { Collection values = null; if(obj instanceof Collection) { if(((Collection) obj).size() == 0) { return true; } values = (Collection) obj; } if(obj instanceof Map) { if(((Map) obj).size() == 0) { return true; } values = ((Map) obj).values(); } int processedEmpty = 0; if(values != null) { for (Object value: values) { if(!isVacantJson(value)) { return false; } processedEmpty++; } if(processedEmpty == values.size()) { return true; } } return false; }
java
public static boolean isVacantJson(final Object obj) { Collection values = null; if(obj instanceof Collection) { if(((Collection) obj).size() == 0) { return true; } values = (Collection) obj; } if(obj instanceof Map) { if(((Map) obj).size() == 0) { return true; } values = ((Map) obj).values(); } int processedEmpty = 0; if(values != null) { for (Object value: values) { if(!isVacantJson(value)) { return false; } processedEmpty++; } if(processedEmpty == values.size()) { return true; } } return false; }
[ "public", "static", "boolean", "isVacantJson", "(", "final", "Object", "obj", ")", "{", "Collection", "values", "=", "null", ";", "if", "(", "obj", "instanceof", "Collection", ")", "{", "if", "(", "(", "(", "Collection", ")", "obj", ")", ".", "size", "(", ")", "==", "0", ")", "{", "return", "true", ";", "}", "values", "=", "(", "Collection", ")", "obj", ";", "}", "if", "(", "obj", "instanceof", "Map", ")", "{", "if", "(", "(", "(", "Map", ")", "obj", ")", ".", "size", "(", ")", "==", "0", ")", "{", "return", "true", ";", "}", "values", "=", "(", "(", "Map", ")", "obj", ")", ".", "values", "(", ")", ";", "}", "int", "processedEmpty", "=", "0", ";", "if", "(", "values", "!=", "null", ")", "{", "for", "(", "Object", "value", ":", "values", ")", "{", "if", "(", "!", "isVacantJson", "(", "value", ")", ")", "{", "return", "false", ";", "}", "processedEmpty", "++", ";", "}", "if", "(", "processedEmpty", "==", "values", ".", "size", "(", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Vacant implies there are empty placeholders, i.e. a vacant hotel Given a json document, checks if it has any "leaf" values, can handle deep nesting of lists and maps i.e. { "a": [ "x": {}, "y": [] ], "b": { "p": [], "q": {} }} ==> is empty @param obj source @return true if its an empty json, can have deep nesting, false otherwise
[ "Vacant", "implies", "there", "are", "empty", "placeholders", "i", ".", "e", ".", "a", "vacant", "hotel", "Given", "a", "json", "document", "checks", "if", "it", "has", "any", "leaf", "values", "can", "handle", "deep", "nesting", "of", "lists", "and", "maps" ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/utils/JoltUtils.java#L252-L279
27,808
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/utils/JoltUtils.java
JoltUtils.listKeyChains
public static List<Object[]> listKeyChains(final Object source) { List<Object[]> keyChainList = new LinkedList<>(); if(source instanceof Map) { Map sourceMap = (Map) source; for (Object key: sourceMap.keySet()) { keyChainList.addAll(listKeyChains(key, sourceMap.get(key))); } } else if(source instanceof List) { List sourceList = (List) source; for(int i=0; i<sourceList.size(); i++) { keyChainList.addAll(listKeyChains(i, sourceList.get(i))); } } else { return Collections.emptyList(); } return keyChainList; }
java
public static List<Object[]> listKeyChains(final Object source) { List<Object[]> keyChainList = new LinkedList<>(); if(source instanceof Map) { Map sourceMap = (Map) source; for (Object key: sourceMap.keySet()) { keyChainList.addAll(listKeyChains(key, sourceMap.get(key))); } } else if(source instanceof List) { List sourceList = (List) source; for(int i=0; i<sourceList.size(); i++) { keyChainList.addAll(listKeyChains(i, sourceList.get(i))); } } else { return Collections.emptyList(); } return keyChainList; }
[ "public", "static", "List", "<", "Object", "[", "]", ">", "listKeyChains", "(", "final", "Object", "source", ")", "{", "List", "<", "Object", "[", "]", ">", "keyChainList", "=", "new", "LinkedList", "<>", "(", ")", ";", "if", "(", "source", "instanceof", "Map", ")", "{", "Map", "sourceMap", "=", "(", "Map", ")", "source", ";", "for", "(", "Object", "key", ":", "sourceMap", ".", "keySet", "(", ")", ")", "{", "keyChainList", ".", "addAll", "(", "listKeyChains", "(", "key", ",", "sourceMap", ".", "get", "(", "key", ")", ")", ")", ";", "}", "}", "else", "if", "(", "source", "instanceof", "List", ")", "{", "List", "sourceList", "=", "(", "List", ")", "source", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "sourceList", ".", "size", "(", ")", ";", "i", "++", ")", "{", "keyChainList", ".", "addAll", "(", "listKeyChains", "(", "i", ",", "sourceList", ".", "get", "(", "i", ")", ")", ")", ";", "}", "}", "else", "{", "return", "Collections", ".", "emptyList", "(", ")", ";", "}", "return", "keyChainList", ";", "}" ]
Given a json document, finds out absolute path to every leaf element i.e. { "a": [ "x": { "y": "alpha" }], "b": { "p": [ "beta", "gamma" ], "q": {} }} will yield 1) "a",0,"x","y" -> to "alpha" 2) "b","p", 0 -> to "beta" 3) "b", "p", 1 -> to "gamma" 4) "b","q" -> to {} (empty Map) @param source json @return list of Object[] representing path to every leaf element
[ "Given", "a", "json", "document", "finds", "out", "absolute", "path", "to", "every", "leaf", "element" ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/utils/JoltUtils.java#L314-L335
27,809
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/utils/JoltUtils.java
JoltUtils.toSimpleTraversrPath
public static String toSimpleTraversrPath(Object[] paths) { StringBuilder pathBuilder = new StringBuilder(); for(int i=0; i<paths.length; i++) { Object path = paths[i]; if(path instanceof Integer) { pathBuilder.append("[").append(((Integer) path).intValue()).append("]"); } else if(path instanceof String) { pathBuilder.append(path.toString()); } else{ throw new UnsupportedOperationException("Only Strings and Integers are supported as path element"); } if(!(i+1 == paths.length)) { pathBuilder.append("."); } } return pathBuilder.toString(); }
java
public static String toSimpleTraversrPath(Object[] paths) { StringBuilder pathBuilder = new StringBuilder(); for(int i=0; i<paths.length; i++) { Object path = paths[i]; if(path instanceof Integer) { pathBuilder.append("[").append(((Integer) path).intValue()).append("]"); } else if(path instanceof String) { pathBuilder.append(path.toString()); } else{ throw new UnsupportedOperationException("Only Strings and Integers are supported as path element"); } if(!(i+1 == paths.length)) { pathBuilder.append("."); } } return pathBuilder.toString(); }
[ "public", "static", "String", "toSimpleTraversrPath", "(", "Object", "[", "]", "paths", ")", "{", "StringBuilder", "pathBuilder", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "paths", ".", "length", ";", "i", "++", ")", "{", "Object", "path", "=", "paths", "[", "i", "]", ";", "if", "(", "path", "instanceof", "Integer", ")", "{", "pathBuilder", ".", "append", "(", "\"[\"", ")", ".", "append", "(", "(", "(", "Integer", ")", "path", ")", ".", "intValue", "(", ")", ")", ".", "append", "(", "\"]\"", ")", ";", "}", "else", "if", "(", "path", "instanceof", "String", ")", "{", "pathBuilder", ".", "append", "(", "path", ".", "toString", "(", ")", ")", ";", "}", "else", "{", "throw", "new", "UnsupportedOperationException", "(", "\"Only Strings and Integers are supported as path element\"", ")", ";", "}", "if", "(", "!", "(", "i", "+", "1", "==", "paths", ".", "length", ")", ")", "{", "pathBuilder", ".", "append", "(", "\".\"", ")", ";", "}", "}", "return", "pathBuilder", ".", "toString", "(", ")", ";", "}" ]
Converts a standard json path to human readable SimpleTraversr compatible path @param paths the path array of objects @return string representation of the path, human readable and SimpleTraversr friendly
[ "Converts", "a", "standard", "json", "path", "to", "human", "readable", "SimpleTraversr", "compatible", "path" ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/utils/JoltUtils.java#L369-L387
27,810
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/utils/JoltUtils.java
JoltUtils.compactJson
@SuppressWarnings("unchecked") public static Object compactJson(Object source) { if (source == null) return null; if (source instanceof List) { for (Object item : (List) source) { if (item instanceof List) { compactJson(item); } else if (item instanceof Map) { compactJson(item); } } ((List) source).removeAll(Collections.singleton(null)); } else if (source instanceof Map) { List keysToRemove = new LinkedList(); for (Object key : ((Map) source).keySet()) { Object value = ((Map)source).get(key); if (value instanceof List) { if (((List) value).size() == 0) keysToRemove.add(key); else { compactJson(value); } } else if (value instanceof Map) { if (((Map) value).size() == 0) { keysToRemove.add(key); } else { compactJson(value); } } else if (value == null) { keysToRemove.add(key); } } for(Object key: keysToRemove) { ((Map) source).remove(key); } } else { throw new UnsupportedOperationException( "Only Map/String and List/Integer types are supported" ); } return source; }
java
@SuppressWarnings("unchecked") public static Object compactJson(Object source) { if (source == null) return null; if (source instanceof List) { for (Object item : (List) source) { if (item instanceof List) { compactJson(item); } else if (item instanceof Map) { compactJson(item); } } ((List) source).removeAll(Collections.singleton(null)); } else if (source instanceof Map) { List keysToRemove = new LinkedList(); for (Object key : ((Map) source).keySet()) { Object value = ((Map)source).get(key); if (value instanceof List) { if (((List) value).size() == 0) keysToRemove.add(key); else { compactJson(value); } } else if (value instanceof Map) { if (((Map) value).size() == 0) { keysToRemove.add(key); } else { compactJson(value); } } else if (value == null) { keysToRemove.add(key); } } for(Object key: keysToRemove) { ((Map) source).remove(key); } } else { throw new UnsupportedOperationException( "Only Map/String and List/Integer types are supported" ); } return source; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "Object", "compactJson", "(", "Object", "source", ")", "{", "if", "(", "source", "==", "null", ")", "return", "null", ";", "if", "(", "source", "instanceof", "List", ")", "{", "for", "(", "Object", "item", ":", "(", "List", ")", "source", ")", "{", "if", "(", "item", "instanceof", "List", ")", "{", "compactJson", "(", "item", ")", ";", "}", "else", "if", "(", "item", "instanceof", "Map", ")", "{", "compactJson", "(", "item", ")", ";", "}", "}", "(", "(", "List", ")", "source", ")", ".", "removeAll", "(", "Collections", ".", "singleton", "(", "null", ")", ")", ";", "}", "else", "if", "(", "source", "instanceof", "Map", ")", "{", "List", "keysToRemove", "=", "new", "LinkedList", "(", ")", ";", "for", "(", "Object", "key", ":", "(", "(", "Map", ")", "source", ")", ".", "keySet", "(", ")", ")", "{", "Object", "value", "=", "(", "(", "Map", ")", "source", ")", ".", "get", "(", "key", ")", ";", "if", "(", "value", "instanceof", "List", ")", "{", "if", "(", "(", "(", "List", ")", "value", ")", ".", "size", "(", ")", "==", "0", ")", "keysToRemove", ".", "add", "(", "key", ")", ";", "else", "{", "compactJson", "(", "value", ")", ";", "}", "}", "else", "if", "(", "value", "instanceof", "Map", ")", "{", "if", "(", "(", "(", "Map", ")", "value", ")", ".", "size", "(", ")", "==", "0", ")", "{", "keysToRemove", ".", "add", "(", "key", ")", ";", "}", "else", "{", "compactJson", "(", "value", ")", ";", "}", "}", "else", "if", "(", "value", "==", "null", ")", "{", "keysToRemove", ".", "add", "(", "key", ")", ";", "}", "}", "for", "(", "Object", "key", ":", "keysToRemove", ")", "{", "(", "(", "Map", ")", "source", ")", ".", "remove", "(", "key", ")", ";", "}", "}", "else", "{", "throw", "new", "UnsupportedOperationException", "(", "\"Only Map/String and List/Integer types are supported\"", ")", ";", "}", "return", "source", ";", "}" ]
Given a 'fluffy' json document, it recursively removes all null elements to compact the json document Warning: mutates the doc, destroys array order @param source @return mutated source where all null elements are nuked
[ "Given", "a", "fluffy", "json", "document", "it", "recursively", "removes", "all", "null", "elements", "to", "compact", "the", "json", "document" ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/utils/JoltUtils.java#L420-L464
27,811
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/removr/spec/RemovrCompositeSpec.java
RemovrCompositeSpec.processChildren
private void processChildren( List<RemovrSpec> children, Object subInput ) { if (subInput != null ) { if( subInput instanceof List ) { List<Object> subList = (List<Object>) subInput; Set<Integer> indiciesToRemove = new HashSet<>(); // build a list of all indicies to remove for(RemovrSpec childSpec : children) { indiciesToRemove.addAll( childSpec.applyToList( subList ) ); } List<Integer> uniqueIndiciesToRemove = new ArrayList<>( indiciesToRemove ); // Sort the list from Biggest to Smallest, so that when we remove items from the input // list we don't muck up the order. // Aka removing 0 _then_ 3 would be bad, because we would have actually removed // 0 and 4 from the "original" list. Collections.sort( uniqueIndiciesToRemove, new Comparator<Integer>() { @Override public int compare( Integer o1, Integer o2 ) { return o2.compareTo( o1 ); } } ); for ( int index : uniqueIndiciesToRemove ) { subList.remove( index ); } } else if (subInput instanceof Map ) { Map<String,Object> subInputMap = (Map<String,Object>) subInput; List<String> keysToRemove = new LinkedList<>(); for(RemovrSpec childSpec : children) { keysToRemove.addAll( childSpec.applyToMap( subInputMap ) ); } subInputMap.keySet().removeAll( keysToRemove ); } } }
java
private void processChildren( List<RemovrSpec> children, Object subInput ) { if (subInput != null ) { if( subInput instanceof List ) { List<Object> subList = (List<Object>) subInput; Set<Integer> indiciesToRemove = new HashSet<>(); // build a list of all indicies to remove for(RemovrSpec childSpec : children) { indiciesToRemove.addAll( childSpec.applyToList( subList ) ); } List<Integer> uniqueIndiciesToRemove = new ArrayList<>( indiciesToRemove ); // Sort the list from Biggest to Smallest, so that when we remove items from the input // list we don't muck up the order. // Aka removing 0 _then_ 3 would be bad, because we would have actually removed // 0 and 4 from the "original" list. Collections.sort( uniqueIndiciesToRemove, new Comparator<Integer>() { @Override public int compare( Integer o1, Integer o2 ) { return o2.compareTo( o1 ); } } ); for ( int index : uniqueIndiciesToRemove ) { subList.remove( index ); } } else if (subInput instanceof Map ) { Map<String,Object> subInputMap = (Map<String,Object>) subInput; List<String> keysToRemove = new LinkedList<>(); for(RemovrSpec childSpec : children) { keysToRemove.addAll( childSpec.applyToMap( subInputMap ) ); } subInputMap.keySet().removeAll( keysToRemove ); } } }
[ "private", "void", "processChildren", "(", "List", "<", "RemovrSpec", ">", "children", ",", "Object", "subInput", ")", "{", "if", "(", "subInput", "!=", "null", ")", "{", "if", "(", "subInput", "instanceof", "List", ")", "{", "List", "<", "Object", ">", "subList", "=", "(", "List", "<", "Object", ">", ")", "subInput", ";", "Set", "<", "Integer", ">", "indiciesToRemove", "=", "new", "HashSet", "<>", "(", ")", ";", "// build a list of all indicies to remove", "for", "(", "RemovrSpec", "childSpec", ":", "children", ")", "{", "indiciesToRemove", ".", "addAll", "(", "childSpec", ".", "applyToList", "(", "subList", ")", ")", ";", "}", "List", "<", "Integer", ">", "uniqueIndiciesToRemove", "=", "new", "ArrayList", "<>", "(", "indiciesToRemove", ")", ";", "// Sort the list from Biggest to Smallest, so that when we remove items from the input", "// list we don't muck up the order.", "// Aka removing 0 _then_ 3 would be bad, because we would have actually removed", "// 0 and 4 from the \"original\" list.", "Collections", ".", "sort", "(", "uniqueIndiciesToRemove", ",", "new", "Comparator", "<", "Integer", ">", "(", ")", "{", "@", "Override", "public", "int", "compare", "(", "Integer", "o1", ",", "Integer", "o2", ")", "{", "return", "o2", ".", "compareTo", "(", "o1", ")", ";", "}", "}", ")", ";", "for", "(", "int", "index", ":", "uniqueIndiciesToRemove", ")", "{", "subList", ".", "remove", "(", "index", ")", ";", "}", "}", "else", "if", "(", "subInput", "instanceof", "Map", ")", "{", "Map", "<", "String", ",", "Object", ">", "subInputMap", "=", "(", "Map", "<", "String", ",", "Object", ">", ")", "subInput", ";", "List", "<", "String", ">", "keysToRemove", "=", "new", "LinkedList", "<>", "(", ")", ";", "for", "(", "RemovrSpec", "childSpec", ":", "children", ")", "{", "keysToRemove", ".", "addAll", "(", "childSpec", ".", "applyToMap", "(", "subInputMap", ")", ")", ";", "}", "subInputMap", ".", "keySet", "(", ")", ".", "removeAll", "(", "keysToRemove", ")", ";", "}", "}", "}" ]
Call our child nodes, build up the set of keys or indices to actually remove, and then remove them.
[ "Call", "our", "child", "nodes", "build", "up", "the", "set", "of", "keys", "or", "indices", "to", "actually", "remove", "and", "then", "remove", "them", "." ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/removr/spec/RemovrCompositeSpec.java#L134-L177
27,812
bazaarvoice/jolt
json-utils/src/main/java/com/bazaarvoice/jolt/JsonUtils.java
JsonUtils.jsonTo
@Deprecated public static <T> T jsonTo( String json, TypeReference<T> typeRef ) { return util.stringToType( json, typeRef ); }
java
@Deprecated public static <T> T jsonTo( String json, TypeReference<T> typeRef ) { return util.stringToType( json, typeRef ); }
[ "@", "Deprecated", "public", "static", "<", "T", ">", "T", "jsonTo", "(", "String", "json", ",", "TypeReference", "<", "T", ">", "typeRef", ")", "{", "return", "util", ".", "stringToType", "(", "json", ",", "typeRef", ")", ";", "}" ]
Use the stringToType method instead.
[ "Use", "the", "stringToType", "method", "instead", "." ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/json-utils/src/main/java/com/bazaarvoice/jolt/JsonUtils.java#L201-L204
27,813
bazaarvoice/jolt
json-utils/src/main/java/com/bazaarvoice/jolt/JsonUtils.java
JsonUtils.navigate
@SuppressWarnings("unchecked") @Deprecated public static <T> T navigate(Object source, Object... paths) throws NullPointerException, UnsupportedOperationException { Object destination = source; for (Object path : paths) { if(destination == null) throw new NullPointerException("Navigation not possible on null object"); if(destination instanceof Map) destination = ((Map) destination).get(path); else if(path instanceof Integer && destination instanceof List) destination = ((List) destination).get((Integer)path); else throw new UnsupportedOperationException("Navigation supports only Map and List source types and non-null String and Integer path types"); } return (T) destination; }
java
@SuppressWarnings("unchecked") @Deprecated public static <T> T navigate(Object source, Object... paths) throws NullPointerException, UnsupportedOperationException { Object destination = source; for (Object path : paths) { if(destination == null) throw new NullPointerException("Navigation not possible on null object"); if(destination instanceof Map) destination = ((Map) destination).get(path); else if(path instanceof Integer && destination instanceof List) destination = ((List) destination).get((Integer)path); else throw new UnsupportedOperationException("Navigation supports only Map and List source types and non-null String and Integer path types"); } return (T) destination; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "@", "Deprecated", "public", "static", "<", "T", ">", "T", "navigate", "(", "Object", "source", ",", "Object", "...", "paths", ")", "throws", "NullPointerException", ",", "UnsupportedOperationException", "{", "Object", "destination", "=", "source", ";", "for", "(", "Object", "path", ":", "paths", ")", "{", "if", "(", "destination", "==", "null", ")", "throw", "new", "NullPointerException", "(", "\"Navigation not possible on null object\"", ")", ";", "if", "(", "destination", "instanceof", "Map", ")", "destination", "=", "(", "(", "Map", ")", "destination", ")", ".", "get", "(", "path", ")", ";", "else", "if", "(", "path", "instanceof", "Integer", "&&", "destination", "instanceof", "List", ")", "destination", "=", "(", "(", "List", ")", "destination", ")", ".", "get", "(", "(", "Integer", ")", "path", ")", ";", "else", "throw", "new", "UnsupportedOperationException", "(", "\"Navigation supports only Map and List source types and non-null String and Integer path types\"", ")", ";", "}", "return", "(", "T", ")", "destination", ";", "}" ]
Navigate inside a json object in quick and dirty way. Deprecated: use JoltUtils instead @param source the source json object @param paths the paths array to travel @return the object of Type <T> at final destination @throws NullPointerException if the source is null @throws UnsupportedOperationException if the source is not Map or List
[ "Navigate", "inside", "a", "json", "object", "in", "quick", "and", "dirty", "way", "." ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/json-utils/src/main/java/com/bazaarvoice/jolt/JsonUtils.java#L246-L257
27,814
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/utils/StringTools.java
StringTools.isBlank
public static boolean isBlank(CharSequence sourceSequence) { int sequenceLength; if (sourceSequence == null || (sequenceLength = sourceSequence.length()) == 0) { return true; } for (int i = 0; i < sequenceLength; i++) { if ((Character.isWhitespace(sourceSequence.charAt(i)) == false)) { return false; } } return true; }
java
public static boolean isBlank(CharSequence sourceSequence) { int sequenceLength; if (sourceSequence == null || (sequenceLength = sourceSequence.length()) == 0) { return true; } for (int i = 0; i < sequenceLength; i++) { if ((Character.isWhitespace(sourceSequence.charAt(i)) == false)) { return false; } } return true; }
[ "public", "static", "boolean", "isBlank", "(", "CharSequence", "sourceSequence", ")", "{", "int", "sequenceLength", ";", "if", "(", "sourceSequence", "==", "null", "||", "(", "sequenceLength", "=", "sourceSequence", ".", "length", "(", ")", ")", "==", "0", ")", "{", "return", "true", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "sequenceLength", ";", "i", "++", ")", "{", "if", "(", "(", "Character", ".", "isWhitespace", "(", "sourceSequence", ".", "charAt", "(", "i", ")", ")", "==", "false", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Check if a sequence is blank @param sourceSequence to check @return true is sourceSequence is blank
[ "Check", "if", "a", "sequence", "is", "blank" ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/utils/StringTools.java#L82-L93
27,815
bazaarvoice/jolt
cli/src/main/java/com/bazaarvoice/jolt/SortCliProcessor.java
SortCliProcessor.intializeSubCommand
@Override public void intializeSubCommand( Subparsers subparsers ) { Subparser sortParser = subparsers.addParser( "sort" ) .description( "Jolt CLI Sort Tool. This tool will ingest one JSON input (from a file or standard input) and " + "perform the Jolt sort operation on it. The sort order is standard alphabetical ascending, with a " + "special case for \"~\" prefixed keys to be bumped to the top. The program will return an exit code " + "of 0 if the sort operation is performed successfully or a 1 if an error is encountered." ) .defaultHelp( true ); sortParser.addArgument( "input" ).help( "File path to the input JSON that the sort operation should be performed on. " + "This file should contain valid JSON. " + "If this argument is not specified then standard input will be used." ) .type( Arguments.fileType().verifyExists().verifyIsFile().verifyCanRead() ) .nargs( "?" ).setDefault( (File) null ).required( false ); // these last two method calls make input optional sortParser.addArgument( "-u" ).help( "Turns off pretty print for the output. Output will be raw json with no formatting." ) .action( Arguments.storeTrue() ); }
java
@Override public void intializeSubCommand( Subparsers subparsers ) { Subparser sortParser = subparsers.addParser( "sort" ) .description( "Jolt CLI Sort Tool. This tool will ingest one JSON input (from a file or standard input) and " + "perform the Jolt sort operation on it. The sort order is standard alphabetical ascending, with a " + "special case for \"~\" prefixed keys to be bumped to the top. The program will return an exit code " + "of 0 if the sort operation is performed successfully or a 1 if an error is encountered." ) .defaultHelp( true ); sortParser.addArgument( "input" ).help( "File path to the input JSON that the sort operation should be performed on. " + "This file should contain valid JSON. " + "If this argument is not specified then standard input will be used." ) .type( Arguments.fileType().verifyExists().verifyIsFile().verifyCanRead() ) .nargs( "?" ).setDefault( (File) null ).required( false ); // these last two method calls make input optional sortParser.addArgument( "-u" ).help( "Turns off pretty print for the output. Output will be raw json with no formatting." ) .action( Arguments.storeTrue() ); }
[ "@", "Override", "public", "void", "intializeSubCommand", "(", "Subparsers", "subparsers", ")", "{", "Subparser", "sortParser", "=", "subparsers", ".", "addParser", "(", "\"sort\"", ")", ".", "description", "(", "\"Jolt CLI Sort Tool. This tool will ingest one JSON input (from a file or standard input) and \"", "+", "\"perform the Jolt sort operation on it. The sort order is standard alphabetical ascending, with a \"", "+", "\"special case for \\\"~\\\" prefixed keys to be bumped to the top. The program will return an exit code \"", "+", "\"of 0 if the sort operation is performed successfully or a 1 if an error is encountered.\"", ")", ".", "defaultHelp", "(", "true", ")", ";", "sortParser", ".", "addArgument", "(", "\"input\"", ")", ".", "help", "(", "\"File path to the input JSON that the sort operation should be performed on. \"", "+", "\"This file should contain valid JSON. \"", "+", "\"If this argument is not specified then standard input will be used.\"", ")", ".", "type", "(", "Arguments", ".", "fileType", "(", ")", ".", "verifyExists", "(", ")", ".", "verifyIsFile", "(", ")", ".", "verifyCanRead", "(", ")", ")", ".", "nargs", "(", "\"?\"", ")", ".", "setDefault", "(", "(", "File", ")", "null", ")", ".", "required", "(", "false", ")", ";", "// these last two method calls make input optional", "sortParser", ".", "addArgument", "(", "\"-u\"", ")", ".", "help", "(", "\"Turns off pretty print for the output. Output will be raw json with no formatting.\"", ")", ".", "action", "(", "Arguments", ".", "storeTrue", "(", ")", ")", ";", "}" ]
Initialize the arg parser for the Sort sub command @param subparsers The Subparsers object to attach the new Subparser to
[ "Initialize", "the", "arg", "parser", "for", "the", "Sort", "sub", "command" ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/cli/src/main/java/com/bazaarvoice/jolt/SortCliProcessor.java#L38-L55
27,816
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/removr/spec/RemovrSpec.java
RemovrSpec.getNonNegativeIntegerFromLiteralPathElement
protected Integer getNonNegativeIntegerFromLiteralPathElement() { Integer pathElementInt = null; try { pathElementInt = Integer.parseInt( pathElement.getRawKey() ); if ( pathElementInt < 0 ) { return null; } } catch( NumberFormatException nfe ) { // If the data is an Array, but the spec keys are Non-Integer Strings, // we are annoyed, but we don't stop the whole transform. // Just this part of the Transform won't work. } return pathElementInt; }
java
protected Integer getNonNegativeIntegerFromLiteralPathElement() { Integer pathElementInt = null; try { pathElementInt = Integer.parseInt( pathElement.getRawKey() ); if ( pathElementInt < 0 ) { return null; } } catch( NumberFormatException nfe ) { // If the data is an Array, but the spec keys are Non-Integer Strings, // we are annoyed, but we don't stop the whole transform. // Just this part of the Transform won't work. } return pathElementInt; }
[ "protected", "Integer", "getNonNegativeIntegerFromLiteralPathElement", "(", ")", "{", "Integer", "pathElementInt", "=", "null", ";", "try", "{", "pathElementInt", "=", "Integer", ".", "parseInt", "(", "pathElement", ".", "getRawKey", "(", ")", ")", ";", "if", "(", "pathElementInt", "<", "0", ")", "{", "return", "null", ";", "}", "}", "catch", "(", "NumberFormatException", "nfe", ")", "{", "// If the data is an Array, but the spec keys are Non-Integer Strings,", "// we are annoyed, but we don't stop the whole transform.", "// Just this part of the Transform won't work.", "}", "return", "pathElementInt", ";", "}" ]
Try to "interpret" the spec String value as a non-negative integer. @return non-negative integer, otherwise null
[ "Try", "to", "interpret", "the", "spec", "String", "value", "as", "a", "non", "-", "negative", "integer", "." ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/removr/spec/RemovrSpec.java#L68-L86
27,817
bazaarvoice/jolt
cli/src/main/java/com/bazaarvoice/jolt/TransformCliProcessor.java
TransformCliProcessor.intializeSubCommand
@Override public void intializeSubCommand( Subparsers subparsers ) { Subparser transformParser = subparsers.addParser( "transform" ) .description( "Jolt CLI Transform Tool. This tool will ingest a JSON spec file and an JSON input (from a file or " + "standard input) and run the transforms specified in the spec file on the input. The program will return an " + "exit code of 0 if the input is transformed successfully or a 1 if an error is encountered" ) .defaultHelp( true ); File nullFile = null; transformParser.addArgument( "spec" ).help( "File path to Jolt Transform Spec to execute on the input. " + "This file should contain valid JSON." ) .type( Arguments.fileType().verifyExists().verifyIsFile().verifyCanRead() ); transformParser.addArgument( "input" ).help( "File path to the input JSON for the Jolt Transform operation. " + "This file should contain valid JSON. " + "If this argument is not specified then standard input will be used." ) .type( Arguments.fileType().verifyExists().verifyIsFile().verifyCanRead() ) .nargs( "?" ).setDefault( nullFile ); // these last two method calls make input optional transformParser.addArgument( "-u" ).help( "Turns off pretty print for the output. Output will be raw json with no formatting." ) .action( Arguments.storeTrue() ); }
java
@Override public void intializeSubCommand( Subparsers subparsers ) { Subparser transformParser = subparsers.addParser( "transform" ) .description( "Jolt CLI Transform Tool. This tool will ingest a JSON spec file and an JSON input (from a file or " + "standard input) and run the transforms specified in the spec file on the input. The program will return an " + "exit code of 0 if the input is transformed successfully or a 1 if an error is encountered" ) .defaultHelp( true ); File nullFile = null; transformParser.addArgument( "spec" ).help( "File path to Jolt Transform Spec to execute on the input. " + "This file should contain valid JSON." ) .type( Arguments.fileType().verifyExists().verifyIsFile().verifyCanRead() ); transformParser.addArgument( "input" ).help( "File path to the input JSON for the Jolt Transform operation. " + "This file should contain valid JSON. " + "If this argument is not specified then standard input will be used." ) .type( Arguments.fileType().verifyExists().verifyIsFile().verifyCanRead() ) .nargs( "?" ).setDefault( nullFile ); // these last two method calls make input optional transformParser.addArgument( "-u" ).help( "Turns off pretty print for the output. Output will be raw json with no formatting." ) .action( Arguments.storeTrue() ); }
[ "@", "Override", "public", "void", "intializeSubCommand", "(", "Subparsers", "subparsers", ")", "{", "Subparser", "transformParser", "=", "subparsers", ".", "addParser", "(", "\"transform\"", ")", ".", "description", "(", "\"Jolt CLI Transform Tool. This tool will ingest a JSON spec file and an JSON input (from a file or \"", "+", "\"standard input) and run the transforms specified in the spec file on the input. The program will return an \"", "+", "\"exit code of 0 if the input is transformed successfully or a 1 if an error is encountered\"", ")", ".", "defaultHelp", "(", "true", ")", ";", "File", "nullFile", "=", "null", ";", "transformParser", ".", "addArgument", "(", "\"spec\"", ")", ".", "help", "(", "\"File path to Jolt Transform Spec to execute on the input. \"", "+", "\"This file should contain valid JSON.\"", ")", ".", "type", "(", "Arguments", ".", "fileType", "(", ")", ".", "verifyExists", "(", ")", ".", "verifyIsFile", "(", ")", ".", "verifyCanRead", "(", ")", ")", ";", "transformParser", ".", "addArgument", "(", "\"input\"", ")", ".", "help", "(", "\"File path to the input JSON for the Jolt Transform operation. \"", "+", "\"This file should contain valid JSON. \"", "+", "\"If this argument is not specified then standard input will be used.\"", ")", ".", "type", "(", "Arguments", ".", "fileType", "(", ")", ".", "verifyExists", "(", ")", ".", "verifyIsFile", "(", ")", ".", "verifyCanRead", "(", ")", ")", ".", "nargs", "(", "\"?\"", ")", ".", "setDefault", "(", "nullFile", ")", ";", "// these last two method calls make input optional", "transformParser", ".", "addArgument", "(", "\"-u\"", ")", ".", "help", "(", "\"Turns off pretty print for the output. Output will be raw json with no formatting.\"", ")", ".", "action", "(", "Arguments", ".", "storeTrue", "(", ")", ")", ";", "}" ]
Initialize the arg parser for the Transform sub command @param subparsers The Subparsers object to attach the new Subparser to
[ "Initialize", "the", "arg", "parser", "for", "the", "Transform", "sub", "command" ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/cli/src/main/java/com/bazaarvoice/jolt/TransformCliProcessor.java#L38-L58
27,818
bazaarvoice/jolt
cli/src/main/java/com/bazaarvoice/jolt/TransformCliProcessor.java
TransformCliProcessor.process
@Override public boolean process( Namespace ns ) { Chainr chainr; try { chainr = ChainrFactory.fromFile((File) ns.get("spec")); } catch ( Exception e ) { JoltCliUtilities.printToStandardOut( "Chainr failed to load spec file.", SUPPRESS_OUTPUT ); e.printStackTrace( System.out ); return false; } File file = ns.get( "input" ); Object input = JoltCliUtilities.readJsonInput( file, SUPPRESS_OUTPUT ); Object output; try { output = chainr.transform( input ); } catch ( Exception e ) { JoltCliUtilities.printToStandardOut( "Chainr failed to run spec file.", SUPPRESS_OUTPUT ); return false; } Boolean uglyPrint = ns.getBoolean( "u" ); return JoltCliUtilities.printJsonObject( output, uglyPrint, SUPPRESS_OUTPUT ); }
java
@Override public boolean process( Namespace ns ) { Chainr chainr; try { chainr = ChainrFactory.fromFile((File) ns.get("spec")); } catch ( Exception e ) { JoltCliUtilities.printToStandardOut( "Chainr failed to load spec file.", SUPPRESS_OUTPUT ); e.printStackTrace( System.out ); return false; } File file = ns.get( "input" ); Object input = JoltCliUtilities.readJsonInput( file, SUPPRESS_OUTPUT ); Object output; try { output = chainr.transform( input ); } catch ( Exception e ) { JoltCliUtilities.printToStandardOut( "Chainr failed to run spec file.", SUPPRESS_OUTPUT ); return false; } Boolean uglyPrint = ns.getBoolean( "u" ); return JoltCliUtilities.printJsonObject( output, uglyPrint, SUPPRESS_OUTPUT ); }
[ "@", "Override", "public", "boolean", "process", "(", "Namespace", "ns", ")", "{", "Chainr", "chainr", ";", "try", "{", "chainr", "=", "ChainrFactory", ".", "fromFile", "(", "(", "File", ")", "ns", ".", "get", "(", "\"spec\"", ")", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "JoltCliUtilities", ".", "printToStandardOut", "(", "\"Chainr failed to load spec file.\"", ",", "SUPPRESS_OUTPUT", ")", ";", "e", ".", "printStackTrace", "(", "System", ".", "out", ")", ";", "return", "false", ";", "}", "File", "file", "=", "ns", ".", "get", "(", "\"input\"", ")", ";", "Object", "input", "=", "JoltCliUtilities", ".", "readJsonInput", "(", "file", ",", "SUPPRESS_OUTPUT", ")", ";", "Object", "output", ";", "try", "{", "output", "=", "chainr", ".", "transform", "(", "input", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "JoltCliUtilities", ".", "printToStandardOut", "(", "\"Chainr failed to run spec file.\"", ",", "SUPPRESS_OUTPUT", ")", ";", "return", "false", ";", "}", "Boolean", "uglyPrint", "=", "ns", ".", "getBoolean", "(", "\"u\"", ")", ";", "return", "JoltCliUtilities", ".", "printJsonObject", "(", "output", ",", "uglyPrint", ",", "SUPPRESS_OUTPUT", ")", ";", "}" ]
Process the transform sub command @param ns Namespace which contains parsed commandline arguments @return true if the transform is successful, false if an error occured
[ "Process", "the", "transform", "sub", "command" ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/cli/src/main/java/com/bazaarvoice/jolt/TransformCliProcessor.java#L66-L91
27,819
bazaarvoice/jolt
complete/src/main/java/com/bazaarvoice/jolt/ChainrFactory.java
ChainrFactory.fromClassPath
public static Chainr fromClassPath( String chainrSpecClassPath, ChainrInstantiator chainrInstantiator ) { Object chainrSpec = JsonUtils.classpathToObject( chainrSpecClassPath ); return getChainr( chainrInstantiator, chainrSpec ); }
java
public static Chainr fromClassPath( String chainrSpecClassPath, ChainrInstantiator chainrInstantiator ) { Object chainrSpec = JsonUtils.classpathToObject( chainrSpecClassPath ); return getChainr( chainrInstantiator, chainrSpec ); }
[ "public", "static", "Chainr", "fromClassPath", "(", "String", "chainrSpecClassPath", ",", "ChainrInstantiator", "chainrInstantiator", ")", "{", "Object", "chainrSpec", "=", "JsonUtils", ".", "classpathToObject", "(", "chainrSpecClassPath", ")", ";", "return", "getChainr", "(", "chainrInstantiator", ",", "chainrSpec", ")", ";", "}" ]
Builds a Chainr instance using the spec described in the data via the class path that is passed in. @param chainrSpecClassPath The class path that points to the chainr spec. @param chainrInstantiator the ChainrInstantiator to use to initialze the Chainr instance @return a Chainr instance
[ "Builds", "a", "Chainr", "instance", "using", "the", "spec", "described", "in", "the", "data", "via", "the", "class", "path", "that", "is", "passed", "in", "." ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/complete/src/main/java/com/bazaarvoice/jolt/ChainrFactory.java#L45-L48
27,820
bazaarvoice/jolt
complete/src/main/java/com/bazaarvoice/jolt/ChainrFactory.java
ChainrFactory.fromFileSystem
public static Chainr fromFileSystem( String chainrSpecFilePath, ChainrInstantiator chainrInstantiator ) { Object chainrSpec = JsonUtils.filepathToObject( chainrSpecFilePath ); return getChainr( chainrInstantiator, chainrSpec ); }
java
public static Chainr fromFileSystem( String chainrSpecFilePath, ChainrInstantiator chainrInstantiator ) { Object chainrSpec = JsonUtils.filepathToObject( chainrSpecFilePath ); return getChainr( chainrInstantiator, chainrSpec ); }
[ "public", "static", "Chainr", "fromFileSystem", "(", "String", "chainrSpecFilePath", ",", "ChainrInstantiator", "chainrInstantiator", ")", "{", "Object", "chainrSpec", "=", "JsonUtils", ".", "filepathToObject", "(", "chainrSpecFilePath", ")", ";", "return", "getChainr", "(", "chainrInstantiator", ",", "chainrSpec", ")", ";", "}" ]
Builds a Chainr instance using the spec described in the data via the file path that is passed in. @param chainrSpecFilePath The file path that points to the chainr spec. @param chainrInstantiator the ChainrInstantiator to use to initialze the Chainr instance @return a Chainr instance
[ "Builds", "a", "Chainr", "instance", "using", "the", "spec", "described", "in", "the", "data", "via", "the", "file", "path", "that", "is", "passed", "in", "." ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/complete/src/main/java/com/bazaarvoice/jolt/ChainrFactory.java#L67-L70
27,821
bazaarvoice/jolt
complete/src/main/java/com/bazaarvoice/jolt/ChainrFactory.java
ChainrFactory.fromFile
public static Chainr fromFile( File chainrSpecFile, ChainrInstantiator chainrInstantiator ) { Object chainrSpec; try { FileInputStream fileInputStream = new FileInputStream( chainrSpecFile ); chainrSpec = JsonUtils.jsonToObject( fileInputStream ); } catch ( Exception e ) { throw new RuntimeException( "Unable to load chainr spec file " + chainrSpecFile.getAbsolutePath() ); } return getChainr( chainrInstantiator, chainrSpec ); }
java
public static Chainr fromFile( File chainrSpecFile, ChainrInstantiator chainrInstantiator ) { Object chainrSpec; try { FileInputStream fileInputStream = new FileInputStream( chainrSpecFile ); chainrSpec = JsonUtils.jsonToObject( fileInputStream ); } catch ( Exception e ) { throw new RuntimeException( "Unable to load chainr spec file " + chainrSpecFile.getAbsolutePath() ); } return getChainr( chainrInstantiator, chainrSpec ); }
[ "public", "static", "Chainr", "fromFile", "(", "File", "chainrSpecFile", ",", "ChainrInstantiator", "chainrInstantiator", ")", "{", "Object", "chainrSpec", ";", "try", "{", "FileInputStream", "fileInputStream", "=", "new", "FileInputStream", "(", "chainrSpecFile", ")", ";", "chainrSpec", "=", "JsonUtils", ".", "jsonToObject", "(", "fileInputStream", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Unable to load chainr spec file \"", "+", "chainrSpecFile", ".", "getAbsolutePath", "(", ")", ")", ";", "}", "return", "getChainr", "(", "chainrInstantiator", ",", "chainrSpec", ")", ";", "}" ]
Builds a Chainr instance using the spec described in the File that is passed in. @param chainrSpecFile The File which contains the chainr spec. @param chainrInstantiator the ChainrInstantiator to use to initialze the Chainr instance @return a Chainr instance
[ "Builds", "a", "Chainr", "instance", "using", "the", "spec", "described", "in", "the", "File", "that", "is", "passed", "in", "." ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/complete/src/main/java/com/bazaarvoice/jolt/ChainrFactory.java#L89-L98
27,822
bazaarvoice/jolt
complete/src/main/java/com/bazaarvoice/jolt/ChainrFactory.java
ChainrFactory.getChainr
private static Chainr getChainr( ChainrInstantiator chainrInstantiator, Object chainrSpec ) { Chainr chainr; if (chainrInstantiator == null ) { chainr = Chainr.fromSpec( chainrSpec ); } else { chainr = Chainr.fromSpec( chainrSpec, chainrInstantiator ); } return chainr; }
java
private static Chainr getChainr( ChainrInstantiator chainrInstantiator, Object chainrSpec ) { Chainr chainr; if (chainrInstantiator == null ) { chainr = Chainr.fromSpec( chainrSpec ); } else { chainr = Chainr.fromSpec( chainrSpec, chainrInstantiator ); } return chainr; }
[ "private", "static", "Chainr", "getChainr", "(", "ChainrInstantiator", "chainrInstantiator", ",", "Object", "chainrSpec", ")", "{", "Chainr", "chainr", ";", "if", "(", "chainrInstantiator", "==", "null", ")", "{", "chainr", "=", "Chainr", ".", "fromSpec", "(", "chainrSpec", ")", ";", "}", "else", "{", "chainr", "=", "Chainr", ".", "fromSpec", "(", "chainrSpec", ",", "chainrInstantiator", ")", ";", "}", "return", "chainr", ";", "}" ]
The main engine in ChainrFactory for building a Chainr Instance. @param chainrInstantiator The ChainrInstantiator to use. If null it will not be used. @param chainrSpec The json spec for the chainr transformation @return the Chainr instance created from the chainrInstantiator and inputStream
[ "The", "main", "engine", "in", "ChainrFactory", "for", "building", "a", "Chainr", "Instance", "." ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/complete/src/main/java/com/bazaarvoice/jolt/ChainrFactory.java#L107-L116
27,823
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/Removr.java
Removr.transform
@Override public Object transform( Object input ) { // Wrap the input in a map to fool the CompositeSpec to recurse itself. Map<String,Object> wrappedMap = new HashMap<>(); wrappedMap.put(ROOT_KEY, input); rootSpec.applyToMap( wrappedMap ); return input; }
java
@Override public Object transform( Object input ) { // Wrap the input in a map to fool the CompositeSpec to recurse itself. Map<String,Object> wrappedMap = new HashMap<>(); wrappedMap.put(ROOT_KEY, input); rootSpec.applyToMap( wrappedMap ); return input; }
[ "@", "Override", "public", "Object", "transform", "(", "Object", "input", ")", "{", "// Wrap the input in a map to fool the CompositeSpec to recurse itself.", "Map", "<", "String", ",", "Object", ">", "wrappedMap", "=", "new", "HashMap", "<>", "(", ")", ";", "wrappedMap", ".", "put", "(", "ROOT_KEY", ",", "input", ")", ";", "rootSpec", ".", "applyToMap", "(", "wrappedMap", ")", ";", "return", "input", ";", "}" ]
Recursively removes data from the input JSON. @param input the JSON object to transform in plain vanilla Jackson Map<String, Object> style
[ "Recursively", "removes", "data", "from", "the", "input", "JSON", "." ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/Removr.java#L205-L213
27,824
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/Shiftr.java
Shiftr.transform
@Override public Object transform( Object input ) { Map<String,Object> output = new HashMap<>(); // Create a root LiteralPathElement so that # is useful at the root level MatchedElement rootLpe = new MatchedElement( ROOT_KEY ); WalkedPath walkedPath = new WalkedPath(); walkedPath.add( input, rootLpe ); rootSpec.apply( ROOT_KEY, Optional.of( input ), walkedPath, output, null ); return output.get( ROOT_KEY ); }
java
@Override public Object transform( Object input ) { Map<String,Object> output = new HashMap<>(); // Create a root LiteralPathElement so that # is useful at the root level MatchedElement rootLpe = new MatchedElement( ROOT_KEY ); WalkedPath walkedPath = new WalkedPath(); walkedPath.add( input, rootLpe ); rootSpec.apply( ROOT_KEY, Optional.of( input ), walkedPath, output, null ); return output.get( ROOT_KEY ); }
[ "@", "Override", "public", "Object", "transform", "(", "Object", "input", ")", "{", "Map", "<", "String", ",", "Object", ">", "output", "=", "new", "HashMap", "<>", "(", ")", ";", "// Create a root LiteralPathElement so that # is useful at the root level", "MatchedElement", "rootLpe", "=", "new", "MatchedElement", "(", "ROOT_KEY", ")", ";", "WalkedPath", "walkedPath", "=", "new", "WalkedPath", "(", ")", ";", "walkedPath", ".", "add", "(", "input", ",", "rootLpe", ")", ";", "rootSpec", ".", "apply", "(", "ROOT_KEY", ",", "Optional", ".", "of", "(", "input", ")", ",", "walkedPath", ",", "output", ",", "null", ")", ";", "return", "output", ".", "get", "(", "ROOT_KEY", ")", ";", "}" ]
Applies the Shiftr transform. @param input the JSON object to transform @return the output object with data shifted to it @throws com.bazaarvoice.jolt.exception.TransformException for a malformed spec or if there are issues during the transform
[ "Applies", "the", "Shiftr", "transform", "." ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/Shiftr.java#L495-L508
27,825
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/common/PathElementBuilder.java
PathElementBuilder.buildMatchablePathElement
public static MatchablePathElement buildMatchablePathElement(String rawJsonKey) { PathElement pe = PathElementBuilder.parseSingleKeyLHS( rawJsonKey ); if ( ! ( pe instanceof MatchablePathElement ) ) { throw new SpecException( "Spec LHS key=" + rawJsonKey + " is not a valid LHS key." ); } return (MatchablePathElement) pe; }
java
public static MatchablePathElement buildMatchablePathElement(String rawJsonKey) { PathElement pe = PathElementBuilder.parseSingleKeyLHS( rawJsonKey ); if ( ! ( pe instanceof MatchablePathElement ) ) { throw new SpecException( "Spec LHS key=" + rawJsonKey + " is not a valid LHS key." ); } return (MatchablePathElement) pe; }
[ "public", "static", "MatchablePathElement", "buildMatchablePathElement", "(", "String", "rawJsonKey", ")", "{", "PathElement", "pe", "=", "PathElementBuilder", ".", "parseSingleKeyLHS", "(", "rawJsonKey", ")", ";", "if", "(", "!", "(", "pe", "instanceof", "MatchablePathElement", ")", ")", "{", "throw", "new", "SpecException", "(", "\"Spec LHS key=\"", "+", "rawJsonKey", "+", "\" is not a valid LHS key.\"", ")", ";", "}", "return", "(", "MatchablePathElement", ")", "pe", ";", "}" ]
Create a path element and ensures it is a Matchable Path Element
[ "Create", "a", "path", "element", "and", "ensures", "it", "is", "a", "Matchable", "Path", "Element" ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/common/PathElementBuilder.java#L55-L63
27,826
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/common/PathElementBuilder.java
PathElementBuilder.parseSingleKeyLHS
public static PathElement parseSingleKeyLHS( String origKey ) { String elementKey; // the String to use to actually make Elements String keyToInspect; // the String to use to determine which kind of Element to create if ( origKey.contains( "\\" ) ) { // only do the extra work of processing for escaped chars, if there is one. keyToInspect = removeEscapedValues( origKey ); elementKey = removeEscapeChars( origKey ); } else { keyToInspect = origKey; elementKey = origKey; } //// LHS single values if ( "@".equals( keyToInspect ) ) { return new AtPathElement( elementKey ); } else if ( "*".equals( keyToInspect ) ) { return new StarAllPathElement( elementKey ); } else if ( keyToInspect.startsWith( "[" ) ) { if ( StringTools.countMatches( keyToInspect, "[" ) != 1 || StringTools.countMatches(keyToInspect, "]") != 1 ) { throw new SpecException( "Invalid key:" + origKey + " has too many [] references."); } return new ArrayPathElement( elementKey ); } //// LHS multiple values else if ( keyToInspect.startsWith("@") || keyToInspect.contains( "@(" ) ) { // The traspose path element gets the origKey so that it has it's escapes. return TransposePathElement.parse( origKey ); } else if ( keyToInspect.contains( "@" ) ) { throw new SpecException( "Invalid key:" + origKey + " can not have an @ other than at the front." ); } else if ( keyToInspect.contains("$") ) { return new DollarPathElement( elementKey ); } else if ( keyToInspect.contains("[") ) { if ( StringTools.countMatches(keyToInspect, "[") != 1 || StringTools.countMatches(keyToInspect, "]") != 1 ) { throw new SpecException( "Invalid key:" + origKey + " has too many [] references."); } return new ArrayPathElement( elementKey ); } else if ( keyToInspect.contains( "&" ) ) { if ( keyToInspect.contains("*") ) { throw new SpecException( "Invalid key:" + origKey + ", Can't mix * with & ) "); } return new AmpPathElement( elementKey ); } else if ( keyToInspect.contains("*" ) ) { int numOfStars = StringTools.countMatches(keyToInspect, "*"); if(numOfStars == 1){ return new StarSinglePathElement( elementKey ); } else if(numOfStars == 2){ return new StarDoublePathElement( elementKey ); } else { return new StarRegexPathElement( elementKey ); } } else if ( keyToInspect.contains("#" ) ) { return new HashPathElement( elementKey ); } else { return new LiteralPathElement( elementKey ); } }
java
public static PathElement parseSingleKeyLHS( String origKey ) { String elementKey; // the String to use to actually make Elements String keyToInspect; // the String to use to determine which kind of Element to create if ( origKey.contains( "\\" ) ) { // only do the extra work of processing for escaped chars, if there is one. keyToInspect = removeEscapedValues( origKey ); elementKey = removeEscapeChars( origKey ); } else { keyToInspect = origKey; elementKey = origKey; } //// LHS single values if ( "@".equals( keyToInspect ) ) { return new AtPathElement( elementKey ); } else if ( "*".equals( keyToInspect ) ) { return new StarAllPathElement( elementKey ); } else if ( keyToInspect.startsWith( "[" ) ) { if ( StringTools.countMatches( keyToInspect, "[" ) != 1 || StringTools.countMatches(keyToInspect, "]") != 1 ) { throw new SpecException( "Invalid key:" + origKey + " has too many [] references."); } return new ArrayPathElement( elementKey ); } //// LHS multiple values else if ( keyToInspect.startsWith("@") || keyToInspect.contains( "@(" ) ) { // The traspose path element gets the origKey so that it has it's escapes. return TransposePathElement.parse( origKey ); } else if ( keyToInspect.contains( "@" ) ) { throw new SpecException( "Invalid key:" + origKey + " can not have an @ other than at the front." ); } else if ( keyToInspect.contains("$") ) { return new DollarPathElement( elementKey ); } else if ( keyToInspect.contains("[") ) { if ( StringTools.countMatches(keyToInspect, "[") != 1 || StringTools.countMatches(keyToInspect, "]") != 1 ) { throw new SpecException( "Invalid key:" + origKey + " has too many [] references."); } return new ArrayPathElement( elementKey ); } else if ( keyToInspect.contains( "&" ) ) { if ( keyToInspect.contains("*") ) { throw new SpecException( "Invalid key:" + origKey + ", Can't mix * with & ) "); } return new AmpPathElement( elementKey ); } else if ( keyToInspect.contains("*" ) ) { int numOfStars = StringTools.countMatches(keyToInspect, "*"); if(numOfStars == 1){ return new StarSinglePathElement( elementKey ); } else if(numOfStars == 2){ return new StarDoublePathElement( elementKey ); } else { return new StarRegexPathElement( elementKey ); } } else if ( keyToInspect.contains("#" ) ) { return new HashPathElement( elementKey ); } else { return new LiteralPathElement( elementKey ); } }
[ "public", "static", "PathElement", "parseSingleKeyLHS", "(", "String", "origKey", ")", "{", "String", "elementKey", ";", "// the String to use to actually make Elements", "String", "keyToInspect", ";", "// the String to use to determine which kind of Element to create", "if", "(", "origKey", ".", "contains", "(", "\"\\\\\"", ")", ")", "{", "// only do the extra work of processing for escaped chars, if there is one.", "keyToInspect", "=", "removeEscapedValues", "(", "origKey", ")", ";", "elementKey", "=", "removeEscapeChars", "(", "origKey", ")", ";", "}", "else", "{", "keyToInspect", "=", "origKey", ";", "elementKey", "=", "origKey", ";", "}", "//// LHS single values", "if", "(", "\"@\"", ".", "equals", "(", "keyToInspect", ")", ")", "{", "return", "new", "AtPathElement", "(", "elementKey", ")", ";", "}", "else", "if", "(", "\"*\"", ".", "equals", "(", "keyToInspect", ")", ")", "{", "return", "new", "StarAllPathElement", "(", "elementKey", ")", ";", "}", "else", "if", "(", "keyToInspect", ".", "startsWith", "(", "\"[\"", ")", ")", "{", "if", "(", "StringTools", ".", "countMatches", "(", "keyToInspect", ",", "\"[\"", ")", "!=", "1", "||", "StringTools", ".", "countMatches", "(", "keyToInspect", ",", "\"]\"", ")", "!=", "1", ")", "{", "throw", "new", "SpecException", "(", "\"Invalid key:\"", "+", "origKey", "+", "\" has too many [] references.\"", ")", ";", "}", "return", "new", "ArrayPathElement", "(", "elementKey", ")", ";", "}", "//// LHS multiple values", "else", "if", "(", "keyToInspect", ".", "startsWith", "(", "\"@\"", ")", "||", "keyToInspect", ".", "contains", "(", "\"@(\"", ")", ")", "{", "// The traspose path element gets the origKey so that it has it's escapes.", "return", "TransposePathElement", ".", "parse", "(", "origKey", ")", ";", "}", "else", "if", "(", "keyToInspect", ".", "contains", "(", "\"@\"", ")", ")", "{", "throw", "new", "SpecException", "(", "\"Invalid key:\"", "+", "origKey", "+", "\" can not have an @ other than at the front.\"", ")", ";", "}", "else", "if", "(", "keyToInspect", ".", "contains", "(", "\"$\"", ")", ")", "{", "return", "new", "DollarPathElement", "(", "elementKey", ")", ";", "}", "else", "if", "(", "keyToInspect", ".", "contains", "(", "\"[\"", ")", ")", "{", "if", "(", "StringTools", ".", "countMatches", "(", "keyToInspect", ",", "\"[\"", ")", "!=", "1", "||", "StringTools", ".", "countMatches", "(", "keyToInspect", ",", "\"]\"", ")", "!=", "1", ")", "{", "throw", "new", "SpecException", "(", "\"Invalid key:\"", "+", "origKey", "+", "\" has too many [] references.\"", ")", ";", "}", "return", "new", "ArrayPathElement", "(", "elementKey", ")", ";", "}", "else", "if", "(", "keyToInspect", ".", "contains", "(", "\"&\"", ")", ")", "{", "if", "(", "keyToInspect", ".", "contains", "(", "\"*\"", ")", ")", "{", "throw", "new", "SpecException", "(", "\"Invalid key:\"", "+", "origKey", "+", "\", Can't mix * with & ) \"", ")", ";", "}", "return", "new", "AmpPathElement", "(", "elementKey", ")", ";", "}", "else", "if", "(", "keyToInspect", ".", "contains", "(", "\"*\"", ")", ")", "{", "int", "numOfStars", "=", "StringTools", ".", "countMatches", "(", "keyToInspect", ",", "\"*\"", ")", ";", "if", "(", "numOfStars", "==", "1", ")", "{", "return", "new", "StarSinglePathElement", "(", "elementKey", ")", ";", "}", "else", "if", "(", "numOfStars", "==", "2", ")", "{", "return", "new", "StarDoublePathElement", "(", "elementKey", ")", ";", "}", "else", "{", "return", "new", "StarRegexPathElement", "(", "elementKey", ")", ";", "}", "}", "else", "if", "(", "keyToInspect", ".", "contains", "(", "\"#\"", ")", ")", "{", "return", "new", "HashPathElement", "(", "elementKey", ")", ";", "}", "else", "{", "return", "new", "LiteralPathElement", "(", "elementKey", ")", ";", "}", "}" ]
Visible for Testing. Inspects the key in a particular order to determine the correct sublass of PathElement to create. @param origKey String that should represent a single PathElement @return a concrete implementation of PathElement
[ "Visible", "for", "Testing", "." ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/common/PathElementBuilder.java#L74-L151
27,827
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/common/PathElementBuilder.java
PathElementBuilder.parseDotNotationRHS
public static List<PathElement> parseDotNotationRHS( String dotNotation ) { String fixedNotation = fixLeadingBracketSugar( dotNotation ); List<String> pathStrs = parseDotNotation( new LinkedList<String>(), stringIterator( fixedNotation ), dotNotation ); return parseList( pathStrs, dotNotation ); }
java
public static List<PathElement> parseDotNotationRHS( String dotNotation ) { String fixedNotation = fixLeadingBracketSugar( dotNotation ); List<String> pathStrs = parseDotNotation( new LinkedList<String>(), stringIterator( fixedNotation ), dotNotation ); return parseList( pathStrs, dotNotation ); }
[ "public", "static", "List", "<", "PathElement", ">", "parseDotNotationRHS", "(", "String", "dotNotation", ")", "{", "String", "fixedNotation", "=", "fixLeadingBracketSugar", "(", "dotNotation", ")", ";", "List", "<", "String", ">", "pathStrs", "=", "parseDotNotation", "(", "new", "LinkedList", "<", "String", ">", "(", ")", ",", "stringIterator", "(", "fixedNotation", ")", ",", "dotNotation", ")", ";", "return", "parseList", "(", "pathStrs", ",", "dotNotation", ")", ";", "}" ]
Parse the dotNotation of the RHS.
[ "Parse", "the", "dotNotation", "of", "the", "RHS", "." ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/common/PathElementBuilder.java#L156-L161
27,828
bazaarvoice/jolt
cli/src/main/java/com/bazaarvoice/jolt/DiffyCliProcessor.java
DiffyCliProcessor.intializeSubCommand
@Override public void intializeSubCommand( Subparsers subparsers ) { Subparser diffyParser = subparsers.addParser( "diffy" ) .description( "Jolt CLI Diffy Tool. This tool will ingest two JSON inputs (from files or standard input) and " + "perform the Jolt Diffy operation to detect any differences. The program will return an exit code of " + "0 if no differences are found or a 1 if a difference is found or an error is encountered." ) .defaultHelp( true ); diffyParser.addArgument( "filePath1" ).help( "File path to feed to Input #1 for the Diffy operation. " + "This file should contain valid JSON." ) .type( Arguments.fileType().verifyExists().verifyIsFile().verifyCanRead() ); diffyParser.addArgument( "filePath2" ).help( "File path to feed to Input #2 for the Diffy operation. " + "This file should contain valid JSON. " + "If this argument is not specified then standard input will be used." ) .type( Arguments.fileType().verifyExists().verifyIsFile().verifyCanRead() ) .nargs( "?" ).setDefault( (File) null ); // these last two method calls make filePath2 optional diffyParser.addArgument( "-s" ).help( "Diffy will suppress output and run silently." ) .action( Arguments.storeTrue() ); diffyParser.addArgument( "-a" ).help( "Diffy will not consider array order when detecting differences" ) .action( Arguments.storeTrue() ); }
java
@Override public void intializeSubCommand( Subparsers subparsers ) { Subparser diffyParser = subparsers.addParser( "diffy" ) .description( "Jolt CLI Diffy Tool. This tool will ingest two JSON inputs (from files or standard input) and " + "perform the Jolt Diffy operation to detect any differences. The program will return an exit code of " + "0 if no differences are found or a 1 if a difference is found or an error is encountered." ) .defaultHelp( true ); diffyParser.addArgument( "filePath1" ).help( "File path to feed to Input #1 for the Diffy operation. " + "This file should contain valid JSON." ) .type( Arguments.fileType().verifyExists().verifyIsFile().verifyCanRead() ); diffyParser.addArgument( "filePath2" ).help( "File path to feed to Input #2 for the Diffy operation. " + "This file should contain valid JSON. " + "If this argument is not specified then standard input will be used." ) .type( Arguments.fileType().verifyExists().verifyIsFile().verifyCanRead() ) .nargs( "?" ).setDefault( (File) null ); // these last two method calls make filePath2 optional diffyParser.addArgument( "-s" ).help( "Diffy will suppress output and run silently." ) .action( Arguments.storeTrue() ); diffyParser.addArgument( "-a" ).help( "Diffy will not consider array order when detecting differences" ) .action( Arguments.storeTrue() ); }
[ "@", "Override", "public", "void", "intializeSubCommand", "(", "Subparsers", "subparsers", ")", "{", "Subparser", "diffyParser", "=", "subparsers", ".", "addParser", "(", "\"diffy\"", ")", ".", "description", "(", "\"Jolt CLI Diffy Tool. This tool will ingest two JSON inputs (from files or standard input) and \"", "+", "\"perform the Jolt Diffy operation to detect any differences. The program will return an exit code of \"", "+", "\"0 if no differences are found or a 1 if a difference is found or an error is encountered.\"", ")", ".", "defaultHelp", "(", "true", ")", ";", "diffyParser", ".", "addArgument", "(", "\"filePath1\"", ")", ".", "help", "(", "\"File path to feed to Input #1 for the Diffy operation. \"", "+", "\"This file should contain valid JSON.\"", ")", ".", "type", "(", "Arguments", ".", "fileType", "(", ")", ".", "verifyExists", "(", ")", ".", "verifyIsFile", "(", ")", ".", "verifyCanRead", "(", ")", ")", ";", "diffyParser", ".", "addArgument", "(", "\"filePath2\"", ")", ".", "help", "(", "\"File path to feed to Input #2 for the Diffy operation. \"", "+", "\"This file should contain valid JSON. \"", "+", "\"If this argument is not specified then standard input will be used.\"", ")", ".", "type", "(", "Arguments", ".", "fileType", "(", ")", ".", "verifyExists", "(", ")", ".", "verifyIsFile", "(", ")", ".", "verifyCanRead", "(", ")", ")", ".", "nargs", "(", "\"?\"", ")", ".", "setDefault", "(", "(", "File", ")", "null", ")", ";", "// these last two method calls make filePath2 optional", "diffyParser", ".", "addArgument", "(", "\"-s\"", ")", ".", "help", "(", "\"Diffy will suppress output and run silently.\"", ")", ".", "action", "(", "Arguments", ".", "storeTrue", "(", ")", ")", ";", "diffyParser", ".", "addArgument", "(", "\"-a\"", ")", ".", "help", "(", "\"Diffy will not consider array order when detecting differences\"", ")", ".", "action", "(", "Arguments", ".", "storeTrue", "(", ")", ")", ";", "}" ]
Initialize the arg parser for the Diffy sub command @param subparsers The Subparsers object to attach the new Subparser to
[ "Initialize", "the", "arg", "parser", "for", "the", "Diffy", "sub", "command" ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/cli/src/main/java/com/bazaarvoice/jolt/DiffyCliProcessor.java#L36-L57
27,829
bazaarvoice/jolt
cli/src/main/java/com/bazaarvoice/jolt/DiffyCliProcessor.java
DiffyCliProcessor.process
@Override public boolean process( Namespace ns ) { boolean suppressOutput = ns.getBoolean( "s" ); Object jsonObject1 = JoltCliUtilities.createJsonObjectFromFile( (File) ns.get( "filePath1" ), suppressOutput ); File file = ns.get( "filePath2" ); Object jsonObject2 = JoltCliUtilities.readJsonInput( file, suppressOutput ); Diffy diffy; if ( ns.getBoolean( "a" ) ) { diffy = new ArrayOrderObliviousDiffy(); } else { diffy = new Diffy(); } Diffy.Result result = diffy.diff( jsonObject1, jsonObject2 ); if ( result.isEmpty() ) { JoltCliUtilities.printToStandardOut( "Diffy found no differences", suppressOutput ); return true; } else { try { JoltCliUtilities.printToStandardOut( "Differences found. Input #1 contained this:\n" + JsonUtils.toPrettyJsonString( result.expected ) + "\n" + "Input #2 contained this:\n" + JsonUtils.toPrettyJsonString( result.actual ), suppressOutput ); } catch ( Exception e ) { JoltCliUtilities.printToStandardOut( "Differences found, but diffy encountered an error while writing the result.", suppressOutput ); } return false; } }
java
@Override public boolean process( Namespace ns ) { boolean suppressOutput = ns.getBoolean( "s" ); Object jsonObject1 = JoltCliUtilities.createJsonObjectFromFile( (File) ns.get( "filePath1" ), suppressOutput ); File file = ns.get( "filePath2" ); Object jsonObject2 = JoltCliUtilities.readJsonInput( file, suppressOutput ); Diffy diffy; if ( ns.getBoolean( "a" ) ) { diffy = new ArrayOrderObliviousDiffy(); } else { diffy = new Diffy(); } Diffy.Result result = diffy.diff( jsonObject1, jsonObject2 ); if ( result.isEmpty() ) { JoltCliUtilities.printToStandardOut( "Diffy found no differences", suppressOutput ); return true; } else { try { JoltCliUtilities.printToStandardOut( "Differences found. Input #1 contained this:\n" + JsonUtils.toPrettyJsonString( result.expected ) + "\n" + "Input #2 contained this:\n" + JsonUtils.toPrettyJsonString( result.actual ), suppressOutput ); } catch ( Exception e ) { JoltCliUtilities.printToStandardOut( "Differences found, but diffy encountered an error while writing the result.", suppressOutput ); } return false; } }
[ "@", "Override", "public", "boolean", "process", "(", "Namespace", "ns", ")", "{", "boolean", "suppressOutput", "=", "ns", ".", "getBoolean", "(", "\"s\"", ")", ";", "Object", "jsonObject1", "=", "JoltCliUtilities", ".", "createJsonObjectFromFile", "(", "(", "File", ")", "ns", ".", "get", "(", "\"filePath1\"", ")", ",", "suppressOutput", ")", ";", "File", "file", "=", "ns", ".", "get", "(", "\"filePath2\"", ")", ";", "Object", "jsonObject2", "=", "JoltCliUtilities", ".", "readJsonInput", "(", "file", ",", "suppressOutput", ")", ";", "Diffy", "diffy", ";", "if", "(", "ns", ".", "getBoolean", "(", "\"a\"", ")", ")", "{", "diffy", "=", "new", "ArrayOrderObliviousDiffy", "(", ")", ";", "}", "else", "{", "diffy", "=", "new", "Diffy", "(", ")", ";", "}", "Diffy", ".", "Result", "result", "=", "diffy", ".", "diff", "(", "jsonObject1", ",", "jsonObject2", ")", ";", "if", "(", "result", ".", "isEmpty", "(", ")", ")", "{", "JoltCliUtilities", ".", "printToStandardOut", "(", "\"Diffy found no differences\"", ",", "suppressOutput", ")", ";", "return", "true", ";", "}", "else", "{", "try", "{", "JoltCliUtilities", ".", "printToStandardOut", "(", "\"Differences found. Input #1 contained this:\\n\"", "+", "JsonUtils", ".", "toPrettyJsonString", "(", "result", ".", "expected", ")", "+", "\"\\n\"", "+", "\"Input #2 contained this:\\n\"", "+", "JsonUtils", ".", "toPrettyJsonString", "(", "result", ".", "actual", ")", ",", "suppressOutput", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "JoltCliUtilities", ".", "printToStandardOut", "(", "\"Differences found, but diffy encountered an error while writing the result.\"", ",", "suppressOutput", ")", ";", "}", "return", "false", ";", "}", "}" ]
Process the Diffy Subcommand @param ns Namespace which contains parsed commandline arguments @return true if no differences are found, false if a difference is found or an error occurs
[ "Process", "the", "Diffy", "Subcommand" ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/cli/src/main/java/com/bazaarvoice/jolt/DiffyCliProcessor.java#L65-L97
27,830
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/common/SpecStringParser.java
SpecStringParser.parseDotNotation
public static List<String> parseDotNotation( List<String> pathStrings, Iterator<Character> iter, String dotNotationRef ) { if ( ! iter.hasNext() ) { return pathStrings; } // Leave the forward slashes, unless it precedes a "." // The way this works is always suppress the forward slashes, but add them back in if the next char is not a "." boolean prevIsEscape = false; boolean currIsEscape = false; StringBuilder sb = new StringBuilder(); char c; while( iter.hasNext() ) { c = iter.next(); currIsEscape = false; if ( c == '\\' && ! prevIsEscape ) { // current is Escape only if the char is escape, or // it is an Escape and the prior char was, then don't consider this one an escape currIsEscape = true; } if ( prevIsEscape && c != '.' && c != '\\') { sb.append( '\\' ); sb.append( c ); } else if( c == '@' ) { sb.append( '@' ); sb.append( parseAtPathElement( iter, dotNotationRef ) ); // there was a "[" seen but no "]" boolean isPartOfArray = sb.indexOf( "[" ) != -1 && sb.indexOf( "]" ) == -1; if ( ! isPartOfArray ) { pathStrings.add( sb.toString() ); sb = new StringBuilder(); } } else if ( c == '.' ) { if ( prevIsEscape ) { sb.append( '.' ); } else { if ( sb.length() != 0 ) { pathStrings.add( sb.toString() ); } return parseDotNotation( pathStrings, iter, dotNotationRef ); } } else if ( ! currIsEscape ) { sb.append( c ); } prevIsEscape = currIsEscape; } if ( sb.length() != 0 ) { pathStrings.add( sb.toString() ); } return pathStrings; }
java
public static List<String> parseDotNotation( List<String> pathStrings, Iterator<Character> iter, String dotNotationRef ) { if ( ! iter.hasNext() ) { return pathStrings; } // Leave the forward slashes, unless it precedes a "." // The way this works is always suppress the forward slashes, but add them back in if the next char is not a "." boolean prevIsEscape = false; boolean currIsEscape = false; StringBuilder sb = new StringBuilder(); char c; while( iter.hasNext() ) { c = iter.next(); currIsEscape = false; if ( c == '\\' && ! prevIsEscape ) { // current is Escape only if the char is escape, or // it is an Escape and the prior char was, then don't consider this one an escape currIsEscape = true; } if ( prevIsEscape && c != '.' && c != '\\') { sb.append( '\\' ); sb.append( c ); } else if( c == '@' ) { sb.append( '@' ); sb.append( parseAtPathElement( iter, dotNotationRef ) ); // there was a "[" seen but no "]" boolean isPartOfArray = sb.indexOf( "[" ) != -1 && sb.indexOf( "]" ) == -1; if ( ! isPartOfArray ) { pathStrings.add( sb.toString() ); sb = new StringBuilder(); } } else if ( c == '.' ) { if ( prevIsEscape ) { sb.append( '.' ); } else { if ( sb.length() != 0 ) { pathStrings.add( sb.toString() ); } return parseDotNotation( pathStrings, iter, dotNotationRef ); } } else if ( ! currIsEscape ) { sb.append( c ); } prevIsEscape = currIsEscape; } if ( sb.length() != 0 ) { pathStrings.add( sb.toString() ); } return pathStrings; }
[ "public", "static", "List", "<", "String", ">", "parseDotNotation", "(", "List", "<", "String", ">", "pathStrings", ",", "Iterator", "<", "Character", ">", "iter", ",", "String", "dotNotationRef", ")", "{", "if", "(", "!", "iter", ".", "hasNext", "(", ")", ")", "{", "return", "pathStrings", ";", "}", "// Leave the forward slashes, unless it precedes a \".\"", "// The way this works is always suppress the forward slashes, but add them back in if the next char is not a \".\"", "boolean", "prevIsEscape", "=", "false", ";", "boolean", "currIsEscape", "=", "false", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "char", "c", ";", "while", "(", "iter", ".", "hasNext", "(", ")", ")", "{", "c", "=", "iter", ".", "next", "(", ")", ";", "currIsEscape", "=", "false", ";", "if", "(", "c", "==", "'", "'", "&&", "!", "prevIsEscape", ")", "{", "// current is Escape only if the char is escape, or", "// it is an Escape and the prior char was, then don't consider this one an escape", "currIsEscape", "=", "true", ";", "}", "if", "(", "prevIsEscape", "&&", "c", "!=", "'", "'", "&&", "c", "!=", "'", "'", ")", "{", "sb", ".", "append", "(", "'", "'", ")", ";", "sb", ".", "append", "(", "c", ")", ";", "}", "else", "if", "(", "c", "==", "'", "'", ")", "{", "sb", ".", "append", "(", "'", "'", ")", ";", "sb", ".", "append", "(", "parseAtPathElement", "(", "iter", ",", "dotNotationRef", ")", ")", ";", "// there was a \"[\" seen but no \"]\"", "boolean", "isPartOfArray", "=", "sb", ".", "indexOf", "(", "\"[\"", ")", "!=", "-", "1", "&&", "sb", ".", "indexOf", "(", "\"]\"", ")", "==", "-", "1", ";", "if", "(", "!", "isPartOfArray", ")", "{", "pathStrings", ".", "add", "(", "sb", ".", "toString", "(", ")", ")", ";", "sb", "=", "new", "StringBuilder", "(", ")", ";", "}", "}", "else", "if", "(", "c", "==", "'", "'", ")", "{", "if", "(", "prevIsEscape", ")", "{", "sb", ".", "append", "(", "'", "'", ")", ";", "}", "else", "{", "if", "(", "sb", ".", "length", "(", ")", "!=", "0", ")", "{", "pathStrings", ".", "add", "(", "sb", ".", "toString", "(", ")", ")", ";", "}", "return", "parseDotNotation", "(", "pathStrings", ",", "iter", ",", "dotNotationRef", ")", ";", "}", "}", "else", "if", "(", "!", "currIsEscape", ")", "{", "sb", ".", "append", "(", "c", ")", ";", "}", "prevIsEscape", "=", "currIsEscape", ";", "}", "if", "(", "sb", ".", "length", "(", ")", "!=", "0", ")", "{", "pathStrings", ".", "add", "(", "sb", ".", "toString", "(", ")", ")", ";", "}", "return", "pathStrings", ";", "}" ]
Method that recursively parses a dotNotation String based on an iterator. This method will call out to parseAtPathElement @param pathStrings List to store parsed Strings that each represent a PathElement @param iter the iterator to pull characters from @param dotNotationRef the original dotNotation string used for error messages @return evaluated List<String> from dot notation string spec
[ "Method", "that", "recursively", "parses", "a", "dotNotation", "String", "based", "on", "an", "iterator", "." ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/common/SpecStringParser.java#L45-L109
27,831
bazaarvoice/jolt
jolt-core/src/main/java/com/bazaarvoice/jolt/common/SpecStringParser.java
SpecStringParser.removeEscapeChars
public static String removeEscapeChars( String origKey ) { StringBuilder sb = new StringBuilder(); boolean prevWasEscape = false; for ( char c : origKey.toCharArray() ) { if ( '\\' == c ) { if ( prevWasEscape ) { sb.append( c ); prevWasEscape = false; } else { prevWasEscape = true; } } else { sb.append( c ); prevWasEscape = false; } } return sb.toString(); }
java
public static String removeEscapeChars( String origKey ) { StringBuilder sb = new StringBuilder(); boolean prevWasEscape = false; for ( char c : origKey.toCharArray() ) { if ( '\\' == c ) { if ( prevWasEscape ) { sb.append( c ); prevWasEscape = false; } else { prevWasEscape = true; } } else { sb.append( c ); prevWasEscape = false; } } return sb.toString(); }
[ "public", "static", "String", "removeEscapeChars", "(", "String", "origKey", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "boolean", "prevWasEscape", "=", "false", ";", "for", "(", "char", "c", ":", "origKey", ".", "toCharArray", "(", ")", ")", "{", "if", "(", "'", "'", "==", "c", ")", "{", "if", "(", "prevWasEscape", ")", "{", "sb", ".", "append", "(", "c", ")", ";", "prevWasEscape", "=", "false", ";", "}", "else", "{", "prevWasEscape", "=", "true", ";", "}", "}", "else", "{", "sb", ".", "append", "(", "c", ")", ";", "prevWasEscape", "=", "false", ";", "}", "}", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
given "rating\\pants" -> "rating\pants" escape the escape char
[ "given", "rating", "\\\\", "pants", "-", ">", "rating", "\\", "pants", "escape", "the", "escape", "char" ]
4cf866a9f4222142da41b50dbcccce022a956bff
https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/common/SpecStringParser.java#L283-L304
27,832
apache/incubator-heron
heron/instance/src/java/org/apache/heron/instance/AbstractOutputCollector.java
AbstractOutputCollector.sendOutState
public void sendOutState(State<Serializable, Serializable> state, String checkpointId, boolean spillState, String location) { outputter.sendOutState(state, checkpointId, spillState, location); }
java
public void sendOutState(State<Serializable, Serializable> state, String checkpointId, boolean spillState, String location) { outputter.sendOutState(state, checkpointId, spillState, location); }
[ "public", "void", "sendOutState", "(", "State", "<", "Serializable", ",", "Serializable", ">", "state", ",", "String", "checkpointId", ",", "boolean", "spillState", ",", "String", "location", ")", "{", "outputter", ".", "sendOutState", "(", "state", ",", "checkpointId", ",", "spillState", ",", "location", ")", ";", "}" ]
Flush the states
[ "Flush", "the", "states" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/instance/src/java/org/apache/heron/instance/AbstractOutputCollector.java#L116-L121
27,833
apache/incubator-heron
storm-compatibility/src/java/org/apache/storm/task/GeneralTopologyContext.java
GeneralTopologyContext.getRawTopology
@SuppressWarnings("deprecation") public StormTopology getRawTopology() { StormTopology stormTopology = new StormTopology(); Map<String, SpoutSpec> spouts = new HashMap<>(); for (TopologyAPI.Spout spout : this.delegate.getRawTopology().getSpoutsList()) { spouts.put(spout.getComp().getName(), new SpoutSpec(spout)); } Map<String, Bolt> bolts = new HashMap<>(); for (TopologyAPI.Bolt bolt : this.delegate.getRawTopology().getBoltsList()) { bolts.put(bolt.getComp().getName(), new Bolt(bolt)); } stormTopology.set_spouts(spouts); stormTopology.set_bolts(bolts); return stormTopology; }
java
@SuppressWarnings("deprecation") public StormTopology getRawTopology() { StormTopology stormTopology = new StormTopology(); Map<String, SpoutSpec> spouts = new HashMap<>(); for (TopologyAPI.Spout spout : this.delegate.getRawTopology().getSpoutsList()) { spouts.put(spout.getComp().getName(), new SpoutSpec(spout)); } Map<String, Bolt> bolts = new HashMap<>(); for (TopologyAPI.Bolt bolt : this.delegate.getRawTopology().getBoltsList()) { bolts.put(bolt.getComp().getName(), new Bolt(bolt)); } stormTopology.set_spouts(spouts); stormTopology.set_bolts(bolts); return stormTopology; }
[ "@", "SuppressWarnings", "(", "\"deprecation\"", ")", "public", "StormTopology", "getRawTopology", "(", ")", "{", "StormTopology", "stormTopology", "=", "new", "StormTopology", "(", ")", ";", "Map", "<", "String", ",", "SpoutSpec", ">", "spouts", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "TopologyAPI", ".", "Spout", "spout", ":", "this", ".", "delegate", ".", "getRawTopology", "(", ")", ".", "getSpoutsList", "(", ")", ")", "{", "spouts", ".", "put", "(", "spout", ".", "getComp", "(", ")", ".", "getName", "(", ")", ",", "new", "SpoutSpec", "(", "spout", ")", ")", ";", "}", "Map", "<", "String", ",", "Bolt", ">", "bolts", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "TopologyAPI", ".", "Bolt", "bolt", ":", "this", ".", "delegate", ".", "getRawTopology", "(", ")", ".", "getBoltsList", "(", ")", ")", "{", "bolts", ".", "put", "(", "bolt", ".", "getComp", "(", ")", ".", "getName", "(", ")", ",", "new", "Bolt", "(", "bolt", ")", ")", ";", "}", "stormTopology", ".", "set_spouts", "(", "spouts", ")", ";", "stormTopology", ".", "set_bolts", "(", "bolts", ")", ";", "return", "stormTopology", ";", "}" ]
Gets the Thrift object representing the topology. @return the Thrift definition representing the topology
[ "Gets", "the", "Thrift", "object", "representing", "the", "topology", "." ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/storm-compatibility/src/java/org/apache/storm/task/GeneralTopologyContext.java#L70-L87
27,834
apache/incubator-heron
heron/simulator/src/java/org/apache/heron/simulator/executors/StreamExecutor.java
StreamExecutor.handleInstanceExecutor
public void handleInstanceExecutor() { for (InstanceExecutor executor : taskIdToInstanceExecutor.values()) { boolean isLocalSpout = spoutSets.contains(executor.getComponentName()); int taskId = executor.getTaskId(); int items = executor.getStreamOutQueue().size(); for (int i = 0; i < items; i++) { Message msg = executor.getStreamOutQueue().poll(); if (msg instanceof HeronTuples.HeronTupleSet) { HeronTuples.HeronTupleSet tupleSet = (HeronTuples.HeronTupleSet) msg; if (tupleSet.hasData()) { HeronTuples.HeronDataTupleSet d = tupleSet.getData(); TopologyAPI.StreamId streamId = d.getStream(); for (HeronTuples.HeronDataTuple tuple : d.getTuplesList()) { List<Integer> outTasks = this.topologyManager.getListToSend(streamId, tuple); outTasks.addAll(tuple.getDestTaskIdsList()); if (outTasks.isEmpty()) { LOG.severe("Nobody to send the tuple to"); } copyDataOutBound(taskId, isLocalSpout, streamId, tuple, outTasks); } } if (tupleSet.hasControl()) { HeronTuples.HeronControlTupleSet c = tupleSet.getControl(); for (HeronTuples.AckTuple ack : c.getAcksList()) { copyControlOutBound(tupleSet.getSrcTaskId(), ack, true); } for (HeronTuples.AckTuple fail : c.getFailsList()) { copyControlOutBound(tupleSet.getSrcTaskId(), fail, false); } } } } } }
java
public void handleInstanceExecutor() { for (InstanceExecutor executor : taskIdToInstanceExecutor.values()) { boolean isLocalSpout = spoutSets.contains(executor.getComponentName()); int taskId = executor.getTaskId(); int items = executor.getStreamOutQueue().size(); for (int i = 0; i < items; i++) { Message msg = executor.getStreamOutQueue().poll(); if (msg instanceof HeronTuples.HeronTupleSet) { HeronTuples.HeronTupleSet tupleSet = (HeronTuples.HeronTupleSet) msg; if (tupleSet.hasData()) { HeronTuples.HeronDataTupleSet d = tupleSet.getData(); TopologyAPI.StreamId streamId = d.getStream(); for (HeronTuples.HeronDataTuple tuple : d.getTuplesList()) { List<Integer> outTasks = this.topologyManager.getListToSend(streamId, tuple); outTasks.addAll(tuple.getDestTaskIdsList()); if (outTasks.isEmpty()) { LOG.severe("Nobody to send the tuple to"); } copyDataOutBound(taskId, isLocalSpout, streamId, tuple, outTasks); } } if (tupleSet.hasControl()) { HeronTuples.HeronControlTupleSet c = tupleSet.getControl(); for (HeronTuples.AckTuple ack : c.getAcksList()) { copyControlOutBound(tupleSet.getSrcTaskId(), ack, true); } for (HeronTuples.AckTuple fail : c.getFailsList()) { copyControlOutBound(tupleSet.getSrcTaskId(), fail, false); } } } } } }
[ "public", "void", "handleInstanceExecutor", "(", ")", "{", "for", "(", "InstanceExecutor", "executor", ":", "taskIdToInstanceExecutor", ".", "values", "(", ")", ")", "{", "boolean", "isLocalSpout", "=", "spoutSets", ".", "contains", "(", "executor", ".", "getComponentName", "(", ")", ")", ";", "int", "taskId", "=", "executor", ".", "getTaskId", "(", ")", ";", "int", "items", "=", "executor", ".", "getStreamOutQueue", "(", ")", ".", "size", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "items", ";", "i", "++", ")", "{", "Message", "msg", "=", "executor", ".", "getStreamOutQueue", "(", ")", ".", "poll", "(", ")", ";", "if", "(", "msg", "instanceof", "HeronTuples", ".", "HeronTupleSet", ")", "{", "HeronTuples", ".", "HeronTupleSet", "tupleSet", "=", "(", "HeronTuples", ".", "HeronTupleSet", ")", "msg", ";", "if", "(", "tupleSet", ".", "hasData", "(", ")", ")", "{", "HeronTuples", ".", "HeronDataTupleSet", "d", "=", "tupleSet", ".", "getData", "(", ")", ";", "TopologyAPI", ".", "StreamId", "streamId", "=", "d", ".", "getStream", "(", ")", ";", "for", "(", "HeronTuples", ".", "HeronDataTuple", "tuple", ":", "d", ".", "getTuplesList", "(", ")", ")", "{", "List", "<", "Integer", ">", "outTasks", "=", "this", ".", "topologyManager", ".", "getListToSend", "(", "streamId", ",", "tuple", ")", ";", "outTasks", ".", "addAll", "(", "tuple", ".", "getDestTaskIdsList", "(", ")", ")", ";", "if", "(", "outTasks", ".", "isEmpty", "(", ")", ")", "{", "LOG", ".", "severe", "(", "\"Nobody to send the tuple to\"", ")", ";", "}", "copyDataOutBound", "(", "taskId", ",", "isLocalSpout", ",", "streamId", ",", "tuple", ",", "outTasks", ")", ";", "}", "}", "if", "(", "tupleSet", ".", "hasControl", "(", ")", ")", "{", "HeronTuples", ".", "HeronControlTupleSet", "c", "=", "tupleSet", ".", "getControl", "(", ")", ";", "for", "(", "HeronTuples", ".", "AckTuple", "ack", ":", "c", ".", "getAcksList", "(", ")", ")", "{", "copyControlOutBound", "(", "tupleSet", ".", "getSrcTaskId", "(", ")", ",", "ack", ",", "true", ")", ";", "}", "for", "(", "HeronTuples", ".", "AckTuple", "fail", ":", "c", ".", "getFailsList", "(", ")", ")", "{", "copyControlOutBound", "(", "tupleSet", ".", "getSrcTaskId", "(", ")", ",", "fail", ",", "false", ")", ";", "}", "}", "}", "}", "}", "}" ]
Handle the execution of the instance
[ "Handle", "the", "execution", "of", "the", "instance" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/simulator/src/java/org/apache/heron/simulator/executors/StreamExecutor.java#L131-L172
27,835
apache/incubator-heron
heron/simulator/src/java/org/apache/heron/simulator/executors/StreamExecutor.java
StreamExecutor.isSendTuplesToInstance
protected boolean isSendTuplesToInstance(List<Integer> taskIds) { for (Integer taskId : taskIds) { if (taskIdToInstanceExecutor.get(taskId).getStreamInQueue().remainingCapacity() <= 0) { return false; } } return true; }
java
protected boolean isSendTuplesToInstance(List<Integer> taskIds) { for (Integer taskId : taskIds) { if (taskIdToInstanceExecutor.get(taskId).getStreamInQueue().remainingCapacity() <= 0) { return false; } } return true; }
[ "protected", "boolean", "isSendTuplesToInstance", "(", "List", "<", "Integer", ">", "taskIds", ")", "{", "for", "(", "Integer", "taskId", ":", "taskIds", ")", "{", "if", "(", "taskIdToInstanceExecutor", ".", "get", "(", "taskId", ")", ".", "getStreamInQueue", "(", ")", ".", "remainingCapacity", "(", ")", "<=", "0", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Check whether target destination task has free room to receive more tuples
[ "Check", "whether", "target", "destination", "task", "has", "free", "room", "to", "receive", "more", "tuples" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/simulator/src/java/org/apache/heron/simulator/executors/StreamExecutor.java#L175-L183
27,836
apache/incubator-heron
heron/simulator/src/java/org/apache/heron/simulator/executors/StreamExecutor.java
StreamExecutor.copyDataOutBound
protected void copyDataOutBound(int sourceTaskId, boolean isLocalSpout, TopologyAPI.StreamId streamId, HeronTuples.HeronDataTuple tuple, List<Integer> outTasks) { boolean firstIteration = true; boolean isAnchored = tuple.getRootsCount() > 0; for (Integer outTask : outTasks) { long tupleKey = tupleCache.addDataTuple(sourceTaskId, outTask, streamId, tuple, isAnchored); if (isAnchored) { // Anchored tuple if (isLocalSpout) { // This is from a local spout. We need to maintain xors if (firstIteration) { xorManager.create(sourceTaskId, tuple.getRoots(0).getKey(), tupleKey); } else { xorManager.anchor(sourceTaskId, tuple.getRoots(0).getKey(), tupleKey); } } else { // Anchored emits from local bolt for (HeronTuples.RootId rootId : tuple.getRootsList()) { HeronTuples.AckTuple t = HeronTuples.AckTuple.newBuilder(). addRoots(rootId). setAckedtuple(tupleKey). build(); tupleCache.addEmitTuple(sourceTaskId, rootId.getTaskid(), t); } } } firstIteration = false; } }
java
protected void copyDataOutBound(int sourceTaskId, boolean isLocalSpout, TopologyAPI.StreamId streamId, HeronTuples.HeronDataTuple tuple, List<Integer> outTasks) { boolean firstIteration = true; boolean isAnchored = tuple.getRootsCount() > 0; for (Integer outTask : outTasks) { long tupleKey = tupleCache.addDataTuple(sourceTaskId, outTask, streamId, tuple, isAnchored); if (isAnchored) { // Anchored tuple if (isLocalSpout) { // This is from a local spout. We need to maintain xors if (firstIteration) { xorManager.create(sourceTaskId, tuple.getRoots(0).getKey(), tupleKey); } else { xorManager.anchor(sourceTaskId, tuple.getRoots(0).getKey(), tupleKey); } } else { // Anchored emits from local bolt for (HeronTuples.RootId rootId : tuple.getRootsList()) { HeronTuples.AckTuple t = HeronTuples.AckTuple.newBuilder(). addRoots(rootId). setAckedtuple(tupleKey). build(); tupleCache.addEmitTuple(sourceTaskId, rootId.getTaskid(), t); } } } firstIteration = false; } }
[ "protected", "void", "copyDataOutBound", "(", "int", "sourceTaskId", ",", "boolean", "isLocalSpout", ",", "TopologyAPI", ".", "StreamId", "streamId", ",", "HeronTuples", ".", "HeronDataTuple", "tuple", ",", "List", "<", "Integer", ">", "outTasks", ")", "{", "boolean", "firstIteration", "=", "true", ";", "boolean", "isAnchored", "=", "tuple", ".", "getRootsCount", "(", ")", ">", "0", ";", "for", "(", "Integer", "outTask", ":", "outTasks", ")", "{", "long", "tupleKey", "=", "tupleCache", ".", "addDataTuple", "(", "sourceTaskId", ",", "outTask", ",", "streamId", ",", "tuple", ",", "isAnchored", ")", ";", "if", "(", "isAnchored", ")", "{", "// Anchored tuple", "if", "(", "isLocalSpout", ")", "{", "// This is from a local spout. We need to maintain xors", "if", "(", "firstIteration", ")", "{", "xorManager", ".", "create", "(", "sourceTaskId", ",", "tuple", ".", "getRoots", "(", "0", ")", ".", "getKey", "(", ")", ",", "tupleKey", ")", ";", "}", "else", "{", "xorManager", ".", "anchor", "(", "sourceTaskId", ",", "tuple", ".", "getRoots", "(", "0", ")", ".", "getKey", "(", ")", ",", "tupleKey", ")", ";", "}", "}", "else", "{", "// Anchored emits from local bolt", "for", "(", "HeronTuples", ".", "RootId", "rootId", ":", "tuple", ".", "getRootsList", "(", ")", ")", "{", "HeronTuples", ".", "AckTuple", "t", "=", "HeronTuples", ".", "AckTuple", ".", "newBuilder", "(", ")", ".", "addRoots", "(", "rootId", ")", ".", "setAckedtuple", "(", "tupleKey", ")", ".", "build", "(", ")", ";", "tupleCache", ".", "addEmitTuple", "(", "sourceTaskId", ",", "rootId", ".", "getTaskid", "(", ")", ",", "t", ")", ";", "}", "}", "}", "firstIteration", "=", "false", ";", "}", "}" ]
Process HeronDataTuple and insert it into cache
[ "Process", "HeronDataTuple", "and", "insert", "it", "into", "cache" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/simulator/src/java/org/apache/heron/simulator/executors/StreamExecutor.java#L186-L222
27,837
apache/incubator-heron
heron/simulator/src/java/org/apache/heron/simulator/executors/StreamExecutor.java
StreamExecutor.copyControlOutBound
protected void copyControlOutBound(int srcTaskId, HeronTuples.AckTuple control, boolean isSuccess) { for (HeronTuples.RootId rootId : control.getRootsList()) { HeronTuples.AckTuple t = HeronTuples.AckTuple.newBuilder(). addRoots(rootId). setAckedtuple(control.getAckedtuple()). build(); if (isSuccess) { tupleCache.addAckTuple(srcTaskId, rootId.getTaskid(), t); } else { tupleCache.addFailTuple(srcTaskId, rootId.getTaskid(), t); } } }
java
protected void copyControlOutBound(int srcTaskId, HeronTuples.AckTuple control, boolean isSuccess) { for (HeronTuples.RootId rootId : control.getRootsList()) { HeronTuples.AckTuple t = HeronTuples.AckTuple.newBuilder(). addRoots(rootId). setAckedtuple(control.getAckedtuple()). build(); if (isSuccess) { tupleCache.addAckTuple(srcTaskId, rootId.getTaskid(), t); } else { tupleCache.addFailTuple(srcTaskId, rootId.getTaskid(), t); } } }
[ "protected", "void", "copyControlOutBound", "(", "int", "srcTaskId", ",", "HeronTuples", ".", "AckTuple", "control", ",", "boolean", "isSuccess", ")", "{", "for", "(", "HeronTuples", ".", "RootId", "rootId", ":", "control", ".", "getRootsList", "(", ")", ")", "{", "HeronTuples", ".", "AckTuple", "t", "=", "HeronTuples", ".", "AckTuple", ".", "newBuilder", "(", ")", ".", "addRoots", "(", "rootId", ")", ".", "setAckedtuple", "(", "control", ".", "getAckedtuple", "(", ")", ")", ".", "build", "(", ")", ";", "if", "(", "isSuccess", ")", "{", "tupleCache", ".", "addAckTuple", "(", "srcTaskId", ",", "rootId", ".", "getTaskid", "(", ")", ",", "t", ")", ";", "}", "else", "{", "tupleCache", ".", "addFailTuple", "(", "srcTaskId", ",", "rootId", ".", "getTaskid", "(", ")", ",", "t", ")", ";", "}", "}", "}" ]
Process HeronAckTuple and insert it into cache
[ "Process", "HeronAckTuple", "and", "insert", "it", "into", "cache" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/simulator/src/java/org/apache/heron/simulator/executors/StreamExecutor.java#L225-L241
27,838
apache/incubator-heron
heron/simulator/src/java/org/apache/heron/simulator/executors/StreamExecutor.java
StreamExecutor.processAcksAndFails
protected void processAcksAndFails(int srcTaskId, int taskId, HeronTuples.HeronControlTupleSet controlTupleSet) { HeronTuples.HeronTupleSet.Builder out = HeronTuples.HeronTupleSet.newBuilder(); out.setSrcTaskId(srcTaskId); // First go over emits. This makes sure that new emits makes // a tuples stay alive before we process its acks for (HeronTuples.AckTuple emitTuple : controlTupleSet.getEmitsList()) { for (HeronTuples.RootId rootId : emitTuple.getRootsList()) { xorManager.anchor(taskId, rootId.getKey(), emitTuple.getAckedtuple()); } } // Then go over acks for (HeronTuples.AckTuple ackTuple : controlTupleSet.getAcksList()) { for (HeronTuples.RootId rootId : ackTuple.getRootsList()) { if (xorManager.anchor(taskId, rootId.getKey(), ackTuple.getAckedtuple())) { // This tuple tree is all over HeronTuples.AckTuple.Builder a = out.getControlBuilder().addAcksBuilder(); HeronTuples.RootId.Builder r = a.addRootsBuilder(); r.setKey(rootId.getKey()); r.setTaskid(taskId); a.setAckedtuple(0); // This is ignored xorManager.remove(taskId, rootId.getKey()); } } } // Now go over the fails for (HeronTuples.AckTuple failTuple : controlTupleSet.getFailsList()) { for (HeronTuples.RootId rootId : failTuple.getRootsList()) { if (xorManager.remove(taskId, rootId.getKey())) { // This tuple tree is failed HeronTuples.AckTuple.Builder f = out.getControlBuilder().addFailsBuilder(); HeronTuples.RootId.Builder r = f.addRootsBuilder(); r.setKey(rootId.getKey()); r.setTaskid(taskId); f.setAckedtuple(0); // This is ignored } } } // Check if we need to send ack tuples to spout task if (out.hasControl()) { sendMessageToInstance(taskId, out.build()); } }
java
protected void processAcksAndFails(int srcTaskId, int taskId, HeronTuples.HeronControlTupleSet controlTupleSet) { HeronTuples.HeronTupleSet.Builder out = HeronTuples.HeronTupleSet.newBuilder(); out.setSrcTaskId(srcTaskId); // First go over emits. This makes sure that new emits makes // a tuples stay alive before we process its acks for (HeronTuples.AckTuple emitTuple : controlTupleSet.getEmitsList()) { for (HeronTuples.RootId rootId : emitTuple.getRootsList()) { xorManager.anchor(taskId, rootId.getKey(), emitTuple.getAckedtuple()); } } // Then go over acks for (HeronTuples.AckTuple ackTuple : controlTupleSet.getAcksList()) { for (HeronTuples.RootId rootId : ackTuple.getRootsList()) { if (xorManager.anchor(taskId, rootId.getKey(), ackTuple.getAckedtuple())) { // This tuple tree is all over HeronTuples.AckTuple.Builder a = out.getControlBuilder().addAcksBuilder(); HeronTuples.RootId.Builder r = a.addRootsBuilder(); r.setKey(rootId.getKey()); r.setTaskid(taskId); a.setAckedtuple(0); // This is ignored xorManager.remove(taskId, rootId.getKey()); } } } // Now go over the fails for (HeronTuples.AckTuple failTuple : controlTupleSet.getFailsList()) { for (HeronTuples.RootId rootId : failTuple.getRootsList()) { if (xorManager.remove(taskId, rootId.getKey())) { // This tuple tree is failed HeronTuples.AckTuple.Builder f = out.getControlBuilder().addFailsBuilder(); HeronTuples.RootId.Builder r = f.addRootsBuilder(); r.setKey(rootId.getKey()); r.setTaskid(taskId); f.setAckedtuple(0); // This is ignored } } } // Check if we need to send ack tuples to spout task if (out.hasControl()) { sendMessageToInstance(taskId, out.build()); } }
[ "protected", "void", "processAcksAndFails", "(", "int", "srcTaskId", ",", "int", "taskId", ",", "HeronTuples", ".", "HeronControlTupleSet", "controlTupleSet", ")", "{", "HeronTuples", ".", "HeronTupleSet", ".", "Builder", "out", "=", "HeronTuples", ".", "HeronTupleSet", ".", "newBuilder", "(", ")", ";", "out", ".", "setSrcTaskId", "(", "srcTaskId", ")", ";", "// First go over emits. This makes sure that new emits makes", "// a tuples stay alive before we process its acks", "for", "(", "HeronTuples", ".", "AckTuple", "emitTuple", ":", "controlTupleSet", ".", "getEmitsList", "(", ")", ")", "{", "for", "(", "HeronTuples", ".", "RootId", "rootId", ":", "emitTuple", ".", "getRootsList", "(", ")", ")", "{", "xorManager", ".", "anchor", "(", "taskId", ",", "rootId", ".", "getKey", "(", ")", ",", "emitTuple", ".", "getAckedtuple", "(", ")", ")", ";", "}", "}", "// Then go over acks", "for", "(", "HeronTuples", ".", "AckTuple", "ackTuple", ":", "controlTupleSet", ".", "getAcksList", "(", ")", ")", "{", "for", "(", "HeronTuples", ".", "RootId", "rootId", ":", "ackTuple", ".", "getRootsList", "(", ")", ")", "{", "if", "(", "xorManager", ".", "anchor", "(", "taskId", ",", "rootId", ".", "getKey", "(", ")", ",", "ackTuple", ".", "getAckedtuple", "(", ")", ")", ")", "{", "// This tuple tree is all over", "HeronTuples", ".", "AckTuple", ".", "Builder", "a", "=", "out", ".", "getControlBuilder", "(", ")", ".", "addAcksBuilder", "(", ")", ";", "HeronTuples", ".", "RootId", ".", "Builder", "r", "=", "a", ".", "addRootsBuilder", "(", ")", ";", "r", ".", "setKey", "(", "rootId", ".", "getKey", "(", ")", ")", ";", "r", ".", "setTaskid", "(", "taskId", ")", ";", "a", ".", "setAckedtuple", "(", "0", ")", ";", "// This is ignored", "xorManager", ".", "remove", "(", "taskId", ",", "rootId", ".", "getKey", "(", ")", ")", ";", "}", "}", "}", "// Now go over the fails", "for", "(", "HeronTuples", ".", "AckTuple", "failTuple", ":", "controlTupleSet", ".", "getFailsList", "(", ")", ")", "{", "for", "(", "HeronTuples", ".", "RootId", "rootId", ":", "failTuple", ".", "getRootsList", "(", ")", ")", "{", "if", "(", "xorManager", ".", "remove", "(", "taskId", ",", "rootId", ".", "getKey", "(", ")", ")", ")", "{", "// This tuple tree is failed", "HeronTuples", ".", "AckTuple", ".", "Builder", "f", "=", "out", ".", "getControlBuilder", "(", ")", ".", "addFailsBuilder", "(", ")", ";", "HeronTuples", ".", "RootId", ".", "Builder", "r", "=", "f", ".", "addRootsBuilder", "(", ")", ";", "r", ".", "setKey", "(", "rootId", ".", "getKey", "(", ")", ")", ";", "r", ".", "setTaskid", "(", "taskId", ")", ";", "f", ".", "setAckedtuple", "(", "0", ")", ";", "// This is ignored", "}", "}", "}", "// Check if we need to send ack tuples to spout task", "if", "(", "out", ".", "hasControl", "(", ")", ")", "{", "sendMessageToInstance", "(", "taskId", ",", "out", ".", "build", "(", ")", ")", ";", "}", "}" ]
Do the XOR control and send the ack tuples to instance if necessary
[ "Do", "the", "XOR", "control", "and", "send", "the", "ack", "tuples", "to", "instance", "if", "necessary" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/simulator/src/java/org/apache/heron/simulator/executors/StreamExecutor.java#L244-L297
27,839
apache/incubator-heron
heron/simulator/src/java/org/apache/heron/simulator/executors/StreamExecutor.java
StreamExecutor.drainCache
protected void drainCache() { // Route the tuples to correct places Map<Integer, List<HeronTuples.HeronTupleSet>> cache = tupleCache.getCache(); if (!isSendTuplesToInstance(new LinkedList<Integer>(cache.keySet()))) { // Check whether we could send tuples return; } for (Map.Entry<Integer, List<HeronTuples.HeronTupleSet>> entry : cache.entrySet()) { int taskId = entry.getKey(); for (HeronTuples.HeronTupleSet message : entry.getValue()) { sendInBound(taskId, message); } } // Reset the tupleCache tupleCache.clear(); }
java
protected void drainCache() { // Route the tuples to correct places Map<Integer, List<HeronTuples.HeronTupleSet>> cache = tupleCache.getCache(); if (!isSendTuplesToInstance(new LinkedList<Integer>(cache.keySet()))) { // Check whether we could send tuples return; } for (Map.Entry<Integer, List<HeronTuples.HeronTupleSet>> entry : cache.entrySet()) { int taskId = entry.getKey(); for (HeronTuples.HeronTupleSet message : entry.getValue()) { sendInBound(taskId, message); } } // Reset the tupleCache tupleCache.clear(); }
[ "protected", "void", "drainCache", "(", ")", "{", "// Route the tuples to correct places", "Map", "<", "Integer", ",", "List", "<", "HeronTuples", ".", "HeronTupleSet", ">", ">", "cache", "=", "tupleCache", ".", "getCache", "(", ")", ";", "if", "(", "!", "isSendTuplesToInstance", "(", "new", "LinkedList", "<", "Integer", ">", "(", "cache", ".", "keySet", "(", ")", ")", ")", ")", "{", "// Check whether we could send tuples", "return", ";", "}", "for", "(", "Map", ".", "Entry", "<", "Integer", ",", "List", "<", "HeronTuples", ".", "HeronTupleSet", ">", ">", "entry", ":", "cache", ".", "entrySet", "(", ")", ")", "{", "int", "taskId", "=", "entry", ".", "getKey", "(", ")", ";", "for", "(", "HeronTuples", ".", "HeronTupleSet", "message", ":", "entry", ".", "getValue", "(", ")", ")", "{", "sendInBound", "(", "taskId", ",", "message", ")", ";", "}", "}", "// Reset the tupleCache", "tupleCache", ".", "clear", "(", ")", ";", "}" ]
Drain the TupleCache if there are room in destination tasks
[ "Drain", "the", "TupleCache", "if", "there", "are", "room", "in", "destination", "tasks" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/simulator/src/java/org/apache/heron/simulator/executors/StreamExecutor.java#L300-L318
27,840
apache/incubator-heron
heron/simulator/src/java/org/apache/heron/simulator/executors/StreamExecutor.java
StreamExecutor.sendInBound
protected void sendInBound(int taskId, HeronTuples.HeronTupleSet message) { if (message.hasData()) { sendMessageToInstance(taskId, message); } if (message.hasControl()) { processAcksAndFails(message.getSrcTaskId(), taskId, message.getControl()); } }
java
protected void sendInBound(int taskId, HeronTuples.HeronTupleSet message) { if (message.hasData()) { sendMessageToInstance(taskId, message); } if (message.hasControl()) { processAcksAndFails(message.getSrcTaskId(), taskId, message.getControl()); } }
[ "protected", "void", "sendInBound", "(", "int", "taskId", ",", "HeronTuples", ".", "HeronTupleSet", "message", ")", "{", "if", "(", "message", ".", "hasData", "(", ")", ")", "{", "sendMessageToInstance", "(", "taskId", ",", "message", ")", ";", "}", "if", "(", "message", ".", "hasControl", "(", ")", ")", "{", "processAcksAndFails", "(", "message", ".", "getSrcTaskId", "(", ")", ",", "taskId", ",", "message", ".", "getControl", "(", ")", ")", ";", "}", "}" ]
Send Stream to instance
[ "Send", "Stream", "to", "instance" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/simulator/src/java/org/apache/heron/simulator/executors/StreamExecutor.java#L321-L329
27,841
apache/incubator-heron
heron/simulator/src/java/org/apache/heron/simulator/executors/StreamExecutor.java
StreamExecutor.sendMessageToInstance
protected void sendMessageToInstance(int taskId, HeronTuples.HeronTupleSet message) { taskIdToInstanceExecutor.get(taskId).getStreamInQueue().offer(message); }
java
protected void sendMessageToInstance(int taskId, HeronTuples.HeronTupleSet message) { taskIdToInstanceExecutor.get(taskId).getStreamInQueue().offer(message); }
[ "protected", "void", "sendMessageToInstance", "(", "int", "taskId", ",", "HeronTuples", ".", "HeronTupleSet", "message", ")", "{", "taskIdToInstanceExecutor", ".", "get", "(", "taskId", ")", ".", "getStreamInQueue", "(", ")", ".", "offer", "(", "message", ")", ";", "}" ]
Send one message to target task
[ "Send", "one", "message", "to", "target", "task" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/simulator/src/java/org/apache/heron/simulator/executors/StreamExecutor.java#L332-L334
27,842
apache/incubator-heron
heron/packing/src/java/org/apache/heron/packing/utils/PackingUtils.java
PackingUtils.getComponentResourceMap
public static Map<String, Resource> getComponentResourceMap( Set<String> components, Map<String, ByteAmount> componentRamMap, Map<String, Double> componentCpuMap, Map<String, ByteAmount> componentDiskMap, Resource defaultInstanceResource) { Map<String, Resource> componentResourceMap = new HashMap<>(); for (String component : components) { ByteAmount instanceRam = componentRamMap.getOrDefault(component, defaultInstanceResource.getRam()); double instanceCpu = componentCpuMap.getOrDefault(component, defaultInstanceResource.getCpu()); ByteAmount instanceDisk = componentDiskMap.getOrDefault(component, defaultInstanceResource.getDisk()); componentResourceMap.put(component, new Resource(instanceCpu, instanceRam, instanceDisk)); } return componentResourceMap; }
java
public static Map<String, Resource> getComponentResourceMap( Set<String> components, Map<String, ByteAmount> componentRamMap, Map<String, Double> componentCpuMap, Map<String, ByteAmount> componentDiskMap, Resource defaultInstanceResource) { Map<String, Resource> componentResourceMap = new HashMap<>(); for (String component : components) { ByteAmount instanceRam = componentRamMap.getOrDefault(component, defaultInstanceResource.getRam()); double instanceCpu = componentCpuMap.getOrDefault(component, defaultInstanceResource.getCpu()); ByteAmount instanceDisk = componentDiskMap.getOrDefault(component, defaultInstanceResource.getDisk()); componentResourceMap.put(component, new Resource(instanceCpu, instanceRam, instanceDisk)); } return componentResourceMap; }
[ "public", "static", "Map", "<", "String", ",", "Resource", ">", "getComponentResourceMap", "(", "Set", "<", "String", ">", "components", ",", "Map", "<", "String", ",", "ByteAmount", ">", "componentRamMap", ",", "Map", "<", "String", ",", "Double", ">", "componentCpuMap", ",", "Map", "<", "String", ",", "ByteAmount", ">", "componentDiskMap", ",", "Resource", "defaultInstanceResource", ")", "{", "Map", "<", "String", ",", "Resource", ">", "componentResourceMap", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "String", "component", ":", "components", ")", "{", "ByteAmount", "instanceRam", "=", "componentRamMap", ".", "getOrDefault", "(", "component", ",", "defaultInstanceResource", ".", "getRam", "(", ")", ")", ";", "double", "instanceCpu", "=", "componentCpuMap", ".", "getOrDefault", "(", "component", ",", "defaultInstanceResource", ".", "getCpu", "(", ")", ")", ";", "ByteAmount", "instanceDisk", "=", "componentDiskMap", ".", "getOrDefault", "(", "component", ",", "defaultInstanceResource", ".", "getDisk", "(", ")", ")", ";", "componentResourceMap", ".", "put", "(", "component", ",", "new", "Resource", "(", "instanceCpu", ",", "instanceRam", ",", "instanceDisk", ")", ")", ";", "}", "return", "componentResourceMap", ";", "}" ]
Compose the component resource map by reading from user configs or default @param components component names @param componentRamMap user configured component ram map @param componentCpuMap user configured component cpu map @param componentDiskMap user configured component disk map @param defaultInstanceResource default instance resources @return component resource map
[ "Compose", "the", "component", "resource", "map", "by", "reading", "from", "user", "configs", "or", "default" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/packing/src/java/org/apache/heron/packing/utils/PackingUtils.java#L58-L76
27,843
apache/incubator-heron
heron/packing/src/java/org/apache/heron/packing/utils/PackingUtils.java
PackingUtils.getComponentsToScale
public static Map<String, Integer> getComponentsToScale(Map<String, Integer> componentChanges, ScalingDirection scalingDirection) { Map<String, Integer> componentsToScale = new HashMap<String, Integer>(); for (String component : componentChanges.keySet()) { int parallelismChange = componentChanges.get(component); if (scalingDirection.includes(parallelismChange)) { componentsToScale.put(component, parallelismChange); } } return componentsToScale; }
java
public static Map<String, Integer> getComponentsToScale(Map<String, Integer> componentChanges, ScalingDirection scalingDirection) { Map<String, Integer> componentsToScale = new HashMap<String, Integer>(); for (String component : componentChanges.keySet()) { int parallelismChange = componentChanges.get(component); if (scalingDirection.includes(parallelismChange)) { componentsToScale.put(component, parallelismChange); } } return componentsToScale; }
[ "public", "static", "Map", "<", "String", ",", "Integer", ">", "getComponentsToScale", "(", "Map", "<", "String", ",", "Integer", ">", "componentChanges", ",", "ScalingDirection", "scalingDirection", ")", "{", "Map", "<", "String", ",", "Integer", ">", "componentsToScale", "=", "new", "HashMap", "<", "String", ",", "Integer", ">", "(", ")", ";", "for", "(", "String", "component", ":", "componentChanges", ".", "keySet", "(", ")", ")", "{", "int", "parallelismChange", "=", "componentChanges", ".", "get", "(", "component", ")", ";", "if", "(", "scalingDirection", ".", "includes", "(", "parallelismChange", ")", ")", "{", "componentsToScale", ".", "put", "(", "component", ",", "parallelismChange", ")", ";", "}", "}", "return", "componentsToScale", ";", "}" ]
Identifies which components need to be scaled given specific scaling direction @return Map &lt; component name, scale factor &gt;
[ "Identifies", "which", "components", "need", "to", "be", "scaled", "given", "specific", "scaling", "direction" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/packing/src/java/org/apache/heron/packing/utils/PackingUtils.java#L111-L121
27,844
apache/incubator-heron
heron/packing/src/java/org/apache/heron/packing/utils/PackingUtils.java
PackingUtils.computeTotalResourceChange
public static Resource computeTotalResourceChange(TopologyAPI.Topology topology, Map<String, Integer> componentChanges, Resource defaultInstanceResources, ScalingDirection scalingDirection) { double cpu = 0; ByteAmount ram = ByteAmount.ZERO; ByteAmount disk = ByteAmount.ZERO; Map<String, ByteAmount> ramMap = TopologyUtils.getComponentRamMapConfig(topology); Map<String, Integer> componentsToScale = PackingUtils.getComponentsToScale( componentChanges, scalingDirection); for (String component : componentsToScale.keySet()) { int parallelismChange = Math.abs(componentChanges.get(component)); cpu += parallelismChange * defaultInstanceResources.getCpu(); disk = disk.plus(defaultInstanceResources.getDisk().multiply(parallelismChange)); if (ramMap.containsKey(component)) { ram = ram.plus(ramMap.get(component).multiply(parallelismChange)); } else { ram = ram.plus(defaultInstanceResources.getRam().multiply(parallelismChange)); } } return new Resource(cpu, ram, disk); }
java
public static Resource computeTotalResourceChange(TopologyAPI.Topology topology, Map<String, Integer> componentChanges, Resource defaultInstanceResources, ScalingDirection scalingDirection) { double cpu = 0; ByteAmount ram = ByteAmount.ZERO; ByteAmount disk = ByteAmount.ZERO; Map<String, ByteAmount> ramMap = TopologyUtils.getComponentRamMapConfig(topology); Map<String, Integer> componentsToScale = PackingUtils.getComponentsToScale( componentChanges, scalingDirection); for (String component : componentsToScale.keySet()) { int parallelismChange = Math.abs(componentChanges.get(component)); cpu += parallelismChange * defaultInstanceResources.getCpu(); disk = disk.plus(defaultInstanceResources.getDisk().multiply(parallelismChange)); if (ramMap.containsKey(component)) { ram = ram.plus(ramMap.get(component).multiply(parallelismChange)); } else { ram = ram.plus(defaultInstanceResources.getRam().multiply(parallelismChange)); } } return new Resource(cpu, ram, disk); }
[ "public", "static", "Resource", "computeTotalResourceChange", "(", "TopologyAPI", ".", "Topology", "topology", ",", "Map", "<", "String", ",", "Integer", ">", "componentChanges", ",", "Resource", "defaultInstanceResources", ",", "ScalingDirection", "scalingDirection", ")", "{", "double", "cpu", "=", "0", ";", "ByteAmount", "ram", "=", "ByteAmount", ".", "ZERO", ";", "ByteAmount", "disk", "=", "ByteAmount", ".", "ZERO", ";", "Map", "<", "String", ",", "ByteAmount", ">", "ramMap", "=", "TopologyUtils", ".", "getComponentRamMapConfig", "(", "topology", ")", ";", "Map", "<", "String", ",", "Integer", ">", "componentsToScale", "=", "PackingUtils", ".", "getComponentsToScale", "(", "componentChanges", ",", "scalingDirection", ")", ";", "for", "(", "String", "component", ":", "componentsToScale", ".", "keySet", "(", ")", ")", "{", "int", "parallelismChange", "=", "Math", ".", "abs", "(", "componentChanges", ".", "get", "(", "component", ")", ")", ";", "cpu", "+=", "parallelismChange", "*", "defaultInstanceResources", ".", "getCpu", "(", ")", ";", "disk", "=", "disk", ".", "plus", "(", "defaultInstanceResources", ".", "getDisk", "(", ")", ".", "multiply", "(", "parallelismChange", ")", ")", ";", "if", "(", "ramMap", ".", "containsKey", "(", "component", ")", ")", "{", "ram", "=", "ram", ".", "plus", "(", "ramMap", ".", "get", "(", "component", ")", ".", "multiply", "(", "parallelismChange", ")", ")", ";", "}", "else", "{", "ram", "=", "ram", ".", "plus", "(", "defaultInstanceResources", ".", "getRam", "(", ")", ".", "multiply", "(", "parallelismChange", ")", ")", ";", "}", "}", "return", "new", "Resource", "(", "cpu", ",", "ram", ",", "disk", ")", ";", "}" ]
Identifies the resources reclaimed by the components that will be scaled down @return Total resources reclaimed
[ "Identifies", "the", "resources", "reclaimed", "by", "the", "components", "that", "will", "be", "scaled", "down" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/packing/src/java/org/apache/heron/packing/utils/PackingUtils.java#L128-L149
27,845
apache/incubator-heron
heron/scheduler-core/src/java/org/apache/heron/scheduler/RuntimeManagerMain.java
RuntimeManagerMain.constructHelpOptions
private static Options constructHelpOptions() { Options options = new Options(); Option help = Option.builder("h") .desc("List all options and their description") .longOpt("help") .build(); options.addOption(help); return options; }
java
private static Options constructHelpOptions() { Options options = new Options(); Option help = Option.builder("h") .desc("List all options and their description") .longOpt("help") .build(); options.addOption(help); return options; }
[ "private", "static", "Options", "constructHelpOptions", "(", ")", "{", "Options", "options", "=", "new", "Options", "(", ")", ";", "Option", "help", "=", "Option", ".", "builder", "(", "\"h\"", ")", ".", "desc", "(", "\"List all options and their description\"", ")", ".", "longOpt", "(", "\"help\"", ")", ".", "build", "(", ")", ";", "options", ".", "addOption", "(", "help", ")", ";", "return", "options", ";", "}" ]
construct command line help options
[ "construct", "command", "line", "help", "options" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/scheduler-core/src/java/org/apache/heron/scheduler/RuntimeManagerMain.java#L213-L222
27,846
apache/incubator-heron
heron/scheduler-core/src/java/org/apache/heron/scheduler/RuntimeManagerMain.java
RuntimeManagerMain.manageTopology
public void manageTopology() throws TopologyRuntimeManagementException, TMasterException, PackingException { String topologyName = Context.topologyName(config); // 1. Do prepare work // create an instance of state manager String statemgrClass = Context.stateManagerClass(config); IStateManager statemgr; try { statemgr = ReflectionUtils.newInstance(statemgrClass); } catch (IllegalAccessException | InstantiationException | ClassNotFoundException e) { throw new TopologyRuntimeManagementException(String.format( "Failed to instantiate state manager class '%s'", statemgrClass), e); } // Put it in a try block so that we can always clean resources try { // initialize the statemgr statemgr.initialize(config); // TODO(mfu): timeout should read from config SchedulerStateManagerAdaptor adaptor = new SchedulerStateManagerAdaptor(statemgr, 5000); boolean hasExecutionData = validateRuntimeManage(adaptor, topologyName); // 2. Try to manage topology if valid // invoke the appropriate command to manage the topology LOG.log(Level.FINE, "Topology: {0} to be {1}ed", new Object[]{topologyName, command}); // build the runtime config Config runtime = Config.newBuilder() .put(Key.TOPOLOGY_NAME, Context.topologyName(config)) .put(Key.SCHEDULER_STATE_MANAGER_ADAPTOR, adaptor) .build(); // Create a ISchedulerClient basing on the config ISchedulerClient schedulerClient = getSchedulerClient(runtime); callRuntimeManagerRunner(runtime, schedulerClient, !hasExecutionData); } finally { // 3. Do post work basing on the result // Currently nothing to do here // 4. Close the resources SysUtils.closeIgnoringExceptions(statemgr); } }
java
public void manageTopology() throws TopologyRuntimeManagementException, TMasterException, PackingException { String topologyName = Context.topologyName(config); // 1. Do prepare work // create an instance of state manager String statemgrClass = Context.stateManagerClass(config); IStateManager statemgr; try { statemgr = ReflectionUtils.newInstance(statemgrClass); } catch (IllegalAccessException | InstantiationException | ClassNotFoundException e) { throw new TopologyRuntimeManagementException(String.format( "Failed to instantiate state manager class '%s'", statemgrClass), e); } // Put it in a try block so that we can always clean resources try { // initialize the statemgr statemgr.initialize(config); // TODO(mfu): timeout should read from config SchedulerStateManagerAdaptor adaptor = new SchedulerStateManagerAdaptor(statemgr, 5000); boolean hasExecutionData = validateRuntimeManage(adaptor, topologyName); // 2. Try to manage topology if valid // invoke the appropriate command to manage the topology LOG.log(Level.FINE, "Topology: {0} to be {1}ed", new Object[]{topologyName, command}); // build the runtime config Config runtime = Config.newBuilder() .put(Key.TOPOLOGY_NAME, Context.topologyName(config)) .put(Key.SCHEDULER_STATE_MANAGER_ADAPTOR, adaptor) .build(); // Create a ISchedulerClient basing on the config ISchedulerClient schedulerClient = getSchedulerClient(runtime); callRuntimeManagerRunner(runtime, schedulerClient, !hasExecutionData); } finally { // 3. Do post work basing on the result // Currently nothing to do here // 4. Close the resources SysUtils.closeIgnoringExceptions(statemgr); } }
[ "public", "void", "manageTopology", "(", ")", "throws", "TopologyRuntimeManagementException", ",", "TMasterException", ",", "PackingException", "{", "String", "topologyName", "=", "Context", ".", "topologyName", "(", "config", ")", ";", "// 1. Do prepare work", "// create an instance of state manager", "String", "statemgrClass", "=", "Context", ".", "stateManagerClass", "(", "config", ")", ";", "IStateManager", "statemgr", ";", "try", "{", "statemgr", "=", "ReflectionUtils", ".", "newInstance", "(", "statemgrClass", ")", ";", "}", "catch", "(", "IllegalAccessException", "|", "InstantiationException", "|", "ClassNotFoundException", "e", ")", "{", "throw", "new", "TopologyRuntimeManagementException", "(", "String", ".", "format", "(", "\"Failed to instantiate state manager class '%s'\"", ",", "statemgrClass", ")", ",", "e", ")", ";", "}", "// Put it in a try block so that we can always clean resources", "try", "{", "// initialize the statemgr", "statemgr", ".", "initialize", "(", "config", ")", ";", "// TODO(mfu): timeout should read from config", "SchedulerStateManagerAdaptor", "adaptor", "=", "new", "SchedulerStateManagerAdaptor", "(", "statemgr", ",", "5000", ")", ";", "boolean", "hasExecutionData", "=", "validateRuntimeManage", "(", "adaptor", ",", "topologyName", ")", ";", "// 2. Try to manage topology if valid", "// invoke the appropriate command to manage the topology", "LOG", ".", "log", "(", "Level", ".", "FINE", ",", "\"Topology: {0} to be {1}ed\"", ",", "new", "Object", "[", "]", "{", "topologyName", ",", "command", "}", ")", ";", "// build the runtime config", "Config", "runtime", "=", "Config", ".", "newBuilder", "(", ")", ".", "put", "(", "Key", ".", "TOPOLOGY_NAME", ",", "Context", ".", "topologyName", "(", "config", ")", ")", ".", "put", "(", "Key", ".", "SCHEDULER_STATE_MANAGER_ADAPTOR", ",", "adaptor", ")", ".", "build", "(", ")", ";", "// Create a ISchedulerClient basing on the config", "ISchedulerClient", "schedulerClient", "=", "getSchedulerClient", "(", "runtime", ")", ";", "callRuntimeManagerRunner", "(", "runtime", ",", "schedulerClient", ",", "!", "hasExecutionData", ")", ";", "}", "finally", "{", "// 3. Do post work basing on the result", "// Currently nothing to do here", "// 4. Close the resources", "SysUtils", ".", "closeIgnoringExceptions", "(", "statemgr", ")", ";", "}", "}" ]
Manager a topology 1. Instantiate necessary resources 2. Valid whether the runtime management is legal 3. Complete the runtime management for a specific command
[ "Manager", "a", "topology", "1", ".", "Instantiate", "necessary", "resources", "2", ".", "Valid", "whether", "the", "runtime", "management", "is", "legal", "3", ".", "Complete", "the", "runtime", "management", "for", "a", "specific", "command" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/scheduler-core/src/java/org/apache/heron/scheduler/RuntimeManagerMain.java#L373-L419
27,847
apache/incubator-heron
heron/scheduler-core/src/java/org/apache/heron/scheduler/RuntimeManagerMain.java
RuntimeManagerMain.validateExecutionState
protected void validateExecutionState( String topologyName, ExecutionEnvironment.ExecutionState executionState) throws TopologyRuntimeManagementException { String stateCluster = executionState.getCluster(); String stateRole = executionState.getRole(); String stateEnv = executionState.getEnviron(); String configCluster = Context.cluster(config); String configRole = Context.role(config); String configEnv = Context.environ(config); if (!stateCluster.equals(configCluster) || !stateRole.equals(configRole) || !stateEnv.equals(configEnv)) { String currentState = String.format("%s/%s/%s", stateCluster, stateRole, stateEnv); String configState = String.format("%s/%s/%s", configCluster, configRole, configEnv); throw new TopologyRuntimeManagementException(String.format( "cluster/role/environ does not match. Topology '%s' is running at %s, not %s", topologyName, currentState, configState)); } }
java
protected void validateExecutionState( String topologyName, ExecutionEnvironment.ExecutionState executionState) throws TopologyRuntimeManagementException { String stateCluster = executionState.getCluster(); String stateRole = executionState.getRole(); String stateEnv = executionState.getEnviron(); String configCluster = Context.cluster(config); String configRole = Context.role(config); String configEnv = Context.environ(config); if (!stateCluster.equals(configCluster) || !stateRole.equals(configRole) || !stateEnv.equals(configEnv)) { String currentState = String.format("%s/%s/%s", stateCluster, stateRole, stateEnv); String configState = String.format("%s/%s/%s", configCluster, configRole, configEnv); throw new TopologyRuntimeManagementException(String.format( "cluster/role/environ does not match. Topology '%s' is running at %s, not %s", topologyName, currentState, configState)); } }
[ "protected", "void", "validateExecutionState", "(", "String", "topologyName", ",", "ExecutionEnvironment", ".", "ExecutionState", "executionState", ")", "throws", "TopologyRuntimeManagementException", "{", "String", "stateCluster", "=", "executionState", ".", "getCluster", "(", ")", ";", "String", "stateRole", "=", "executionState", ".", "getRole", "(", ")", ";", "String", "stateEnv", "=", "executionState", ".", "getEnviron", "(", ")", ";", "String", "configCluster", "=", "Context", ".", "cluster", "(", "config", ")", ";", "String", "configRole", "=", "Context", ".", "role", "(", "config", ")", ";", "String", "configEnv", "=", "Context", ".", "environ", "(", "config", ")", ";", "if", "(", "!", "stateCluster", ".", "equals", "(", "configCluster", ")", "||", "!", "stateRole", ".", "equals", "(", "configRole", ")", "||", "!", "stateEnv", ".", "equals", "(", "configEnv", ")", ")", "{", "String", "currentState", "=", "String", ".", "format", "(", "\"%s/%s/%s\"", ",", "stateCluster", ",", "stateRole", ",", "stateEnv", ")", ";", "String", "configState", "=", "String", ".", "format", "(", "\"%s/%s/%s\"", ",", "configCluster", ",", "configRole", ",", "configEnv", ")", ";", "throw", "new", "TopologyRuntimeManagementException", "(", "String", ".", "format", "(", "\"cluster/role/environ does not match. Topology '%s' is running at %s, not %s\"", ",", "topologyName", ",", "currentState", ",", "configState", ")", ")", ";", "}", "}" ]
Verify that the environment information in execution state matches the request
[ "Verify", "that", "the", "environment", "information", "in", "execution", "state", "matches", "the", "request" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/scheduler-core/src/java/org/apache/heron/scheduler/RuntimeManagerMain.java#L465-L485
27,848
apache/incubator-heron
heron/api/src/java/org/apache/heron/api/tuple/Fields.java
Fields.fieldIndex
public int fieldIndex(String field) { Integer ret = mIndex.get(field); if (ret == null) { throw new IllegalArgumentException(field + " does not exist"); } return ret; }
java
public int fieldIndex(String field) { Integer ret = mIndex.get(field); if (ret == null) { throw new IllegalArgumentException(field + " does not exist"); } return ret; }
[ "public", "int", "fieldIndex", "(", "String", "field", ")", "{", "Integer", "ret", "=", "mIndex", ".", "get", "(", "field", ")", ";", "if", "(", "ret", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "field", "+", "\" does not exist\"", ")", ";", "}", "return", "ret", ";", "}" ]
Returns the position of the specified field.
[ "Returns", "the", "position", "of", "the", "specified", "field", "." ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/api/src/java/org/apache/heron/api/tuple/Fields.java#L80-L86
27,849
apache/incubator-heron
heron/schedulers/src/java/org/apache/heron/scheduler/yarn/YarnLauncher.java
YarnLauncher.getClientConf
private Configuration getClientConf() { return HeronClientConfiguration.CONF .set(ClientConfiguration.ON_JOB_RUNNING, ReefClientSideHandlers.RunningJobHandler.class) .set(ClientConfiguration.ON_JOB_FAILED, ReefClientSideHandlers.FailedJobHandler.class) .set(ClientConfiguration.ON_RUNTIME_ERROR, ReefClientSideHandlers.RuntimeErrorHandler.class) .set(HeronClientConfiguration.TOPOLOGY_NAME, topologyName) .build(); }
java
private Configuration getClientConf() { return HeronClientConfiguration.CONF .set(ClientConfiguration.ON_JOB_RUNNING, ReefClientSideHandlers.RunningJobHandler.class) .set(ClientConfiguration.ON_JOB_FAILED, ReefClientSideHandlers.FailedJobHandler.class) .set(ClientConfiguration.ON_RUNTIME_ERROR, ReefClientSideHandlers.RuntimeErrorHandler.class) .set(HeronClientConfiguration.TOPOLOGY_NAME, topologyName) .build(); }
[ "private", "Configuration", "getClientConf", "(", ")", "{", "return", "HeronClientConfiguration", ".", "CONF", ".", "set", "(", "ClientConfiguration", ".", "ON_JOB_RUNNING", ",", "ReefClientSideHandlers", ".", "RunningJobHandler", ".", "class", ")", ".", "set", "(", "ClientConfiguration", ".", "ON_JOB_FAILED", ",", "ReefClientSideHandlers", ".", "FailedJobHandler", ".", "class", ")", ".", "set", "(", "ClientConfiguration", ".", "ON_RUNTIME_ERROR", ",", "ReefClientSideHandlers", ".", "RuntimeErrorHandler", ".", "class", ")", ".", "set", "(", "HeronClientConfiguration", ".", "TOPOLOGY_NAME", ",", "topologyName", ")", ".", "build", "(", ")", ";", "}" ]
Builds and returns configuration needed by REEF client to launch topology as a REEF job and track it.
[ "Builds", "and", "returns", "configuration", "needed", "by", "REEF", "client", "to", "launch", "topology", "as", "a", "REEF", "job", "and", "track", "it", "." ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/schedulers/src/java/org/apache/heron/scheduler/yarn/YarnLauncher.java#L189-L196
27,850
apache/incubator-heron
heron/common/src/java/org/apache/heron/common/basics/NIOLooper.java
NIOLooper.handleSelectedKeys
private void handleSelectedKeys() { Set<SelectionKey> selectedKeys = selector.selectedKeys(); Iterator<SelectionKey> keyIterator = selectedKeys.iterator(); while (keyIterator.hasNext()) { SelectionKey key = keyIterator.next(); keyIterator.remove(); ISelectHandler callback = (ISelectHandler) key.attachment(); if (!key.isValid()) { // This method key.channel() will continue to return the channel even after the // key is cancelled. callback.handleError(key.channel()); continue; } // We need to check whether the key is still valid since: // 1. The key could be cancelled by last operation // 2. The process might not fail-fast or throw exceptions after the key is cancelled if (key.isValid() && key.isWritable()) { callback.handleWrite(key.channel()); } if (key.isValid() && key.isReadable()) { callback.handleRead(key.channel()); } if (key.isValid() && key.isConnectable()) { callback.handleConnect(key.channel()); } if (key.isValid() && key.isAcceptable()) { callback.handleAccept(key.channel()); } } }
java
private void handleSelectedKeys() { Set<SelectionKey> selectedKeys = selector.selectedKeys(); Iterator<SelectionKey> keyIterator = selectedKeys.iterator(); while (keyIterator.hasNext()) { SelectionKey key = keyIterator.next(); keyIterator.remove(); ISelectHandler callback = (ISelectHandler) key.attachment(); if (!key.isValid()) { // This method key.channel() will continue to return the channel even after the // key is cancelled. callback.handleError(key.channel()); continue; } // We need to check whether the key is still valid since: // 1. The key could be cancelled by last operation // 2. The process might not fail-fast or throw exceptions after the key is cancelled if (key.isValid() && key.isWritable()) { callback.handleWrite(key.channel()); } if (key.isValid() && key.isReadable()) { callback.handleRead(key.channel()); } if (key.isValid() && key.isConnectable()) { callback.handleConnect(key.channel()); } if (key.isValid() && key.isAcceptable()) { callback.handleAccept(key.channel()); } } }
[ "private", "void", "handleSelectedKeys", "(", ")", "{", "Set", "<", "SelectionKey", ">", "selectedKeys", "=", "selector", ".", "selectedKeys", "(", ")", ";", "Iterator", "<", "SelectionKey", ">", "keyIterator", "=", "selectedKeys", ".", "iterator", "(", ")", ";", "while", "(", "keyIterator", ".", "hasNext", "(", ")", ")", "{", "SelectionKey", "key", "=", "keyIterator", ".", "next", "(", ")", ";", "keyIterator", ".", "remove", "(", ")", ";", "ISelectHandler", "callback", "=", "(", "ISelectHandler", ")", "key", ".", "attachment", "(", ")", ";", "if", "(", "!", "key", ".", "isValid", "(", ")", ")", "{", "// This method key.channel() will continue to return the channel even after the", "// key is cancelled.", "callback", ".", "handleError", "(", "key", ".", "channel", "(", ")", ")", ";", "continue", ";", "}", "// We need to check whether the key is still valid since:", "// 1. The key could be cancelled by last operation", "// 2. The process might not fail-fast or throw exceptions after the key is cancelled", "if", "(", "key", ".", "isValid", "(", ")", "&&", "key", ".", "isWritable", "(", ")", ")", "{", "callback", ".", "handleWrite", "(", "key", ".", "channel", "(", ")", ")", ";", "}", "if", "(", "key", ".", "isValid", "(", ")", "&&", "key", ".", "isReadable", "(", ")", ")", "{", "callback", ".", "handleRead", "(", "key", ".", "channel", "(", ")", ")", ";", "}", "if", "(", "key", ".", "isValid", "(", ")", "&&", "key", ".", "isConnectable", "(", ")", ")", "{", "callback", ".", "handleConnect", "(", "key", ".", "channel", "(", ")", ")", ";", "}", "if", "(", "key", ".", "isValid", "(", ")", "&&", "key", ".", "isAcceptable", "(", ")", ")", "{", "callback", ".", "handleAccept", "(", "key", ".", "channel", "(", ")", ")", ";", "}", "}", "}" ]
Handle the selected keys
[ "Handle", "the", "selected", "keys" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/common/src/java/org/apache/heron/common/basics/NIOLooper.java#L92-L128
27,851
apache/incubator-heron
heron/common/src/java/org/apache/heron/common/basics/NIOLooper.java
NIOLooper.registerRead
public void registerRead(SelectableChannel channel, ISelectHandler callback) throws ClosedChannelException { assert channel.keyFor(selector) == null || (channel.keyFor(selector).interestOps() & SelectionKey.OP_CONNECT) == 0; addInterest(channel, SelectionKey.OP_READ, callback); }
java
public void registerRead(SelectableChannel channel, ISelectHandler callback) throws ClosedChannelException { assert channel.keyFor(selector) == null || (channel.keyFor(selector).interestOps() & SelectionKey.OP_CONNECT) == 0; addInterest(channel, SelectionKey.OP_READ, callback); }
[ "public", "void", "registerRead", "(", "SelectableChannel", "channel", ",", "ISelectHandler", "callback", ")", "throws", "ClosedChannelException", "{", "assert", "channel", ".", "keyFor", "(", "selector", ")", "==", "null", "||", "(", "channel", ".", "keyFor", "(", "selector", ")", ".", "interestOps", "(", ")", "&", "SelectionKey", ".", "OP_CONNECT", ")", "==", "0", ";", "addInterest", "(", "channel", ",", "SelectionKey", ".", "OP_READ", ",", "callback", ")", ";", "}" ]
Followings are the register, unregister, isRegister for different operations for the selector and channel
[ "Followings", "are", "the", "register", "unregister", "isRegister", "for", "different", "operations", "for", "the", "selector", "and", "channel" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/common/src/java/org/apache/heron/common/basics/NIOLooper.java#L138-L143
27,852
apache/incubator-heron
heron/common/src/java/org/apache/heron/common/basics/NIOLooper.java
NIOLooper.removeInterest
private void removeInterest(SelectableChannel channel, int operation) { SelectionKey key = channel.keyFor(selector); // Exception would be thrown if key is null or key is inValid // We do not need double check it ahead key.interestOps(key.interestOps() & (~operation)); }
java
private void removeInterest(SelectableChannel channel, int operation) { SelectionKey key = channel.keyFor(selector); // Exception would be thrown if key is null or key is inValid // We do not need double check it ahead key.interestOps(key.interestOps() & (~operation)); }
[ "private", "void", "removeInterest", "(", "SelectableChannel", "channel", ",", "int", "operation", ")", "{", "SelectionKey", "key", "=", "channel", ".", "keyFor", "(", "selector", ")", ";", "// Exception would be thrown if key is null or key is inValid", "// We do not need double check it ahead", "key", ".", "interestOps", "(", "key", ".", "interestOps", "(", ")", "&", "(", "~", "operation", ")", ")", ";", "}" ]
Remove one operation interest on a SelectableChannel. The SelectableChannel has to be registered with Selector ahead. Otherwise, NullPointerExceptions would throw The key for SelectableChannel has to be valid. Otherwise, InvalidValid Exception would throw. @param channel the SelectableChannel to remove operation interest @param operation the interest to remove
[ "Remove", "one", "operation", "interest", "on", "a", "SelectableChannel", ".", "The", "SelectableChannel", "has", "to", "be", "registered", "with", "Selector", "ahead", ".", "Otherwise", "NullPointerExceptions", "would", "throw", "The", "key", "for", "SelectableChannel", "has", "to", "be", "valid", ".", "Otherwise", "InvalidValid", "Exception", "would", "throw", "." ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/common/src/java/org/apache/heron/common/basics/NIOLooper.java#L254-L260
27,853
apache/incubator-heron
heron/common/src/java/org/apache/heron/common/basics/NIOLooper.java
NIOLooper.isInterestRegistered
private boolean isInterestRegistered(SelectableChannel channel, int operation) { SelectionKey key = channel.keyFor(selector); return key != null && (key.interestOps() & operation) != 0; }
java
private boolean isInterestRegistered(SelectableChannel channel, int operation) { SelectionKey key = channel.keyFor(selector); return key != null && (key.interestOps() & operation) != 0; }
[ "private", "boolean", "isInterestRegistered", "(", "SelectableChannel", "channel", ",", "int", "operation", ")", "{", "SelectionKey", "key", "=", "channel", ".", "keyFor", "(", "selector", ")", ";", "return", "key", "!=", "null", "&&", "(", "key", ".", "interestOps", "(", ")", "&", "operation", ")", "!=", "0", ";", "}" ]
Check whether an operation interest was registered on a SelectableChannel There are two cases that interest is not registered 1. The whole key does not exist; no interests ever registered for this channel 2. The key exists due to other interests registered but not the one we are adding If the key exists, the key for SelectableChannel has to be valid. Otherwise, InvalidValid Exception would throw. @param channel The Selectable to check @param operation The operation interest to check
[ "Check", "whether", "an", "operation", "interest", "was", "registered", "on", "a", "SelectableChannel", "There", "are", "two", "cases", "that", "interest", "is", "not", "registered", "1", ".", "The", "whole", "key", "does", "not", "exist", ";", "no", "interests", "ever", "registered", "for", "this", "channel", "2", ".", "The", "key", "exists", "due", "to", "other", "interests", "registered", "but", "not", "the", "one", "we", "are", "adding", "If", "the", "key", "exists", "the", "key", "for", "SelectableChannel", "has", "to", "be", "valid", ".", "Otherwise", "InvalidValid", "Exception", "would", "throw", "." ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/common/src/java/org/apache/heron/common/basics/NIOLooper.java#L273-L277
27,854
apache/incubator-heron
heron/uploaders/src/java/org/apache/heron/uploader/localfs/LocalFileSystemUploader.java
LocalFileSystemUploader.uploadPackage
@Override public URI uploadPackage() throws UploaderException { // first, check if the topology package exists boolean fileExists = new File(topologyPackageLocation).isFile(); if (!fileExists) { throw new UploaderException( String.format("Topology package does not exist at '%s'", topologyPackageLocation)); } // get the directory containing the file Path filePath = Paths.get(destTopologyFile); File parentDirectory = filePath.getParent().toFile(); assert parentDirectory != null; // if the dest directory does not exist, create it. if (!parentDirectory.exists()) { LOG.fine(String.format( "Working directory does not exist. Creating it now at %s", parentDirectory.getPath())); if (!parentDirectory.mkdirs()) { throw new UploaderException( String.format("Failed to create directory for topology package at %s", parentDirectory.getPath())); } } // if the dest file exists, write a log message fileExists = new File(filePath.toString()).isFile(); if (fileExists) { LOG.fine(String.format("Target topology package already exists at '%s'. Overwriting it now", filePath.toString())); } // copy the topology package to target working directory LOG.fine(String.format("Copying topology package at '%s' to target working directory '%s'", topologyPackageLocation, filePath.toString())); Path source = Paths.get(topologyPackageLocation); try { CopyOption[] options = new CopyOption[]{StandardCopyOption.REPLACE_EXISTING}; Files.copy(source, filePath, options); } catch (IOException e) { throw new UploaderException( String.format("Unable to copy topology file from '%s' to '%s'", source, filePath), e); } return getUri(destTopologyFile); }
java
@Override public URI uploadPackage() throws UploaderException { // first, check if the topology package exists boolean fileExists = new File(topologyPackageLocation).isFile(); if (!fileExists) { throw new UploaderException( String.format("Topology package does not exist at '%s'", topologyPackageLocation)); } // get the directory containing the file Path filePath = Paths.get(destTopologyFile); File parentDirectory = filePath.getParent().toFile(); assert parentDirectory != null; // if the dest directory does not exist, create it. if (!parentDirectory.exists()) { LOG.fine(String.format( "Working directory does not exist. Creating it now at %s", parentDirectory.getPath())); if (!parentDirectory.mkdirs()) { throw new UploaderException( String.format("Failed to create directory for topology package at %s", parentDirectory.getPath())); } } // if the dest file exists, write a log message fileExists = new File(filePath.toString()).isFile(); if (fileExists) { LOG.fine(String.format("Target topology package already exists at '%s'. Overwriting it now", filePath.toString())); } // copy the topology package to target working directory LOG.fine(String.format("Copying topology package at '%s' to target working directory '%s'", topologyPackageLocation, filePath.toString())); Path source = Paths.get(topologyPackageLocation); try { CopyOption[] options = new CopyOption[]{StandardCopyOption.REPLACE_EXISTING}; Files.copy(source, filePath, options); } catch (IOException e) { throw new UploaderException( String.format("Unable to copy topology file from '%s' to '%s'", source, filePath), e); } return getUri(destTopologyFile); }
[ "@", "Override", "public", "URI", "uploadPackage", "(", ")", "throws", "UploaderException", "{", "// first, check if the topology package exists", "boolean", "fileExists", "=", "new", "File", "(", "topologyPackageLocation", ")", ".", "isFile", "(", ")", ";", "if", "(", "!", "fileExists", ")", "{", "throw", "new", "UploaderException", "(", "String", ".", "format", "(", "\"Topology package does not exist at '%s'\"", ",", "topologyPackageLocation", ")", ")", ";", "}", "// get the directory containing the file", "Path", "filePath", "=", "Paths", ".", "get", "(", "destTopologyFile", ")", ";", "File", "parentDirectory", "=", "filePath", ".", "getParent", "(", ")", ".", "toFile", "(", ")", ";", "assert", "parentDirectory", "!=", "null", ";", "// if the dest directory does not exist, create it.", "if", "(", "!", "parentDirectory", ".", "exists", "(", ")", ")", "{", "LOG", ".", "fine", "(", "String", ".", "format", "(", "\"Working directory does not exist. Creating it now at %s\"", ",", "parentDirectory", ".", "getPath", "(", ")", ")", ")", ";", "if", "(", "!", "parentDirectory", ".", "mkdirs", "(", ")", ")", "{", "throw", "new", "UploaderException", "(", "String", ".", "format", "(", "\"Failed to create directory for topology package at %s\"", ",", "parentDirectory", ".", "getPath", "(", ")", ")", ")", ";", "}", "}", "// if the dest file exists, write a log message", "fileExists", "=", "new", "File", "(", "filePath", ".", "toString", "(", ")", ")", ".", "isFile", "(", ")", ";", "if", "(", "fileExists", ")", "{", "LOG", ".", "fine", "(", "String", ".", "format", "(", "\"Target topology package already exists at '%s'. Overwriting it now\"", ",", "filePath", ".", "toString", "(", ")", ")", ")", ";", "}", "// copy the topology package to target working directory", "LOG", ".", "fine", "(", "String", ".", "format", "(", "\"Copying topology package at '%s' to target working directory '%s'\"", ",", "topologyPackageLocation", ",", "filePath", ".", "toString", "(", ")", ")", ")", ";", "Path", "source", "=", "Paths", ".", "get", "(", "topologyPackageLocation", ")", ";", "try", "{", "CopyOption", "[", "]", "options", "=", "new", "CopyOption", "[", "]", "{", "StandardCopyOption", ".", "REPLACE_EXISTING", "}", ";", "Files", ".", "copy", "(", "source", ",", "filePath", ",", "options", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "UploaderException", "(", "String", ".", "format", "(", "\"Unable to copy topology file from '%s' to '%s'\"", ",", "source", ",", "filePath", ")", ",", "e", ")", ";", "}", "return", "getUri", "(", "destTopologyFile", ")", ";", "}" ]
Upload the topology package to the destined location in local file system @return destination URI of where the topology package has been uploaded if successful, or {@code null} if failed.
[ "Upload", "the", "topology", "package", "to", "the", "destined", "location", "in", "local", "file", "system" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/uploaders/src/java/org/apache/heron/uploader/localfs/LocalFileSystemUploader.java#L77-L124
27,855
apache/incubator-heron
heron/uploaders/src/java/org/apache/heron/uploader/localfs/LocalFileSystemUploader.java
LocalFileSystemUploader.undo
@Override public boolean undo() { if (destTopologyFile != null) { LOG.info("Clean uploaded jar"); File file = new File(destTopologyFile); return file.delete(); } return true; }
java
@Override public boolean undo() { if (destTopologyFile != null) { LOG.info("Clean uploaded jar"); File file = new File(destTopologyFile); return file.delete(); } return true; }
[ "@", "Override", "public", "boolean", "undo", "(", ")", "{", "if", "(", "destTopologyFile", "!=", "null", ")", "{", "LOG", ".", "info", "(", "\"Clean uploaded jar\"", ")", ";", "File", "file", "=", "new", "File", "(", "destTopologyFile", ")", ";", "return", "file", ".", "delete", "(", ")", ";", "}", "return", "true", ";", "}" ]
Remove the uploaded topology package for cleaning up @return true, if successful
[ "Remove", "the", "uploaded", "topology", "package", "for", "cleaning", "up" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/uploaders/src/java/org/apache/heron/uploader/localfs/LocalFileSystemUploader.java#L131-L139
27,856
apache/incubator-heron
heron/packing/src/java/org/apache/heron/packing/AbstractPacking.java
AbstractPacking.setPackingConfigs
private void setPackingConfigs(Config config) { List<TopologyAPI.Config.KeyValue> topologyConfig = topology.getTopologyConfig().getKvsList(); // instance default resources are acquired from heron system level config this.defaultInstanceResources = new Resource( Context.instanceCpu(config), Context.instanceRam(config), Context.instanceDisk(config)); int paddingPercentage = TopologyUtils.getConfigWithDefault(topologyConfig, TOPOLOGY_CONTAINER_PADDING_PERCENTAGE, PackingUtils.DEFAULT_CONTAINER_PADDING_PERCENTAGE); ByteAmount ramPadding = TopologyUtils.getConfigWithDefault(topologyConfig, TOPOLOGY_CONTAINER_RAM_PADDING, PackingUtils.DEFAULT_CONTAINER_RAM_PADDING); double cpuPadding = TopologyUtils.getConfigWithDefault(topologyConfig, TOPOLOGY_CONTAINER_CPU_PADDING, PackingUtils.DEFAULT_CONTAINER_CPU_PADDING); Resource preliminaryPadding = new Resource(cpuPadding, ramPadding, PackingUtils.DEFAULT_CONTAINER_DISK_PADDING); this.maxNumInstancesPerContainer = TopologyUtils.getConfigWithDefault(topologyConfig, TOPOLOGY_CONTAINER_MAX_NUM_INSTANCES, PackingUtils.DEFAULT_MAX_NUM_INSTANCES_PER_CONTAINER); // container default resources are computed as: // max number of instances per container * default instance resources double containerDefaultCpu = this.defaultInstanceResources.getCpu() * maxNumInstancesPerContainer; ByteAmount containerDefaultRam = this.defaultInstanceResources.getRam() .multiply(maxNumInstancesPerContainer); ByteAmount containerDefaultDisk = this.defaultInstanceResources.getDisk() .multiply(maxNumInstancesPerContainer); double containerCpu = TopologyUtils.getConfigWithDefault(topologyConfig, TOPOLOGY_CONTAINER_CPU_REQUESTED, containerDefaultCpu); ByteAmount containerRam = TopologyUtils.getConfigWithDefault(topologyConfig, TOPOLOGY_CONTAINER_RAM_REQUESTED, containerDefaultRam); ByteAmount containerDisk = TopologyUtils.getConfigWithDefault(topologyConfig, TOPOLOGY_CONTAINER_DISK_REQUESTED, containerDefaultDisk); Resource containerResource = new Resource(containerCpu, containerRam, containerDisk); // finalize padding this.padding = PackingUtils.finalizePadding(containerResource, preliminaryPadding, paddingPercentage); // finalize container resources this.maxContainerResources = containerResource; this.componentResourceMap = PackingUtils.getComponentResourceMap( TopologyUtils.getComponentParallelism(topology).keySet(), TopologyUtils.getComponentRamMapConfig(topology), TopologyUtils.getComponentCpuMapConfig(topology), TopologyUtils.getComponentDiskMapConfig(topology), defaultInstanceResources ); }
java
private void setPackingConfigs(Config config) { List<TopologyAPI.Config.KeyValue> topologyConfig = topology.getTopologyConfig().getKvsList(); // instance default resources are acquired from heron system level config this.defaultInstanceResources = new Resource( Context.instanceCpu(config), Context.instanceRam(config), Context.instanceDisk(config)); int paddingPercentage = TopologyUtils.getConfigWithDefault(topologyConfig, TOPOLOGY_CONTAINER_PADDING_PERCENTAGE, PackingUtils.DEFAULT_CONTAINER_PADDING_PERCENTAGE); ByteAmount ramPadding = TopologyUtils.getConfigWithDefault(topologyConfig, TOPOLOGY_CONTAINER_RAM_PADDING, PackingUtils.DEFAULT_CONTAINER_RAM_PADDING); double cpuPadding = TopologyUtils.getConfigWithDefault(topologyConfig, TOPOLOGY_CONTAINER_CPU_PADDING, PackingUtils.DEFAULT_CONTAINER_CPU_PADDING); Resource preliminaryPadding = new Resource(cpuPadding, ramPadding, PackingUtils.DEFAULT_CONTAINER_DISK_PADDING); this.maxNumInstancesPerContainer = TopologyUtils.getConfigWithDefault(topologyConfig, TOPOLOGY_CONTAINER_MAX_NUM_INSTANCES, PackingUtils.DEFAULT_MAX_NUM_INSTANCES_PER_CONTAINER); // container default resources are computed as: // max number of instances per container * default instance resources double containerDefaultCpu = this.defaultInstanceResources.getCpu() * maxNumInstancesPerContainer; ByteAmount containerDefaultRam = this.defaultInstanceResources.getRam() .multiply(maxNumInstancesPerContainer); ByteAmount containerDefaultDisk = this.defaultInstanceResources.getDisk() .multiply(maxNumInstancesPerContainer); double containerCpu = TopologyUtils.getConfigWithDefault(topologyConfig, TOPOLOGY_CONTAINER_CPU_REQUESTED, containerDefaultCpu); ByteAmount containerRam = TopologyUtils.getConfigWithDefault(topologyConfig, TOPOLOGY_CONTAINER_RAM_REQUESTED, containerDefaultRam); ByteAmount containerDisk = TopologyUtils.getConfigWithDefault(topologyConfig, TOPOLOGY_CONTAINER_DISK_REQUESTED, containerDefaultDisk); Resource containerResource = new Resource(containerCpu, containerRam, containerDisk); // finalize padding this.padding = PackingUtils.finalizePadding(containerResource, preliminaryPadding, paddingPercentage); // finalize container resources this.maxContainerResources = containerResource; this.componentResourceMap = PackingUtils.getComponentResourceMap( TopologyUtils.getComponentParallelism(topology).keySet(), TopologyUtils.getComponentRamMapConfig(topology), TopologyUtils.getComponentCpuMapConfig(topology), TopologyUtils.getComponentDiskMapConfig(topology), defaultInstanceResources ); }
[ "private", "void", "setPackingConfigs", "(", "Config", "config", ")", "{", "List", "<", "TopologyAPI", ".", "Config", ".", "KeyValue", ">", "topologyConfig", "=", "topology", ".", "getTopologyConfig", "(", ")", ".", "getKvsList", "(", ")", ";", "// instance default resources are acquired from heron system level config", "this", ".", "defaultInstanceResources", "=", "new", "Resource", "(", "Context", ".", "instanceCpu", "(", "config", ")", ",", "Context", ".", "instanceRam", "(", "config", ")", ",", "Context", ".", "instanceDisk", "(", "config", ")", ")", ";", "int", "paddingPercentage", "=", "TopologyUtils", ".", "getConfigWithDefault", "(", "topologyConfig", ",", "TOPOLOGY_CONTAINER_PADDING_PERCENTAGE", ",", "PackingUtils", ".", "DEFAULT_CONTAINER_PADDING_PERCENTAGE", ")", ";", "ByteAmount", "ramPadding", "=", "TopologyUtils", ".", "getConfigWithDefault", "(", "topologyConfig", ",", "TOPOLOGY_CONTAINER_RAM_PADDING", ",", "PackingUtils", ".", "DEFAULT_CONTAINER_RAM_PADDING", ")", ";", "double", "cpuPadding", "=", "TopologyUtils", ".", "getConfigWithDefault", "(", "topologyConfig", ",", "TOPOLOGY_CONTAINER_CPU_PADDING", ",", "PackingUtils", ".", "DEFAULT_CONTAINER_CPU_PADDING", ")", ";", "Resource", "preliminaryPadding", "=", "new", "Resource", "(", "cpuPadding", ",", "ramPadding", ",", "PackingUtils", ".", "DEFAULT_CONTAINER_DISK_PADDING", ")", ";", "this", ".", "maxNumInstancesPerContainer", "=", "TopologyUtils", ".", "getConfigWithDefault", "(", "topologyConfig", ",", "TOPOLOGY_CONTAINER_MAX_NUM_INSTANCES", ",", "PackingUtils", ".", "DEFAULT_MAX_NUM_INSTANCES_PER_CONTAINER", ")", ";", "// container default resources are computed as:", "// max number of instances per container * default instance resources", "double", "containerDefaultCpu", "=", "this", ".", "defaultInstanceResources", ".", "getCpu", "(", ")", "*", "maxNumInstancesPerContainer", ";", "ByteAmount", "containerDefaultRam", "=", "this", ".", "defaultInstanceResources", ".", "getRam", "(", ")", ".", "multiply", "(", "maxNumInstancesPerContainer", ")", ";", "ByteAmount", "containerDefaultDisk", "=", "this", ".", "defaultInstanceResources", ".", "getDisk", "(", ")", ".", "multiply", "(", "maxNumInstancesPerContainer", ")", ";", "double", "containerCpu", "=", "TopologyUtils", ".", "getConfigWithDefault", "(", "topologyConfig", ",", "TOPOLOGY_CONTAINER_CPU_REQUESTED", ",", "containerDefaultCpu", ")", ";", "ByteAmount", "containerRam", "=", "TopologyUtils", ".", "getConfigWithDefault", "(", "topologyConfig", ",", "TOPOLOGY_CONTAINER_RAM_REQUESTED", ",", "containerDefaultRam", ")", ";", "ByteAmount", "containerDisk", "=", "TopologyUtils", ".", "getConfigWithDefault", "(", "topologyConfig", ",", "TOPOLOGY_CONTAINER_DISK_REQUESTED", ",", "containerDefaultDisk", ")", ";", "Resource", "containerResource", "=", "new", "Resource", "(", "containerCpu", ",", "containerRam", ",", "containerDisk", ")", ";", "// finalize padding", "this", ".", "padding", "=", "PackingUtils", ".", "finalizePadding", "(", "containerResource", ",", "preliminaryPadding", ",", "paddingPercentage", ")", ";", "// finalize container resources", "this", ".", "maxContainerResources", "=", "containerResource", ";", "this", ".", "componentResourceMap", "=", "PackingUtils", ".", "getComponentResourceMap", "(", "TopologyUtils", ".", "getComponentParallelism", "(", "topology", ")", ".", "keySet", "(", ")", ",", "TopologyUtils", ".", "getComponentRamMapConfig", "(", "topology", ")", ",", "TopologyUtils", ".", "getComponentCpuMapConfig", "(", "topology", ")", ",", "TopologyUtils", ".", "getComponentDiskMapConfig", "(", "topology", ")", ",", "defaultInstanceResources", ")", ";", "}" ]
Instatiate the packing algorithm parameters related to this topology.
[ "Instatiate", "the", "packing", "algorithm", "parameters", "related", "to", "this", "topology", "." ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/packing/src/java/org/apache/heron/packing/AbstractPacking.java#L118-L171
27,857
apache/incubator-heron
heron/common/src/java/org/apache/heron/common/utils/topology/GeneralTopologyContextImpl.java
GeneralTopologyContextImpl.getComponentStreams
public Set<String> getComponentStreams(String componentId) { if (outputs.containsKey(componentId)) { Set<String> streams = new HashSet<>(); List<TopologyAPI.OutputStream> olist = outputs.get(componentId); for (TopologyAPI.OutputStream ostream : olist) { streams.add(ostream.getStream().getId()); } return streams; } else { return null; } }
java
public Set<String> getComponentStreams(String componentId) { if (outputs.containsKey(componentId)) { Set<String> streams = new HashSet<>(); List<TopologyAPI.OutputStream> olist = outputs.get(componentId); for (TopologyAPI.OutputStream ostream : olist) { streams.add(ostream.getStream().getId()); } return streams; } else { return null; } }
[ "public", "Set", "<", "String", ">", "getComponentStreams", "(", "String", "componentId", ")", "{", "if", "(", "outputs", ".", "containsKey", "(", "componentId", ")", ")", "{", "Set", "<", "String", ">", "streams", "=", "new", "HashSet", "<>", "(", ")", ";", "List", "<", "TopologyAPI", ".", "OutputStream", ">", "olist", "=", "outputs", ".", "get", "(", "componentId", ")", ";", "for", "(", "TopologyAPI", ".", "OutputStream", "ostream", ":", "olist", ")", "{", "streams", ".", "add", "(", "ostream", ".", "getStream", "(", ")", ".", "getId", "(", ")", ")", ";", "}", "return", "streams", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Gets the set of streams declared for the specified component.
[ "Gets", "the", "set", "of", "streams", "declared", "for", "the", "specified", "component", "." ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/common/src/java/org/apache/heron/common/utils/topology/GeneralTopologyContextImpl.java#L152-L163
27,858
apache/incubator-heron
heron/common/src/java/org/apache/heron/common/utils/topology/GeneralTopologyContextImpl.java
GeneralTopologyContextImpl.getSources
public Map<TopologyAPI.StreamId, TopologyAPI.Grouping> getSources(String componentId) { if (inputs.containsKey(componentId)) { Map<TopologyAPI.StreamId, TopologyAPI.Grouping> retVal = new HashMap<>(); for (TopologyAPI.InputStream istream : inputs.get(componentId)) { retVal.put(istream.getStream(), istream.getGtype()); } return retVal; } else { return null; } }
java
public Map<TopologyAPI.StreamId, TopologyAPI.Grouping> getSources(String componentId) { if (inputs.containsKey(componentId)) { Map<TopologyAPI.StreamId, TopologyAPI.Grouping> retVal = new HashMap<>(); for (TopologyAPI.InputStream istream : inputs.get(componentId)) { retVal.put(istream.getStream(), istream.getGtype()); } return retVal; } else { return null; } }
[ "public", "Map", "<", "TopologyAPI", ".", "StreamId", ",", "TopologyAPI", ".", "Grouping", ">", "getSources", "(", "String", "componentId", ")", "{", "if", "(", "inputs", ".", "containsKey", "(", "componentId", ")", ")", "{", "Map", "<", "TopologyAPI", ".", "StreamId", ",", "TopologyAPI", ".", "Grouping", ">", "retVal", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "TopologyAPI", ".", "InputStream", "istream", ":", "inputs", ".", "get", "(", "componentId", ")", ")", "{", "retVal", ".", "put", "(", "istream", ".", "getStream", "(", ")", ",", "istream", ".", "getGtype", "(", ")", ")", ";", "}", "return", "retVal", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Gets the declared inputs to the specified component. @return A map from subscribed component/stream to the grouping subscribed with.
[ "Gets", "the", "declared", "inputs", "to", "the", "specified", "component", "." ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/common/src/java/org/apache/heron/common/utils/topology/GeneralTopologyContextImpl.java#L204-L215
27,859
apache/incubator-heron
heron/scheduler-core/src/java/org/apache/heron/scheduler/SubmitterMain.java
SubmitterMain.submitTopology
public void submitTopology() throws TopologySubmissionException { // build primary runtime config first Config primaryRuntime = Config.newBuilder() .putAll(LauncherUtils.getInstance().createPrimaryRuntime(topology)).build(); // call launcher directly here if in dry-run mode if (Context.dryRun(config)) { callLauncherRunner(primaryRuntime); return; } // 1. Do prepare work // create an instance of state manager String statemgrClass = Context.stateManagerClass(config); IStateManager statemgr; // Create an instance of the launcher class String launcherClass = Context.launcherClass(config); ILauncher launcher; // create an instance of the uploader class String uploaderClass = Context.uploaderClass(config); IUploader uploader; // create an instance of state manager try { statemgr = ReflectionUtils.newInstance(statemgrClass); } catch (IllegalAccessException | InstantiationException | ClassNotFoundException e) { throw new TopologySubmissionException( String.format("Failed to instantiate state manager class '%s'", statemgrClass), e); } // create an instance of launcher try { launcher = ReflectionUtils.newInstance(launcherClass); } catch (IllegalAccessException | InstantiationException | ClassNotFoundException e) { throw new LauncherException( String.format("Failed to instantiate launcher class '%s'", launcherClass), e); } // create an instance of uploader try { uploader = ReflectionUtils.newInstance(uploaderClass); } catch (IllegalAccessException | InstantiationException | ClassNotFoundException e) { throw new UploaderException( String.format("Failed to instantiate uploader class '%s'", uploaderClass), e); } // Put it in a try block so that we can always clean resources try { // initialize the state manager statemgr.initialize(config); // initialize the uploader uploader.initialize(config); // TODO(mfu): timeout should read from config SchedulerStateManagerAdaptor adaptor = new SchedulerStateManagerAdaptor(statemgr, 5000); // Check if topology is already running validateSubmit(adaptor, topology.getName()); LOG.log(Level.FINE, "Topology {0} to be submitted", topology.getName()); Config runtimeWithoutPackageURI = Config.newBuilder() .putAll(primaryRuntime) .putAll(LauncherUtils.getInstance().createAdaptorRuntime(adaptor)) .put(Key.LAUNCHER_CLASS_INSTANCE, launcher) .build(); PackingPlan packingPlan = LauncherUtils.getInstance() .createPackingPlan(config, runtimeWithoutPackageURI); // The packing plan might call for a number of containers different than the config // settings. If that's the case we need to modify the configs to match. runtimeWithoutPackageURI = updateNumContainersIfNeeded(runtimeWithoutPackageURI, topology, packingPlan); // If the packing plan is valid we will upload necessary packages URI packageURI = uploadPackage(uploader); // Update the runtime config with the packageURI Config runtimeAll = Config.newBuilder() .putAll(runtimeWithoutPackageURI) .put(Key.TOPOLOGY_PACKAGE_URI, packageURI) .build(); callLauncherRunner(runtimeAll); } catch (LauncherException | PackingException e) { // we undo uploading of topology package only if launcher fails to // launch topology, which will throw LauncherException or PackingException uploader.undo(); throw e; } finally { SysUtils.closeIgnoringExceptions(uploader); SysUtils.closeIgnoringExceptions(launcher); SysUtils.closeIgnoringExceptions(statemgr); } }
java
public void submitTopology() throws TopologySubmissionException { // build primary runtime config first Config primaryRuntime = Config.newBuilder() .putAll(LauncherUtils.getInstance().createPrimaryRuntime(topology)).build(); // call launcher directly here if in dry-run mode if (Context.dryRun(config)) { callLauncherRunner(primaryRuntime); return; } // 1. Do prepare work // create an instance of state manager String statemgrClass = Context.stateManagerClass(config); IStateManager statemgr; // Create an instance of the launcher class String launcherClass = Context.launcherClass(config); ILauncher launcher; // create an instance of the uploader class String uploaderClass = Context.uploaderClass(config); IUploader uploader; // create an instance of state manager try { statemgr = ReflectionUtils.newInstance(statemgrClass); } catch (IllegalAccessException | InstantiationException | ClassNotFoundException e) { throw new TopologySubmissionException( String.format("Failed to instantiate state manager class '%s'", statemgrClass), e); } // create an instance of launcher try { launcher = ReflectionUtils.newInstance(launcherClass); } catch (IllegalAccessException | InstantiationException | ClassNotFoundException e) { throw new LauncherException( String.format("Failed to instantiate launcher class '%s'", launcherClass), e); } // create an instance of uploader try { uploader = ReflectionUtils.newInstance(uploaderClass); } catch (IllegalAccessException | InstantiationException | ClassNotFoundException e) { throw new UploaderException( String.format("Failed to instantiate uploader class '%s'", uploaderClass), e); } // Put it in a try block so that we can always clean resources try { // initialize the state manager statemgr.initialize(config); // initialize the uploader uploader.initialize(config); // TODO(mfu): timeout should read from config SchedulerStateManagerAdaptor adaptor = new SchedulerStateManagerAdaptor(statemgr, 5000); // Check if topology is already running validateSubmit(adaptor, topology.getName()); LOG.log(Level.FINE, "Topology {0} to be submitted", topology.getName()); Config runtimeWithoutPackageURI = Config.newBuilder() .putAll(primaryRuntime) .putAll(LauncherUtils.getInstance().createAdaptorRuntime(adaptor)) .put(Key.LAUNCHER_CLASS_INSTANCE, launcher) .build(); PackingPlan packingPlan = LauncherUtils.getInstance() .createPackingPlan(config, runtimeWithoutPackageURI); // The packing plan might call for a number of containers different than the config // settings. If that's the case we need to modify the configs to match. runtimeWithoutPackageURI = updateNumContainersIfNeeded(runtimeWithoutPackageURI, topology, packingPlan); // If the packing plan is valid we will upload necessary packages URI packageURI = uploadPackage(uploader); // Update the runtime config with the packageURI Config runtimeAll = Config.newBuilder() .putAll(runtimeWithoutPackageURI) .put(Key.TOPOLOGY_PACKAGE_URI, packageURI) .build(); callLauncherRunner(runtimeAll); } catch (LauncherException | PackingException e) { // we undo uploading of topology package only if launcher fails to // launch topology, which will throw LauncherException or PackingException uploader.undo(); throw e; } finally { SysUtils.closeIgnoringExceptions(uploader); SysUtils.closeIgnoringExceptions(launcher); SysUtils.closeIgnoringExceptions(statemgr); } }
[ "public", "void", "submitTopology", "(", ")", "throws", "TopologySubmissionException", "{", "// build primary runtime config first", "Config", "primaryRuntime", "=", "Config", ".", "newBuilder", "(", ")", ".", "putAll", "(", "LauncherUtils", ".", "getInstance", "(", ")", ".", "createPrimaryRuntime", "(", "topology", ")", ")", ".", "build", "(", ")", ";", "// call launcher directly here if in dry-run mode", "if", "(", "Context", ".", "dryRun", "(", "config", ")", ")", "{", "callLauncherRunner", "(", "primaryRuntime", ")", ";", "return", ";", "}", "// 1. Do prepare work", "// create an instance of state manager", "String", "statemgrClass", "=", "Context", ".", "stateManagerClass", "(", "config", ")", ";", "IStateManager", "statemgr", ";", "// Create an instance of the launcher class", "String", "launcherClass", "=", "Context", ".", "launcherClass", "(", "config", ")", ";", "ILauncher", "launcher", ";", "// create an instance of the uploader class", "String", "uploaderClass", "=", "Context", ".", "uploaderClass", "(", "config", ")", ";", "IUploader", "uploader", ";", "// create an instance of state manager", "try", "{", "statemgr", "=", "ReflectionUtils", ".", "newInstance", "(", "statemgrClass", ")", ";", "}", "catch", "(", "IllegalAccessException", "|", "InstantiationException", "|", "ClassNotFoundException", "e", ")", "{", "throw", "new", "TopologySubmissionException", "(", "String", ".", "format", "(", "\"Failed to instantiate state manager class '%s'\"", ",", "statemgrClass", ")", ",", "e", ")", ";", "}", "// create an instance of launcher", "try", "{", "launcher", "=", "ReflectionUtils", ".", "newInstance", "(", "launcherClass", ")", ";", "}", "catch", "(", "IllegalAccessException", "|", "InstantiationException", "|", "ClassNotFoundException", "e", ")", "{", "throw", "new", "LauncherException", "(", "String", ".", "format", "(", "\"Failed to instantiate launcher class '%s'\"", ",", "launcherClass", ")", ",", "e", ")", ";", "}", "// create an instance of uploader", "try", "{", "uploader", "=", "ReflectionUtils", ".", "newInstance", "(", "uploaderClass", ")", ";", "}", "catch", "(", "IllegalAccessException", "|", "InstantiationException", "|", "ClassNotFoundException", "e", ")", "{", "throw", "new", "UploaderException", "(", "String", ".", "format", "(", "\"Failed to instantiate uploader class '%s'\"", ",", "uploaderClass", ")", ",", "e", ")", ";", "}", "// Put it in a try block so that we can always clean resources", "try", "{", "// initialize the state manager", "statemgr", ".", "initialize", "(", "config", ")", ";", "// initialize the uploader", "uploader", ".", "initialize", "(", "config", ")", ";", "// TODO(mfu): timeout should read from config", "SchedulerStateManagerAdaptor", "adaptor", "=", "new", "SchedulerStateManagerAdaptor", "(", "statemgr", ",", "5000", ")", ";", "// Check if topology is already running", "validateSubmit", "(", "adaptor", ",", "topology", ".", "getName", "(", ")", ")", ";", "LOG", ".", "log", "(", "Level", ".", "FINE", ",", "\"Topology {0} to be submitted\"", ",", "topology", ".", "getName", "(", ")", ")", ";", "Config", "runtimeWithoutPackageURI", "=", "Config", ".", "newBuilder", "(", ")", ".", "putAll", "(", "primaryRuntime", ")", ".", "putAll", "(", "LauncherUtils", ".", "getInstance", "(", ")", ".", "createAdaptorRuntime", "(", "adaptor", ")", ")", ".", "put", "(", "Key", ".", "LAUNCHER_CLASS_INSTANCE", ",", "launcher", ")", ".", "build", "(", ")", ";", "PackingPlan", "packingPlan", "=", "LauncherUtils", ".", "getInstance", "(", ")", ".", "createPackingPlan", "(", "config", ",", "runtimeWithoutPackageURI", ")", ";", "// The packing plan might call for a number of containers different than the config", "// settings. If that's the case we need to modify the configs to match.", "runtimeWithoutPackageURI", "=", "updateNumContainersIfNeeded", "(", "runtimeWithoutPackageURI", ",", "topology", ",", "packingPlan", ")", ";", "// If the packing plan is valid we will upload necessary packages", "URI", "packageURI", "=", "uploadPackage", "(", "uploader", ")", ";", "// Update the runtime config with the packageURI", "Config", "runtimeAll", "=", "Config", ".", "newBuilder", "(", ")", ".", "putAll", "(", "runtimeWithoutPackageURI", ")", ".", "put", "(", "Key", ".", "TOPOLOGY_PACKAGE_URI", ",", "packageURI", ")", ".", "build", "(", ")", ";", "callLauncherRunner", "(", "runtimeAll", ")", ";", "}", "catch", "(", "LauncherException", "|", "PackingException", "e", ")", "{", "// we undo uploading of topology package only if launcher fails to", "// launch topology, which will throw LauncherException or PackingException", "uploader", ".", "undo", "(", ")", ";", "throw", "e", ";", "}", "finally", "{", "SysUtils", ".", "closeIgnoringExceptions", "(", "uploader", ")", ";", "SysUtils", ".", "closeIgnoringExceptions", "(", "launcher", ")", ";", "SysUtils", ".", "closeIgnoringExceptions", "(", "statemgr", ")", ";", "}", "}" ]
Submit a topology 1. Instantiate necessary resources 2. Valid whether it is legal to submit a topology 3. Call LauncherRunner
[ "Submit", "a", "topology", "1", ".", "Instantiate", "necessary", "resources", "2", ".", "Valid", "whether", "it", "is", "legal", "to", "submit", "a", "topology", "3", ".", "Call", "LauncherRunner" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/scheduler-core/src/java/org/apache/heron/scheduler/SubmitterMain.java#L375-L472
27,860
apache/incubator-heron
heron/schedulers/src/java/org/apache/heron/scheduler/yarn/HeronMasterDriver.java
HeronMasterDriver.scheduleHeronWorkers
void scheduleHeronWorkers(PackingPlan topologyPacking) throws ContainerAllocationException { this.componentRamMap = topologyPacking.getComponentRamDistribution(); scheduleHeronWorkers(topologyPacking.getContainers()); }
java
void scheduleHeronWorkers(PackingPlan topologyPacking) throws ContainerAllocationException { this.componentRamMap = topologyPacking.getComponentRamDistribution(); scheduleHeronWorkers(topologyPacking.getContainers()); }
[ "void", "scheduleHeronWorkers", "(", "PackingPlan", "topologyPacking", ")", "throws", "ContainerAllocationException", "{", "this", ".", "componentRamMap", "=", "topologyPacking", ".", "getComponentRamDistribution", "(", ")", ";", "scheduleHeronWorkers", "(", "topologyPacking", ".", "getContainers", "(", ")", ")", ";", "}" ]
Container allocation is asynchronous. Requests all containers in the input packing plan serially to ensure allocated resources match the required resources.
[ "Container", "allocation", "is", "asynchronous", ".", "Requests", "all", "containers", "in", "the", "input", "packing", "plan", "serially", "to", "ensure", "allocated", "resources", "match", "the", "required", "resources", "." ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/schedulers/src/java/org/apache/heron/scheduler/yarn/HeronMasterDriver.java#L182-L185
27,861
apache/incubator-heron
heron/schedulers/src/java/org/apache/heron/scheduler/yarn/HeronMasterDriver.java
HeronMasterDriver.scheduleHeronWorkers
void scheduleHeronWorkers(Set<ContainerPlan> containers) throws ContainerAllocationException { for (ContainerPlan containerPlan : containers) { int id = containerPlan.getId(); if (containerPlans.containsKey(containerPlan.getId())) { throw new ContainerAllocationException("Received duplicate allocation request for " + id); } Resource reqResource = containerPlan.getRequiredResource(); containerPlans.put(id, containerPlan); requestContainerForWorker(id, new HeronWorker(id, reqResource)); } }
java
void scheduleHeronWorkers(Set<ContainerPlan> containers) throws ContainerAllocationException { for (ContainerPlan containerPlan : containers) { int id = containerPlan.getId(); if (containerPlans.containsKey(containerPlan.getId())) { throw new ContainerAllocationException("Received duplicate allocation request for " + id); } Resource reqResource = containerPlan.getRequiredResource(); containerPlans.put(id, containerPlan); requestContainerForWorker(id, new HeronWorker(id, reqResource)); } }
[ "void", "scheduleHeronWorkers", "(", "Set", "<", "ContainerPlan", ">", "containers", ")", "throws", "ContainerAllocationException", "{", "for", "(", "ContainerPlan", "containerPlan", ":", "containers", ")", "{", "int", "id", "=", "containerPlan", ".", "getId", "(", ")", ";", "if", "(", "containerPlans", ".", "containsKey", "(", "containerPlan", ".", "getId", "(", ")", ")", ")", "{", "throw", "new", "ContainerAllocationException", "(", "\"Received duplicate allocation request for \"", "+", "id", ")", ";", "}", "Resource", "reqResource", "=", "containerPlan", ".", "getRequiredResource", "(", ")", ";", "containerPlans", ".", "put", "(", "id", ",", "containerPlan", ")", ";", "requestContainerForWorker", "(", "id", ",", "new", "HeronWorker", "(", "id", ",", "reqResource", ")", ")", ";", "}", "}" ]
Container allocation is asynchronous. Requests all containers in the input set serially to ensure allocated resources match the required resources.
[ "Container", "allocation", "is", "asynchronous", ".", "Requests", "all", "containers", "in", "the", "input", "set", "serially", "to", "ensure", "allocated", "resources", "match", "the", "required", "resources", "." ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/schedulers/src/java/org/apache/heron/scheduler/yarn/HeronMasterDriver.java#L199-L209
27,862
apache/incubator-heron
heron/schedulers/src/java/org/apache/heron/scheduler/yarn/HeronMasterDriver.java
HeronMasterDriver.killWorkers
public void killWorkers(Set<ContainerPlan> containers) { for (ContainerPlan container : containers) { LOG.log(Level.INFO, "Find and kill container for worker {0}", container.getId()); Optional<HeronWorker> worker = multiKeyWorkerMap.lookupByWorkerId(container.getId()); if (worker.isPresent()) { LOG.log(Level.INFO, "Killing container {0} for worker {1}", new Object[]{worker.get().evaluator.getId(), worker.get().workerId}); AllocatedEvaluator evaluator = multiKeyWorkerMap.detachEvaluatorAndRemove(worker.get()); evaluator.close(); } else { LOG.log(Level.WARNING, "Did not find worker for {0}", container.getId()); } containerPlans.remove(container.getId()); } }
java
public void killWorkers(Set<ContainerPlan> containers) { for (ContainerPlan container : containers) { LOG.log(Level.INFO, "Find and kill container for worker {0}", container.getId()); Optional<HeronWorker> worker = multiKeyWorkerMap.lookupByWorkerId(container.getId()); if (worker.isPresent()) { LOG.log(Level.INFO, "Killing container {0} for worker {1}", new Object[]{worker.get().evaluator.getId(), worker.get().workerId}); AllocatedEvaluator evaluator = multiKeyWorkerMap.detachEvaluatorAndRemove(worker.get()); evaluator.close(); } else { LOG.log(Level.WARNING, "Did not find worker for {0}", container.getId()); } containerPlans.remove(container.getId()); } }
[ "public", "void", "killWorkers", "(", "Set", "<", "ContainerPlan", ">", "containers", ")", "{", "for", "(", "ContainerPlan", "container", ":", "containers", ")", "{", "LOG", ".", "log", "(", "Level", ".", "INFO", ",", "\"Find and kill container for worker {0}\"", ",", "container", ".", "getId", "(", ")", ")", ";", "Optional", "<", "HeronWorker", ">", "worker", "=", "multiKeyWorkerMap", ".", "lookupByWorkerId", "(", "container", ".", "getId", "(", ")", ")", ";", "if", "(", "worker", ".", "isPresent", "(", ")", ")", "{", "LOG", ".", "log", "(", "Level", ".", "INFO", ",", "\"Killing container {0} for worker {1}\"", ",", "new", "Object", "[", "]", "{", "worker", ".", "get", "(", ")", ".", "evaluator", ".", "getId", "(", ")", ",", "worker", ".", "get", "(", ")", ".", "workerId", "}", ")", ";", "AllocatedEvaluator", "evaluator", "=", "multiKeyWorkerMap", ".", "detachEvaluatorAndRemove", "(", "worker", ".", "get", "(", ")", ")", ";", "evaluator", ".", "close", "(", ")", ";", "}", "else", "{", "LOG", ".", "log", "(", "Level", ".", "WARNING", ",", "\"Did not find worker for {0}\"", ",", "container", ".", "getId", "(", ")", ")", ";", "}", "containerPlans", ".", "remove", "(", "container", ".", "getId", "(", ")", ")", ";", "}", "}" ]
Terminates any yarn containers associated with the given containers.
[ "Terminates", "any", "yarn", "containers", "associated", "with", "the", "given", "containers", "." ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/schedulers/src/java/org/apache/heron/scheduler/yarn/HeronMasterDriver.java#L282-L296
27,863
apache/incubator-heron
heron/api/src/java/org/apache/heron/api/windowing/WindowManager.java
WindowManager.restoreState
@SuppressWarnings("unchecked") public void restoreState(Map<String, Serializable> state) { LOG.info("Restoring window manager state"); //restore eviction policy state if (state.get(EVICTION_STATE_KEY) != null) { ((EvictionPolicy) evictionPolicy).restoreState(state.get(EVICTION_STATE_KEY)); } // restore trigger policy state if (state.get(TRIGGER_STATE_KEY) != null) { ((TriggerPolicy) triggerPolicy).restoreState(state.get(TRIGGER_STATE_KEY)); } // restore all pending events to the queue this.queue.addAll((Collection<Event<T>>) state.get(QUEUE)); // restore all expired events this.expiredEvents.addAll((List<T>) state.get(EXPIRED_EVENTS)); // restore all prevWindowEvents this.prevWindowEvents.addAll((Set<Event<T>>) state.get(PRE_WINDOW_EVENTS)); // restore the count of the number events since last expiry this.eventsSinceLastExpiry.set((int) state.get(EVENTS_SINCE_LAST_EXPIRY)); }
java
@SuppressWarnings("unchecked") public void restoreState(Map<String, Serializable> state) { LOG.info("Restoring window manager state"); //restore eviction policy state if (state.get(EVICTION_STATE_KEY) != null) { ((EvictionPolicy) evictionPolicy).restoreState(state.get(EVICTION_STATE_KEY)); } // restore trigger policy state if (state.get(TRIGGER_STATE_KEY) != null) { ((TriggerPolicy) triggerPolicy).restoreState(state.get(TRIGGER_STATE_KEY)); } // restore all pending events to the queue this.queue.addAll((Collection<Event<T>>) state.get(QUEUE)); // restore all expired events this.expiredEvents.addAll((List<T>) state.get(EXPIRED_EVENTS)); // restore all prevWindowEvents this.prevWindowEvents.addAll((Set<Event<T>>) state.get(PRE_WINDOW_EVENTS)); // restore the count of the number events since last expiry this.eventsSinceLastExpiry.set((int) state.get(EVENTS_SINCE_LAST_EXPIRY)); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "void", "restoreState", "(", "Map", "<", "String", ",", "Serializable", ">", "state", ")", "{", "LOG", ".", "info", "(", "\"Restoring window manager state\"", ")", ";", "//restore eviction policy state", "if", "(", "state", ".", "get", "(", "EVICTION_STATE_KEY", ")", "!=", "null", ")", "{", "(", "(", "EvictionPolicy", ")", "evictionPolicy", ")", ".", "restoreState", "(", "state", ".", "get", "(", "EVICTION_STATE_KEY", ")", ")", ";", "}", "// restore trigger policy state", "if", "(", "state", ".", "get", "(", "TRIGGER_STATE_KEY", ")", "!=", "null", ")", "{", "(", "(", "TriggerPolicy", ")", "triggerPolicy", ")", ".", "restoreState", "(", "state", ".", "get", "(", "TRIGGER_STATE_KEY", ")", ")", ";", "}", "// restore all pending events to the queue", "this", ".", "queue", ".", "addAll", "(", "(", "Collection", "<", "Event", "<", "T", ">", ">", ")", "state", ".", "get", "(", "QUEUE", ")", ")", ";", "// restore all expired events", "this", ".", "expiredEvents", ".", "addAll", "(", "(", "List", "<", "T", ">", ")", "state", ".", "get", "(", "EXPIRED_EVENTS", ")", ")", ";", "// restore all prevWindowEvents", "this", ".", "prevWindowEvents", ".", "addAll", "(", "(", "Set", "<", "Event", "<", "T", ">", ">", ")", "state", ".", "get", "(", "PRE_WINDOW_EVENTS", ")", ")", ";", "// restore the count of the number events since last expiry", "this", ".", "eventsSinceLastExpiry", ".", "set", "(", "(", "int", ")", "state", ".", "get", "(", "EVENTS_SINCE_LAST_EXPIRY", ")", ")", ";", "}" ]
Restore state associated with the window manager @param state
[ "Restore", "state", "associated", "with", "the", "window", "manager" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/api/src/java/org/apache/heron/api/windowing/WindowManager.java#L315-L340
27,864
apache/incubator-heron
heron/api/src/java/org/apache/heron/api/windowing/WindowManager.java
WindowManager.getState
public Map<String, Serializable> getState() { Map<String, Serializable> ret = new HashMap<>(); // get potential eviction policy state if (evictionPolicy.getState() != null) { ret.put(EVICTION_STATE_KEY, (Serializable) evictionPolicy.getState()); } // get potential trigger policy state if (triggerPolicy.getState() != null) { ret.put(TRIGGER_STATE_KEY, (Serializable) triggerPolicy.getState()); } ret.put(QUEUE, (Serializable) this.queue); ret.put(EXPIRED_EVENTS, (Serializable) this.expiredEvents); ret.put(PRE_WINDOW_EVENTS, (Serializable) this.prevWindowEvents); ret.put(EVENTS_SINCE_LAST_EXPIRY, this.eventsSinceLastExpiry.get()); return ret; }
java
public Map<String, Serializable> getState() { Map<String, Serializable> ret = new HashMap<>(); // get potential eviction policy state if (evictionPolicy.getState() != null) { ret.put(EVICTION_STATE_KEY, (Serializable) evictionPolicy.getState()); } // get potential trigger policy state if (triggerPolicy.getState() != null) { ret.put(TRIGGER_STATE_KEY, (Serializable) triggerPolicy.getState()); } ret.put(QUEUE, (Serializable) this.queue); ret.put(EXPIRED_EVENTS, (Serializable) this.expiredEvents); ret.put(PRE_WINDOW_EVENTS, (Serializable) this.prevWindowEvents); ret.put(EVENTS_SINCE_LAST_EXPIRY, this.eventsSinceLastExpiry.get()); return ret; }
[ "public", "Map", "<", "String", ",", "Serializable", ">", "getState", "(", ")", "{", "Map", "<", "String", ",", "Serializable", ">", "ret", "=", "new", "HashMap", "<>", "(", ")", ";", "// get potential eviction policy state", "if", "(", "evictionPolicy", ".", "getState", "(", ")", "!=", "null", ")", "{", "ret", ".", "put", "(", "EVICTION_STATE_KEY", ",", "(", "Serializable", ")", "evictionPolicy", ".", "getState", "(", ")", ")", ";", "}", "// get potential trigger policy state", "if", "(", "triggerPolicy", ".", "getState", "(", ")", "!=", "null", ")", "{", "ret", ".", "put", "(", "TRIGGER_STATE_KEY", ",", "(", "Serializable", ")", "triggerPolicy", ".", "getState", "(", ")", ")", ";", "}", "ret", ".", "put", "(", "QUEUE", ",", "(", "Serializable", ")", "this", ".", "queue", ")", ";", "ret", ".", "put", "(", "EXPIRED_EVENTS", ",", "(", "Serializable", ")", "this", ".", "expiredEvents", ")", ";", "ret", ".", "put", "(", "PRE_WINDOW_EVENTS", ",", "(", "Serializable", ")", "this", ".", "prevWindowEvents", ")", ";", "ret", ".", "put", "(", "EVENTS_SINCE_LAST_EXPIRY", ",", "this", ".", "eventsSinceLastExpiry", ".", "get", "(", ")", ")", ";", "return", "ret", ";", "}" ]
Get the state of the window manager @return a Map representing the state of the window manager
[ "Get", "the", "state", "of", "the", "window", "manager" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/api/src/java/org/apache/heron/api/windowing/WindowManager.java#L346-L361
27,865
apache/incubator-heron
heron/scheduler-core/src/java/org/apache/heron/scheduler/utils/SchedulerUtils.java
SchedulerUtils.schedulerCommand
public static String[] schedulerCommand( Config config, Config runtime, List<Integer> freePorts) { List<String> commands = new ArrayList<>(); // The java executable should be "{JAVA_HOME}/bin/java" String javaExecutable = String.format("%s/%s", Context.clusterJavaHome(config), "bin/java"); commands.add(javaExecutable); commands.add("-cp"); // Construct the complete classpath to start scheduler String completeSchedulerProcessClassPath = String.format("%s:%s:%s", Context.schedulerClassPath(config), Context.packingClassPath(config), Context.stateManagerClassPath(config)); commands.add(completeSchedulerProcessClassPath); commands.add("org.apache.heron.scheduler.SchedulerMain"); String[] commandArgs = schedulerCommandArgs(config, runtime, freePorts); commands.addAll(Arrays.asList(commandArgs)); return commands.toArray(new String[0]); }
java
public static String[] schedulerCommand( Config config, Config runtime, List<Integer> freePorts) { List<String> commands = new ArrayList<>(); // The java executable should be "{JAVA_HOME}/bin/java" String javaExecutable = String.format("%s/%s", Context.clusterJavaHome(config), "bin/java"); commands.add(javaExecutable); commands.add("-cp"); // Construct the complete classpath to start scheduler String completeSchedulerProcessClassPath = String.format("%s:%s:%s", Context.schedulerClassPath(config), Context.packingClassPath(config), Context.stateManagerClassPath(config)); commands.add(completeSchedulerProcessClassPath); commands.add("org.apache.heron.scheduler.SchedulerMain"); String[] commandArgs = schedulerCommandArgs(config, runtime, freePorts); commands.addAll(Arrays.asList(commandArgs)); return commands.toArray(new String[0]); }
[ "public", "static", "String", "[", "]", "schedulerCommand", "(", "Config", "config", ",", "Config", "runtime", ",", "List", "<", "Integer", ">", "freePorts", ")", "{", "List", "<", "String", ">", "commands", "=", "new", "ArrayList", "<>", "(", ")", ";", "// The java executable should be \"{JAVA_HOME}/bin/java\"", "String", "javaExecutable", "=", "String", ".", "format", "(", "\"%s/%s\"", ",", "Context", ".", "clusterJavaHome", "(", "config", ")", ",", "\"bin/java\"", ")", ";", "commands", ".", "add", "(", "javaExecutable", ")", ";", "commands", ".", "add", "(", "\"-cp\"", ")", ";", "// Construct the complete classpath to start scheduler", "String", "completeSchedulerProcessClassPath", "=", "String", ".", "format", "(", "\"%s:%s:%s\"", ",", "Context", ".", "schedulerClassPath", "(", "config", ")", ",", "Context", ".", "packingClassPath", "(", "config", ")", ",", "Context", ".", "stateManagerClassPath", "(", "config", ")", ")", ";", "commands", ".", "add", "(", "completeSchedulerProcessClassPath", ")", ";", "commands", ".", "add", "(", "\"org.apache.heron.scheduler.SchedulerMain\"", ")", ";", "String", "[", "]", "commandArgs", "=", "schedulerCommandArgs", "(", "config", ",", "runtime", ",", "freePorts", ")", ";", "commands", ".", "addAll", "(", "Arrays", ".", "asList", "(", "commandArgs", ")", ")", ";", "return", "commands", ".", "toArray", "(", "new", "String", "[", "0", "]", ")", ";", "}" ]
Utils method to construct the command to start heron-scheduler @param config The static Config @param runtime The runtime Config @param freePorts list of free ports @return String[] representing the command to start heron-scheduler
[ "Utils", "method", "to", "construct", "the", "command", "to", "start", "heron", "-", "scheduler" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/scheduler-core/src/java/org/apache/heron/scheduler/utils/SchedulerUtils.java#L117-L140
27,866
apache/incubator-heron
heron/scheduler-core/src/java/org/apache/heron/scheduler/utils/SchedulerUtils.java
SchedulerUtils.schedulerCommandArgs
public static String[] schedulerCommandArgs( Config config, Config runtime, List<Integer> freePorts) { // First let us have some safe checks if (freePorts.size() < PORTS_REQUIRED_FOR_SCHEDULER) { throw new RuntimeException("Failed to find enough ports for executor"); } for (int port : freePorts) { if (port == -1) { throw new RuntimeException("Failed to find available ports for executor"); } } int httpPort = freePorts.get(0); List<String> commands = new ArrayList<>(); commands.add("--cluster"); commands.add(Context.cluster(config)); commands.add("--role"); commands.add(Context.role(config)); commands.add("--environment"); commands.add(Context.environ(config)); commands.add("--topology_name"); commands.add(Context.topologyName(config)); commands.add("--topology_bin"); commands.add(Context.topologyBinaryFile(config)); commands.add("--http_port"); commands.add(Integer.toString(httpPort)); return commands.toArray(new String[0]); }
java
public static String[] schedulerCommandArgs( Config config, Config runtime, List<Integer> freePorts) { // First let us have some safe checks if (freePorts.size() < PORTS_REQUIRED_FOR_SCHEDULER) { throw new RuntimeException("Failed to find enough ports for executor"); } for (int port : freePorts) { if (port == -1) { throw new RuntimeException("Failed to find available ports for executor"); } } int httpPort = freePorts.get(0); List<String> commands = new ArrayList<>(); commands.add("--cluster"); commands.add(Context.cluster(config)); commands.add("--role"); commands.add(Context.role(config)); commands.add("--environment"); commands.add(Context.environ(config)); commands.add("--topology_name"); commands.add(Context.topologyName(config)); commands.add("--topology_bin"); commands.add(Context.topologyBinaryFile(config)); commands.add("--http_port"); commands.add(Integer.toString(httpPort)); return commands.toArray(new String[0]); }
[ "public", "static", "String", "[", "]", "schedulerCommandArgs", "(", "Config", "config", ",", "Config", "runtime", ",", "List", "<", "Integer", ">", "freePorts", ")", "{", "// First let us have some safe checks", "if", "(", "freePorts", ".", "size", "(", ")", "<", "PORTS_REQUIRED_FOR_SCHEDULER", ")", "{", "throw", "new", "RuntimeException", "(", "\"Failed to find enough ports for executor\"", ")", ";", "}", "for", "(", "int", "port", ":", "freePorts", ")", "{", "if", "(", "port", "==", "-", "1", ")", "{", "throw", "new", "RuntimeException", "(", "\"Failed to find available ports for executor\"", ")", ";", "}", "}", "int", "httpPort", "=", "freePorts", ".", "get", "(", "0", ")", ";", "List", "<", "String", ">", "commands", "=", "new", "ArrayList", "<>", "(", ")", ";", "commands", ".", "add", "(", "\"--cluster\"", ")", ";", "commands", ".", "add", "(", "Context", ".", "cluster", "(", "config", ")", ")", ";", "commands", ".", "add", "(", "\"--role\"", ")", ";", "commands", ".", "add", "(", "Context", ".", "role", "(", "config", ")", ")", ";", "commands", ".", "add", "(", "\"--environment\"", ")", ";", "commands", ".", "add", "(", "Context", ".", "environ", "(", "config", ")", ")", ";", "commands", ".", "add", "(", "\"--topology_name\"", ")", ";", "commands", ".", "add", "(", "Context", ".", "topologyName", "(", "config", ")", ")", ";", "commands", ".", "add", "(", "\"--topology_bin\"", ")", ";", "commands", ".", "add", "(", "Context", ".", "topologyBinaryFile", "(", "config", ")", ")", ";", "commands", ".", "add", "(", "\"--http_port\"", ")", ";", "commands", ".", "add", "(", "Integer", ".", "toString", "(", "httpPort", ")", ")", ";", "return", "commands", ".", "toArray", "(", "new", "String", "[", "0", "]", ")", ";", "}" ]
Util method to get the arguments to the heron scheduler. @param config The static Config @param runtime The runtime Config @param freePorts list of free ports @return String[] representing the arguments to start heron-scheduler
[ "Util", "method", "to", "get", "the", "arguments", "to", "the", "heron", "scheduler", "." ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/scheduler-core/src/java/org/apache/heron/scheduler/utils/SchedulerUtils.java#L150-L180
27,867
apache/incubator-heron
heron/scheduler-core/src/java/org/apache/heron/scheduler/utils/SchedulerUtils.java
SchedulerUtils.executorCommandArgs
public static String[] executorCommandArgs( Config config, Config runtime, Map<ExecutorPort, String> ports, String containerIndex) { List<String> args = new ArrayList<>(); addExecutorTopologyArgs(args, config, runtime); addExecutorContainerArgs(args, ports, containerIndex); return args.toArray(new String[args.size()]); }
java
public static String[] executorCommandArgs( Config config, Config runtime, Map<ExecutorPort, String> ports, String containerIndex) { List<String> args = new ArrayList<>(); addExecutorTopologyArgs(args, config, runtime); addExecutorContainerArgs(args, ports, containerIndex); return args.toArray(new String[args.size()]); }
[ "public", "static", "String", "[", "]", "executorCommandArgs", "(", "Config", "config", ",", "Config", "runtime", ",", "Map", "<", "ExecutorPort", ",", "String", ">", "ports", ",", "String", "containerIndex", ")", "{", "List", "<", "String", ">", "args", "=", "new", "ArrayList", "<>", "(", ")", ";", "addExecutorTopologyArgs", "(", "args", ",", "config", ",", "runtime", ")", ";", "addExecutorContainerArgs", "(", "args", ",", "ports", ",", "containerIndex", ")", ";", "return", "args", ".", "toArray", "(", "new", "String", "[", "args", ".", "size", "(", ")", "]", ")", ";", "}" ]
Util method to get the arguments to the heron executor. This method creates the arguments without the container index, which is the first argument to the executor @param config The static Config @param runtime The runtime Config @param ports a map of ports to use where the key indicate the port type and the value is the port @param containerIndex The index of the current container @return String[] representing the arguments to start heron-executor
[ "Util", "method", "to", "get", "the", "arguments", "to", "the", "heron", "executor", ".", "This", "method", "creates", "the", "arguments", "without", "the", "container", "index", "which", "is", "the", "first", "argument", "to", "the", "executor" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/scheduler-core/src/java/org/apache/heron/scheduler/utils/SchedulerUtils.java#L235-L242
27,868
apache/incubator-heron
heron/scheduler-core/src/java/org/apache/heron/scheduler/utils/SchedulerUtils.java
SchedulerUtils.addExecutorContainerArgs
public static void addExecutorContainerArgs( List<String> args, Map<ExecutorPort, String> ports, String containerIndex) { String masterPort = ExecutorPort.getPort(ExecutorPort.MASTER_PORT, ports); String tmasterControllerPort = ExecutorPort.getPort( ExecutorPort.TMASTER_CONTROLLER_PORT, ports); String tmasterStatsPort = ExecutorPort.getPort(ExecutorPort.TMASTER_STATS_PORT, ports); String shellPort = ExecutorPort.getPort(ExecutorPort.SHELL_PORT, ports); String metricsmgrPort = ExecutorPort.getPort(ExecutorPort.METRICS_MANAGER_PORT, ports); String schedulerPort = ExecutorPort.getPort(ExecutorPort.SCHEDULER_PORT, ports); String metricsCacheMasterPort = ExecutorPort.getPort( ExecutorPort.METRICS_CACHE_MASTER_PORT, ports); String metricsCacheStatsPort = ExecutorPort.getPort( ExecutorPort.METRICS_CACHE_STATS_PORT, ports); String ckptmgrPort = ExecutorPort.getPort(ExecutorPort.CHECKPOINT_MANAGER_PORT, ports); String remoteDebuggerPorts = ExecutorPort.getPort( ExecutorPort.JVM_REMOTE_DEBUGGER_PORTS, ports); if (containerIndex != null) { args.add(createCommandArg(ExecutorFlag.Shard, containerIndex)); } args.add(createCommandArg(ExecutorFlag.MasterPort, masterPort)); args.add(createCommandArg(ExecutorFlag.TMasterControllerPort, tmasterControllerPort)); args.add(createCommandArg(ExecutorFlag.TMasterStatsPort, tmasterStatsPort)); args.add(createCommandArg(ExecutorFlag.ShellPort, shellPort)); args.add(createCommandArg(ExecutorFlag.MetricsManagerPort, metricsmgrPort)); args.add(createCommandArg(ExecutorFlag.SchedulerPort, schedulerPort)); args.add(createCommandArg(ExecutorFlag.MetricsCacheManagerMasterPort, metricsCacheMasterPort)); args.add(createCommandArg(ExecutorFlag.MetricsCacheManagerStatsPort, metricsCacheStatsPort)); args.add(createCommandArg(ExecutorFlag.CheckpointManagerPort, ckptmgrPort)); if (remoteDebuggerPorts != null) { args.add(createCommandArg(ExecutorFlag.JvmRemoteDebuggerPorts, remoteDebuggerPorts)); } }
java
public static void addExecutorContainerArgs( List<String> args, Map<ExecutorPort, String> ports, String containerIndex) { String masterPort = ExecutorPort.getPort(ExecutorPort.MASTER_PORT, ports); String tmasterControllerPort = ExecutorPort.getPort( ExecutorPort.TMASTER_CONTROLLER_PORT, ports); String tmasterStatsPort = ExecutorPort.getPort(ExecutorPort.TMASTER_STATS_PORT, ports); String shellPort = ExecutorPort.getPort(ExecutorPort.SHELL_PORT, ports); String metricsmgrPort = ExecutorPort.getPort(ExecutorPort.METRICS_MANAGER_PORT, ports); String schedulerPort = ExecutorPort.getPort(ExecutorPort.SCHEDULER_PORT, ports); String metricsCacheMasterPort = ExecutorPort.getPort( ExecutorPort.METRICS_CACHE_MASTER_PORT, ports); String metricsCacheStatsPort = ExecutorPort.getPort( ExecutorPort.METRICS_CACHE_STATS_PORT, ports); String ckptmgrPort = ExecutorPort.getPort(ExecutorPort.CHECKPOINT_MANAGER_PORT, ports); String remoteDebuggerPorts = ExecutorPort.getPort( ExecutorPort.JVM_REMOTE_DEBUGGER_PORTS, ports); if (containerIndex != null) { args.add(createCommandArg(ExecutorFlag.Shard, containerIndex)); } args.add(createCommandArg(ExecutorFlag.MasterPort, masterPort)); args.add(createCommandArg(ExecutorFlag.TMasterControllerPort, tmasterControllerPort)); args.add(createCommandArg(ExecutorFlag.TMasterStatsPort, tmasterStatsPort)); args.add(createCommandArg(ExecutorFlag.ShellPort, shellPort)); args.add(createCommandArg(ExecutorFlag.MetricsManagerPort, metricsmgrPort)); args.add(createCommandArg(ExecutorFlag.SchedulerPort, schedulerPort)); args.add(createCommandArg(ExecutorFlag.MetricsCacheManagerMasterPort, metricsCacheMasterPort)); args.add(createCommandArg(ExecutorFlag.MetricsCacheManagerStatsPort, metricsCacheStatsPort)); args.add(createCommandArg(ExecutorFlag.CheckpointManagerPort, ckptmgrPort)); if (remoteDebuggerPorts != null) { args.add(createCommandArg(ExecutorFlag.JvmRemoteDebuggerPorts, remoteDebuggerPorts)); } }
[ "public", "static", "void", "addExecutorContainerArgs", "(", "List", "<", "String", ">", "args", ",", "Map", "<", "ExecutorPort", ",", "String", ">", "ports", ",", "String", "containerIndex", ")", "{", "String", "masterPort", "=", "ExecutorPort", ".", "getPort", "(", "ExecutorPort", ".", "MASTER_PORT", ",", "ports", ")", ";", "String", "tmasterControllerPort", "=", "ExecutorPort", ".", "getPort", "(", "ExecutorPort", ".", "TMASTER_CONTROLLER_PORT", ",", "ports", ")", ";", "String", "tmasterStatsPort", "=", "ExecutorPort", ".", "getPort", "(", "ExecutorPort", ".", "TMASTER_STATS_PORT", ",", "ports", ")", ";", "String", "shellPort", "=", "ExecutorPort", ".", "getPort", "(", "ExecutorPort", ".", "SHELL_PORT", ",", "ports", ")", ";", "String", "metricsmgrPort", "=", "ExecutorPort", ".", "getPort", "(", "ExecutorPort", ".", "METRICS_MANAGER_PORT", ",", "ports", ")", ";", "String", "schedulerPort", "=", "ExecutorPort", ".", "getPort", "(", "ExecutorPort", ".", "SCHEDULER_PORT", ",", "ports", ")", ";", "String", "metricsCacheMasterPort", "=", "ExecutorPort", ".", "getPort", "(", "ExecutorPort", ".", "METRICS_CACHE_MASTER_PORT", ",", "ports", ")", ";", "String", "metricsCacheStatsPort", "=", "ExecutorPort", ".", "getPort", "(", "ExecutorPort", ".", "METRICS_CACHE_STATS_PORT", ",", "ports", ")", ";", "String", "ckptmgrPort", "=", "ExecutorPort", ".", "getPort", "(", "ExecutorPort", ".", "CHECKPOINT_MANAGER_PORT", ",", "ports", ")", ";", "String", "remoteDebuggerPorts", "=", "ExecutorPort", ".", "getPort", "(", "ExecutorPort", ".", "JVM_REMOTE_DEBUGGER_PORTS", ",", "ports", ")", ";", "if", "(", "containerIndex", "!=", "null", ")", "{", "args", ".", "add", "(", "createCommandArg", "(", "ExecutorFlag", ".", "Shard", ",", "containerIndex", ")", ")", ";", "}", "args", ".", "add", "(", "createCommandArg", "(", "ExecutorFlag", ".", "MasterPort", ",", "masterPort", ")", ")", ";", "args", ".", "add", "(", "createCommandArg", "(", "ExecutorFlag", ".", "TMasterControllerPort", ",", "tmasterControllerPort", ")", ")", ";", "args", ".", "add", "(", "createCommandArg", "(", "ExecutorFlag", ".", "TMasterStatsPort", ",", "tmasterStatsPort", ")", ")", ";", "args", ".", "add", "(", "createCommandArg", "(", "ExecutorFlag", ".", "ShellPort", ",", "shellPort", ")", ")", ";", "args", ".", "add", "(", "createCommandArg", "(", "ExecutorFlag", ".", "MetricsManagerPort", ",", "metricsmgrPort", ")", ")", ";", "args", ".", "add", "(", "createCommandArg", "(", "ExecutorFlag", ".", "SchedulerPort", ",", "schedulerPort", ")", ")", ";", "args", ".", "add", "(", "createCommandArg", "(", "ExecutorFlag", ".", "MetricsCacheManagerMasterPort", ",", "metricsCacheMasterPort", ")", ")", ";", "args", ".", "add", "(", "createCommandArg", "(", "ExecutorFlag", ".", "MetricsCacheManagerStatsPort", ",", "metricsCacheStatsPort", ")", ")", ";", "args", ".", "add", "(", "createCommandArg", "(", "ExecutorFlag", ".", "CheckpointManagerPort", ",", "ckptmgrPort", ")", ")", ";", "if", "(", "remoteDebuggerPorts", "!=", "null", ")", "{", "args", ".", "add", "(", "createCommandArg", "(", "ExecutorFlag", ".", "JvmRemoteDebuggerPorts", ",", "remoteDebuggerPorts", ")", ")", ";", "}", "}" ]
Util method to parse port map and container id and translate them into arguments to be used by executor @param args The list to accept new topology arguments @param ports a map of ports to use where the key indicate the port type and the value is the port @param containerIndex The index of the current container
[ "Util", "method", "to", "parse", "port", "map", "and", "container", "id", "and", "translate", "them", "into", "arguments", "to", "be", "used", "by", "executor" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/scheduler-core/src/java/org/apache/heron/scheduler/utils/SchedulerUtils.java#L334-L368
27,869
apache/incubator-heron
heron/scheduler-core/src/java/org/apache/heron/scheduler/utils/SchedulerUtils.java
SchedulerUtils.setLibSchedulerLocation
public static boolean setLibSchedulerLocation( Config runtime, IScheduler scheduler, boolean isService) { // Dummy value since there is no scheduler running as service final String endpoint = "scheduler_as_lib_no_endpoint"; return setSchedulerLocation(runtime, endpoint, scheduler); }
java
public static boolean setLibSchedulerLocation( Config runtime, IScheduler scheduler, boolean isService) { // Dummy value since there is no scheduler running as service final String endpoint = "scheduler_as_lib_no_endpoint"; return setSchedulerLocation(runtime, endpoint, scheduler); }
[ "public", "static", "boolean", "setLibSchedulerLocation", "(", "Config", "runtime", ",", "IScheduler", "scheduler", ",", "boolean", "isService", ")", "{", "// Dummy value since there is no scheduler running as service", "final", "String", "endpoint", "=", "\"scheduler_as_lib_no_endpoint\"", ";", "return", "setSchedulerLocation", "(", "runtime", ",", "endpoint", ",", "scheduler", ")", ";", "}" ]
Set the location of scheduler for other processes to discover, when invoke IScheduler as a library on client side @param runtime the runtime configuration @param scheduler the IScheduler to provide more info @param isService true if the scheduler is a service; false otherwise
[ "Set", "the", "location", "of", "scheduler", "for", "other", "processes", "to", "discover", "when", "invoke", "IScheduler", "as", "a", "library", "on", "client", "side" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/scheduler-core/src/java/org/apache/heron/scheduler/utils/SchedulerUtils.java#L386-L393
27,870
apache/incubator-heron
heron/scheduler-core/src/java/org/apache/heron/scheduler/utils/SchedulerUtils.java
SchedulerUtils.setSchedulerLocation
public static boolean setSchedulerLocation( Config runtime, String schedulerEndpoint, IScheduler scheduler) { // Set scheduler location to host:port by default. Overwrite scheduler location if behind DNS. Scheduler.SchedulerLocation.Builder builder = Scheduler.SchedulerLocation.newBuilder() .setTopologyName(Runtime.topologyName(runtime)) .setHttpEndpoint(schedulerEndpoint); // Set the job link in SchedulerLocation if any List<String> jobLinks = scheduler.getJobLinks(); // Check whether IScheduler provides valid job link if (jobLinks != null) { builder.addAllJobPageLink(jobLinks); } Scheduler.SchedulerLocation location = builder.build(); LOG.log(Level.INFO, "Setting Scheduler locations: {0}", location); SchedulerStateManagerAdaptor statemgr = Runtime.schedulerStateManagerAdaptor(runtime); Boolean result = statemgr.setSchedulerLocation(location, Runtime.topologyName(runtime)); if (result == null || !result) { LOG.severe("Failed to set Scheduler location"); return false; } return true; }
java
public static boolean setSchedulerLocation( Config runtime, String schedulerEndpoint, IScheduler scheduler) { // Set scheduler location to host:port by default. Overwrite scheduler location if behind DNS. Scheduler.SchedulerLocation.Builder builder = Scheduler.SchedulerLocation.newBuilder() .setTopologyName(Runtime.topologyName(runtime)) .setHttpEndpoint(schedulerEndpoint); // Set the job link in SchedulerLocation if any List<String> jobLinks = scheduler.getJobLinks(); // Check whether IScheduler provides valid job link if (jobLinks != null) { builder.addAllJobPageLink(jobLinks); } Scheduler.SchedulerLocation location = builder.build(); LOG.log(Level.INFO, "Setting Scheduler locations: {0}", location); SchedulerStateManagerAdaptor statemgr = Runtime.schedulerStateManagerAdaptor(runtime); Boolean result = statemgr.setSchedulerLocation(location, Runtime.topologyName(runtime)); if (result == null || !result) { LOG.severe("Failed to set Scheduler location"); return false; } return true; }
[ "public", "static", "boolean", "setSchedulerLocation", "(", "Config", "runtime", ",", "String", "schedulerEndpoint", ",", "IScheduler", "scheduler", ")", "{", "// Set scheduler location to host:port by default. Overwrite scheduler location if behind DNS.", "Scheduler", ".", "SchedulerLocation", ".", "Builder", "builder", "=", "Scheduler", ".", "SchedulerLocation", ".", "newBuilder", "(", ")", ".", "setTopologyName", "(", "Runtime", ".", "topologyName", "(", "runtime", ")", ")", ".", "setHttpEndpoint", "(", "schedulerEndpoint", ")", ";", "// Set the job link in SchedulerLocation if any", "List", "<", "String", ">", "jobLinks", "=", "scheduler", ".", "getJobLinks", "(", ")", ";", "// Check whether IScheduler provides valid job link", "if", "(", "jobLinks", "!=", "null", ")", "{", "builder", ".", "addAllJobPageLink", "(", "jobLinks", ")", ";", "}", "Scheduler", ".", "SchedulerLocation", "location", "=", "builder", ".", "build", "(", ")", ";", "LOG", ".", "log", "(", "Level", ".", "INFO", ",", "\"Setting Scheduler locations: {0}\"", ",", "location", ")", ";", "SchedulerStateManagerAdaptor", "statemgr", "=", "Runtime", ".", "schedulerStateManagerAdaptor", "(", "runtime", ")", ";", "Boolean", "result", "=", "statemgr", ".", "setSchedulerLocation", "(", "location", ",", "Runtime", ".", "topologyName", "(", "runtime", ")", ")", ";", "if", "(", "result", "==", "null", "||", "!", "result", ")", "{", "LOG", ".", "severe", "(", "\"Failed to set Scheduler location\"", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}" ]
Set the location of scheduler for other processes to discover @param runtime the runtime configuration @param schedulerEndpoint the endpoint that scheduler listens for receives requests @param scheduler the IScheduler to provide more info
[ "Set", "the", "location", "of", "scheduler", "for", "other", "processes", "to", "discover" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/scheduler-core/src/java/org/apache/heron/scheduler/utils/SchedulerUtils.java#L402-L432
27,871
apache/incubator-heron
heron/scheduler-core/src/java/org/apache/heron/scheduler/utils/SchedulerUtils.java
SchedulerUtils.constructSchedulerResponse
public static Scheduler.SchedulerResponse constructSchedulerResponse(boolean isOK) { Common.Status.Builder status = Common.Status.newBuilder(); if (isOK) { status.setStatus(Common.StatusCode.OK); } else { status.setStatus(Common.StatusCode.NOTOK); } return Scheduler.SchedulerResponse.newBuilder(). setStatus(status). build(); }
java
public static Scheduler.SchedulerResponse constructSchedulerResponse(boolean isOK) { Common.Status.Builder status = Common.Status.newBuilder(); if (isOK) { status.setStatus(Common.StatusCode.OK); } else { status.setStatus(Common.StatusCode.NOTOK); } return Scheduler.SchedulerResponse.newBuilder(). setStatus(status). build(); }
[ "public", "static", "Scheduler", ".", "SchedulerResponse", "constructSchedulerResponse", "(", "boolean", "isOK", ")", "{", "Common", ".", "Status", ".", "Builder", "status", "=", "Common", ".", "Status", ".", "newBuilder", "(", ")", ";", "if", "(", "isOK", ")", "{", "status", ".", "setStatus", "(", "Common", ".", "StatusCode", ".", "OK", ")", ";", "}", "else", "{", "status", ".", "setStatus", "(", "Common", ".", "StatusCode", ".", "NOTOK", ")", ";", "}", "return", "Scheduler", ".", "SchedulerResponse", ".", "newBuilder", "(", ")", ".", "setStatus", "(", "status", ")", ".", "build", "(", ")", ";", "}" ]
construct heron scheduler response basing on the given result @param isOK whether the request successful
[ "construct", "heron", "scheduler", "response", "basing", "on", "the", "given", "result" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/scheduler-core/src/java/org/apache/heron/scheduler/utils/SchedulerUtils.java#L439-L450
27,872
apache/incubator-heron
heron/scheduler-core/src/java/org/apache/heron/scheduler/utils/SchedulerUtils.java
SchedulerUtils.createOrCleanDirectory
public static boolean createOrCleanDirectory(String directory) { // if the directory does not exist, create it. if (!FileUtils.isDirectoryExists(directory)) { LOG.fine("The directory does not exist; creating it."); if (!FileUtils.createDirectory(directory)) { LOG.severe("Failed to create directory: " + directory); return false; } } // Cleanup the directory if (!FileUtils.cleanDir(directory)) { LOG.severe("Failed to clean directory: " + directory); return false; } return true; }
java
public static boolean createOrCleanDirectory(String directory) { // if the directory does not exist, create it. if (!FileUtils.isDirectoryExists(directory)) { LOG.fine("The directory does not exist; creating it."); if (!FileUtils.createDirectory(directory)) { LOG.severe("Failed to create directory: " + directory); return false; } } // Cleanup the directory if (!FileUtils.cleanDir(directory)) { LOG.severe("Failed to clean directory: " + directory); return false; } return true; }
[ "public", "static", "boolean", "createOrCleanDirectory", "(", "String", "directory", ")", "{", "// if the directory does not exist, create it.", "if", "(", "!", "FileUtils", ".", "isDirectoryExists", "(", "directory", ")", ")", "{", "LOG", ".", "fine", "(", "\"The directory does not exist; creating it.\"", ")", ";", "if", "(", "!", "FileUtils", ".", "createDirectory", "(", "directory", ")", ")", "{", "LOG", ".", "severe", "(", "\"Failed to create directory: \"", "+", "directory", ")", ";", "return", "false", ";", "}", "}", "// Cleanup the directory", "if", "(", "!", "FileUtils", ".", "cleanDir", "(", "directory", ")", ")", "{", "LOG", ".", "severe", "(", "\"Failed to clean directory: \"", "+", "directory", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}" ]
Create the directory if it does not exist otherwise clean the directory. @param directory the working directory to setup @return true if successful
[ "Create", "the", "directory", "if", "it", "does", "not", "exist", "otherwise", "clean", "the", "directory", "." ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/scheduler-core/src/java/org/apache/heron/scheduler/utils/SchedulerUtils.java#L498-L515
27,873
apache/incubator-heron
heron/scheduler-core/src/java/org/apache/heron/scheduler/utils/SchedulerUtils.java
SchedulerUtils.curlAndExtractPackage
public static boolean curlAndExtractPackage( String workingDirectory, String packageURI, String packageDestination, boolean isDeletePackage, boolean isVerbose) { // curl the package to the working directory and extract it LOG.log(Level.FINE, "Fetching package {0}", packageURI); LOG.fine("Fetched package can overwrite old one."); if (!ShellUtils.curlPackage( packageURI, packageDestination, isVerbose, false)) { LOG.severe("Failed to fetch package."); return false; } // untar the heron core release package in the working directory LOG.log(Level.FINE, "Extracting the package {0}", packageURI); if (!ShellUtils.extractPackage( packageDestination, workingDirectory, isVerbose, false)) { LOG.severe("Failed to extract package."); return false; } // remove the core release package if (isDeletePackage && !FileUtils.deleteFile(packageDestination)) { LOG.warning("Failed to delete the package: " + packageDestination); } return true; }
java
public static boolean curlAndExtractPackage( String workingDirectory, String packageURI, String packageDestination, boolean isDeletePackage, boolean isVerbose) { // curl the package to the working directory and extract it LOG.log(Level.FINE, "Fetching package {0}", packageURI); LOG.fine("Fetched package can overwrite old one."); if (!ShellUtils.curlPackage( packageURI, packageDestination, isVerbose, false)) { LOG.severe("Failed to fetch package."); return false; } // untar the heron core release package in the working directory LOG.log(Level.FINE, "Extracting the package {0}", packageURI); if (!ShellUtils.extractPackage( packageDestination, workingDirectory, isVerbose, false)) { LOG.severe("Failed to extract package."); return false; } // remove the core release package if (isDeletePackage && !FileUtils.deleteFile(packageDestination)) { LOG.warning("Failed to delete the package: " + packageDestination); } return true; }
[ "public", "static", "boolean", "curlAndExtractPackage", "(", "String", "workingDirectory", ",", "String", "packageURI", ",", "String", "packageDestination", ",", "boolean", "isDeletePackage", ",", "boolean", "isVerbose", ")", "{", "// curl the package to the working directory and extract it", "LOG", ".", "log", "(", "Level", ".", "FINE", ",", "\"Fetching package {0}\"", ",", "packageURI", ")", ";", "LOG", ".", "fine", "(", "\"Fetched package can overwrite old one.\"", ")", ";", "if", "(", "!", "ShellUtils", ".", "curlPackage", "(", "packageURI", ",", "packageDestination", ",", "isVerbose", ",", "false", ")", ")", "{", "LOG", ".", "severe", "(", "\"Failed to fetch package.\"", ")", ";", "return", "false", ";", "}", "// untar the heron core release package in the working directory", "LOG", ".", "log", "(", "Level", ".", "FINE", ",", "\"Extracting the package {0}\"", ",", "packageURI", ")", ";", "if", "(", "!", "ShellUtils", ".", "extractPackage", "(", "packageDestination", ",", "workingDirectory", ",", "isVerbose", ",", "false", ")", ")", "{", "LOG", ".", "severe", "(", "\"Failed to extract package.\"", ")", ";", "return", "false", ";", "}", "// remove the core release package", "if", "(", "isDeletePackage", "&&", "!", "FileUtils", ".", "deleteFile", "(", "packageDestination", ")", ")", "{", "LOG", ".", "warning", "(", "\"Failed to delete the package: \"", "+", "packageDestination", ")", ";", "}", "return", "true", ";", "}" ]
Curl a package, extract it to working directory @param workingDirectory the working directory to setup @param packageURI the URL of core release package @param packageDestination the destination of the core release package fetched @param isDeletePackage delete the package curled or not @param isVerbose display verbose output or not @return true if successful
[ "Curl", "a", "package", "extract", "it", "to", "working", "directory" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/scheduler-core/src/java/org/apache/heron/scheduler/utils/SchedulerUtils.java#L533-L562
27,874
apache/incubator-heron
heron/scheduler-core/src/java/org/apache/heron/scheduler/utils/SchedulerUtils.java
SchedulerUtils.persistUpdatedPackingPlan
public static void persistUpdatedPackingPlan(String topologyName, PackingPlan updatedPackingPlan, SchedulerStateManagerAdaptor stateManager) { LOG.log(Level.INFO, "Updating scheduled-resource in packing plan: {0}", topologyName); PackingPlanProtoSerializer serializer = new PackingPlanProtoSerializer(); if (!stateManager.updatePackingPlan(serializer.toProto(updatedPackingPlan), topologyName)) { throw new RuntimeException(String.format( "Failed to update packing plan for topology %s", topologyName)); } }
java
public static void persistUpdatedPackingPlan(String topologyName, PackingPlan updatedPackingPlan, SchedulerStateManagerAdaptor stateManager) { LOG.log(Level.INFO, "Updating scheduled-resource in packing plan: {0}", topologyName); PackingPlanProtoSerializer serializer = new PackingPlanProtoSerializer(); if (!stateManager.updatePackingPlan(serializer.toProto(updatedPackingPlan), topologyName)) { throw new RuntimeException(String.format( "Failed to update packing plan for topology %s", topologyName)); } }
[ "public", "static", "void", "persistUpdatedPackingPlan", "(", "String", "topologyName", ",", "PackingPlan", "updatedPackingPlan", ",", "SchedulerStateManagerAdaptor", "stateManager", ")", "{", "LOG", ".", "log", "(", "Level", ".", "INFO", ",", "\"Updating scheduled-resource in packing plan: {0}\"", ",", "topologyName", ")", ";", "PackingPlanProtoSerializer", "serializer", "=", "new", "PackingPlanProtoSerializer", "(", ")", ";", "if", "(", "!", "stateManager", ".", "updatePackingPlan", "(", "serializer", ".", "toProto", "(", "updatedPackingPlan", ")", ",", "topologyName", ")", ")", "{", "throw", "new", "RuntimeException", "(", "String", ".", "format", "(", "\"Failed to update packing plan for topology %s\"", ",", "topologyName", ")", ")", ";", "}", "}" ]
Replaces persisted packing plan in state manager.
[ "Replaces", "persisted", "packing", "plan", "in", "state", "manager", "." ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/scheduler-core/src/java/org/apache/heron/scheduler/utils/SchedulerUtils.java#L567-L577
27,875
apache/incubator-heron
heron/packing/src/java/org/apache/heron/packing/builder/PackingPlanBuilder.java
PackingPlanBuilder.build
public PackingPlan build() { assertResourceSettings(); Set<PackingPlan.ContainerPlan> containerPlans = buildContainerPlans(this.containers); return new PackingPlan(topologyId, containerPlans); }
java
public PackingPlan build() { assertResourceSettings(); Set<PackingPlan.ContainerPlan> containerPlans = buildContainerPlans(this.containers); return new PackingPlan(topologyId, containerPlans); }
[ "public", "PackingPlan", "build", "(", ")", "{", "assertResourceSettings", "(", ")", ";", "Set", "<", "PackingPlan", ".", "ContainerPlan", ">", "containerPlans", "=", "buildContainerPlans", "(", "this", ".", "containers", ")", ";", "return", "new", "PackingPlan", "(", "topologyId", ",", "containerPlans", ")", ";", "}" ]
build container plan sets by summing up instance resources
[ "build", "container", "plan", "sets", "by", "summing", "up", "instance", "resources" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/packing/src/java/org/apache/heron/packing/builder/PackingPlanBuilder.java#L250-L254
27,876
apache/incubator-heron
heron/packing/src/java/org/apache/heron/packing/builder/PackingPlanBuilder.java
PackingPlanBuilder.buildContainerPlans
private static Set<PackingPlan.ContainerPlan> buildContainerPlans( Map<Integer, Container> containerInstances) { Set<PackingPlan.ContainerPlan> containerPlans = new LinkedHashSet<>(); for (Integer containerId : containerInstances.keySet()) { Container container = containerInstances.get(containerId); if (container.getInstances().size() == 0) { continue; } Resource totalUsedResources = container.getTotalUsedResources(); Resource resource = new Resource( Math.round(totalUsedResources.getCpu()), totalUsedResources.getRam(), totalUsedResources.getDisk()); PackingPlan.ContainerPlan containerPlan = new PackingPlan.ContainerPlan(containerId, container.getInstances(), resource); containerPlans.add(containerPlan); } return containerPlans; }
java
private static Set<PackingPlan.ContainerPlan> buildContainerPlans( Map<Integer, Container> containerInstances) { Set<PackingPlan.ContainerPlan> containerPlans = new LinkedHashSet<>(); for (Integer containerId : containerInstances.keySet()) { Container container = containerInstances.get(containerId); if (container.getInstances().size() == 0) { continue; } Resource totalUsedResources = container.getTotalUsedResources(); Resource resource = new Resource( Math.round(totalUsedResources.getCpu()), totalUsedResources.getRam(), totalUsedResources.getDisk()); PackingPlan.ContainerPlan containerPlan = new PackingPlan.ContainerPlan(containerId, container.getInstances(), resource); containerPlans.add(containerPlan); } return containerPlans; }
[ "private", "static", "Set", "<", "PackingPlan", ".", "ContainerPlan", ">", "buildContainerPlans", "(", "Map", "<", "Integer", ",", "Container", ">", "containerInstances", ")", "{", "Set", "<", "PackingPlan", ".", "ContainerPlan", ">", "containerPlans", "=", "new", "LinkedHashSet", "<>", "(", ")", ";", "for", "(", "Integer", "containerId", ":", "containerInstances", ".", "keySet", "(", ")", ")", "{", "Container", "container", "=", "containerInstances", ".", "get", "(", "containerId", ")", ";", "if", "(", "container", ".", "getInstances", "(", ")", ".", "size", "(", ")", "==", "0", ")", "{", "continue", ";", "}", "Resource", "totalUsedResources", "=", "container", ".", "getTotalUsedResources", "(", ")", ";", "Resource", "resource", "=", "new", "Resource", "(", "Math", ".", "round", "(", "totalUsedResources", ".", "getCpu", "(", ")", ")", ",", "totalUsedResources", ".", "getRam", "(", ")", ",", "totalUsedResources", ".", "getDisk", "(", ")", ")", ";", "PackingPlan", ".", "ContainerPlan", "containerPlan", "=", "new", "PackingPlan", ".", "ContainerPlan", "(", "containerId", ",", "container", ".", "getInstances", "(", ")", ",", "resource", ")", ";", "containerPlans", ".", "add", "(", "containerPlan", ")", ";", "}", "return", "containerPlans", ";", "}" ]
Estimate the per instance and topology resources for the packing plan based on the ramMap, instance defaults and paddingPercentage. @return container plans
[ "Estimate", "the", "per", "instance", "and", "topology", "resources", "for", "the", "packing", "plan", "based", "on", "the", "ramMap", "instance", "defaults", "and", "paddingPercentage", "." ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/packing/src/java/org/apache/heron/packing/builder/PackingPlanBuilder.java#L325-L347
27,877
apache/incubator-heron
heron/packing/src/java/org/apache/heron/packing/builder/PackingPlanBuilder.java
PackingPlanBuilder.getContainers
@VisibleForTesting static Map<Integer, Container> getContainers( PackingPlan currentPackingPlan, Resource maxContainerResource, Resource padding, Map<String, TreeSet<Integer>> componentIndexes, TreeSet<Integer> taskIds) { Map<Integer, Container> containers = new HashMap<>(); Resource capacity = maxContainerResource; for (PackingPlan.ContainerPlan currentContainerPlan : currentPackingPlan.getContainers()) { Container container = new Container(currentContainerPlan.getId(), capacity, padding); for (PackingPlan.InstancePlan instancePlan : currentContainerPlan.getInstances()) { addToContainer(container, instancePlan, componentIndexes, taskIds); } containers.put(currentContainerPlan.getId(), container); } return containers; }
java
@VisibleForTesting static Map<Integer, Container> getContainers( PackingPlan currentPackingPlan, Resource maxContainerResource, Resource padding, Map<String, TreeSet<Integer>> componentIndexes, TreeSet<Integer> taskIds) { Map<Integer, Container> containers = new HashMap<>(); Resource capacity = maxContainerResource; for (PackingPlan.ContainerPlan currentContainerPlan : currentPackingPlan.getContainers()) { Container container = new Container(currentContainerPlan.getId(), capacity, padding); for (PackingPlan.InstancePlan instancePlan : currentContainerPlan.getInstances()) { addToContainer(container, instancePlan, componentIndexes, taskIds); } containers.put(currentContainerPlan.getId(), container); } return containers; }
[ "@", "VisibleForTesting", "static", "Map", "<", "Integer", ",", "Container", ">", "getContainers", "(", "PackingPlan", "currentPackingPlan", ",", "Resource", "maxContainerResource", ",", "Resource", "padding", ",", "Map", "<", "String", ",", "TreeSet", "<", "Integer", ">", ">", "componentIndexes", ",", "TreeSet", "<", "Integer", ">", "taskIds", ")", "{", "Map", "<", "Integer", ",", "Container", ">", "containers", "=", "new", "HashMap", "<>", "(", ")", ";", "Resource", "capacity", "=", "maxContainerResource", ";", "for", "(", "PackingPlan", ".", "ContainerPlan", "currentContainerPlan", ":", "currentPackingPlan", ".", "getContainers", "(", ")", ")", "{", "Container", "container", "=", "new", "Container", "(", "currentContainerPlan", ".", "getId", "(", ")", ",", "capacity", ",", "padding", ")", ";", "for", "(", "PackingPlan", ".", "InstancePlan", "instancePlan", ":", "currentContainerPlan", ".", "getInstances", "(", ")", ")", "{", "addToContainer", "(", "container", ",", "instancePlan", ",", "componentIndexes", ",", "taskIds", ")", ";", "}", "containers", ".", "put", "(", "currentContainerPlan", ".", "getId", "(", ")", ",", "container", ")", ";", "}", "return", "containers", ";", "}" ]
Generates the containers that correspond to the current packing plan along with their associated instances. @return Map of containers for the current packing plan, keyed by containerId
[ "Generates", "the", "containers", "that", "correspond", "to", "the", "current", "packing", "plan", "along", "with", "their", "associated", "instances", "." ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/packing/src/java/org/apache/heron/packing/builder/PackingPlanBuilder.java#L355-L371
27,878
apache/incubator-heron
heron/packing/src/java/org/apache/heron/packing/builder/PackingPlanBuilder.java
PackingPlanBuilder.addToContainer
private static void addToContainer(Container container, PackingPlan.InstancePlan instancePlan, Map<String, TreeSet<Integer>> componentIndexes, Set<Integer> taskIds) { container.add(instancePlan); String componentName = instancePlan.getComponentName(); // update componentIndex and taskIds componentIndexes.computeIfAbsent(componentName, k -> new TreeSet<Integer>()); componentIndexes.get(componentName).add(instancePlan.getComponentIndex()); taskIds.add(instancePlan.getTaskId()); }
java
private static void addToContainer(Container container, PackingPlan.InstancePlan instancePlan, Map<String, TreeSet<Integer>> componentIndexes, Set<Integer> taskIds) { container.add(instancePlan); String componentName = instancePlan.getComponentName(); // update componentIndex and taskIds componentIndexes.computeIfAbsent(componentName, k -> new TreeSet<Integer>()); componentIndexes.get(componentName).add(instancePlan.getComponentIndex()); taskIds.add(instancePlan.getTaskId()); }
[ "private", "static", "void", "addToContainer", "(", "Container", "container", ",", "PackingPlan", ".", "InstancePlan", "instancePlan", ",", "Map", "<", "String", ",", "TreeSet", "<", "Integer", ">", ">", "componentIndexes", ",", "Set", "<", "Integer", ">", "taskIds", ")", "{", "container", ".", "add", "(", "instancePlan", ")", ";", "String", "componentName", "=", "instancePlan", ".", "getComponentName", "(", ")", ";", "// update componentIndex and taskIds", "componentIndexes", ".", "computeIfAbsent", "(", "componentName", ",", "k", "->", "new", "TreeSet", "<", "Integer", ">", "(", ")", ")", ";", "componentIndexes", ".", "get", "(", "componentName", ")", ".", "add", "(", "instancePlan", ".", "getComponentIndex", "(", ")", ")", ";", "taskIds", ".", "add", "(", "instancePlan", ".", "getTaskId", "(", ")", ")", ";", "}" ]
Add instancePlan to container and update the componentIndexes and taskIds indexes
[ "Add", "instancePlan", "to", "container", "and", "update", "the", "componentIndexes", "and", "taskIds", "indexes" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/packing/src/java/org/apache/heron/packing/builder/PackingPlanBuilder.java#L384-L395
27,879
apache/incubator-heron
examples/src/java/org/apache/heron/examples/streamlet/utils/StreamletUtils.java
StreamletUtils.randomFromList
public static <T> T randomFromList(List<T> ls) { return ls.get(new Random().nextInt(ls.size())); }
java
public static <T> T randomFromList(List<T> ls) { return ls.get(new Random().nextInt(ls.size())); }
[ "public", "static", "<", "T", ">", "T", "randomFromList", "(", "List", "<", "T", ">", "ls", ")", "{", "return", "ls", ".", "get", "(", "new", "Random", "(", ")", ".", "nextInt", "(", "ls", ".", "size", "(", ")", ")", ")", ";", "}" ]
Selects a random item from a list. Used in many example source streamlets.
[ "Selects", "a", "random", "item", "from", "a", "list", ".", "Used", "in", "many", "example", "source", "streamlets", "." ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/examples/src/java/org/apache/heron/examples/streamlet/utils/StreamletUtils.java#L57-L59
27,880
apache/incubator-heron
examples/src/java/org/apache/heron/examples/streamlet/utils/StreamletUtils.java
StreamletUtils.getParallelism
public static int getParallelism(String[] args, int defaultParallelism) { return (args.length > 1) ? Integer.parseInt(args[1]) : defaultParallelism; }
java
public static int getParallelism(String[] args, int defaultParallelism) { return (args.length > 1) ? Integer.parseInt(args[1]) : defaultParallelism; }
[ "public", "static", "int", "getParallelism", "(", "String", "[", "]", "args", ",", "int", "defaultParallelism", ")", "{", "return", "(", "args", ".", "length", ">", "1", ")", "?", "Integer", ".", "parseInt", "(", "args", "[", "1", "]", ")", ":", "defaultParallelism", ";", "}" ]
Fetches the topology's parallelism from the second-command-line argument or defers to a supplied default.
[ "Fetches", "the", "topology", "s", "parallelism", "from", "the", "second", "-", "command", "-", "line", "argument", "or", "defers", "to", "a", "supplied", "default", "." ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/examples/src/java/org/apache/heron/examples/streamlet/utils/StreamletUtils.java#L65-L67
27,881
apache/incubator-heron
examples/src/java/org/apache/heron/examples/streamlet/utils/StreamletUtils.java
StreamletUtils.intListAsString
public static String intListAsString(List<Integer> ls) { return String.join(", ", ls.stream().map(i -> i.toString()).collect(Collectors.toList())); }
java
public static String intListAsString(List<Integer> ls) { return String.join(", ", ls.stream().map(i -> i.toString()).collect(Collectors.toList())); }
[ "public", "static", "String", "intListAsString", "(", "List", "<", "Integer", ">", "ls", ")", "{", "return", "String", ".", "join", "(", "\", \"", ",", "ls", ".", "stream", "(", ")", ".", "map", "(", "i", "->", "i", ".", "toString", "(", ")", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ")", ";", "}" ]
Converts a list of integers into a comma-separated string.
[ "Converts", "a", "list", "of", "integers", "into", "a", "comma", "-", "separated", "string", "." ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/examples/src/java/org/apache/heron/examples/streamlet/utils/StreamletUtils.java#L72-L74
27,882
apache/incubator-heron
heron/common/src/java/org/apache/heron/common/network/HeronClient.java
HeronClient.sendRequest
public void sendRequest(Message request, Object context, Message.Builder responseBuilder, Duration timeout) { // Pack it as a no-timeout request and send it! final REQID rid = REQID.generate(); contextMap.put(rid, context); responseMessageMap.put(rid, responseBuilder); // Add timeout for this request if necessary if (timeout.getSeconds() > 0) { registerTimerEvent(timeout, new Runnable() { @Override public void run() { handleTimeout(rid); } }); } OutgoingPacket opk = new OutgoingPacket(rid, request); socketChannelHelper.sendPacket(opk); }
java
public void sendRequest(Message request, Object context, Message.Builder responseBuilder, Duration timeout) { // Pack it as a no-timeout request and send it! final REQID rid = REQID.generate(); contextMap.put(rid, context); responseMessageMap.put(rid, responseBuilder); // Add timeout for this request if necessary if (timeout.getSeconds() > 0) { registerTimerEvent(timeout, new Runnable() { @Override public void run() { handleTimeout(rid); } }); } OutgoingPacket opk = new OutgoingPacket(rid, request); socketChannelHelper.sendPacket(opk); }
[ "public", "void", "sendRequest", "(", "Message", "request", ",", "Object", "context", ",", "Message", ".", "Builder", "responseBuilder", ",", "Duration", "timeout", ")", "{", "// Pack it as a no-timeout request and send it!", "final", "REQID", "rid", "=", "REQID", ".", "generate", "(", ")", ";", "contextMap", ".", "put", "(", "rid", ",", "context", ")", ";", "responseMessageMap", ".", "put", "(", "rid", ",", "responseBuilder", ")", ";", "// Add timeout for this request if necessary", "if", "(", "timeout", ".", "getSeconds", "(", ")", ">", "0", ")", "{", "registerTimerEvent", "(", "timeout", ",", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "handleTimeout", "(", "rid", ")", ";", "}", "}", ")", ";", "}", "OutgoingPacket", "opk", "=", "new", "OutgoingPacket", "(", "rid", ",", "request", ")", ";", "socketChannelHelper", ".", "sendPacket", "(", "opk", ")", ";", "}" ]
A negative value of the timeout means no timeout.
[ "A", "negative", "value", "of", "the", "timeout", "means", "no", "timeout", "." ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/common/src/java/org/apache/heron/common/network/HeronClient.java#L192-L211
27,883
apache/incubator-heron
heron/common/src/java/org/apache/heron/common/network/HeronClient.java
HeronClient.sendRequest
public void sendRequest(Message request, Message.Builder responseBuilder) { sendRequest(request, null, responseBuilder, Duration.ZERO); }
java
public void sendRequest(Message request, Message.Builder responseBuilder) { sendRequest(request, null, responseBuilder, Duration.ZERO); }
[ "public", "void", "sendRequest", "(", "Message", "request", ",", "Message", ".", "Builder", "responseBuilder", ")", "{", "sendRequest", "(", "request", ",", "null", ",", "responseBuilder", ",", "Duration", ".", "ZERO", ")", ";", "}" ]
Convenience method of the above method with no timeout or context
[ "Convenience", "method", "of", "the", "above", "method", "with", "no", "timeout", "or", "context" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/common/src/java/org/apache/heron/common/network/HeronClient.java#L214-L216
27,884
apache/incubator-heron
heron/common/src/java/org/apache/heron/common/network/HeronClient.java
HeronClient.handleTimeout
protected void handleTimeout(REQID rid) { if (contextMap.containsKey(rid)) { Object ctx = contextMap.get(rid); contextMap.remove(rid); responseMessageMap.remove(rid); onResponse(StatusCode.TIMEOUT_ERROR, ctx, null); } else { // Since we dont do cancel timer, this is because we already have // the response. So just disregard this timeout // TODO:- implement cancel timer to avoid this overhead } }
java
protected void handleTimeout(REQID rid) { if (contextMap.containsKey(rid)) { Object ctx = contextMap.get(rid); contextMap.remove(rid); responseMessageMap.remove(rid); onResponse(StatusCode.TIMEOUT_ERROR, ctx, null); } else { // Since we dont do cancel timer, this is because we already have // the response. So just disregard this timeout // TODO:- implement cancel timer to avoid this overhead } }
[ "protected", "void", "handleTimeout", "(", "REQID", "rid", ")", "{", "if", "(", "contextMap", ".", "containsKey", "(", "rid", ")", ")", "{", "Object", "ctx", "=", "contextMap", ".", "get", "(", "rid", ")", ";", "contextMap", ".", "remove", "(", "rid", ")", ";", "responseMessageMap", ".", "remove", "(", "rid", ")", ";", "onResponse", "(", "StatusCode", ".", "TIMEOUT_ERROR", ",", "ctx", ",", "null", ")", ";", "}", "else", "{", "// Since we dont do cancel timer, this is because we already have", "// the response. So just disregard this timeout", "// TODO:- implement cancel timer to avoid this overhead", "}", "}" ]
Handle the timeout for a particular REQID
[ "Handle", "the", "timeout", "for", "a", "particular", "REQID" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/common/src/java/org/apache/heron/common/network/HeronClient.java#L320-L331
27,885
apache/incubator-heron
heron/schedulers/src/java/org/apache/heron/scheduler/mesos/MesosScheduler.java
MesosScheduler.startSchedulerDriver
protected void startSchedulerDriver() { // start the driver non-blocking, // since we need to set heron state after the scheduler driver is started. // Heron will block the main thread eventually driver.start(); // Staging the Mesos Framework LOG.info("Waiting for Mesos Framework get registered"); long timeout = MesosContext.getHeronMesosFrameworkStagingTimeoutMs(config); if (!mesosFramework.waitForRegistered(timeout, TimeUnit.MILLISECONDS)) { throw new RuntimeException("Failed to register with Mesos Master in time"); } }
java
protected void startSchedulerDriver() { // start the driver non-blocking, // since we need to set heron state after the scheduler driver is started. // Heron will block the main thread eventually driver.start(); // Staging the Mesos Framework LOG.info("Waiting for Mesos Framework get registered"); long timeout = MesosContext.getHeronMesosFrameworkStagingTimeoutMs(config); if (!mesosFramework.waitForRegistered(timeout, TimeUnit.MILLISECONDS)) { throw new RuntimeException("Failed to register with Mesos Master in time"); } }
[ "protected", "void", "startSchedulerDriver", "(", ")", "{", "// start the driver non-blocking,", "// since we need to set heron state after the scheduler driver is started.", "// Heron will block the main thread eventually", "driver", ".", "start", "(", ")", ";", "// Staging the Mesos Framework", "LOG", ".", "info", "(", "\"Waiting for Mesos Framework get registered\"", ")", ";", "long", "timeout", "=", "MesosContext", ".", "getHeronMesosFrameworkStagingTimeoutMs", "(", "config", ")", ";", "if", "(", "!", "mesosFramework", ".", "waitForRegistered", "(", "timeout", ",", "TimeUnit", ".", "MILLISECONDS", ")", ")", "{", "throw", "new", "RuntimeException", "(", "\"Failed to register with Mesos Master in time\"", ")", ";", "}", "}" ]
Start the scheduler driver and wait it to get registered
[ "Start", "the", "scheduler", "driver", "and", "wait", "it", "to", "get", "registered" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/schedulers/src/java/org/apache/heron/scheduler/mesos/MesosScheduler.java#L78-L90
27,886
apache/incubator-heron
heron/schedulers/src/java/org/apache/heron/scheduler/mesos/MesosScheduler.java
MesosScheduler.joinSchedulerDriver
protected void joinSchedulerDriver(long timeout, TimeUnit unit) { // ExecutorService used to monitor whether close() completes in time ExecutorService service = Executors.newFixedThreadPool(1); final CountDownLatch closeLatch = new CountDownLatch(1); Runnable driverJoin = new Runnable() { @Override public void run() { driver.join(); closeLatch.countDown(); } }; service.submit(driverJoin); LOG.info("Waiting for Mesos Driver got stopped"); try { if (!closeLatch.await(timeout, unit)) { LOG.severe("Mesos Driver failed to stop in time."); } else { LOG.info("Mesos Driver stopped."); } } catch (InterruptedException e) { LOG.log(Level.SEVERE, "Close latch thread is interrupted: ", e); } // Shutdown the ExecutorService service.shutdownNow(); }
java
protected void joinSchedulerDriver(long timeout, TimeUnit unit) { // ExecutorService used to monitor whether close() completes in time ExecutorService service = Executors.newFixedThreadPool(1); final CountDownLatch closeLatch = new CountDownLatch(1); Runnable driverJoin = new Runnable() { @Override public void run() { driver.join(); closeLatch.countDown(); } }; service.submit(driverJoin); LOG.info("Waiting for Mesos Driver got stopped"); try { if (!closeLatch.await(timeout, unit)) { LOG.severe("Mesos Driver failed to stop in time."); } else { LOG.info("Mesos Driver stopped."); } } catch (InterruptedException e) { LOG.log(Level.SEVERE, "Close latch thread is interrupted: ", e); } // Shutdown the ExecutorService service.shutdownNow(); }
[ "protected", "void", "joinSchedulerDriver", "(", "long", "timeout", ",", "TimeUnit", "unit", ")", "{", "// ExecutorService used to monitor whether close() completes in time", "ExecutorService", "service", "=", "Executors", ".", "newFixedThreadPool", "(", "1", ")", ";", "final", "CountDownLatch", "closeLatch", "=", "new", "CountDownLatch", "(", "1", ")", ";", "Runnable", "driverJoin", "=", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "driver", ".", "join", "(", ")", ";", "closeLatch", ".", "countDown", "(", ")", ";", "}", "}", ";", "service", ".", "submit", "(", "driverJoin", ")", ";", "LOG", ".", "info", "(", "\"Waiting for Mesos Driver got stopped\"", ")", ";", "try", "{", "if", "(", "!", "closeLatch", ".", "await", "(", "timeout", ",", "unit", ")", ")", "{", "LOG", ".", "severe", "(", "\"Mesos Driver failed to stop in time.\"", ")", ";", "}", "else", "{", "LOG", ".", "info", "(", "\"Mesos Driver stopped.\"", ")", ";", "}", "}", "catch", "(", "InterruptedException", "e", ")", "{", "LOG", ".", "log", "(", "Level", ".", "SEVERE", ",", "\"Close latch thread is interrupted: \"", ",", "e", ")", ";", "}", "// Shutdown the ExecutorService", "service", ".", "shutdownNow", "(", ")", ";", "}" ]
Waits for the driver to be stopped or aborted @param timeout maximum time waiting @param unit time unit to wait
[ "Waits", "for", "the", "driver", "to", "be", "stopped", "or", "aborted" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/schedulers/src/java/org/apache/heron/scheduler/mesos/MesosScheduler.java#L98-L124
27,887
apache/incubator-heron
heron/schedulers/src/java/org/apache/heron/scheduler/mesos/MesosScheduler.java
MesosScheduler.getBaseContainer
protected BaseContainer getBaseContainer(Integer containerIndex, PackingPlan packing) { BaseContainer container = new BaseContainer(); container.name = TaskUtils.getTaskNameForContainerIndex(containerIndex); container.runAsUser = Context.role(config); container.description = String.format("Container %d for topology %s", containerIndex, Context.topologyName(config)); // Fill in the resources requirement for this container fillResourcesRequirementForBaseContainer(container, containerIndex, packing); // Force running as shell container.shell = true; // Infinite retries container.retries = Integer.MAX_VALUE; // The dependencies for the container container.dependencies = new ArrayList<>(); String topologyPath = Runtime.schedulerProperties(runtime).getProperty(Key.TOPOLOGY_PACKAGE_URI.value()); String heronCoreReleasePath = Context.corePackageUri(config); container.dependencies.add(topologyPath); container.dependencies.add(heronCoreReleasePath); return container; }
java
protected BaseContainer getBaseContainer(Integer containerIndex, PackingPlan packing) { BaseContainer container = new BaseContainer(); container.name = TaskUtils.getTaskNameForContainerIndex(containerIndex); container.runAsUser = Context.role(config); container.description = String.format("Container %d for topology %s", containerIndex, Context.topologyName(config)); // Fill in the resources requirement for this container fillResourcesRequirementForBaseContainer(container, containerIndex, packing); // Force running as shell container.shell = true; // Infinite retries container.retries = Integer.MAX_VALUE; // The dependencies for the container container.dependencies = new ArrayList<>(); String topologyPath = Runtime.schedulerProperties(runtime).getProperty(Key.TOPOLOGY_PACKAGE_URI.value()); String heronCoreReleasePath = Context.corePackageUri(config); container.dependencies.add(topologyPath); container.dependencies.add(heronCoreReleasePath); return container; }
[ "protected", "BaseContainer", "getBaseContainer", "(", "Integer", "containerIndex", ",", "PackingPlan", "packing", ")", "{", "BaseContainer", "container", "=", "new", "BaseContainer", "(", ")", ";", "container", ".", "name", "=", "TaskUtils", ".", "getTaskNameForContainerIndex", "(", "containerIndex", ")", ";", "container", ".", "runAsUser", "=", "Context", ".", "role", "(", "config", ")", ";", "container", ".", "description", "=", "String", ".", "format", "(", "\"Container %d for topology %s\"", ",", "containerIndex", ",", "Context", ".", "topologyName", "(", "config", ")", ")", ";", "// Fill in the resources requirement for this container", "fillResourcesRequirementForBaseContainer", "(", "container", ",", "containerIndex", ",", "packing", ")", ";", "// Force running as shell", "container", ".", "shell", "=", "true", ";", "// Infinite retries", "container", ".", "retries", "=", "Integer", ".", "MAX_VALUE", ";", "// The dependencies for the container", "container", ".", "dependencies", "=", "new", "ArrayList", "<>", "(", ")", ";", "String", "topologyPath", "=", "Runtime", ".", "schedulerProperties", "(", "runtime", ")", ".", "getProperty", "(", "Key", ".", "TOPOLOGY_PACKAGE_URI", ".", "value", "(", ")", ")", ";", "String", "heronCoreReleasePath", "=", "Context", ".", "corePackageUri", "(", "config", ")", ";", "container", ".", "dependencies", ".", "add", "(", "topologyPath", ")", ";", "container", ".", "dependencies", ".", "add", "(", "heronCoreReleasePath", ")", ";", "return", "container", ";", "}" ]
Get BaseContainer info. @param containerIndex container index to start @param packing the PackingPlan @return BaseContainer Info
[ "Get", "BaseContainer", "info", "." ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/schedulers/src/java/org/apache/heron/scheduler/mesos/MesosScheduler.java#L217-L244
27,888
apache/incubator-heron
heron/schedulers/src/java/org/apache/heron/scheduler/mesos/framework/LaunchableTask.java
LaunchableTask.constructMesosTaskInfo
public Protos.TaskInfo constructMesosTaskInfo(Config heronConfig, Config heronRuntime) { //String taskIdStr, BaseContainer task, Offer offer String taskIdStr = this.taskId; Protos.TaskID mesosTaskID = Protos.TaskID.newBuilder().setValue(taskIdStr).build(); Protos.TaskInfo.Builder taskInfo = Protos.TaskInfo.newBuilder() .setName(baseContainer.name) .setTaskId(mesosTaskID); Protos.Environment.Builder environment = Protos.Environment.newBuilder(); // If the job defines custom environment variables, add them to the builder // Don't add them if they already exist to prevent overwriting the defaults Set<String> builtinEnvNames = new HashSet<>(); for (Protos.Environment.Variable variable : environment.getVariablesList()) { builtinEnvNames.add(variable.getName()); } for (BaseContainer.EnvironmentVariable ev : baseContainer.environmentVariables) { environment.addVariables( Protos.Environment.Variable.newBuilder().setName(ev.name).setValue(ev.value)); } taskInfo .addResources(scalarResource(TaskResources.CPUS_RESOURCE_NAME, baseContainer.cpu)) .addResources(scalarResource(TaskResources.MEM_RESOURCE_NAME, baseContainer.memInMB)) .addResources(scalarResource(TaskResources.DISK_RESOURCE_NAME, baseContainer.diskInMB)) .addResources(rangeResource(TaskResources.PORT_RESOURCE_NAME, this.freePorts.get(0), this.freePorts.get(this.freePorts.size() - 1))). setSlaveId(this.offer.getSlaveId()); int containerIndex = TaskUtils.getContainerIndexForTaskId(taskIdStr); String commandStr = executorCommand(heronConfig, heronRuntime, containerIndex); Protos.CommandInfo.Builder command = Protos.CommandInfo.newBuilder(); List<Protos.CommandInfo.URI> uriProtos = new ArrayList<>(); for (String uri : baseContainer.dependencies) { uriProtos.add(Protos.CommandInfo.URI.newBuilder() .setValue(uri) .setExtract(true) .build()); } command.setValue(commandStr) .setShell(baseContainer.shell) .setEnvironment(environment) .addAllUris(uriProtos); if (!baseContainer.runAsUser.isEmpty()) { command.setUser(baseContainer.runAsUser); } taskInfo.setCommand(command); return taskInfo.build(); }
java
public Protos.TaskInfo constructMesosTaskInfo(Config heronConfig, Config heronRuntime) { //String taskIdStr, BaseContainer task, Offer offer String taskIdStr = this.taskId; Protos.TaskID mesosTaskID = Protos.TaskID.newBuilder().setValue(taskIdStr).build(); Protos.TaskInfo.Builder taskInfo = Protos.TaskInfo.newBuilder() .setName(baseContainer.name) .setTaskId(mesosTaskID); Protos.Environment.Builder environment = Protos.Environment.newBuilder(); // If the job defines custom environment variables, add them to the builder // Don't add them if they already exist to prevent overwriting the defaults Set<String> builtinEnvNames = new HashSet<>(); for (Protos.Environment.Variable variable : environment.getVariablesList()) { builtinEnvNames.add(variable.getName()); } for (BaseContainer.EnvironmentVariable ev : baseContainer.environmentVariables) { environment.addVariables( Protos.Environment.Variable.newBuilder().setName(ev.name).setValue(ev.value)); } taskInfo .addResources(scalarResource(TaskResources.CPUS_RESOURCE_NAME, baseContainer.cpu)) .addResources(scalarResource(TaskResources.MEM_RESOURCE_NAME, baseContainer.memInMB)) .addResources(scalarResource(TaskResources.DISK_RESOURCE_NAME, baseContainer.diskInMB)) .addResources(rangeResource(TaskResources.PORT_RESOURCE_NAME, this.freePorts.get(0), this.freePorts.get(this.freePorts.size() - 1))). setSlaveId(this.offer.getSlaveId()); int containerIndex = TaskUtils.getContainerIndexForTaskId(taskIdStr); String commandStr = executorCommand(heronConfig, heronRuntime, containerIndex); Protos.CommandInfo.Builder command = Protos.CommandInfo.newBuilder(); List<Protos.CommandInfo.URI> uriProtos = new ArrayList<>(); for (String uri : baseContainer.dependencies) { uriProtos.add(Protos.CommandInfo.URI.newBuilder() .setValue(uri) .setExtract(true) .build()); } command.setValue(commandStr) .setShell(baseContainer.shell) .setEnvironment(environment) .addAllUris(uriProtos); if (!baseContainer.runAsUser.isEmpty()) { command.setUser(baseContainer.runAsUser); } taskInfo.setCommand(command); return taskInfo.build(); }
[ "public", "Protos", ".", "TaskInfo", "constructMesosTaskInfo", "(", "Config", "heronConfig", ",", "Config", "heronRuntime", ")", "{", "//String taskIdStr, BaseContainer task, Offer offer", "String", "taskIdStr", "=", "this", ".", "taskId", ";", "Protos", ".", "TaskID", "mesosTaskID", "=", "Protos", ".", "TaskID", ".", "newBuilder", "(", ")", ".", "setValue", "(", "taskIdStr", ")", ".", "build", "(", ")", ";", "Protos", ".", "TaskInfo", ".", "Builder", "taskInfo", "=", "Protos", ".", "TaskInfo", ".", "newBuilder", "(", ")", ".", "setName", "(", "baseContainer", ".", "name", ")", ".", "setTaskId", "(", "mesosTaskID", ")", ";", "Protos", ".", "Environment", ".", "Builder", "environment", "=", "Protos", ".", "Environment", ".", "newBuilder", "(", ")", ";", "// If the job defines custom environment variables, add them to the builder", "// Don't add them if they already exist to prevent overwriting the defaults", "Set", "<", "String", ">", "builtinEnvNames", "=", "new", "HashSet", "<>", "(", ")", ";", "for", "(", "Protos", ".", "Environment", ".", "Variable", "variable", ":", "environment", ".", "getVariablesList", "(", ")", ")", "{", "builtinEnvNames", ".", "add", "(", "variable", ".", "getName", "(", ")", ")", ";", "}", "for", "(", "BaseContainer", ".", "EnvironmentVariable", "ev", ":", "baseContainer", ".", "environmentVariables", ")", "{", "environment", ".", "addVariables", "(", "Protos", ".", "Environment", ".", "Variable", ".", "newBuilder", "(", ")", ".", "setName", "(", "ev", ".", "name", ")", ".", "setValue", "(", "ev", ".", "value", ")", ")", ";", "}", "taskInfo", ".", "addResources", "(", "scalarResource", "(", "TaskResources", ".", "CPUS_RESOURCE_NAME", ",", "baseContainer", ".", "cpu", ")", ")", ".", "addResources", "(", "scalarResource", "(", "TaskResources", ".", "MEM_RESOURCE_NAME", ",", "baseContainer", ".", "memInMB", ")", ")", ".", "addResources", "(", "scalarResource", "(", "TaskResources", ".", "DISK_RESOURCE_NAME", ",", "baseContainer", ".", "diskInMB", ")", ")", ".", "addResources", "(", "rangeResource", "(", "TaskResources", ".", "PORT_RESOURCE_NAME", ",", "this", ".", "freePorts", ".", "get", "(", "0", ")", ",", "this", ".", "freePorts", ".", "get", "(", "this", ".", "freePorts", ".", "size", "(", ")", "-", "1", ")", ")", ")", ".", "setSlaveId", "(", "this", ".", "offer", ".", "getSlaveId", "(", ")", ")", ";", "int", "containerIndex", "=", "TaskUtils", ".", "getContainerIndexForTaskId", "(", "taskIdStr", ")", ";", "String", "commandStr", "=", "executorCommand", "(", "heronConfig", ",", "heronRuntime", ",", "containerIndex", ")", ";", "Protos", ".", "CommandInfo", ".", "Builder", "command", "=", "Protos", ".", "CommandInfo", ".", "newBuilder", "(", ")", ";", "List", "<", "Protos", ".", "CommandInfo", ".", "URI", ">", "uriProtos", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "String", "uri", ":", "baseContainer", ".", "dependencies", ")", "{", "uriProtos", ".", "add", "(", "Protos", ".", "CommandInfo", ".", "URI", ".", "newBuilder", "(", ")", ".", "setValue", "(", "uri", ")", ".", "setExtract", "(", "true", ")", ".", "build", "(", ")", ")", ";", "}", "command", ".", "setValue", "(", "commandStr", ")", ".", "setShell", "(", "baseContainer", ".", "shell", ")", ".", "setEnvironment", "(", "environment", ")", ".", "addAllUris", "(", "uriProtos", ")", ";", "if", "(", "!", "baseContainer", ".", "runAsUser", ".", "isEmpty", "(", ")", ")", "{", "command", ".", "setUser", "(", "baseContainer", ".", "runAsUser", ")", ";", "}", "taskInfo", ".", "setCommand", "(", "command", ")", ";", "return", "taskInfo", ".", "build", "(", ")", ";", "}" ]
Construct the Mesos TaskInfo in Protos to launch basing on the LaunchableTask @param heronConfig the heron config @param heronRuntime the heron runtime @return Mesos TaskInfo in Protos to launch
[ "Construct", "the", "Mesos", "TaskInfo", "in", "Protos", "to", "launch", "basing", "on", "the", "LaunchableTask" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/schedulers/src/java/org/apache/heron/scheduler/mesos/framework/LaunchableTask.java#L143-L197
27,889
apache/incubator-heron
heron/common/src/java/org/apache/heron/common/utils/metrics/MetricsCollector.java
MetricsCollector.gatherOneMetric
@SuppressWarnings("unchecked") private void gatherOneMetric( String metricName, Metrics.MetricPublisherPublishMessage.Builder builder) { Object metricValue = metrics.get(metricName).getValueAndReset(); // Decide how to handle the metric based on type if (metricValue == null) { return; } if (metricValue instanceof Map) { for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) metricValue).entrySet()) { if (entry.getKey() != null && entry.getValue() != null) { addDataToMetricPublisher( builder, metricName + "/" + entry.getKey().toString(), entry.getValue()); } } } else if (metricValue instanceof Collection) { int index = 0; for (Object value : (Collection) metricValue) { addDataToMetricPublisher(builder, metricName + "/" + (index++), value); } } else { addDataToMetricPublisher(builder, metricName, metricValue); } }
java
@SuppressWarnings("unchecked") private void gatherOneMetric( String metricName, Metrics.MetricPublisherPublishMessage.Builder builder) { Object metricValue = metrics.get(metricName).getValueAndReset(); // Decide how to handle the metric based on type if (metricValue == null) { return; } if (metricValue instanceof Map) { for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) metricValue).entrySet()) { if (entry.getKey() != null && entry.getValue() != null) { addDataToMetricPublisher( builder, metricName + "/" + entry.getKey().toString(), entry.getValue()); } } } else if (metricValue instanceof Collection) { int index = 0; for (Object value : (Collection) metricValue) { addDataToMetricPublisher(builder, metricName + "/" + (index++), value); } } else { addDataToMetricPublisher(builder, metricName, metricValue); } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "private", "void", "gatherOneMetric", "(", "String", "metricName", ",", "Metrics", ".", "MetricPublisherPublishMessage", ".", "Builder", "builder", ")", "{", "Object", "metricValue", "=", "metrics", ".", "get", "(", "metricName", ")", ".", "getValueAndReset", "(", ")", ";", "// Decide how to handle the metric based on type", "if", "(", "metricValue", "==", "null", ")", "{", "return", ";", "}", "if", "(", "metricValue", "instanceof", "Map", ")", "{", "for", "(", "Map", ".", "Entry", "<", "Object", ",", "Object", ">", "entry", ":", "(", "(", "Map", "<", "Object", ",", "Object", ">", ")", "metricValue", ")", ".", "entrySet", "(", ")", ")", "{", "if", "(", "entry", ".", "getKey", "(", ")", "!=", "null", "&&", "entry", ".", "getValue", "(", ")", "!=", "null", ")", "{", "addDataToMetricPublisher", "(", "builder", ",", "metricName", "+", "\"/\"", "+", "entry", ".", "getKey", "(", ")", ".", "toString", "(", ")", ",", "entry", ".", "getValue", "(", ")", ")", ";", "}", "}", "}", "else", "if", "(", "metricValue", "instanceof", "Collection", ")", "{", "int", "index", "=", "0", ";", "for", "(", "Object", "value", ":", "(", "Collection", ")", "metricValue", ")", "{", "addDataToMetricPublisher", "(", "builder", ",", "metricName", "+", "\"/\"", "+", "(", "index", "++", ")", ",", "value", ")", ";", "}", "}", "else", "{", "addDataToMetricPublisher", "(", "builder", ",", "metricName", ",", "metricValue", ")", ";", "}", "}" ]
and add it to MetricPublisherPublishMessage builder given.
[ "and", "add", "it", "to", "MetricPublisherPublishMessage", "builder", "given", "." ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/common/src/java/org/apache/heron/common/utils/metrics/MetricsCollector.java#L176-L200
27,890
apache/incubator-heron
heron/metricscachemgr/src/java/org/apache/heron/metricscachemgr/metricscache/MetricsCacheQueryUtils.java
MetricsCacheQueryUtils.fromProtobuf
public static MetricRequest fromProtobuf(TopologyMaster.MetricRequest request) { String componentName = request.getComponentName(); Map<String, Set<String>> componentNameInstanceId = new HashMap<>(); if (request.getInstanceIdCount() == 0) { // empty list means all instances // 'null' means all instances componentNameInstanceId.put(componentName, null); } else { Set<String> instances = new HashSet<>(); // only one component componentNameInstanceId.put(componentName, instances); // if there are instances specified instances.addAll(request.getInstanceIdList()); } Set<String> metricNames = new HashSet<>(); if (request.getMetricCount() > 0) { metricNames.addAll(request.getMetricList()); } // empty list means no metrics // default: the whole time horizon long startTime = 0; long endTime = Long.MAX_VALUE; if (request.hasInterval()) { // endTime = now endTime = System.currentTimeMillis(); long interval = request.getInterval(); // in seconds if (interval <= 0) { // means all startTime = 0; } else { // means [-interval, now] startTime = endTime - interval * 1000; } } else { startTime = request.getExplicitInterval().getStart() * 1000; endTime = request.getExplicitInterval().getEnd() * 1000; } // default: aggregate all metrics MetricGranularity aggregationGranularity = AGGREGATE_ALL_METRICS; if (request.hasMinutely() && request.getMinutely()) { aggregationGranularity = AGGREGATE_BY_BUCKET; } return new MetricRequest(componentNameInstanceId, metricNames, startTime, endTime, aggregationGranularity); }
java
public static MetricRequest fromProtobuf(TopologyMaster.MetricRequest request) { String componentName = request.getComponentName(); Map<String, Set<String>> componentNameInstanceId = new HashMap<>(); if (request.getInstanceIdCount() == 0) { // empty list means all instances // 'null' means all instances componentNameInstanceId.put(componentName, null); } else { Set<String> instances = new HashSet<>(); // only one component componentNameInstanceId.put(componentName, instances); // if there are instances specified instances.addAll(request.getInstanceIdList()); } Set<String> metricNames = new HashSet<>(); if (request.getMetricCount() > 0) { metricNames.addAll(request.getMetricList()); } // empty list means no metrics // default: the whole time horizon long startTime = 0; long endTime = Long.MAX_VALUE; if (request.hasInterval()) { // endTime = now endTime = System.currentTimeMillis(); long interval = request.getInterval(); // in seconds if (interval <= 0) { // means all startTime = 0; } else { // means [-interval, now] startTime = endTime - interval * 1000; } } else { startTime = request.getExplicitInterval().getStart() * 1000; endTime = request.getExplicitInterval().getEnd() * 1000; } // default: aggregate all metrics MetricGranularity aggregationGranularity = AGGREGATE_ALL_METRICS; if (request.hasMinutely() && request.getMinutely()) { aggregationGranularity = AGGREGATE_BY_BUCKET; } return new MetricRequest(componentNameInstanceId, metricNames, startTime, endTime, aggregationGranularity); }
[ "public", "static", "MetricRequest", "fromProtobuf", "(", "TopologyMaster", ".", "MetricRequest", "request", ")", "{", "String", "componentName", "=", "request", ".", "getComponentName", "(", ")", ";", "Map", "<", "String", ",", "Set", "<", "String", ">", ">", "componentNameInstanceId", "=", "new", "HashMap", "<>", "(", ")", ";", "if", "(", "request", ".", "getInstanceIdCount", "(", ")", "==", "0", ")", "{", "// empty list means all instances", "// 'null' means all instances", "componentNameInstanceId", ".", "put", "(", "componentName", ",", "null", ")", ";", "}", "else", "{", "Set", "<", "String", ">", "instances", "=", "new", "HashSet", "<>", "(", ")", ";", "// only one component", "componentNameInstanceId", ".", "put", "(", "componentName", ",", "instances", ")", ";", "// if there are instances specified", "instances", ".", "addAll", "(", "request", ".", "getInstanceIdList", "(", ")", ")", ";", "}", "Set", "<", "String", ">", "metricNames", "=", "new", "HashSet", "<>", "(", ")", ";", "if", "(", "request", ".", "getMetricCount", "(", ")", ">", "0", ")", "{", "metricNames", ".", "addAll", "(", "request", ".", "getMetricList", "(", ")", ")", ";", "}", "// empty list means no metrics", "// default: the whole time horizon", "long", "startTime", "=", "0", ";", "long", "endTime", "=", "Long", ".", "MAX_VALUE", ";", "if", "(", "request", ".", "hasInterval", "(", ")", ")", "{", "// endTime = now", "endTime", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "long", "interval", "=", "request", ".", "getInterval", "(", ")", ";", "// in seconds", "if", "(", "interval", "<=", "0", ")", "{", "// means all", "startTime", "=", "0", ";", "}", "else", "{", "// means [-interval, now]", "startTime", "=", "endTime", "-", "interval", "*", "1000", ";", "}", "}", "else", "{", "startTime", "=", "request", ".", "getExplicitInterval", "(", ")", ".", "getStart", "(", ")", "*", "1000", ";", "endTime", "=", "request", ".", "getExplicitInterval", "(", ")", ".", "getEnd", "(", ")", "*", "1000", ";", "}", "// default: aggregate all metrics", "MetricGranularity", "aggregationGranularity", "=", "AGGREGATE_ALL_METRICS", ";", "if", "(", "request", ".", "hasMinutely", "(", ")", "&&", "request", ".", "getMinutely", "(", ")", ")", "{", "aggregationGranularity", "=", "AGGREGATE_BY_BUCKET", ";", "}", "return", "new", "MetricRequest", "(", "componentNameInstanceId", ",", "metricNames", ",", "startTime", ",", "endTime", ",", "aggregationGranularity", ")", ";", "}" ]
compatible with org.apache.heron.proto.tmaster.TopologyMaster.MetricRequest @param request protobuf defined message @return metricscache defined data structure
[ "compatible", "with", "org", ".", "apache", ".", "heron", ".", "proto", ".", "tmaster", ".", "TopologyMaster", ".", "MetricRequest" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/metricscachemgr/src/java/org/apache/heron/metricscachemgr/metricscache/MetricsCacheQueryUtils.java#L55-L101
27,891
apache/incubator-heron
heron/metricscachemgr/src/java/org/apache/heron/metricscachemgr/metricscache/MetricsCacheQueryUtils.java
MetricsCacheQueryUtils.toProtobuf
public static TopologyMaster.MetricResponse toProtobuf(MetricResponse response, MetricRequest request) { TopologyMaster.MetricResponse.Builder builder = TopologyMaster.MetricResponse.newBuilder(); builder.setInterval((request.getEndTime() - request.getStartTime()) / 1000); // in seconds // default OK if we have response to build already builder.setStatus(Common.Status.newBuilder().setStatus(Common.StatusCode.OK)); // instanceId -> [metricName -> metricValue] // componentName is ignored, since there is only one component in the query Map<String, Map<String, List<MetricTimeRangeValue>>> aggregation = new HashMap<>(); for (MetricDatum datum : response.getMetricList()) { String instanceId = datum.getInstanceId(); String metricName = datum.getMetricName(); List<MetricTimeRangeValue> metricValue = datum.getMetricValue(); // prepare if (!aggregation.containsKey(instanceId)) { aggregation.put(instanceId, new HashMap<String, List<MetricTimeRangeValue>>()); } if (!aggregation.get(instanceId).containsKey(metricName)) { aggregation.get(instanceId).put(metricName, new ArrayList<MetricTimeRangeValue>()); } // aggregate aggregation.get(instanceId).get(metricName).addAll(metricValue); } // add TaskMetric for (String instanceId : aggregation.keySet()) { TopologyMaster.MetricResponse.TaskMetric.Builder taskMetricBuilder = TopologyMaster.MetricResponse.TaskMetric.newBuilder(); taskMetricBuilder.setInstanceId(instanceId); // add IndividualMetric for (String metricName : aggregation.get(instanceId).keySet()) { TopologyMaster.MetricResponse.IndividualMetric.Builder individualMetricBuilder = TopologyMaster.MetricResponse.IndividualMetric.newBuilder(); individualMetricBuilder.setName(metricName); // add value|IntervalValue List<MetricTimeRangeValue> list = aggregation.get(instanceId).get(metricName); if (list.size() == 1) { individualMetricBuilder.setValue(list.get(0).getValue()); } else { for (MetricTimeRangeValue v : list) { TopologyMaster.MetricResponse.IndividualMetric.IntervalValue.Builder intervalValueBuilder = TopologyMaster.MetricResponse.IndividualMetric.IntervalValue.newBuilder(); intervalValueBuilder.setValue(v.getValue()); intervalValueBuilder.setInterval(TopologyMaster.MetricInterval.newBuilder() .setStart(v.getStartTime()).setEnd(v.getEndTime())); individualMetricBuilder.addIntervalValues(intervalValueBuilder); }// end IntervalValue } taskMetricBuilder.addMetric(individualMetricBuilder); }// end IndividualMetric builder.addMetric(taskMetricBuilder); }// end TaskMetric return builder.build(); }
java
public static TopologyMaster.MetricResponse toProtobuf(MetricResponse response, MetricRequest request) { TopologyMaster.MetricResponse.Builder builder = TopologyMaster.MetricResponse.newBuilder(); builder.setInterval((request.getEndTime() - request.getStartTime()) / 1000); // in seconds // default OK if we have response to build already builder.setStatus(Common.Status.newBuilder().setStatus(Common.StatusCode.OK)); // instanceId -> [metricName -> metricValue] // componentName is ignored, since there is only one component in the query Map<String, Map<String, List<MetricTimeRangeValue>>> aggregation = new HashMap<>(); for (MetricDatum datum : response.getMetricList()) { String instanceId = datum.getInstanceId(); String metricName = datum.getMetricName(); List<MetricTimeRangeValue> metricValue = datum.getMetricValue(); // prepare if (!aggregation.containsKey(instanceId)) { aggregation.put(instanceId, new HashMap<String, List<MetricTimeRangeValue>>()); } if (!aggregation.get(instanceId).containsKey(metricName)) { aggregation.get(instanceId).put(metricName, new ArrayList<MetricTimeRangeValue>()); } // aggregate aggregation.get(instanceId).get(metricName).addAll(metricValue); } // add TaskMetric for (String instanceId : aggregation.keySet()) { TopologyMaster.MetricResponse.TaskMetric.Builder taskMetricBuilder = TopologyMaster.MetricResponse.TaskMetric.newBuilder(); taskMetricBuilder.setInstanceId(instanceId); // add IndividualMetric for (String metricName : aggregation.get(instanceId).keySet()) { TopologyMaster.MetricResponse.IndividualMetric.Builder individualMetricBuilder = TopologyMaster.MetricResponse.IndividualMetric.newBuilder(); individualMetricBuilder.setName(metricName); // add value|IntervalValue List<MetricTimeRangeValue> list = aggregation.get(instanceId).get(metricName); if (list.size() == 1) { individualMetricBuilder.setValue(list.get(0).getValue()); } else { for (MetricTimeRangeValue v : list) { TopologyMaster.MetricResponse.IndividualMetric.IntervalValue.Builder intervalValueBuilder = TopologyMaster.MetricResponse.IndividualMetric.IntervalValue.newBuilder(); intervalValueBuilder.setValue(v.getValue()); intervalValueBuilder.setInterval(TopologyMaster.MetricInterval.newBuilder() .setStart(v.getStartTime()).setEnd(v.getEndTime())); individualMetricBuilder.addIntervalValues(intervalValueBuilder); }// end IntervalValue } taskMetricBuilder.addMetric(individualMetricBuilder); }// end IndividualMetric builder.addMetric(taskMetricBuilder); }// end TaskMetric return builder.build(); }
[ "public", "static", "TopologyMaster", ".", "MetricResponse", "toProtobuf", "(", "MetricResponse", "response", ",", "MetricRequest", "request", ")", "{", "TopologyMaster", ".", "MetricResponse", ".", "Builder", "builder", "=", "TopologyMaster", ".", "MetricResponse", ".", "newBuilder", "(", ")", ";", "builder", ".", "setInterval", "(", "(", "request", ".", "getEndTime", "(", ")", "-", "request", ".", "getStartTime", "(", ")", ")", "/", "1000", ")", ";", "// in seconds", "// default OK if we have response to build already", "builder", ".", "setStatus", "(", "Common", ".", "Status", ".", "newBuilder", "(", ")", ".", "setStatus", "(", "Common", ".", "StatusCode", ".", "OK", ")", ")", ";", "// instanceId -> [metricName -> metricValue]", "// componentName is ignored, since there is only one component in the query", "Map", "<", "String", ",", "Map", "<", "String", ",", "List", "<", "MetricTimeRangeValue", ">", ">", ">", "aggregation", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "MetricDatum", "datum", ":", "response", ".", "getMetricList", "(", ")", ")", "{", "String", "instanceId", "=", "datum", ".", "getInstanceId", "(", ")", ";", "String", "metricName", "=", "datum", ".", "getMetricName", "(", ")", ";", "List", "<", "MetricTimeRangeValue", ">", "metricValue", "=", "datum", ".", "getMetricValue", "(", ")", ";", "// prepare", "if", "(", "!", "aggregation", ".", "containsKey", "(", "instanceId", ")", ")", "{", "aggregation", ".", "put", "(", "instanceId", ",", "new", "HashMap", "<", "String", ",", "List", "<", "MetricTimeRangeValue", ">", ">", "(", ")", ")", ";", "}", "if", "(", "!", "aggregation", ".", "get", "(", "instanceId", ")", ".", "containsKey", "(", "metricName", ")", ")", "{", "aggregation", ".", "get", "(", "instanceId", ")", ".", "put", "(", "metricName", ",", "new", "ArrayList", "<", "MetricTimeRangeValue", ">", "(", ")", ")", ";", "}", "// aggregate", "aggregation", ".", "get", "(", "instanceId", ")", ".", "get", "(", "metricName", ")", ".", "addAll", "(", "metricValue", ")", ";", "}", "// add TaskMetric", "for", "(", "String", "instanceId", ":", "aggregation", ".", "keySet", "(", ")", ")", "{", "TopologyMaster", ".", "MetricResponse", ".", "TaskMetric", ".", "Builder", "taskMetricBuilder", "=", "TopologyMaster", ".", "MetricResponse", ".", "TaskMetric", ".", "newBuilder", "(", ")", ";", "taskMetricBuilder", ".", "setInstanceId", "(", "instanceId", ")", ";", "// add IndividualMetric", "for", "(", "String", "metricName", ":", "aggregation", ".", "get", "(", "instanceId", ")", ".", "keySet", "(", ")", ")", "{", "TopologyMaster", ".", "MetricResponse", ".", "IndividualMetric", ".", "Builder", "individualMetricBuilder", "=", "TopologyMaster", ".", "MetricResponse", ".", "IndividualMetric", ".", "newBuilder", "(", ")", ";", "individualMetricBuilder", ".", "setName", "(", "metricName", ")", ";", "// add value|IntervalValue", "List", "<", "MetricTimeRangeValue", ">", "list", "=", "aggregation", ".", "get", "(", "instanceId", ")", ".", "get", "(", "metricName", ")", ";", "if", "(", "list", ".", "size", "(", ")", "==", "1", ")", "{", "individualMetricBuilder", ".", "setValue", "(", "list", ".", "get", "(", "0", ")", ".", "getValue", "(", ")", ")", ";", "}", "else", "{", "for", "(", "MetricTimeRangeValue", "v", ":", "list", ")", "{", "TopologyMaster", ".", "MetricResponse", ".", "IndividualMetric", ".", "IntervalValue", ".", "Builder", "intervalValueBuilder", "=", "TopologyMaster", ".", "MetricResponse", ".", "IndividualMetric", ".", "IntervalValue", ".", "newBuilder", "(", ")", ";", "intervalValueBuilder", ".", "setValue", "(", "v", ".", "getValue", "(", ")", ")", ";", "intervalValueBuilder", ".", "setInterval", "(", "TopologyMaster", ".", "MetricInterval", ".", "newBuilder", "(", ")", ".", "setStart", "(", "v", ".", "getStartTime", "(", ")", ")", ".", "setEnd", "(", "v", ".", "getEndTime", "(", ")", ")", ")", ";", "individualMetricBuilder", ".", "addIntervalValues", "(", "intervalValueBuilder", ")", ";", "}", "// end IntervalValue", "}", "taskMetricBuilder", ".", "addMetric", "(", "individualMetricBuilder", ")", ";", "}", "// end IndividualMetric", "builder", ".", "addMetric", "(", "taskMetricBuilder", ")", ";", "}", "// end TaskMetric", "return", "builder", ".", "build", "(", ")", ";", "}" ]
compatible with org.apache.heron.proto.tmaster.TopologyMaster.MetricResponse @param response metricscache defined data structure @param request metricscache defined data structure @return protobuf defined message
[ "compatible", "with", "org", ".", "apache", ".", "heron", ".", "proto", ".", "tmaster", ".", "TopologyMaster", ".", "MetricResponse" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/metricscachemgr/src/java/org/apache/heron/metricscachemgr/metricscache/MetricsCacheQueryUtils.java#L109-L174
27,892
apache/incubator-heron
heron/metricscachemgr/src/java/org/apache/heron/metricscachemgr/metricscache/MetricsCacheQueryUtils.java
MetricsCacheQueryUtils.fromProtobuf
public static ExceptionRequest fromProtobuf(TopologyMaster.ExceptionLogRequest request) { String componentName = request.getComponentName(); Map<String, Set<String>> componentNameInstanceId = new HashMap<>(); Set<String> instances = null; if (request.getInstancesCount() > 0) { instances = new HashSet<>(); instances.addAll(request.getInstancesList()); } // empty list means all instances; 'null' means all instances // only one component componentNameInstanceId.put(componentName, instances); return new ExceptionRequest(componentNameInstanceId); }
java
public static ExceptionRequest fromProtobuf(TopologyMaster.ExceptionLogRequest request) { String componentName = request.getComponentName(); Map<String, Set<String>> componentNameInstanceId = new HashMap<>(); Set<String> instances = null; if (request.getInstancesCount() > 0) { instances = new HashSet<>(); instances.addAll(request.getInstancesList()); } // empty list means all instances; 'null' means all instances // only one component componentNameInstanceId.put(componentName, instances); return new ExceptionRequest(componentNameInstanceId); }
[ "public", "static", "ExceptionRequest", "fromProtobuf", "(", "TopologyMaster", ".", "ExceptionLogRequest", "request", ")", "{", "String", "componentName", "=", "request", ".", "getComponentName", "(", ")", ";", "Map", "<", "String", ",", "Set", "<", "String", ">", ">", "componentNameInstanceId", "=", "new", "HashMap", "<>", "(", ")", ";", "Set", "<", "String", ">", "instances", "=", "null", ";", "if", "(", "request", ".", "getInstancesCount", "(", ")", ">", "0", ")", "{", "instances", "=", "new", "HashSet", "<>", "(", ")", ";", "instances", ".", "addAll", "(", "request", ".", "getInstancesList", "(", ")", ")", ";", "}", "// empty list means all instances; 'null' means all instances", "// only one component", "componentNameInstanceId", ".", "put", "(", "componentName", ",", "instances", ")", ";", "return", "new", "ExceptionRequest", "(", "componentNameInstanceId", ")", ";", "}" ]
compatible with org.apache.heron.proto.tmaster.TopologyMaster.ExceptionLogRequest
[ "compatible", "with", "org", ".", "apache", ".", "heron", ".", "proto", ".", "tmaster", ".", "TopologyMaster", ".", "ExceptionLogRequest" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/metricscachemgr/src/java/org/apache/heron/metricscachemgr/metricscache/MetricsCacheQueryUtils.java#L177-L192
27,893
apache/incubator-heron
heron/metricscachemgr/src/java/org/apache/heron/metricscachemgr/metricscache/MetricsCacheQueryUtils.java
MetricsCacheQueryUtils.toProtobuf
public static TopologyMaster.ExceptionLogResponse toProtobuf(ExceptionResponse response) { TopologyMaster.ExceptionLogResponse.Builder builder = TopologyMaster.ExceptionLogResponse.newBuilder(); // default OK if we have response to build already builder.setStatus(Common.Status.newBuilder().setStatus(Common.StatusCode.OK)); for (ExceptionDatum e : response.getExceptionDatapointList()) { TopologyMaster.TmasterExceptionLog.Builder exceptionBuilder = TopologyMaster.TmasterExceptionLog.newBuilder(); // ExceptionDatapoint exceptionBuilder.setComponentName(e.getComponentName()); exceptionBuilder.setHostname(e.getHostname()); exceptionBuilder.setInstanceId(e.getInstanceId()); // ExceptionData exceptionBuilder.setStacktrace(e.getStackTrace()); exceptionBuilder.setLasttime(e.getLastTime()); exceptionBuilder.setFirsttime(e.getFirstTime()); exceptionBuilder.setCount(e.getCount()); exceptionBuilder.setLogging(e.getLogging()); builder.addExceptions(exceptionBuilder); } return builder.build(); }
java
public static TopologyMaster.ExceptionLogResponse toProtobuf(ExceptionResponse response) { TopologyMaster.ExceptionLogResponse.Builder builder = TopologyMaster.ExceptionLogResponse.newBuilder(); // default OK if we have response to build already builder.setStatus(Common.Status.newBuilder().setStatus(Common.StatusCode.OK)); for (ExceptionDatum e : response.getExceptionDatapointList()) { TopologyMaster.TmasterExceptionLog.Builder exceptionBuilder = TopologyMaster.TmasterExceptionLog.newBuilder(); // ExceptionDatapoint exceptionBuilder.setComponentName(e.getComponentName()); exceptionBuilder.setHostname(e.getHostname()); exceptionBuilder.setInstanceId(e.getInstanceId()); // ExceptionData exceptionBuilder.setStacktrace(e.getStackTrace()); exceptionBuilder.setLasttime(e.getLastTime()); exceptionBuilder.setFirsttime(e.getFirstTime()); exceptionBuilder.setCount(e.getCount()); exceptionBuilder.setLogging(e.getLogging()); builder.addExceptions(exceptionBuilder); } return builder.build(); }
[ "public", "static", "TopologyMaster", ".", "ExceptionLogResponse", "toProtobuf", "(", "ExceptionResponse", "response", ")", "{", "TopologyMaster", ".", "ExceptionLogResponse", ".", "Builder", "builder", "=", "TopologyMaster", ".", "ExceptionLogResponse", ".", "newBuilder", "(", ")", ";", "// default OK if we have response to build already", "builder", ".", "setStatus", "(", "Common", ".", "Status", ".", "newBuilder", "(", ")", ".", "setStatus", "(", "Common", ".", "StatusCode", ".", "OK", ")", ")", ";", "for", "(", "ExceptionDatum", "e", ":", "response", ".", "getExceptionDatapointList", "(", ")", ")", "{", "TopologyMaster", ".", "TmasterExceptionLog", ".", "Builder", "exceptionBuilder", "=", "TopologyMaster", ".", "TmasterExceptionLog", ".", "newBuilder", "(", ")", ";", "// ExceptionDatapoint", "exceptionBuilder", ".", "setComponentName", "(", "e", ".", "getComponentName", "(", ")", ")", ";", "exceptionBuilder", ".", "setHostname", "(", "e", ".", "getHostname", "(", ")", ")", ";", "exceptionBuilder", ".", "setInstanceId", "(", "e", ".", "getInstanceId", "(", ")", ")", ";", "// ExceptionData", "exceptionBuilder", ".", "setStacktrace", "(", "e", ".", "getStackTrace", "(", ")", ")", ";", "exceptionBuilder", ".", "setLasttime", "(", "e", ".", "getLastTime", "(", ")", ")", ";", "exceptionBuilder", ".", "setFirsttime", "(", "e", ".", "getFirstTime", "(", ")", ")", ";", "exceptionBuilder", ".", "setCount", "(", "e", ".", "getCount", "(", ")", ")", ";", "exceptionBuilder", ".", "setLogging", "(", "e", ".", "getLogging", "(", ")", ")", ";", "builder", ".", "addExceptions", "(", "exceptionBuilder", ")", ";", "}", "return", "builder", ".", "build", "(", ")", ";", "}" ]
compatible with org.apache.heron.proto.tmaster.TopologyMaster.ExceptionLogResponse
[ "compatible", "with", "org", ".", "apache", ".", "heron", ".", "proto", ".", "tmaster", ".", "TopologyMaster", ".", "ExceptionLogResponse" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/metricscachemgr/src/java/org/apache/heron/metricscachemgr/metricscache/MetricsCacheQueryUtils.java#L195-L219
27,894
apache/incubator-heron
heron/simulator/src/java/org/apache/heron/simulator/utils/TopologyManager.java
TopologyManager.getComponentToTaskIds
public Map<String, List<Integer>> getComponentToTaskIds() { if (this.componentToTaskIds == null) { this.componentToTaskIds = new HashMap<>(); // Iterate over all instances and insert necessary info into the map for (PhysicalPlans.Instance instance : this.getPhysicalPlan().getInstancesList()) { int taskId = instance.getInfo().getTaskId(); String componentName = instance.getInfo().getComponentName(); if (!this.componentToTaskIds.containsKey(componentName)) { this.componentToTaskIds.put(componentName, new ArrayList<Integer>()); } this.componentToTaskIds.get(componentName).add(taskId); } } return this.componentToTaskIds; }
java
public Map<String, List<Integer>> getComponentToTaskIds() { if (this.componentToTaskIds == null) { this.componentToTaskIds = new HashMap<>(); // Iterate over all instances and insert necessary info into the map for (PhysicalPlans.Instance instance : this.getPhysicalPlan().getInstancesList()) { int taskId = instance.getInfo().getTaskId(); String componentName = instance.getInfo().getComponentName(); if (!this.componentToTaskIds.containsKey(componentName)) { this.componentToTaskIds.put(componentName, new ArrayList<Integer>()); } this.componentToTaskIds.get(componentName).add(taskId); } } return this.componentToTaskIds; }
[ "public", "Map", "<", "String", ",", "List", "<", "Integer", ">", ">", "getComponentToTaskIds", "(", ")", "{", "if", "(", "this", ".", "componentToTaskIds", "==", "null", ")", "{", "this", ".", "componentToTaskIds", "=", "new", "HashMap", "<>", "(", ")", ";", "// Iterate over all instances and insert necessary info into the map", "for", "(", "PhysicalPlans", ".", "Instance", "instance", ":", "this", ".", "getPhysicalPlan", "(", ")", ".", "getInstancesList", "(", ")", ")", "{", "int", "taskId", "=", "instance", ".", "getInfo", "(", ")", ".", "getTaskId", "(", ")", ";", "String", "componentName", "=", "instance", ".", "getInfo", "(", ")", ".", "getComponentName", "(", ")", ";", "if", "(", "!", "this", ".", "componentToTaskIds", ".", "containsKey", "(", "componentName", ")", ")", "{", "this", ".", "componentToTaskIds", ".", "put", "(", "componentName", ",", "new", "ArrayList", "<", "Integer", ">", "(", ")", ")", ";", "}", "this", ".", "componentToTaskIds", ".", "get", "(", "componentName", ")", ".", "add", "(", "taskId", ")", ";", "}", "}", "return", "this", ".", "componentToTaskIds", ";", "}" ]
Get the map &lt;componentId -&gt; taskIds&gt; from the Physical Plan @return the map from componentId to its task ids
[ "Get", "the", "map", "&lt", ";", "componentId", "-", "&gt", ";", "taskIds&gt", ";", "from", "the", "Physical", "Plan" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/simulator/src/java/org/apache/heron/simulator/utils/TopologyManager.java#L110-L128
27,895
apache/incubator-heron
heron/simulator/src/java/org/apache/heron/simulator/utils/TopologyManager.java
TopologyManager.extractTopologyTimeout
public Duration extractTopologyTimeout() { for (TopologyAPI.Config.KeyValue keyValue : this.getTopology().getTopologyConfig().getKvsList()) { if (keyValue.getKey().equals("topology.message.timeout.secs")) { return TypeUtils.getDuration(keyValue.getValue(), ChronoUnit.SECONDS); } } throw new IllegalArgumentException("topology.message.timeout.secs does not exist"); }
java
public Duration extractTopologyTimeout() { for (TopologyAPI.Config.KeyValue keyValue : this.getTopology().getTopologyConfig().getKvsList()) { if (keyValue.getKey().equals("topology.message.timeout.secs")) { return TypeUtils.getDuration(keyValue.getValue(), ChronoUnit.SECONDS); } } throw new IllegalArgumentException("topology.message.timeout.secs does not exist"); }
[ "public", "Duration", "extractTopologyTimeout", "(", ")", "{", "for", "(", "TopologyAPI", ".", "Config", ".", "KeyValue", "keyValue", ":", "this", ".", "getTopology", "(", ")", ".", "getTopologyConfig", "(", ")", ".", "getKvsList", "(", ")", ")", "{", "if", "(", "keyValue", ".", "getKey", "(", ")", ".", "equals", "(", "\"topology.message.timeout.secs\"", ")", ")", "{", "return", "TypeUtils", ".", "getDuration", "(", "keyValue", ".", "getValue", "(", ")", ",", "ChronoUnit", ".", "SECONDS", ")", ";", "}", "}", "throw", "new", "IllegalArgumentException", "(", "\"topology.message.timeout.secs does not exist\"", ")", ";", "}" ]
Extract the config value "topology.message.timeout.secs" for given topology protobuf @return the config value of "topology.message.timeout.secs"
[ "Extract", "the", "config", "value", "topology", ".", "message", ".", "timeout", ".", "secs", "for", "given", "topology", "protobuf" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/simulator/src/java/org/apache/heron/simulator/utils/TopologyManager.java#L135-L144
27,896
apache/incubator-heron
heron/simulator/src/java/org/apache/heron/simulator/utils/TopologyManager.java
TopologyManager.getStreamConsumers
public HashMap<TopologyAPI.StreamId, List<Grouping>> getStreamConsumers() { if (this.streamConsumers == null) { this.streamConsumers = new HashMap<>(); // First get a map of (TopologyAPI.StreamId -> TopologyAPI.StreamSchema) Map<TopologyAPI.StreamId, TopologyAPI.StreamSchema> streamToSchema = new HashMap<>(); // Calculate spout's output stream for (TopologyAPI.Spout spout : this.getTopology().getSpoutsList()) { for (TopologyAPI.OutputStream outputStream : spout.getOutputsList()) { streamToSchema.put(outputStream.getStream(), outputStream.getSchema()); } } // Calculate bolt's output stream for (TopologyAPI.Bolt bolt : this.getTopology().getBoltsList()) { for (TopologyAPI.OutputStream outputStream : bolt.getOutputsList()) { streamToSchema.put(outputStream.getStream(), outputStream.getSchema()); } } // Only bolts could consume from input stream for (TopologyAPI.Bolt bolt : this.getTopology().getBoltsList()) { for (TopologyAPI.InputStream inputStream : bolt.getInputsList()) { TopologyAPI.StreamSchema schema = streamToSchema.get(inputStream.getStream()); String componentName = bolt.getComp().getName(); List<Integer> taskIds = this.getComponentToTaskIds().get(componentName); if (!this.streamConsumers.containsKey(inputStream.getStream())) { this.streamConsumers.put(inputStream.getStream(), new ArrayList<>()); } this.streamConsumers.get(inputStream.getStream()).add(Grouping.create( inputStream.getGtype(), inputStream, schema, taskIds) ); } } } return this.streamConsumers; }
java
public HashMap<TopologyAPI.StreamId, List<Grouping>> getStreamConsumers() { if (this.streamConsumers == null) { this.streamConsumers = new HashMap<>(); // First get a map of (TopologyAPI.StreamId -> TopologyAPI.StreamSchema) Map<TopologyAPI.StreamId, TopologyAPI.StreamSchema> streamToSchema = new HashMap<>(); // Calculate spout's output stream for (TopologyAPI.Spout spout : this.getTopology().getSpoutsList()) { for (TopologyAPI.OutputStream outputStream : spout.getOutputsList()) { streamToSchema.put(outputStream.getStream(), outputStream.getSchema()); } } // Calculate bolt's output stream for (TopologyAPI.Bolt bolt : this.getTopology().getBoltsList()) { for (TopologyAPI.OutputStream outputStream : bolt.getOutputsList()) { streamToSchema.put(outputStream.getStream(), outputStream.getSchema()); } } // Only bolts could consume from input stream for (TopologyAPI.Bolt bolt : this.getTopology().getBoltsList()) { for (TopologyAPI.InputStream inputStream : bolt.getInputsList()) { TopologyAPI.StreamSchema schema = streamToSchema.get(inputStream.getStream()); String componentName = bolt.getComp().getName(); List<Integer> taskIds = this.getComponentToTaskIds().get(componentName); if (!this.streamConsumers.containsKey(inputStream.getStream())) { this.streamConsumers.put(inputStream.getStream(), new ArrayList<>()); } this.streamConsumers.get(inputStream.getStream()).add(Grouping.create( inputStream.getGtype(), inputStream, schema, taskIds) ); } } } return this.streamConsumers; }
[ "public", "HashMap", "<", "TopologyAPI", ".", "StreamId", ",", "List", "<", "Grouping", ">", ">", "getStreamConsumers", "(", ")", "{", "if", "(", "this", ".", "streamConsumers", "==", "null", ")", "{", "this", ".", "streamConsumers", "=", "new", "HashMap", "<>", "(", ")", ";", "// First get a map of (TopologyAPI.StreamId -> TopologyAPI.StreamSchema)", "Map", "<", "TopologyAPI", ".", "StreamId", ",", "TopologyAPI", ".", "StreamSchema", ">", "streamToSchema", "=", "new", "HashMap", "<>", "(", ")", ";", "// Calculate spout's output stream", "for", "(", "TopologyAPI", ".", "Spout", "spout", ":", "this", ".", "getTopology", "(", ")", ".", "getSpoutsList", "(", ")", ")", "{", "for", "(", "TopologyAPI", ".", "OutputStream", "outputStream", ":", "spout", ".", "getOutputsList", "(", ")", ")", "{", "streamToSchema", ".", "put", "(", "outputStream", ".", "getStream", "(", ")", ",", "outputStream", ".", "getSchema", "(", ")", ")", ";", "}", "}", "// Calculate bolt's output stream", "for", "(", "TopologyAPI", ".", "Bolt", "bolt", ":", "this", ".", "getTopology", "(", ")", ".", "getBoltsList", "(", ")", ")", "{", "for", "(", "TopologyAPI", ".", "OutputStream", "outputStream", ":", "bolt", ".", "getOutputsList", "(", ")", ")", "{", "streamToSchema", ".", "put", "(", "outputStream", ".", "getStream", "(", ")", ",", "outputStream", ".", "getSchema", "(", ")", ")", ";", "}", "}", "// Only bolts could consume from input stream", "for", "(", "TopologyAPI", ".", "Bolt", "bolt", ":", "this", ".", "getTopology", "(", ")", ".", "getBoltsList", "(", ")", ")", "{", "for", "(", "TopologyAPI", ".", "InputStream", "inputStream", ":", "bolt", ".", "getInputsList", "(", ")", ")", "{", "TopologyAPI", ".", "StreamSchema", "schema", "=", "streamToSchema", ".", "get", "(", "inputStream", ".", "getStream", "(", ")", ")", ";", "String", "componentName", "=", "bolt", ".", "getComp", "(", ")", ".", "getName", "(", ")", ";", "List", "<", "Integer", ">", "taskIds", "=", "this", ".", "getComponentToTaskIds", "(", ")", ".", "get", "(", "componentName", ")", ";", "if", "(", "!", "this", ".", "streamConsumers", ".", "containsKey", "(", "inputStream", ".", "getStream", "(", ")", ")", ")", "{", "this", ".", "streamConsumers", ".", "put", "(", "inputStream", ".", "getStream", "(", ")", ",", "new", "ArrayList", "<>", "(", ")", ")", ";", "}", "this", ".", "streamConsumers", ".", "get", "(", "inputStream", ".", "getStream", "(", ")", ")", ".", "add", "(", "Grouping", ".", "create", "(", "inputStream", ".", "getGtype", "(", ")", ",", "inputStream", ",", "schema", ",", "taskIds", ")", ")", ";", "}", "}", "}", "return", "this", ".", "streamConsumers", ";", "}" ]
Get the stream consumers map that was generated from the topology @return the populated stream consumers' map
[ "Get", "the", "stream", "consumers", "map", "that", "was", "generated", "from", "the", "topology" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/simulator/src/java/org/apache/heron/simulator/utils/TopologyManager.java#L168-L214
27,897
apache/incubator-heron
heron/common/src/java/org/apache/heron/common/network/HeronServer.java
HeronServer.stop
public void stop() { if (acceptChannel == null || !acceptChannel.isOpen()) { LOG.info("Fail to stop server; not yet open."); return; } // Clear all connected socket and related stuff for (Map.Entry<SocketChannel, SocketChannelHelper> connections : activeConnections.entrySet()) { SocketChannel channel = connections.getKey(); SocketAddress channelAddress = channel.socket().getRemoteSocketAddress(); LOG.info("Closing connected channel from client: " + channelAddress); LOG.info("Removing all interest on channel: " + channelAddress); nioLooper.removeAllInterest(channel); // Dispatch the child instance onClose(channel); // Clear the SocketChannelHelper connections.getValue().clear(); } // Clear state inside the HeronServer activeConnections.clear(); requestMap.clear(); messageMap.clear(); try { acceptChannel.close(); } catch (IOException e) { LOG.log(Level.SEVERE, "Failed to close server", e); } }
java
public void stop() { if (acceptChannel == null || !acceptChannel.isOpen()) { LOG.info("Fail to stop server; not yet open."); return; } // Clear all connected socket and related stuff for (Map.Entry<SocketChannel, SocketChannelHelper> connections : activeConnections.entrySet()) { SocketChannel channel = connections.getKey(); SocketAddress channelAddress = channel.socket().getRemoteSocketAddress(); LOG.info("Closing connected channel from client: " + channelAddress); LOG.info("Removing all interest on channel: " + channelAddress); nioLooper.removeAllInterest(channel); // Dispatch the child instance onClose(channel); // Clear the SocketChannelHelper connections.getValue().clear(); } // Clear state inside the HeronServer activeConnections.clear(); requestMap.clear(); messageMap.clear(); try { acceptChannel.close(); } catch (IOException e) { LOG.log(Level.SEVERE, "Failed to close server", e); } }
[ "public", "void", "stop", "(", ")", "{", "if", "(", "acceptChannel", "==", "null", "||", "!", "acceptChannel", ".", "isOpen", "(", ")", ")", "{", "LOG", ".", "info", "(", "\"Fail to stop server; not yet open.\"", ")", ";", "return", ";", "}", "// Clear all connected socket and related stuff", "for", "(", "Map", ".", "Entry", "<", "SocketChannel", ",", "SocketChannelHelper", ">", "connections", ":", "activeConnections", ".", "entrySet", "(", ")", ")", "{", "SocketChannel", "channel", "=", "connections", ".", "getKey", "(", ")", ";", "SocketAddress", "channelAddress", "=", "channel", ".", "socket", "(", ")", ".", "getRemoteSocketAddress", "(", ")", ";", "LOG", ".", "info", "(", "\"Closing connected channel from client: \"", "+", "channelAddress", ")", ";", "LOG", ".", "info", "(", "\"Removing all interest on channel: \"", "+", "channelAddress", ")", ";", "nioLooper", ".", "removeAllInterest", "(", "channel", ")", ";", "// Dispatch the child instance", "onClose", "(", "channel", ")", ";", "// Clear the SocketChannelHelper", "connections", ".", "getValue", "(", ")", ".", "clear", "(", ")", ";", "}", "// Clear state inside the HeronServer", "activeConnections", ".", "clear", "(", ")", ";", "requestMap", ".", "clear", "(", ")", ";", "messageMap", ".", "clear", "(", ")", ";", "try", "{", "acceptChannel", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "LOG", ".", "log", "(", "Level", ".", "SEVERE", ",", "\"Failed to close server\"", ",", "e", ")", ";", "}", "}" ]
Stop the HeronServer and clean relative staff
[ "Stop", "the", "HeronServer", "and", "clean", "relative", "staff" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/common/src/java/org/apache/heron/common/network/HeronServer.java#L107-L135
27,898
apache/incubator-heron
storm-compatibility/src/java/backtype/storm/metric/api/GlobalMetrics.java
GlobalMetrics.incr
public static void incr(String counterName) { org.apache.heron.api.metric.GlobalMetrics.incr(counterName); }
java
public static void incr(String counterName) { org.apache.heron.api.metric.GlobalMetrics.incr(counterName); }
[ "public", "static", "void", "incr", "(", "String", "counterName", ")", "{", "org", ".", "apache", ".", "heron", ".", "api", ".", "metric", ".", "GlobalMetrics", ".", "incr", "(", "counterName", ")", ";", "}" ]
Not thread safe increment of counterName. Counter doesn't exist unless incremented once
[ "Not", "thread", "safe", "increment", "of", "counterName", ".", "Counter", "doesn", "t", "exist", "unless", "incremented", "once" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/storm-compatibility/src/java/backtype/storm/metric/api/GlobalMetrics.java#L29-L31
27,899
apache/incubator-heron
heron/scheduler-core/src/java/org/apache/heron/scheduler/RuntimeManagerRunner.java
RuntimeManagerRunner.activateTopologyHandler
private void activateTopologyHandler(String topologyName) throws TMasterException { assert !potentialStaleExecutionData; NetworkUtils.TunnelConfig tunnelConfig = NetworkUtils.TunnelConfig.build(config, NetworkUtils.HeronSystem.SCHEDULER); TMasterUtils.transitionTopologyState(topologyName, TMasterUtils.TMasterCommand.ACTIVATE, Runtime.schedulerStateManagerAdaptor(runtime), TopologyAPI.TopologyState.PAUSED, TopologyAPI.TopologyState.RUNNING, tunnelConfig); }
java
private void activateTopologyHandler(String topologyName) throws TMasterException { assert !potentialStaleExecutionData; NetworkUtils.TunnelConfig tunnelConfig = NetworkUtils.TunnelConfig.build(config, NetworkUtils.HeronSystem.SCHEDULER); TMasterUtils.transitionTopologyState(topologyName, TMasterUtils.TMasterCommand.ACTIVATE, Runtime.schedulerStateManagerAdaptor(runtime), TopologyAPI.TopologyState.PAUSED, TopologyAPI.TopologyState.RUNNING, tunnelConfig); }
[ "private", "void", "activateTopologyHandler", "(", "String", "topologyName", ")", "throws", "TMasterException", "{", "assert", "!", "potentialStaleExecutionData", ";", "NetworkUtils", ".", "TunnelConfig", "tunnelConfig", "=", "NetworkUtils", ".", "TunnelConfig", ".", "build", "(", "config", ",", "NetworkUtils", ".", "HeronSystem", ".", "SCHEDULER", ")", ";", "TMasterUtils", ".", "transitionTopologyState", "(", "topologyName", ",", "TMasterUtils", ".", "TMasterCommand", ".", "ACTIVATE", ",", "Runtime", ".", "schedulerStateManagerAdaptor", "(", "runtime", ")", ",", "TopologyAPI", ".", "TopologyState", ".", "PAUSED", ",", "TopologyAPI", ".", "TopologyState", ".", "RUNNING", ",", "tunnelConfig", ")", ";", "}" ]
Handler to activate a topology
[ "Handler", "to", "activate", "a", "topology" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/scheduler-core/src/java/org/apache/heron/scheduler/RuntimeManagerRunner.java#L111-L118