idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
18,300 | @ CheckForNull public String getName ( ) { Source parent = getParent ( ) ; if ( parent != null ) return parent . getName ( ) ; return null ; } | Returns the human - readable name of the current Source . | 37 | 11 |
18,301 | @ Nonnull public Token skipline ( boolean white ) throws IOException , LexerException { for ( ; ; ) { Token tok = token ( ) ; switch ( tok . getType ( ) ) { case EOF : /* There ought to be a newline before EOF. * At least, in any skipline context. */ /* XXX Are we sure about this? */ warning ( tok . getLine ( ) , tok . getColumn ( ) , "No newline before end of file" ) ; return new Token ( NL , tok . getLine ( ) , tok . getColumn ( ) , "\n" ) ; // return tok; case NL : /* This may contain one or more newlines. */ return tok ; case CCOMMENT : case CPPCOMMENT : case WHITESPACE : break ; default : /* XXX Check white, if required. */ if ( white ) warning ( tok . getLine ( ) , tok . getColumn ( ) , "Unexpected nonwhite token" ) ; break ; } } } | Skips tokens until the end of line . | 228 | 9 |
18,302 | void notifyListenersOnStateChange ( ) { LOGGER . debug ( "Notifying connection listeners about state change to {}" , state ) ; for ( ConnectionListener listener : connectionListeners ) { switch ( state ) { case CONNECTED : listener . onConnectionEstablished ( connection ) ; break ; case CONNECTING : listener . onConnectionLost ( connection ) ; break ; case CLOSED : listener . onConnectionClosed ( connection ) ; break ; default : break ; } } } | Notifies all connection listener about a state change . | 102 | 10 |
18,303 | void establishConnection ( ) throws IOException { synchronized ( operationOnConnectionMonitor ) { if ( state == State . CLOSED ) { throw new IOException ( "Attempt to establish a connection with a closed connection factory" ) ; } else if ( state == State . CONNECTED ) { LOGGER . warn ( "Establishing new connection although a connection is already established" ) ; } try { LOGGER . info ( "Trying to establish connection to {}:{}" , getHost ( ) , getPort ( ) ) ; connection = super . newConnection ( executorService ) ; connection . addShutdownListener ( connectionShutdownListener ) ; LOGGER . info ( "Established connection to {}:{}" , getHost ( ) , getPort ( ) ) ; changeState ( State . CONNECTED ) ; } catch ( IOException e ) { LOGGER . error ( "Failed to establish connection to {}:{}" , getHost ( ) , getPort ( ) ) ; throw e ; } } } | Establishes a new connection . | 210 | 7 |
18,304 | public static String sliceOf ( String str , int start , int end ) { return slc ( str , start , end ) ; } | Get slice of string | 28 | 4 |
18,305 | public static String slcEnd ( String str , int end ) { return FastStringUtils . noCopyStringFromChars ( Chr . slcEnd ( FastStringUtils . toCharArray ( str ) , end ) ) ; } | Gets end slice of a string . | 50 | 8 |
18,306 | public static char idx ( String str , int index ) { int i = calculateIndex ( str . length ( ) , index ) ; char c = str . charAt ( i ) ; return c ; } | Gets character at index | 43 | 5 |
18,307 | public static String idx ( String str , int index , char c ) { char [ ] chars = str . toCharArray ( ) ; Chr . idx ( chars , index , c ) ; return new String ( chars ) ; } | Puts character at index | 49 | 5 |
18,308 | public static boolean in ( char c , String str ) { return Chr . in ( c , FastStringUtils . toCharArray ( str ) ) ; } | See if a char is in another string | 33 | 8 |
18,309 | public static String add ( String str , String str2 ) { return FastStringUtils . noCopyStringFromChars ( Chr . add ( FastStringUtils . toCharArray ( str ) , FastStringUtils . toCharArray ( str2 ) ) ) ; } | Add one string to another | 58 | 5 |
18,310 | public static String add ( String ... strings ) { int length = 0 ; for ( String str : strings ) { if ( str == null ) { continue ; } length += str . length ( ) ; } CharBuf builder = CharBuf . createExact ( length ) ; for ( String str : strings ) { if ( str == null ) { continue ; } builder . add ( str ) ; } return builder . toString ( ) ; } | Add many strings together to another | 93 | 6 |
18,311 | public static String sputl ( Object ... messages ) { CharBuf buf = CharBuf . create ( 100 ) ; return sputl ( buf , messages ) . toString ( ) ; } | like putl but writes to a string . | 42 | 9 |
18,312 | public static String sputs ( Object ... messages ) { CharBuf buf = CharBuf . create ( 80 ) ; return sputs ( buf , messages ) . toString ( ) ; } | Like puts but writes to a String . | 40 | 8 |
18,313 | public static CharBuf sputl ( CharBuf buf , Object ... messages ) { for ( Object message : messages ) { if ( message == null ) { buf . add ( "<NULL>" ) ; } else if ( message . getClass ( ) . isArray ( ) ) { buf . add ( toListOrSingletonList ( message ) . toString ( ) ) ; } else { buf . add ( message . toString ( ) ) ; } buf . add ( ' ' ) ; } buf . add ( ' ' ) ; return buf ; } | Writes to a char buf . A char buf is like a StringBuilder . | 117 | 16 |
18,314 | private Object parseFile ( File file , String scharset ) { Charset charset = scharset == null || scharset . length ( ) == 0 ? StandardCharsets . UTF_8 : Charset . forName ( scharset ) ; if ( file . length ( ) > 2_000_000 ) { try ( Reader reader = Files . newBufferedReader ( Classpaths . path ( file . toString ( ) ) , charset ) ) { return parse ( reader ) ; } catch ( IOException ioe ) { throw new JsonException ( "Unable to process file: " + file . getPath ( ) , ioe ) ; } } else { try { return JsonFactory . create ( ) . fromJson ( Files . newBufferedReader ( Classpaths . path ( file . toString ( ) ) , charset ) ) ; } catch ( IOException e ) { throw new JsonException ( "Unable to process file: " + file . getPath ( ) , e ) ; } } } | Slight changes to remove groovy dependencies . | 225 | 9 |
18,315 | public static void puts ( Object ... messages ) { for ( Object message : messages ) { IO . print ( message ) ; if ( ! ( message instanceof Terminal . Escape ) ) IO . print ( ' ' ) ; } IO . println ( ) ; } | Like print but prints out a whole slew of objects on the same line . | 53 | 15 |
18,316 | private int compareOrder ( CacheEntry other ) { if ( order > other . order ) { //this order is lower so it has higher priority return 1 ; } else if ( order < other . order ) { //this order is higher so it has lower priority return - 1 ; } else if ( order == other . order ) { //equal priority return 0 ; } die ( ) ; return 0 ; } | Compare the order . | 83 | 4 |
18,317 | private int compareToLFU ( CacheEntry other ) { int cmp = compareReadCount ( other ) ; if ( cmp != 0 ) { return cmp ; } cmp = compareTime ( other ) ; if ( cmp != 0 ) { return cmp ; } return compareOrder ( other ) ; } | Compares the read counts . | 66 | 6 |
18,318 | private int compareToLRU ( CacheEntry other ) { int cmp = compareTime ( other ) ; if ( cmp != 0 ) { return cmp ; } cmp = compareOrder ( other ) ; if ( cmp != 0 ) { return cmp ; } return compareReadCount ( other ) ; } | Compare the time . | 66 | 4 |
18,319 | private int compareToFIFO ( CacheEntry other ) { int cmp = compareOrder ( other ) ; if ( cmp != 0 ) { return cmp ; } cmp = compareTime ( other ) ; if ( cmp != 0 ) { return cmp ; } return cmp = compareReadCount ( other ) ; } | Compare for FIFO | 70 | 5 |
18,320 | @ SuppressWarnings ( "unchecked" ) public < T > T readBodyAs ( Class < T > type ) { if ( String . class . isAssignableFrom ( type ) ) { return ( T ) readBodyAsString ( ) ; } else if ( Number . class . isAssignableFrom ( type ) ) { return ( T ) readBodyAsNumber ( ( Class < Number > ) type ) ; } else if ( Boolean . class . isAssignableFrom ( type ) ) { return ( T ) readBodyAsBoolean ( ) ; } else if ( Character . class . isAssignableFrom ( type ) ) { return ( T ) readBodyAsChar ( ) ; } return readBodyAsObject ( type ) ; } | Extracts the message body and interprets it as the given Java type | 161 | 15 |
18,321 | public String readBodyAsString ( ) { Charset charset = readCharset ( ) ; byte [ ] bodyContent = message . getBodyContent ( ) ; return new String ( bodyContent , charset ) ; } | Extracts the message body and interprets it as a string . | 48 | 14 |
18,322 | @ SuppressWarnings ( "unchecked" ) public < T > T readBodyAsObject ( Class < T > type ) { Charset charset = readCharset ( ) ; InputStream inputStream = new ByteArrayInputStream ( message . getBodyContent ( ) ) ; InputStreamReader inputReader = new InputStreamReader ( inputStream , charset ) ; StreamSource streamSource = new StreamSource ( inputReader ) ; try { Unmarshaller unmarshaller = JAXBContext . newInstance ( type ) . createUnmarshaller ( ) ; if ( type . isAnnotationPresent ( XmlRootElement . class ) ) { return ( T ) unmarshaller . unmarshal ( streamSource ) ; } else { JAXBElement < T > element = unmarshaller . unmarshal ( streamSource , type ) ; return element . getValue ( ) ; } } catch ( JAXBException e ) { throw new RuntimeException ( e ) ; } } | Extracts the message body and interprets it as the XML representation of an object of the given type . | 217 | 22 |
18,323 | public < T > void addEvent ( Class < T > eventType , PublisherConfiguration configuration ) { publisherConfigurations . put ( eventType , configuration ) ; } | Adds events of the given type to the CDI events to which the event publisher listens in order to publish them . The publisher configuration is used to decide where to and how to publish messages . | 33 | 38 |
18,324 | MessagePublisher providePublisher ( PublisherReliability reliability , Class < ? > eventType ) { Map < Class < ? > , MessagePublisher > localPublishers = publishers . get ( ) ; if ( localPublishers == null ) { localPublishers = new HashMap < Class < ? > , MessagePublisher > ( ) ; publishers . set ( localPublishers ) ; } MessagePublisher publisher = localPublishers . get ( eventType ) ; if ( publisher == null ) { publisher = new GenericPublisher ( connectionFactory , reliability ) ; localPublishers . put ( eventType , publisher ) ; } return publisher ; } | Provides a publisher with the specified reliability . Within the same thread the same producer instance is provided for the given event type . | 126 | 25 |
18,325 | static Message buildMessage ( PublisherConfiguration publisherConfiguration , Object event ) { Message message = new Message ( publisherConfiguration . basicProperties ) . exchange ( publisherConfiguration . exchange ) . routingKey ( publisherConfiguration . routingKey ) ; if ( publisherConfiguration . persistent ) { message . persistent ( ) ; } if ( event instanceof ContainsData ) { message . body ( ( ( ContainsData ) event ) . getData ( ) ) ; } else if ( event instanceof ContainsContent ) { message . body ( ( ( ContainsContent ) event ) . getContent ( ) ) ; } else if ( event instanceof ContainsId ) { message . body ( ( ( ContainsId ) event ) . getId ( ) ) ; } return message ; } | Builds a message based on a CDI event and its publisher configuration . | 151 | 15 |
18,326 | public < T > Message body ( T body , Charset charset ) { messageWriter . writeBody ( body , charset ) ; return this ; } | Serializes and adds the given object as body to the message using the given charset for encoding . | 33 | 20 |
18,327 | public Message contentEncoding ( String charset ) { basicProperties = basicProperties . builder ( ) . contentEncoding ( charset ) . build ( ) ; return this ; } | Sets the content charset encoding of this message . | 39 | 11 |
18,328 | public Message contentType ( String contentType ) { basicProperties = basicProperties . builder ( ) . contentType ( contentType ) . build ( ) ; return this ; } | Sets the content type of this message . | 37 | 9 |
18,329 | public void publish ( Channel channel , DeliveryOptions deliveryOptions ) throws IOException { // Assure to have a timestamp if ( basicProperties . getTimestamp ( ) == null ) { basicProperties . builder ( ) . timestamp ( new Date ( ) ) ; } boolean mandatory = deliveryOptions == DeliveryOptions . MANDATORY ; boolean immediate = deliveryOptions == DeliveryOptions . IMMEDIATE ; LOGGER . info ( "Publishing message to exchange '{}' with routing key '{}' (deliveryOptions: {}, persistent: {})" , new Object [ ] { exchange , routingKey , deliveryOptions , basicProperties . getDeliveryMode ( ) == 2 } ) ; channel . basicPublish ( exchange , routingKey , mandatory , immediate , basicProperties , bodyContent ) ; LOGGER . info ( "Successfully published message to exchange '{}' with routing key '{}'" , exchange , routingKey ) ; } | Publishes a message via the given channel while using the specified delivery options . | 198 | 15 |
18,330 | @ SuppressWarnings ( "unchecked" ) Object buildEvent ( Message message ) { Object event = eventPool . get ( ) ; if ( event instanceof ContainsData ) { ( ( ContainsData ) event ) . setData ( message . getBodyContent ( ) ) ; } else if ( event instanceof ContainsContent ) { Class < ? > parameterType = getParameterType ( event , ContainsContent . class ) ; ( ( ContainsContent ) event ) . setContent ( message . getBodyAs ( parameterType ) ) ; } else if ( event instanceof ContainsId ) { Class < ? > parameterType = getParameterType ( event , ContainsId . class ) ; ( ( ContainsId ) event ) . setId ( message . getBodyAs ( parameterType ) ) ; } return event ; } | Builds a CDI event from a message . The CDI event instance is retrieved from the injection container . | 168 | 22 |
18,331 | @ SuppressWarnings ( "unchecked" ) static Class < ? > getParameterType ( Object object , Class < ? > expectedType ) { Collection < Class < ? > > extendedAndImplementedTypes = getExtendedAndImplementedTypes ( object . getClass ( ) , new LinkedList < Class < ? > > ( ) ) ; for ( Class < ? > type : extendedAndImplementedTypes ) { Type [ ] implementedInterfaces = type . getGenericInterfaces ( ) ; for ( Type implementedInterface : implementedInterfaces ) { if ( implementedInterface instanceof ParameterizedType ) { ParameterizedType parameterizedCandidateType = ( ParameterizedType ) implementedInterface ; if ( parameterizedCandidateType . getRawType ( ) . equals ( expectedType ) ) { Type [ ] typeArguments = parameterizedCandidateType . getActualTypeArguments ( ) ; Type typeArgument ; if ( typeArguments . length == 0 ) { typeArgument = Object . class ; } else { typeArgument = parameterizedCandidateType . getActualTypeArguments ( ) [ 0 ] ; } return ( Class < ? > ) typeArgument ; } } } } // This may never happen in case the caller checked if object instanceof expectedType throw new RuntimeException ( "Expected type " + expectedType + " is not in class hierarchy of " + object . getClass ( ) ) ; } | Gets the type parameter of the expected generic interface which is actually used by the class of the given object . The generic interface can be implemented by an class or interface in the object s class hierarchy | 306 | 39 |
18,332 | static List < Class < ? > > getExtendedAndImplementedTypes ( Class < ? > clazz , List < Class < ? > > hierarchy ) { hierarchy . add ( clazz ) ; Class < ? > superClass = clazz . getSuperclass ( ) ; if ( superClass != null ) { hierarchy = getExtendedAndImplementedTypes ( superClass , hierarchy ) ; } for ( Class < ? > implementedInterface : clazz . getInterfaces ( ) ) { hierarchy = getExtendedAndImplementedTypes ( implementedInterface , hierarchy ) ; } return hierarchy ; } | Gets all classes and interfaces in the class hierarchy of the given class including the class itself . | 125 | 19 |
18,333 | protected Channel provideChannel ( ) throws IOException { if ( channel == null || ! channel . isOpen ( ) ) { Connection connection = connectionFactory . newConnection ( ) ; channel = connection . createChannel ( ) ; } return channel ; } | Initializes a channel if there is not already an open channel . | 50 | 13 |
18,334 | protected void handleIoException ( int attempt , IOException ioException ) throws IOException { if ( channel != null && channel . isOpen ( ) ) { try { channel . close ( ) ; } catch ( IOException e ) { LOGGER . warn ( "Failed to close channel after failed publish" , e ) ; } } channel = null ; if ( attempt == DEFAULT_RETRY_ATTEMPTS ) { throw ioException ; } try { Thread . sleep ( DEFAULT_RETRY_INTERVAL ) ; } catch ( InterruptedException e ) { LOGGER . warn ( "Sending message interrupted while waiting for retry attempt" , e ) ; } } | Handles an IOException depending on the already used attempts to send a message . Also performs a soft reset of the currently used channel . | 142 | 27 |
18,335 | public static String getSortableFieldFromClass ( Class < ? > clazz ) { /** See if the fieldName is in the field listStream already. * We keep a hash-map cache. * */ String fieldName = getSortableField ( clazz ) ; /** * Not found in cache. */ if ( fieldName == null ) { /* See if we have this sortable field and look for string first. */ for ( String name : fieldSortNames ) { if ( classHasStringField ( clazz , name ) ) { fieldName = name ; break ; } } /* Now see if we can find one of our predefined suffixes. */ if ( fieldName == null ) { for ( String name : fieldSortNamesSuffixes ) { fieldName = getFirstStringFieldNameEndsWithFromClass ( clazz , name ) ; if ( fieldName != null ) { break ; } } } /** * Ok. We still did not find it so give us the first comparable or * primitive that we can find. */ if ( fieldName == null ) { fieldName = getFirstComparableOrPrimitiveFromClass ( clazz ) ; } /* We could not find a sortable field. */ if ( fieldName == null ) { setSortableField ( clazz , "NOT FOUND" ) ; Exceptions . die ( "Could not find a sortable field for type " + clazz ) ; } /* We found a sortable field. */ setSortableField ( clazz , fieldName ) ; } return fieldName ; } | Gets the first sortable field . | 326 | 8 |
18,336 | public void configureFactory ( Class < ? > clazz ) { ConnectionConfiguration connectionConfiguration = resolveConnectionConfiguration ( clazz ) ; if ( connectionConfiguration == null ) { return ; } connectionFactory . setHost ( connectionConfiguration . host ( ) ) ; connectionFactory . setVirtualHost ( connectionConfiguration . virtualHost ( ) ) ; connectionFactory . setPort ( connectionConfiguration . port ( ) ) ; connectionFactory . setConnectionTimeout ( connectionConfiguration . timeout ( ) ) ; connectionFactory . setRequestedHeartbeat ( connectionConfiguration . heartbeat ( ) ) ; connectionFactory . setUsername ( connectionConfiguration . username ( ) ) ; connectionFactory . setPassword ( connectionConfiguration . password ( ) ) ; connectionFactory . setRequestedFrameMax ( connectionConfiguration . frameMax ( ) ) ; } | Configures the connection factory supplied by dependency injection using the connection configuration annotated at the given class . | 161 | 20 |
18,337 | private final void buildIfNeededMap ( ) { if ( map == null ) { map = new HashMap <> ( items . length ) ; for ( Entry < String , Value > miv : items ) { if ( miv == null ) { break ; } map . put ( miv . getKey ( ) , miv . getValue ( ) ) ; } } } | Build the map if requested to it does this lazily . | 80 | 12 |
18,338 | public static boolean respondsTo ( Object object , String method ) { if ( object instanceof Class ) { return Reflection . respondsTo ( ( Class ) object , method ) ; } else { return Reflection . respondsTo ( object , method ) ; } } | Checks to see if an object responds to a method . Helper facade over Reflection library . | 53 | 20 |
18,339 | public < T > void writeBodyFromObject ( T bodyAsObject , Charset charset ) { @ SuppressWarnings ( "unchecked" ) Class < T > clazz = ( Class < T > ) bodyAsObject . getClass ( ) ; ByteArrayOutputStream outputStream = new ByteArrayOutputStream ( ) ; Writer outputWriter = new OutputStreamWriter ( outputStream , charset ) ; try { Marshaller marshaller = JAXBContext . newInstance ( clazz ) . createMarshaller ( ) ; if ( clazz . isAnnotationPresent ( XmlRootElement . class ) ) { marshaller . marshal ( bodyAsObject , outputWriter ) ; } else { String tagName = unCapitalizedClassName ( clazz ) ; JAXBElement < T > element = new JAXBElement < T > ( new QName ( "" , tagName ) , clazz , bodyAsObject ) ; marshaller . marshal ( element , outputWriter ) ; } } catch ( JAXBException e ) { throw new RuntimeException ( e ) ; } byte [ ] bodyContent = outputStream . toByteArray ( ) ; message . contentType ( Message . APPLICATION_XML ) . contentEncoding ( charset . name ( ) ) ; message . body ( bodyContent ) ; } | Writes the body by serializing the given object to XML . | 285 | 13 |
18,340 | public static boolean toBoolean ( Object obj , boolean defaultValue ) { if ( obj == null ) { return defaultValue ; } if ( obj instanceof Boolean ) { return ( ( Boolean ) obj ) . booleanValue ( ) ; } else if ( obj instanceof Number || obj . getClass ( ) . isPrimitive ( ) ) { int value = toInt ( obj ) ; return value != 0 ? true : false ; } else if ( obj instanceof Value ) { return ( ( Value ) obj ) . booleanValue ( ) ; } else if ( obj instanceof String || obj instanceof CharSequence ) { String str = Conversions . toString ( obj ) ; if ( str . length ( ) == 0 ) { return false ; } if ( str . equals ( "false" ) ) { return false ; } else { return true ; } } else if ( isArray ( obj ) ) { return len ( obj ) > 0 ; } else if ( obj instanceof Collection ) { if ( len ( obj ) > 0 ) { List list = Lists . list ( ( Collection ) obj ) ; while ( list . remove ( null ) ) { } return Lists . len ( list ) > 0 ; } else { return false ; } } else { return toBoolean ( Conversions . toString ( obj ) ) ; } } | Converts the value to boolean and if it is null it uses the default value passed . | 278 | 18 |
18,341 | public void addConsumer ( Consumer consumer , String queue ) { addConsumer ( consumer , new ConsumerConfiguration ( queue ) , DEFAULT_AMOUNT_OF_INSTANCES ) ; } | Adds a consumer to the container and binds it to the given queue with auto acknowledge disabled . Does NOT enable the consumer to consume from the message broker until the container is started . | 38 | 35 |
18,342 | public synchronized void addConsumer ( Consumer consumer , ConsumerConfiguration configuration , int instances ) { for ( int i = 0 ; i < instances ; i ++ ) { this . consumerHolders . add ( new ConsumerHolder ( consumer , configuration ) ) ; } } | Adds a consumer to the container and configures it according to the consumer configuration . Does NOT enable the consumer to consume from the message broker until the container is started . | 53 | 33 |
18,343 | protected List < ConsumerHolder > filterConsumersForClass ( Class < ? extends Consumer > consumerClass ) { List < ConsumerHolder > consumerHolderSubList = new LinkedList < ConsumerHolder > ( ) ; for ( ConsumerHolder consumerHolder : consumerHolders ) { if ( consumerClass . isAssignableFrom ( consumerHolder . getConsumer ( ) . getClass ( ) ) ) { consumerHolderSubList . add ( consumerHolder ) ; } } return consumerHolderSubList ; } | Filters the consumers being an instance extending or implementing the given class from the list of managed consumers . | 111 | 20 |
18,344 | protected List < ConsumerHolder > filterConsumersForEnabledFlag ( boolean enabled ) { List < ConsumerHolder > consumerHolderSubList = new LinkedList < ConsumerHolder > ( ) ; for ( ConsumerHolder consumerHolder : consumerHolders ) { if ( consumerHolder . isEnabled ( ) == enabled ) { consumerHolderSubList . add ( consumerHolder ) ; } } return consumerHolderSubList ; } | Filters the consumers matching the given enabled flag from the list of managed consumers . | 92 | 16 |
18,345 | protected List < ConsumerHolder > filterConsumersForActiveFlag ( boolean active ) { List < ConsumerHolder > consumerHolderSubList = new LinkedList < ConsumerHolder > ( ) ; for ( ConsumerHolder consumerHolder : consumerHolders ) { if ( consumerHolder . isActive ( ) == active ) { consumerHolderSubList . add ( consumerHolder ) ; } } return consumerHolderSubList ; } | Filters the consumers matching the given active flag from the list of managed consumers . | 93 | 16 |
18,346 | protected void enableConsumers ( List < ConsumerHolder > consumerHolders ) throws IOException { checkPreconditions ( consumerHolders ) ; try { for ( ConsumerHolder consumerHolder : consumerHolders ) { consumerHolder . enable ( ) ; } } catch ( IOException e ) { LOGGER . error ( "Failed to enable consumers - disabling already enabled consumers" ) ; disableConsumers ( consumerHolders ) ; throw e ; } } | Enables all consumers in the given list and hands them over for activation afterwards . | 96 | 16 |
18,347 | protected void activateConsumers ( List < ConsumerHolder > consumerHolders ) throws IOException { synchronized ( activationMonitor ) { for ( ConsumerHolder consumerHolder : consumerHolders ) { try { consumerHolder . activate ( ) ; } catch ( IOException e ) { LOGGER . error ( "Failed to activate consumer - deactivating already activated consumers" ) ; deactivateConsumers ( consumerHolders ) ; throw e ; } } } } | Activates all consumers in the given list . | 96 | 9 |
18,348 | protected void deactivateConsumers ( List < ConsumerHolder > consumerHolders ) { synchronized ( activationMonitor ) { for ( ConsumerHolder consumerHolder : consumerHolders ) { consumerHolder . deactivate ( ) ; } } } | Deactivates all consumers in the given list . | 50 | 10 |
18,349 | protected void checkPreconditions ( List < ConsumerHolder > consumerHolders ) throws IOException { Channel channel = createChannel ( ) ; for ( ConsumerHolder consumerHolder : consumerHolders ) { String queue = consumerHolder . getConfiguration ( ) . getQueueName ( ) ; try { channel . queueDeclarePassive ( queue ) ; LOGGER . debug ( "Queue {} found on broker" , queue ) ; } catch ( IOException e ) { LOGGER . error ( "Queue {} not found on broker" , queue ) ; throw e ; } } channel . close ( ) ; } | Checks if all preconditions are fulfilled on the broker to successfully register a consumer there . One important precondition is the existence of the queue the consumer shall consume from . | 127 | 36 |
18,350 | protected Channel createChannel ( ) throws IOException { LOGGER . debug ( "Creating channel" ) ; Connection connection = connectionFactory . newConnection ( ) ; Channel channel = connection . createChannel ( ) ; LOGGER . debug ( "Created channel" ) ; return channel ; } | Creates a channel to be used for consuming from the broker . | 57 | 13 |
18,351 | public final char [ ] findNextChar ( boolean inMiddleOfString , boolean wasEscapeChar , int match , int esc ) { try { ensureBuffer ( ) ; //grow the buffer and read in if needed int idx = index ; char [ ] _chars = readBuf ; int length = this . length ; int ch = this . ch ; if ( ! inMiddleOfString ) { foundEscape = false ; if ( ch == match ) { //we can start with a match but we // ignore it if we are not in the middle of a string. } else if ( idx < length - 1 ) { ch = _chars [ idx ] ; if ( ch == match ) { idx ++ ; } } } if ( idx < length ) { ch = _chars [ idx ] ; } /* Detect an empty string and then leave unless we came into this method in the escape state.. */ if ( ch == ' ' && ! wasEscapeChar ) { index = idx ; index ++ ; return EMPTY_CHARS ; } int start = idx ; if ( wasEscapeChar ) { idx ++ ; } boolean foundEnd = false ; //Have we actually found the end of the string? char [ ] results ; //The results so far might be the whole thing if we found the end. boolean _foundEscape = false ; /* Iterate through the buffer looking for the match which is the close quote most likely. */ while ( true ) { ch = _chars [ idx ] ; /* If we found the close quote " or the escape character \ */ if ( ch == match || ch == esc ) { if ( ch == match ) { foundEnd = true ; break ; } else if ( ch == esc ) { wasEscapeChar = true ; _foundEscape = true ; /** if we are dealing with an escape then see if the escaped char is a match * if so, skip it. */ if ( idx + 1 < length ) { wasEscapeChar = false ; //this denotes if we were able to skip because // if we were not then the next method in the recursion has to if we don't find the end. idx ++ ; } } } if ( idx >= length ) break ; idx ++ ; } foundEscape = _foundEscape ; /* After all that, we still might have an empty string! */ if ( idx == 0 ) { results = EMPTY_CHARS ; } else { results = Arrays . copyOfRange ( _chars , start , idx ) ; } // At this point we have some results but it might not be all of the results if we did not // find the close '"' (match) index = idx ; /* We found everthing so make like a tree and leave. */ if ( foundEnd ) { index ++ ; if ( index < length ) { ch = _chars [ index ] ; this . ch = ch ; } return results ; /* We did not find everything so prepare for the next buffer read. */ } else { /* Detect if we have more buffers to read. */ if ( index >= length && ! done ) { /*If we have more to read then read it. */ ensureBuffer ( ) ; /* Recursively call this method. */ char results2 [ ] = findNextChar ( true , wasEscapeChar , match , esc ) ; return Chr . add ( results , results2 ) ; } else { return Exceptions . die ( char [ ] . class , "Unable to find close char " + ( char ) match + " " + new String ( results ) ) ; } } } catch ( Exception ex ) { String str = CharScanner . errorDetails ( "findNextChar issue" , readBuf , index , ch ) ; return Exceptions . handle ( char [ ] . class , str , ex ) ; } } | Remember that this must work past buffer reader boundaries so we need to keep track where we were in the nested run . | 819 | 23 |
18,352 | public boolean addArray ( float ... values ) { if ( end + values . length >= this . values . length ) { this . values = grow ( this . values , ( this . values . length + values . length ) * 2 ) ; } System . arraycopy ( values , 0 , this . values , end , values . length ) ; end += values . length ; return true ; } | Add a new array to the list . | 81 | 8 |
18,353 | private static PropertyDescriptor getPropertyDescriptor ( final Class < ? > type , final String propertyName ) { Exceptions . requireNonNull ( type ) ; Exceptions . requireNonNull ( propertyName ) ; if ( ! propertyName . contains ( "." ) ) { return doGetPropertyDescriptor ( type , propertyName ) ; } else { String [ ] propertyNames = propertyName . split ( "[.]" ) ; Class < ? > clazz = type ; PropertyDescriptor propertyDescriptor = null ; for ( String pName : propertyNames ) { propertyDescriptor = doGetPropertyDescriptor ( clazz , pName ) ; if ( propertyDescriptor == null ) { return null ; } clazz = propertyDescriptor . getPropertyType ( ) ; } return propertyDescriptor ; } } | This needs refactor and put into Refleciton . | 178 | 12 |
18,354 | public boolean open ( ) { LibMediaInfo lib = LibMediaInfo . INSTANCE ; handle = lib . MediaInfo_New ( ) ; if ( handle != null ) { int opened = lib . MediaInfo_Open ( handle , new WString ( filename ) ) ; if ( opened == 1 ) { return true ; } else { lib . MediaInfo_Delete ( handle ) ; } } return false ; } | Open the media file . | 85 | 5 |
18,355 | public void close ( ) { if ( handle != null ) { LibMediaInfo . INSTANCE . MediaInfo_Close ( handle ) ; LibMediaInfo . INSTANCE . MediaInfo_Delete ( handle ) ; } } | Close the media file . | 45 | 5 |
18,356 | MediaInfo parse ( ) { try { BufferedReader reader = new BufferedReader ( new StringReader ( data ) ) ; MediaInfo mediaInfo = new MediaInfo ( ) ; String sectionName ; String line ; Sections sections ; Section section = null ; while ( parseState != ParseState . FINISHED ) { switch ( parseState ) { case DEFAULT : parseState = ParseState . NEXT_SECTION ; break ; case NEXT_SECTION : sectionName = reader . readLine ( ) ; if ( sectionName == null ) { parseState = ParseState . FINISHED ; } else if ( sectionName . length ( ) > 0 ) { parseState = ParseState . SECTION ; sections = mediaInfo . sections ( sectionName ) ; section = sections . newSection ( ) ; } break ; case SECTION : line = reader . readLine ( ) ; if ( line == null ) { parseState = ParseState . FINISHED ; } else if ( line . length ( ) == 0 ) { parseState = ParseState . NEXT_SECTION ; } else { String [ ] values = line . split ( ":" , 2 ) ; section . put ( values [ 0 ] . trim ( ) , values [ 1 ] . trim ( ) ) ; } break ; default : throw new IllegalStateException ( ) ; } } return mediaInfo ; } catch ( IOException e ) { throw new MediaInfoParseException ( "Failed to parse media info" , e ) ; } } | Parse the raw data . | 316 | 6 |
18,357 | private void checkChildrenCount ( ) { if ( getChildCount ( ) != 2 ) Log . e ( getResources ( ) . getString ( R . string . tag ) , getResources ( ) . getString ( R . string . wrong_number_children_error ) ) ; } | Checks if children number is correct and logs an error if it is not | 60 | 15 |
18,358 | public static MediaInfo mediaInfo ( String filename ) { MediaInfo result ; LibMediaInfo lib = LibMediaInfo . INSTANCE ; Pointer handle = lib . MediaInfo_New ( ) ; if ( handle != null ) { try { int opened = lib . MediaInfo_Open ( handle , new WString ( filename ) ) ; if ( opened == 1 ) { WString data = lib . MediaInfo_Inform ( handle ) ; lib . MediaInfo_Close ( handle ) ; result = new Parser ( data . toString ( ) ) . parse ( ) ; } else { result = null ; } } finally { lib . MediaInfo_Delete ( handle ) ; } } else { result = null ; } return result ; } | Extract media information for a particular file . | 153 | 9 |
18,359 | public Sections sections ( String type ) { Sections result = sectionsByType . get ( type ) ; if ( result == null ) { result = new Sections ( ) ; sectionsByType . put ( type , result ) ; } return result ; } | Get all of the sections of a particular type . | 50 | 10 |
18,360 | public Section first ( String type ) { Section result ; Sections sections = sections ( type ) ; if ( sections != null ) { result = sections . first ( ) ; } else { result = null ; } return result ; } | Get the first section of a particular type . | 46 | 9 |
18,361 | public void completeAnimationToFullHeight ( int completeExpandAnimationSpeed ) { HeightAnimation heightAnim = new HeightAnimation ( animableView , animableView . getMeasuredHeight ( ) , displayHeight ) ; heightAnim . setDuration ( completeExpandAnimationSpeed ) ; heightAnim . setInterpolator ( new DecelerateInterpolator ( ) ) ; animableView . startAnimation ( heightAnim ) ; } | Animates animableView until it reaches full screen height | 88 | 11 |
18,362 | public void completeAnimationToInitialHeight ( int completeShrinkAnimationSpeed , int initialAnimableLayoutHeight ) { HeightAnimation heightAnim = new HeightAnimation ( animableView , animableView . getMeasuredHeight ( ) , initialAnimableLayoutHeight ) ; heightAnim . setDuration ( completeShrinkAnimationSpeed ) ; heightAnim . setInterpolator ( new DecelerateInterpolator ( ) ) ; animableView . startAnimation ( heightAnim ) ; } | Animates animableView to get its initial height back | 100 | 11 |
18,363 | static Integer integer ( String value ) { Integer result ; if ( value != null ) { value = value . trim ( ) ; Matcher matcher = INTEGER_PATTERN . matcher ( value ) ; if ( matcher . matches ( ) ) { result = Integer . parseInt ( matcher . group ( 1 ) . replace ( " " , "" ) ) ; } else { throw new IllegalArgumentException ( "Unknown format for value: " + value ) ; } } else { result = null ; } return result ; } | Convert a string to an integer . | 113 | 8 |
18,364 | static BigDecimal decimal ( String value ) { BigDecimal result ; if ( value != null ) { value = value . trim ( ) ; Matcher matcher = DECIMAL_PATTERN . matcher ( value ) ; if ( matcher . matches ( ) ) { result = new BigDecimal ( matcher . group ( 1 ) ) ; } else { throw new IllegalArgumentException ( "Unknown format for value: " + value ) ; } } else { result = null ; } return result ; } | Convert a string to a big decimal . | 109 | 9 |
18,365 | static Duration duration ( String value ) { Duration result ; if ( value != null ) { value = value . trim ( ) ; Matcher matcher = DURATION_PATTERN . matcher ( value ) ; if ( matcher . matches ( ) ) { int hours = matcher . group ( 1 ) != null ? Integer . parseInt ( matcher . group ( 1 ) ) : 0 ; int minutes = matcher . group ( 2 ) != null ? Integer . parseInt ( matcher . group ( 2 ) ) : 0 ; int seconds = matcher . group ( 3 ) != null ? Integer . parseInt ( matcher . group ( 3 ) ) : 0 ; int millis = matcher . group ( 4 ) != null ? Integer . parseInt ( matcher . group ( 4 ) ) : 0 ; result = new Duration ( hours , minutes , seconds , millis ) ; } else { throw new IllegalArgumentException ( "Unknown format for value: " + value ) ; } } else { result = null ; } return result ; } | Convert a string to a duration . | 221 | 8 |
18,366 | private void loadWebConfigs ( Environment environment , SpringConfiguration config , ApplicationContext appCtx ) throws ClassNotFoundException { // Load filters. loadFilters ( config . getFilters ( ) , environment ) ; // Load servlet listener. environment . servlets ( ) . addServletListeners ( new RestContextLoaderListener ( ( XmlRestWebApplicationContext ) appCtx ) ) ; // Load servlets. loadServlets ( config . getServlets ( ) , environment ) ; } | Load filter servlets or listeners for WebApplicationContext . | 105 | 11 |
18,367 | @ SuppressWarnings ( "unchecked" ) private void loadFilters ( Map < String , FilterConfiguration > filters , Environment environment ) throws ClassNotFoundException { if ( filters != null ) { for ( Map . Entry < String , FilterConfiguration > filterEntry : filters . entrySet ( ) ) { FilterConfiguration filter = filterEntry . getValue ( ) ; // Create filter holder FilterHolder filterHolder = new FilterHolder ( ( Class < ? extends Filter > ) Class . forName ( filter . getClazz ( ) ) ) ; // Set name of filter filterHolder . setName ( filterEntry . getKey ( ) ) ; // Set params if ( filter . getParam ( ) != null ) { for ( Map . Entry < String , String > entry : filter . getParam ( ) . entrySet ( ) ) { filterHolder . setInitParameter ( entry . getKey ( ) , entry . getValue ( ) ) ; } } // Add filter environment . getApplicationContext ( ) . addFilter ( filterHolder , filter . getUrl ( ) , EnumSet . of ( DispatcherType . REQUEST ) ) ; } } } | Load all filters . | 246 | 4 |
18,368 | @ SuppressWarnings ( "unchecked" ) private void loadServlets ( Map < String , ServletConfiguration > servlets , Environment environment ) throws ClassNotFoundException { if ( servlets != null ) { for ( Map . Entry < String , ServletConfiguration > servletEntry : servlets . entrySet ( ) ) { ServletConfiguration servlet = servletEntry . getValue ( ) ; // Create servlet holder ServletHolder servletHolder = new ServletHolder ( ( Class < ? extends Servlet > ) Class . forName ( servlet . getClazz ( ) ) ) ; // Set name of servlet servletHolder . setName ( servletEntry . getKey ( ) ) ; // Set params if ( servlet . getParam ( ) != null ) { for ( Map . Entry < String , String > entry : servlet . getParam ( ) . entrySet ( ) ) { servletHolder . setInitParameter ( entry . getKey ( ) , entry . getValue ( ) ) ; } } // Add servlet environment . getApplicationContext ( ) . addServlet ( servletHolder , servlet . getUrl ( ) ) ; } } } | Load all servlets . | 256 | 5 |
18,369 | private String getPart ( int pos ) { String value = this . getValue ( ) ; if ( value == null ) { return null ; } String [ ] parts = value . split ( "/" ) ; return parts . length >= pos + 1 ? parts [ pos ] : null ; } | Extracts the given part from the unique identifier . | 60 | 11 |
18,370 | public NeedleRule withOuter ( final MethodRule rule ) { if ( rule instanceof InjectionProvider ) { addInjectionProvider ( ( InjectionProvider < ? > ) rule ) ; } methodRuleChain . add ( 0 , rule ) ; return this ; } | Encloses the added rule . | 56 | 7 |
18,371 | private List < String > buildCommand ( ) { List < String > command = new ArrayList < String > ( ) ; command . add ( cmd ) ; command . add ( "thin" ) ; command . add ( "--sourceAppPath=" + getSourceAppPath ( ) ) ; command . add ( "--targetLibCachePath=" + getTargetLibCachePath ( ) ) ; command . add ( "--targetThinAppPath=" + getTargetThinAppPath ( ) ) ; if ( getParentLibCachePath ( ) != null ) { command . add ( "--parentLibCachePath=" + getParentLibCachePath ( ) ) ; } return command ; } | Build up a command string to launch in new process | 143 | 10 |
18,372 | @ SuppressWarnings ( "unchecked" ) public < X > X resetToNice ( final Object mock ) { EasyMock . resetToNice ( mock ) ; return ( X ) mock ; } | Resets the given mock object and turns them to a mock with nice behavior . For details see the EasyMock documentation . | 44 | 25 |
18,373 | @ SuppressWarnings ( "unchecked" ) public < X > X resetToStrict ( final Object mock ) { EasyMock . resetToStrict ( mock ) ; return ( X ) mock ; } | Resets the given mock object and turns them to a mock with strict behavior . For details see the EasyMock documentation . | 46 | 25 |
18,374 | @ SuppressWarnings ( "unchecked" ) public < X > X resetToDefault ( final Object mock ) { EasyMock . resetToDefault ( mock ) ; return ( X ) mock ; } | Resets the given mock object and turns them to a mock with default behavior . For details see the EasyMock documentation . | 44 | 25 |
18,375 | protected void deleteContent ( final List < String > tables , final Statement statement ) throws SQLException { final ArrayList < String > tempTables = new ArrayList < String > ( tables ) ; // Loop until all data is deleted: we don't know the correct DROP // order, so we have to retry upon failure while ( ! tempTables . isEmpty ( ) ) { final int sizeBefore = tempTables . size ( ) ; for ( final ListIterator < String > iterator = tempTables . listIterator ( ) ; iterator . hasNext ( ) ; ) { final String table = iterator . next ( ) ; try { statement . executeUpdate ( "DELETE FROM " + table ) ; iterator . remove ( ) ; } catch ( final SQLException exc ) { LOG . warn ( "Ignored exception: " + exc . getMessage ( ) + ". WILL RETRY." ) ; } } if ( tempTables . size ( ) == sizeBefore ) { throw new AssertionError ( "unable to clean tables " + tempTables ) ; } } } | Deletes all contents from the given tables . | 231 | 9 |
18,376 | private List < String > initCommand ( ) { List < String > command = new ArrayList < String > ( ) ; command . add ( cmd ) ; command . add ( "install" ) ; if ( acceptLicense ) { command . add ( "--acceptLicense" ) ; } else { command . add ( "--viewLicenseAgreement" ) ; } if ( to != null ) { command . add ( "--to=" + to ) ; } if ( from != null ) { command . add ( "--from=" + from ) ; } return command ; } | Generate a String list containing all the parameter for the command . | 119 | 13 |
18,377 | private < T extends XSString > T createXSString ( Class < T > clazz , String value ) { if ( value == null ) { return null ; } QName elementName = null ; String localName = null ; try { elementName = ( QName ) clazz . getDeclaredField ( "DEFAULT_ELEMENT_NAME" ) . get ( null ) ; localName = ( String ) clazz . getDeclaredField ( "DEFAULT_ELEMENT_LOCAL_NAME" ) . get ( null ) ; } catch ( NoSuchFieldException | IllegalArgumentException | IllegalAccessException | SecurityException e ) { throw new RuntimeException ( e ) ; } XMLObjectBuilder < ? extends XMLObject > builder = XMLObjectProviderRegistrySupport . getBuilderFactory ( ) . getBuilder ( elementName ) ; Object object = builder . buildObject ( new QName ( this . getElementQName ( ) . getNamespaceURI ( ) , localName , this . getElementQName ( ) . getPrefix ( ) ) ) ; T xsstring = clazz . cast ( object ) ; xsstring . setValue ( value ) ; return xsstring ; } | Utility method for creating an OpenSAML object given its type and assigns the value . | 256 | 18 |
18,378 | public Annotation [ ] getAnnotations ( ) { final Annotation [ ] accessibleObjectAnnotations = accessibleObject . getAnnotations ( ) ; final Annotation [ ] annotations = new Annotation [ accessibleObjectAnnotations . length + parameterAnnotations . length ] ; System . arraycopy ( accessibleObjectAnnotations , 0 , annotations , 0 , accessibleObjectAnnotations . length ) ; System . arraycopy ( parameterAnnotations , 0 , annotations , accessibleObjectAnnotations . length , parameterAnnotations . length ) ; return annotations ; } | Returns an array of all annotations present on the injection target . | 110 | 12 |
18,379 | public static final MetadataServiceListVersion valueOf ( final int majorVersion , final int minorVersion ) { if ( majorVersion == 1 && minorVersion == 0 ) { return MetadataServiceListVersion . VERSION_10 ; } return new MetadataServiceListVersion ( majorVersion , minorVersion ) ; } | Gets the version given the major and minor version number . | 64 | 12 |
18,380 | public static final MetadataServiceListVersion valueOf ( String version ) { String [ ] components = version . split ( "\\." ) ; return valueOf ( Integer . valueOf ( components [ 0 ] ) , Integer . valueOf ( components [ 1 ] ) ) ; } | Gets the version for a given version string such as 1 . 0 . | 57 | 15 |
18,381 | public static < T > InjectionProvider < T > providerForQualifiedInstance ( final Class < ? extends Annotation > qualifier , final T instance ) { return new QualifiedInstanceInjectionProvider < T > ( qualifier , instance ) ; } | InjectionProvider that provides a singleton instance of type T for every injection point that is annotated with the given qualifier . | 50 | 25 |
18,382 | private static Set < InjectionProvider < ? > > newProviderSet ( final InjectionProvider < ? > ... providers ) { final Set < InjectionProvider < ? > > result = new LinkedHashSet < InjectionProvider < ? > > ( ) ; if ( providers != null && providers . length > 0 ) { for ( final InjectionProvider < ? > provider : providers ) { result . add ( provider ) ; } } return result ; } | Creates a new Set . | 94 | 6 |
18,383 | private static InjectionProviderInstancesSupplier mergeSuppliers ( final InjectionProviderInstancesSupplier ... suppliers ) { final Set < InjectionProvider < ? > > result = new LinkedHashSet < InjectionProvider < ? > > ( ) ; if ( suppliers != null && suppliers . length > 0 ) { for ( final InjectionProviderInstancesSupplier supplier : suppliers ) { result . addAll ( supplier . get ( ) ) ; } } return new InjectionProviderInstancesSupplier ( ) { @ Override public Set < InjectionProvider < ? > > get ( ) { return result ; } } ; } | Creates new supplier containing all providers in a new set . | 132 | 12 |
18,384 | public static InjectionProvider < ? > [ ] providersForInstancesSuppliers ( final InjectionProviderInstancesSupplier ... suppliers ) { final InjectionProviderInstancesSupplier supplier = mergeSuppliers ( suppliers ) ; return supplier . get ( ) . toArray ( new InjectionProvider < ? > [ supplier . get ( ) . size ( ) ] ) ; } | Create array of providers from given suppliers . | 79 | 8 |
18,385 | public static InjectionProvider < ? > [ ] providersToArray ( final Collection < InjectionProvider < ? > > providers ) { return providers == null ? new InjectionProvider < ? > [ 0 ] : providers . toArray ( new InjectionProvider < ? > [ providers . size ( ) ] ) ; } | Create array of InjectionProviders for given collection . | 65 | 11 |
18,386 | public final < T > T saveObject ( final T obj ) throws Exception { return executeInTransaction ( new Runnable < T > ( ) { @ Override public T run ( final EntityManager entityManager ) { return persist ( obj , entityManager ) ; } } ) ; } | Saves the given object in the database . | 59 | 9 |
18,387 | public final < T > T loadObject ( final Class < T > clazz , final Object id ) throws Exception { return executeInTransaction ( new Runnable < T > ( ) { @ Override public T run ( final EntityManager entityManager ) { return loadObject ( entityManager , clazz , id ) ; } } ) ; } | Finds and returns the object of the given id in the persistence context . | 71 | 15 |
18,388 | public final < T > List < T > loadAllObjects ( final Class < T > clazz ) throws Exception { final Entity entityAnnotation = clazz . getAnnotation ( Entity . class ) ; if ( entityAnnotation == null ) { throw new IllegalArgumentException ( "Unknown entity: " + clazz . getName ( ) ) ; } return executeInTransaction ( new Runnable < List < T > > ( ) { @ Override @ SuppressWarnings ( "unchecked" ) public List < T > run ( final EntityManager entityManager ) { final String fromEntity = entityAnnotation . name ( ) . isEmpty ( ) ? clazz . getSimpleName ( ) : entityAnnotation . name ( ) ; final String alias = fromEntity . toLowerCase ( ) ; return entityManager . createQuery ( "SELECT " + alias + " FROM " + fromEntity + " " + alias ) . getResultList ( ) ; } } ) ; } | Returns all objects of the given class in persistence context . | 207 | 11 |
18,389 | @ Override public XMLObject unmarshall ( Element domElement ) throws UnmarshallingException { Document newDocument = null ; Node childNode = domElement . getFirstChild ( ) ; while ( childNode != null ) { if ( childNode . getNodeType ( ) != Node . TEXT_NODE ) { // We skip everything except for a text node. log . info ( "Ignoring node {} - it is not a text node" , childNode . getNodeName ( ) ) ; } else { newDocument = parseContents ( ( Text ) childNode , domElement ) ; if ( newDocument != null ) { break ; } } childNode = childNode . getNextSibling ( ) ; } return super . unmarshall ( newDocument != null ? newDocument . getDocumentElement ( ) : domElement ) ; } | Special handling of the Base64 encoded value that represents the address elements . | 176 | 14 |
18,390 | private static Map < String , String > getNamespaceBindings ( Element element ) { Map < String , String > namespaceMap = new HashMap < String , String > ( ) ; getNamespaceBindings ( element , namespaceMap ) ; return namespaceMap ; } | Returns a map holding all registered namespace bindings where the key is the qualified name of the namespace and the value part is the URI . | 55 | 26 |
18,391 | public String waitForStringInLog ( String regexp , long timeout , File outputFile ) { int waited = 0 ; final int waitIncrement = 500 ; log ( MessageFormat . format ( messages . getString ( "info.search.string" ) , regexp , outputFile . getAbsolutePath ( ) , timeout / 1000 ) ) ; try { while ( waited <= timeout ) { String string = findStringInFile ( regexp , outputFile ) ; if ( string == null ) { try { Thread . sleep ( waitIncrement ) ; } catch ( InterruptedException e ) { // Ignore and carry on } waited += waitIncrement ; } else { return string ; } } log ( MessageFormat . format ( messages . getString ( "error.serch.string.timeout" ) , regexp , outputFile . getAbsolutePath ( ) ) ) ; } catch ( Exception e ) { // I think we can assume if we can't read the file it doesn't // contain our string throw new BuildException ( e ) ; } return null ; } | Check for a number of strings in a potentially remote file | 223 | 11 |
18,392 | public void bootstrap ( ) throws ConfigurationException { XMLConfigurator configurator = new XMLConfigurator ( ) ; for ( String config : configs ) { log . debug ( "Loading XMLTooling configuration " + config ) ; configurator . load ( Configuration . class . getResourceAsStream ( config ) ) ; } } | Bootstrap method for this library . | 71 | 7 |
18,393 | public static InputStream loadResource ( final String resource ) throws FileNotFoundException { final boolean hasLeadingSlash = resource . startsWith ( "/" ) ; final String stripped = hasLeadingSlash ? resource . substring ( 1 ) : resource ; InputStream stream = null ; final ClassLoader classLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; if ( classLoader != null ) { stream = classLoader . getResourceAsStream ( resource ) ; if ( stream == null && hasLeadingSlash ) { stream = classLoader . getResourceAsStream ( stripped ) ; } } if ( stream == null ) { throw new FileNotFoundException ( "resource " + resource + " not found" ) ; } return stream ; } | Returns an input stream for reading the specified resource . | 160 | 10 |
18,394 | @ Override public OperationResult operate ( TestStep testStep ) { String testStepName = testStep . getLocator ( ) . getValue ( ) ; LogRecord log = LogRecord . info ( LOG , testStep , "script.execute" , testStepName ) ; current . backup ( ) ; TestScript testScript = dao . load ( new File ( pm . getPageScriptDir ( ) , testStepName ) , sheetName , false ) ; current . setTestScript ( testScript ) ; current . reset ( ) ; current . setCurrentIndex ( current . getCurrentIndex ( ) - 1 ) ; String caseNo = testStep . getValue ( ) ; if ( testScript . containsCaseNo ( caseNo ) ) { current . setCaseNo ( caseNo ) ; } else { String msg = MessageManager . getMessage ( "case.number.error" , caseNo ) + testScript . getCaseNoMap ( ) . keySet ( ) ; throw new TestException ( msg ) ; } current . setTestContextListener ( this ) ; return new OperationResult ( log ) ; } | OperationLog opelog ; | 233 | 6 |
18,395 | @ Override public OperationResult operate ( TestStep testStep ) { String value = testStep . getValue ( ) ; LogRecord record = LogRecord . info ( log , testStep , "test.step.execute" , value ) ; TestScript testScript = current . getTestScript ( ) ; int nextIndex = testScript . getIndexByScriptNo ( value ) - 1 ; current . setCurrentIndex ( nextIndex ) ; return new OperationResult ( record ) ; } | protected OperationLog opelog ; | 100 | 7 |
18,396 | private WMenu buildTreeMenu ( final WText selectedMenuText ) { WMenu menu = new WMenu ( WMenu . MenuType . TREE ) ; menu . setSelectMode ( SelectMode . SINGLE ) ; mapTreeHierarchy ( menu , createExampleHierarchy ( ) , selectedMenuText ) ; return menu ; } | Builds up a tree menu for inclusion in the example . | 72 | 12 |
18,397 | private void mapTreeHierarchy ( final WComponent currentComponent , final StringTreeNode currentNode , final WText selectedMenuText ) { if ( currentNode . isLeaf ( ) ) { WMenuItem menuItem = new WMenuItem ( currentNode . getData ( ) , new ExampleMenuAction ( selectedMenuText ) ) ; menuItem . setActionObject ( currentNode . getData ( ) ) ; if ( currentComponent instanceof WMenu ) { ( ( WMenu ) currentComponent ) . add ( menuItem ) ; } else { ( ( WSubMenu ) currentComponent ) . add ( menuItem ) ; } } else { WSubMenu subMenu = new WSubMenu ( currentNode . getData ( ) ) ; subMenu . setSelectMode ( SelectMode . SINGLE ) ; if ( currentComponent instanceof WMenu ) { ( ( WMenu ) currentComponent ) . add ( subMenu ) ; } else { ( ( WSubMenu ) currentComponent ) . add ( subMenu ) ; } // Expand the first couple of levels in the tree by default. if ( currentNode . getLevel ( ) < 2 ) { subMenu . setOpen ( true ) ; } for ( Iterator < TreeNode > i = currentNode . children ( ) ; i . hasNext ( ) ; ) { mapTreeHierarchy ( subMenu , ( StringTreeNode ) i . next ( ) , selectedMenuText ) ; } } } | Recursively maps a tree hierarchy to a hierarchical menu . | 305 | 12 |
18,398 | private static StringTreeNode createExampleHierarchy ( ) { StringTreeNode root = new StringTreeNode ( Object . class . getName ( ) ) ; Map < String , StringTreeNode > nodeMap = new HashMap <> ( ) ; nodeMap . put ( root . getData ( ) , root ) ; // The classes to show in the hierarchy Class < ? > [ ] classes = new Class [ ] { WMenu . class , WMenuItem . class , WSubMenu . class , WMenuItemGroup . class , WText . class , WText . class } ; for ( Class < ? > clazz : classes ) { StringTreeNode childNode = new StringTreeNode ( clazz . getName ( ) ) ; nodeMap . put ( childNode . getData ( ) , childNode ) ; for ( Class < ? > parentClass = clazz . getSuperclass ( ) ; parentClass != null ; parentClass = parentClass . getSuperclass ( ) ) { StringTreeNode parentNode = nodeMap . get ( parentClass . getName ( ) ) ; if ( parentNode == null ) { parentNode = new StringTreeNode ( parentClass . getName ( ) ) ; nodeMap . put ( parentNode . getData ( ) , parentNode ) ; parentNode . add ( childNode ) ; childNode = parentNode ; } else { parentNode . add ( childNode ) ; // already have this node hierarchy break ; } } } return root ; } | Creates an example hierarchy showing the WMenu API . | 312 | 11 |
18,399 | public void addTerm ( final String term , final WComponent ... data ) { for ( WComponent component : data ) { if ( component != null ) { content . add ( component , term ) ; } } // If the term doesn't exist, we may need to add a dummy component if ( getComponentsForTerm ( term ) . isEmpty ( ) ) { content . add ( new DefaultWComponent ( ) , term ) ; } } | Adds a term to this definition list . If there is an existing term the component is added to the list of data for the term . | 92 | 27 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.