Input: Creates the interpreter and launches its top - level run loop . [CODESPLIT] public static void main ( String [ ] args ) { try { SymbolTableImpl < Integer , String , Object > symbolTable = new SymbolTableImpl < Integer , String , Object > ( ) ; WAMResolvingMachine machine = new WAMResolvingNativeMachine ( symbolTable ) ; Parser < Clause , Token > parser = new SentenceParser ( machine ) ; parser . setTokenSource ( TokenSource . getTokenSourceForInputStream ( System . in ) ) ; LogicCompiler < Clause , WAMCompiledPredicate , WAMCompiledQuery > compiler = new WAMCompiler ( symbolTable , machine ) ; ResolutionEngine < Clause , WAMCompiledPredicate , WAMCompiledQuery > engine = new WAMEngine ( parser , machine , compiler , machine ) ; engine . reset ( ) ; ResolutionInterpreter < WAMCompiledPredicate , WAMCompiledQuery > interpreter = new ResolutionInterpreter < WAMCompiledPredicate , WAMCompiledQuery > ( engine ) ; interpreter . interpreterLoop ( ) ; } catch ( Exception e ) { /*log.log(java.util.logging.Level.SEVERE, e.getMessage(), e);*/ e . printStackTrace ( new PrintStream ( System . err ) ) ; System . exit ( - 1 ) ; } }


Input: { @inheritDoc } [CODESPLIT] public void mousePressed ( MouseEvent e ) { gripComponent . setCursor ( moveCursor ) ; pressed = true ; lastY = e . getYOnScreen ( ) ; lastX = e . getXOnScreen ( ) ; }


Input: { @inheritDoc } [CODESPLIT] public void mouseDragged ( MouseEvent e ) { if ( pressed ) { int deltaY = e . getYOnScreen ( ) - lastY ; lastY = e . getYOnScreen ( ) ; int deltaX = e . getXOnScreen ( ) - lastX ; lastX = e . getXOnScreen ( ) ; boolean revalidate = false ; if ( deltaY != 0 ) { resizeable . deltaY ( - deltaY ) ; revalidate = true ; } if ( deltaX != 0 ) { resizeable . deltaX ( - deltaX ) ; revalidate = true ; } if ( revalidate ) { SwingUtilities . invokeLater ( new Runnable ( ) { public void run ( ) { gripComponent . getParent ( ) . revalidate ( ) ; } } ) ; } } }


Input: ---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void getRequestsPath ( ) throws InterruptedException { server ( ) . enqueue ( new MockResponse ( ) ) ; newBrowser ( ) . get ( url ( server ( ) , "/x" ) ) ; assertThat ( "request path" , server ( ) . takeRequest ( ) . getPath ( ) , is ( "/x" ) ) ; }


Input: ---------------------------------------------------------------------------------------------------------------- [CODESPLIT] public final Link getLink ( String rel ) { List < Link > links = getLinks ( rel ) ; if ( links . isEmpty ( ) ) { throw new LinkNotFoundException ( rel ) ; } return links . get ( 0 ) ; }


Input: Pops the first object placed on the stack off of it and returns it . [CODESPLIT] public E pop ( ) { E ob ; if ( size ( ) == 0 ) { return null ; } ob = get ( 0 ) ; remove ( 0 ) ; return ob ; }


