idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
20,400 | public String getCanonicalForm ( ) { StringBuilder buf = new StringBuilder ( ) ; for ( PathElement pe : elements ) { buf . append ( "." ) . append ( pe . getCanonicalForm ( ) ) ; } return buf . substring ( 1 ) ; } | Testing method . |
20,401 | 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 . |
20,402 | 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 ) ... | 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 |
20,403 | 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 ) ) ) ; ... | Given a json document finds out absolute path to every leaf element |
20,404 | 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 ( "]" )... | Converts a standard json path to human readable SimpleTraversr compatible path |
20,405 | @ 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... | Given a fluffy json document it recursively removes all null elements to compact the json document |
20,406 | 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 < > ( ) ; for ( RemovrSpec childSpec : children ) { indiciesToRemove . add... | Call our child nodes build up the set of keys or indices to actually remove and then remove them . |
20,407 | public static < T > T jsonTo ( String json , TypeReference < T > typeRef ) { return util . stringToType ( json , typeRef ) ; } | Use the stringToType method instead . |
20,408 | @ SuppressWarnings ( "unchecked" ) 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 ob... | Navigate inside a json object in quick and dirty way . |
20,409 | 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 ) ) { r... | Check if a sequence is blank |
20,410 | 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... | Initialize the arg parser for the Sort sub command |
20,411 | protected Integer getNonNegativeIntegerFromLiteralPathElement ( ) { Integer pathElementInt = null ; try { pathElementInt = Integer . parseInt ( pathElement . getRawKey ( ) ) ; if ( pathElementInt < 0 ) { return null ; } } catch ( NumberFormatException nfe ) { } return pathElementInt ; } | Try to interpret the spec String value as a non - negative integer . |
20,412 | 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 ... | Initialize the arg parser for the Transform sub command |
20,413 | 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 fil... | Process the transform sub command |
20,414 | 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 . |
20,415 | 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 . |
20,416 | 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 ... | Builds a Chainr instance using the spec described in the File that is passed in . |
20,417 | 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 . |
20,418 | public Object transform ( Object input ) { Map < String , Object > wrappedMap = new HashMap < > ( ) ; wrappedMap . put ( ROOT_KEY , input ) ; rootSpec . applyToMap ( wrappedMap ) ; return input ; } | Recursively removes data from the input JSON . |
20,419 | public Object transform ( Object input ) { Map < String , Object > output = new HashMap < > ( ) ; MatchedElement rootLpe = new MatchedElement ( ROOT_KEY ) ; WalkedPath walkedPath = new WalkedPath ( ) ; walkedPath . add ( input , rootLpe ) ; rootSpec . apply ( ROOT_KEY , Optional . of ( input ) , walkedPath , output , n... | Applies the Shiftr transform . |
20,420 | 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 ( MatchablePath... | Create a path element and ensures it is a Matchable Path Element |
20,421 | public static PathElement parseSingleKeyLHS ( String origKey ) { String elementKey ; String keyToInspect ; if ( origKey . contains ( "\\" ) ) { keyToInspect = removeEscapedValues ( origKey ) ; elementKey = removeEscapeChars ( origKey ) ; } else { keyToInspect = origKey ; elementKey = origKey ; } if ( "@" . equals ( key... | Visible for Testing . |
20,422 | 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 . |
20,423 | 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 a... | Initialize the arg parser for the Diffy sub command |
20,424 | 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 , sup... | Process the Diffy Subcommand |
20,425 | public static List < String > parseDotNotation ( List < String > pathStrings , Iterator < Character > iter , String dotNotationRef ) { if ( ! iter . hasNext ( ) ) { return pathStrings ; } boolean prevIsEscape = false ; boolean currIsEscape = false ; StringBuilder sb = new StringBuilder ( ) ; char c ; while ( iter . has... | Method that recursively parses a dotNotation String based on an iterator . |
20,426 | 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... | given rating \\ pants - > rating \ pants escape the escape char |
20,427 | public void sendOutState ( State < Serializable , Serializable > state , String checkpointId , boolean spillState , String location ) { outputter . sendOutState ( state , checkpointId , spillState , location ) ; } | Flush the states |
20,428 | @ 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 ( )... | Gets the Thrift object representing the topology . |
20,429 | 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 < i... | Handle the execution of the instance |
20,430 | 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 |
20,431 | 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 = tuple... | Process HeronDataTuple and insert it into cache |
20,432 | 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 ... | Process HeronAckTuple and insert it into cache |
20,433 | protected void processAcksAndFails ( int srcTaskId , int taskId , HeronTuples . HeronControlTupleSet controlTupleSet ) { HeronTuples . HeronTupleSet . Builder out = HeronTuples . HeronTupleSet . newBuilder ( ) ; out . setSrcTaskId ( srcTaskId ) ; for ( HeronTuples . AckTuple emitTuple : controlTupleSet . getEmitsList (... | Do the XOR control and send the ack tuples to instance if necessary |
20,434 | protected void drainCache ( ) { Map < Integer , List < HeronTuples . HeronTupleSet > > cache = tupleCache . getCache ( ) ; if ( ! isSendTuplesToInstance ( new LinkedList < Integer > ( cache . keySet ( ) ) ) ) { return ; } for ( Map . Entry < Integer , List < HeronTuples . HeronTupleSet > > entry : cache . entrySet ( ) ... | Drain the TupleCache if there are room in destination tasks |
20,435 | 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 |
20,436 | protected void sendMessageToInstance ( int taskId , HeronTuples . HeronTupleSet message ) { taskIdToInstanceExecutor . get ( taskId ) . getStreamInQueue ( ) . offer ( message ) ; } | Send one message to target task |
20,437 | 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 H... | Compose the component resource map by reading from user configs or default |
20,438 | 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 = component... | Identifies which components need to be scaled given specific scaling direction |
20,439 | 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 , ByteAmoun... | Identifies the resources reclaimed by the components that will be scaled down |
20,440 | 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 |
20,441 | public void manageTopology ( ) throws TopologyRuntimeManagementException , TMasterException , PackingException { String topologyName = Context . topologyName ( config ) ; String statemgrClass = Context . stateManagerClass ( config ) ; IStateManager statemgr ; try { statemgr = ReflectionUtils . newInstance ( statemgrCla... | Manager a topology 1 . Instantiate necessary resources 2 . Valid whether the runtime management is legal 3 . Complete the runtime management for a specific command |
20,442 | protected void validateExecutionState ( String topologyName , ExecutionEnvironment . ExecutionState executionState ) throws TopologyRuntimeManagementException { String stateCluster = executionState . getCluster ( ) ; String stateRole = executionState . getRole ( ) ; String stateEnv = executionState . getEnviron ( ) ; S... | Verify that the environment information in execution state matches the request |
20,443 | 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 . |
20,444 | 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_... | Builds and returns configuration needed by REEF client to launch topology as a REEF job and track it . |
20,445 | private void handleSelectedKeys ( ) { Set < SelectionKey > selectedKeys = selector . selectedKeys ( ) ; Iterator < SelectionKey > keyIterator = selectedKeys . iterator ( ) ; while ( keyIterator . hasNext ( ) ) { SelectionKey key = keyIterator . next ( ) ; keyIterator . remove ( ) ; ISelectHandler callback = ( ISelectHa... | Handle the selected keys |
20,446 | 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 |
20,447 | private void removeInterest ( SelectableChannel channel , int operation ) { SelectionKey key = channel . keyFor ( selector ) ; 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 . |
20,448 | 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 ... |
20,449 | public URI uploadPackage ( ) throws UploaderException { boolean fileExists = new File ( topologyPackageLocation ) . isFile ( ) ; if ( ! fileExists ) { throw new UploaderException ( String . format ( "Topology package does not exist at '%s'" , topologyPackageLocation ) ) ; } Path filePath = Paths . get ( destTopologyFil... | Upload the topology package to the destined location in local file system |
20,450 | 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 |
20,451 | private void setPackingConfigs ( Config config ) { List < TopologyAPI . Config . KeyValue > topologyConfig = topology . getTopologyConfig ( ) . getKvsList ( ) ; this . defaultInstanceResources = new Resource ( Context . instanceCpu ( config ) , Context . instanceRam ( config ) , Context . instanceDisk ( config ) ) ; in... | Instatiate the packing algorithm parameters related to this topology . |
20,452 | 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 . getS... | Gets the set of streams declared for the specified component . |
20,453 | 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 ... | Gets the declared inputs to the specified component . |
20,454 | public void submitTopology ( ) throws TopologySubmissionException { Config primaryRuntime = Config . newBuilder ( ) . putAll ( LauncherUtils . getInstance ( ) . createPrimaryRuntime ( topology ) ) . build ( ) ; if ( Context . dryRun ( config ) ) { callLauncherRunner ( primaryRuntime ) ; return ; } String statemgrClass ... | Submit a topology 1 . Instantiate necessary resources 2 . Valid whether it is legal to submit a topology 3 . Call LauncherRunner |
20,455 | 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 . |
20,456 | 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 al... | Container allocation is asynchronous . Requests all containers in the input set serially to ensure allocated resources match the required resources . |
20,457 | 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 . i... | Terminates any yarn containers associated with the given containers . |
20,458 | @ SuppressWarnings ( "unchecked" ) public void restoreState ( Map < String , Serializable > state ) { LOG . info ( "Restoring window manager state" ) ; if ( state . get ( EVICTION_STATE_KEY ) != null ) { ( ( EvictionPolicy ) evictionPolicy ) . restoreState ( state . get ( EVICTION_STATE_KEY ) ) ; } if ( state . get ( T... | Restore state associated with the window manager |
20,459 | public Map < String , Serializable > getState ( ) { Map < String , Serializable > ret = new HashMap < > ( ) ; if ( evictionPolicy . getState ( ) != null ) { ret . put ( EVICTION_STATE_KEY , ( Serializable ) evictionPolicy . getState ( ) ) ; } if ( triggerPolicy . getState ( ) != null ) { ret . put ( TRIGGER_STATE_KEY ,... | Get the state of the window manager |
20,460 | public static String [ ] schedulerCommand ( Config config , Config runtime , List < Integer > freePorts ) { List < String > commands = new ArrayList < > ( ) ; String javaExecutable = String . format ( "%s/%s" , Context . clusterJavaHome ( config ) , "bin/java" ) ; commands . add ( javaExecutable ) ; commands . add ( "-... | Utils method to construct the command to start heron - scheduler |
20,461 | public static String [ ] schedulerCommandArgs ( Config config , Config runtime , List < Integer > freePorts ) { 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 Runtime... | Util method to get the arguments to the heron scheduler . |
20,462 | 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 . ... | 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 |
20,463 | 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 ... | Util method to parse port map and container id and translate them into arguments to be used by executor |
20,464 | public static boolean setLibSchedulerLocation ( Config runtime , IScheduler scheduler , boolean isService ) { 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 |
20,465 | public static boolean setSchedulerLocation ( Config runtime , String schedulerEndpoint , IScheduler scheduler ) { Scheduler . SchedulerLocation . Builder builder = Scheduler . SchedulerLocation . newBuilder ( ) . setTopologyName ( Runtime . topologyName ( runtime ) ) . setHttpEndpoint ( schedulerEndpoint ) ; List < Str... | Set the location of scheduler for other processes to discover |
20,466 | 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 . SchedulerResp... | construct heron scheduler response basing on the given result |
20,467 | public static boolean createOrCleanDirectory ( String directory ) { 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 ; } } i... | Create the directory if it does not exist otherwise clean the directory . |
20,468 | public static boolean curlAndExtractPackage ( String workingDirectory , String packageURI , String packageDestination , boolean isDeletePackage , boolean isVerbose ) { LOG . log ( Level . FINE , "Fetching package {0}" , packageURI ) ; LOG . fine ( "Fetched package can overwrite old one." ) ; if ( ! ShellUtils . curlPac... | Curl a package extract it to working directory |
20,469 | 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 ( ) ... | Replaces persisted packing plan in state manager . |
20,470 | 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 |
20,471 | 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 ( co... | Estimate the per instance and topology resources for the packing plan based on the ramMap instance defaults and paddingPercentage . |
20,472 | 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 = maxContainerRe... | Generates the containers that correspond to the current packing plan along with their associated instances . |
20,473 | private static void addToContainer ( Container container , PackingPlan . InstancePlan instancePlan , Map < String , TreeSet < Integer > > componentIndexes , Set < Integer > taskIds ) { container . add ( instancePlan ) ; String componentName = instancePlan . getComponentName ( ) ; componentIndexes . computeIfAbsent ( co... | Add instancePlan to container and update the componentIndexes and taskIds indexes |
20,474 | 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 . |
20,475 | 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 . |
20,476 | 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 . |
20,477 | public void sendRequest ( Message request , Object context , Message . Builder responseBuilder , Duration timeout ) { final REQID rid = REQID . generate ( ) ; contextMap . put ( rid , context ) ; responseMessageMap . put ( rid , responseBuilder ) ; if ( timeout . getSeconds ( ) > 0 ) { registerTimerEvent ( timeout , ne... | A negative value of the timeout means no timeout . |
20,478 | 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 |
20,479 | 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 { } } | Handle the timeout for a particular REQID |
20,480 | protected void startSchedulerDriver ( ) { driver . start ( ) ; LOG . info ( "Waiting for Mesos Framework get registered" ) ; long timeout = MesosContext . getHeronMesosFrameworkStagingTimeoutMs ( config ) ; if ( ! mesosFramework . waitForRegistered ( timeout , TimeUnit . MILLISECONDS ) ) { throw new RuntimeException ( ... | Start the scheduler driver and wait it to get registered |
20,481 | protected void joinSchedulerDriver ( long timeout , TimeUnit unit ) { ExecutorService service = Executors . newFixedThreadPool ( 1 ) ; final CountDownLatch closeLatch = new CountDownLatch ( 1 ) ; Runnable driverJoin = new Runnable ( ) { public void run ( ) { driver . join ( ) ; closeLatch . countDown ( ) ; } } ; servic... | Waits for the driver to be stopped or aborted |
20,482 | 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 ( "... | Get BaseContainer info . |
20,483 | public Protos . TaskInfo constructMesosTaskInfo ( Config heronConfig , Config heronRuntime ) { String taskIdStr = this . taskId ; Protos . TaskID mesosTaskID = Protos . TaskID . newBuilder ( ) . setValue ( taskIdStr ) . build ( ) ; Protos . TaskInfo . Builder taskInfo = Protos . TaskInfo . newBuilder ( ) . setName ( ba... | Construct the Mesos TaskInfo in Protos to launch basing on the LaunchableTask |
20,484 | @ SuppressWarnings ( "unchecked" ) private void gatherOneMetric ( String metricName , Metrics . MetricPublisherPublishMessage . Builder builder ) { Object metricValue = metrics . get ( metricName ) . getValueAndReset ( ) ; if ( metricValue == null ) { return ; } if ( metricValue instanceof Map ) { for ( Map . Entry < O... | and add it to MetricPublisherPublishMessage builder given . |
20,485 | public static MetricRequest fromProtobuf ( TopologyMaster . MetricRequest request ) { String componentName = request . getComponentName ( ) ; Map < String , Set < String > > componentNameInstanceId = new HashMap < > ( ) ; if ( request . getInstanceIdCount ( ) == 0 ) { componentNameInstanceId . put ( componentName , nul... | compatible with org . apache . heron . proto . tmaster . TopologyMaster . MetricRequest |
20,486 | public static TopologyMaster . MetricResponse toProtobuf ( MetricResponse response , MetricRequest request ) { TopologyMaster . MetricResponse . Builder builder = TopologyMaster . MetricResponse . newBuilder ( ) ; builder . setInterval ( ( request . getEndTime ( ) - request . getStartTime ( ) ) / 1000 ) ; builder . set... | compatible with org . apache . heron . proto . tmaster . TopologyMaster . MetricResponse |
20,487 | 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 ... | compatible with org . apache . heron . proto . tmaster . TopologyMaster . ExceptionLogRequest |
20,488 | public static TopologyMaster . ExceptionLogResponse toProtobuf ( ExceptionResponse response ) { TopologyMaster . ExceptionLogResponse . Builder builder = TopologyMaster . ExceptionLogResponse . newBuilder ( ) ; builder . setStatus ( Common . Status . newBuilder ( ) . setStatus ( Common . StatusCode . OK ) ) ; for ( Exc... | compatible with org . apache . heron . proto . tmaster . TopologyMaster . ExceptionLogResponse |
20,489 | public Map < String , List < Integer > > getComponentToTaskIds ( ) { if ( this . componentToTaskIds == null ) { this . componentToTaskIds = new HashMap < > ( ) ; for ( PhysicalPlans . Instance instance : this . getPhysicalPlan ( ) . getInstancesList ( ) ) { int taskId = instance . getInfo ( ) . getTaskId ( ) ; String c... | Get the map < ; componentId - > ; taskIds> ; from the Physical Plan |
20,490 | 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 ) ... | Extract the config value topology . message . timeout . secs for given topology protobuf |
20,491 | public HashMap < TopologyAPI . StreamId , List < Grouping > > getStreamConsumers ( ) { if ( this . streamConsumers == null ) { this . streamConsumers = new HashMap < > ( ) ; Map < TopologyAPI . StreamId , TopologyAPI . StreamSchema > streamToSchema = new HashMap < > ( ) ; for ( TopologyAPI . Spout spout : this . getTop... | Get the stream consumers map that was generated from the topology |
20,492 | public void stop ( ) { if ( acceptChannel == null || ! acceptChannel . isOpen ( ) ) { LOG . info ( "Fail to stop server; not yet open." ) ; return ; } for ( Map . Entry < SocketChannel , SocketChannelHelper > connections : activeConnections . entrySet ( ) ) { SocketChannel channel = connections . getKey ( ) ; SocketAdd... | Stop the HeronServer and clean relative staff |
20,493 | 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 |
20,494 | private void activateTopologyHandler ( String topologyName ) throws TMasterException { assert ! potentialStaleExecutionData ; NetworkUtils . TunnelConfig tunnelConfig = NetworkUtils . TunnelConfig . build ( config , NetworkUtils . HeronSystem . SCHEDULER ) ; TMasterUtils . transitionTopologyState ( topologyName , TMast... | Handler to activate a topology |
20,495 | protected void cleanState ( String topologyName , SchedulerStateManagerAdaptor statemgr ) throws TopologyRuntimeManagementException { LOG . fine ( "Cleaning up topology state" ) ; Boolean result ; result = statemgr . deleteTMasterLocation ( topologyName ) ; if ( result == null || ! result ) { throw new TopologyRuntimeM... | Clean all states of a heron topology 1 . Topology def and ExecutionState are required to exist to delete 2 . TMasterLocation SchedulerLocation and PhysicalPlan may not exist to delete |
20,496 | public PackingPlan pack ( ) { PackingPlanBuilder planBuilder = newPackingPlanBuilder ( null ) ; try { planBuilder = getFFDAllocation ( planBuilder ) ; } catch ( ConstraintViolationException e ) { throw new PackingException ( "Could not allocate all instances to packing plan" , e ) ; } return planBuilder . build ( ) ; } | Get a packing plan using First Fit Decreasing |
20,497 | private void assignInstancesToContainers ( PackingPlanBuilder planBuilder , Map < String , Integer > parallelismMap ) throws ConstraintViolationException { List < ResourceRequirement > resourceRequirements = getSortedInstances ( parallelismMap . keySet ( ) ) ; for ( ResourceRequirement resourceRequirement : resourceReq... | Assigns instances to containers |
20,498 | private void placeFFDInstance ( PackingPlanBuilder planBuilder , String componentName ) throws ConstraintViolationException { if ( this . numContainers == 0 ) { planBuilder . updateNumContainers ( ++ numContainers ) ; } try { planBuilder . addInstance ( new ContainerIdScorer ( ) , componentName ) ; } catch ( ResourceEx... | Assign a particular instance to an existing container or to a new container |
20,499 | public Map < Integer , List < HeronTuples . HeronTupleSet > > getCache ( ) { Map < Integer , List < HeronTuples . HeronTupleSet > > res = new HashMap < > ( ) ; for ( Map . Entry < Integer , TupleList > entry : cache . entrySet ( ) ) { res . put ( entry . getKey ( ) , entry . getValue ( ) . getTuplesList ( ) ) ; } retur... | Modification on Map would not cahnge values in cache |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.