idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
19,400
String getStatistics ( ) { String msg = "PropertyChanges stats :\r\n" + "# registered handlers : " + nbRegisteredHandlers + "\r\n" + "# notifications : " + nbNotifications + "\r\n" + "# dispatches : " + nbDispatches + "\r\n" ; StringBuilder details = new StringBuilder ( ) ; for ( Entry < String , Integer > e : counts . entrySet ( ) ) { details . append ( e . getKey ( ) + " => " + e . getValue ( ) ) ; Integer oldCount = oldCounts . get ( e . getKey ( ) ) ; if ( oldCount != null ) details . append ( " (diff: " + ( e . getValue ( ) - oldCount ) + ")" ) ; details . append ( "\n" ) ; } oldCounts = new HashMap < > ( counts ) ; return msg + details . toString ( ) ; }
Show an alert containing useful information for debugging . It also shows how many registrations happened since last call ; that s useful to detect registration leaks .
19,401
public < T > T manageTransaction ( DatabaseContext ctx , TransactionManagedAction < T > action ) { ctx . db . startTransaction ( ) ; try { T result = action . execute ( ctx ) ; ctx . db . commit ( ) ; return result ; } catch ( Exception exception ) { ctx . db . rollback ( ) ; throw new ManagedTransactionException ( "Exception during managed transaction, see cause for details" , exception ) ; } }
it everything goes fine commit
19,402
public synchronized DatabaseContextFactory dbFactory ( String databaseUri ) { DatabaseContextFactory factory = new DatabaseContextFactory ( ) ; if ( ! factory . init ( databaseUri ) ) { log . error ( "Cannot initialize database connection pool, it won't be available to the program !" ) ; return null ; } return factory ; }
handles the database connection creation
19,403
public static Throwable getCause ( Throwable e , Class < ? extends Throwable > ... causes ) { if ( ( e == null ) || ( causes == null ) || ( causes . length < 1 ) ) { return null ; } else if ( isInstance ( e , causes ) ) { if ( ( ( e . getCause ( ) == null ) || ( e . getCause ( ) . equals ( e ) || ( ! equals ( e . getClass ( ) , causes ) ) ) ) ) { return e ; } else { return getCause ( e . getCause ( ) , causes ) ; } } else if ( ( e . getCause ( ) == null ) && ( e instanceof InvocationTargetException ) ) { return getCause ( ( ( InvocationTargetException ) e ) . getTargetException ( ) , causes ) ; } else if ( e . getCause ( ) == null ) { return null ; } else { return getCause ( e . getCause ( ) , causes ) ; } }
Gets the cause which are one of the given expected causes . This method is useful when you have to find a cause within unexpected or unpredictable exception wrappings .
19,404
public static HttpMockServer start ( ConfigReader configReader , NetworkType networkType ) { return HttpMockServer . startMockApiServer ( configReader , networkType ) ; }
Starts local HTTP server .
19,405
@ SuppressWarnings ( "unchecked" ) public static < T > T getBean ( String name ) { BeanManager bm = getBeanManager ( ) ; Bean < ? > bean = bm . getBeans ( name ) . iterator ( ) . next ( ) ; CreationalContext < ? > ctx = bm . createCreationalContext ( bean ) ; return ( T ) bm . getReference ( bean , bean . getBeanClass ( ) , ctx ) ; }
Retrieves the instance for a named bean by the given name
19,406
public int toInt ( ) { int day = ( ( year + 1900 ) * 12 + month ) * 31 + ( date - 1 ) ; if ( day < TIME_BEGIN ) day = TIME_BEGIN ; else if ( day > TIME_END ) day = TIME_END ; return day ; }
encodes the date into an int
19,407
public int indexOf ( Widget w ) { for ( int i = 0 ; i < size ; ++ i ) { if ( array [ i ] == w ) { return i ; } } return - 1 ; }
Gets the index of the specified index .
19,408
public void insert ( Shape w , int beforeIndex ) { if ( ( beforeIndex < 0 ) || ( beforeIndex > size ) ) { throw new IndexOutOfBoundsException ( ) ; } if ( size == array . length ) { Shape [ ] newArray = new Shape [ array . length * 2 ] ; for ( int i = 0 ; i < array . length ; ++ i ) { newArray [ i ] = array [ i ] ; } array = newArray ; } ++ size ; for ( int i = size - 1 ; i > beforeIndex ; -- i ) { array [ i ] = array [ i - 1 ] ; } array [ beforeIndex ] = w ; }
Inserts a widget before the specified index .
19,409
public void remove ( int index ) { if ( ( index < 0 ) || ( index >= size ) ) { throw new IndexOutOfBoundsException ( ) ; } -- size ; for ( int i = index ; i < size ; ++ i ) { array [ i ] = array [ i + 1 ] ; } array [ size ] = null ; }
Removes the widget at the specified index .
19,410
public void remove ( Widget w ) { int index = indexOf ( w ) ; if ( index == - 1 ) { throw new NoSuchElementException ( ) ; } remove ( index ) ; }
Removes the specified widget .
19,411
Class < ? > getSetterPropertyType ( Clazz < ? > clazz , String name ) { ClassInfoCache cache = retrieveCache ( clazz ) ; Class < ? > res = cache . getSetterType ( name ) ; if ( res != null ) return res ; String setterName = "set" + capitalizeFirstLetter ( name ) ; Method setter = clazz . getMethod ( setterName ) ; if ( setter != null && setter . getParameterTypes ( ) . size ( ) == 1 ) { res = setter . getParameterTypes ( ) . get ( 0 ) ; } else { Field field = clazz . getAllField ( name ) ; if ( field != null ) res = field . getType ( ) ; } if ( res != null ) cache . setSetterType ( name , res ) ; return res ; }
Returns the class of the setter property . It can be this of the setter or of the field
19,412
boolean hasObjectDynamicProperty ( Object object , String propertyName ) { DynamicPropertyBag bag = propertyBagAccess . getObjectDynamicPropertyBag ( object ) ; return bag != null && bag . contains ( propertyName ) ; }
Whether a dynamic property value has already been set on this object
19,413
public void register ( Object source , String path ) { unregister ( ) ; dataBinding = Binder . bind ( source , path ) . mode ( Mode . OneWay ) . to ( adapter ) . activate ( ) ; }
Registers the databinding source . If any previous source was binded its bindings are freed .
19,414
public static BindingCreation bind ( Object source , String propertyPath ) { return createBinder ( new CompositePropertyAdapter ( source , propertyPath ) ) ; }
First step accepts a data binding source definition and creates a binder
19,415
public static DataBinding map ( Object source , Object destination ) { return bindObject ( source ) . mapTo ( destination ) ; }
Maps two objects together . All matching fields will then be two - way data - bound .
19,416
public HttpResponse postTopicMessage ( String topicName , String jsonPayload , Map < String , String > headers ) throws RestClientException { return postMessage ( Type . TOPIC , topicName , jsonPayload , headers ) ; }
Sends a message to the REST endpoint in order to put a message on the given topic .
19,417
public HttpResponse postQueueMessage ( String queueName , String jsonPayload , Map < String , String > headers ) throws RestClientException { return postMessage ( Type . QUEUE , queueName , jsonPayload , headers ) ; }
Sends a message to the REST endpoint in order to put a message on the given queue .
19,418
public void run ( AcceptsOneWidget container ) { container . setWidget ( UiBuilder . addIn ( new VerticalPanel ( ) , personListWidget , personneForm , categoryForm , nextButton ) ) ; Bind ( personListWidget , "selectedPersonne" ) . Mode ( Mode . OneWay ) . Log ( "PERSONNEFORM" ) . To ( personneForm , "personne" ) ; Bind ( personListWidget , "selectedPersonne.category" ) . Mode ( Mode . OneWay ) . MapTo ( categoryForm ) ; Bind ( personListWidget , "selectedPersonne.description" ) . Mode ( Mode . OneWay ) . To ( new WriteOnlyPropertyAdapter ( ) { public void setValue ( Object object ) { Window . setTitle ( ( String ) object ) ; } } ) ; personListWidget . setPersonList ( famille ) ; personListWidget . setSelectedPersonne ( famille . get ( 0 ) ) ; nextButton . addClickHandler ( nextButtonClickHandler ) ; }
Runs the demo
19,419
private void _RemoveValidator ( Row item , int column ) { if ( m_currentEditedItem == null && m_currentEditedColumn < 0 ) return ; if ( m_callback != null ) m_callback . onTouchCellContent ( item , column ) ; if ( m_currentEditor != null ) m_currentEditor . removeFromParent ( ) ; m_currentEditor = null ; m_currentEditedItem = null ; m_currentEditedColumn = - 1 ; }
just replace the validator widget by a text in the table
19,420
public static void processFile ( String input , String mappingPath , String outputFile , boolean doPrune , Log log ) throws IOException { Set < String > usedClassNames = new HashSet < > ( ) ; input = replaceClassNames ( input , mappingPath , usedClassNames , log ) ; log . debug ( usedClassNames . size ( ) + " used css classes in the mapping file" ) ; log . debug ( "used css classes : " + usedClassNames ) ; CssRewriter cssRewriter = new CssRewriter ( usedClassNames , doPrune , log ) ; input = cssRewriter . process ( input ) ; input += "\r\n// generated by HexaCss maven plugin, see http://www.lteconsulting.fr/hexacss" ; writeFile ( outputFile , input , log ) ; }
Process an input file
19,421
public void updateGroup ( long groupId , String name , boolean isPrivate ) { LinkedMultiValueMap < String , String > params = new LinkedMultiValueMap < String , String > ( ) ; params . set ( "name" , name ) ; params . set ( "private" , String . valueOf ( isPrivate ) ) ; restTemplate . put ( buildUri ( "groups/" + groupId ) , params ) ; }
Method returns 401 from Yammer so it isn t visible in GroupOperations yet
19,422
static Map < String , String > getVersionAttributes ( URL url ) throws IOException { Map < String , String > ret = new LinkedHashMap < > ( ) ; try ( InputStream inputStream = url . openStream ( ) ) { Manifest manifest = new Manifest ( inputStream ) ; Attributes attributes = manifest . getMainAttributes ( ) ; for ( String key : VERSION_ATTRIBUTES ) { final String value = attributes . getValue ( key ) ; ret . put ( key , value == null ? UNKNOWN_VALUE : value ) ; } } return ret ; }
For the sake of unit testing
19,423
protected View createOverlayView ( ) { LinearLayout ll = new LinearLayout ( getContext ( ) ) ; ll . setLayoutParams ( new FrameLayout . LayoutParams ( FrameLayout . LayoutParams . MATCH_PARENT , FrameLayout . LayoutParams . MATCH_PARENT ) ) ; ll . setGravity ( Gravity . CENTER ) ; View progressBar = createProgressBar ( ) ; ll . addView ( progressBar ) ; return ll ; }
create loading mask
19,424
protected String getNestName ( ) { if ( nestName == null || nestName . equals ( NestSubsystemExtension . NEST_NAME_AUTOGENERATE ) ) { return this . envServiceValue . getValue ( ) . getNodeName ( ) ; } else { return nestName ; } }
Do not call this until the nest has been initialized - it needs a dependent service .
19,425
@ RobotKeyword ( "Connect to MQTT Broker" ) @ ArgumentNames ( { "broker" , "clientId" } ) public void connectToMQTTBroker ( String broker , String clientId ) throws MqttException { client = new MqttClient ( broker , clientId ) ; System . out . println ( "*INFO:" + System . currentTimeMillis ( ) + "* connecting to broker" ) ; client . connect ( ) ; System . out . println ( "*INFO:" + System . currentTimeMillis ( ) + "* connected" ) ; }
Connect to an MQTT broker .
19,426
@ ArgumentNames ( { "topic" , "message" } ) public void publishToMQTTSynchronously ( String topic , Object message ) throws MqttException { publishToMQTTSynchronously ( topic , message , 0 , false ) ; }
Publish a message to a topic
19,427
@ RobotKeyword ( "Publish to MQTT Synchronously" ) @ ArgumentNames ( { "topic" , "message" , "qos=0" , "retained=false" } ) public void publishToMQTTSynchronously ( String topic , Object message , int qos , boolean retained ) throws MqttException { MqttMessage msg ; if ( message instanceof String ) { msg = new MqttMessage ( message . toString ( ) . getBytes ( ) ) ; } else { msg = new MqttMessage ( ( byte [ ] ) message ) ; } msg . setQos ( qos ) ; msg . setRetained ( retained ) ; System . out . println ( "*INFO:" + System . currentTimeMillis ( ) + "* publishing message" ) ; client . publish ( topic , msg ) ; System . out . println ( "*INFO:" + System . currentTimeMillis ( ) + "* published" ) ; }
Publish a message to a topic with specified qos and retained flag
19,428
@ RobotKeyword ( "Disconnect from MQTT Broker" ) public void disconnectFromMQTTBroker ( ) { if ( client != null ) { try { client . disconnect ( ) ; } catch ( MqttException e ) { throw new RuntimeException ( e . getLocalizedMessage ( ) ) ; } } }
Disconnect from MQTT Broker
19,429
@ RobotKeyword ( "Subscribe to MQTT Broker and validate that it received a specific message" ) @ ArgumentNames ( { "broker" , "clientId" , "topic" , "expectedPayload" , "timeout" } ) public void subscribeToMQTTAndValidate ( String broker , String clientId , String topic , String expectedPayload , long timeout ) { MqttClient client = null ; try { MqttClientPersistence persistence = new MemoryPersistence ( ) ; client = new MqttClient ( broker , clientId , persistence ) ; MqttConnectOptions connOpts = new MqttConnectOptions ( ) ; connOpts . setCleanSession ( false ) ; MQTTResponseHandler handler = new MQTTResponseHandler ( ) ; client . setCallback ( handler ) ; System . out . println ( "*INFO:" + System . currentTimeMillis ( ) + "* Connecting to broker: " + broker ) ; client . connect ( connOpts ) ; System . out . println ( "*INFO:" + System . currentTimeMillis ( ) + "* Subscribing to topic: " + topic ) ; client . subscribe ( topic ) ; System . out . println ( "*INFO:" + System . currentTimeMillis ( ) + "* Subscribed to topic: " + topic ) ; System . out . println ( "*INFO:" + System . currentTimeMillis ( ) + "* Waiting for message to arrive" ) ; boolean validated = false ; byte [ ] payload ; MqttMessage message ; long endTime = System . currentTimeMillis ( ) + timeout ; while ( true ) { message = handler . getNextMessage ( timeout ) ; if ( message != null ) { payload = message . getPayload ( ) ; String payloadStr = new String ( payload ) ; if ( expectedPayload . isEmpty ( ) || ( payloadStr . matches ( expectedPayload ) ) ) { validated = true ; break ; } } if ( ( timeout = endTime - System . currentTimeMillis ( ) ) <= 0 ) { System . out . println ( "*DEBUG:" + System . currentTimeMillis ( ) + "* timeout: " + timeout ) ; break ; } } if ( ! validated ) { throw new RuntimeException ( "The expected payload didn't arrive in the topic" ) ; } } catch ( MqttException e ) { throw new RuntimeException ( e . getLocalizedMessage ( ) ) ; } finally { try { client . disconnect ( ) ; } catch ( MqttException e ) { } } }
Subscribe to an MQTT broker and validate that a message with specified payload is received
19,430
private String _getUniqueKey ( ) { StringBuilder b = new StringBuilder ( ) ; b . append ( service ) ; b . append ( "#" ) ; b . append ( method ) ; if ( params != null ) { b . append ( "#" ) ; b . append ( params . toString ( ) ) ; } return b . toString ( ) ; }
calculate the unique key of that request
19,431
public void initialize ( @ Initialized ( ApplicationScoped . class ) Object ignore ) { log . debugf ( "Initializing [%s]" , this . getClass ( ) . getName ( ) ) ; try { feedSessionListenerProducer = new BiFunction < String , Session , WsSessionListener > ( ) { public WsSessionListener apply ( String key , Session session ) { final Endpoint endpoint = Constants . FEED_COMMAND_QUEUE ; BasicMessageListener < BasicMessage > busEndpointListener = new FeedBusEndpointListener ( session , key , endpoint ) ; return new BusWsSessionListener ( Constants . HEADER_FEEDID , key , endpoint , busEndpointListener ) ; } } ; wsEndpoints . getFeedSessions ( ) . addWsSessionListenerProducer ( feedSessionListenerProducer ) ; uiClientSessionListenerProducer = new BiFunction < String , Session , WsSessionListener > ( ) { public WsSessionListener apply ( String key , Session session ) { final Endpoint endpoint = Constants . UI_COMMAND_QUEUE ; BasicMessageListener < BasicMessage > busEndpointListener = new UiClientBusEndpointListener ( commandContextFactory , busCommands , endpoint ) ; return new BusWsSessionListener ( Constants . HEADER_UICLIENTID , key , endpoint , busEndpointListener ) ; } } ; wsEndpoints . getUiClientSessions ( ) . addWsSessionListenerProducer ( uiClientSessionListenerProducer ) ; } catch ( Exception e ) { log . errorCouldNotInitialize ( e , this . getClass ( ) . getName ( ) ) ; } }
This creates the bi - function listener - producers that will create listeners which will create JMS bus listeners for each websocket session that gets created in the future .
19,432
void modifyData ( final TrieNode < V > node , final V value ) { node . value = value ; ++ modCount ; ++ size ; }
Sets the given value as the new value on the given node increases size and modCount .
19,433
private void addNode ( final TrieNode < V > node , final CharSequence key , final int beginIndex , final TrieNode < V > newNode ) { final int lastKeyIndex = key . length ( ) - 1 ; TrieNode < V > currentNode = node ; int i = beginIndex ; for ( ; i < lastKeyIndex ; i ++ ) { final TrieNode < V > nextNode = new TrieNode < V > ( false ) ; currentNode . children . put ( key . charAt ( i ) , nextNode ) ; currentNode = nextNode ; } currentNode . children . put ( key . charAt ( i ) , newNode ) ; }
Adds the given new node to the node with the given key beginning at beginIndex .
19,434
V removeMapping ( final Object o ) { if ( ! ( o instanceof Map . Entry ) ) { throw new IllegalArgumentException ( ) ; } @ SuppressWarnings ( "unchecked" ) final Entry < ? extends CharSequence , V > e = ( Map . Entry < ? extends CharSequence , V > ) o ; final CharSequence key = keyCheck ( e . getKey ( ) ) ; final V value = e . getValue ( ) ; final TrieNode < V > currentNode = findPreviousNode ( key ) ; if ( currentNode == null ) { return null ; } final TrieNode < V > node = currentNode . children . get ( key . charAt ( key . length ( ) - 1 ) ) ; if ( node == null || ! node . inUse ) { return null ; } final V removed = node . value ; if ( removed != value && ( removed == null || ! removed . equals ( value ) ) ) { return null ; } node . unset ( ) ; -- size ; ++ modCount ; if ( node . children . isEmpty ( ) ) { compact ( key ) ; } return removed ; }
Special version of remove for EntrySet .
19,435
private void compact ( final CharSequence key ) { final int keyLength = key . length ( ) ; TrieNode < V > currentNode = getRoot ( ) ; TrieNode < V > lastInUseNode = currentNode ; int lastInUseIndex = 0 ; for ( int i = 0 ; i < keyLength && currentNode != null ; i ++ ) { if ( currentNode . inUse ) { lastInUseNode = currentNode ; lastInUseIndex = i ; } currentNode = currentNode . children . get ( key . charAt ( i ) ) ; } currentNode = lastInUseNode ; for ( int i = lastInUseIndex ; i < keyLength ; i ++ ) { currentNode = currentNode . children . remove ( key . charAt ( i ) ) . unset ( ) ; } }
Compact the trie by removing unused nodes on the path that is specified by the given key .
19,436
public static String getTypeQualifiedName ( TypeMirror type ) throws CodeGenerationIncompleteException { if ( type . toString ( ) . equals ( "<any>" ) ) { throw new CodeGenerationIncompleteException ( "Type reported as <any> is likely a not-yet " + "generated parameterized type." ) ; } switch ( type . getKind ( ) ) { case ARRAY : return getTypeQualifiedName ( ( ( ArrayType ) type ) . getComponentType ( ) ) + "[]" ; case BOOLEAN : return "boolean" ; case BYTE : return "byte" ; case CHAR : return "char" ; case DOUBLE : return "double" ; case FLOAT : return "float" ; case INT : return "int" ; case LONG : return "long" ; case SHORT : return "short" ; case DECLARED : StringBuilder b = new StringBuilder ( ) ; b . append ( ( ( TypeElement ) ( ( DeclaredType ) type ) . asElement ( ) ) . getQualifiedName ( ) . toString ( ) ) ; if ( ! ( ( DeclaredType ) type ) . getTypeArguments ( ) . isEmpty ( ) ) { b . append ( "<" ) ; boolean addComa = false ; for ( TypeMirror pType : ( ( DeclaredType ) type ) . getTypeArguments ( ) ) { if ( addComa ) b . append ( ", " ) ; else addComa = true ; b . append ( getTypeQualifiedName ( pType ) ) ; } b . append ( ">" ) ; } return b . toString ( ) ; default : return type . toString ( ) ; } }
Returns the qualified name of a TypeMirror .
19,437
public boolean IsInside ( String pDate ) { if ( periods == null ) { if ( days == null ) return false ; if ( days . getDay ( CalendarFunctions . date_get_day ( pDate ) ) . get ( ) > 0 ) return true ; return false ; } for ( int i = 0 ; i < periods . size ( ) ; i ++ ) { Period period = periods . get ( i ) ; if ( period . getFrom ( ) . compareTo ( pDate ) > 0 ) return false ; if ( ( period . getFrom ( ) . compareTo ( pDate ) <= 0 ) && ( period . getTo ( ) . compareTo ( pDate ) >= 0 ) ) return true ; } return false ; }
false if not
19,438
public boolean IsContained ( String pFrom , String pTo ) { if ( periods == null ) { throw new RuntimeException ( "Error Periods is Null" ) ; } for ( int i = 0 ; i < periods . size ( ) ; i ++ ) { Period period = periods . get ( i ) ; if ( period . getFrom ( ) . compareTo ( pFrom ) > 0 ) return false ; if ( ( pFrom . compareTo ( period . getFrom ( ) ) >= 0 ) && ( pTo . compareTo ( period . getTo ( ) ) <= 0 ) ) return true ; } return false ; }
list of periods false if not
19,439
public void Resolve ( String pFrom , String pTo ) { if ( periods != null ) { throw new RuntimeException ( "Error call on an already resolved CalendarPeriod" ) ; } int nb = 0 ; for ( int i = 0 ; i < 7 ; i ++ ) nb += days . getDay ( i ) . get ( ) ; if ( nb == 7 ) { periods = new ArrayList < Period > ( ) ; periods . add ( new Period ( pFrom , pTo ) ) ; return ; } else if ( nb == 0 ) { periods = new ArrayList < Period > ( ) ; return ; } int fromDay = CalendarFunctions . date_get_day ( pFrom ) ; Groups groups = new Groups ( ) ; Group curGroup = null ; for ( int i = fromDay ; i < fromDay + 7 ; i ++ ) { if ( days . getDay ( i % 7 ) . get ( ) > 0 ) { if ( curGroup == null ) curGroup = new Group ( i - fromDay , i - fromDay ) ; else if ( curGroup . getTo ( ) == i - fromDay - 1 ) curGroup . setTo ( i - fromDay ) ; else { groups . add ( curGroup ) ; curGroup = new Group ( i - fromDay , i - fromDay ) ; } } } if ( curGroup != null ) groups . add ( curGroup ) ; String firstOccurence = pFrom ; days = null ; periods = new ArrayList < Period > ( ) ; while ( firstOccurence . compareTo ( pTo ) <= 0 ) { for ( int i = 0 ; i < groups . size ( ) ; i ++ ) { Group group = groups . get ( i ) ; String mpFrom = CalendarFunctions . date_add_day ( firstOccurence , group . getFrom ( ) ) ; if ( mpFrom . compareTo ( pTo ) <= 0 ) { String mpTo = CalendarFunctions . date_add_day ( firstOccurence , group . getTo ( ) ) ; if ( mpTo . compareTo ( pTo ) > 0 ) mpTo = pTo ; periods . add ( new Period ( mpFrom , mpTo ) ) ; } } firstOccurence = CalendarFunctions . date_add_day ( firstOccurence , 7 ) ; } }
from and to parameters
19,440
private List < Period > _Intersect ( List < Period > periods1 , List < Period > periods2 ) { List < Period > result = new ArrayList < Period > ( ) ; int count1 = periods1 . size ( ) ; int count2 = periods2 . size ( ) ; int i = 0 ; int j = 0 ; while ( i < count1 && j < count2 ) { if ( periods1 . get ( i ) . getFrom ( ) . compareTo ( periods2 . get ( j ) . getTo ( ) ) > 0 ) { j ++ ; } else if ( periods2 . get ( j ) . getFrom ( ) . compareTo ( periods1 . get ( i ) . getTo ( ) ) > 0 ) { i ++ ; } else { result . add ( new Period ( CalendarFunctions . max_date ( periods1 . get ( i ) . getFrom ( ) , periods2 . get ( j ) . getFrom ( ) ) , CalendarFunctions . min_date ( periods1 . get ( i ) . getTo ( ) , periods2 . get ( j ) . getTo ( ) ) ) ) ; if ( periods1 . get ( i ) . getTo ( ) . compareTo ( periods2 . get ( j ) . getTo ( ) ) > 0 ) j ++ ; else i ++ ; } } return result ; }
intersect two period arrays
19,441
protected Integer compareNullObjects ( Object object1 , Object object2 ) { if ( ( object1 == null ) && ( object2 == null ) ) { return 0 ; } if ( object1 == null ) { return 1 ; } if ( object2 == null ) { return - 1 ; } return null ; }
Checks for null objects and returns the proper result depedning on which object is null
19,442
public PathBuilder append ( String cmd , double ... coords ) { s . append ( cmd ) . append ( " " ) ; for ( double a : coords ) { s . append ( a ) . append ( " " ) ; } return this ; }
append an SVG Path command to this instance
19,443
public Object handle ( InvocationContext ic ) throws Exception { Method m = ic . getMethod ( ) ; Object targetObject = ic . getTarget ( ) ; Class < ? > targetClass = targetObject == null ? m . getDeclaringClass ( ) : targetObject . getClass ( ) ; CatchHandler exceptionHandlerAnnotation = AnnotationUtils . findAnnotation ( m , targetClass , CatchHandler . class ) ; Exception unexpectedException = null ; if ( exceptionHandlerAnnotation == null ) { throw new IllegalStateException ( "The interceptor annotation can not be determined!" ) ; } CatchHandling [ ] exceptionHandlingAnnotations = exceptionHandlerAnnotation . value ( ) ; Class < ? extends Throwable > [ ] unwrap = exceptionHandlerAnnotation . unwrap ( ) ; try { return ic . proceed ( ) ; } catch ( Exception ex ) { if ( ! contains ( unwrap , InvocationTargetException . class ) ) { unwrap = Arrays . copyOf ( unwrap , unwrap . length + 1 ) ; unwrap [ unwrap . length - 1 ] = InvocationTargetException . class ; } Throwable t = ExceptionUtils . unwrap ( ex , InvocationTargetException . class ) ; boolean exceptionHandled = false ; boolean cleanupInvoked = false ; if ( exceptionHandlingAnnotations . length > 0 ) { for ( CatchHandling handling : exceptionHandlingAnnotations ) { if ( handling . exception ( ) . isInstance ( t ) ) { try { handleThrowable ( t ) ; exceptionHandled = true ; } catch ( Exception unexpected ) { unexpectedException = unexpected ; } if ( ! handling . cleanup ( ) . equals ( Object . class ) ) { cleanupInvoked = invokeCleanups ( targetClass , targetObject , handling . cleanup ( ) , t ) ; } break ; } } } if ( ! exceptionHandled ) { if ( exceptionHandlerAnnotation . exception ( ) . isInstance ( t ) ) { try { handleThrowable ( t ) ; exceptionHandled = true ; } catch ( Exception unexpected ) { unexpectedException = unexpected ; } if ( ! exceptionHandlerAnnotation . cleanup ( ) . equals ( Object . class ) && ! cleanupInvoked ) { if ( ! cleanupInvoked ) { invokeCleanups ( targetClass , targetObject , exceptionHandlerAnnotation . cleanup ( ) , t ) ; } } } } if ( ! exceptionHandled ) { if ( t instanceof Exception ) { unexpectedException = ( Exception ) t ; } else { unexpectedException = new Exception ( t ) ; } } } if ( unexpectedException != null ) { throw unexpectedException ; } return null ; }
Handles the exception .
19,444
private boolean invokeCleanups ( Class < ? > clazz , Object target , Class < ? > cleanupClazz , Throwable exception ) throws Exception { boolean invoked = false ; if ( ! cleanupClazz . equals ( Object . class ) ) { List < Method > methods = ReflectionUtils . getMethods ( target . getClass ( ) , Cleanup . class ) ; Method m = null ; for ( Method candidate : methods ) { Cleanup c = AnnotationUtils . findAnnotation ( candidate , Cleanup . class ) ; if ( cleanupClazz . equals ( c . value ( ) ) ) { m = candidate ; break ; } } if ( m != null ) { final Class < ? > [ ] parameterTypes = m . getParameterTypes ( ) ; if ( parameterTypes . length == 1 ) { if ( ReflectionUtils . isSubtype ( exception . getClass ( ) , parameterTypes [ 0 ] ) ) { m . invoke ( target , exception ) ; invoked = true ; } else { throw new IllegalArgumentException ( "Cleanup method with name " + cleanupClazz . getName ( ) + " requires a parameter that is not a subtype of the exception class " + exception . getClass ( ) . getName ( ) ) ; } } else { m . invoke ( target ) ; invoked = true ; } } } return invoked ; }
Invokes the cleanup methods of the exception handler or exception handling .
19,445
public ProducerConnectionContext createProducerConnectionContext ( Endpoint endpoint ) throws JMSException { ProducerConnectionContext context = new ProducerConnectionContext ( ) ; createOrReuseConnection ( context , true ) ; createSession ( context ) ; createDestination ( context , endpoint ) ; createProducer ( context ) ; return context ; }
Creates a new producer connection context reusing any existing connection that might have already been created . The destination of the connection s session will be that of the given endpoint .
19,446
protected void cacheConnection ( Connection connection , boolean closeExistingConnection ) { if ( this . connection != null && closeExistingConnection ) { try { this . connection . close ( ) ; } catch ( JMSException e ) { msglog . errorCannotCloseConnectionMemoryMightLeak ( e ) ; } } this . connection = connection ; }
To store a connection in this processor object call this setter . If there was already a cached connection it will be closed .
19,447
protected void createConnection ( ConnectionContext context ) throws JMSException { if ( context == null ) { throw new IllegalStateException ( "The context is null" ) ; } ConnectionFactory factory = getConnectionFactory ( ) ; Connection conn = factory . createConnection ( ) ; context . setConnection ( conn ) ; }
Creates a connection using this object s connection factory and stores that connection in the given context object .
19,448
protected void createSession ( ConnectionContext context ) throws JMSException { if ( context == null ) { throw new IllegalStateException ( "The context is null" ) ; } Connection conn = context . getConnection ( ) ; if ( conn == null ) { throw new IllegalStateException ( "The context had a null connection" ) ; } Session session = conn . createSession ( false , Session . AUTO_ACKNOWLEDGE ) ; context . setSession ( session ) ; }
Creates a default session using the context s connection . This implementation creates a non - transacted auto - acknowledged session . Subclasses are free to override this behavior .
19,449
protected void createDestination ( ConnectionContext context , Endpoint endpoint ) throws JMSException { if ( endpoint == null ) { throw new IllegalStateException ( "Endpoint is null" ) ; } if ( context == null ) { throw new IllegalStateException ( "The context is null" ) ; } Session session = context . getSession ( ) ; if ( session == null ) { throw new IllegalStateException ( "The context had a null session" ) ; } Destination dest ; if ( endpoint . getType ( ) == Endpoint . Type . QUEUE ) { if ( endpoint . isTemporary ( ) ) { dest = session . createTemporaryQueue ( ) ; } else { dest = session . createQueue ( getDestinationName ( endpoint ) ) ; } } else { if ( endpoint . isTemporary ( ) ) { dest = session . createTemporaryTopic ( ) ; } else { dest = session . createTopic ( getDestinationName ( endpoint ) ) ; } } context . setDestination ( dest ) ; }
Creates a destination using the context s session . The destination correlates to the given named queue or topic .
19,450
protected void createProducer ( ProducerConnectionContext context ) throws JMSException { if ( context == null ) { throw new IllegalStateException ( "The context is null" ) ; } Session session = context . getSession ( ) ; if ( session == null ) { throw new IllegalStateException ( "The context had a null session" ) ; } Destination dest = context . getDestination ( ) ; if ( dest == null ) { throw new IllegalStateException ( "The context had a null destination" ) ; } MessageProducer producer = session . createProducer ( dest ) ; context . setMessageProducer ( producer ) ; }
Creates a message producer using the context s session and destination .
19,451
protected void createConsumer ( ConsumerConnectionContext context , String messageSelector ) throws JMSException { if ( context == null ) { throw new IllegalStateException ( "The context is null" ) ; } Session session = context . getSession ( ) ; if ( session == null ) { throw new IllegalStateException ( "The context had a null session" ) ; } Destination dest = context . getDestination ( ) ; if ( dest == null ) { throw new IllegalStateException ( "The context had a null destination" ) ; } MessageConsumer consumer = session . createConsumer ( dest , messageSelector ) ; context . setMessageConsumer ( consumer ) ; }
Creates a message consumer using the context s session and destination .
19,452
public static Bindings defaultBindings ( ) { return noHashMapBindings ( ) . set ( ClassLoader . class , Thread . currentThread ( ) . getContextClassLoader ( ) ) . set ( ConfigParseOptions . class , ConfigParseOptions . defaults ( ) ) . set ( ConfigResolveOptions . class , ConfigResolveOptions . defaults ( ) ) . set ( Config . class , emptyConfig ( ) ) ; }
Some default bindings that most config factories will need .
19,453
public void Init ( CalendarPeriod period , T value ) { for ( int i = 0 ; i < period . getPeriods ( ) . size ( ) ; i ++ ) { Period p = period . getPeriods ( ) . get ( i ) ; periods . add ( new PeriodAssociative < T > ( p . getFrom ( ) , p . getTo ( ) , value ) ) ; } }
init from a CalendarPeriod with a value
19,454
public Boolean Add ( CalendarPeriodAssociative < T > period , AddFunction < T > addFunction ) { List < PeriodAssociative < T > > combined = _Combine ( periods , period . getPeriods ( ) ) ; List < PeriodAssociative < T > > result = _Merge ( combined , addFunction ) ; if ( result == null ) return null ; periods = result ; return true ; }
adding two associative periods
19,455
public CalendarPeriod GetCalendarPeriod ( ) { CalendarPeriod res = new CalendarPeriod ( ) ; List < Period > periods = new ArrayList < Period > ( ) ; for ( int i = 0 ; i < this . periods . size ( ) ; i ++ ) { PeriodAssociative < T > p = this . periods . get ( i ) ; periods . add ( new Period ( p . getFrom ( ) , p . getTo ( ) ) ) ; } res . setPeriods ( res . _Merge ( periods ) ) ; return res ; }
returns the same but with no values and with the periods merged
19,456
private boolean _readDate ( ) { int endIndex = pos + 10 ; if ( endIndex <= len ) { _date = text . substring ( pos , endIndex ) ; pos += 10 ; return true ; } pos = len ; return false ; }
parse a date in the format yyyy - mm - dd
19,457
public void emphasizePoint ( int index ) { if ( dots == null || dots . length < ( index - 1 ) ) return ; if ( emphasizedPoint == index ) return ; if ( emphasizedPoint >= 0 ) { dots [ emphasizedPoint ] . attr ( "r" , dotNormalSize ) ; emphasizedPoint = - 1 ; } if ( index >= 0 ) { dots [ index ] . attr ( "r" , dotBigSize ) ; emphasizedPoint = index ; } }
index < 0 means that we emphasize no point at all
19,458
public void moveLastChild ( Row newParent ) { if ( this == newParent ) return ; Row parentItem = m_parent ; if ( parentItem == null ) parentItem = this . treeTable . m_rootItem ; parentItem . getChilds ( ) . remove ( this ) ; if ( newParent == null ) newParent = this . treeTable . m_rootItem ; Row lastLeaf = newParent . getLastLeaf ( ) ; Element trToInsertAfter = lastLeaf . m_tr ; if ( trToInsertAfter != null ) { int after = DOM . getChildIndex ( this . treeTable . m_body , trToInsertAfter ) ; int before = after + 1 ; DOM . insertChild ( this . treeTable . m_body , m_tr , before ) ; } else { DOM . appendChild ( this . treeTable . m_body , m_tr ) ; } parentItem . getChilds ( ) . add ( this ) ; Element firstTd = DOM . getChild ( m_tr , 0 ) ; firstTd . getStyle ( ) . setPaddingLeft ( getLevel ( ) * this . treeTable . treePadding , Unit . PX ) ; }
move to be the last item of parent
19,459
public void moveBefore ( Row item ) { if ( this == item ) return ; Element lastTrToMove = getLastLeafTR ( ) ; Element firstChildRow = DOM . getNextSibling ( m_tr ) ; Row parentItem = m_parent ; if ( parentItem == null ) parentItem = this . treeTable . m_rootItem ; parentItem . getChilds ( ) . remove ( this ) ; if ( item == null ) { Row lastLeaf = parentItem . getLastLeaf ( ) ; Element trToInsertAfter = lastLeaf . m_tr ; if ( trToInsertAfter != null ) { int after = DOM . getChildIndex ( this . treeTable . m_body , trToInsertAfter ) ; int before = after + 1 ; DOM . insertChild ( this . treeTable . m_body , m_tr , before ) ; } else { DOM . appendChild ( this . treeTable . m_body , m_tr ) ; } parentItem . getChilds ( ) . add ( this ) ; } else { Row newParentItem = item . m_parent ; if ( newParentItem == null ) newParentItem = this . treeTable . m_rootItem ; int itemPos = item . m_parent . getChilds ( ) . indexOf ( item ) ; newParentItem . getChilds ( ) . add ( itemPos , this ) ; DOM . insertBefore ( this . treeTable . m_body , m_tr , item . m_tr ) ; } Element firstTd = DOM . getChild ( m_tr , 0 ) ; firstTd . getStyle ( ) . setPaddingLeft ( getLevel ( ) * this . treeTable . treePadding , Unit . PX ) ; Element nextTR = DOM . getNextSibling ( m_tr ) ; if ( firstChildRow != null && lastTrToMove != null && hasChilds ( ) ) { while ( true ) { Element next = DOM . getNextSibling ( firstChildRow ) ; DOM . insertBefore ( this . treeTable . m_body , firstChildRow , nextTR ) ; if ( firstChildRow == lastTrToMove ) break ; firstChildRow = next ; } } }
move to position just before item
19,460
void removeHandler ( Object handlerRegistration ) { if ( handlerRegistration instanceof DirectHandlerInfo ) { DirectHandlerInfo info = ( DirectHandlerInfo ) handlerRegistration ; info . source . removePropertyChangedHandler ( info . registrationObject ) ; return ; } if ( ! ( handlerRegistration instanceof HandlerInfo ) ) return ; HandlerInfo info = ( HandlerInfo ) handlerRegistration ; HashMap < String , ArrayList < PropertyChangedHandler > > handlersMap = PlatformSpecificProvider . get ( ) . getObjectMetadata ( info . source ) ; if ( handlersMap == null ) return ; ArrayList < PropertyChangedHandler > handlerList = handlersMap . get ( info . propertyName ) ; if ( handlerList == null ) return ; handlerList . remove ( info . handler ) ; if ( handlerList . isEmpty ( ) ) handlersMap . remove ( info . propertyName ) ; if ( handlersMap . isEmpty ( ) ) PlatformSpecificProvider . get ( ) . setObjectMetadata ( info . source , null ) ; stats . statsRemovedRegistration ( info ) ; info . handler = null ; info . propertyName = null ; info . source = null ; }
Unregisters a handler freeing associated resources
19,461
public static void filterRequest ( ContainerRequestContext requestContext , Predicate < String > predicate ) { String requestOrigin = requestContext . getHeaderString ( Headers . ORIGIN ) ; if ( requestOrigin == null ) { return ; } if ( ! predicate . test ( requestOrigin ) ) { requestContext . abortWith ( Response . status ( Response . Status . BAD_REQUEST ) . build ( ) ) ; return ; } if ( requestContext . getMethod ( ) . equalsIgnoreCase ( HttpMethod . OPTIONS ) ) { requestContext . abortWith ( Response . status ( Response . Status . OK ) . build ( ) ) ; } }
Apply CORS filter on request
19,462
public static void filterResponse ( ContainerRequestContext requestContext , ContainerResponseContext responseContext , String extraAccesControlAllowHeaders ) { String requestOrigin = requestContext . getHeaderString ( Headers . ORIGIN ) ; if ( requestOrigin == null ) { return ; } MultivaluedMap < String , Object > responseHeaders = responseContext . getHeaders ( ) ; responseHeaders . add ( Headers . ACCESS_CONTROL_ALLOW_ORIGIN , requestOrigin ) ; responseHeaders . add ( Headers . ACCESS_CONTROL_ALLOW_CREDENTIALS , "true" ) ; responseHeaders . add ( Headers . ACCESS_CONTROL_ALLOW_METHODS , Headers . DEFAULT_CORS_ACCESS_CONTROL_ALLOW_METHODS ) ; responseHeaders . add ( Headers . ACCESS_CONTROL_MAX_AGE , 72 * 60 * 60 ) ; if ( extraAccesControlAllowHeaders != null ) { responseHeaders . add ( Headers . ACCESS_CONTROL_ALLOW_HEADERS , Headers . DEFAULT_CORS_ACCESS_CONTROL_ALLOW_HEADERS + "," + extraAccesControlAllowHeaders . trim ( ) ) ; } else { responseHeaders . add ( Headers . ACCESS_CONTROL_ALLOW_HEADERS , Headers . DEFAULT_CORS_ACCESS_CONTROL_ALLOW_HEADERS ) ; } }
Apply CORS headers on response
19,463
public static TableCellElement getCell ( Element root , int column , int row ) { TableSectionElement tbody = getTBodyElement ( root ) ; TableRowElement tr = tbody . getChild ( row ) . cast ( ) ; TableCellElement td = tr . getChild ( column ) . cast ( ) ; return td ; }
Get the TD element
19,464
public static Pair < Integer , Integer > getParentCellForElement ( Element root , Element element ) { Element tbody = getTBodyElement ( root ) ; ArrayList < Element > path = TemplateUtils . isDescendant ( tbody , element ) ; if ( path == null ) return null ; int row = DOM . getChildIndex ( path . get ( 0 ) , path . get ( 1 ) ) ; int col = DOM . getChildIndex ( path . get ( 1 ) , path . get ( 2 ) ) ; return new Pair < Integer , Integer > ( col , row ) ; }
Returns the coordinate of the cell containing the element given that root is the root of a HtmlTableTemplate
19,465
public static void setDragData ( Object source , Object data ) { DragUtils . source = source ; DragUtils . data = data ; }
Sets the drag and drop data and its source
19,466
public static ConfigFactory webappConfigFactory ( ServletContext servletContext ) { checkNotNull ( servletContext ) ; return webappConfigFactory ( ) . bind ( ServletContextPath . class ) . toInstance ( ServletContextPath . fromServletContext ( servletContext ) ) ; }
A sensible default configuration factory for a web application .
19,467
public void setWidget ( Widget w ) { if ( w == widget ) return ; if ( w != null ) w . removeFromParent ( ) ; if ( widget != null ) remove ( widget ) ; widget = w ; if ( w != null ) { DOM . appendChild ( containerElement , widget . getElement ( ) ) ; adopt ( w ) ; } }
Sets this panel s widget . Any existing child widget will be removed .
19,468
private String getSentenceFromTokens ( final String [ ] tokens ) { final StringBuilder sb = new StringBuilder ( ) ; for ( final String token : tokens ) { sb . append ( token ) . append ( " " ) ; } final String sentence = sb . toString ( ) ; return sentence ; }
It takes an array of tokens and outputs a string with tokens joined by a whitespace .
19,469
private String addHeadWordsToTreebank ( final List < String > inputTrees ) { final StringBuffer parsedDoc = new StringBuffer ( ) ; for ( final String parseSent : inputTrees ) { final Parse parsedSentence = Parse . parseParse ( parseSent ) ; this . headFinder . printHeads ( parsedSentence ) ; parsedSentence . show ( parsedDoc ) ; parsedDoc . append ( "\n" ) ; } return parsedDoc . toString ( ) ; }
Takes as input a list of parse strings one for line and annotates the headwords
19,470
public void terminate ( ) { log ( "term" ) ; fActivated = false ; converter = null ; source . removePropertyChangedHandler ( sourceHandler ) ; source = null ; sourceHandler = null ; destination . removePropertyChangedHandler ( destinationHandler ) ; destination = null ; destinationHandler = null ; }
Terminates the Data Binding activation and cleans up all related resources . You should call this method when you want to free the binding in order to lower memory usage .
19,471
public static void tryToShowPrompt ( Context context , OnCompleteListener onCompleteListener ) { tryToShowPrompt ( context , null , null , onCompleteListener ) ; }
Show rating dialog . The dialog will be showed if the user hasn t declined to rate or hasn t rated current version .
19,472
public static void resetIfAppVersionChanged ( Context context ) { SharedPreferences prefs = getSharedPreferences ( context ) ; int appVersionCode = Integer . MIN_VALUE ; final int previousAppVersionCode = prefs . getInt ( PREF_KEY_APP_VERSION_CODE , Integer . MIN_VALUE ) ; try { appVersionCode = context . getPackageManager ( ) . getPackageInfo ( context . getPackageName ( ) , 0 ) . versionCode ; } catch ( PackageManager . NameNotFoundException e ) { Log . w ( TAG , "Occurred PackageManager.NameNotFoundException" , e ) ; } if ( previousAppVersionCode != appVersionCode ) { SharedPreferences . Editor prefsEditor = prefs . edit ( ) ; prefsEditor . putLong ( PREF_KEY_APP_LAUNCH_COUNT , 0 ) ; prefsEditor . putLong ( PREF_KEY_APP_THIS_VERSION_CODE_LAUNCH_COUNT , 0 ) ; prefsEditor . putLong ( PREF_KEY_APP_FIRST_LAUNCHED_DATE , 0 ) ; prefsEditor . putInt ( PREF_KEY_APP_VERSION_CODE , Integer . MIN_VALUE ) ; prefsEditor . putLong ( PREF_KEY_RATE_CLICK_DATE , 0 ) ; prefsEditor . putLong ( PREF_KEY_REMINDER_CLICK_DATE , 0 ) ; prefsEditor . putBoolean ( PREF_KEY_DO_NOT_SHOW_AGAIN , false ) ; prefsEditor . commit ( ) ; } }
Reset saved conditions if app version changed .
19,473
public static Class < ? > getObjectClassOfPrimitve ( Class < ? > primitive ) { Class < ? > objectClass = PRIMITIVE_TO_WRAPPER . get ( primitive ) ; if ( objectClass != null ) { return objectClass ; } return primitive ; }
Returns the wrapper class of the given primitive class or the given class .
19,474
public static int getTypeVariablePosition ( GenericDeclaration genericDeclartion , TypeVariable < ? > typeVariable ) { int position = - 1 ; TypeVariable < ? > [ ] typeVariableDeclarationParameters = genericDeclartion . getTypeParameters ( ) ; for ( int i = 0 ; i < typeVariableDeclarationParameters . length ; i ++ ) { if ( typeVariableDeclarationParameters [ i ] . equals ( typeVariable ) ) { position = i ; break ; } } return position ; }
Tries to find the position of the given type variable in the type parameters of the given class . This method iterates through the type parameters of the given class and tries to find the given type variable within the type parameters . When the type variable is found the position is returned otherwise - 1 .
19,475
public static Field [ ] getMatchingFields ( Class < ? > clazz , final int modifiers ) { final Set < Field > fields = new TreeSet < Field > ( FIELD_NAME_AND_DECLARING_CLASS_COMPARATOR ) ; traverseHierarchy ( clazz , new TraverseTask < Field > ( ) { public Field run ( Class < ? > clazz ) { Field [ ] fieldArray = clazz . getDeclaredFields ( ) ; for ( int i = 0 ; i < fieldArray . length ; i ++ ) { if ( ( modifiers & fieldArray [ i ] . getModifiers ( ) ) != 0 ) { fields . add ( fieldArray [ i ] ) ; } } return null ; } } ) ; return fields . toArray ( new Field [ fields . size ( ) ] ) ; }
Returns the field objects that are declared in the given class or any of it s super types that have any of the given modifiers . The type hierarchy is traversed upwards and all declared fields that match the given modifiers are added to the result array . The elements in the array are sorted by their names and declaring classes .
19,476
public static Field getField ( Class < ? > clazz , String fieldName ) { final String internedName = fieldName . intern ( ) ; return traverseHierarchy ( clazz , new TraverseTask < Field > ( ) { public Field run ( Class < ? > clazz ) { Field [ ] fields = clazz . getDeclaredFields ( ) ; for ( int i = 0 ; i < fields . length ; i ++ ) { if ( fields [ i ] . getName ( ) == internedName ) { return fields [ i ] ; } } return null ; } } ) ; }
Returns the field object found for the given field name in the given class . This method traverses through the super classes of the given class and tries to find the field as declared field within these classes . When the object class is reached the traversing stops . If the field can not be found null is returned .
19,477
public static Method getMethod ( Class < ? > clazz , final String methodName , final Class < ? > ... parameterTypes ) { final String internedName = methodName . intern ( ) ; return traverseHierarchy ( clazz , new TraverseTask < Method > ( ) { public Method run ( Class < ? > clazz ) { Method [ ] methods = clazz . getDeclaredMethods ( ) ; Method res = null ; for ( int i = 0 ; i < methods . length ; i ++ ) { Method m = methods [ i ] ; if ( m . getName ( ) == internedName && arrayContentsEq ( parameterTypes , m . getParameterTypes ( ) ) && ( res == null || res . getReturnType ( ) . isAssignableFrom ( m . getReturnType ( ) ) ) ) { res = m ; } } return res ; } } ) ; }
Returns the method object found for the given method name in the given class . This method traverses through the super classes of the given class and tries to find the method as declared method within these classes . When the object class is reached the traversing stops . If the method can not be found null is returned .
19,478
public static List < Method > getMethods ( Class < ? > clazz , final Class < ? extends Annotation > annotation ) { final List < Method > methods = new ArrayList < Method > ( ) ; traverseHierarchy ( clazz , new TraverseTask < Method > ( ) { public Method run ( Class < ? > clazz ) { Method [ ] methodArray = clazz . getDeclaredMethods ( ) ; for ( int i = 0 ; i < methodArray . length ; i ++ ) { Method m = methodArray [ i ] ; if ( m . getAnnotation ( annotation ) != null ) { methods . add ( m ) ; } } return null ; } } ) ; return methods ; }
Returns the method objects for methods which are annotated with the given annotation of the given class . This method traverses through the super classes of the given class and tries to find methods as declared methods within these classes which are annotated with an annotation of the given annotation type . When the object class is reached the traversing stops . If no methods can be found an empty list is returned . The order of the methods is random .
19,479
public static ArrayList < Element > verifyPath ( Element root , ArrayList < Element > path ) { if ( root == path . get ( 0 ) ) return path ; return null ; }
asserts that a path s root is the waited element
19,480
public T getRecordForRow ( Row row ) { Integer recordId = rowToRecordIds . get ( row ) ; if ( recordId == null ) return null ; return getRecordForId ( recordId ) ; }
Gets the record associated with a specific Row
19,481
public static Class < ? > getSetterPropertyType ( Clazz < ? > clazz , String name ) { return propertyValues . getSetterPropertyType ( clazz , name ) ; }
Returns the class of the setter property . It can be the class of the first argument in the setter or the class of the field if no setter is found . If a virtual property is used it returns null or the class of the current property s value
19,482
private Map < String , Object > extractErrorDetailsFromResponse ( ClientHttpResponse response ) throws IOException { ObjectMapper mapper = new ObjectMapper ( new JsonFactory ( ) ) ; try { return mapper . < Map < String , Object > > readValue ( response . getBody ( ) , new TypeReference < Map < String , Object > > ( ) { } ) ; } catch ( JsonParseException e ) { return null ; } }
Error details are returned in the message body as JSON . Extract these in a map
19,483
private void key ( final byte key [ ] ) { int i ; final int koffp [ ] = { 0 } ; final int lr [ ] = { 0 , 0 } ; final int plen = P . length , slen = S . length ; for ( i = 0 ; i < plen ; i ++ ) { P [ i ] = P [ i ] ^ streamtoword ( key , koffp ) ; } for ( i = 0 ; i < plen ; i += 2 ) { encipher ( lr , 0 ) ; P [ i ] = lr [ 0 ] ; P [ i + 1 ] = lr [ 1 ] ; } for ( i = 0 ; i < slen ; i += 2 ) { encipher ( lr , 0 ) ; S [ i ] = lr [ 0 ] ; S [ i + 1 ] = lr [ 1 ] ; } }
Key the Blowfish cipher
19,484
public final static int createLocalId ( ) { Storage storage = Storage . getLocalStorageIfSupported ( ) ; if ( storage == null ) return 0 ; int increment = 0 ; String incrementString = storage . getItem ( LOCAL_CURRENT_ID_INCREMENT ) ; try { increment = Integer . parseInt ( incrementString ) ; } catch ( Exception e ) { } increment += 1 ; storage . setItem ( LOCAL_CURRENT_ID_INCREMENT , increment + "" ) ; return - increment ; }
Create a negative ID .
19,485
public < T > void RegisterClazz ( Clazz < T > clazz ) { _ensureMap ( ) ; if ( clazzz . containsKey ( clazz . getReflectedClass ( ) ) ) return ; clazzz . put ( clazz . getReflectedClass ( ) , clazz ) ; }
Register a runtime type information provider
19,486
public void init ( String baseUrl , XRPCBatchRequestSender callback ) { this . url = baseUrl + "&locale=" + LocaleInfo . getCurrentLocale ( ) . getLocaleName ( ) ; this . callback = callback ; }
initialize with url and other needed information
19,487
private void checkCallService ( RequestCallInfo info ) { String service = info . request . service ; String interfaceChecksum = info . request . interfaceChecksum ; String key = getServiceKey ( info ) ; if ( usedServices . containsKey ( key ) ) return ; ServiceInfo serviceInfo = new ServiceInfo ( service , interfaceChecksum ) ; serviceInfo . id = usedServices . size ( ) ; usedServices . put ( key , serviceInfo ) ; }
necessary to be sure that call s service is referenced
19,488
public boolean send ( ) { assert sentRequests == null ; sentRequests = new ArrayList < RequestCallInfo > ( ) ; addPrependedRequests ( sentRequests ) ; while ( ! requestsToSend . isEmpty ( ) ) sentRequests . add ( requestsToSend . remove ( 0 ) ) ; addAppendedRequests ( sentRequests ) ; JSONArray payload = createPayload ( ) ; RequestBuilder builderPost = buildMultipart ( "payload" , payload . toString ( ) ) ; nbSentBytes += builderPost . getRequestData ( ) . length ( ) ; try { sentRequest = builderPost . send ( ) ; } catch ( RequestException e ) { callback . error ( RPCErrorCodes . ERROR_REQUEST_SEND , e , this ) ; return false ; } callback . sent ( this ) ; return true ; }
when response arrives it will be given back to each request callback
19,489
private RequestBuilder buildMultipart ( String name , String value ) { String boundary = "AJAX------" + Math . random ( ) + "" + new Date ( ) . getTime ( ) ; RequestBuilder builderPost = new RequestBuilder ( RequestBuilder . POST , url ) ; builderPost . setHeader ( "Content-Type" , "multipart/form-data; charset=utf-8; boundary=" + boundary ) ; builderPost . setCallback ( requestCallback ) ; String CRLF = "\r\n" ; String data = "--" + boundary + CRLF ; data += "--" + boundary + CRLF ; data += "Content-Disposition: form-data; " ; data += "name=\"" + name + "\"" + CRLF + CRLF ; data += value + CRLF ; data += "--" + boundary + "--" + CRLF ; builderPost . setRequestData ( data ) ; return builderPost ; }
prepare a multipart form http request
19,490
public FormCreator field ( Widget widget ) { return field ( widget , totalWidth - currentlyUsedWidth - ( fFirstItem ? 0 : spacing ) ) ; }
automatically fills the line to the end
19,491
public void copy ( ConnectionContext source ) { this . connection = source . connection ; this . session = source . session ; this . destination = source . destination ; }
Sets this context object with the same data found in the source context .
19,492
public static Set < Annotation > getAllAnnotations ( Method m ) { Set < Annotation > annotationSet = new LinkedHashSet < Annotation > ( ) ; Annotation [ ] annotations = m . getAnnotations ( ) ; List < Class < ? > > annotationTypes = new ArrayList < Class < ? > > ( ) ; for ( Annotation a : annotations ) { annotationSet . add ( a ) ; annotationTypes . add ( a . annotationType ( ) ) ; } if ( stereotypeAnnotationClass != null ) { while ( ! annotationTypes . isEmpty ( ) ) { Class < ? > annotationType = annotationTypes . remove ( annotationTypes . size ( ) - 1 ) ; if ( annotationType . isAnnotationPresent ( stereotypeAnnotationClass ) ) { for ( Annotation annotation : annotationType . getAnnotations ( ) ) { annotationTypes . add ( annotation . annotationType ( ) ) ; if ( ! annotation . annotationType ( ) . equals ( stereotypeAnnotationClass ) ) { annotationSet . add ( annotation ) ; } } } } } return annotationSet ; }
Returns all annotations of a class also the annotations of the super classes implemented interfaces and the annotations that are present in stereotype annotations . The stereotype annotation will not be included in the annotation set .
19,493
public static < T extends Annotation > T findAnnotation ( Method m , Class < T > annotationClazz ) { T annotation = m . getAnnotation ( annotationClazz ) ; if ( annotation != null ) { return annotation ; } if ( stereotypeAnnotationClass != null ) { List < Class < ? > > annotations = new ArrayList < > ( ) ; for ( Annotation a : m . getAnnotations ( ) ) { annotations . add ( a . annotationType ( ) ) ; } return findAnnotation ( annotations , annotationClazz ) ; } return null ; }
Returns the annotation object for the specified annotation class of the method if it can be found otherwise null . The annotation is searched in the method which and if a stereotype annotation is found the annotations present on an annotation are also examined . If the annotation can not be found null is returned .
19,494
public static < T extends Annotation > T findAnnotation ( Class < ? > clazz , Class < T > annotationClazz ) { T annotation = clazz . getAnnotation ( annotationClazz ) ; if ( annotation != null ) { return annotation ; } Set < Class < ? > > superTypes = ReflectionUtils . getSuperTypes ( clazz ) ; for ( Class < ? > type : superTypes ) { annotation = type . getAnnotation ( annotationClazz ) ; if ( annotation != null ) { return annotation ; } } if ( stereotypeAnnotationClass != null ) { List < Class < ? > > annotations = new ArrayList < > ( ) ; for ( Class < ? > type : superTypes ) { for ( Annotation a : type . getAnnotations ( ) ) { annotations . add ( a . annotationType ( ) ) ; } } return findAnnotation ( annotations , annotationClazz ) ; } return null ; }
Returns the annotation object for the specified annotation class of the given class object . All super types of the given class are examined to find the annotation . If a stereotype annotation is found the annotations present on an annotation are also examined .
19,495
public < T extends BasicMessage > void listen ( ConsumerConnectionContext context , AbstractBasicMessageListener < T > listener ) throws JMSException { if ( context == null ) { throw new NullPointerException ( "context must not be null" ) ; } if ( listener == null ) { throw new NullPointerException ( "listener must not be null" ) ; } MessageConsumer consumer = context . getMessageConsumer ( ) ; if ( consumer == null ) { throw new NullPointerException ( "context had a null consumer" ) ; } listener . setConsumerConnectionContext ( context ) ; consumer . setMessageListener ( listener ) ; }
Listens for messages .
19,496
public MessageId send ( ProducerConnectionContext context , BasicMessage basicMessage , Map < String , String > headers ) throws JMSException { if ( context == null ) { throw new IllegalArgumentException ( "context must not be null" ) ; } if ( basicMessage == null ) { throw new IllegalArgumentException ( "message must not be null" ) ; } Message msg = createMessage ( context , basicMessage , headers ) ; if ( basicMessage . getCorrelationId ( ) != null ) { msg . setJMSCorrelationID ( basicMessage . getCorrelationId ( ) . toString ( ) ) ; } if ( basicMessage . getMessageId ( ) != null ) { log . debugf ( "Non-null message ID [%s] will be ignored and a new one generated" , basicMessage . getMessageId ( ) ) ; basicMessage . setMessageId ( null ) ; } MessageProducer producer = context . getMessageProducer ( ) ; if ( producer == null ) { throw new IllegalStateException ( "context had a null producer" ) ; } producer . send ( msg ) ; MessageId messageId = new MessageId ( msg . getJMSMessageID ( ) ) ; basicMessage . setMessageId ( messageId ) ; return messageId ; }
Send the given message to its destinations across the message bus . Once sent the message will get assigned a generated message ID . That message ID will also be returned by this method .
19,497
public < T extends BasicMessage > RPCConnectionContext sendAndListen ( ProducerConnectionContext context , BasicMessage basicMessage , BasicMessageListener < T > responseListener , Map < String , String > headers ) throws JMSException { if ( context == null ) { throw new IllegalArgumentException ( "context must not be null" ) ; } if ( basicMessage == null ) { throw new IllegalArgumentException ( "message must not be null" ) ; } if ( responseListener == null ) { throw new IllegalArgumentException ( "response listener must not be null" ) ; } Message msg = createMessage ( context , basicMessage , headers ) ; if ( basicMessage . getCorrelationId ( ) != null ) { msg . setJMSCorrelationID ( basicMessage . getCorrelationId ( ) . toString ( ) ) ; } if ( basicMessage . getMessageId ( ) != null ) { log . debugf ( "Non-null message ID [%s] will be ignored and a new one generated" , basicMessage . getMessageId ( ) ) ; basicMessage . setMessageId ( null ) ; } MessageProducer producer = context . getMessageProducer ( ) ; if ( producer == null ) { throw new NullPointerException ( "Cannot send request-response message - the producer is null" ) ; } Session session = context . getSession ( ) ; if ( session == null ) { throw new NullPointerException ( "Cannot send request-response message - the session is null" ) ; } TemporaryQueue responseQueue = session . createTemporaryQueue ( ) ; MessageConsumer responseConsumer = session . createConsumer ( responseQueue ) ; RPCConnectionContext rpcContext = new RPCConnectionContext ( ) ; rpcContext . copy ( context ) ; rpcContext . setDestination ( responseQueue ) ; rpcContext . setMessageConsumer ( responseConsumer ) ; rpcContext . setRequestMessage ( msg ) ; rpcContext . setResponseListener ( responseListener ) ; responseListener . setConsumerConnectionContext ( rpcContext ) ; responseConsumer . setMessageListener ( responseListener ) ; msg . setJMSReplyTo ( responseQueue ) ; producer . send ( msg ) ; MessageId messageId = new MessageId ( msg . getJMSMessageID ( ) ) ; basicMessage . setMessageId ( messageId ) ; return rpcContext ; }
Send the given message to its destinations across the message bus and any response sent back will be passed to the given listener . Use this for request - response messages where you expect to get a non - void response back .
19,498
public void sendBasicMessageAsync ( Session session , BasicMessage msg ) { String text = ApiDeserializer . toHawkularFormat ( msg ) ; sendTextAsync ( session , text ) ; }
Converts the given message to JSON and sends that JSON text to clients asynchronously .
19,499
public void sendBinaryAsync ( Session session , InputStream inputStream , ExecutorService threadPool ) { if ( session == null ) { return ; } if ( inputStream == null ) { throw new IllegalArgumentException ( "inputStream must not be null" ) ; } log . debugf ( "Attempting to send async binary data to client [%s]" , session . getId ( ) ) ; if ( session . isOpen ( ) ) { if ( this . asyncTimeout != null ) { } CopyStreamRunnable runnable = new CopyStreamRunnable ( session , inputStream ) ; threadPool . execute ( runnable ) ; } return ; }
Sends binary data to a client asynchronously .