Input: { [CODESPLIT] public T nextInSequence ( ) { T result = null ; // Poll results from the buffer until no more are available, but only once the state machine has flushed // the buffer. if ( flushMode ) { result = buffer . poll ( ) ; if ( result != null ) { return result ; } flushMode = false ; } // Feed input from the source into the state machine, until some results become available on the buffer. while ( source . hasNext ( ) ) { S next = source . next ( ) ; fsm . apply ( next ) ; if ( flushMode ) { result = buffer . poll ( ) ; if ( result != null ) { return result ; } flushMode = false ; } } // Once the end of the input source is reached, inform the state machine of this, and try and poll any // buffered results. fsm . end ( ) ; if ( flushMode ) { result = buffer . poll ( ) ; } return result ; }


Input: { [CODESPLIT] public void onReset ( WAMResolvingMachineDPI dpi ) { System . out . println ( "reset" ) ; tableModel = new TextTableImpl ( ) ; layoutRegisters = new InternalMemoryLayoutBean ( 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ) ; layoutRegisters . addPropertyChangeListener ( this ) ; layoutRegisters . updateRegisters ( layoutRegisters ) ; internalRegisters = new InternalRegisterBean ( 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , false ) ; internalRegisters . addPropertyChangeListener ( this ) ; internalRegisters . updateRegisters ( dpi . getInternalRegisters ( ) ) ; }


Input: { [CODESPLIT] public void onCodeUpdate ( WAMResolvingMachineDPI dpi , int start , int length ) { System . out . println ( "Code updated, " + length + " bytes at " + start + "." ) ; tableModel = new TextTableImpl ( ) ; ByteBuffer code = dpi . getCodeBuffer ( start , length ) ; SizeableList < WAMInstruction > instructions = WAMInstruction . disassemble ( start , length , code , dpi . getVariableAndFunctorInterner ( ) , dpi ) ; int row = 0 ; for ( WAMInstruction instruction : instructions ) { if ( instruction . getLabel ( ) != null ) { tableModel . put ( 0 , row , instruction . getLabel ( ) . toPrettyString ( ) ) ; } tableModel . put ( 1 , row , instruction . toString ( ) ) ; row ++ ; } printTable ( tableModel ) ; }


Input: Renders the table . [CODESPLIT] protected void printTable ( TextTableModel printTable ) { for ( int i = 0 ; i < printTable . getRowCount ( ) ; i ++ ) { StringBuffer result = new StringBuffer ( ) ; for ( int j = 0 ; j < printTable . getColumnCount ( ) ; j ++ ) { String valueToPrint = printTable . get ( j , i ) ; valueToPrint = ( valueToPrint == null ) ? "" : valueToPrint ; result . append ( valueToPrint ) ; Integer maxColumnSize = printTable . getMaxColumnSize ( j ) ; int padding = ( ( maxColumnSize == null ) ? 0 : maxColumnSize ) - valueToPrint . length ( ) ; padding = ( padding < 0 ) ? 0 : padding ; for ( int s = 0 ; s < padding ; s ++ ) { result . append ( " " ) ; } result . append ( " % " ) ; } result . append ( "\n" ) ; System . out . print ( result ) ; } }


Input: { [CODESPLIT] public KeyStroke withKey ( String key ) { // Extract the modifiers as a specification string. String keyString = modifiersToString ( modifiers ) ; // Reset the modifiers so the builder can be used again. modifiers = 0 ; return KeyStroke . getKeyStroke ( keyString + key ) ; }


Input: Converts the modifiers to a specification string for KeyStroke . [CODESPLIT] private String modifiersToString ( int modifiers ) { String result = "" ; if ( ( modifiers & InputEvent . SHIFT_MASK ) != 0 ) { result += "shift " ; } if ( ( modifiers & InputEvent . CTRL_MASK ) != 0 ) { result += "ctrl " ; } if ( ( modifiers & InputEvent . META_MASK ) != 0 ) { result += "meta " ; } if ( ( modifiers & InputEvent . ALT_MASK ) != 0 ) { result += "alt " ; } if ( ( modifiers & InputEvent . ALT_GRAPH_MASK ) != 0 ) { result += "altGraph " ; } return result ; }


Input: { [CODESPLIT] public void insertAttribute ( AttributeSet attributes , int c , int r ) { attributeGrid . insertAttribute ( attributes , c , r ) ; updateListenersOnAttributeChange ( c , r ) ; }


Input: { [CODESPLIT] public void insertColumnAttribute ( AttributeSet attributes , int c ) { attributeGrid . insertColumnAttribute ( attributes , c ) ; updateListenersOnAttributeChange ( c , - 1 ) ; }


Input: { [CODESPLIT] public void insertRowAttribute ( AttributeSet attributes , int r ) { attributeGrid . insertRowAttribute ( attributes , r ) ; updateListenersOnAttributeChange ( - 1 , r ) ; }


Input: Notifies all interested listeners of an update to this model . [CODESPLIT] protected void updateListenersOnAttributeChange ( int col , int row ) { TextTableEvent event = new TextTableEvent ( this , row , col , true ) ; for ( TextTableListener listener : listeners ) { listener . changedUpdate ( event ) ; } }


Input: Converts a string to an integer . The string must be a valid integer or the result will be zero . [CODESPLIT] public static int toInteger ( String s ) { try { return Integer . parseInt ( s ) ; } catch ( NumberFormatException e ) { // Exception noted so can be ignored. e = null ; return 0 ; } }


Input: Converts a string to a date . The string must be a date in the correct format or this method will return null . [CODESPLIT] public static Date toDate ( String s ) { // Build a date formatter using the format specified by dateFormat DateFormat dateFormatter = new SimpleDateFormat ( dateFormat ) ; try { return dateFormatter . parse ( s ) ; } catch ( ParseException e ) { // Exception noted so can be ignored. e = null ; return null ; } }


Input: Check that a string is a date in the format specified by dateFormat . [CODESPLIT] public static boolean isDate ( String s ) { // Build a date formatter using the format specified by dateFormat DateFormat dateFormatter = new SimpleDateFormat ( dateFormat ) ; try { dateFormatter . parse ( s ) ; return true ; } catch ( ParseException e ) { // Exception noted so can be ignored. e = null ; return false ; } }


Input: Checks that a string is a time in the format specified by timeFormat . [CODESPLIT] public static boolean isTime ( String s ) { // Build a time formatter using the format specified by timeFormat DateFormat dateFormatter = new SimpleDateFormat ( timeFormat ) ; try { dateFormatter . parse ( s ) ; return true ; } catch ( ParseException e ) { // Exception noted so can be ignored. e = null ; return false ; } }


Input: Checks that a string is a datetime in the format specified by dateTimeFormat . [CODESPLIT] public static boolean isDateTime ( String s ) { DateFormat dateFormatter = new SimpleDateFormat ( dateTimeFormat ) ; try { dateFormatter . parse ( s ) ; return true ; } catch ( ParseException e ) { // Exception noted so can be ignored. e = null ; return false ; } }


Input: Creates a token source on a string . [CODESPLIT] public static TokenSource getTokenSourceForString ( String stringToTokenize ) { SimpleCharStream inputStream = new SimpleCharStream ( new StringReader ( stringToTokenize ) , 1 , 1 ) ; PrologParserTokenManager tokenManager = new PrologParserTokenManager ( inputStream ) ; return new TokenSource ( tokenManager ) ; }


Input: Creates a token source on a file . [CODESPLIT] public static TokenSource getTokenSourceForFile ( File file ) throws FileNotFoundException { // Create a token source to load the model rules from. Reader ins = new FileReader ( file ) ; SimpleCharStream inputStream = new SimpleCharStream ( ins , 1 , 1 ) ; PrologParserTokenManager tokenManager = new PrologParserTokenManager ( inputStream ) ; return new TokenSource ( tokenManager ) ; }


Input: Creates a token source on an input stream . [CODESPLIT] public static Source getTokenSourceForInputStream ( InputStream in ) { SimpleCharStream inputStream = new SimpleCharStream ( in , 1 , 1 ) ; PrologParserTokenManager tokenManager = new PrologParserTokenManager ( inputStream ) ; return new TokenSource ( tokenManager ) ; }


Input: Retrieves and removes the head token or <tt > null< / tt > if there are no more tokens . [CODESPLIT] public Token poll ( ) { if ( token . next == null ) { token . next = tokenManager . getNextToken ( ) ; } token = token . next ; return token ; }


Input: Retrieves but does not remove the head token returning <tt > null< / tt > if there are no more tokens . [CODESPLIT] public Token peek ( ) { if ( token . next == null ) { token . next = tokenManager . getNextToken ( ) ; } return token . next ; }


Input: { [CODESPLIT] public void apply ( WAMInstruction next ) { shift ( next ) ; // Anonymous or singleton variable optimizations. if ( ( UnifyVar == next . getMnemonic ( ) ) && isVoidVariable ( next ) ) { if ( state != State . UVE ) { voidCount = 0 ; } discard ( ( voidCount == 0 ) ? 1 : 2 ) ; WAMInstruction unifyVoid = new WAMInstruction ( UnifyVoid , WAMInstruction . REG_ADDR , ( byte ) ++ voidCount ) ; shift ( unifyVoid ) ; state = State . UVE ; /*log.fine(next + " -> " + unifyVoid);*/ } else if ( ( SetVar == next . getMnemonic ( ) ) && isVoidVariable ( next ) ) { if ( state != State . SVE ) { voidCount = 0 ; } discard ( ( voidCount == 0 ) ? 1 : 2 ) ; WAMInstruction setVoid = new WAMInstruction ( SetVoid , WAMInstruction . REG_ADDR , ( byte ) ++ voidCount ) ; shift ( setVoid ) ; state = State . SVE ; /*log.fine(next + " -> " + setVoid);*/ } else if ( ( GetVar == next . getMnemonic ( ) ) && ( next . getMode1 ( ) == WAMInstruction . REG_ADDR ) && ( next . getReg1 ( ) == next . getReg2 ( ) ) ) { discard ( 1 ) ; /*log.fine(next + " -> eliminated");*/ state = State . NM ; } // Constant optimizations. else if ( ( UnifyVar == next . getMnemonic ( ) ) && isConstant ( next ) && isNonArg ( next ) ) { discard ( 1 ) ; FunctorName functorName = interner . getDeinternedFunctorName ( next . getFunctorNameReg1 ( ) ) ; WAMInstruction unifyConst = new WAMInstruction ( UnifyConstant , functorName ) ; shift ( unifyConst ) ; flush ( ) ; state = State . NM ; /*log.fine(next + " -> " + unifyConst);*/ } else if ( ( GetStruc == next . getMnemonic ( ) ) && isConstant ( next ) && isNonArg ( next ) ) { discard ( 1 ) ; state = State . NM ; /*log.fine(next + " -> eliminated");*/ } else if ( ( GetStruc == next . getMnemonic ( ) ) && isConstant ( next ) && ! isNonArg ( next ) ) { discard ( 1 ) ; WAMInstruction getConst = new WAMInstruction ( GetConstant , next . getMode1 ( ) , next . getReg1 ( ) , next . getFn ( ) ) ; shift ( getConst ) ; flush ( ) ; state = State . NM ; /*log.fine(next + " -> " + getConst);*/ } else if ( ( PutStruc == next . getMnemonic ( ) ) && isConstant ( next ) && isNonArg ( next ) ) { discard ( 1 ) ; state = State . NM ; /*log.fine(next + " -> eliminated");*/ } else if ( ( PutStruc == next . getMnemonic ( ) ) && isConstant ( next ) && ! isNonArg ( next ) ) { discard ( 1 ) ; WAMInstruction putConst = new WAMInstruction ( PutConstant , next . getMode1 ( ) , next . getReg1 ( ) , next . getFn ( ) ) ; shift ( putConst ) ; state = State . NM ; /*log.fine(next + " -> " + putConst);*/ } else if ( ( SetVal == next . getMnemonic ( ) ) && isConstant ( next ) && isNonArg ( next ) ) { discard ( 1 ) ; FunctorName functorName = interner . getDeinternedFunctorName ( next . getFunctorNameReg1 ( ) ) ; WAMInstruction setConst = new WAMInstruction ( SetConstant , functorName ) ; shift ( setConst ) ; flush ( ) ; state = State . NM ; /*log.fine(next + " -> " + setConst);*/ } // List optimizations. else if ( ( GetStruc == next . getMnemonic ( ) ) && ( "cons" . equals ( next . getFn ( ) . getName ( ) ) && ( next . getFn ( ) . getArity ( ) == 2 ) ) ) { discard ( 1 ) ; WAMInstruction getList = new WAMInstruction ( GetList , next . getMode1 ( ) , next . getReg1 ( ) ) ; shift ( getList ) ; state = State . NM ; /*log.fine(next + " -> " + getList);*/ } else if ( ( PutStruc == next . getMnemonic ( ) ) && ( "cons" . equals ( next . getFn ( ) . getName ( ) ) && ( next . getFn ( ) . getArity ( ) == 2 ) ) ) { discard ( 1 ) ; WAMInstruction putList = new WAMInstruction ( PutList , next . getMode1 ( ) , next . getReg1 ( ) ) ; shift ( putList ) ; state = State . NM ; /*log.fine(next + " -> " + putList);*/ } // Default. else { state = State . NM ; flush ( ) ; } }


Input: Checks if the term argument to an instruction was a constant . [CODESPLIT] public boolean isConstant ( WAMInstruction instruction ) { Integer name = instruction . getFunctorNameReg1 ( ) ; if ( name != null ) { FunctorName functorName = interner . getDeinternedFunctorName ( name ) ; if ( functorName . getArity ( ) == 0 ) { return true ; } } return false ; }


Input: Checks if the term argument to an instruction was a singleton non - argument position variable . The variable must also be non - permanent to ensure that singleton variables in queries are created . [CODESPLIT] private boolean isVoidVariable ( WAMInstruction instruction ) { SymbolKey symbolKey = instruction . getSymbolKeyReg1 ( ) ; if ( symbolKey != null ) { Integer count = ( Integer ) symbolTable . get ( symbolKey , SymbolTableKeys . SYMKEY_VAR_OCCURRENCE_COUNT ) ; Boolean nonArgPositionOnly = ( Boolean ) symbolTable . get ( symbolKey , SymbolTableKeys . SYMKEY_VAR_NON_ARG ) ; Integer allocation = ( Integer ) symbolTable . get ( symbolKey , SymbolTableKeys . SYMKEY_ALLOCATION ) ; boolean singleton = ( count != null ) && count . equals ( 1 ) ; boolean nonArgPosition = ( nonArgPositionOnly != null ) && TRUE . equals ( nonArgPositionOnly ) ; boolean permanent = ( allocation != null ) && ( ( byte ) ( ( allocation & 0xff00 ) >> 8 ) == WAMInstruction . STACK_ADDR ) ; if ( singleton && nonArgPosition && ! permanent ) { return true ; } } return false ; }


Input: Checks if the term argument to an instruction was in a non - argument position . [CODESPLIT] private boolean isNonArg ( WAMInstruction instruction ) { SymbolKey symbolKey = instruction . getSymbolKeyReg1 ( ) ; if ( symbolKey != null ) { Boolean nonArgPositionOnly = ( Boolean ) symbolTable . get ( symbolKey , SymbolTableKeys . SYMKEY_FUNCTOR_NON_ARG ) ; if ( TRUE . equals ( nonArgPositionOnly ) ) { return true ; } } return false ; }


Input: { [CODESPLIT] protected TermBuilder < com . thesett . aima . logic . fol . Term > createCompoundBuilder ( ) { return new LojixTermBuilder ( interner ) ; }


Input: Renders the table . [CODESPLIT] public void renderTable ( ) { for ( int i = 0 ; i < tableModel . getRowCount ( ) ; i ++ ) { int colOffset = 0 ; for ( int j = 0 ; j < tableModel . getColumnCount ( ) ; j ++ ) { String valueToPrint = tableModel . get ( j , i ) ; valueToPrint = ( valueToPrint == null ) ? "" : valueToPrint ; gridModel . insert ( valueToPrint , colOffset , i ) ; AttributeSet attributes = tableModel . getAttributeAt ( j , i ) ; int columnSize = tableModel . getMaxColumnSize ( j ) ; if ( attributes != null ) { for ( int k = 0 ; k < columnSize ; k ++ ) { gridModel . insertAttribute ( attributes , colOffset + k , i ) ; } } // Pad spaces up to the column width if the contents are shorter. int spaces = columnSize - valueToPrint . length ( ) ; while ( spaces > 0 ) { gridModel . insert ( " " , colOffset + valueToPrint . length ( ) + spaces -- - 1 , i ) ; } // Shift to the next column. colOffset += columnSize ; } } }


Input: Provides an iterator over the child terms if there are any . Only functors and clauses are compound and build across a list of child arguments . [CODESPLIT] public Iterator < Operator < Term > > getChildren ( boolean reverse ) { if ( ( traverser != null ) && ( traverser instanceof ClauseTraverser ) ) { return ( ( ClauseTraverser ) traverser ) . traverse ( this , reverse ) ; } else { LinkedList < Operator < Term >> resultList = null ; if ( ! reverse ) { resultList = new LinkedList < Operator < Term > > ( ) ; } else { resultList = new StackQueue < Operator < Term > > ( ) ; } if ( head != null ) { resultList . add ( head ) ; } if ( body != null ) { for ( Term bodyTerm : body ) { resultList . add ( bodyTerm ) ; } } return resultList . iterator ( ) ; } }


Input: Makes a clone of the term converting its variables to refer directly to their storage cells . [CODESPLIT] public Clause queryConversion ( ) { Clause copy = ( Clause ) super . queryConversion ( ) ; if ( head != null ) { copy . head = head . queryConversion ( ) ; } if ( body != null ) { copy . body = new Functor [ body . length ] ; for ( int i = 0 ; i < body . length ; i ++ ) { copy . body [ i ] = body [ i ] . queryConversion ( ) ; } } return copy ; }


Input: { [CODESPLIT] public void accept ( TermVisitor visitor ) { if ( visitor instanceof ClauseVisitor ) { ( ( ClauseVisitor ) visitor ) . visit ( this ) ; } else { super . accept ( visitor ) ; } }


Input: { [CODESPLIT] public Clause acceptTransformer ( TermTransformer transformer ) { Clause result ; if ( transformer instanceof ClauseTransformer ) { result = ( ( ClauseTransformer ) transformer ) . transform ( this ) ; } else { result = ( Clause ) super . acceptTransformer ( transformer ) ; } if ( head != null ) { result . head = ( Functor ) head . acceptTransformer ( transformer ) ; } if ( body != null ) { for ( int i = 0 ; i < body . length ; i ++ ) { result . body [ i ] = ( Functor ) body [ i ] . acceptTransformer ( transformer ) ; } } return result ; }


Input: Works out all the possible successors by applying all the operators returned by the { @link Traversable#validOperators } method . [CODESPLIT] public Iterator < Successor < O > > successors ( boolean reverse ) { return new Filterator < Operator < O > , Successor < O > > ( validOperators ( reverse ) , new Function < Operator < O > , Successor < O > > ( ) { public Successor < O > apply ( Operator operator ) { return new Successor < O > ( getChildStateForOperator ( operator ) , operator , costOf ( operator ) ) ; } } ) ; }


Input: Reports whether or not this term is a ground term . Constants ( functors of arity zero ) and numbers are ground terms as are functors all of the arguments of which are ground term . [CODESPLIT] public boolean isGround ( ) { for ( int i = 0 ; i < arity ; i ++ ) { if ( ! arguments [ i ] . isGround ( ) ) { return false ; } } return true ; }


Input: Gets the argument within the functor with the specified index . [CODESPLIT] public Term getArgument ( int index ) { if ( ( arguments == null ) || ( index > ( arguments . length - 1 ) ) ) { return null ; } else { return arguments [ index ] ; } }


Input: Compares this term for structural equality with another . Two terms are structurally equal if they are the same functor with the same arguments or are the same unbound variable or the bound values of the left or right variable operands are structurally equal . Structural equality is a stronger equality than unification and unlike unification it does not produce any variable bindings . Two unified terms will always be structurally equal . [CODESPLIT] public boolean structuralEquals ( Term term ) { Term comparator = term . getValue ( ) ; if ( this == comparator ) { return true ; } if ( ( comparator == null ) || ! ( getClass ( ) . isAssignableFrom ( comparator . getClass ( ) ) ) ) { return false ; } Functor functor = ( Functor ) comparator ; if ( ( arity != functor . arity ) || ( name != functor . name ) ) { return false ; } // Check the arguments of this functor and the comparator for structural equality. boolean passedArgCheck = true ; if ( arguments != null ) { for ( int i = 0 ; i < arguments . length ; i ++ ) { Term leftArg = arguments [ i ] ; Term rightArg = functor . arguments [ i ] ; if ( ! leftArg . structuralEquals ( rightArg ) ) { passedArgCheck = false ; break ; } } } return passedArgCheck ; }


Input: Provides an iterator over the child terms if there are any . Only functors are compound and built across a list of child arguments . [CODESPLIT] public Iterator < Operator < Term > > getChildren ( boolean reverse ) { if ( ( traverser != null ) && ( traverser instanceof FunctorTraverser ) ) { return ( ( FunctorTraverser ) traverser ) . traverse ( this , reverse ) ; } else { if ( arguments == null ) { return new LinkedList < Operator < Term > > ( ) . iterator ( ) ; } else if ( ! reverse ) { return Arrays . asList ( ( Operator < Term > [ ] ) arguments ) . iterator ( ) ; } else { List < Operator < Term >> argList = new LinkedList < Operator < Term > > ( ) ; for ( int i = arity - 1 ; i >= 0 ; i -- ) { argList . add ( arguments [ i ] ) ; } return argList . iterator ( ) ; } } }


Input: Makes a clone of the term converting its variables to refer directly to their storage cells . [CODESPLIT] public Functor queryConversion ( ) { /*log.fine("public Functor queryConversion(): called)");*/ Functor copy = ( Functor ) super . queryConversion ( ) ; if ( arguments != null ) { copy . arguments = new Term [ arguments . length ] ; for ( int i = 0 ; i < arguments . length ; i ++ ) { copy . arguments [ i ] = arguments [ i ] . queryConversion ( ) ; } } return copy ; }


Input: { [CODESPLIT] public void accept ( TermVisitor visitor ) { if ( visitor instanceof FunctorVisitor ) { ( ( FunctorVisitor ) visitor ) . visit ( this ) ; } else { super . accept ( visitor ) ; } }


Input: { [CODESPLIT] public Functor acceptTransformer ( TermTransformer transformer ) { Functor result ; if ( transformer instanceof FunctorTransformer ) { result = ( ( FunctorTransformer ) transformer ) . transform ( this ) ; } else { result = ( Functor ) super . acceptTransformer ( transformer ) ; } if ( arguments != null ) { for ( int i = 0 ; i < arguments . length ; i ++ ) { result . arguments [ i ] = arguments [ i ] . acceptTransformer ( transformer ) ; } } return result ; }


Input: Creates a string representation of this functors arguments mostly used for debugging purposes . [CODESPLIT] protected String toStringArguments ( ) { String result = "" ; if ( arity > 0 ) { result += "[ " ; for ( int i = 0 ; i < arity ; i ++ ) { Term nextArg = arguments [ i ] ; result += ( ( nextArg != null ) ? nextArg . toString ( ) : "<null>" ) + ( ( i < ( arity - 1 ) ) ? ", " : " " ) ; } result += " ]" ; } return result ; }


Input: Execute a query to retrieve the summary . This do not have any group by element [CODESPLIT] public < T extends MeasureAppender > T retrieveSummary ( SchemaDefinition schemaDefinition , Class < T > resultClazz , QueryParameter queryParameter ) throws NovieRuntimeException { final SqlQueryBuilder < T > sqlQueryBuilder = new SqlQueryBuilder < T > ( schemaDefinition , resultClazz , queryParameter . partialCopy ( QueryParameterKind . GROUPS , QueryParameterKind . PAGE ) ) ; List < T > result = executeQuery ( sqlQueryBuilder ) ; if ( result . isEmpty ( ) ) { throw new NovieRuntimeException ( "Summary doesn't return any result." ) ; } if ( result . size ( ) > 1 ) { throw new NovieRuntimeException ( "Summary returns more than one result." ) ; } return result . get ( 0 ) ; }


Input: Execute a query to retrieve the records . [CODESPLIT] public < T extends MeasureAppender > List < T > retrieveRecords ( SchemaDefinition schemaDefinition , Class < T > resultClazz , QueryParameter queryParameter ) throws NovieRuntimeException { final SqlQueryBuilder < T > sqlQueryBuilder = new SqlQueryBuilder < T > ( schemaDefinition , resultClazz , queryParameter ) ; return executeQuery ( sqlQueryBuilder ) ; }


Input: Private methode called by the public ones to effectively run the query . [CODESPLIT] private < T extends MeasureAppender > List < T > executeQuery ( final SqlQueryBuilder < T > sqlQueryBuilder ) throws NovieRuntimeException { sqlQueryBuilder . buildQuery ( ) ; final String queryString = sqlQueryBuilder . getQueryString ( ) ; LOG . debug ( queryString ) ; long beforeQuery = System . currentTimeMillis ( ) ; List < T > returnValue = jdbcTemplate . query ( queryString , sqlQueryBuilder . getMapSqlParameterSource ( ) , sqlQueryBuilder ) ; if ( LOG . isInfoEnabled ( ) ) { LOG . info ( "SQL query successfully ran in " + ( System . currentTimeMillis ( ) - beforeQuery ) + "ms." ) ; } if ( LOG . isDebugEnabled ( ) ) { StringBuilder sb = new StringBuilder ( ) ; for ( Entry < String , Object > e : sqlQueryBuilder . getMapSqlParameterSource ( ) . getValues ( ) . entrySet ( ) ) { if ( sb . length ( ) > 0 ) { sb . append ( "," ) ; } sb . append ( e . getKey ( ) ) ; sb . append ( "=" ) ; sb . append ( e . getValue ( ) ) ; } sb . insert ( 0 , "Parameters [" ) ; sb . append ( "]" ) ; LOG . debug ( sb . toString ( ) ) ; } return returnValue ; }


Input: { [CODESPLIT] public void onReset ( WAMResolvingMachineDPI dpi ) { internalRegisters = new InternalRegisterBean ( 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , false ) ; internalRegisters . addPropertyChangeListener ( registerSetMonitor ) ; internalRegisters . addPropertyChangeListener ( breakpointMonitor ) ; internalRegisters . updateRegisters ( dpi . getInternalRegisters ( ) ) ; layoutRegisters = new InternalMemoryLayoutBean ( 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ) ; layoutRegisters . addPropertyChangeListener ( layoutMonitor ) ; layoutRegisters . updateRegisters ( dpi . getMemoryLayout ( ) ) ; }


Input: { [CODESPLIT] public void onCodeUpdate ( WAMResolvingMachineDPI dpi , int start , int length ) { ByteBuffer codeBuffer = dpi . getCodeBuffer ( start , length ) ; byteCodeMonitor . onCodeUpdate ( codeBuffer , start , length , dpi . getVariableAndFunctorInterner ( ) , dpi ) ; }


Input: { [CODESPLIT] public void onExecute ( WAMResolvingMachineDPI dpi ) { internalRegisters . updateRegisters ( dpi . getInternalRegisters ( ) ) ; layoutRegisters . updateRegisters ( dpi . getMemoryLayout ( ) ) ; }


Input: { [CODESPLIT] public void onStep ( WAMResolvingMachineDPI dpi ) { internalRegisters . updateRegisters ( dpi . getInternalRegisters ( ) ) ; layoutRegisters . updateRegisters ( dpi . getMemoryLayout ( ) ) ; breakpointMonitor . pause ( ) ; }


Input: Disassembles the instructions from the specified byte buffer starting at a given location ( ip ) . An interner for the functor names encountered in the instruction buffer must also be supplied in order to look up the functor names by encoded value . [CODESPLIT] public static SizeableList < WAMInstruction > disassemble ( int start , int length , ByteBuffer codeBuf , VariableAndFunctorInterner interner , WAMCodeView codeView ) { SizeableList < WAMInstruction > result = new SizeableLinkedList < WAMInstruction > ( ) ; int ip = start ; while ( ip < ( start + length ) ) { // Decode the instruction and its arguments. byte iCode = codeBuf . get ( ip ) ; WAMInstruction instruction = new WAMInstruction ( iCode ) ; instruction . mnemonic . disassembleArguments ( instruction , ip , codeBuf , interner ) ; // Restore any label on the instruction. Integer label = codeView . getNameForAddress ( ip ) ; if ( label != null ) { FunctorName name = interner . getDeinternedFunctorName ( label ) ; if ( name instanceof WAMLabel ) { instruction . label = ( WAMLabel ) name ; } } result . add ( instruction ) ; ip += instruction . mnemonic . length ( ) ; } return result ; }


Input: Writes out the instruction plus arguments in the byte code format to the specified location within a code buffer . [CODESPLIT] public void emmitCode ( ByteBuffer codeBuffer , WAMMachine machine ) throws LinkageException { mnemonic . emmitCode ( this , codeBuffer , machine ) ; }


Input: { [CODESPLIT] public T getDefaultInstance ( ) { Object result ; // For basic Java types return the standard default value. For others, try the default constructor. switch ( type ) { case BOOLEAN : result = DEFAULT_BOOLEAN ; break ; case CHARACTER : result = DEFAULT_CHARACTER ; break ; case BYTE : result = DEFAULT_BYTE ; break ; case SHORT : result = DEFAULT_SHORT ; break ; case INTEGER : result = DEFAULT_INTEGER ; break ; case LONG : result = DEFAULT_LONG ; break ; case FLOAT : result = DEFAULT_FLOAT ; break ; case DOUBLE : result = DEFAULT_DOUBLE ; break ; case OTHER : default : try { result = underlyingClass . newInstance ( ) ; } catch ( InstantiationException e ) { throw new IllegalStateException ( e ) ; } catch ( IllegalAccessException e ) { throw new IllegalStateException ( e ) ; } break ; } return ( T ) result ; }


Input: { [CODESPLIT] public T getRandomInstance ( ) throws RandomInstanceNotSupportedException { Object result = null ; // For basic Java types return the standard default value. For others, try the default constructor. switch ( type ) { case BOOLEAN : result = RANDOM . nextBoolean ( ) ; break ; case CHARACTER : result = ( char ) RANDOM . nextInt ( ) ; break ; case BYTE : result = ( byte ) RANDOM . nextInt ( ) ; break ; case SHORT : result = ( short ) RANDOM . nextInt ( ) ; break ; case INTEGER : result = RANDOM . nextInt ( ) ; break ; case LONG : result = RANDOM . nextLong ( ) ; break ; case FLOAT : result = RANDOM . nextFloat ( ) ; break ; case DOUBLE : result = RANDOM . nextDouble ( ) ; break ; case OTHER : default : if ( String . class . equals ( underlyingClass ) ) { byte [ ] bytes = new byte [ 6 ] ; RANDOM . nextBytes ( bytes ) ; result = new String ( bytes ) ; } break ; } if ( result != null ) { return ( T ) result ; } else { throw new RandomInstanceNotSupportedException ( "Type does not support random instance creation." , null ) ; } }


Input: Sets the basic type of this type depending on the class . [CODESPLIT] private void setBasicType ( Class c ) { if ( Boolean . class . equals ( c ) ) { type = BasicTypes . BOOLEAN ; } else if ( Character . class . equals ( c ) ) { type = BasicTypes . CHARACTER ; } else if ( Byte . class . equals ( c ) ) { type = BasicTypes . BYTE ; } else if ( Short . class . equals ( c ) ) { type = BasicTypes . SHORT ; } else if ( Integer . class . equals ( c ) ) { type = BasicTypes . INTEGER ; } else if ( Long . class . equals ( c ) ) { type = BasicTypes . LONG ; } else if ( Float . class . equals ( c ) ) { type = BasicTypes . FLOAT ; } else if ( Double . class . equals ( c ) ) { type = BasicTypes . DOUBLE ; } else { type = BasicTypes . OTHER ; } }


Input: Consults an input stream reading first order logic clauses from it and inserting them into the resolvers knowledge base . [CODESPLIT] public void consultInputStream ( InputStream stream ) throws SourceCodeException { // Create a token source to read from the specified input stream. Source < Token > tokenSource = TokenSource . getTokenSourceForInputStream ( stream ) ; getParser ( ) . setTokenSource ( tokenSource ) ; // Consult the type checking rules and add them to the knowledge base. while ( true ) { Sentence < S > sentence = getParser ( ) . parse ( ) ; if ( sentence == null ) { break ; } getCompiler ( ) . compile ( sentence ) ; } }


Input: Prints all of the logic variables in the results of a query . [CODESPLIT] public String printSolution ( Iterable < Variable > solution ) { String result = "" ; for ( Variable var : solution ) { result += printVariableBinding ( var ) + "\n" ; } return result ; }


Input: Prints all of the logic variables in the results of a query . [CODESPLIT] public String printSolution ( Map < String , Variable > variables ) { String result = "" ; for ( Map . Entry < String , Variable > entry : variables . entrySet ( ) ) { result += printVariableBinding ( entry . getValue ( ) ) + "\n" ; } return result ; }


Input: Prints a variable binding in the form Var = value . [CODESPLIT] public String printVariableBinding ( Term var ) { return var . toString ( getInterner ( ) , true , false ) + " = " + var . getValue ( ) . toString ( getInterner ( ) , false , true ) ; }


Input: Transforms an iterator over sets of variable bindings resulting from a query to an iterator over a map from the string name of variables to their bindings for the same sequence of query solutions . [CODESPLIT] public Iterable < Map < String , Variable > > expandResultSetToMap ( Iterator < Set < Variable > > solutions ) { return new Filterator < Set < Variable > , Map < String , Variable > > ( solutions , new Function < Set < Variable > , Map < String , Variable > > ( ) { public Map < String , Variable > apply ( Set < Variable > variables ) { Map < String , Variable > results = new HashMap < String , Variable > ( ) ; for ( Variable var : variables ) { String varName = getInterner ( ) . getVariableName ( var . getName ( ) ) ; results . put ( varName , var ) ; } return results ; } } ) ; }


Input: { [CODESPLIT] public void setOperator ( String operatorName , int priority , OpSymbol . Associativity associativity ) { parser . setOperator ( operatorName , priority , associativity ) ; }


Input: { [CODESPLIT] public SizeableLinkedList < WAMInstruction > compileBodyArguments ( Functor expression , boolean isFirstBody , FunctorName clauseName , int bodyNumber ) { return null ; }


Input: A dedicated thread loop for reading the stream and sending incoming packets to the appropriate router . [CODESPLIT] public void run ( ) { try { readStream ( ) ; } catch ( EOFException eof ) { // Normal disconnect } catch ( SocketException se ) { // Do nothing if the exception occured while shutting down the // component otherwise // log the error and try to establish a new connection if ( ! shutdown ) { component . getManager ( ) . getLog ( ) . error ( se ) ; component . connectionLost ( ) ; } } catch ( XmlPullParserException ie ) { component . getManager ( ) . getLog ( ) . error ( ie ) ; } catch ( Exception e ) { component . getManager ( ) . getLog ( ) . warn ( e ) ; } }


Input: Read the incoming stream until it ends . [CODESPLIT] private void readStream ( ) throws Exception { while ( ! shutdown ) { Element doc = reader . parseDocument ( ) . getRootElement ( ) ; if ( doc == null ) { // Stop reading the stream since the server has sent an end of // stream element and // probably closed the connection return ; } Packet packet ; String tag = doc . getName ( ) ; if ( "message" . equals ( tag ) ) { packet = new Message ( doc ) ; } else if ( "presence" . equals ( tag ) ) { packet = new Presence ( doc ) ; } else if ( "iq" . equals ( tag ) ) { packet = getIQ ( doc ) ; } else { throw new XmlPullParserException ( "Unknown packet type was read: " + tag ) ; } // Request the component to process the received packet component . processPacket ( packet ) ; } }


Input: / * Initializer for type 1 UUIDs . Creates random generator and genenerates the node portion of the UUID using the IP address . [CODESPLIT] private static synchronized void initializeForType1 ( ) { if ( type1Initialized == true ) { return ; } // note that secure random is very slow the first time // it is used; consider switching to a standard random RANDOM = new SecureRandom ( ) ; _seq = ( short ) RANDOM . nextInt ( MAX_14BIT ) ; byte [ ] ip = null ; try { ip = InetAddress . getLocalHost ( ) . getAddress ( ) ; } catch ( IOException ioe ) { throw new NestableRuntimeException ( ioe ) ; } IP = new byte [ 6 ] ; RANDOM . nextBytes ( IP ) ; System . arraycopy ( ip , 0 , IP , 2 , ip . length ) ; type1Initialized = true ; }


Input: / * Creates a type 1 UUID [CODESPLIT] public static byte [ ] next ( ) { if ( type1Initialized == false ) { initializeForType1 ( ) ; } // set ip addr byte [ ] uuid = new byte [ 16 ] ; System . arraycopy ( IP , 0 , uuid , 10 , IP . length ) ; // Set time info. Have to do this processing within a synchronized // block because of the statics... long now = 0 ; synchronized ( Type1UUID . class ) { // Get the time to use for this uuid. This method has the side // effect of modifying the clock sequence, as well. now = getTime ( ) ; // Insert the resulting clock sequence into the uuid uuid [ IDX_TIME_SEQ ] = ( byte ) ( ( _seq & 0x3F00 ) >>> 8 ) ; uuid [ IDX_VARIATION ] |= 0x80 ; uuid [ IDX_TIME_SEQ + 1 ] = ( byte ) ( _seq & 0xFF ) ; } // have to break up time because bytes are spread through uuid byte [ ] timeBytes = toBytes ( now ) ; // Copy time low System . arraycopy ( timeBytes , TS_TIME_LO_IDX , uuid , IDX_TIME_LO , TS_TIME_LO_LEN ) ; // Copy time mid System . arraycopy ( timeBytes , TS_TIME_MID_IDX , uuid , IDX_TIME_MID , TS_TIME_MID_LEN ) ; // Copy time hi System . arraycopy ( timeBytes , TS_TIME_HI_IDX , uuid , IDX_TIME_HI , TS_TIME_HI_LEN ) ; // Set version (time-based) uuid [ IDX_TYPE ] |= TYPE_TIME_BASED ; // 0001 0000 return uuid ; }


Input: package - visibility for testing [CODESPLIT] static long getTime ( ) { if ( RANDOM == null ) initializeForType1 ( ) ; long newTime = getUUIDTime ( ) ; if ( newTime <= _lastMillis ) { incrementSequence ( ) ; newTime = getUUIDTime ( ) ; } _lastMillis = newTime ; return newTime ; }


Input: Gets the appropriately modified timestamep for the UUID . Must be called from a synchronized block . [CODESPLIT] private static long getUUIDTime ( ) { if ( _currentMillis != System . currentTimeMillis ( ) ) { _currentMillis = System . currentTimeMillis ( ) ; _counter = 0 ; // reset counter } // check to see if we have created too many uuid's for this timestamp if ( _counter + 1 >= MILLI_MULT ) { // Original algorithm threw exception. Seemed like overkill. // Let's just increment the timestamp instead and start over... _currentMillis ++ ; _counter = 0 ; } // calculate time as current millis plus offset times 100 ns ticks long currentTime = ( _currentMillis + GREG_OFFSET ) * MILLI_MULT ; // return the uuid time plus the artificial tick counter incremented return currentTime + _counter ++ ; }


Input: stops the playing / indicates that the playing stopped . <p > this method has no effect if runsInPlay is enabled in the constructor . <br > < / p > [CODESPLIT] public void stopMusicPlayback ( ) { if ( runsInPlay || ! isPlaying ) return ; lock . lock ( ) ; try { if ( blockRequest != null ) blockRequest . signal ( ) ; } finally { lock . unlock ( ) ; } isPlaying = false ; stopSound ( ) ; endedSound ( ) ; rollBackToDefault ( ) ; super . stop ( ) ; }


Input:
checks if the trackInfo is an update and fires the appropriate Event . This method should not be called without an active playlist or an NullPointerException will be thrown . this method :
 - fires nothing if the trackInfo equals the current trackInfo .
 - fires an trackInfoUpdate if the trackInfo contains information not found in the current .
 [CODESPLIT] @ SuppressWarnings ( "unused" ) public void updateCurrentTrackInfo ( TrackInfo trackInfo ) { if ( playlist . getCurrent ( ) . equals ( trackInfo ) || playlist . getCurrent ( ) . isNew ( trackInfo ) ) return ; this . playlist = playlist . update ( playlist . getCurrent ( ) , trackInfo ) ; trackInfoUpdate ( playlist , trackInfo ) ; }


Input: call this method if the trackInfo object in the playlist was updated . Only the trackinfo object will be sent via Event [CODESPLIT] @ SuppressWarnings ( "unused" ) public void trackInfoUpdate ( Playlist playlist , TrackInfo info ) { this . playlist = playlist ; updatePlayInfo ( info ) ; }


Input: fires an update event which notifies that parameters have changed [CODESPLIT] @ Override public void updatePlayInfo ( Volume volume ) { if ( this . volume . equals ( volume ) ) return ; this . volume = volume ; MusicHelper . super . updatePlayInfo ( volume ) ; }


Input: updates the Info about the current song [CODESPLIT] @ SuppressWarnings ( "unused" ) public void updatePlayInfo ( Playlist playlist , Progress progress , Volume volume ) { if ( playlist != null ) this . playlist = playlist ; if ( progress != null ) this . progress = progress ; if ( volume != null ) this . volume = volume ; updatePlayInfo ( playlist , progress , null , volume ) ; }


Input: fires an update event which notifies that parameters have changed [CODESPLIT] @ Override public void updatePlayInfo ( Playlist playlist , Progress progress , TrackInfo trackInfo , Volume volume ) { if ( playlist != null ) this . playlist = playlist ; if ( progress != null ) this . progress = progress ; if ( volume != null ) this . volume = volume ; MusicHelper . super . updatePlayInfo ( playlist , progress , null , volume ) ; }


Input: This method is called when an object wants to get a Resource . <p > Don t use the Resources provided as arguments they are just the requests . There is a timeout after 1 second . < / p > [CODESPLIT] @ Override public List < ResourceModel > provideResource ( List < ? extends ResourceModel > resources , Optional < EventModel > event ) { return informationProvider . provideResource ( resources , event ) ; }


Input: method that uses the data from the OutputExtensions to generate a final output that will then be rendered . [CODESPLIT] @ Override public void renderFinalOutput ( List < T > data , EventModel eventModel ) { if ( StartMusicRequest . verify ( eventModel , capabilities , this , activators ) ) { if ( isOutputRunning ( ) ) { playerError ( PlayerError . ERROR_ALREADY_PLAYING , eventModel . getSource ( ) ) ; } else { handleEventRequest ( eventModel ) ; } } else if ( eventModel . getListResourceContainer ( ) . providesResource ( Collections . singletonList ( MusicUsageResource . ID ) ) ) { if ( isOutputRunning ( ) ) { eventModel . getListResourceContainer ( ) . provideResource ( MusicUsageResource . ID ) . forEach ( resourceModel -> playerError ( PlayerError . ERROR_ALREADY_PLAYING , resourceModel . getProvider ( ) ) ) ; } else { handleResourceRequest ( eventModel ) ; } } else { handleCommands ( eventModel ) ; } }


Input: handles the a request to start playing music via Resource [CODESPLIT] private void handleResourceRequest ( EventModel eventModel ) { if ( MusicUsageResource . isPermanent ( eventModel ) ) { ResourceModel resourceModel = eventModel . getListResourceContainer ( ) . provideResource ( MusicUsageResource . ID ) . stream ( ) . filter ( MusicUsageResource :: isPermanent ) . findAny ( ) . orElse ( null ) ; //should not happen //a partially applied function which takes an Identification an returns an Optional StartMusicRequest Function < Identification , Optional < StartMusicRequest > > getStartMusicRequest = own -> StartMusicRequest . createStartMusicRequest ( resourceModel . getProvider ( ) , own ) ; //if we have a trackInfo we create it with the trackInfo as a parameter getStartMusicRequest = TrackInfoResource . getTrackInfo ( eventModel ) . map ( trackInfo -> ( Function < Identification , Optional < StartMusicRequest > > ) own -> StartMusicRequest . createStartMusicRequest ( resourceModel . getProvider ( ) , own , trackInfo ) ) . orElse ( getStartMusicRequest ) ; //if we have a trackInfo we create it with the playlist as a parameter getStartMusicRequest = PlaylistResource . getPlaylist ( eventModel ) . map ( playlist -> ( Function < Identification , Optional < StartMusicRequest > > ) own -> StartMusicRequest . createStartMusicRequest ( resourceModel . getProvider ( ) , own , playlist ) ) . orElse ( getStartMusicRequest ) ; //composes a new Function which appends the Volume to the result getStartMusicRequest = getStartMusicRequest . andThen ( VolumeResource . getVolume ( eventModel ) . flatMap ( volume -> IdentificationManagerM . getInstance ( ) . getIdentification ( this ) . map ( identification -> new VolumeResource ( identification , volume ) ) ) . map ( resource -> ( Function < Optional < StartMusicRequest > , Optional < StartMusicRequest > > ) opt -> opt . map ( event -> ( StartMusicRequest ) event . addResource ( resource ) ) ) . orElse ( Function . identity ( ) ) :: apply ) ; IdentificationManagerM . getInstance ( ) . getIdentification ( this ) . flatMap ( getStartMusicRequest :: apply ) . ifPresent ( this :: fire ) ; } else { play ( eventModel ) ; if ( ! runsInPlay ) { blockRequest = lock . newCondition ( ) ; lock . lock ( ) ; try { blockRequest . await ( 10 , TimeUnit . MINUTES ) ; } catch ( InterruptedException e ) { debug ( "interrupted" , e ) ; } finally { lock . unlock ( ) ; } } } }


Input: handles the commands encoded as Resources / EventIds [CODESPLIT] private void handleCommands ( EventModel eventModel ) { Consumer < Runnable > checkOrCall = runnable -> { List < ResourceModel > resourceModels = eventModel . getListResourceContainer ( ) . provideResource ( SelectorResource . RESOURCE_ID ) ; if ( resourceModels . isEmpty ( ) ) { runnable . run ( ) ; } else { resourceModels . stream ( ) . map ( resourceModel -> resourceModel . getResource ( ) instanceof Identification ? ( ( Identification ) resourceModel . getResource ( ) ) : null ) . filter ( Objects :: nonNull ) . filter ( this :: isOwner ) . findAny ( ) . ifPresent ( id -> runnable . run ( ) ) ; } } ; if ( eventModel . containsDescriptor ( MuteEvent . ID ) ) { checkOrCall . accept ( this :: mute ) ; } if ( eventModel . containsDescriptor ( UnMuteEvent . ID ) ) { checkOrCall . accept ( this :: unMute ) ; } if ( eventModel . containsDescriptor ( StopEvent . ID ) ) { checkOrCall . accept ( this :: stopMusicPlayback ) ; } if ( StopMusic . verify ( eventModel , this ) ) { stopMusicPlayback ( ) ; } if ( PlayerCommand . verify ( eventModel , this ) ) { getCommandHandler ( ) . handleCommandResources ( eventModel ) ; } }


Input: handles the a request to start playing music via Event [CODESPLIT] private void handleEventRequest ( EventModel eventModel ) { playingThread = submit ( ( Runnable ) ( ) -> { //noinspection RedundantIfStatement if ( runsInPlay ) { isRunning = false ; } else { isRunning = true ; } isPlaying = true ; fireStartMusicRequest ( eventModel ) ; } ) . thenRun ( ( ) -> play ( eventModel ) ) . thenRun ( ( ) -> { if ( runsInPlay ) { isRunning = false ; isPlaying = false ; endedSound ( ) ; } } ) ; }


Input: this method will be called to create and fire the StartMusicRequest [CODESPLIT] protected void fireStartMusicRequest ( EventModel eventModel ) { Optional < Playlist > playlist = PlaylistResource . getPlaylist ( eventModel ) ; Optional < Progress > progress = ProgressResource . getProgress ( eventModel ) ; Optional < TrackInfo > trackInfo = TrackInfoResource . getTrackInfo ( eventModel ) ; Optional < Volume > volume = VolumeResource . getVolume ( eventModel ) ; startedSound ( playlist . orElse ( null ) , progress . orElse ( null ) , trackInfo . orElse ( null ) , volume . orElse ( null ) , isUsingJava ) ; }


Input: sets every information into its default state ( playlist volume etc ... ) [CODESPLIT] public void rollBackToDefault ( ) { playlist = new Playlist ( new ArrayList <> ( ) ) ; volume = Volume . createVolume ( 50 ) . orElse ( null ) ; progress = new Progress ( 0 , 0 ) ; playbackState = PlaybackState . PLAY ; if ( playingThread != null ) playingThread . cancel ( true ) ; isRunning = false ; isPlaying = false ; }


Input: Initializes the reader in order to be used . The reader is initialized during the first connection and when reconnecting due to an abruptly disconnection . [CODESPLIT] protected void init ( ) { done = false ; connectionID = null ; readerThread = new Thread ( ) { public void run ( ) { parsePackets ( this ) ; } } ; readerThread . setName ( "Smack Packet Reader (" + connection . connectionCounterValue + ")" ) ; readerThread . setDaemon ( true ) ; // Create an executor to deliver incoming packets to listeners. We'll // use a single // thread with an unbounded queue. listenerExecutor = Executors . newSingleThreadExecutor ( new ThreadFactory ( ) { public Thread newThread ( Runnable runnable ) { Thread thread = new Thread ( runnable , "Smack Listener Processor (" + connection . connectionCounterValue + ")" ) ; thread . setDaemon ( true ) ; return thread ; } } ) ; resetParser ( ) ; }


Input: Starts the packet reader thread and returns once a connection to the server has been established . A connection will be attempted for a maximum of five seconds . An XMPPException will be thrown if the connection fails . [CODESPLIT] synchronized public void startup ( ) throws XMPPException { final List < Exception > errors = new LinkedList < Exception > ( ) ; AbstractConnectionListener connectionErrorListener = new AbstractConnectionListener ( ) { @ Override public void connectionClosedOnError ( Exception e ) { errors . add ( e ) ; } } ; connection . addConnectionListener ( connectionErrorListener ) ; readerThread . start ( ) ; // Wait for stream tag before returning. We'll wait a couple of seconds // before // giving up and throwing an error. try { // A waiting thread may be woken up before the wait time or a notify // (although this is a rare thing). Therefore, we continue waiting // until either a connectionID has been set (and hence a notify was // made) or the total wait time has elapsed. int waitTime = SmackConfiguration . getPacketReplyTimeout ( ) ; wait ( 3 * waitTime ) ; } catch ( InterruptedException ie ) { // Ignore. } connection . removeConnectionListener ( connectionErrorListener ) ; if ( connectionID == null ) { throw new XMPPException ( "Connection failed. No response from server." ) ; } else if ( ! errors . isEmpty ( ) ) { throw new XMPPException ( errors . iterator ( ) . next ( ) ) ; } else { connection . connectionID = connectionID ; } }


Input: Shuts the packet reader down . [CODESPLIT] public void shutdown ( ) { // Notify connection listeners of the connection closing if done hasn't // already been set. if ( ! done ) { for ( ConnectionListener listener : connection . getConnectionListeners ( ) ) { try { listener . connectionClosed ( ) ; } catch ( Exception e ) { // Catch and print any exception so we can recover // from a faulty listener and finish the shutdown process LOGGER . log ( Level . ERROR , "Error in listener while closing connection" , e ) ; } } } done = true ; // Shut down the listener executor. listenerExecutor . shutdown ( ) ; }


Input: Resets the parser using the latest connection s reader . Reseting the parser is necessary when the plain connection has been secured or when a new opening stream element is going to be sent by the server . [CODESPLIT] private void resetParser ( ) { try { innerReader = new XPPPacketReader ( ) ; innerReader . setXPPFactory ( XmlPullParserFactory . newInstance ( ) ) ; innerReader . getXPPParser ( ) . setInput ( connection . reader ) ; reset = true ; } catch ( Exception xppe ) { LOGGER . log ( Level . WARN , "Error while resetting parser" , xppe ) ; } }


Input: Parse top - level packets in order to process them further . [CODESPLIT] private void parsePackets ( Thread thread ) { try { while ( ! done ) { if ( reset ) { startStream ( ) ; LOGGER . debug ( "Started xmlstream..." ) ; reset = false ; continue ; } Element doc = innerReader . parseDocument ( ) . getRootElement ( ) ; if ( doc == null ) { connection . disconnect ( ) ; LOGGER . debug ( "End of xmlstream." ) ; continue ; } Packet packet = null ; LOGGER . debug ( "Processing packet " + doc . asXML ( ) ) ; packet = parseFromPlugins ( doc , packet ) ; if ( packet == null ) { packet = parseFromCore ( doc ) ; } if ( packet != null ) { processPacket ( packet ) ; } } } catch ( Exception e ) { if ( ! done && ! connection . isSocketClosed ( ) ) { connection . notifyConnectionError ( e ) ; if ( ! connection . isConnected ( ) ) { releaseConnectionIDLock ( ) ; } } } }


Input: Processes a packet after it s been fully parsed by looping through the installed packet collectors and listeners and letting them examine the packet to see if they are a match with the filter . [CODESPLIT] private void processPacket ( Packet packet ) { if ( packet == null ) { return ; } // Loop through all collectors and notify the appropriate ones. for ( PacketCollector collector : connection . getPacketCollectors ( ) ) { collector . processPacket ( packet ) ; } // Deliver the incoming packet to listeners. listenerExecutor . submit ( new ListenerNotification ( packet ) ) ; }


Input: Sets the CLI option . [CODESPLIT] protected final void setCliOption ( Option option ) { if ( option != null ) { this . cliOption = option ; } if ( this . cliOption . getDescription ( ) != null ) { this . descr = this . cliOption . getDescription ( ) ; } else { this . cliOption . setDescription ( this . descr ) ; } }


Input: Creates a new chat and returns it . [CODESPLIT] public Chat createChat ( String userJID , MessageListener listener ) { return createChat ( userJID , null , listener ) ; }


Input: Try to get a matching chat for the given user JID based on the { @link MatchMode } . <li > NONE - return null <li > SUPPLIED_JID - match the jid in the from field of the message exactly . <li > BARE_JID - if not match for from field try the bare jid . [CODESPLIT] private Chat getUserChat ( String userJID ) { if ( matchMode == MatchMode . NONE ) { return null ; } Chat match = jidChats . get ( userJID ) ; if ( match == null && ( matchMode == MatchMode . BARE_JID ) ) { match = baseJidChats . get ( StringUtils . parseBareAddress ( userJID ) ) ; } return match ; }


Input: Returns a list of HostAddresses under which the specified XMPP server can be reached at for server - to - server communication . A DNS lookup for a SRV record in the form _xmpp - server . _tcp . example . com is attempted according to section 14 . 4 of RFC 3920 . If that lookup fails a lookup in the older form of _jabber . _tcp . example . com is attempted since servers that implement an older version of the protocol may be listed using that notation . If that lookup fails as well it s assumed that the XMPP server lives at the host resolved by a DNS lookup at the specified domain on the default port of 5269 . <p > [CODESPLIT] public static List < HostAddress > resolveXMPPServerDomain ( final String domain ) { if ( dnsResolver == null ) { List < HostAddress > addresses = new ArrayList < HostAddress > ( 1 ) ; addresses . add ( new HostAddress ( domain , 5269 ) ) ; return addresses ; } return resolveDomain ( domain , ' ' ) ; }


Input: Convert a new content object to an internal version . [CODESPLIT] void internalize ( ContentManagerImpl contentManager , boolean readOnly ) { this . contentManager = contentManager ; updated = false ; newcontent = false ; this . readOnly = readOnly ; }


Input: Reset the object back to its last saved state . [CODESPLIT] public void reset ( Map < String , Object > updatedMap ) { if ( ! readOnly ) { this . content = ImmutableMap . copyOf ( updatedMap ) ; updatedContent . clear ( ) ; updated = false ; LOGGER . debug ( "Reset to {} " , updatedMap ) ; } }


Input: set a property creating if it does not exist overwriting if it does . [CODESPLIT] public void setProperty ( String key , Object value ) { if ( readOnly ) { return ; } if ( value == null ) { throw new IllegalArgumentException ( "value must not be null" ) ; } Object o = content . get ( key ) ; if ( ! value . equals ( o ) ) { updatedContent . put ( key , value ) ; updated = true ; } else if ( updatedContent . containsKey ( key ) && ! value . equals ( updatedContent . get ( key ) ) ) { updatedContent . put ( key , value ) ; updated = true ; } }


Input: Adds a filter to the filter list for the OR operation . A packet will pass the filter if any filter in the list accepts it . [CODESPLIT] public void addFilter ( PacketFilter filter ) { if ( filter == null ) { throw new IllegalArgumentException ( "Parameter cannot be null." ) ; } // If there is no more room left in the filters array, expand it. if ( size == filters . length ) { PacketFilter [ ] newFilters = new PacketFilter [ filters . length + 2 ] ; for ( int i = 0 ; i < filters . length ; i ++ ) { newFilters [ i ] = filters [ i ] ; } filters = newFilters ; } // Add the new filter to the array. filters [ size ] = filter ; size ++ ; }


Input: Process the request in a stream . [CODESPLIT] public void processRequest ( HttpServletRequest request ) throws IOException , FileUploadException , StorageClientException , AccessDeniedException { boolean debug = LOGGER . isDebugEnabled ( ) ; if ( ServletFileUpload . isMultipartContent ( request ) ) { if ( debug ) { LOGGER . debug ( "Multipart POST " ) ; } feedback . add ( "Multipart Upload" ) ; ServletFileUpload upload = new ServletFileUpload ( ) ; FileItemIterator iterator = upload . getItemIterator ( request ) ; while ( iterator . hasNext ( ) ) { FileItemStream item = iterator . next ( ) ; if ( debug ) { LOGGER . debug ( "Got Item {}" , item ) ; } String name = item . getFieldName ( ) ; InputStream stream = item . openStream ( ) ; if ( item . isFormField ( ) ) { ParameterType pt = ParameterType . typeOfRequestParameter ( name ) ; String propertyName = RequestUtils . propertyName ( pt . getPropertyName ( name ) ) ; RequestUtils . accumulate ( stores . get ( pt ) , propertyName , RequestUtils . toValue ( name , Streams . asString ( stream ) ) ) ; feedback . add ( pt . feedback ( propertyName ) ) ; } else { if ( streamProcessor != null ) { feedback . addAll ( streamProcessor . processStream ( name , StorageClientUtils . getObjectName ( item . getName ( ) ) , item . getContentType ( ) , stream , this ) ) ; } } } if ( debug ) { LOGGER . debug ( "No More items " ) ; } } else { if ( debug ) { LOGGER . debug ( "Trad Post " ) ; } // use traditional unstreamed operations. @ SuppressWarnings ( "unchecked" ) Map < String , String [ ] > parameters = request . getParameterMap ( ) ; if ( debug ) { LOGGER . debug ( "Traditional POST {} " , parameters ) ; } Set < Entry < String , String [ ] > > entries = parameters . entrySet ( ) ; for ( Entry < String , String [ ] > param : entries ) { String name = ( String ) param . getKey ( ) ; ParameterType pt = ParameterType . typeOfRequestParameter ( name ) ; String propertyName = RequestUtils . propertyName ( pt . getPropertyName ( name ) ) ; RequestUtils . accumulate ( stores . get ( pt ) , propertyName , RequestUtils . toValue ( name , param . getValue ( ) ) ) ; feedback . add ( pt . feedback ( propertyName ) ) ; } } }


Input: Clear the current set of properties to add and remove . [CODESPLIT] public void resetProperties ( ) { for ( Entry < ParameterType , Map < String , Object > > e : stores . entrySet ( ) ) { e . getValue ( ) . clear ( ) ; } }


Input: Calculate an RFC2104 compliant HMAC ( Hash - based Message Authentication Code ) [CODESPLIT] public static String calculateRFC2104HMAC ( String data , String key ) throws java . security . SignatureException { if ( data == null ) { throw new IllegalArgumentException ( "String data == null" ) ; } if ( key == null ) { throw new IllegalArgumentException ( "String key == null" ) ; } try { // Get an hmac_sha1 key from the raw key bytes byte [ ] keyBytes = key . getBytes ( "UTF-8" ) ; SecretKeySpec signingKey = new SecretKeySpec ( keyBytes , HMAC_SHA1_ALGORITHM ) ; // Get an hmac_sha1 Mac instance and initialize with the signing key Mac mac = Mac . getInstance ( HMAC_SHA1_ALGORITHM ) ; mac . init ( signingKey ) ; // Compute the hmac on input data bytes byte [ ] rawHmac = mac . doFinal ( data . getBytes ( "UTF-8" ) ) ; // Convert raw bytes to encoding return Base64 . encodeBase64URLSafeString ( rawHmac ) ; } catch ( NoSuchAlgorithmException e ) { throw new SignatureException ( "Failed to generate HMAC : " + e . getMessage ( ) , e ) ; } catch ( InvalidKeyException e ) { throw new SignatureException ( "Failed to generate HMAC : " + e . getMessage ( ) , e ) ; } catch ( UnsupportedEncodingException e ) { throw new SignatureException ( "Failed to generate HMAC : " + e . getMessage ( ) , e ) ; } }


Input: Takes the original request and starts the batching . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) protected void batchRequest ( HttpServletRequest request , HttpServletResponse response , boolean allowModify ) throws IOException , ServletException { String json = request . getParameter ( REQUESTS_PARAMETER ) ; String template = request . getParameter ( REQUEST_TEMPLATE ) ; if ( template != null && template . length ( ) > 0 ) { if ( templateService . checkTemplateExists ( template ) ) { StringWriter processedTemplate = new StringWriter ( ) ; templateService . process ( request . getParameterMap ( ) , "UTF-8" , processedTemplate , template ) ; json = processedTemplate . toString ( ) ; } else { response . sendError ( HttpServletResponse . SC_BAD_REQUEST , "Template specified in request parameter t does not exist" ) ; } } batchProcessor . batchRequest ( request , response , json , allowModify ) ; }


Input: TODO : Unit test [CODESPLIT] public static void addAcl ( boolean grant , Permission permssion , String key , List < AclModification > modifications ) { if ( grant ) { key = AclModification . grantKey ( key ) ; } else { key = AclModification . denyKey ( key ) ; } modifications . add ( new AclModification ( key , permssion . getPermission ( ) , AclModification . Operation . OP_OR ) ) ; }


Input: TODO : Unit test [CODESPLIT] public static void removeAcl ( boolean grant , Permission permssion , String key , List < AclModification > modifications ) { if ( grant ) { key = AclModification . grantKey ( key ) ; } else { key = AclModification . denyKey ( key ) ; } modifications . add ( new AclModification ( key , ~ permssion . getPermission ( ) , AclModification . Operation . OP_AND ) ) ; }


Input: TODO : Unit test [CODESPLIT] public static void filterAcl ( Map < String , Object > acl , boolean grant , Permission permission , boolean set , List < AclModification > modifications ) { int perm = permission . getPermission ( ) ; Operation op = Operation . OP_OR ; if ( ! set ) { perm = 0xffff ^ perm ; op = Operation . OP_AND ; } for ( Entry < String , Object > ace : acl . entrySet ( ) ) { String key = ace . getKey ( ) ; if ( AclModification . isGrant ( key ) == grant ) { // clear the bit if set. modifications . add ( new AclModification ( key , perm , op ) ) ; } } }


Input: TODO : Unit test [CODESPLIT] public static String getPrincipal ( String principalKey ) { if ( principalKey == null ) { return principalKey ; } if ( principalKey . length ( ) <= GRANTED_MARKER . length ( ) ) { return null ; } if ( principalKey . endsWith ( GRANTED_MARKER ) ) { return principalKey . substring ( 0 , principalKey . length ( ) - GRANTED_MARKER . length ( ) ) ; } else if ( principalKey . endsWith ( DENIED_MARKER ) ) { return principalKey . substring ( 0 , principalKey . length ( ) - DENIED_MARKER . length ( ) ) ; } else { return null ; } }


Input: TODO : Unit test [CODESPLIT] public static Permission [ ] listPermissions ( int perms ) { List < Permission > permissions = Lists . newArrayList ( ) ; for ( Permission p : Permissions . PRIMARY_PERMISSIONS ) { if ( ( perms & p . getPermission ( ) ) == p . getPermission ( ) ) { permissions . add ( p ) ; } } return permissions . toArray ( new Permission [ permissions . size ( ) ] ) ; }


Input: Factory method to create a synchronized map . [CODESPLIT] public static < K , V > TransactionalSortedBidiMap < K , V > decorate ( TransactionalSortedBidiMap < K , V > map ) { return new SynchronizedTransactionalSortedBidiMap < K , V > ( map ) ; }


Input: ----------------------------------------------------------------------- [CODESPLIT] public void commit ( ) { SyncUtils . synchronizeWrite ( lock , new Callback < Object > ( ) { @ Override protected void doAction ( ) { getTransactionalSortedBidiMap ( ) . commit ( ) ; } } ) ; }


Input: Initializes the writer in order to be used . It is called at the first connection and also is invoked if the connection is disconnected by an error . [CODESPLIT] protected void init ( ) { this . writer = connection . writer ; done = false ; writerThread = new Thread ( ) { public void run ( ) { writePackets ( this ) ; } } ; writerThread . setName ( "Smack Packet Writer (" + connection . connectionCounterValue + ")" ) ; writerThread . setDaemon ( true ) ; }


Input: Sends the specified packet to the server . [CODESPLIT] public void sendPacket ( Packet packet ) { if ( ! done ) { // Invoke interceptors for the new packet that is about to be sent. // Interceptors // may modify the content of the packet. connection . firePacketInterceptors ( packet ) ; try { queue . put ( packet ) ; } catch ( InterruptedException ie ) { LOGGER . log ( Level . ERROR , "Failed to queue packet to send to server: " + packet . toString ( ) , ie ) ; return ; } synchronized ( queue ) { queue . notifyAll ( ) ; } // Process packet writer listeners. Note that we're using the // sending // thread so it's expected that listeners are fast. connection . firePacketSendingListeners ( packet ) ; } }


Input: Returns the next available packet from the queue for writing . [CODESPLIT] private Packet nextPacket ( ) { Packet packet = null ; // Wait until there's a packet or we're done. while ( ! done && ( packet = queue . poll ( ) ) == null ) { try { synchronized ( queue ) { queue . wait ( ) ; } } catch ( InterruptedException ie ) { // Do nothing } } return packet ; }


Input: Sends to the server a new stream element . This operation may be requested several times so we need to encapsulate the logic in one place . This message will be sent while doing TLS SASL and resource binding . [CODESPLIT] void openStream ( ) throws IOException { StringBuilder stream = new StringBuilder ( ) ; stream . append ( "<stream:stream" ) ; stream . append ( " to=\"" ) . append ( connection . getServiceName ( ) ) . append ( "\"" ) ; stream . append ( " xmlns=\"jabber:client\"" ) ; stream . append ( " xmlns:stream=\"http://etherx.jabber.org/streams\"" ) ; stream . append ( " version=\"1.0\">" ) ; writer . write ( stream . toString ( ) ) ; writer . flush ( ) ; }


Input: Get the Goodwill schema associated to a schema name . < / p > Typical invocation : <pre > try { GoodwillSchema type = accessor . getSchema ( test ) . get () ; ... } catch ( Exception e ) { // Connection exception? Goodwill server down? } < / pre > [CODESPLIT] public Future < GoodwillSchema > getSchema ( final String schemaName ) { try { return client . prepareGet ( String . format ( "%s/%s" , url , schemaName ) ) . addHeader ( "Accept" , "application/json" ) . execute ( new AsyncCompletionHandler < GoodwillSchema > ( ) { @ Override public GoodwillSchema onCompleted ( final Response response ) throws Exception { if ( response . getStatusCode ( ) != 200 ) { return null ; } final InputStream in = response . getResponseBodyAsStream ( ) ; try { return mapper . readValue ( in , GoodwillSchema . class ) ; } finally { closeStream ( in ) ; } } @ Override public void onThrowable ( final Throwable t ) { log . warn ( "Got exception looking up the schema" , t ) ; } } ) ; } catch ( IOException e ) { log . warn ( "Got exception looking up the schema" , e ) ; return null ; } }


Input: Get all schemata . <p / > Use schemata instead of schemas which is closer to the original σχήματα . [CODESPLIT] public Future < List < GoodwillSchema > > getSchemata ( ) { try { return client . prepareGet ( url ) . addHeader ( "Accept" , "application/json" ) . execute ( new AsyncCompletionHandler < List < GoodwillSchema > > ( ) { @ Override public List < GoodwillSchema > onCompleted ( final Response response ) throws Exception { if ( response . getStatusCode ( ) != 200 ) { return null ; } InputStream in = response . getResponseBodyAsStream ( ) ; try { final HashMap < String , List < GoodwillSchema > > map = mapper . readValue ( in , new TypeReference < HashMap < String , List < GoodwillSchema > > > ( ) { } ) ; return map . get ( "types" ) ; } finally { closeStream ( in ) ; } } @ Override public void onThrowable ( final Throwable t ) { log . warn ( "Got exception looking up the schema list" , t ) ; } } ) ; } catch ( IOException e ) { log . warn ( "Got exception looking up the schema list" , e ) ; return null ; } }


Input: note : if called from base - class constructor couldn t sub - class ; hence just make static [CODESPLIT] private static AsyncHttpClient createHttpClient ( ) { // Don't limit the number of connections per host // See https://github.com/ning/async-http-client/issues/issue/28 final AsyncHttpClientConfig . Builder builder = new AsyncHttpClientConfig . Builder ( ) ; builder . setMaximumConnectionsPerHost ( - 1 ) ; return new AsyncHttpClient ( builder . build ( ) ) ; }


Input: Creates a new Event Object [CODESPLIT] public static Optional < Event > createEvent ( String type , Identification source ) { try { return Optional . of ( new Event ( type , source , new ArrayList <> ( ) ) ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } }


Input: Creates a new Event Object [CODESPLIT] public static Optional < Event > createEvent ( String type , Identification source , List < String > descriptors ) { try { return Optional . of ( new Event ( type , source , descriptors ) ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } }


Input: returns a List containing all the Descriptors and the type . [CODESPLIT] @ Override public List < String > getAllInformations ( ) { ArrayList < String > strings = new ArrayList <> ( descriptors ) ; strings . add ( type ) ; return strings ; }


Input: sets the Descriptors ( but not the Event - Type ) . [CODESPLIT] public Event addDescriptor ( String descriptor ) { List < String > newDescriptors = new ArrayList <> ( ) ; newDescriptors . addAll ( descriptors ) ; newDescriptors . add ( descriptor ) ; return new Event ( getType ( ) , getSource ( ) , newDescriptors ) ; }


Input: returns whether the event contains the specific descriptor . this method also checks whether it matches the type . [CODESPLIT] @ Override public boolean containsDescriptor ( String descriptor ) { return descriptors . contains ( descriptor ) || type . equals ( descriptor ) ; }


Input: adds the Consumer to the specified EventLifeCycle . In its current implementation the invocation of the Callback method is parallel but the notificaton of the listners not . [CODESPLIT] @ SuppressWarnings ( "unused" ) public Event addEventLifeCycleListener ( EventLifeCycle eventLifeCycle , Consumer < EventLifeCycle > cycleCallback ) { lifeCycleListeners . compute ( eventLifeCycle , ( unused , list ) -> { if ( list == null ) list = new ArrayList <> ( ) ; list . add ( cycleCallback ) ; return list ; } ) ; return this ; }


Input: Default implementation waits until a new Event has been received and then processes it . <p > This method is made to be overwritten as seen fit by the developer [CODESPLIT] @ Override public EventModel blockingQueueHandling ( ) throws InterruptedException { EventModel eventModel = super . blockingQueueHandling ( ) ; if ( eventModel . containsDescriptor ( MuteEvent . ID ) ) { List < ResourceModel > resourceModels = eventModel . getListResourceContainer ( ) . provideResource ( SelectorResource . RESOURCE_ID ) ; if ( resourceModels . isEmpty ( ) ) { mute ( ) ; } else { resourceModels . stream ( ) . map ( resourceModel -> resourceModel . getResource ( ) instanceof Identification ? ( ( Identification ) resourceModel . getResource ( ) ) : null ) . filter ( Objects :: nonNull ) . filter ( this :: isOwner ) . findAny ( ) . ifPresent ( id -> mute ( ) ) ; } } if ( eventModel . containsDescriptor ( UnMuteEvent . ID ) ) { List < ResourceModel > resourceModels = eventModel . getListResourceContainer ( ) . provideResource ( SelectorResource . RESOURCE_ID ) ; if ( resourceModels . isEmpty ( ) ) { unMute ( ) ; } else { resourceModels . stream ( ) . map ( resourceModel -> resourceModel . getResource ( ) instanceof Identification ? ( ( Identification ) resourceModel . getResource ( ) ) : null ) . filter ( Objects :: nonNull ) . filter ( this :: isOwner ) . findAny ( ) . ifPresent ( id -> unMute ( ) ) ; } } if ( eventModel . containsDescriptor ( StopEvent . ID ) ) { List < ResourceModel > resourceModels = eventModel . getListResourceContainer ( ) . provideResource ( SelectorResource . RESOURCE_ID ) ; if ( resourceModels . isEmpty ( ) ) { stopSound ( ) ; } else { resourceModels . stream ( ) . map ( resourceModel -> resourceModel . getResource ( ) instanceof Identification ? ( ( Identification ) resourceModel . getResource ( ) ) : null ) . filter ( Objects :: nonNull ) . filter ( this :: isOwner ) . findAny ( ) . ifPresent ( id -> stopSound ( ) ) ; } } return eventModel ; }


Input: use this method to start playing sound ( only plays sound if it is not already playing ) [CODESPLIT] public Optional < CompletableFuture < Void > > startPlaying ( Runnable function ) { if ( isCurrentlyPlayingSound ) return Optional . empty ( ) ; CompletableFuture < Void > voidCompletableFuture = submit ( ( Runnable ) ( ) -> startedSound ( isUsingJava ) ) . thenRun ( ( ) -> { try { isCurrentlyPlayingSound = true ; function . run ( ) ; } finally { submit ( ( Runnable ) this :: endedSound ) ; isCurrentlyPlayingSound = false ; } } ) ; return Optional . of ( voidCompletableFuture ) ; }


Input: Shuts down the task engine service . [CODESPLIT] public void shutdown ( ) { if ( executor != null ) { executor . shutdownNow ( ) ; executor = null ; } if ( timer != null ) { timer . cancel ( ) ; timer = null ; } }


Input: Factory method to create a synchronized map . [CODESPLIT] public static < E > FilterableCollection < E > decorate ( FilterableCollection < E > collection ) { return new SynchronizedFilterableCollection < E > ( collection ) ; }


Input: ----------------------------------------------------------------------- [CODESPLIT] public FilterableCollection < E > filteredCollection ( final Filter < ? super E > filter ) { return SyncUtils . synchronizeRead ( lock , new Callback < FilterableCollection < E > > ( ) { @ Override protected void doAction ( ) { FilterableCollection < E > _col = getFilterableCollection ( ) . filteredCollection ( filter ) ; _return ( new SynchronizedFilterableCollection < E > ( _col , lock ) ) ; } } ) ; }


Input: Identical File Contents [CODESPLIT] public static Boolean contentEquals ( Path file1 , Path file2 ) throws IOException { if ( ! java . nio . file . Files . isRegularFile ( file1 ) ) throw new IllegalArgumentException ( file1 + "is not a regular file" ) ; if ( ! java . nio . file . Files . isRegularFile ( file2 ) ) throw new IllegalArgumentException ( file2 + "is not a regular file" ) ; FileChannel channel1 = null ; FileChannel channel2 = null ; MappedByteBuffer buffer1 = null ; MappedByteBuffer buffer2 = null ; try { long size1 = java . nio . file . Files . size ( file1 ) ; long size2 = java . nio . file . Files . size ( file2 ) ; if ( size1 != size2 ) return false ; long position = 0 ; long length = Math . min ( Integer . MAX_VALUE , size1 - position ) ; channel1 = FileChannel . open ( file1 ) ; channel2 = FileChannel . open ( file2 ) ; // Cannot map files larger than Integer.MAX_VALUE, // so we have to do it in pieces. while ( length > 0 ) { buffer1 = channel1 . map ( MapMode . READ_ONLY , position , length ) ; buffer2 = channel2 . map ( MapMode . READ_ONLY , position , length ) ; // if (!buffer1.equals(buffer2)) return false; // The line above is much slower than the line below. // It should not be, but it is, possibly because it is // loading the entire buffer into memory before comparing // the contents. See the corresponding unit test. EK for ( int i = 0 ; i < length ; i ++ ) if ( buffer1 . get ( ) != buffer2 . get ( ) ) return false ; position += length ; length = Math . min ( Integer . MAX_VALUE , size1 - position ) ; cleanDirectByteBuffer ( buffer1 ) ; buffer1 = null ; cleanDirectByteBuffer ( buffer2 ) ; buffer2 = null ; } } finally { // Is is important to clean up so we do not hold any // file locks, in case the caller wants to do something // else with the files. // In terms of functional programming, holding a lock after // returning to the caller would be an unwelcome side-effect. cleanDirectByteBuffer ( buffer1 ) ; cleanDirectByteBuffer ( buffer2 ) ; if ( channel1 != null ) try { channel1 . close ( ) ; } catch ( IOException e ) { if ( channel2 != null ) channel2 . close ( ) ; throw e ; } if ( channel2 != null ) channel2 . close ( ) ; } return true ; }


Input: Clean or unmap a direct ByteBuffer [CODESPLIT] public static void cleanDirectByteBuffer ( final ByteBuffer byteBuffer ) { if ( byteBuffer == null ) return ; if ( ! byteBuffer . isDirect ( ) ) throw new IllegalArgumentException ( "byteBuffer isn't direct!" ) ; AccessController . doPrivileged ( new PrivilegedAction < Void > ( ) { public Void run ( ) { try { Method cleanerMethod = byteBuffer . getClass ( ) . getMethod ( "cleaner" ) ; cleanerMethod . setAccessible ( true ) ; Object cleaner = cleanerMethod . invoke ( byteBuffer ) ; Method cleanMethod = cleaner . getClass ( ) . getMethod ( "clean" ) ; cleanMethod . setAccessible ( true ) ; cleanMethod . invoke ( cleaner ) ; } catch ( NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e ) { throw new RuntimeException ( "Could not clean MappedByteBuffer -- File may still be locked!" ) ; } return null ; // nothing to return } } ) ; }


Input: Rolls back the changes to the map . [CODESPLIT] public void rollback ( ) { if ( auto_commit ) return ; String id = getCurrentThreadId ( ) ; Entry < K , V > tab [ ] = table ; for ( int i = 0 ; i < tab . length ; i ++ ) { Entry < K , V > prev = table [ i ] ; Entry < K , V > e = prev ; while ( e != null ) { Entry < K , V > next = e . next ; if ( e . is ( Entry . ADDED , id ) ) { modCount ++ ; size -- ; if ( prev == e ) table [ i ] = next ; else prev . next = next ; } else if ( e . is ( Entry . DELETED , id ) ) e . setStatus ( Entry . NO_CHANGE , null ) ; prev = e ; e = next ; } } }


Input: Checks that this entry is valid for the current thread [CODESPLIT] private boolean validEntry ( final Entry < K , V > entry ) { if ( auto_commit || entry == null ) return ( entry != null ) ; String id = getCurrentThreadId ( ) ; return ! ( ( entry . is ( Entry . DELETED , id ) ) || ( entry . is ( Entry . ADDED , null ) && entry . is ( Entry . NO_CHANGE , id ) ) ) ; }


Input: Returns internal representation for key . Use NULL_KEY if key is null . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) static < T > T maskNull ( T key ) { return ( key == null ? ( T ) NULL_KEY : key ) ; }


Input: Returns a hash value for the specified object . In addition to the object s own hashCode this method applies a supplemental hash function which defends against poor quality hash functions . This is critical because HashMap uses power - of two length hash tables . <p > [CODESPLIT] static int hash ( Object x ) { int h = x . hashCode ( ) ; h += ~ ( h << 9 ) ; h ^= ( h >>> 14 ) ; h += ( h << 4 ) ; h ^= ( h >>> 10 ) ; return h ; }


Input: Check for equality of non - null reference x and possibly - null y . [CODESPLIT] static boolean eq ( Object x , Object y ) { return x == y || x . equals ( y ) ; }


Input: Returns the value to which the specified key is mapped in this identity hash map or <tt > null< / tt > if the map contains no mapping for this key . A return value of <tt > null< / tt > does not <i > necessarily< / i > indicate that the map contains no mapping for the key ; it is also possible that the map explicitly maps the key to <tt > null< / tt > . The <tt > containsKey< / tt > method may be used to distinguish these two cases . [CODESPLIT] @ Override public V get ( Object key ) { Object k = maskNull ( key ) ; int hash = hash ( k ) ; int i = indexFor ( hash , table . length ) ; Entry < K , V > e = table [ i ] ; while ( true ) { if ( e == null ) return null ; if ( e . hash == hash && validEntry ( e ) && eq ( k , e . key ) ) return e . value ; e = e . next ; } }


Input: Returns the entry associated with the specified key in the HashMap . Returns null if the HashMap contains no mapping for this key . [CODESPLIT] Entry < K , V > getEntry ( Object key ) { Object k = maskNull ( key ) ; int hash = hash ( k ) ; int i = indexFor ( hash , table . length ) ; Entry < K , V > e = table [ i ] ; while ( e != null && ! ( e . hash == hash && validEntry ( e ) && eq ( k , e . key ) ) ) e = e . next ; return e ; }


Input:
Associates the specified value with the specified key in this map . If the map previously contained a mapping for this key the old value is replaced . [CODESPLIT] @ Override public V put ( K key , V value ) throws ConcurrentModificationException { K k = maskNull ( key ) ; int hash = hash ( k ) ; int i = indexFor ( hash , table . length ) ; V oldValue = null ; for ( Entry < K , V > e = table [ i ] ; e != null ; e = e . next ) { if ( e . hash == hash && eq ( k , e . key ) ) { //check if someone else has a pending add for the same key
 if ( e . is ( Entry . ADDED , null ) && ! e . is ( Entry . ADDED , getCurrentThreadId ( ) ) ) throw new ConcurrentModificationException ( ) ; if ( validEntry ( e ) ) { oldValue = e . value ; //if not transactional can reuse entries
 if ( auto_commit ) { e . value = value ; return oldValue ; } else e . setStatus ( Entry . DELETED , getCurrentThreadId ( ) ) ; } } } modCount ++ ; addEntry ( hash , k , value , i ) ; return oldValue ; }


Input:
This method is used instead of put by constructors and pseudoconstructors ( clone readObject ) . It does not resize the table check for comodification etc . It calls createEntry rather than addEntry . [CODESPLIT] private void putForCreate ( K key , V value ) { K k = maskNull ( key ) ; int hash = hash ( k ) ; int i = indexFor ( hash , table . length ) ; /**
         * Look for preexisting entry for key.  This will never happen for
         * clone or deserialize.  It will only happen for construction if the
         * input Map is a sorted map whose ordering is inconsistent w/ equals.
         */ for ( Entry < K , V > e = table [ i ] ; e != null ; e = e . next ) { if ( e . hash == hash && eq ( k , e . key ) ) { e . value = value ; return ; } } createEntry ( hash , k , value , i ) ; }


Input: Rehashes the contents of this map into a new array with a larger capacity . This method is called automatically when the number of keys in this map reaches its threshold . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) void resize ( int newCapacity ) { Entry < K , V > [ ] oldTable = table ; int oldCapacity = oldTable . length ; if ( oldCapacity == MAXIMUM_CAPACITY ) { threshold = Integer . MAX_VALUE ; return ; } Entry < K , V > [ ] newTable = new Entry [ newCapacity ] ; transfer ( newTable ) ; table = newTable ; threshold = ( int ) ( newCapacity * loadFactor ) ; }


Input:
Copies all of the mappings from the specified map to this map These mappings will replace any mappings that this map had for any of the keys currently in the specified map . [CODESPLIT] @ Override public void putAll ( Map < ? extends K , ? extends V > m ) { int numKeysToBeAdded = m . size ( ) ; if ( numKeysToBeAdded == 0 ) return ; /*
         * Expand the map if the map if the number of mappings to be added
         * is greater than or equal to threshold.  This is conservative; the
         * obvious condition is (m.size() + size) >= threshold, but this
         * condition could result in a map with twice the appropriate capacity,
         * if the keys to be added overlap with the keys already in this map.
         * By using the conservative calculation, we subject ourself
         * to at most one extra resize.
         */ if ( numKeysToBeAdded > threshold ) { int targetCapacity = ( int ) ( numKeysToBeAdded / loadFactor + 1 ) ; if ( targetCapacity > MAXIMUM_CAPACITY ) targetCapacity = MAXIMUM_CAPACITY ; int newCapacity = table . length ; while ( newCapacity < targetCapacity ) newCapacity <<= 1 ; if ( newCapacity > table . length ) resize ( newCapacity ) ; } for ( Iterator < ? extends Map . Entry < ? extends K , ? extends V > > i = m . entrySet ( ) . iterator ( ) ; i . hasNext ( ) ; ) { Map . Entry < ? extends K , ? extends V > e = i . next ( ) ; put ( e . getKey ( ) , e . getValue ( ) ) ; } }


Input: Removes the mapping for this key from this map if present . [CODESPLIT] @ Override public V remove ( Object key ) throws ConcurrentModificationException { Entry < K , V > e = removeEntryForKey ( key ) ; return ( e == null ? null : e . value ) ; }


Input: Removes and returns the entry associated with the specified key in the HashMap . Returns null if the HashMap contains no mapping for this key . [CODESPLIT] Entry < K , V > removeEntryForKey ( Object key ) throws ConcurrentModificationException { Object k = maskNull ( key ) ; int hash = hash ( k ) ; int i = indexFor ( hash , table . length ) ; Entry < K , V > prev = table [ i ] ; Entry < K , V > e = prev ; while ( e != null ) { Entry < K , V > next = e . next ; if ( e . hash == hash && validEntry ( e ) && eq ( k , e . key ) ) { if ( e . is ( Entry . DELETED , null ) && ! e . is ( Entry . DELETED , getCurrentThreadId ( ) ) ) throw new ConcurrentModificationException ( ) ; if ( auto_commit ) { modCount ++ ; size -- ; if ( prev == e ) table [ i ] = next ; else prev . next = next ; return e ; } else e . setStatus ( Entry . DELETED , getCurrentThreadId ( ) ) ; } prev = e ; e = next ; } return e ; }


Input: Special version of remove for EntrySet . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) Entry < K , V > removeMapping ( Object o ) { if ( ! ( o instanceof Map . Entry ) ) return null ; Map . Entry < K , V > entry = ( Map . Entry < K , V > ) o ; Object k = maskNull ( entry . getKey ( ) ) ; int hash = hash ( k ) ; int i = indexFor ( hash , table . length ) ; Entry < K , V > prev = table [ i ] ; Entry < K , V > e = prev ; while ( e != null ) { Entry < K , V > next = e . next ; if ( e . hash == hash && validEntry ( e ) && e . equals ( entry ) ) { if ( auto_commit ) { modCount ++ ; size -- ; if ( prev == e ) table [ i ] = next ; else prev . next = next ; } else e . setStatus ( Entry . DELETED , getCurrentThreadId ( ) ) ; return e ; } prev = e ; e = next ; } return e ; }


Input: Removes all mappings from this map . [CODESPLIT] @ Override public void clear ( ) { modCount ++ ; Entry < K , V > tab [ ] = table ; for ( int i = 0 ; i < tab . length ; i ++ ) tab [ i ] = null ; size = 0 ; }


Input: Add a new entry with the specified key value and hash code to the specified bucket . It is the responsibility of this method to resize the table if appropriate . [CODESPLIT] void addEntry ( int hash , K key , V value , int bucketIndex ) { table [ bucketIndex ] = new Entry < K , V > ( hash , key , value , table [ bucketIndex ] ) ; if ( ! auto_commit ) table [ bucketIndex ] . setStatus ( Entry . ADDED , getCurrentThreadId ( ) ) ; if ( size ++ >= threshold ) resize ( 2 * table . length ) ; }


Input: Like addEntry except that this version is used when creating entries as part of Map construction or pseudo - construction ( cloning deserialization ) . This version needn t worry about resizing the table . [CODESPLIT] void createEntry ( int hash , K key , V value , int bucketIndex ) { table [ bucketIndex ] = new Entry < K , V > ( hash , key , value , table [ bucketIndex ] ) ; size ++ ; }


Input: Creates map delegate . [CODESPLIT] private static < K , V > ImmutableMap < K , V > createDelegate ( final Map < K , V > base , final Set < ? extends K > keys , final Function < K , V > augmentation ) { final ImmutableMap . Builder < K , V > builder = ImmutableMap . builder ( ) ; builder . putAll ( base ) ; keys . stream ( ) . filter ( key -> ! base . containsKey ( key ) ) . forEach ( key -> builder . put ( key , augmentation . apply ( key ) ) ) ; return builder . build ( ) ; }


Input:
Parses the given date string in either of the three profiles of  XEP - 0082 - XMPP Date and Time Profiles or  XEP - 0091 - Legacy Delayed Delivery format .
 This method uses internal date formatters and is thus threadsafe . [CODESPLIT] public static Date parseDate ( String dateString ) throws ParseException { Matcher matcher = xep0091Pattern . matcher ( dateString ) ; /*
         * if date is in XEP-0091 format handle ambiguous dates missing the
         * leading zero in month and day
         */ if ( matcher . matches ( ) ) { int length = dateString . split ( "T" ) [ 0 ] . length ( ) ; if ( length < 8 ) { Date date = handleDateWithMissingLeadingZeros ( dateString , length ) ; if ( date != null ) return date ; } else { synchronized ( xep0091Formatter ) { return xep0091Formatter . parse ( dateString ) ; } } } else { for ( PatternCouplings coupling : couplings ) { matcher = coupling . pattern . matcher ( dateString ) ; if ( matcher . matches ( ) ) { if ( coupling . needToConvertTimeZone ) { dateString = coupling . convertTime ( dateString ) ; } synchronized ( coupling . formatter ) { return coupling . formatter . parse ( dateString ) ; } } } } /*
         * We assume it is the XEP-0082 DateTime profile with no milliseconds at
         * this point. If it isn't, is is just not parseable, then we attempt to
         * parse it regardless and let it throw the ParseException.
         */ synchronized ( dateTimeNoMillisFormatter ) { return dateTimeNoMillisFormatter . parse ( dateString ) ; } }


Input: Parses the given date string in different ways and returns the date that lies in the past and / or is nearest to the current date - time . [CODESPLIT] private static Date handleDateWithMissingLeadingZeros ( String stampString , int dateLength ) throws ParseException { if ( dateLength == 6 ) { synchronized ( xep0091Date6DigitFormatter ) { return xep0091Date6DigitFormatter . parse ( stampString ) ; } } Calendar now = Calendar . getInstance ( ) ; Calendar oneDigitMonth = parseXEP91Date ( stampString , xep0091Date7Digit1MonthFormatter ) ; Calendar twoDigitMonth = parseXEP91Date ( stampString , xep0091Date7Digit2MonthFormatter ) ; List < Calendar > dates = filterDatesBefore ( now , oneDigitMonth , twoDigitMonth ) ; if ( ! dates . isEmpty ( ) ) { return determineNearestDate ( now , dates ) . getTime ( ) ; } return null ; }


Input: Returns the name portion of a XMPP address . For example for the address matt@jivesoftware . com / Smack matt would be returned . If no username is present in the address the empty string will be returned . [CODESPLIT] public static String parseName ( String XMPPAddress ) { if ( XMPPAddress == null ) { return null ; } int atIndex = XMPPAddress . lastIndexOf ( "@" ) ; if ( atIndex <= 0 ) { return "" ; } else { return XMPPAddress . substring ( 0 , atIndex ) ; } }


Input: Returns the server portion of a XMPP address . For example for the address matt@jivesoftware . com / Smack jivesoftware . com would be returned . If no server is present in the address the empty string will be returned . [CODESPLIT] public static String parseServer ( String XMPPAddress ) { if ( XMPPAddress == null ) { return null ; } int atIndex = XMPPAddress . lastIndexOf ( "@" ) ; // If the String ends with '@', return the empty string. if ( atIndex + 1 > XMPPAddress . length ( ) ) { return "" ; } int slashIndex = XMPPAddress . indexOf ( "/" ) ; if ( slashIndex > 0 && slashIndex > atIndex ) { return XMPPAddress . substring ( atIndex + 1 , slashIndex ) ; } else { return XMPPAddress . substring ( atIndex + 1 ) ; } }


Input: Returns the resource portion of a XMPP address . For example for the address matt@jivesoftware . com / Smack Smack would be returned . If no resource is present in the address the empty string will be returned . [CODESPLIT] public static String parseResource ( String XMPPAddress ) { if ( XMPPAddress == null ) { return null ; } int slashIndex = XMPPAddress . indexOf ( "/" ) ; if ( slashIndex + 1 > XMPPAddress . length ( ) || slashIndex < 0 ) { return "" ; } else { return XMPPAddress . substring ( slashIndex + 1 ) ; } }


Input: Returns the XMPP address with any resource information removed . For example for the address matt@jivesoftware . com / Smack matt@jivesoftware . com would be returned . [CODESPLIT] public static String parseBareAddress ( String XMPPAddress ) { if ( XMPPAddress == null ) { return null ; } int slashIndex = XMPPAddress . indexOf ( "/" ) ; if ( slashIndex < 0 ) { return XMPPAddress ; } else if ( slashIndex == 0 ) { return "" ; } else { return XMPPAddress . substring ( 0 , slashIndex ) ; } }


Input: Returns true if jid is a full JID ( i . e . a JID with resource part ) . [CODESPLIT] public static boolean isFullJID ( String jid ) { if ( parseName ( jid ) . length ( ) <= 0 || parseServer ( jid ) . length ( ) <= 0 || parseResource ( jid ) . length ( ) <= 0 ) { return false ; } return true ; }


Input: Escapes the node portion of a JID according to JID Escaping ( JEP - 0106 ) . Escaping replaces characters prohibited by node - prep with escape sequences as follows : <p > [CODESPLIT] public static String escapeNode ( String node ) { if ( node == null ) { return null ; } StringBuilder buf = new StringBuilder ( node . length ( ) + 8 ) ; for ( int i = 0 , n = node . length ( ) ; i < n ; i ++ ) { char c = node . charAt ( i ) ; switch ( c ) { case ' ' : buf . append ( "\\22" ) ; break ; case ' ' : buf . append ( "\\26" ) ; break ; case ' ' : buf . append ( "\\27" ) ; break ; case ' ' : buf . append ( "\\2f" ) ; break ; case ' ' : buf . append ( "\\3a" ) ; break ; case ' ' : buf . append ( "\\3c" ) ; break ; case ' ' : buf . append ( "\\3e" ) ; break ; case ' ' : buf . append ( "\\40" ) ; break ; case ' ' : buf . append ( "\\5c" ) ; break ; default : { if ( Character . isWhitespace ( c ) ) { buf . append ( "\\20" ) ; } else { buf . append ( c ) ; } } } } return buf . toString ( ) ; }


Input: Un - escapes the node portion of a JID according to JID Escaping ( JEP - 0106 ) . <p > Escaping replaces characters prohibited by node - prep with escape sequences as follows : <p > [CODESPLIT] public static String unescapeNode ( String node ) { if ( node == null ) { return null ; } char [ ] nodeChars = node . toCharArray ( ) ; StringBuilder buf = new StringBuilder ( nodeChars . length ) ; for ( int i = 0 , n = nodeChars . length ; i < n ; i ++ ) { compare : { char c = node . charAt ( i ) ; if ( c == ' ' && i + 2 < n ) { char c2 = nodeChars [ i + 1 ] ; char c3 = nodeChars [ i + 2 ] ; if ( c2 == ' ' ) { switch ( c3 ) { case ' ' : buf . append ( ' ' ) ; i += 2 ; break compare ; case ' ' : buf . append ( ' ' ) ; i += 2 ; break compare ; case ' ' : buf . append ( ' ' ) ; i += 2 ; break compare ; case ' ' : buf . append ( ' ' ) ; i += 2 ; break compare ; case ' ' : buf . append ( ' ' ) ; i += 2 ; break compare ; } } else if ( c2 == ' ' ) { switch ( c3 ) { case ' ' : buf . append ( ' ' ) ; i += 2 ; break compare ; case ' ' : buf . append ( ' ' ) ; i += 2 ; break compare ; case ' ' : buf . append ( ' ' ) ; i += 2 ; break compare ; } } else if ( c2 == ' ' ) { if ( c3 == ' ' ) { buf . append ( "@" ) ; i += 2 ; break compare ; } } else if ( c2 == ' ' ) { if ( c3 == ' ' ) { buf . append ( "\\" ) ; i += 2 ; break compare ; } } } buf . append ( c ) ; } } return buf . toString ( ) ; }


Input: Encodes a string for use in an XML attribute by escaping characters with a special meaning . In particular white spaces are encoded as character references such that they are not replaced by on parsing . [CODESPLIT] private static String xmlAttribEncodeBinary ( String value ) { StringBuilder s = new StringBuilder ( ) ; char buf [ ] = value . toCharArray ( ) ; for ( char c : buf ) { switch ( c ) { case ' ' : s . append ( "<" ) ; break ; case ' ' : s . append ( ">" ) ; break ; case ' ' : s . append ( "&" ) ; break ; case ' ' : s . append ( """ ) ; break ; case ' ' : s . append ( "'" ) ; break ; default : if ( c <= 0x1f || ( 0x7f <= c && c <= 0x9f ) ) { // includes \t, \n, // \r s . append ( "&#x" ) ; s . append ( String . format ( "%X" , ( int ) c ) ) ; s . append ( ' ' ) ; } else { s . append ( c ) ; } } } return s . toString ( ) ; }


Input: Hashes a String using the SHA - 1 algorithm and returns the result as a String of hexadecimal numbers . This method is synchronized to avoid excessive MessageDigest object creation . If calling this method becomes a bottleneck in your code you may wish to maintain a pool of MessageDigest objects instead of using this method . <p > A hash is a one - way function -- that is given an input an output is easily computed . However given the output the input is almost impossible to compute . This is useful for passwords since we can store the hash and a hacker will then have a very hard time determining the original password . [CODESPLIT] public synchronized static String hash ( String data ) { if ( digest == null ) { try { digest = MessageDigest . getInstance ( "SHA-1" ) ; } catch ( NoSuchAlgorithmException nsae ) { log . log ( Level . ERROR , "Failed to load the SHA-1 MessageDigest. Smack will be unable to function normally." , nsae ) ; } } // Now, compute hash. try { digest . update ( data . getBytes ( "UTF-8" ) ) ; } catch ( UnsupportedEncodingException e ) { log . log ( Level . ERROR , "Error computing hash" , e ) ; } return encodeHex ( digest . digest ( ) ) ; }


Input: Encodes an array of bytes as String representation of hexadecimal . [CODESPLIT] public static String encodeHex ( byte [ ] bytes ) { StringBuilder hex = new StringBuilder ( bytes . length * 2 ) ; for ( byte aByte : bytes ) { if ( ( ( int ) aByte & 0xff ) < 0x10 ) { hex . append ( "0" ) ; } hex . append ( Integer . toString ( ( int ) aByte & 0xff , 16 ) ) ; } return hex . toString ( ) ; }


Input: Encodes a String as a base64 String . [CODESPLIT] public static String encodeBase64 ( String data ) { byte [ ] bytes = null ; try { bytes = data . getBytes ( "ISO-8859-1" ) ; } catch ( UnsupportedEncodingException uee ) { throw new IllegalStateException ( uee ) ; } return encodeBase64 ( bytes ) ; }


Input: Encodes a byte array into a bse64 String . [CODESPLIT] public static String encodeBase64 ( byte [ ] data , int offset , int len , boolean lineBreaks ) { return Base64 . encodeBytes ( data , offset , len , ( lineBreaks ? Base64 . NO_OPTIONS : Base64 . DONT_BREAK_LINES ) ) ; }