idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
40,900 | private void connectBacklink ( final AbstractJobVertex vertex , final ChannelType channelType , final int indexOfOutputGate , final int indexOfInputGate , DistributionPattern distributionPattern ) { for ( int i = this . backwardEdges . size ( ) ; i <= indexOfInputGate ; i ++ ) { this . backwardEdges . add ( null ) ; } this . backwardEdges . set ( indexOfInputGate , new JobEdge ( vertex , channelType , indexOfOutputGate , distributionPattern ) ) ; } | Creates a backward link from a connected job vertex . |
40,901 | public void checkConfiguration ( final AbstractInvokable invokable ) throws IllegalConfigurationException { if ( invokable == null ) { throw new IllegalArgumentException ( "Argument invokable is null" ) ; } try { invokable . checkConfiguration ( ) ; } catch ( IllegalConfigurationException icex ) { throw icex ; } catch ( Throwable t ) { throw new IllegalConfigurationException ( "Checking the invokable's configuration caused an error: " + StringUtils . stringifyException ( t ) ) ; } } | Performs task specific checks if the respective task has been configured properly . |
40,902 | @ SuppressWarnings ( "unchecked" ) public O withConstantSetFirst ( String ... constantSetFirst ) { if ( this . udfSemantics == null ) { this . udfSemantics = new DualInputSemanticProperties ( ) ; } SemanticPropUtil . getSemanticPropsDualFromString ( this . udfSemantics , constantSetFirst , null , null , null , null , null , this . getInput1Type ( ) , this . getInput2Type ( ) , this . getResultType ( ) ) ; O returnType = ( O ) this ; return returnType ; } | Adds a constant - set annotation for the first input of the UDF . |
40,903 | @ SuppressWarnings ( "unchecked" ) public O withConstantSetSecond ( String ... constantSetSecond ) { if ( this . udfSemantics == null ) { this . udfSemantics = new DualInputSemanticProperties ( ) ; } SemanticPropUtil . getSemanticPropsDualFromString ( this . udfSemantics , null , constantSetSecond , null , null , null , null , this . getInput1Type ( ) , this . getInput2Type ( ) , this . getResultType ( ) ) ; O returnType = ( O ) this ; return returnType ; } | Adds a constant - set annotation for the second input of the UDF . |
40,904 | public boolean hasDeadlock ( List < ? extends PlanNode > sinks ) { this . g = new DeadlockGraph ( ) ; for ( PlanNode s : sinks ) { s . accept ( this ) ; } if ( g . hasCycle ( ) ) { return true ; } else { return false ; } } | Creates new DeadlockGraph from plan and checks for cycles |
40,905 | public ExecutionVertex duplicateVertex ( final boolean preserveVertexID ) { ExecutionVertexID newVertexID ; if ( preserveVertexID ) { newVertexID = this . vertexID ; } else { newVertexID = new ExecutionVertexID ( ) ; } final ExecutionVertex duplicatedVertex = new ExecutionVertex ( newVertexID , this . executionGraph , this . groupVertex , this . outputGates . length , this . inputGates . length ) ; for ( int i = 0 ; i < this . outputGates . length ; ++ i ) { duplicatedVertex . outputGates [ i ] = new ExecutionGate ( new GateID ( ) , duplicatedVertex , this . outputGates [ i ] . getGroupEdge ( ) , false ) ; } for ( int i = 0 ; i < this . inputGates . length ; ++ i ) { duplicatedVertex . inputGates [ i ] = new ExecutionGate ( new GateID ( ) , duplicatedVertex , this . inputGates [ i ] . getGroupEdge ( ) , true ) ; } duplicatedVertex . setAllocatedResource ( this . allocatedResource . get ( ) ) ; return duplicatedVertex ; } | Returns a duplicate of this execution vertex . |
40,906 | void insertOutputGate ( final int pos , final ExecutionGate outputGate ) { if ( this . outputGates [ pos ] != null ) { throw new IllegalStateException ( "Output gate at position " + pos + " is not null" ) ; } this . outputGates [ pos ] = outputGate ; } | Inserts the output gate at the given position . |
40,907 | void insertInputGate ( final int pos , final ExecutionGate inputGate ) { if ( this . inputGates [ pos ] != null ) { throw new IllegalStateException ( "Input gate at position " + pos + " is not null" ) ; } this . inputGates [ pos ] = inputGate ; } | Inserts the input gate at the given position . |
40,908 | public void updateExecutionStateAsynchronously ( final ExecutionState newExecutionState , final String optionalMessage ) { final Runnable command = new Runnable ( ) { public void run ( ) { updateExecutionState ( newExecutionState , optionalMessage ) ; } } ; this . executionGraph . executeCommand ( command ) ; } | Updates the vertex s current execution state through the job s executor service . |
40,909 | public ExecutionState updateExecutionState ( ExecutionState newExecutionState , final String optionalMessage ) { if ( newExecutionState == null ) { throw new IllegalArgumentException ( "Argument newExecutionState must not be null" ) ; } final ExecutionState currentExecutionState = this . executionState . get ( ) ; if ( currentExecutionState == ExecutionState . CANCELING ) { if ( newExecutionState == ExecutionState . FINISHING ) { return currentExecutionState ; } if ( newExecutionState == ExecutionState . FINISHED ) { LOG . info ( "Received transition from CANCELING to FINISHED for vertex " + toString ( ) + ", converting it to CANCELED" ) ; newExecutionState = ExecutionState . CANCELED ; } } final ExecutionState previousState = this . executionState . getAndSet ( newExecutionState ) ; if ( previousState == newExecutionState ) { return previousState ; } ExecutionStateTransition . checkTransition ( true , toString ( ) , previousState , newExecutionState ) ; final Iterator < ExecutionListener > it = this . executionListeners . values ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { it . next ( ) . executionStateChanged ( this . executionGraph . getJobID ( ) , this . vertexID , newExecutionState , optionalMessage ) ; } checkCancelRequestedFlag ( ) ; return previousState ; } | Updates the vertex s current execution state . |
40,910 | private void checkCancelRequestedFlag ( ) { if ( this . cancelRequested . compareAndSet ( true , false ) ) { final TaskCancelResult tsr = cancelTask ( ) ; if ( tsr . getReturnCode ( ) != AbstractTaskResult . ReturnCode . SUCCESS && tsr . getReturnCode ( ) != AbstractTaskResult . ReturnCode . TASK_NOT_FOUND ) { LOG . error ( "Unable to cancel vertex " + this + ": " + tsr . getReturnCode ( ) . toString ( ) + ( ( tsr . getDescription ( ) != null ) ? ( " (" + tsr . getDescription ( ) + ")" ) : "" ) ) ; } } } | Checks if another thread requested the vertex to cancel while it was in state STARTING . If so the method clears the respective flag and repeats the cancel request . |
40,911 | public int getNumberOfPredecessors ( ) { int numberOfPredecessors = 0 ; for ( int i = 0 ; i < this . inputGates . length ; ++ i ) { numberOfPredecessors += this . inputGates [ i ] . getNumberOfEdges ( ) ; } return numberOfPredecessors ; } | Returns the number of predecessors i . e . the number of vertices which connect to this vertex . |
40,912 | public int getNumberOfSuccessors ( ) { int numberOfSuccessors = 0 ; for ( int i = 0 ; i < this . outputGates . length ; ++ i ) { numberOfSuccessors += this . outputGates [ i ] . getNumberOfEdges ( ) ; } return numberOfSuccessors ; } | Returns the number of successors i . e . the number of vertices this vertex is connected to . |
40,913 | public TaskSubmissionResult startTask ( ) { final AllocatedResource ar = this . allocatedResource . get ( ) ; if ( ar == null ) { final TaskSubmissionResult result = new TaskSubmissionResult ( getID ( ) , AbstractTaskResult . ReturnCode . NO_INSTANCE ) ; result . setDescription ( "Assigned instance of vertex " + this . toString ( ) + " is null!" ) ; return result ; } final List < TaskDeploymentDescriptor > tasks = new SerializableArrayList < TaskDeploymentDescriptor > ( ) ; tasks . add ( constructDeploymentDescriptor ( ) ) ; try { final List < TaskSubmissionResult > results = ar . getInstance ( ) . submitTasks ( tasks ) ; return results . get ( 0 ) ; } catch ( IOException e ) { final TaskSubmissionResult result = new TaskSubmissionResult ( getID ( ) , AbstractTaskResult . ReturnCode . IPC_ERROR ) ; result . setDescription ( StringUtils . stringifyException ( e ) ) ; return result ; } } | Deploys and starts the task represented by this vertex on the assigned instance . |
40,914 | public TaskDeploymentDescriptor constructDeploymentDescriptor ( ) { final SerializableArrayList < GateDeploymentDescriptor > ogd = new SerializableArrayList < GateDeploymentDescriptor > ( this . outputGates . length ) ; for ( int i = 0 ; i < this . outputGates . length ; ++ i ) { final ExecutionGate eg = this . outputGates [ i ] ; final List < ChannelDeploymentDescriptor > cdd = new ArrayList < ChannelDeploymentDescriptor > ( eg . getNumberOfEdges ( ) ) ; final int numberOfOutputChannels = eg . getNumberOfEdges ( ) ; for ( int j = 0 ; j < numberOfOutputChannels ; ++ j ) { final ExecutionEdge ee = eg . getEdge ( j ) ; cdd . add ( new ChannelDeploymentDescriptor ( ee . getOutputChannelID ( ) , ee . getInputChannelID ( ) ) ) ; } ogd . add ( new GateDeploymentDescriptor ( eg . getGateID ( ) , eg . getChannelType ( ) , cdd ) ) ; } final SerializableArrayList < GateDeploymentDescriptor > igd = new SerializableArrayList < GateDeploymentDescriptor > ( this . inputGates . length ) ; for ( int i = 0 ; i < this . inputGates . length ; ++ i ) { final ExecutionGate eg = this . inputGates [ i ] ; final List < ChannelDeploymentDescriptor > cdd = new ArrayList < ChannelDeploymentDescriptor > ( eg . getNumberOfEdges ( ) ) ; final int numberOfInputChannels = eg . getNumberOfEdges ( ) ; for ( int j = 0 ; j < numberOfInputChannels ; ++ j ) { final ExecutionEdge ee = eg . getEdge ( j ) ; cdd . add ( new ChannelDeploymentDescriptor ( ee . getOutputChannelID ( ) , ee . getInputChannelID ( ) ) ) ; } igd . add ( new GateDeploymentDescriptor ( eg . getGateID ( ) , eg . getChannelType ( ) , cdd ) ) ; } final TaskDeploymentDescriptor tdd = new TaskDeploymentDescriptor ( this . executionGraph . getJobID ( ) , this . vertexID , this . groupVertex . getName ( ) , this . indexInVertexGroup , this . groupVertex . getCurrentNumberOfGroupMembers ( ) , this . executionGraph . getJobConfiguration ( ) , this . groupVertex . getConfiguration ( ) , this . groupVertex . getInvokableClass ( ) , ogd , igd ) ; return tdd ; } | Constructs a new task deployment descriptor for this vertex . |
40,915 | synchronized AllocatedSlice createSlice ( final InstanceType reqType , final JobID jobID ) { if ( remainingCapacity . getNumberOfComputeUnits ( ) >= reqType . getNumberOfComputeUnits ( ) && remainingCapacity . getNumberOfCores ( ) >= reqType . getNumberOfCores ( ) && remainingCapacity . getMemorySize ( ) >= reqType . getMemorySize ( ) && remainingCapacity . getDiskCapacity ( ) >= reqType . getDiskCapacity ( ) ) { remainingCapacity = InstanceTypeFactory . construct ( remainingCapacity . getIdentifier ( ) , remainingCapacity . getNumberOfComputeUnits ( ) - reqType . getNumberOfComputeUnits ( ) , remainingCapacity . getNumberOfCores ( ) - reqType . getNumberOfCores ( ) , remainingCapacity . getMemorySize ( ) - reqType . getMemorySize ( ) , remainingCapacity . getDiskCapacity ( ) - reqType . getDiskCapacity ( ) , remainingCapacity . getPricePerHour ( ) ) ; final long allocationTime = System . currentTimeMillis ( ) ; final AllocatedSlice slice = new AllocatedSlice ( this , reqType , jobID , allocationTime ) ; this . allocatedSlices . put ( slice . getAllocationID ( ) , slice ) ; return slice ; } return null ; } | Tries to create a new slice on this instance . |
40,916 | synchronized AllocatedSlice removeAllocatedSlice ( final AllocationID allocationID ) { final AllocatedSlice slice = this . allocatedSlices . remove ( allocationID ) ; if ( slice != null ) { this . remainingCapacity = InstanceTypeFactory . construct ( this . remainingCapacity . getIdentifier ( ) , this . remainingCapacity . getNumberOfComputeUnits ( ) + slice . getType ( ) . getNumberOfComputeUnits ( ) , this . remainingCapacity . getNumberOfCores ( ) + slice . getType ( ) . getNumberOfCores ( ) , this . remainingCapacity . getMemorySize ( ) + slice . getType ( ) . getMemorySize ( ) , this . remainingCapacity . getDiskCapacity ( ) + slice . getType ( ) . getDiskCapacity ( ) , this . remainingCapacity . getPricePerHour ( ) ) ; } return slice ; } | Removes the slice identified by the given allocation ID from this instance and frees up the allocated resources . |
40,917 | synchronized List < AllocatedSlice > removeAllAllocatedSlices ( ) { final List < AllocatedSlice > slices = new ArrayList < AllocatedSlice > ( this . allocatedSlices . values ( ) ) ; final Iterator < AllocatedSlice > it = slices . iterator ( ) ; while ( it . hasNext ( ) ) { removeAllocatedSlice ( it . next ( ) . getAllocationID ( ) ) ; } return slices ; } | Removes all allocated slices on this instance and frees up their allocated resources . |
40,918 | protected int [ ] getConstantKeySet ( int input ) { Operator < ? > contract = getPactContract ( ) ; if ( contract instanceof AbstractUdfOperator < ? , ? > ) { AbstractUdfOperator < ? , ? > abstractPact = ( AbstractUdfOperator < ? , ? > ) contract ; int [ ] keyColumns = abstractPact . getKeyColumns ( input ) ; if ( keyColumns != null ) { if ( keyColumns . length == 0 ) { return null ; } for ( int keyColumn : keyColumns ) { if ( ! isFieldConstant ( input , keyColumn ) ) { return null ; } } return keyColumns ; } } return null ; } | Returns the key columns for the specific input if all keys are preserved by this node . Null otherwise . |
40,919 | public void addVertex ( final AbstractJobInputVertex inputVertex ) { if ( ! inputVertices . containsKey ( inputVertex . getID ( ) ) ) { inputVertices . put ( inputVertex . getID ( ) , inputVertex ) ; } } | Adds a new input vertex to the job graph if it is not already included . |
40,920 | public void addVertex ( final AbstractJobOutputVertex outputVertex ) { if ( ! outputVertices . containsKey ( outputVertex . getID ( ) ) ) { outputVertices . put ( outputVertex . getID ( ) , outputVertex ) ; } } | Adds a new output vertex to the job graph if it is not already included . |
40,921 | public Iterator < AbstractJobInputVertex > getInputVertices ( ) { final Collection < AbstractJobInputVertex > coll = this . inputVertices . values ( ) ; return coll . iterator ( ) ; } | Returns an iterator to iterate all input vertices registered with the job graph . |
40,922 | public Iterator < AbstractJobOutputVertex > getOutputVertices ( ) { final Collection < AbstractJobOutputVertex > coll = this . outputVertices . values ( ) ; return coll . iterator ( ) ; } | Returns an iterator to iterate all output vertices registered with the job graph . |
40,923 | public Iterator < JobTaskVertex > getTaskVertices ( ) { final Collection < JobTaskVertex > coll = this . taskVertices . values ( ) ; return coll . iterator ( ) ; } | Returns an iterator to iterate all task vertices registered with the job graph . |
40,924 | public AbstractJobVertex [ ] getAllReachableJobVertices ( ) { final Vector < AbstractJobVertex > collector = new Vector < AbstractJobVertex > ( ) ; collectVertices ( null , collector ) ; return collector . toArray ( new AbstractJobVertex [ 0 ] ) ; } | Returns an array of all job vertices than can be reached when traversing the job graph from the input vertices . |
40,925 | public AbstractJobVertex [ ] getAllJobVertices ( ) { int i = 0 ; final AbstractJobVertex [ ] vertices = new AbstractJobVertex [ inputVertices . size ( ) + outputVertices . size ( ) + taskVertices . size ( ) ] ; final Iterator < AbstractJobInputVertex > iv = getInputVertices ( ) ; while ( iv . hasNext ( ) ) { vertices [ i ++ ] = iv . next ( ) ; } final Iterator < AbstractJobOutputVertex > ov = getOutputVertices ( ) ; while ( ov . hasNext ( ) ) { vertices [ i ++ ] = ov . next ( ) ; } final Iterator < JobTaskVertex > tv = getTaskVertices ( ) ; while ( tv . hasNext ( ) ) { vertices [ i ++ ] = tv . next ( ) ; } return vertices ; } | Returns an array of all job vertices that are registered with the job graph . The order in which the vertices appear in the list is not defined . |
40,926 | private void collectVertices ( final AbstractJobVertex jv , final List < AbstractJobVertex > collector ) { if ( jv == null ) { final Iterator < AbstractJobInputVertex > iter = getInputVertices ( ) ; while ( iter . hasNext ( ) ) { collectVertices ( iter . next ( ) , collector ) ; } } else { if ( ! collector . contains ( jv ) ) { collector . add ( jv ) ; } else { return ; } for ( int i = 0 ; i < jv . getNumberOfForwardConnections ( ) ; i ++ ) { collectVertices ( jv . getForwardConnection ( i ) . getConnectedVertex ( ) , collector ) ; } } } | Auxiliary method to collect all vertices which are reachable from the input vertices . |
40,927 | public AbstractJobVertex findVertexByID ( final JobVertexID id ) { if ( this . inputVertices . containsKey ( id ) ) { return this . inputVertices . get ( id ) ; } if ( this . outputVertices . containsKey ( id ) ) { return this . outputVertices . get ( id ) ; } if ( this . taskVertices . containsKey ( id ) ) { return this . taskVertices . get ( id ) ; } return null ; } | Searches for a vertex with a matching ID and returns it . |
40,928 | private boolean includedInJobGraph ( final JobVertexID id ) { if ( this . inputVertices . containsKey ( id ) ) { return true ; } if ( this . outputVertices . containsKey ( id ) ) { return true ; } if ( this . taskVertices . containsKey ( id ) ) { return true ; } return false ; } | Checks if the job vertex with the given ID is registered with the job graph . |
40,929 | public boolean isWeaklyConnected ( ) { final AbstractJobVertex [ ] reachable = getAllReachableJobVertices ( ) ; final AbstractJobVertex [ ] all = getAllJobVertices ( ) ; if ( reachable . length != all . length ) { return false ; } final HashMap < JobVertexID , AbstractJobVertex > tmp = new HashMap < JobVertexID , AbstractJobVertex > ( ) ; for ( int i = 0 ; i < reachable . length ; i ++ ) { tmp . put ( reachable [ i ] . getID ( ) , reachable [ i ] ) ; } for ( int i = 0 ; i < all . length ; i ++ ) { if ( ! tmp . containsKey ( all [ i ] . getID ( ) ) ) { return false ; } } for ( int i = 0 ; i < reachable . length ; i ++ ) { if ( ! includedInJobGraph ( reachable [ i ] . getID ( ) ) ) { return false ; } } return true ; } | Checks if the job graph is weakly connected . |
40,930 | public boolean isAcyclic ( ) { final AbstractJobVertex [ ] reachable = getAllReachableJobVertices ( ) ; final HashMap < AbstractJobVertex , Integer > indexMap = new HashMap < AbstractJobVertex , Integer > ( ) ; final HashMap < AbstractJobVertex , Integer > lowLinkMap = new HashMap < AbstractJobVertex , Integer > ( ) ; final Stack < AbstractJobVertex > stack = new Stack < AbstractJobVertex > ( ) ; final Integer index = Integer . valueOf ( 0 ) ; for ( int i = 0 ; i < reachable . length ; i ++ ) { if ( ! indexMap . containsKey ( reachable [ i ] ) ) { if ( ! tarjan ( reachable [ i ] , index , indexMap , lowLinkMap , stack ) ) { return false ; } } } return true ; } | Checks if the job graph is acyclic . |
40,931 | private boolean tarjan ( final AbstractJobVertex jv , Integer index , final HashMap < AbstractJobVertex , Integer > indexMap , final HashMap < AbstractJobVertex , Integer > lowLinkMap , final Stack < AbstractJobVertex > stack ) { indexMap . put ( jv , Integer . valueOf ( index ) ) ; lowLinkMap . put ( jv , Integer . valueOf ( index ) ) ; index = Integer . valueOf ( index . intValue ( ) + 1 ) ; stack . push ( jv ) ; for ( int i = 0 ; i < jv . getNumberOfForwardConnections ( ) ; i ++ ) { final AbstractJobVertex jv2 = jv . getForwardConnection ( i ) . getConnectedVertex ( ) ; if ( ! indexMap . containsKey ( jv2 ) || stack . contains ( jv2 ) ) { if ( ! indexMap . containsKey ( jv2 ) ) { if ( ! tarjan ( jv2 , index , indexMap , lowLinkMap , stack ) ) { return false ; } } if ( lowLinkMap . get ( jv ) > lowLinkMap . get ( jv2 ) ) { lowLinkMap . put ( jv , Integer . valueOf ( lowLinkMap . get ( jv2 ) ) ) ; } } } if ( lowLinkMap . get ( jv ) . equals ( indexMap . get ( jv ) ) ) { int count = 0 ; while ( stack . size ( ) > 0 ) { final AbstractJobVertex jv2 = stack . pop ( ) ; if ( jv == jv2 ) { break ; } count ++ ; } if ( count > 0 ) { return false ; } } return true ; } | Auxiliary method implementing Tarjan s algorithm for strongly - connected components to determine whether the job graph is acyclic . |
40,932 | private void readRequiredJarFiles ( final DataInput in ) throws IOException { final int numJars = in . readInt ( ) ; if ( numJars > 0 ) { for ( int i = 0 ; i < numJars ; i ++ ) { final Path p = new Path ( ) ; p . read ( in ) ; this . userJars . add ( p ) ; final long sizeOfJar = in . readLong ( ) ; LibraryCacheManager . addLibrary ( this . jobID , p , sizeOfJar , in ) ; } } LibraryCacheManager . register ( this . jobID , this . userJars . toArray ( new Path [ 0 ] ) ) ; } | Reads required JAR files from an input stream and adds them to the library cache manager . |
40,933 | private ExtendedManagementProtocol getJMConnection ( ) throws IOException { String jmHost = config . getString ( ConfigConstants . JOB_MANAGER_IPC_ADDRESS_KEY , null ) ; String jmPort = config . getString ( ConfigConstants . JOB_MANAGER_IPC_PORT_KEY , null ) ; return RPC . getProxy ( ExtendedManagementProtocol . class , new InetSocketAddress ( jmHost , Integer . parseInt ( jmPort ) ) , NetUtils . getSocketFactory ( ) ) ; } | Sets up a connection to the JobManager . |
40,934 | public String getPreviewPlan ( ) throws ProgramInvocationException { Thread . currentThread ( ) . setContextClassLoader ( this . getUserCodeClassLoader ( ) ) ; List < DataSinkNode > previewPlan ; if ( isUsingProgramEntryPoint ( ) ) { previewPlan = PactCompiler . createPreOptimizedPlan ( getPlan ( ) ) ; } else if ( isUsingInteractiveMode ( ) ) { PreviewPlanEnvironment env = new PreviewPlanEnvironment ( ) ; env . setAsContext ( ) ; try { invokeInteractiveModeForExecution ( ) ; } catch ( ProgramInvocationException e ) { throw e ; } catch ( Throwable t ) { if ( env . previewPlan != null ) { previewPlan = env . previewPlan ; } else { throw new ProgramInvocationException ( "The program caused an error: " , t ) ; } } if ( env . previewPlan != null ) { previewPlan = env . previewPlan ; } else { throw new ProgramInvocationException ( "The program plan could not be fetched. The program silently swallowed the control flow exceptions." ) ; } } else { throw new RuntimeException ( ) ; } PlanJSONDumpGenerator jsonGen = new PlanJSONDumpGenerator ( ) ; StringWriter string = new StringWriter ( 1024 ) ; PrintWriter pw = null ; try { pw = new PrintWriter ( string ) ; jsonGen . dumpPactPlanAsJSON ( previewPlan , pw ) ; } finally { pw . close ( ) ; } return string . toString ( ) ; } | Returns the analyzed plan without any optimizations . |
40,935 | public String getDescription ( ) throws ProgramInvocationException { if ( ProgramDescription . class . isAssignableFrom ( this . mainClass ) ) { ProgramDescription descr ; if ( this . program != null ) { descr = ( ProgramDescription ) this . program ; } else { try { descr = InstantiationUtil . instantiate ( this . mainClass . asSubclass ( ProgramDescription . class ) , ProgramDescription . class ) ; } catch ( Throwable t ) { return null ; } } try { return descr . getDescription ( ) ; } catch ( Throwable t ) { throw new ProgramInvocationException ( "Error while getting the program description" + ( t . getMessage ( ) == null ? "." : ": " + t . getMessage ( ) ) , t ) ; } } else { return null ; } } | Returns the description provided by the Program class . This may contain a description of the plan itself and its arguments . |
40,936 | void registerJob ( final ExecutionGraph eg ) { final Iterator < ExecutionGroupVertex > it = new ExecutionGroupVertexIterator ( eg , true , - 1 ) ; while ( it . hasNext ( ) ) { final ExecutionGroupVertex groupVertex = it . next ( ) ; final InputSplit [ ] inputSplits = groupVertex . getInputSplits ( ) ; if ( inputSplits == null ) { continue ; } if ( inputSplits . length == 0 ) { continue ; } for ( int i = 0 ; i < groupVertex . getCurrentNumberOfGroupMembers ( ) ; ++ i ) { final ExecutionVertex vertex = groupVertex . getGroupMember ( i ) ; if ( this . splitMap . put ( vertex . getID ( ) , new ArrayList < InputSplit > ( ) ) != null ) { LOG . error ( "InputSplitTracker must keep track of two vertices with ID " + vertex . getID ( ) ) ; } } } } | Registers a new job with the input split tracker . |
40,937 | void unregisterJob ( final ExecutionGraph eg ) { final Iterator < ExecutionVertex > it = new ExecutionGraphIterator ( eg , true ) ; while ( it . hasNext ( ) ) { this . splitMap . remove ( it . next ( ) . getID ( ) ) ; } } | Unregisters a job from the input split tracker . |
40,938 | void addInputSplitToLog ( final ExecutionVertex vertex , final int sequenceNumber , final InputSplit inputSplit ) { final List < InputSplit > inputSplitLog = this . splitMap . get ( vertex . getID ( ) ) ; if ( inputSplitLog == null ) { LOG . error ( "Cannot find input split log for vertex " + vertex + " (" + vertex . getID ( ) + ")" ) ; return ; } synchronized ( inputSplitLog ) { if ( inputSplitLog . size ( ) != sequenceNumber ) { LOG . error ( "Expected input split with sequence number " + inputSplitLog . size ( ) + " for vertex " + vertex + " (" + vertex . getID ( ) + ") but received " + sequenceNumber + ", skipping..." ) ; return ; } inputSplitLog . add ( inputSplit ) ; } } | Adds the given input split to the vertex s log and stores it under the specified sequence number . |
40,939 | private TaskOperationProtocol getTaskManagerProxy ( ) throws IOException { if ( this . taskManager == null ) { this . taskManager = RPC . getProxy ( TaskOperationProtocol . class , new InetSocketAddress ( getInstanceConnectionInfo ( ) . address ( ) , getInstanceConnectionInfo ( ) . ipcPort ( ) ) , NetUtils . getSocketFactory ( ) ) ; } return this . taskManager ; } | Creates or returns the RPC stub object for the instance s task manager . |
40,940 | public synchronized void checkLibraryAvailability ( final JobID jobID ) throws IOException { String [ ] requiredLibraries = LibraryCacheManager . getRequiredJarFiles ( jobID ) ; if ( requiredLibraries == null ) { throw new IOException ( "No entry of required libraries for job " + jobID ) ; } LibraryCacheProfileRequest request = new LibraryCacheProfileRequest ( ) ; request . setRequiredLibraries ( requiredLibraries ) ; LibraryCacheProfileResponse response = null ; response = getTaskManagerProxy ( ) . getLibraryCacheProfile ( request ) ; for ( int k = 0 ; k < requiredLibraries . length ; k ++ ) { if ( ! response . isCached ( k ) ) { LibraryCacheUpdate update = new LibraryCacheUpdate ( requiredLibraries [ k ] ) ; getTaskManagerProxy ( ) . updateLibraryCache ( update ) ; } } } | Checks if all the libraries required to run the job with the given job ID are available on this instance . Any libary that is missing is transferred to the instance as a result of this call . |
40,941 | public void mapResultToRecord ( Record record , HBaseKey key , HBaseResult result ) { record . setField ( 0 , key ) ; record . setField ( 1 , result ) ; } | Maps the current HBase Result into a Record . This implementation simply stores the HBaseKey at position 0 and the HBase Result object at position 1 . |
40,942 | public static void loadLibraryFromFile ( final String directory , final String filename ) throws IOException { final String libraryPath = directory + File . separator + filename ; synchronized ( loadedLibrarySet ) { final File outputFile = new File ( directory , filename ) ; if ( ! outputFile . exists ( ) ) { final ClassLoader cl = ClassLoader . getSystemClassLoader ( ) ; final InputStream in = cl . getResourceAsStream ( JAR_PREFIX + filename ) ; if ( in == null ) { throw new IOException ( "Unable to extract native library " + filename + " to " + directory ) ; } final OutputStream out = new FileOutputStream ( outputFile ) ; copy ( in , out ) ; } System . load ( libraryPath ) ; loadedLibrarySet . add ( filename ) ; } } | Loads a native library from a file . |
40,943 | void addRequest ( final InstanceType instanceType , final int numberOfInstances ) { Integer numberOfRemainingInstances = this . pendingRequests . get ( instanceType ) ; if ( numberOfRemainingInstances == null ) { numberOfRemainingInstances = Integer . valueOf ( numberOfInstances ) ; } else { numberOfRemainingInstances = Integer . valueOf ( numberOfRemainingInstances . intValue ( ) + numberOfInstances ) ; } this . pendingRequests . put ( instanceType , numberOfRemainingInstances ) ; } | Adds the a pending request for the given number of instances of the given type to this map . |
40,944 | void decreaseNumberOfPendingInstances ( final InstanceType instanceType ) { Integer numberOfRemainingInstances = this . pendingRequests . get ( instanceType ) ; if ( numberOfRemainingInstances == null ) { return ; } numberOfRemainingInstances = Integer . valueOf ( numberOfRemainingInstances . intValue ( ) - 1 ) ; if ( numberOfRemainingInstances . intValue ( ) == 0 ) { this . pendingRequests . remove ( instanceType ) ; } else { this . pendingRequests . put ( instanceType , numberOfRemainingInstances ) ; } } | Decreases the number of remaining instances to request of the given type . |
40,945 | public ManagementStage getStage ( final int index ) { if ( index >= 0 && index < this . stages . size ( ) ) { return this . stages . get ( index ) ; } return null ; } | Returns the management stage with the given index . |
40,946 | public int getNumberOfInputGroupVertices ( final int stage ) { if ( stage < 0 || stage >= this . stages . size ( ) ) { return 0 ; } return this . stages . get ( stage ) . getNumberOfInputGroupVertices ( ) ; } | Returns the number of input group vertices in the management stage with the given index . |
40,947 | public ManagementGroupVertex getInputGroupVertex ( final int stage , final int index ) { if ( stage >= this . stages . size ( ) ) { return null ; } return this . stages . get ( stage ) . getInputGroupVertex ( index ) ; } | Returns the input group vertex at the given index in the given stage . |
40,948 | public ManagementGroupVertex getOutputGroupVertex ( final int stage , final int index ) { if ( stage >= this . stages . size ( ) ) { return null ; } return this . stages . get ( stage ) . getOutputGroupVertex ( index ) ; } | Returns the output group vertex at the given index in the given stage . |
40,949 | public ManagementVertex getInputVertex ( final int stage , final int index ) { if ( stage >= this . stages . size ( ) ) { return null ; } return this . stages . get ( stage ) . getInputManagementVertex ( index ) ; } | Returns the input vertex with the specified index for the given stage . |
40,950 | public List < ManagementGroupVertex > getGroupVerticesInTopologicalOrder ( ) { final List < ManagementGroupVertex > topologicalSort = new ArrayList < ManagementGroupVertex > ( ) ; final Deque < ManagementGroupVertex > noIncomingEdges = new ArrayDeque < ManagementGroupVertex > ( ) ; final Map < ManagementGroupVertex , Integer > indegrees = new HashMap < ManagementGroupVertex , Integer > ( ) ; final Iterator < ManagementGroupVertex > it = new ManagementGroupVertexIterator ( this , true , - 1 ) ; while ( it . hasNext ( ) ) { final ManagementGroupVertex groupVertex = it . next ( ) ; indegrees . put ( groupVertex , Integer . valueOf ( groupVertex . getNumberOfBackwardEdges ( ) ) ) ; if ( groupVertex . getNumberOfBackwardEdges ( ) == 0 ) { noIncomingEdges . add ( groupVertex ) ; } } while ( ! noIncomingEdges . isEmpty ( ) ) { final ManagementGroupVertex groupVertex = noIncomingEdges . removeFirst ( ) ; topologicalSort . add ( groupVertex ) ; for ( int i = 0 ; i < groupVertex . getNumberOfForwardEdges ( ) ; i ++ ) { final ManagementGroupVertex targetVertex = groupVertex . getForwardEdge ( i ) . getTarget ( ) ; Integer indegree = indegrees . get ( targetVertex ) ; indegree = Integer . valueOf ( indegree . intValue ( ) - 1 ) ; indegrees . put ( targetVertex , indegree ) ; if ( indegree . intValue ( ) == 0 ) { noIncomingEdges . add ( targetVertex ) ; } } } return topologicalSort ; } | Returns a list of group vertices sorted in topological order . |
40,951 | public List < ManagementGroupVertex > getGroupVerticesInReverseTopologicalOrder ( ) { final List < ManagementGroupVertex > reverseTopologicalSort = new ArrayList < ManagementGroupVertex > ( ) ; final Deque < ManagementGroupVertex > noOutgoingEdges = new ArrayDeque < ManagementGroupVertex > ( ) ; final Map < ManagementGroupVertex , Integer > outdegrees = new HashMap < ManagementGroupVertex , Integer > ( ) ; final Iterator < ManagementGroupVertex > it = new ManagementGroupVertexIterator ( this , false , - 1 ) ; while ( it . hasNext ( ) ) { final ManagementGroupVertex groupVertex = it . next ( ) ; outdegrees . put ( groupVertex , Integer . valueOf ( groupVertex . getNumberOfForwardEdges ( ) ) ) ; if ( groupVertex . getNumberOfForwardEdges ( ) == 0 ) { noOutgoingEdges . add ( groupVertex ) ; } } while ( ! noOutgoingEdges . isEmpty ( ) ) { final ManagementGroupVertex groupVertex = noOutgoingEdges . removeFirst ( ) ; reverseTopologicalSort . add ( groupVertex ) ; for ( int i = 0 ; i < groupVertex . getNumberOfBackwardEdges ( ) ; i ++ ) { final ManagementGroupVertex sourceVertex = groupVertex . getBackwardEdge ( i ) . getSource ( ) ; Integer outdegree = outdegrees . get ( sourceVertex ) ; outdegree = Integer . valueOf ( outdegree . intValue ( ) - 1 ) ; outdegrees . put ( sourceVertex , outdegree ) ; if ( outdegree . intValue ( ) == 0 ) { noOutgoingEdges . add ( sourceVertex ) ; } } } return reverseTopologicalSort ; } | Returns a list of group vertices sorted in reverse topological order . |
40,952 | public static boolean validate ( Fragment fragment , IValidationCallback callback ) { return validate ( fragment . getActivity ( ) , fragment , callback ) ; } | Perform validation over the views of given fragment |
40,953 | @ SuppressWarnings ( "unchecked" ) private static ValidationFail performFieldValidations ( Context context , FieldInfo fieldInfo , View view ) { if ( fieldInfo . condition != null && fieldInfo . condition . validationAnnotation ( ) . equals ( Condition . class ) ) { boolean evaluation = evaluateCondition ( view , fieldInfo . condition ) ; if ( ! evaluation ) { return null ; } } for ( ValidationInfo valInfo : fieldInfo . validationInfoList ) { final Annotation annotation = valInfo . annotation ; if ( fieldInfo . condition != null && fieldInfo . condition . validationAnnotation ( ) . equals ( annotation . annotationType ( ) ) ) { boolean evaluation = evaluateCondition ( view , fieldInfo . condition ) ; if ( ! evaluation ) { continue ; } } final IFieldAdapter adapter = FieldAdapterFactory . getAdapterForField ( view , annotation ) ; if ( adapter == null ) { throw new NoFieldAdapterException ( view , annotation ) ; } final Object value = adapter . getFieldValue ( annotation , view ) ; final boolean isValid = valInfo . validator . validate ( annotation , value ) ; if ( ! isValid ) { final String message = valInfo . validator . getMessage ( context , annotation , value ) ; final int order = valInfo . validator . getOrder ( annotation ) ; return new ValidationFail ( view , message , order ) ; } } return null ; } | perform all validations on single field |
40,954 | static Map < View , FormValidator . FieldInfo > getFieldsForTarget ( Object target ) { Map < View , FormValidator . FieldInfo > infoMap = sCachedFieldsByTarget . get ( target ) ; if ( infoMap != null ) { for ( View view : infoMap . keySet ( ) ) { if ( view . getWindowToken ( ) == null ) { infoMap = null ; break ; } } } if ( infoMap == null ) { infoMap = findFieldsToValidate ( target ) ; sCachedFieldsByTarget . put ( target , infoMap ) ; } return infoMap ; } | get map of field information on view for given target |
40,955 | @ SuppressWarnings ( "TryWithIdenticalCatches" ) private static Map < View , FormValidator . FieldInfo > findFieldsToValidate ( Object target ) { final Field [ ] fields = target . getClass ( ) . getDeclaredFields ( ) ; if ( fields == null || fields . length == 0 ) { return Collections . emptyMap ( ) ; } final WeakHashMap < View , FormValidator . FieldInfo > infoMap = new WeakHashMap < > ( fields . length ) ; for ( Field field : fields ) { final List < FormValidator . ValidationInfo > infos = new ArrayList < > ( ) ; final Annotation [ ] annotations = field . getDeclaredAnnotations ( ) ; if ( annotations . length > 0 ) { if ( ! View . class . isAssignableFrom ( field . getType ( ) ) ) { continue ; } final View view ; try { field . setAccessible ( true ) ; view = ( View ) field . get ( target ) ; } catch ( IllegalAccessException e ) { throw new FormsValidationException ( e ) ; } if ( view == null ) { continue ; } for ( Annotation annotation : annotations ) { final IValidator validator ; try { validator = ValidatorFactory . getValidator ( annotation ) ; } catch ( IllegalAccessException e ) { throw new FormsValidationException ( e ) ; } catch ( InstantiationException e ) { throw new FormsValidationException ( e ) ; } if ( validator != null ) { FormValidator . ValidationInfo info = new FormValidator . ValidationInfo ( annotation , validator ) ; infos . add ( info ) ; } } final Condition conditionAnnotation = field . getAnnotation ( Condition . class ) ; if ( infos . size ( ) > 0 ) { Collections . sort ( infos , new Comparator < FormValidator . ValidationInfo > ( ) { public int compare ( FormValidator . ValidationInfo lhs , FormValidator . ValidationInfo rhs ) { return lhs . order < rhs . order ? - 1 : ( lhs . order == rhs . order ? 0 : 1 ) ; } } ) ; } final FormValidator . FieldInfo fieldInfo = new FormValidator . FieldInfo ( conditionAnnotation , infos ) ; infoMap . put ( view , fieldInfo ) ; } } return infoMap ; } | find fields on target to validate and prepare for their validation |
40,956 | public static < T extends Enum < T > > T getEnum ( Class < T > enumClass , AbstractConfig config , String key ) { Preconditions . checkNotNull ( enumClass , "enumClass cannot be null" ) ; Preconditions . checkState ( enumClass . isEnum ( ) , "enumClass must be an enum." ) ; String textValue = config . getString ( key ) ; return Enum . valueOf ( enumClass , textValue ) ; } | Method is used to return an enum value from a given string . |
40,957 | public static String enumValues ( Class < ? > enumClass ) { Preconditions . checkNotNull ( enumClass , "enumClass cannot be null" ) ; Preconditions . checkState ( enumClass . isEnum ( ) , "enumClass must be an enum." ) ; return Joiner . on ( ", " ) . join ( enumClass . getEnumConstants ( ) ) ; } | Method is used to return the values for an enum . |
40,958 | public static File getAbsoluteFile ( AbstractConfig config , String key ) { Preconditions . checkNotNull ( config , "config cannot be null" ) ; String path = config . getString ( key ) ; File file = new File ( path ) ; if ( ! file . isAbsolute ( ) ) { throw new ConfigException ( key , path , "Must be an absolute path." ) ; } return new File ( path ) ; } | Method is used to return a File checking to ensure that it is an absolute path . |
40,959 | public static List < HostAndPort > hostAndPorts ( AbstractConfig config , String key , Integer defaultPort ) { final List < String > inputs = config . getList ( key ) ; List < HostAndPort > result = new ArrayList < > ( ) ; for ( final String input : inputs ) { final HostAndPort hostAndPort = hostAndPort ( input , defaultPort ) ; result . add ( hostAndPort ) ; } return ImmutableList . copyOf ( result ) ; } | Method is used to parse a list ConfigDef item to a list of HostAndPort |
40,960 | public static List < HostAndPort > hostAndPorts ( AbstractConfig config , String key ) { return hostAndPorts ( config , key , null ) ; } | Method is used to parse hosts and ports |
40,961 | public static URL url ( AbstractConfig config , String key ) { final String value = config . getString ( key ) ; return url ( key , value ) ; } | Method is used to retrieve a URL from a configuration key . |
40,962 | public static URI uri ( AbstractConfig config , String key ) { final String value = config . getString ( key ) ; return uri ( key , value ) ; } | Method is used to retrieve a URI from a configuration key . |
40,963 | public static Set < String > getSet ( AbstractConfig config , String key ) { List < String > value = config . getList ( key ) ; return ImmutableSet . copyOf ( value ) ; } | Method is used to retrieve a list and convert it to an immutable set . |
40,964 | public static Pattern pattern ( AbstractConfig config , String key ) { String pattern = config . getString ( key ) ; try { return Pattern . compile ( pattern ) ; } catch ( PatternSyntaxException e ) { throw new ConfigException ( key , pattern , String . format ( "Could not compile regex '%s'." , pattern ) ) ; } } | Method is used to create a pattern based on the config element . |
40,965 | public static char [ ] passwordCharArray ( AbstractConfig config , String key ) { final Password password = config . getPassword ( key ) ; return password . value ( ) . toCharArray ( ) ; } | Method is used to return an array of characters representing the password stored in the config . |
40,966 | public static KeyStore keyStore ( AbstractConfig config , String key ) { final String keyStoreType = config . getString ( key ) ; try { return KeyStore . getInstance ( keyStoreType ) ; } catch ( KeyStoreException e ) { ConfigException exception = new ConfigException ( key , keyStoreType , "Invalid KeyStore type." ) ; exception . initCause ( e ) ; throw exception ; } } | Method will create a KeyStore based on the KeyStore type specified in the config . |
40,967 | public static KeyManagerFactory keyManagerFactory ( AbstractConfig config , String key ) { final String keyManagerFactoryType = config . getString ( key ) ; try { return KeyManagerFactory . getInstance ( keyManagerFactoryType ) ; } catch ( NoSuchAlgorithmException e ) { ConfigException exception = new ConfigException ( key , keyManagerFactoryType , "Unknown Algorithm." ) ; exception . initCause ( e ) ; throw exception ; } } | Method will create a KeyManagerFactory based on the Algorithm type specified in the config . |
40,968 | public static TrustManagerFactory trustManagerFactory ( AbstractConfig config , String key ) { final String trustManagerFactoryType = config . getString ( key ) ; try { return TrustManagerFactory . getInstance ( trustManagerFactoryType ) ; } catch ( NoSuchAlgorithmException e ) { ConfigException exception = new ConfigException ( key , trustManagerFactoryType , "Unknown Algorithm." ) ; exception . initCause ( e ) ; throw exception ; } } | Method will create a TrustManagerFactory based on the Algorithm type specified in the config . |
40,969 | public static SSLContext sslContext ( AbstractConfig config , String key ) { final String trustManagerFactoryType = config . getString ( key ) ; try { return SSLContext . getInstance ( trustManagerFactoryType ) ; } catch ( NoSuchAlgorithmException e ) { ConfigException exception = new ConfigException ( key , trustManagerFactoryType , "Unknown Algorithm." ) ; exception . initCause ( e ) ; throw exception ; } } | Method will create a SSLContext based on the Algorithm type specified in the config . |
40,970 | protected String getRequestUrl ( String key ) throws Exception { String result = "" ; try { result = this . methods . get ( key ) [ 0 ] ; } catch ( Exception ex ) { throw new Exception ( "Unknown method key: " + key ) ; } return result ; } | Gets the URL of REST Mango Pay API . |
40,971 | protected < T extends Dto > List < T > getList ( Class < T [ ] > classOfT , Class < T > classOfTItem , String methodKey , Pagination pagination , String entityId , String secondEntityId , Map < String , String > filter , Sorting sorting ) throws Exception { String urlMethod = "" ; if ( entityId != null && entityId . length ( ) > 0 && secondEntityId != null && secondEntityId . length ( ) > 0 ) urlMethod = String . format ( this . getRequestUrl ( methodKey ) , entityId , secondEntityId ) ; else if ( entityId != null && entityId . length ( ) > 0 ) urlMethod = String . format ( this . getRequestUrl ( methodKey ) , entityId ) ; else urlMethod = this . getRequestUrl ( methodKey ) ; if ( pagination == null ) { pagination = new Pagination ( ) ; } Map < String , String > additionalUrlParams = new HashMap < > ( ) ; if ( filter != null ) { additionalUrlParams . putAll ( filter ) ; } if ( sorting != null ) { additionalUrlParams . putAll ( sorting . getSortParameter ( ) ) ; } RestTool rest = new RestTool ( this . root , true ) ; return rest . requestList ( classOfT , classOfTItem , urlMethod , this . getRequestType ( methodKey ) , null , pagination , additionalUrlParams ) ; } | Gets the array of Dto instances from API . |
40,972 | public boolean drain ( List < SourceRecord > records , int timeout ) throws InterruptedException { Preconditions . checkNotNull ( records , "records cannot be null" ) ; Preconditions . checkArgument ( timeout >= 0 , "timeout should be greater than or equal to 0." ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "determining size for this run. batchSize={}, records.size()={}" , this . batchSize , records . size ( ) ) ; } int count = Math . min ( this . batchSize , this . size ( ) ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Draining {} record(s)." , count ) ; } for ( int i = 0 ; i < count ; i ++ ) { SourceRecord record = this . poll ( ) ; if ( null != record ) { records . add ( record ) ; } else { if ( log . isDebugEnabled ( ) ) { log . debug ( "Poll returned null. exiting" ) ; break ; } } } if ( records . isEmpty ( ) && timeout > 0 ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "Found no records, sleeping {} ms." , timeout ) ; } Thread . sleep ( timeout ) ; } return ! records . isEmpty ( ) ; } | Method is used to drain the records from the deque in order and add them to the supplied list . |
40,973 | public String getHttpHeaderBasicKey ( ) throws Exception { if ( root . getConfig ( ) . getClientId ( ) == null || root . getConfig ( ) . getClientId ( ) . length ( ) == 0 ) throw new Exception ( "MangoPay.config.ClientId is not set." ) ; if ( root . getConfig ( ) . getClientPassword ( ) == null || root . getConfig ( ) . getClientPassword ( ) . length ( ) == 0 ) throw new Exception ( "MangoPay.config.ClientPassword is not set." ) ; String signature = root . getConfig ( ) . getClientId ( ) + ':' + root . getConfig ( ) . getClientPassword ( ) ; return Base64Encoder . encode ( signature ) ; } | Gets basic key for HTTP header . |
40,974 | private Map < String , String > getHttpHeaderBasic ( ) throws Exception { return new HashMap < String , String > ( ) { { put ( "Authorization" , "Basic " + getHttpHeaderBasicKey ( ) ) ; } } ; } | gets HTTP header value with authorization string for basic authentication |
40,975 | private Map < String , String > getHttpHeaderStrong ( ) throws Exception { final OAuthToken token = root . getOAuthTokenManager ( ) . getToken ( ) ; if ( token == null || token . getAccessToken ( ) . length ( ) == 0 || token . getTokenType ( ) . length ( ) == 0 ) throw new Exception ( "OAuth token is not created (or is invalid) for strong authentication" ) ; return new HashMap < String , String > ( ) { { put ( "Authorization" , token . getTokenType ( ) + " " + token . getAccessToken ( ) ) ; } } ; } | gets HTTP header value with authorization string for strong authentication |
40,976 | public void addField ( String fieldName , SortDirection sortDirection ) { if ( sortFields == null ) sortFields = new HashMap < > ( ) ; sortFields . put ( fieldName , sortDirection ) ; } | Adds field to sort by . |
40,977 | public Map < String , String > getSortParameter ( ) { return new HashMap < String , String > ( ) { { put ( sortUrlParameterName , getFields ( ) ) ; } } ; } | Gets sort parameters . |
40,978 | public String getFullUrl ( String restUrl ) { String result = "" ; try { result = ( new URL ( root . getConfig ( ) . getBaseUrl ( ) ) ) . getProtocol ( ) + "://" + this . getHost ( ) + restUrl ; } catch ( Exception ex ) { } return result ; } | Gets complete url . |
40,979 | public Boolean isValid ( ) { return addressLine1 != null || addressLine2 != null || city != null || region != null || postalCode != null || ( country != null && country != CountryIso . NotSpecified ) ; } | Helper method used internally . |
40,980 | private String readMangopayVersion ( ) { try { Properties prop = new Properties ( ) ; InputStream input = getClass ( ) . getResourceAsStream ( "mangopay.properties" ) ; prop . load ( input ) ; return prop . getProperty ( "version" ) ; } catch ( IOException ex ) { Logger . getLogger ( Configuration . class . getName ( ) ) . log ( Level . SEVERE , null , ex ) ; } return "unknown" ; } | Read Mangopay version from mangopay properties |
40,981 | public void ensureValid ( String setting , Object value ) { if ( null == value || ! ( value instanceof Integer ) ) { throw new ConfigException ( setting , "Must be an integer." ) ; } final Integer port = ( Integer ) value ; if ( ! ( port >= this . start && port <= this . end ) ) { throw new ConfigException ( setting , String . format ( "(%s) must be between %s and %s." , port , this . start , this . end ) ) ; } } | Method is used to validate that the supplied port is within the valid range . |
40,982 | public static ConfigDef . Recommender visibleIf ( String configKey , Object value ) { return new VisibleIfRecommender ( configKey , value , ValidValuesCallback . EMPTY ) ; } | Method is used to return a recommender that will mark a ConfigItem as visible if the configKey is set to the specified value . |
40,983 | public void addRequestHttpHeader ( final String key , final String value ) { addRequestHttpHeader ( new HashMap < String , String > ( ) { { put ( key , value ) ; } } ) ; } | Adds HTTP header into the request . |
40,984 | private Map < String , String > getHttpHeaders ( String restUrl ) throws Exception { if ( this . requestHttpHeaders != null ) return this . requestHttpHeaders ; Map < String , String > httpHeaders = new HashMap < > ( ) ; httpHeaders . put ( "Content-Type" , "application/json" ) ; if ( this . authRequired ) { AuthenticationHelper authHlp = new AuthenticationHelper ( root ) ; httpHeaders . putAll ( authHlp . getHttpHeaderKey ( ) ) ; } return httpHeaders ; } | Gets HTTP header to use in request . |
40,985 | private void checkResponseCode ( String message ) throws ResponseException { if ( this . responseCode != 200 && this . responseCode != 204 ) { HashMap < Integer , String > responseCodes = new HashMap < Integer , String > ( ) { { put ( 206 , "PartialContent" ) ; put ( 400 , "Bad request" ) ; put ( 401 , "Unauthorized" ) ; put ( 403 , "Prohibition to use the method" ) ; put ( 404 , "Not found" ) ; put ( 405 , "Method not allowed" ) ; put ( 413 , "Request entity too large" ) ; put ( 422 , "Unprocessable entity" ) ; put ( 500 , "Internal server error" ) ; put ( 501 , "Not implemented" ) ; } } ; ResponseException responseException = new ResponseException ( message ) ; responseException . setResponseHttpCode ( this . responseCode ) ; if ( responseCodes . containsKey ( this . responseCode ) ) { responseException . setResponseHttpDescription ( responseCodes . get ( this . responseCode ) ) ; } else { responseException . setResponseHttpDescription ( "Unknown response error" ) ; } if ( message != null ) { JsonObject error = new JsonParser ( ) . parse ( message ) . getAsJsonObject ( ) ; for ( Entry < String , JsonElement > entry : error . entrySet ( ) ) { switch ( entry . getKey ( ) . toLowerCase ( ) ) { case "message" : responseException . setApiMessage ( entry . getValue ( ) . getAsString ( ) ) ; break ; case "type" : responseException . setType ( entry . getValue ( ) . getAsString ( ) ) ; break ; case "id" : responseException . setId ( entry . getValue ( ) . getAsString ( ) ) ; break ; case "date" : responseException . setDate ( ( int ) entry . getValue ( ) . getAsDouble ( ) ) ; break ; case "errors" : if ( entry . getValue ( ) == null ) break ; if ( entry . getValue ( ) . isJsonNull ( ) ) break ; for ( Entry < String , JsonElement > errorEntry : entry . getValue ( ) . getAsJsonObject ( ) . entrySet ( ) ) { if ( ! responseException . getErrors ( ) . containsKey ( errorEntry . getKey ( ) ) ) responseException . getErrors ( ) . put ( errorEntry . getKey ( ) , errorEntry . getValue ( ) . getAsString ( ) ) ; else { String description = responseException . getErrors ( ) . get ( errorEntry . getKey ( ) ) ; description = " | " + errorEntry . getValue ( ) . getAsString ( ) ; responseException . getErrors ( ) . put ( errorEntry . getKey ( ) , description ) ; } } break ; } } } throw responseException ; } } | Checks the HTTP response code and if it s neither 200 nor 204 throws a ResponseException . |
40,986 | public final void registerTypeParser ( Schema schema , TypeParser typeParser ) { Preconditions . checkNotNull ( schema , "schema cannot be null." ) ; Preconditions . checkNotNull ( typeParser , "typeParser cannot be null." ) ; this . typeParsers . put ( new ParserKey ( schema ) , typeParser ) ; } | Method is used to register a TypeParser for a given schema . If the schema is already registered the new TypeParser will replace the existing one . |
40,987 | public Object parseString ( Schema schema , String input ) { checkSchemaAndInput ( schema , input ) ; if ( null == input ) { return null ; } TypeParser parser = findParser ( schema ) ; try { Object result = parser . parseString ( input , schema ) ; return result ; } catch ( Exception ex ) { String message = String . format ( "Could not parse '%s' to '%s'" , input , parser . expectedClass ( ) . getSimpleName ( ) ) ; throw new DataException ( message , ex ) ; } } | Method is used to parse String data to the proper Java types . |
40,988 | public static Validator blankOr ( Validator validator ) { Preconditions . checkNotNull ( validator , "validator cannot be null." ) ; return BlankOrValidator . of ( validator ) ; } | Method will return a validator that will accept a blank string . Any other value will be passed on to the supplied validator . |
40,989 | public static Validator validCharset ( String ... charsets ) { if ( null == charsets || charsets . length == 0 ) { return new ValidCharset ( ) ; } else { return new ValidCharset ( charsets ) ; } } | Method will return a validator that will ensure that a String or List contains a charset that is supported by the system . |
40,990 | public static Validator validEnum ( Class < ? extends Enum > enumClass , Enum ... excludes ) { String [ ] ex = new String [ excludes . length ] ; for ( int i = 0 ; i < ex . length ; i ++ ) { ex [ i ] = excludes [ i ] . toString ( ) ; } return ValidEnum . of ( enumClass , ex ) ; } | Method is used to create a new INSTANCE of the enum validator . |
40,991 | public static Validator validHostAndPort ( Integer defaultPort , boolean requireBracketsForIPv6 , boolean portRequired ) { return ValidHostAndPort . of ( defaultPort , requireBracketsForIPv6 , portRequired ) ; } | Validator to ensure that a configuration setting is a hostname and port . |
40,992 | public static Validator validKeyStoreType ( ) { return ( s , o ) -> { if ( ! ( o instanceof String ) ) { throw new ConfigException ( s , o , "Must be a string." ) ; } String keyStoreType = o . toString ( ) ; try { KeyStore . getInstance ( keyStoreType ) ; } catch ( KeyStoreException e ) { ConfigException exception = new ConfigException ( s , o , "Invalid KeyStore type" ) ; exception . initCause ( e ) ; throw exception ; } } ; } | Validator is used to ensure that the KeyStore type specified is valid . |
40,993 | public static Validator validKeyManagerFactory ( ) { return ( s , o ) -> { if ( ! ( o instanceof String ) ) { throw new ConfigException ( s , o , "Must be a string." ) ; } String keyStoreType = o . toString ( ) ; try { KeyManagerFactory . getInstance ( keyStoreType ) ; } catch ( NoSuchAlgorithmException e ) { ConfigException exception = new ConfigException ( s , o , "Invalid Algorithm" ) ; exception . initCause ( e ) ; throw exception ; } } ; } | Validator is used to ensure that the KeyManagerFactory Algorithm specified is valid . |
40,994 | public static List < Map < String , String > > single ( Map < String , String > settings ) { Preconditions . checkNotNull ( settings , "settings cannot be null." ) ; return ImmutableList . of ( settings ) ; } | Method will create a single from the supplied settings . |
40,995 | public static List < Map < String , String > > multiple ( Map < String , String > settings , final int taskCount ) { Preconditions . checkNotNull ( settings , "settings cannot be null." ) ; Preconditions . checkState ( taskCount > 0 , "taskCount must be greater than 0." ) ; final List < Map < String , String > > result = new ArrayList < > ( taskCount ) ; for ( int i = 0 ; i < taskCount ; i ++ ) { result . add ( settings ) ; } return ImmutableList . copyOf ( result ) ; } | Method is used to generate a list of taskConfigs based on the supplied settings . |
40,996 | private DataFrame createDataFrame ( ByteBuf buf ) { if ( buf . readableBytes ( ) > 3 ) { byte messageType = buf . getByte ( buf . readerIndex ( ) + 3 ) ; switch ( messageType ) { case Version . ID : return new Version ( buf ) ; case MemoryGetId . ID : return new MemoryGetId ( buf ) ; case InitData . ID : return new InitData ( buf ) ; case NodeProtocolInfo . ID : return new NodeProtocolInfo ( buf ) ; case SendData . ID : return new SendData ( buf ) ; case ApplicationCommand . ID : return new ApplicationCommand ( buf ) ; case ApplicationUpdate . ID : return new ApplicationUpdate ( buf ) ; case RequestNodeInfo . ID : return new RequestNodeInfo ( buf ) ; case GetRoutingInfo . ID : return new GetRoutingInfo ( buf ) ; case GetSUCNodeId . ID : return new GetSUCNodeId ( buf ) ; case AddNodeToNetwork . ID : return new AddNodeToNetwork ( buf ) ; case RemoveNodeFromNetwork . ID : return new RemoveNodeFromNetwork ( buf ) ; case SetDefault . ID : return new SetDefault ( buf ) ; } } return null ; } | Creates a Z - Wave DataFrame from a ByteBuf . |
40,997 | public void onApplicationCommand ( ZWaveControllerContext context , ApplicationCommand ac ) { byte commandClassId = ac . getCommandClassId ( ) ; CommandClass cc = getCommandClass ( commandClassId ) ; if ( cc != null ) { if ( cc instanceof BasicCommandClass ) { cc = performBasicCommandClassMapping ( ( BasicCommandClass ) cc ) ; } cc . onApplicationCommand ( new WrapperedNodeContext ( context , this ) , ac . getCommandClassBytes ( ) , 0 ) ; if ( cc instanceof VersionCommandClass && nodeState == ZWaveNodeState . RetrieveVersionSent ) { pendingVersionResponses -- ; if ( pendingVersionResponses <= 0 ) { setState ( context , ZWaveNodeState . RetrieveStatePending ) ; } } else if ( nodeState == ZWaveNodeState . RetrieveStateSent ) { pendingStatusResponses -- ; if ( pendingStatusResponses <= 0 ) { setState ( context , ZWaveNodeState . Started ) ; } } } else { logger . error ( "Received message for unsupported command class ID: {}" , ByteUtil . createString ( commandClassId ) ) ; } } | Called when an application command message is received for this specific node . |
40,998 | public void onApplicationUpdate ( ZWaveControllerContext context , ApplicationUpdate update ) { switch ( nodeState ) { case NodeInfo : if ( update . didInfoRequestFail ( ) ) { if ( stateRetries < 1 ) { logger . trace ( "Application update failed for node {}; will retry" , getNodeId ( ) ) ; sendDataFrame ( context , new RequestNodeInfo ( getNodeId ( ) ) ) ; stateRetries ++ ; } else { if ( isListeningNode ( ) ) { logger . trace ( "Node {} provided no node info after {} retries; should be listening so flagging as unavailable and started" , getNodeId ( ) , stateRetries ) ; available = false ; setState ( context , ZWaveNodeState . Started ) ; } else { logger . trace ( "Node {} provided no node info after {} retries; not flagged as listening so assuming it's asleep" , getNodeId ( ) , stateRetries ) ; available = true ; setState ( context , ZWaveNodeState . Started ) ; } } } else { byte [ ] commandClasses = update . getNodeInfo ( ) . getCommandClasses ( ) ; for ( byte commandClassId : commandClasses ) { if ( ! hasCommandClass ( commandClassId ) ) { CommandClass cc = CommandClassFactory . createCommandClass ( commandClassId ) ; if ( cc != null ) { addCommandClass ( commandClassId , cc ) ; } else { logger . trace ( "Ignoring optional command class: {}" , ByteUtil . createString ( commandClassId ) ) ; } } } if ( getCommandClass ( VersionCommandClass . ID ) != null ) { setState ( context , ZWaveNodeState . RetrieveVersionPending ) ; } else { setState ( context , ZWaveNodeState . RetrieveStatePending ) ; } } break ; default : logger . trace ( "Unsolicited ApplicationUpdate received; refreshing node" ) ; refresh ( false ) ; break ; } } | Called when an application update message is received for this node . |
40,999 | public void channelRead ( ChannelHandlerContext ctx , Object msg ) { if ( msg instanceof Frame ) { Frame frame = ( Frame ) msg ; if ( hasCurrentTransaction ( ) ) { String tid = currentDataFrameTransaction . getId ( ) ; logger . trace ( "Received frame within transaction ({}) context: {}" , tid , frame ) ; NettyZWaveChannelContext zctx = new NettyZWaveChannelContext ( ) ; if ( currentDataFrameTransaction . addFrame ( zctx , frame ) ) { if ( currentDataFrameTransaction . isComplete ( ) ) { logger . trace ( "*** Data frame transaction ({}) completed" , tid ) ; logger . trace ( "" ) ; cancelTimeoutCallback ( ) ; } zctx . process ( ctx ) ; } else { logger . trace ( "Transaction ignored frame so passing it along" ) ; ctx . fireChannelRead ( msg ) ; } } else if ( msg instanceof AddNodeToNetwork ) { logger . trace ( "Received ADD_NODE_STATUS_NODE_FOUND; starting transaction" ) ; NettyZWaveChannelContext zctx = new NettyZWaveChannelContext ( ) ; currentDataFrameTransaction = new NodeInclusionTransaction ( zctx , ( DataFrame ) msg ) ; zctx . process ( ctx ) ; } else { logger . trace ( "Received frame outside of transaction context so passing it along: {}" , frame ) ; ctx . fireChannelRead ( msg ) ; } } } | Called when data is read from the Z - Wave network . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.