idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
142,800 | private void appendFactoryId ( JMessage < ? > message ) { writer . appendln ( "@Override" ) . appendln ( "public int getFactoryId() {" ) . begin ( ) //TODO: The factory should be file unqiue. ID is struct unique so for id we want to define several constants. // so for content_cms we want the factory name ContentCmsFactory or ContentCmsPortableFactory. // as well as some way to count this up for each struct that has a hazelcast_portable tag in it. . formatln ( "return %s.%s;" , getHazelcastFactory ( message . descriptor ( ) ) , HazelcastPortableProgramFormatter . FACTORY_ID ) . end ( ) . appendln ( "}" ) . newline ( ) ; } | Method to append get factory id from hazelcast_portable . | 175 | 14 |
142,801 | private void appendClassId ( JMessage < ? > message ) { writer . appendln ( "@Override" ) . appendln ( "public int getClassId() {" ) . begin ( ) //TODO: Need to add method to create a constant for the description or struct here. . formatln ( "return %s.%s;" , getHazelcastFactory ( message . descriptor ( ) ) , getHazelcastClassId ( message . descriptor ( ) ) ) . end ( ) . appendln ( "}" ) . newline ( ) ; } | Method to append get class id from hazelcast_portable . | 118 | 14 |
142,802 | private void appendPortableWriter ( JMessage < ? > message ) { writer . appendln ( "@Override" ) . formatln ( "public void writePortable(%s %s) throws %s {" , PortableWriter . class . getName ( ) , PORTABLE_WRITER , IOException . class . getName ( ) ) . begin ( ) ; // TODO: This should be short[] instead, as field IDs are restricted to 16bit. writer . appendln ( "int[] setFields = presentFields().stream()" ) . appendln ( " .mapToInt(_Field::getId)" ) . appendln ( " .toArray();" ) . appendln ( "portableWriter.writeIntArray(\"__fields__\", setFields);" ) ; for ( JField field : message . declaredOrderFields ( ) ) { if ( ! field . alwaysPresent ( ) ) { writer . formatln ( "if( %s() ) {" , field . isSet ( ) ) . begin ( ) ; } writePortableField ( field ) ; if ( ! field . alwaysPresent ( ) ) { writer . end ( ) . appendln ( "} else {" ) . begin ( ) ; writeDefaultPortableField ( field ) ; writer . end ( ) . appendln ( "}" ) ; } } writer . end ( ) . appendln ( "}" ) . newline ( ) ; } | Method to append writePortable from hazelcast_portable . | 305 | 14 |
142,803 | private void appendPortableReader ( JMessage < ? > message ) { writer . appendln ( "@Override" ) . formatln ( "public void readPortable(%s %s) throws %s {" , PortableReader . class . getName ( ) , PORTABLE_READER , IOException . class . getName ( ) ) . begin ( ) ; // TODO: This should be short[] instead, as field IDs are restricted to 16bit. writer . formatln ( "int[] field_ids = %s.readIntArray(\"__fields__\");" , PORTABLE_READER ) . appendln ( ) . appendln ( "for (int id : field_ids) {" ) . begin ( ) . appendln ( "switch (id) {" ) . begin ( ) ; for ( JField field : message . declaredOrderFields ( ) ) { writer . formatln ( "case %d: {" , field . id ( ) ) . begin ( ) ; readPortableField ( field ) ; writer . appendln ( "break;" ) . end ( ) . appendln ( "}" ) ; } writer . end ( ) . appendln ( "}" ) // switch . end ( ) . appendln ( "}" ) // for loop . end ( ) . appendln ( "}" ) // readPortable . newline ( ) ; } | Method to append readPortable from hazelcast_portable . | 291 | 14 |
142,804 | @ Programmatic public ApplicationRole newRole ( final String name , final String description ) { ApplicationRole role = findByName ( name ) ; if ( role == null ) { role = getApplicationRoleFactory ( ) . newApplicationRole ( ) ; role . setName ( name ) ; role . setDescription ( description ) ; container . persist ( role ) ; } return role ; } | region > newRole | 79 | 4 |
142,805 | private void hangOut ( final RequestCallInfo req , GenericJSO hangOut ) { final int hangOutId = hangOut . getIntByIdx ( 0 ) ; JsArrayString tmp = hangOut . getGenericJSOByIdx ( 1 ) . cast ( ) ; String name = tmp . get ( 0 ) ; String type = tmp . get ( 1 ) ; String title = tmp . get ( 2 ) ; String description = tmp . get ( 3 ) ; JavaScriptObject hangOutCurrentData = hangOut . getGenericJSOByIdx ( 2 ) ; callback . hangOut ( title , description , name , type , hangOutCurrentData , new IAsyncCallback < JavaScriptObject > ( ) { @ Override public void onSuccess ( JavaScriptObject result ) { JSONArray params = new JSONArray ( ) ; params . set ( 0 , new JSONNumber ( hangOutId ) ) ; params . set ( 1 , new JSONObject ( result ) ) ; req . request = new RequestDesc ( req . request . service , req . request . interfaceChecksum , "_hang_out_reply_" , params ) ; sendRequest ( req . request , req . cookie , req . callback ) ; } } ) ; } | over the network | 256 | 3 |
142,806 | private RPCBatchRequestSender getBatchRequestSender ( ) { RPCBatchRequestSender sender = null ; // test the last sender we have in the list if ( ! batchRequestSenders . isEmpty ( ) ) { sender = batchRequestSenders . get ( batchRequestSenders . size ( ) - 1 ) ; if ( sender . canAddRequest ( ) ) return sender ; } // otherwise, create a new one sender = new RPCBatchRequestSender ( ) ; sender . init ( baseUrl , batchSenderCallback ) ; batchRequestSenders . add ( sender ) ; return sender ; } | retrieve a batch request sender that is OK for adding requests | 131 | 12 |
142,807 | private Set < ConstraintViolation < Object > > addViolations ( Set < ConstraintViolation < Object > > source , Set < ConstraintViolation < Object > > target ) { if ( supportsConstraintComposition ) { target . addAll ( source ) ; return target ; } for ( final Iterator < ConstraintViolation < Object > > iter = source . iterator ( ) ; iter . hasNext ( ) ; ) { final ConstraintViolation < Object > violation = iter . next ( ) ; final Iterator < Node > nodeIter = violation . getPropertyPath ( ) . iterator ( ) ; /* * Only include violations that have no property path or just one * node */ if ( ! nodeIter . hasNext ( ) || ( nodeIter . next ( ) != null && ! nodeIter . hasNext ( ) ) ) { target . add ( violation ) ; } } return target ; } | Add the given source violations to the target set and return the target set . This method will skip violations that have a property path depth greater than 1 . | 196 | 30 |
142,808 | private void passViolations ( ConstraintValidatorContext context , Set < ConstraintViolation < Object > > source ) { for ( final ConstraintViolation < Object > violation : source ) { final Iterator < Node > nodeIter = violation . getPropertyPath ( ) . iterator ( ) ; final ConstraintViolationBuilder builder = context . buildConstraintViolationWithTemplate ( violation . getMessageTemplate ( ) ) ; ConstraintValidatorContext nodeContext ; if ( nodeIter . hasNext ( ) ) { StringBuilder sb = new StringBuilder ( nodeIter . next ( ) . getName ( ) ) ; if ( supportsConstraintComposition ) { while ( nodeIter . hasNext ( ) ) { sb . append ( ' ' ) . append ( nodeIter . next ( ) ) ; } } builder . addNode ( sb . toString ( ) ) . addConstraintViolation ( ) ; } else { builder . addConstraintViolation ( ) ; } } } | Pass the given violations to the given context . This method will skip violations that have a property path depth greater than 1 . | 218 | 24 |
142,809 | private void editCell ( Cell cell ) { if ( cell == null || cell == editedCell ) return ; T record = getRecordForRow ( cell . getParentRow ( ) ) ; if ( record == null ) return ; registerCurrentEdition ( cell , record ) ; } | Begin cell edition | 58 | 3 |
142,810 | public static String toHawkularFormat ( BasicMessage msg ) { return String . format ( "%s=%s" , msg . getClass ( ) . getSimpleName ( ) , msg . toJSON ( ) ) ; } | Returns a string that encodes the given object as a JSON message but then prefixes that JSON with additional information that a Hawkular client will need to be able to deserialize the JSON . | 48 | 39 |
142,811 | public static < T extends BasicMessage > T fromJSON ( String json , Class < T > clazz ) { try { Method buildObjectMapperForDeserializationMethod = findBuildObjectMapperForDeserializationMethod ( clazz ) ; final ObjectMapper mapper = ( ObjectMapper ) buildObjectMapperForDeserializationMethod . invoke ( null ) ; if ( FailOnUnknownProperties . class . isAssignableFrom ( clazz ) ) { mapper . configure ( DeserializationFeature . FAIL_ON_UNKNOWN_PROPERTIES , true ) ; } return mapper . readValue ( json , clazz ) ; } catch ( Exception e ) { throw new IllegalStateException ( "JSON message cannot be converted to object of type [" + clazz + "]" , e ) ; } } | Convenience static method that converts a JSON string to a particular message object . | 175 | 16 |
142,812 | public static < T extends BasicMessage > BasicMessageWithExtraData < T > fromJSON ( InputStream in , Class < T > clazz ) { final T obj ; final byte [ ] remainder ; try ( JsonParser parser = new JsonFactory ( ) . configure ( Feature . AUTO_CLOSE_SOURCE , false ) . createParser ( in ) ) { Method buildObjectMapperForDeserializationMethod = findBuildObjectMapperForDeserializationMethod ( clazz ) ; final ObjectMapper mapper = ( ObjectMapper ) buildObjectMapperForDeserializationMethod . invoke ( null ) ; if ( FailOnUnknownProperties . class . isAssignableFrom ( clazz ) ) { mapper . configure ( DeserializationFeature . FAIL_ON_UNKNOWN_PROPERTIES , true ) ; } obj = mapper . readValue ( parser , clazz ) ; final ByteArrayOutputStream remainderStream = new ByteArrayOutputStream ( ) ; final int released = parser . releaseBuffered ( remainderStream ) ; remainder = ( released > 0 ) ? remainderStream . toByteArray ( ) : new byte [ 0 ] ; } catch ( Exception e ) { throw new IllegalArgumentException ( "Stream cannot be converted to JSON object of type [" + clazz + "]" , e ) ; } return new BasicMessageWithExtraData < T > ( obj , new BinaryData ( remainder , in ) ) ; } | Convenience static method that reads a JSON string from the given stream and converts the JSON string to a particular message object . The input stream will remain open so the caller can stream any extra data that might appear after it . | 304 | 45 |
142,813 | protected static ObjectMapper buildObjectMapperForDeserialization ( ) { final ObjectMapper mapper = new ObjectMapper ( ) ; mapper . configure ( DeserializationFeature . FAIL_ON_UNKNOWN_PROPERTIES , false ) ; return mapper ; } | This is static so really there is no true overriding it in subclasses . However fromJSON will do the proper reflection in order to invoke the proper method for the class that is being deserialized . So subclasses that want to provide their own ObjectMapper will define their own method that matches the signature of this method and it will be used . | 61 | 70 |
142,814 | @ Override public String toJSON ( ) { final ObjectMapper mapper = buildObjectMapperForSerialization ( ) ; try { return mapper . writeValueAsString ( this ) ; } catch ( JsonProcessingException e ) { throw new IllegalStateException ( "Object cannot be parsed as JSON." , e ) ; } } | Converts this message to its JSON string representation . | 72 | 10 |
142,815 | @ Override public void onResponse ( Object cookie , ResponseJSO response , int msgLevel , String msg ) { PendingRequestInfo info = ( PendingRequestInfo ) cookie ; // Store answer in cache if ( info . fStoreResultInCache ) cache . put ( info . requestKey , response ) ; // give the result to all the subscribees for ( RequestCallInfo call : info . subscriptions ) call . setResult ( msgLevel , msg , null , response ) ; // forget this request pendingRequests . remove ( info ) ; // calls back the clients checkAnswersToGive ( ) ; } | receives the answer from the ServerComm object | 127 | 10 |
142,816 | public static boolean dumpDatabaseSchemaToFile ( DatabaseContext ctx , File file ) { log . info ( "Dumping database schema to file " + file . getAbsolutePath ( ) ) ; DatabaseDescriptionInspector inspector = new DatabaseDescriptionInspector ( ) ; DatabaseDescription dbDesc = inspector . getDatabaseDescription ( ctx . db , ctx . dbh ) ; Gson gson = new Gson ( ) ; String json = gson . toJson ( dbDesc ) ; try { PrintWriter writer ; writer = new PrintWriter ( file ) ; writer . print ( json ) ; writer . close ( ) ; return true ; } catch ( FileNotFoundException e ) { e . printStackTrace ( ) ; return false ; } } | Writes the current database schema to a file in JSON format . This file can be used to update another database . | 161 | 23 |
142,817 | 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 . | 208 | 28 |
142,818 | 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 | 99 | 5 |
142,819 | 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 | 71 | 6 |
142,820 | 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 . | 212 | 32 |
142,821 | public static HttpMockServer start ( ConfigReader configReader , NetworkType networkType ) { return HttpMockServer . startMockApiServer ( configReader , networkType ) ; } | Starts local HTTP server . | 42 | 6 |
142,822 | @ 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 | 108 | 13 |
142,823 | 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 | 65 | 7 |
142,824 | 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 . | 45 | 9 |
142,825 | public void insert ( Shape w , int beforeIndex ) { if ( ( beforeIndex < 0 ) || ( beforeIndex > size ) ) { throw new IndexOutOfBoundsException ( ) ; } // Realloc array if necessary (doubling). 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 ; // Move all widgets after 'beforeIndex' back a slot. for ( int i = size - 1 ; i > beforeIndex ; -- i ) { array [ i ] = array [ i - 1 ] ; } array [ beforeIndex ] = w ; } | Inserts a widget before the specified index . | 168 | 9 |
142,826 | 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 . | 74 | 9 |
142,827 | public void remove ( Widget w ) { int index = indexOf ( w ) ; if ( index == - 1 ) { throw new NoSuchElementException ( ) ; } remove ( index ) ; } | Removes the specified widget . | 42 | 6 |
142,828 | 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 | 183 | 21 |
142,829 | 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 | 50 | 12 |
142,830 | 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 . | 48 | 20 |
142,831 | 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 | 33 | 13 |
142,832 | 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 . | 28 | 18 |
142,833 | 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 . | 50 | 19 |
142,834 | 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 . | 51 | 19 |
142,835 | public void run ( AcceptsOneWidget container ) { /** Add our widgets in the container */ container . setWidget ( UiBuilder . addIn ( new VerticalPanel ( ) , personListWidget , personneForm , categoryForm , nextButton ) ) ; /* * Bind things together */ // selectedPerson to person form Bind ( personListWidget , "selectedPersonne" ) . Mode ( Mode . OneWay ) . Log ( "PERSONNEFORM" ) . To ( personneForm , "personne" ) ; // maps the selected person's category to the category form Bind ( personListWidget , "selectedPersonne.category" ) . Mode ( Mode . OneWay ) . MapTo ( categoryForm ) ; // selected person's description to Window's title Bind ( personListWidget , "selectedPersonne.description" ) . Mode ( Mode . OneWay ) . To ( new WriteOnlyPropertyAdapter ( ) { @ Override public void setValue ( Object object ) { Window . setTitle ( ( String ) object ) ; } } ) ; /* * Initialize person list widget */ personListWidget . setPersonList ( famille ) ; personListWidget . setSelectedPersonne ( famille . get ( 0 ) ) ; nextButton . addClickHandler ( nextButtonClickHandler ) ; } | Runs the demo | 271 | 4 |
142,836 | private void _RemoveValidator ( Row item , int column ) { // already clean ? if ( m_currentEditedItem == null && m_currentEditedColumn < 0 ) return ; // touch the table 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 | 109 | 12 |
142,837 | 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 | 189 | 4 |
142,838 | 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 | 93 | 16 |
142,839 | 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 | 123 | 6 |
142,840 | @ Override 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 | 104 | 3 |
142,841 | 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 . | 67 | 17 |
142,842 | @ 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 . | 128 | 8 |
142,843 | @ RobotKeywordOverload @ ArgumentNames ( { "topic" , "message" } ) public void publishToMQTTSynchronously ( String topic , Object message ) throws MqttException { publishToMQTTSynchronously ( topic , message , 0 , false ) ; } | Publish a message to a topic | 60 | 7 |
142,844 | @ 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 | 211 | 14 |
142,845 | @ 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 | 70 | 8 |
142,846 | @ 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 ) ; // set clean session to false so the state is remembered across // sessions MqttConnectOptions connOpts = new MqttConnectOptions ( ) ; connOpts . setCleanSession ( false ) ; // set callback before connecting so prior messages are delivered as // soon as we connect 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 ) ; // now loop until either we receive the message in the topic or // timeout 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 ) { /* * If expected payload is empty, all we need to validate is * receiving the message in the topic. If expected payload is * not empty, then we need to validate that it is contained in * the actual payload */ message = handler . getNextMessage ( timeout ) ; if ( message != null ) { // received a message in the topic payload = message . getPayload ( ) ; String payloadStr = new String ( payload ) ; if ( expectedPayload . isEmpty ( ) || ( payloadStr . matches ( expectedPayload ) ) ) { validated = true ; break ; } } // update timeout to remaining time and check 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 ) { // empty } } } | Subscribe to an MQTT broker and validate that a message with specified payload is received | 660 | 17 |
142,847 | 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 | 78 | 9 |
142,848 | public void initialize ( @ Observes @ Initialized ( ApplicationScoped . class ) Object ignore ) { log . debugf ( "Initializing [%s]" , this . getClass ( ) . getName ( ) ) ; try { feedSessionListenerProducer = new BiFunction < String , Session , WsSessionListener > ( ) { @ Override public WsSessionListener apply ( String key , Session session ) { // In the future, if we need other queues/topics that need to be listened to, we add them here. 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 > ( ) { @ Override public WsSessionListener apply ( String key , Session session ) { // In the future, if we need other queues/topics that need to be listened to, we add them here. 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 . | 424 | 32 |
142,849 | 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 . | 32 | 19 |
142,850 | 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 . | 147 | 17 |
142,851 | 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 ) { /* Node not found for the given key */ return null ; } final TrieNode < V > node = currentNode . children . get ( key . charAt ( key . length ( ) - 1 ) ) ; if ( node == null || ! node . inUse ) { /* Node not found for the given key or is not in use */ return null ; } final V removed = node . value ; if ( removed != value && ( removed == null || ! removed . equals ( value ) ) ) { /* * Value in the map differs from the value given in the entry so do * nothing and return null. */ return null ; } node . unset ( ) ; -- size ; ++ modCount ; if ( node . children . isEmpty ( ) ) { /* Since there are no children left, we can compact the trie */ compact ( key ) ; } return removed ; } | Special version of remove for EntrySet . | 309 | 8 |
142,852 | 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 . | 177 | 20 |
142,853 | 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 . | 369 | 10 |
142,854 | public boolean IsInside ( String pDate ) { if ( periods == null ) { if ( days == null ) // security added to avoid null exception 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 | 164 | 3 |
142,855 | public boolean IsContained ( String pFrom , String pTo ) { if ( periods == null ) { // echo "IsContained() TO BE IMPLEMENTED FLLKJ :: {{ } ''<br/>"; 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 | 158 | 6 |
142,856 | public void Resolve ( String pFrom , String pTo ) { if ( periods != null ) { // call on an already resolved CalendarPeriod // echo // "LJLJKZHL KJH ELF B.EB EKJGF EFJBH EKLFJHL JGH <{{ : ' } <br/>"; throw new RuntimeException ( "Error call on an already resolved CalendarPeriod" ) ; } // echo "Resolving from $from to $to " . implode( ".", $this->days ) . // "<br/>"; // if all days are selected, make a whole period // build the micro periods 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 ; } // echo "Continuing<br/>"; int fromDay = CalendarFunctions . date_get_day ( pFrom ) ; // we have at least one gap 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 ) // no group created yet curGroup = new Group ( i - fromDay , i - fromDay ) ; else if ( curGroup . getTo ( ) == i - fromDay - 1 ) // day jointed to // current group curGroup . setTo ( i - fromDay ) ; else // day disjointed from current group { groups . add ( curGroup ) ; curGroup = new Group ( i - fromDay , i - fromDay ) ; } } } if ( curGroup != null ) groups . add ( curGroup ) ; // Dump( $groups ); // now generate the periods // String msg = "Starts on " + pFrom + ", which day is a " + fromDay + // "<br/>"; // for( int i = 0; i < groups.size(); i++ ) // { // Group group = groups.get( i ); // msg += "Group : " + group.implode( " to " ) + "<br/>"; // } // echo "From day : $from : $fromDay <br/>"; String firstOccurence = pFrom ; // echo "First occurence : $firstOccurence<br/>"; days = null ; periods = new ArrayList < Period > ( ) ; while ( firstOccurence . compareTo ( pTo ) <= 0 ) { // msg += "Occurence " + firstOccurence + "<br/>"; // day of $firstOccurence is always $fromDay // foreach( $groups as $group ) 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 ; // msg += "Adding " + mpFrom + ", " + mpTo + "<br/>"; periods . add ( new Period ( mpFrom , mpTo ) ) ; } } firstOccurence = CalendarFunctions . date_add_day ( firstOccurence , 7 ) ; } // ServerState::inst()->AddMessage( $msg ); } | from and to parameters | 839 | 4 |
142,857 | 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 ) { // one of the periods begins after the end of the other if ( periods1 . get ( i ) . getFrom ( ) . compareTo ( periods2 . get ( j ) . getTo ( ) ) > 0 ) { // period 1 begins after period 2 finishes => period2 is // eliminated ! j ++ ; } else if ( periods2 . get ( j ) . getFrom ( ) . compareTo ( periods1 . get ( i ) . getTo ( ) ) > 0 ) { // period 2 begins after end of period 1 => period 1 is eliminated // ! i ++ ; } // after that test, we can assume there is a non-void intersection else { // result[] = array( max($periods1[$i][0],$periods2[$j][0]), // min($periods1[$i][1],$periods2[$j][1]) ); 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 | 399 | 5 |
142,858 | 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 | 66 | 18 |
142,859 | 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 | 54 | 8 |
142,860 | @ AroundInvoke 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 ; } // Unwrap Exception if ex is instanceof InvocationTargetException 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 ; } // Only invoke cleanup declared at handling level if ( ! handling . cleanup ( ) . equals ( Object . class ) ) { cleanupInvoked = invokeCleanups ( targetClass , targetObject , handling . cleanup ( ) , t ) ; } break ; } } } // Handle the default exception type if no handlings are // declared or the handling did not handle the exception 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 . | 604 | 5 |
142,861 | private boolean invokeCleanups ( Class < ? > clazz , Object target , Class < ? > cleanupClazz , Throwable exception ) throws Exception { boolean invoked = false ; if ( ! cleanupClazz . equals ( Object . class ) ) { // Christian Beikov 29.07.2013: Traverse whole hierarchy // instead of retrieving the annotation directly from // the class object. 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 . | 316 | 13 |
142,862 | 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 . | 68 | 34 |
142,863 | protected void cacheConnection ( Connection connection , boolean closeExistingConnection ) { if ( this . connection != null && closeExistingConnection ) { try { // make sure it is closed to free up any resources it was using 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 . | 89 | 25 |
142,864 | 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 . | 65 | 20 |
142,865 | 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 . | 100 | 33 |
142,866 | 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 . | 217 | 21 |
142,867 | 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 . | 132 | 13 |
142,868 | 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 . | 137 | 13 |
142,869 | 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 . | 92 | 10 |
142,870 | 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 | 89 | 9 |
142,871 | public Boolean Add ( CalendarPeriodAssociative < T > period , AddFunction < T > addFunction ) { // combine les deux tableaux dans ordre croissant List < PeriodAssociative < T >> combined = _Combine ( periods , period . getPeriods ( ) ) ; // merge overlapping periods List < PeriodAssociative < T > > result = _Merge ( combined , addFunction ) ; if ( result == null ) return null ; // we should stop the MakeUpCalendarAssociative process periods = result ; // to say we can continue... return true ; } | adding two associative periods | 128 | 5 |
142,872 | 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 ( ) ) ) ; } // use merge to merge jointed periods... res . setPeriods ( res . _Merge ( periods ) ) ; return res ; } | returns the same but with no values and with the periods merged | 132 | 13 |
142,873 | 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 | 54 | 13 |
142,874 | public void emphasizePoint ( int index ) { if ( dots == null || dots . length < ( index - 1 ) ) return ; // impossible ! // if no change, nothing to do if ( emphasizedPoint == index ) return ; // de-emphasize the current emphasized point 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 | 121 | 11 |
142,875 | public void moveLastChild ( Row newParent ) { if ( this == newParent ) return ; // remove from its current position Row parentItem = m_parent ; if ( parentItem == null ) parentItem = this . treeTable . m_rootItem ; parentItem . getChilds ( ) . remove ( this ) ; // DOM.removeChild( m_body, m_tr ); if ( newParent == null ) newParent = this . treeTable . m_rootItem ; // insert at the end of the current parent // DOM add 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 ) ; // take care of the left padding Element firstTd = DOM . getChild ( m_tr , 0 ) ; firstTd . getStyle ( ) . setPaddingLeft ( getLevel ( ) * this . treeTable . treePadding , Unit . PX ) ; } | move to be the last item of parent | 301 | 8 |
142,876 | public void moveBefore ( Row item ) { if ( this == item ) return ; Element lastTrToMove = getLastLeafTR ( ) ; Element firstChildRow = DOM . getNextSibling ( m_tr ) ; // remove from its current position Row parentItem = m_parent ; if ( parentItem == null ) parentItem = this . treeTable . m_rootItem ; parentItem . getChilds ( ) . remove ( this ) ; // insert at the selected position if ( item == null ) { // insert at the end of the current parent // DOM add 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 ) ; } // take care of the left padding Element firstTd = DOM . getChild ( m_tr , 0 ) ; firstTd . getStyle ( ) . setPaddingLeft ( getLevel ( ) * this . treeTable . treePadding , Unit . PX ) ; // update child rows 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 | 515 | 6 |
142,877 | void removeHandler ( Object handlerRegistration ) { // Through object's interface implementation 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 | 245 | 8 |
142,878 | public static void filterRequest ( ContainerRequestContext requestContext , Predicate < String > predicate ) { //NOT a CORS request String requestOrigin = requestContext . getHeaderString ( Headers . ORIGIN ) ; if ( requestOrigin == null ) { return ; } if ( ! predicate . test ( requestOrigin ) ) { requestContext . abortWith ( Response . status ( Response . Status . BAD_REQUEST ) . build ( ) ) ; return ; } //It is a CORS pre-flight request, there is no route for it, just return 200 if ( requestContext . getMethod ( ) . equalsIgnoreCase ( HttpMethod . OPTIONS ) ) { requestContext . abortWith ( Response . status ( Response . Status . OK ) . build ( ) ) ; } } | Apply CORS filter on request | 164 | 6 |
142,879 | public static void filterResponse ( ContainerRequestContext requestContext , ContainerResponseContext responseContext , String extraAccesControlAllowHeaders ) { String requestOrigin = requestContext . getHeaderString ( Headers . ORIGIN ) ; if ( requestOrigin == null ) { return ; } // CORS validation already checked on request filter, see AbstractCorsRequestFilter 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 | 347 | 6 |
142,880 | 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 | 71 | 4 |
142,881 | public static Pair < Integer , Integer > getParentCellForElement ( Element root , Element element ) { Element tbody = getTBodyElement ( root ) ; // Is the element in our table ? and what's the path from the table to it ? ArrayList < Element > path = TemplateUtils . isDescendant ( tbody , element ) ; if ( path == null ) return null ; // we know that path[0] is tbody and that path[1] is a tr template 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 | 166 | 21 |
142,882 | public static void setDragData ( Object source , Object data ) { DragUtils . source = source ; DragUtils . data = data ; } | Sets the drag and drop data and its source | 31 | 10 |
142,883 | 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 . | 64 | 10 |
142,884 | @ Override public void setWidget ( Widget w ) { // Validate if ( w == widget ) return ; // Detach new child. if ( w != null ) w . removeFromParent ( ) ; // Remove old child. if ( widget != null ) remove ( widget ) ; // Logical attach. widget = w ; if ( w != null ) { // Physical attach. DOM . appendChild ( containerElement , widget . getElement ( ) ) ; adopt ( w ) ; } } | Sets this panel s widget . Any existing child widget will be removed . | 103 | 15 |
142,885 | 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 . | 67 | 18 |
142,886 | 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 | 107 | 18 |
142,887 | 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 . | 64 | 32 |
142,888 | 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 . | 38 | 24 |
142,889 | 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 . | 357 | 9 |
142,890 | 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 . | 61 | 14 |
142,891 | public static int getTypeVariablePosition ( GenericDeclaration genericDeclartion , TypeVariable < ? > typeVariable ) { int position = - 1 ; TypeVariable < ? > [ ] typeVariableDeclarationParameters = genericDeclartion . getTypeParameters ( ) ; // Try to find the position of the type variable in the class 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 . | 119 | 59 |
142,892 | 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 > ( ) { @ Override 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 . | 183 | 63 |
142,893 | public static Field getField ( Class < ? > clazz , String fieldName ) { final String internedName = fieldName . intern ( ) ; return traverseHierarchy ( clazz , new TraverseTask < Field > ( ) { @ Override 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 . | 131 | 62 |
142,894 | public static Method getMethod ( Class < ? > clazz , final String methodName , final Class < ? > ... parameterTypes ) { final String internedName = methodName . intern ( ) ; return traverseHierarchy ( clazz , new TraverseTask < Method > ( ) { @ Override 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 . | 194 | 62 |
142,895 | public static List < Method > getMethods ( Class < ? > clazz , final Class < ? extends Annotation > annotation ) { final List < Method > methods = new ArrayList < Method > ( ) ; traverseHierarchy ( clazz , new TraverseTask < Method > ( ) { @ Override 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 . | 153 | 86 |
142,896 | 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 | 39 | 11 |
142,897 | 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 | 47 | 9 |
142,898 | 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 | 41 | 53 |
142,899 | 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 | 98 | 16 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.