idx int64 0 41.2k | question stringlengths 83 4.15k | target stringlengths 5 715 |
|---|---|---|
12,800 | private Tree < Row > downLeft ( Element token ) { return current = current . getParent ( ) . addSibling ( Tree . of ( new Row ( token ) ) ) ; } | Starts a new row one indentation level to the left . |
12,801 | private Tree < Row > down ( Element token ) { return current = current . addSibling ( Tree . of ( new Row ( token ) ) ) ; } | Starts a new row at the same level of indentation . |
12,802 | private Tree < Row > here ( Element token ) { current . getContent ( ) . addToken ( token ) ; return current ; } | Adds element to the same row . |
12,803 | public static < I > Result < I > rangeResult ( List < I > result , long offset , long fullRequestSize ) { return new Result < > ( result , offset , fullRequestSize ) ; } | Creates a new Result . |
12,804 | T get ( long index ) { checkRange ( index ) ; if ( checkSubRange ( index ) ) { return subList . get ( ( int ) ( index - subListOffset ) ) ; } return null ; } | Gets the item at the index . |
12,805 | List < T > subList ( long from , long to ) { if ( fullListSize > 0 && to - from > 0 ) { checkRange ( from ) ; checkRange ( to - 1 ) ; assertSubRange ( from , to - 1 ) ; return subList . subList ( ( int ) ( from - subListOffset ) , ( int ) ( to - subListOffset ) ) ; } return new ArrayList < > ( ) ; } | Returns a portion of this list between the specified from inclusive and to exclusive . |
12,806 | private void assertSubRange ( long from , long to ) { if ( ! checkSubRange ( from ) || ! checkSubRange ( to ) ) { throw new IndexOutOfBoundsException ( "Required data for the sub list [" + from + "," + ( to + 1 ) + "[ have " + "not been loaded in the virtual list." ) ; } } | Asserts that the requested sub list is available in the virtual list . Otherwise it throws an IndexOutOfBoundsException . |
12,807 | public static Object getFieldValue ( Object candidate , Field field ) { try { return ReflectUtils . getValue ( ReflectUtils . makeAccessible ( field ) , candidate ) ; } catch ( Exception e ) { throw BusinessException . wrap ( e , BusinessErrorCode . ERROR_ACCESSING_FIELD ) . put ( "className" , candidate . getClass ( ) ) . put ( "fieldName" , field . getName ( ) ) ; } } | Return the value contained in the specified field of the candidate object . |
12,808 | public static Optional < Field > resolveField ( Class < ? > someClass , String fieldName ) { return fieldCache . get ( new FieldReference ( someClass , fieldName ) ) ; } | Returns the specified field found on the specified class and its ancestors . |
12,809 | public static String removeBrackets ( String condition ) { String value = StringUtils . strip ( condition ) ; if ( value != null && value . length ( ) >= 3 ) { return value . substring ( 2 , value . length ( ) - 1 ) ; } return value ; } | After trimming the input removes two characters from the start and one from the end and returns the result . |
12,810 | public static boolean isReservedVariable ( String variableName ) { return ReservedVariables . NOW . equalsIgnoreCase ( variableName ) || ReservedVariables . WORKFLOW_INSTANCE_ID . equalsIgnoreCase ( variableName ) ; } | Checks if the given variable name is a reserved keyword and SHOULD NOT be used as a key for an Environment attribute . |
12,811 | private Tree < Row > findIf ( Tree < Row > pointer ) { while ( ! Type . IF . equals ( pointer . getContent ( ) . getType ( ) ) ) { pointer = pointer . getPrevious ( ) ; } return pointer ; } | Finds the associate IF for an ELSE_IF ELSE or END_IF pointer . |
12,812 | private Tree < Row > findEndIf ( Tree < Row > pointer ) { while ( ! Type . END_IF . equals ( pointer . getContent ( ) . getType ( ) ) ) { pointer = pointer . getNext ( ) ; } return pointer ; } | Finds the associate END_IF for an IF ELSE_IF or ELSE pointer |
12,813 | private Tree < Row > findNext ( Tree < Row > pointer ) { if ( pointer . hasNext ( ) ) { if ( Type . END . equals ( pointer . getNext ( ) . getContent ( ) . getType ( ) ) ) { return null ; } else { return pointer . getNext ( ) ; } } Tree < Row > parent = pointer . getParent ( ) ; Type parentType = parent . getContent ( ) . getType ( ) ; if ( Type . WHILE_DO_BEGIN . equals ( parentType ) ) { return parent . getNext ( ) ; } else if ( Type . DO_WHILE_BEGIN . equals ( parentType ) ) { return parent . getNext ( ) ; } if ( Type . BRANCH . equals ( parentType ) ) { Tree < Row > join = parent . getParent ( ) . getNext ( ) ; return join ; } else if ( Type . IF . equals ( parentType ) || Type . ELSE_IF . equals ( parentType ) || Type . ELSE . equals ( parentType ) ) { Tree < Row > endIf = findEndIf ( parent ) ; return endIf ; } else { throw new IllegalStateException ( "Unknown containting block type for row " + parent . getContent ( ) ) ; } } | Finds the following node which to create a transition to . Supports tree - nodes that are not the last in their block and those which are last . |
12,814 | public static Method findMatchingMethod ( Class < ? > classToInspect , Class < ? > returnType , Object ... params ) { Method [ ] methods = classToInspect . getMethods ( ) ; Method checkedMethod = null ; for ( Method method : methods ) { Type [ ] parameterTypes = method . getParameterTypes ( ) ; boolean matchReturnType = returnType == null || returnType . equals ( method . getReturnType ( ) ) ; if ( checkParams ( parameterTypes , params ) && matchReturnType ) { if ( checkedMethod == null ) { checkedMethod = method ; } else { throw BusinessException . createNew ( BusinessErrorCode . AMBIGUOUS_METHOD_FOUND ) . put ( "method1" , method ) . put ( "method2" , checkedMethod ) . put ( "object" , classToInspect . getSimpleName ( ) ) . put ( "parameters" , params ) ; } } } return checkedMethod ; } | Finds a method matching the given parameters and return type . |
12,815 | @ SuppressWarnings ( "unchecked" ) public static < T > Constructor < T > findMatchingConstructor ( Class < T > classToInspect , Object ... params ) { Constructor < T > checkedConstructors = null ; for ( Constructor < ? > constructor : classToInspect . getDeclaredConstructors ( ) ) { Type [ ] parameterTypes = constructor . getParameterTypes ( ) ; if ( parameterTypes . length == params . length && checkParameterTypes ( parameterTypes , params ) ) { if ( checkedConstructors == null ) { checkedConstructors = ( Constructor < T > ) constructor ; } else { throw BusinessException . createNew ( BusinessErrorCode . AMBIGUOUS_CONSTRUCTOR_FOUND ) . put ( "constructor1" , constructor ) . put ( "constructor2" , checkedConstructors ) . put ( "object" , classToInspect . getSimpleName ( ) ) . put ( "parameters" , params ) ; } } } return checkedConstructors ; } | Finds a constructor matching the given parameters . |
12,816 | protected < A extends AggregateRoot < ? > > A createFromFactory ( Class < A > aggregateClass , Object ... parameters ) { checkNotNull ( aggregateClass ) ; checkNotNull ( parameters ) ; Factory < A > factory = domainRegistry . getFactory ( aggregateClass ) ; Method factoryMethod ; boolean useDefaultFactory = false ; try { factoryMethod = MethodMatcher . findMatchingMethod ( factory . getClass ( ) , aggregateClass , parameters ) ; if ( factoryMethod == null ) { useDefaultFactory = true ; } } catch ( Exception e ) { throw BusinessException . wrap ( e , BusinessErrorCode . UNABLE_TO_FIND_FACTORY_METHOD ) . put ( "aggregateClass" , aggregateClass . getName ( ) ) . put ( "parameters" , Arrays . toString ( parameters ) ) ; } try { if ( useDefaultFactory ) { return factory . create ( parameters ) ; } else { if ( parameters . length == 0 ) { return ReflectUtils . invoke ( factoryMethod , factory ) ; } else { return ReflectUtils . invoke ( factoryMethod , factory , parameters ) ; } } } catch ( Exception e ) { throw BusinessException . wrap ( e , BusinessErrorCode . UNABLE_TO_INVOKE_FACTORY_METHOD ) . put ( "aggregateClass" , aggregateClass . getName ( ) ) . put ( "factoryClass" , factory . getClass ( ) . getName ( ) ) . put ( "factoryMethod" , Optional . ofNullable ( factoryMethod ) . map ( Method :: getName ) . orElse ( "create" ) ) . put ( "parameters" , Arrays . toString ( parameters ) ) ; } } | Implements the logic to create an aggregate . |
12,817 | static void serialize ( final Document doc , final OutputStream os , final String encoding ) throws TransformerFactoryConfigurationError , TransformerException , IOException { if ( doc == null ) throw new IllegalArgumentException ( "No document provided." ) ; if ( os == null ) throw new IllegalArgumentException ( "No output stream provided" ) ; if ( encoding == null || encoding . isEmpty ( ) ) throw new IllegalArgumentException ( "No encoding provided." ) ; final TransformerFactory transformerFactory = TransformerFactory . newInstance ( ) ; transformerFactory . setAttribute ( "indent-number" , Integer . valueOf ( 2 ) ) ; final Transformer t = transformerFactory . newTransformer ( ) ; t . setOutputProperty ( OutputKeys . OMIT_XML_DECLARATION , "no" ) ; t . setOutputProperty ( OutputKeys . METHOD , "xml" ) ; t . setOutputProperty ( OutputKeys . INDENT , "yes" ) ; t . setOutputProperty ( OutputKeys . ENCODING , encoding ) ; final OutputStreamWriter osw = new OutputStreamWriter ( os , encoding ) ; t . transform ( new DOMSource ( doc ) , new StreamResult ( osw ) ) ; osw . flush ( ) ; } | Serializes a DOM . The OutputStream handed over to this method is not closed inside this method . |
12,818 | public byte [ ] toByteArray ( ) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream ( 16 ) ; outputStream . write ( commandByte ) ; outputStream . write ( sysexCommandByte ) ; if ( serialize ( outputStream ) ) { outputStream . write ( CommandBytes . END_SYSEX . getCommandByte ( ) ) ; return outputStream . toByteArray ( ) ; } return null ; } | Combine the SysexCommandByte and the serialized sysex message packet together to form a Firmata supported sysex byte packet to be sent over the SerialPort . |
12,819 | protected boolean isValidFragment ( String fragmentName ) { Boolean knownFrag = false ; for ( Class < ? > cls : INNER_CLASSES ) { if ( cls . getName ( ) . equals ( fragmentName ) ) { knownFrag = true ; break ; } } return knownFrag ; } | Google found a security vulnerability and imposed this hack . Have to check this fragment was actually conceived by this activity . |
12,820 | public byte [ ] toByteArray ( ) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream ( 32 ) ; outputStream . write ( commandByte ) ; if ( serialize ( outputStream ) ) { return outputStream . toByteArray ( ) ; } return null ; } | Combine the CommandByte and the serialized message packet together to form a Firmata supported byte packet to be sent over the SerialPort . |
12,821 | protected void fireEvent ( SerialPortEventTypes eventType ) { executor . submit ( new Runnable ( ) { public void run ( ) { for ( SerialPortEventListener listener : eventListeners ) { listener . serialEvent ( new SerialPortEvent ( eventType ) ) ; } } } ) ; } | Tell the client if there is data available etc . |
12,822 | public ArrayList < PinCapability > getPinCapabilities ( Integer pin ) { if ( pinCapabilities . size ( ) >= pin ) { return pinCapabilities . get ( pin ) ; } return null ; } | Get Pin Capabilities Get a list of modes that a given pin supports . |
12,823 | public void addMessageListener ( Integer channel , MessageListener < ? extends Message > messageListener ) { addListener ( channel , messageListener . getMessageType ( ) , messageListener ) ; } | Add a messageListener to the Firmta object which will fire whenever a matching message is received over the SerialPort that corresponds to the given channel . |
12,824 | public void addMessageListener ( DigitalChannel channel , MessageListener < ? extends Message > messageListener ) { addListener ( channel . getIdentifier ( ) , messageListener . getMessageType ( ) , messageListener ) ; } | Add a messageListener to the Firmata object which will fire whenever a matching message is received over the SerialPort that corresponds to the given DigitalChannel . |
12,825 | public void addMessageListener ( Class < ? extends Message > messageClass , MessageListener < Message > messageListener ) { addMessageListener ( messageListener . getChannelIdentifier ( ) , messageClass , messageListener ) ; } | Add a generic message listener to listen for a specific type of message . Useful if you want to combine several or more message handlers into one bucket . |
12,826 | public void removeMessageListener ( Class < ? extends Message > messageClass , MessageListener < Message > messageListener ) { removeMessageListener ( messageListener . getChannelIdentifier ( ) , messageClass , messageListener ) ; } | Remove a generic message listener from listening to a specific type of message . |
12,827 | public synchronized Boolean sendMessage ( TransmittableMessage message ) { if ( ! start ( ) ) { log . error ( "Firmata library is not connected / started! Cannot send message {}" , message . getClass ( ) . getSimpleName ( ) ) ; return false ; } try { log . debug ( "Transmitting message {}. Bytes: {}" , message . getClass ( ) . getSimpleName ( ) , FirmataHelper . bytesToHexString ( message . toByteArray ( ) ) ) ; serialPort . getOutputStream ( ) . write ( message . toByteArray ( ) ) ; return true ; } catch ( IOException e ) { log . error ( "Unable to transmit message {} through serial port" , message . getClass ( ) . getName ( ) ) ; stop ( ) ; } return false ; } | Send a Message over the serial port to a Firmata supported device . |
12,828 | public synchronized Boolean sendRaw ( byte ... rawBytes ) { if ( ! start ( ) ) { log . error ( "Firmata library is not connected / started! Cannot send bytes {}" , FirmataHelper . bytesToHexString ( rawBytes ) ) ; return false ; } try { serialPort . getOutputStream ( ) . write ( rawBytes ) ; return true ; } catch ( IOException e ) { log . error ( "Unable to transmit raw bytes through serial port. Bytes: {}" , FirmataHelper . bytesToHexString ( rawBytes ) ) ; stop ( ) ; } return false ; } | Send a series of raw bytes over the serial port to a Firmata supported device . |
12,829 | public synchronized Boolean start ( ) { if ( started ) { return true ; } createSerialPort ( ) ; serialPort . addEventListener ( this ) ; if ( ! serialPort . connect ( ) ) { log . error ( "Failed to start Firmata Library. Cannot connect to Serial Port." ) ; log . error ( "Configuration is {}" , configuration ) ; stop ( ) ; return false ; } if ( configuration . getTestProtocolCommunication ( ) ) { if ( ! testProtocolCommunication ( ) ) { stop ( ) ; return false ; } } started = true ; return true ; } | Starts the firmata library . If the library is already started this will just return true . Starts the SerialPort and handlers and ensures the attached device is able to communicate with our library . This will return an UnsupportedDevice exception if the attached device does not meet the library requirements . |
12,830 | public synchronized Boolean stop ( ) { if ( serialPort != null ) { serialPort . removeEventListener ( this ) ; } if ( ! removeSerialPort ( ) ) { log . error ( "Failed to stop Firmata Library. Cannot close Serial Port." ) ; log . error ( "Configuration is {}" , configuration ) ; return false ; } started = false ; return true ; } | Stops the Firmata library . If the library is already stopped this will still attempt to stop anything that may still be lingering . Take note that many calls could eventually result in noticeable cpu usage . |
12,831 | private void createSerialPort ( ) { Constructor < ? extends SerialPort > constructor ; try { constructor = configuration . getSerialPortAdapterClass ( ) . getDeclaredConstructor ( String . class , Integer . class , SerialPortDataBits . class , SerialPortStopBits . class , SerialPortParity . class ) ; } catch ( NoSuchMethodException e ) { log . error ( "Unable to construct SerialPort object. Programming error. Your class adapter must support " + "a constructor with input args of" + "YourSerialPort(String.class, Integer.class, SerialPortDataBits.class, " + "SerialPortStopBits.class, SerialPortParity.class);" ) ; e . printStackTrace ( ) ; throw new RuntimeException ( "Cannot construct SerialPort adapter!" ) ; } try { serialPort = constructor . newInstance ( configuration . getSerialPortID ( ) , configuration . getSerialPortBaudRate ( ) , configuration . getSerialPortDataBits ( ) , configuration . getSerialPortStopBits ( ) , configuration . getSerialPortParity ( ) ) ; } catch ( InstantiationException | IllegalAccessException | InvocationTargetException e ) { log . error ( "Unable to construct SerialPort object. Programming error. Instantiation error. {}" , e . getMessage ( ) ) ; e . printStackTrace ( ) ; throw new RuntimeException ( "Cannot construct SerialPort adapter!" ) ; } } | Generate the SerialPort object using the SerialPort adapter class provided in the FirmataConfiguration If there is any issue constructing this object toss a RuntimeException as this is a developer error in implementing the SerialPort adapter for this library . |
12,832 | private Boolean removeSerialPort ( ) { Boolean ret = true ; if ( serialPort != null ) { ret = serialPort . disconnect ( ) ; serialPort = null ; } return ret ; } | Disconnect from the SerialPort object that we are communicating with over the Firmata protocol . |
12,833 | private void handleDataAvailable ( ) { InputStream inputStream = serialPort . getInputStream ( ) ; try { while ( inputStream . available ( ) > 0 ) { byte inputByte = ( byte ) inputStream . read ( ) ; if ( inputByte == - 1 ) { log . error ( "Reached end of stream trying to read serial port." ) ; stop ( ) ; return ; } Message message = configuration . getCommandParser ( ) . handleInputStream ( inputByte , inputStream ) ; if ( message != null ) { log . debug ( "Routing message {}" , message . getClass ( ) . getSimpleName ( ) ) ; routeMessage ( message ) ; } } } catch ( IOException e ) { log . error ( "IO Error reading from serial port. Closing connection." ) ; e . printStackTrace ( ) ; stop ( ) ; } } | Handles the SerialPort input stream and builds a message object if a detected CommandByte is discovered over the communications stream . |
12,834 | private void routeMessage ( Message message ) { Class messageClass = message . getClass ( ) ; if ( messageListenerMap . containsKey ( messageClass ) ) { dispatchMessage ( messageListenerMap . get ( messageClass ) , message ) ; } if ( messageListenerMap . containsKey ( Message . class ) ) { dispatchMessage ( messageListenerMap . get ( Message . class ) , message ) ; } } | Route a Message object built from data over the SerialPort communication line to a corresponding MessageListener array designed to handle and interpret the object for processing in the client code . |
12,835 | @ SuppressWarnings ( "unchecked" ) private void dispatchMessage ( ArrayListMultimap < Integer , MessageListener > listenerMap , Message message ) { List < MessageListener > messageListeners ; if ( message instanceof ChannelMessage ) { messageListeners = listenerMap . get ( ( ( ChannelMessage ) message ) . getChannelInt ( ) ) ; if ( messageListeners != null ) { for ( MessageListener listener : messageListeners ) { listener . messageReceived ( message ) ; } } } messageListeners = listenerMap . get ( null ) ; if ( messageListeners != null ) { for ( MessageListener listener : messageListeners ) { listener . messageReceived ( message ) ; } } } | Dispatch a message to the corresponding listener arrays in the listener map |
12,836 | public Message handleInputStream ( byte commandByte , InputStream inputStream ) { byte firmataCommandByte = commandByte < ( byte ) 0xF0 ? ( byte ) ( commandByte & 0xF0 ) : commandByte ; MessageBuilder messageBuilder = messageBuilderMap . get ( firmataCommandByte ) ; if ( messageBuilder != null ) { byte channelByte = ( byte ) ( commandByte & 0x0F ) ; Message message = messageBuilder . buildMessage ( channelByte , inputStream ) ; if ( message == null ) { log . error ( "Error building Firmata messageBuilder for command byte {}." , FirmataHelper . bytesToHexString ( commandByte ) ) ; } else { return message ; } } else { log . warn ( "Dropped byte {}." , FirmataHelper . bytesToHexString ( commandByte ) ) ; } return null ; } | Attempts to identify the corresponding Firmata Message object that responds to the given commandByte If found it will ask for the message to be built using given inputStream . The builder will take away any bytes necessary to build the message and then return . To attempt to identify the correct message we must mask the incoming byte against 0xF0 if the byte is less than 0xF0 as commands below 0xF0 are only legal within this mask due to potential data padding in the same byte per the Firmata spec . |
12,837 | public void messageReceived ( T message ) { if ( responseReceived != null ) { if ( responseReceived ) { log . warn ( "Received more than one synchronous message reply!" ) ; } else { log . warn ( "Received response message after timeout was hit!" ) ; } } responseMessage = message ; responseReceived = true ; synchronized ( lock ) { lock . notify ( ) ; } } | When we get our expected message response . Save the message object and notify the waiting thread that the message is now available to be passed back . This method attempts to handle and warn against cases where multiple messages came in or a message came in after the timeout period . |
12,838 | public Message buildMessage ( Byte channelByte , InputStream inputStream ) { byte sysexCommandByte ; try { sysexCommandByte = ( byte ) inputStream . read ( ) ; } catch ( IOException e ) { log . error ( "Error reading Sysex command byte." ) ; return null ; } ByteArrayOutputStream messageBodyBuilder = new ByteArrayOutputStream ( 16 ) ; try { int messagePiece ; while ( ( messagePiece = inputStream . read ( ) ) != - 1 ) { if ( ( byte ) messagePiece == CommandBytes . END_SYSEX . getCommandByte ( ) ) { break ; } messageBodyBuilder . write ( messagePiece ) ; } } catch ( IOException e ) { log . error ( "Error reading Sysex message body for command {}." , FirmataHelper . bytesToHexString ( sysexCommandByte ) ) ; return null ; } byte [ ] messageBodyBytes = messageBodyBuilder . toByteArray ( ) ; try { messageBodyBuilder . close ( ) ; } catch ( IOException e ) { log . error ( "Programming error. Cannot close our byte buffer." ) ; } SysexMessageBuilder messageBuilder = messageBuilderMap . get ( sysexCommandByte ) ; if ( messageBuilder == null ) { log . error ( "There is no Sysex message parser registered for command {}. Body: {}" , FirmataHelper . bytesToHexString ( sysexCommandByte ) , FirmataHelper . bytesToHexString ( messageBodyBuilder . toByteArray ( ) ) ) ; return null ; } return messageBuilder . buildMessage ( messageBodyBytes ) ; } | Attempts to identify the corresponding Firmata Sysex Message object that responds to the identified sysexCommandByte . If found it will ask for the sysex message to be built using the identified bytes between the sysexCommandByte and the END_SYSEX commandByte later in the input stream . |
12,839 | public static String sanitize ( String raw ) { return ( raw == null || raw . length ( ) == 0 ) ? raw : HTMLEntityEncode ( canonicalize ( raw ) ) ; } | Sanitize user inputs . |
12,840 | public static String HTMLEntityEncode ( String input ) { String next = scriptPattern . matcher ( input ) . replaceAll ( "script" ) ; StringBuffer sb = new StringBuffer ( ) ; for ( int i = 0 ; i < next . length ( ) ; ++ i ) { char ch = next . charAt ( i ) ; if ( ch == '<' ) { sb . append ( "<" ) ; } else if ( ch == '>' ) { sb . append ( ">" ) ; } else { sb . append ( ch ) ; } } return sb . toString ( ) ; } | Encode HTML entities . |
12,841 | private void checkEnd ( ) { if ( ended && ! closed && children == 0 ) { closed = true ; connection . doBatchEnd ( id , endArgs ) ; if ( endHandler != null ) { endHandler . handle ( ( Void ) null ) ; } } } | Checks whether the batch is complete . |
12,842 | void start ( Handler < ConnectionOutputBatch > startHandler ) { connection . doBatchStart ( id , args ) ; this . startHandler = startHandler ; } | Starts the output batch . |
12,843 | public List < String > getInPorts ( ) { List < String > ports = new ArrayList < > ( ) ; JsonObject jsonPorts = config . getObject ( "ports" ) ; if ( jsonPorts == null ) { return ports ; } JsonArray jsonInPorts = jsonPorts . getArray ( "in" ) ; if ( jsonInPorts == null ) { return ports ; } for ( Object jsonInPort : jsonInPorts ) { ports . add ( ( String ) jsonInPort ) ; } return ports ; } | Returns a list of input ports defined by the module . |
12,844 | public List < String > getOutPorts ( ) { List < String > ports = new ArrayList < > ( ) ; JsonObject jsonPorts = config . getObject ( "ports" ) ; if ( jsonPorts == null ) { return ports ; } JsonArray jsonOutPorts = jsonPorts . getArray ( "out" ) ; if ( jsonOutPorts == null ) { return ports ; } for ( Object jsonOutPort : jsonOutPorts ) { ports . add ( ( String ) jsonOutPort ) ; } return ports ; } | Returns a list of output ports defined by the module . |
12,845 | public void fail ( Throwable t ) { if ( ! failed ) { if ( doneHandler != null ) { doneHandler . handle ( new DefaultFutureResult < T > ( t ) ) ; } else { cause = t ; } failed = true ; } } | Indicates that a call failed . This will immediately fail the handler . |
12,846 | public CountingCompletionHandler < T > setHandler ( Handler < AsyncResult < T > > doneHandler ) { this . doneHandler = doneHandler ; checkDone ( ) ; return this ; } | Sets the completion handler . |
12,847 | private void checkDone ( ) { if ( doneHandler != null ) { if ( cause != null ) { doneHandler . handle ( new DefaultFutureResult < T > ( cause ) ) ; } else { if ( count == required ) { doneHandler . handle ( new DefaultFutureResult < T > ( ( T ) null ) ) ; } } } } | Checks whether the handler should be called . |
12,848 | private void setup ( final Handler < AsyncResult < Void > > doneHandler ) { log . debug ( String . format ( "%s - Starting cluster coordination" , DefaultComponent . this ) ) ; coordinator . start ( new Handler < AsyncResult < Void > > ( ) { public void handle ( AsyncResult < Void > result ) { if ( result . failed ( ) ) { new DefaultFutureResult < Void > ( result . cause ( ) ) . setHandler ( doneHandler ) ; } else { final CountingCompletionHandler < Void > ioHandler = new CountingCompletionHandler < Void > ( 2 ) ; ioHandler . setHandler ( new Handler < AsyncResult < Void > > ( ) { public void handle ( AsyncResult < Void > result ) { if ( result . failed ( ) ) { new DefaultFutureResult < Void > ( result . cause ( ) ) . setHandler ( doneHandler ) ; } else { coordinator . resume ( ) ; } } } ) ; output . open ( new Handler < AsyncResult < Void > > ( ) { public void handle ( AsyncResult < Void > result ) { if ( result . failed ( ) ) { log . error ( String . format ( "%s - Failed to open component outputs" , DefaultComponent . this ) , result . cause ( ) ) ; ioHandler . fail ( result . cause ( ) ) ; } else { ioHandler . succeed ( ) ; } } } ) ; input . open ( new Handler < AsyncResult < Void > > ( ) { public void handle ( AsyncResult < Void > result ) { if ( result . failed ( ) ) { log . error ( String . format ( "%s - Failed to open component inputs" , DefaultComponent . this ) , result . cause ( ) ) ; ioHandler . fail ( result . cause ( ) ) ; } else { ioHandler . succeed ( ) ; } } } ) ; } } } ) ; coordinator . resumeHandler ( new Handler < Void > ( ) { @ SuppressWarnings ( "unchecked" ) public void handle ( Void _ ) { if ( ! started ) { started = true ; log . debug ( String . format ( "%s - Started" , DefaultComponent . this , context . component ( ) . name ( ) , context . number ( ) ) ) ; List < ComponentHook > hooks = context . component ( ) . hooks ( ) ; for ( ComponentHook hook : hooks ) { hook . handleStart ( DefaultComponent . this ) ; } new DefaultFutureResult < Void > ( ( Void ) null ) . setHandler ( doneHandler ) ; } } } ) ; } | Sets up the component . |
12,849 | public void start ( ) { input . messageHandler ( new Handler < Object > ( ) { public void handle ( Object message ) { output . send ( message ) ; pumped ++ ; } } ) ; } | Starts the pump . |
12,850 | public static < T extends Output < T > > Feeder < T > createFeeder ( T output ) { return new Feeder < T > ( output ) ; } | Creates a new feeder . |
12,851 | private void doFeed ( ) { if ( fed && ! output . sendQueueFull ( ) ) { fed = false ; vertx . runOnContext ( feedRunner ) ; } else { feedTimer = vertx . setTimer ( feedDelay , recursiveRunner ) ; } } | Feeds the next message . |
12,852 | public static Component createComponent ( Vertx vertx , Container container ) { InstanceContext context = parseContext ( container . config ( ) ) ; return new DefaultComponentFactory ( ) . setVertx ( vertx ) . setContainer ( container ) . createComponent ( context , new DefaultCluster ( context . component ( ) . network ( ) . cluster ( ) , vertx , container ) ) ; } | Creates a component instance for the current Vert . x instance . |
12,853 | public static JsonObject buildConfig ( InstanceContext context , Cluster cluster ) { JsonObject config = context . component ( ) . config ( ) . copy ( ) ; return config . putObject ( "__context__" , Contexts . serialize ( context ) ) ; } | Builds a verticle configuration . |
12,854 | private static InstanceContext parseContext ( JsonObject config ) { JsonObject context = config . getObject ( "__context__" ) ; if ( context == null ) { throw new IllegalArgumentException ( "No component context found." ) ; } config . removeField ( "__context__" ) ; return Contexts . deserialize ( context ) ; } | Parses an instance context from configuration . |
12,855 | private List < File > locateModules ( ) { File [ ] files = modRoot . listFiles ( ) ; List < File > modFiles = new ArrayList < > ( ) ; for ( File file : files ) { if ( file . isDirectory ( ) ) { boolean isValid = true ; try { new ModuleIdentifier ( file . getName ( ) ) ; } catch ( Exception e ) { isValid = false ; } if ( isValid ) { File modJson = new File ( file , MOD_JSON_FILE ) ; if ( modJson . exists ( ) ) { modFiles . add ( file ) ; } } } } return modFiles ; } | Locates all modules in the local repository . |
12,856 | private File locateModule ( ModuleIdentifier modID ) { File modDir = new File ( modRoot , modID . toString ( ) ) ; if ( modDir . exists ( ) ) { return modDir ; } return null ; } | Locates a module in the modules root directory . |
12,857 | private void pullInDependencies ( ModuleIdentifier modID , File modDir ) { File modJsonFile = new File ( modDir , MOD_JSON_FILE ) ; ModuleInfo info = loadModuleInfo ( modID , modJsonFile ) ; ModuleFields fields = info . fields ( ) ; List < String > mods = new ArrayList < > ( ) ; String sincludes = fields . getIncludes ( ) ; if ( sincludes != null ) { String [ ] includes = parseIncludes ( sincludes ) ; if ( includes != null ) { mods . addAll ( Arrays . asList ( includes ) ) ; } } String sdeploys = fields . getDeploys ( ) ; if ( sdeploys != null ) { String [ ] deploys = parseIncludes ( sdeploys ) ; if ( deploys != null ) { mods . addAll ( Arrays . asList ( deploys ) ) ; } } if ( ! mods . isEmpty ( ) ) { File internalModsDir = new File ( modDir , "mods" ) ; if ( ! internalModsDir . exists ( ) ) { if ( ! internalModsDir . mkdir ( ) ) { throw new PlatformManagerException ( "Failed to create directory " + internalModsDir ) ; } } for ( String moduleName : mods ) { File internalModDir = new File ( internalModsDir , moduleName ) ; if ( ! internalModDir . exists ( ) ) { ModuleIdentifier childModID = new ModuleIdentifier ( moduleName ) ; File includeModDir = locateModule ( childModID ) ; if ( includeModDir != null ) { vertx . fileSystem ( ) . copySync ( includeModDir . getAbsolutePath ( ) , internalModDir . getAbsolutePath ( ) , true ) ; pullInDependencies ( childModID , internalModDir ) ; } } } } } | Pulls in all dependencies for a module . |
12,858 | private File zipModule ( ModuleIdentifier modID ) { File modDir = new File ( modRoot , modID . toString ( ) ) ; if ( ! modDir . exists ( ) ) { throw new PlatformManagerException ( "Cannot find module" ) ; } File modRoot = new File ( TEMP_DIR , "vertx-zip-mods" ) ; File zipFile = new File ( modRoot , modID . toString ( ) + ".zip" ) ; if ( zipFile . exists ( ) ) { return zipFile ; } File modDest = new File ( modRoot , modID . toString ( ) + "-" + UUID . randomUUID ( ) . toString ( ) ) ; File modHome = new File ( modDest , modID . toString ( ) ) ; vertx . fileSystem ( ) . mkdirSync ( modHome . getAbsolutePath ( ) , true ) ; vertx . fileSystem ( ) . copySync ( modDir . getAbsolutePath ( ) , modHome . getAbsolutePath ( ) , true ) ; pullInDependencies ( modID , modHome ) ; zipDirectory ( zipFile . getPath ( ) , modDest . getAbsolutePath ( ) ) ; vertx . fileSystem ( ) . deleteSync ( modDest . getAbsolutePath ( ) , true ) ; return zipFile ; } | Creates a zip file from a module . |
12,859 | private void zipDirectory ( String zipFile , String dirToZip ) { File directory = new File ( dirToZip ) ; try ( ZipOutputStream stream = new ZipOutputStream ( new FileOutputStream ( zipFile ) ) ) { addDirectoryToZip ( directory , directory , stream ) ; } catch ( Exception e ) { throw new PlatformManagerException ( "Failed to zip module" , e ) ; } } | Zips up a directory . |
12,860 | private void addDirectoryToZip ( File topDirectory , File directory , ZipOutputStream out ) throws IOException { Path top = Paths . get ( topDirectory . getAbsolutePath ( ) ) ; File [ ] files = directory . listFiles ( ) ; byte [ ] buffer = new byte [ BUFFER_SIZE ] ; for ( int i = 0 ; i < files . length ; i ++ ) { Path entry = Paths . get ( files [ i ] . getAbsolutePath ( ) ) ; Path relative = top . relativize ( entry ) ; String entryName = relative . toString ( ) ; if ( files [ i ] . isDirectory ( ) ) { entryName += FILE_SEPARATOR ; } out . putNextEntry ( new ZipEntry ( entryName . replace ( "\\" , "/" ) ) ) ; if ( ! files [ i ] . isDirectory ( ) ) { try ( FileInputStream in = new FileInputStream ( files [ i ] ) ) { int bytesRead ; while ( ( bytesRead = in . read ( buffer ) ) != - 1 ) { out . write ( buffer , 0 , bytesRead ) ; } } out . closeEntry ( ) ; } if ( files [ i ] . isDirectory ( ) ) { addDirectoryToZip ( topDirectory , files [ i ] , out ) ; } } } | Recursively adds directories to a zip file . |
12,861 | private String [ ] parseIncludes ( String sincludes ) { sincludes = sincludes . trim ( ) ; if ( "" . equals ( sincludes ) ) { return null ; } String [ ] arr = sincludes . split ( "," ) ; if ( arr != null ) { for ( int i = 0 ; i < arr . length ; i ++ ) { arr [ i ] = arr [ i ] . trim ( ) ; } } return arr ; } | Parses an includes string . |
12,862 | private void unzipModuleData ( File directory , File zipFile , boolean deleteZip ) { try ( InputStream in = new BufferedInputStream ( new FileInputStream ( zipFile ) ) ; ZipInputStream zin = new ZipInputStream ( new BufferedInputStream ( in ) ) ) { ZipEntry entry ; while ( ( entry = zin . getNextEntry ( ) ) != null ) { String entryName = entry . getName ( ) ; if ( ! entryName . isEmpty ( ) ) { if ( entry . isDirectory ( ) ) { File dir = new File ( directory , entryName ) ; if ( ! dir . exists ( ) ) { if ( ! new File ( directory , entryName ) . mkdir ( ) ) { throw new PlatformManagerException ( "Failed to create directory" ) ; } } } else { int count ; byte [ ] buffer = new byte [ BUFFER_SIZE ] ; BufferedOutputStream out = null ; try { OutputStream os = new FileOutputStream ( new File ( directory , entryName ) ) ; out = new BufferedOutputStream ( os , BUFFER_SIZE ) ; while ( ( count = zin . read ( buffer , 0 , BUFFER_SIZE ) ) != - 1 ) { out . write ( buffer , 0 , count ) ; } out . flush ( ) ; } finally { if ( out != null ) { out . close ( ) ; } } } } } } catch ( Exception e ) { throw new PlatformManagerException ( "Failed to unzip module" , e ) ; } finally { if ( deleteZip ) { zipFile . delete ( ) ; } } } | Unzips a module . |
12,863 | @ SuppressLint ( "ShowToast" ) public Toast build ( ) { Toast toast = Toast . makeText ( context , message , duration ) ; TextView toastMessage = setupToastView ( toast ) ; setToastMessageTextColor ( toastMessage ) ; setToastGravity ( toast ) ; return toast ; } | Build a Toast using the options specified in the builder . |
12,864 | private void handleCreate ( final NetworkContext context ) { log . debug ( String . format ( "%s - Network configuration created in cluster: %s" , NetworkManager . this , cluster . address ( ) ) ) ; log . debug ( String . format ( "%s - Scheduling network deployment task" , NetworkManager . this ) ) ; tasks . runTask ( new Handler < Task > ( ) { public void handle ( final Task task ) { currentContext = context ; unready ( new Handler < AsyncResult < Void > > ( ) { public void handle ( AsyncResult < Void > result ) { if ( result . failed ( ) ) { log . error ( result . cause ( ) ) ; task . complete ( ) ; } else { deployNetwork ( context , new Handler < AsyncResult < NetworkContext > > ( ) { public void handle ( AsyncResult < NetworkContext > result ) { task . complete ( ) ; if ( result . failed ( ) ) { log . error ( result . cause ( ) ) ; } else { log . info ( String . format ( "%s - Successfully deployed network" , NetworkManager . this ) ) ; } } } ) ; } } } ) ; } } ) ; } | Handles the creation of the network . |
12,865 | private void undeployRemovedComponents ( final NetworkContext context , final NetworkContext runningContext , final Handler < AsyncResult < Void > > doneHandler ) { final List < ComponentContext < ? > > removedComponents = new ArrayList < > ( ) ; for ( ComponentContext < ? > runningComponent : runningContext . components ( ) ) { if ( context . component ( runningComponent . name ( ) ) == null ) { removedComponents . add ( runningComponent ) ; } } if ( ! removedComponents . isEmpty ( ) ) { final CountingCompletionHandler < Void > counter = new CountingCompletionHandler < Void > ( removedComponents . size ( ) ) ; counter . setHandler ( new Handler < AsyncResult < Void > > ( ) { public void handle ( AsyncResult < Void > result ) { if ( result . failed ( ) ) { new DefaultFutureResult < Void > ( result . cause ( ) ) . setHandler ( doneHandler ) ; } else { log . info ( String . format ( "%s - Removed %d components" , NetworkManager . this , removedComponents . size ( ) ) ) ; new DefaultFutureResult < Void > ( ( Void ) null ) . setHandler ( doneHandler ) ; } } } ) ; undeployComponents ( removedComponents , counter ) ; } else { new DefaultFutureResult < Void > ( ( Void ) null ) . setHandler ( doneHandler ) ; } } | Undeploys components that were removed from the network . |
12,866 | private void handleDelete ( ) { log . debug ( String . format ( "%s - Network configuration removed from cluster: %s" , NetworkManager . this , cluster . address ( ) ) ) ; tasks . runTask ( new Handler < Task > ( ) { public void handle ( final Task task ) { unready ( new Handler < AsyncResult < Void > > ( ) { public void handle ( AsyncResult < Void > result ) { if ( result . failed ( ) ) { log . error ( result . cause ( ) ) ; } if ( currentContext != null ) { log . info ( String . format ( "%s - Undeploying network" , NetworkManager . this ) ) ; undeployNetwork ( currentContext , new Handler < AsyncResult < Void > > ( ) { public void handle ( AsyncResult < Void > result ) { if ( result . failed ( ) ) { log . error ( result . cause ( ) ) ; task . complete ( ) ; } else { data . put ( currentContext . status ( ) , "" , new Handler < AsyncResult < String > > ( ) { public void handle ( AsyncResult < String > result ) { if ( result . failed ( ) ) { log . error ( result . cause ( ) ) ; } else { log . info ( String . format ( "%s - Successfully undeployed all components" , NetworkManager . this ) ) ; } task . complete ( ) ; } } ) ; } } } ) ; } else { task . complete ( ) ; } } } ) ; } } ) ; } | Handles the deletion of the network . |
12,867 | private void unready ( final Handler < AsyncResult < Void > > doneHandler ) { if ( currentContext != null && data != null ) { log . debug ( String . format ( "%s - Pausing network" , NetworkManager . this ) ) ; data . remove ( currentContext . status ( ) , new Handler < AsyncResult < String > > ( ) { public void handle ( AsyncResult < String > result ) { if ( result . failed ( ) ) { new DefaultFutureResult < Void > ( result . cause ( ) ) . setHandler ( doneHandler ) ; } else { new DefaultFutureResult < Void > ( ( Void ) null ) . setHandler ( doneHandler ) ; } } } ) ; } } | Unreadies the network . |
12,868 | private void handleReady ( String address ) { log . debug ( String . format ( "%s - Received ready message from %s" , NetworkManager . this , address ) ) ; ready . add ( address ) ; checkReady ( ) ; } | Called when a component instance is ready . |
12,869 | private void checkReady ( ) { if ( allReady ( ) ) { log . debug ( String . format ( "%s - All components ready in network, starting components" , NetworkManager . this ) ) ; data . put ( currentContext . status ( ) , currentContext . version ( ) , new Handler < AsyncResult < String > > ( ) { public void handle ( AsyncResult < String > result ) { if ( result . failed ( ) ) { log . error ( result . cause ( ) ) ; } } } ) ; } } | Checks whether the network is ready . |
12,870 | private void handleUnready ( String address ) { log . debug ( String . format ( "%s - Received unready message from: %s" , NetworkManager . this , address ) ) ; ready . remove ( address ) ; checkUnready ( ) ; } | Called when a component instance is unready . |
12,871 | private void checkUnready ( ) { if ( ! allReady ( ) ) { log . debug ( String . format ( "%s - Components not ready, pausing components" , NetworkManager . this ) ) ; data . remove ( currentContext . address ( ) , new Handler < AsyncResult < String > > ( ) { public void handle ( AsyncResult < String > result ) { if ( result . failed ( ) ) { log . error ( result . cause ( ) ) ; } } } ) ; } } | Checks whether the network is unready . |
12,872 | private boolean allReady ( ) { if ( currentContext == null ) return false ; List < InstanceContext > instances = new ArrayList < > ( ) ; boolean match = true ; outer : for ( ComponentContext < ? > component : currentContext . components ( ) ) { instances . addAll ( component . instances ( ) ) ; for ( InstanceContext instance : component . instances ( ) ) { if ( ! ready . contains ( instance . address ( ) ) ) { match = false ; break outer ; } } } return match ; } | Checks whether all components are ready in the network . |
12,873 | private void deployNetwork ( final NetworkContext context , final Handler < AsyncResult < NetworkContext > > doneHandler ) { log . debug ( String . format ( "%s - Deploying network" , NetworkManager . this ) ) ; final CountingCompletionHandler < Void > complete = new CountingCompletionHandler < Void > ( context . components ( ) . size ( ) ) ; complete . setHandler ( new Handler < AsyncResult < Void > > ( ) { public void handle ( AsyncResult < Void > result ) { if ( result . failed ( ) ) { new DefaultFutureResult < NetworkContext > ( result . cause ( ) ) . setHandler ( doneHandler ) ; } else { new DefaultFutureResult < NetworkContext > ( context ) . setHandler ( doneHandler ) ; } } } ) ; deployComponents ( context . components ( ) , complete ) ; } | Deploys a complete network . |
12,874 | private void deployComponents ( Collection < ComponentContext < ? > > components , final CountingCompletionHandler < Void > counter ) { for ( final ComponentContext < ? > component : components ) { deployComponent ( component , new Handler < AsyncResult < Void > > ( ) { public void handle ( AsyncResult < Void > result ) { if ( result . failed ( ) ) { counter . fail ( result . cause ( ) ) ; } else { data . put ( component . address ( ) , Contexts . serialize ( component ) . encode ( ) , new Handler < AsyncResult < String > > ( ) { public void handle ( AsyncResult < String > result ) { if ( result . failed ( ) ) { counter . fail ( result . cause ( ) ) ; } else { counter . succeed ( ) ; } } } ) ; } } } ) ; } } | Deploys all network components . |
12,875 | private void deployInstances ( List < InstanceContext > instances , final Handler < AsyncResult < Void > > doneHandler ) { final CountingCompletionHandler < Void > counter = new CountingCompletionHandler < Void > ( instances . size ( ) ) . setHandler ( doneHandler ) ; for ( final InstanceContext instance : instances ) { deploymentIDs . get ( instance . address ( ) , new Handler < AsyncResult < String > > ( ) { public void handle ( AsyncResult < String > result ) { if ( result . failed ( ) ) { counter . fail ( result . cause ( ) ) ; } else if ( result . result ( ) == null ) { deployInstance ( instance , counter ) ; } else { data . put ( instance . address ( ) , Contexts . serialize ( instance ) . encode ( ) , new Handler < AsyncResult < String > > ( ) { public void handle ( AsyncResult < String > result ) { if ( result . failed ( ) ) { counter . fail ( result . cause ( ) ) ; } else { counter . succeed ( ) ; } } } ) ; } } } ) ; } } | Deploys all network component instances . |
12,876 | private void deployInstance ( final InstanceContext instance , final CountingCompletionHandler < Void > counter ) { if ( instance . component ( ) . group ( ) != null ) { cluster . getGroup ( instance . component ( ) . group ( ) , new Handler < AsyncResult < Group > > ( ) { public void handle ( AsyncResult < Group > result ) { if ( result . failed ( ) ) { counter . fail ( result . cause ( ) ) ; } else { result . result ( ) . selectNode ( instance . address ( ) , new Handler < AsyncResult < Node > > ( ) { public void handle ( AsyncResult < Node > result ) { if ( result . failed ( ) ) { counter . fail ( result . cause ( ) ) ; } else { deployInstance ( result . result ( ) , instance , counter ) ; } } } ) ; } } } ) ; } else { cluster . selectNode ( instance . address ( ) , new Handler < AsyncResult < Node > > ( ) { public void handle ( AsyncResult < Node > result ) { if ( result . failed ( ) ) { counter . fail ( result . cause ( ) ) ; } else { deployInstance ( result . result ( ) , instance , counter ) ; } } } ) ; } } | Deploys a single component instance . |
12,877 | private void deployInstance ( final Node node , final InstanceContext instance , final CountingCompletionHandler < Void > counter ) { data . put ( instance . address ( ) , Contexts . serialize ( instance ) . encode ( ) , new Handler < AsyncResult < String > > ( ) { public void handle ( AsyncResult < String > result ) { if ( result . failed ( ) ) { counter . fail ( result . cause ( ) ) ; } else { if ( ! watchHandlers . containsKey ( instance . address ( ) ) ) { final Handler < MapEvent < String , String > > watchHandler = new Handler < MapEvent < String , String > > ( ) { public void handle ( MapEvent < String , String > event ) { if ( event . type ( ) . equals ( MapEvent . Type . CREATE ) || event . type ( ) . equals ( MapEvent . Type . UPDATE ) ) { handleReady ( instance . address ( ) ) ; } else if ( event . type ( ) . equals ( MapEvent . Type . DELETE ) ) { handleUnready ( instance . address ( ) ) ; } } } ; data . watch ( instance . status ( ) , watchHandler , new Handler < AsyncResult < Void > > ( ) { public void handle ( AsyncResult < Void > result ) { if ( result . failed ( ) ) { counter . fail ( result . cause ( ) ) ; } else { watchHandlers . put ( instance . address ( ) , watchHandler ) ; if ( instance . component ( ) . isModule ( ) ) { deployModule ( node , instance , counter ) ; } else if ( instance . component ( ) . isVerticle ( ) && ! instance . component ( ) . asVerticle ( ) . isWorker ( ) ) { deployVerticle ( node , instance , counter ) ; } else if ( instance . component ( ) . isVerticle ( ) && instance . component ( ) . asVerticle ( ) . isWorker ( ) ) { deployWorkerVerticle ( node , instance , counter ) ; } } } } ) ; } else { if ( instance . component ( ) . isModule ( ) ) { deployModule ( node , instance , counter ) ; } else if ( instance . component ( ) . isVerticle ( ) && ! instance . component ( ) . asVerticle ( ) . isWorker ( ) ) { deployVerticle ( node , instance , counter ) ; } else if ( instance . component ( ) . isVerticle ( ) && instance . component ( ) . asVerticle ( ) . isWorker ( ) ) { deployWorkerVerticle ( node , instance , counter ) ; } } } } } ) ; } | Deploys an instance to a specific node . |
12,878 | private void deployModule ( final Node node , final InstanceContext instance , final CountingCompletionHandler < Void > counter ) { log . debug ( String . format ( "%s - Deploying %s to %s" , NetworkManager . this , instance . component ( ) . asModule ( ) . module ( ) , node . address ( ) ) ) ; node . deployModule ( instance . component ( ) . asModule ( ) . module ( ) , Components . buildConfig ( instance , cluster ) , 1 , new Handler < AsyncResult < String > > ( ) { public void handle ( AsyncResult < String > result ) { if ( result . failed ( ) ) { counter . fail ( result . cause ( ) ) ; } else { deploymentIDs . put ( instance . address ( ) , result . result ( ) , new Handler < AsyncResult < String > > ( ) { public void handle ( AsyncResult < String > result ) { counter . succeed ( ) ; } } ) ; } } } ) ; } | Deploys a module component instance in the network s cluster . |
12,879 | private void installModules ( final Node node , final NetworkContext context , final Handler < AsyncResult < Void > > doneHandler ) { List < ModuleContext > modules = new ArrayList < > ( ) ; for ( ComponentContext < ? > component : context . components ( ) ) { if ( component . isModule ( ) ) { modules . add ( component . asModule ( ) ) ; } } final CountingCompletionHandler < Void > counter = new CountingCompletionHandler < Void > ( modules . size ( ) ) . setHandler ( doneHandler ) ; for ( ModuleContext module : modules ) { installModule ( node , module , counter ) ; } } | Installs all modules on a node . |
12,880 | private void installModule ( final Node node , final ModuleContext module , final Handler < AsyncResult < Void > > doneHandler ) { node . installModule ( module . module ( ) , doneHandler ) ; } | Installs a module on a node . |
12,881 | private void undeployComponents ( Collection < ComponentContext < ? > > components , final CountingCompletionHandler < Void > complete ) { for ( final ComponentContext < ? > component : components ) { final CountingCompletionHandler < Void > counter = new CountingCompletionHandler < Void > ( component . instances ( ) . size ( ) ) ; counter . setHandler ( new Handler < AsyncResult < Void > > ( ) { public void handle ( AsyncResult < Void > result ) { if ( result . failed ( ) ) { complete . fail ( result . cause ( ) ) ; } else { data . remove ( component . address ( ) , new Handler < AsyncResult < String > > ( ) { public void handle ( AsyncResult < String > result ) { if ( result . failed ( ) ) { complete . fail ( result . cause ( ) ) ; } else { complete . succeed ( ) ; } } } ) ; } } } ) ; undeployInstances ( component . instances ( ) , counter ) ; } } | Undeploys all network components . |
12,882 | private void undeployInstances ( List < InstanceContext > instances , final CountingCompletionHandler < Void > counter ) { for ( final InstanceContext instance : instances ) { if ( instance . component ( ) . isModule ( ) ) { undeployModule ( instance , counter ) ; } else if ( instance . component ( ) . isVerticle ( ) ) { undeployVerticle ( instance , counter ) ; } } } | Undeploys all component instances . |
12,883 | private void unwatchInstance ( final InstanceContext instance , final CountingCompletionHandler < Void > counter ) { Handler < MapEvent < String , String > > watchHandler = watchHandlers . remove ( instance . address ( ) ) ; if ( watchHandler != null ) { data . unwatch ( instance . status ( ) , watchHandler , new Handler < AsyncResult < Void > > ( ) { public void handle ( AsyncResult < Void > result ) { data . remove ( instance . address ( ) , new Handler < AsyncResult < String > > ( ) { public void handle ( AsyncResult < String > result ) { if ( result . failed ( ) ) { counter . fail ( result . cause ( ) ) ; } else { counter . succeed ( ) ; } } } ) ; } } ) ; } else { data . remove ( instance . address ( ) , new Handler < AsyncResult < String > > ( ) { public void handle ( AsyncResult < String > result ) { if ( result . failed ( ) ) { counter . fail ( result . cause ( ) ) ; } else { counter . succeed ( ) ; } } } ) ; } } | Unwatches a component instance s status and context . |
12,884 | private void undeployModule ( final InstanceContext instance , final CountingCompletionHandler < Void > counter ) { deploymentIDs . remove ( instance . address ( ) , new Handler < AsyncResult < String > > ( ) { public void handle ( AsyncResult < String > result ) { if ( result . failed ( ) ) { counter . fail ( result . cause ( ) ) ; } else if ( result . result ( ) != null ) { cluster . undeployModule ( result . result ( ) , new Handler < AsyncResult < Void > > ( ) { public void handle ( AsyncResult < Void > result ) { unwatchInstance ( instance , counter ) ; } } ) ; } else { unwatchInstance ( instance , counter ) ; } } } ) ; } | Undeploys a module component instance . |
12,885 | private void updateNetwork ( final NetworkContext context , final Handler < AsyncResult < Void > > doneHandler ) { final CountingCompletionHandler < Void > complete = new CountingCompletionHandler < Void > ( context . components ( ) . size ( ) ) ; complete . setHandler ( new Handler < AsyncResult < Void > > ( ) { public void handle ( AsyncResult < Void > result ) { if ( result . failed ( ) ) { new DefaultFutureResult < Void > ( result . cause ( ) ) . setHandler ( doneHandler ) ; } else { new DefaultFutureResult < Void > ( ( Void ) null ) . setHandler ( doneHandler ) ; } } } ) ; updateComponents ( context . components ( ) , complete ) ; } | Updates a network . |
12,886 | private void updateComponents ( Collection < ComponentContext < ? > > components , final CountingCompletionHandler < Void > complete ) { for ( final ComponentContext < ? > component : components ) { final CountingCompletionHandler < Void > counter = new CountingCompletionHandler < Void > ( component . instances ( ) . size ( ) ) ; counter . setHandler ( new Handler < AsyncResult < Void > > ( ) { public void handle ( AsyncResult < Void > result ) { if ( result . failed ( ) ) { complete . fail ( result . cause ( ) ) ; } else { complete . succeed ( ) ; } } } ) ; updateInstances ( component . instances ( ) , counter ) ; } } | Updates all network components . |
12,887 | private void updateInstances ( List < InstanceContext > instances , final CountingCompletionHandler < Void > counter ) { for ( final InstanceContext instance : instances ) { data . put ( instance . address ( ) , Contexts . serialize ( instance ) . encode ( ) , new Handler < AsyncResult < String > > ( ) { public void handle ( AsyncResult < String > result ) { if ( result . failed ( ) ) { counter . fail ( result . cause ( ) ) ; } else { counter . succeed ( ) ; } } } ) ; } } | Updates all component instances . |
12,888 | private void doNodeJoined ( final Node node ) { tasks . runTask ( new Handler < Task > ( ) { public void handle ( final Task task ) { if ( currentContext != null ) { log . info ( String . format ( "%s - %s joined the cluster. Uploading components to new node" , NetworkManager . this , node . address ( ) ) ) ; installModules ( node , currentContext , new Handler < AsyncResult < Void > > ( ) { public void handle ( AsyncResult < Void > result ) { if ( result . failed ( ) ) { log . error ( result . cause ( ) ) ; } else { log . info ( String . format ( "%s - Successfully uploaded components to %s" , NetworkManager . this , node . address ( ) ) ) ; } task . complete ( ) ; } } ) ; } else { task . complete ( ) ; } } } ) ; } | Handles a node joining the cluster . |
12,889 | private void doNodeLeft ( final Node node ) { tasks . runTask ( new Handler < Task > ( ) { public void handle ( final Task task ) { if ( currentContext != null ) { log . info ( String . format ( "%s - %s left the cluster. Reassigning components" , NetworkManager . this , node . address ( ) ) ) ; deploymentNodes . keySet ( new Handler < AsyncResult < Set < String > > > ( ) { public void handle ( AsyncResult < Set < String > > result ) { if ( result . succeeded ( ) ) { final CountingCompletionHandler < Void > counter = new CountingCompletionHandler < Void > ( result . result ( ) . size ( ) ) ; counter . setHandler ( new Handler < AsyncResult < Void > > ( ) { public void handle ( AsyncResult < Void > result ) { task . complete ( ) ; } } ) ; for ( final String instanceAddress : result . result ( ) ) { deploymentNodes . get ( instanceAddress , new Handler < AsyncResult < String > > ( ) { public void handle ( AsyncResult < String > result ) { if ( result . succeeded ( ) && result . result ( ) . equals ( node . address ( ) ) ) { data . get ( instanceAddress , new Handler < AsyncResult < String > > ( ) { public void handle ( AsyncResult < String > result ) { if ( result . succeeded ( ) && result . result ( ) != null ) { deployInstance ( Contexts . < InstanceContext > deserialize ( new JsonObject ( result . result ( ) ) ) , counter ) ; } else { counter . succeed ( ) ; } } } ) ; } else { counter . succeed ( ) ; } } } ) ; } } } } ) ; } else { task . complete ( ) ; } } } ) ; } | Handles a node leaving the cluster . |
12,890 | private void disconnect ( final Handler < AsyncResult < Void > > doneHandler ) { eventBus . sendWithTimeout ( inAddress , new JsonObject ( ) . putString ( "action" , "disconnect" ) , 5000 , new Handler < AsyncResult < Message < Boolean > > > ( ) { public void handle ( AsyncResult < Message < Boolean > > result ) { if ( result . failed ( ) ) { ReplyException failure = ( ReplyException ) result . cause ( ) ; if ( failure . failureType ( ) . equals ( ReplyFailure . RECIPIENT_FAILURE ) ) { log . warn ( String . format ( "%s - Failed to disconnect from %s" , DefaultOutputConnection . this , context . target ( ) ) , result . cause ( ) ) ; new DefaultFutureResult < Void > ( failure ) . setHandler ( doneHandler ) ; } else if ( failure . failureType ( ) . equals ( ReplyFailure . NO_HANDLERS ) ) { log . info ( String . format ( "%s - Disconnected from %s" , DefaultOutputConnection . this , context . target ( ) ) ) ; new DefaultFutureResult < Void > ( ( Void ) null ) . setHandler ( doneHandler ) ; } else { log . debug ( String . format ( "%s - Disconnection from %s failed, retrying" , DefaultOutputConnection . this , context . target ( ) ) ) ; disconnect ( doneHandler ) ; } } else if ( result . result ( ) . body ( ) ) { log . info ( String . format ( "%s - Disconnected from %s" , DefaultOutputConnection . this , context . target ( ) ) ) ; open = false ; new DefaultFutureResult < Void > ( ( Void ) null ) . setHandler ( doneHandler ) ; } else { log . debug ( String . format ( "%s - Disconnection from %s failed, retrying" , DefaultOutputConnection . this , context . target ( ) ) ) ; vertx . setTimer ( 500 , new Handler < Long > ( ) { public void handle ( Long timerID ) { disconnect ( doneHandler ) ; } } ) ; } } } ) ; } | Disconnects from the other side of the connection . |
12,891 | private void checkFull ( ) { if ( ! full && messages . size ( ) >= maxQueueSize ) { full = true ; log . debug ( String . format ( "%s - Connection to %s is full" , this , context . target ( ) ) ) ; } } | Checks whether the connection is full . |
12,892 | private void checkDrain ( ) { if ( full && ! paused && messages . size ( ) < maxQueueSize / 2 ) { full = false ; log . debug ( String . format ( "%s - Connection to %s is drained" , this , context . target ( ) ) ) ; if ( drainHandler != null ) { drainHandler . handle ( ( Void ) null ) ; } } } | Checks whether the connection has been drained . |
12,893 | private void doAck ( long id ) { if ( log . isDebugEnabled ( ) ) { log . debug ( String . format ( "%s - Received ack for messages up to %d, removing all previous messages from memory" , this , id ) ) ; } if ( messages . containsKey ( id + 1 ) ) { messages . tailMap ( id + 1 ) ; } else { messages . clear ( ) ; } checkDrain ( ) ; } | Handles a batch ack . |
12,894 | private void doFail ( long id ) { if ( log . isDebugEnabled ( ) ) { log . debug ( String . format ( "%s - Received resend request for messages starting at %d" , this , id ) ) ; } doAck ( id ) ; Iterator < Map . Entry < Long , JsonObject > > iter = messages . entrySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { eventBus . send ( inAddress , iter . next ( ) . getValue ( ) ) ; } } | Handles a batch fail . |
12,895 | private void doPause ( long id ) { log . debug ( String . format ( "%s - Paused connection to %s" , this , context . target ( ) ) ) ; paused = true ; } | Handles a connection pause . |
12,896 | private void doResume ( long id ) { if ( paused ) { log . debug ( String . format ( "%s - Resumed connection to %s" , this , context . target ( ) ) ) ; paused = false ; checkDrain ( ) ; } } | Handles a connection resume . |
12,897 | void doGroupStart ( String group , String name , Object args , String parent ) { checkOpen ( ) ; JsonObject message = createMessage ( args ) . putString ( "group" , group ) . putString ( "name" , name ) . putString ( "parent" , parent ) . putString ( "action" , "startGroup" ) ; if ( open && ! paused ) { if ( log . isDebugEnabled ( ) ) { if ( parent != null ) { log . debug ( String . format ( "%s - Group start: Group[name=%s, group=%s, parent=%s, args=%s]" , this , name , group , parent , args ) ) ; } else { log . debug ( String . format ( "%s - Group start: Group[name=%s, group=%s, args=%s]" , this , name , group , args ) ) ; } } eventBus . send ( inAddress , message ) ; } checkFull ( ) ; } | Sends a group start message . |
12,898 | void doGroupSend ( String group , Object value ) { checkOpen ( ) ; JsonObject message = createMessage ( value ) . putString ( "action" , "group" ) . putString ( "group" , group ) ; if ( open && ! paused ) { if ( log . isDebugEnabled ( ) ) { log . debug ( String . format ( "%s - Group send: Group[group=%s, id=%d, message=%s" , this , group , message . getLong ( "id" ) , value ) ) ; } eventBus . send ( inAddress , message ) ; } for ( OutputHook hook : hooks ) { hook . handleSend ( value ) ; } checkFull ( ) ; } | Sends a group message . |
12,899 | void doGroupEnd ( String group , Object args ) { checkOpen ( ) ; JsonObject message = createMessage ( args ) . putString ( "action" , "endGroup" ) . putString ( "group" , group ) ; if ( open && ! paused ) { if ( log . isDebugEnabled ( ) ) { log . debug ( String . format ( "%s - Group end: Group[group=%s, args=%s]" , this , group , args ) ) ; } eventBus . send ( inAddress , message ) ; } groups . remove ( group ) ; } | Sends a group end message . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.