idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
21,700
public Object parseIdRefElement ( Element ele ) { // A generic reference to any name of any bean. String refName = ele . getAttribute ( BEAN_REF_ATTRIBUTE ) ; if ( ! StringUtils . hasLength ( refName ) ) { // A reference to the id of another bean in the same XML file. refName = ele . getAttribute ( LOCAL_REF_ATTRIBUTE ) ; if ( ! StringUtils . hasLength ( refName ) ) { error ( "Either 'bean' or 'local' is required for <idref> element" , ele ) ; return null ; } } if ( ! StringUtils . hasText ( refName ) ) { error ( "<idref> element contains empty target attribute" , ele ) ; return null ; } RuntimeBeanNameReference ref = new RuntimeBeanNameReference ( refName ) ; ref . setSource ( extractSource ( ele ) ) ; return ref ; }
Return a typed String value Object for the given idref element .
204
13
21,701
public Object parseValueElement ( Element ele , String defaultTypeName ) { // It's a literal value. String value = DomUtils . getTextValue ( ele ) ; String specifiedTypeName = ele . getAttribute ( TYPE_ATTRIBUTE ) ; String typeName = specifiedTypeName ; if ( ! StringUtils . hasText ( typeName ) ) typeName = defaultTypeName ; try { TypedStringValue typedValue = buildTypedStringValue ( value , typeName ) ; typedValue . setSource ( extractSource ( ele ) ) ; typedValue . setSpecifiedTypeName ( specifiedTypeName ) ; return typedValue ; } catch ( ClassNotFoundException ex ) { error ( "Type class [" + typeName + "] not found for <value> element" , ele , ex ) ; return value ; } }
Return a typed String value Object for the given value element .
176
12
21,702
public Object parseArrayElement ( Element arrayEle , BeanDefinition bd ) { String elementType = arrayEle . getAttribute ( VALUE_TYPE_ATTRIBUTE ) ; NodeList nl = arrayEle . getChildNodes ( ) ; ManagedArray target = new ManagedArray ( elementType , nl . getLength ( ) ) ; target . setSource ( extractSource ( arrayEle ) ) ; target . setElementTypeName ( elementType ) ; target . setMergeEnabled ( parseMergeAttribute ( arrayEle ) ) ; parseCollectionElements ( nl , target , bd , elementType ) ; return target ; }
Parse an array element .
136
6
21,703
public List < Object > parseListElement ( Element collectionEle , BeanDefinition bd ) { String defaultElementType = collectionEle . getAttribute ( VALUE_TYPE_ATTRIBUTE ) ; NodeList nl = collectionEle . getChildNodes ( ) ; ManagedList < Object > target = new ManagedList < Object > ( nl . getLength ( ) ) ; target . setSource ( extractSource ( collectionEle ) ) ; target . setElementTypeName ( defaultElementType ) ; target . setMergeEnabled ( parseMergeAttribute ( collectionEle ) ) ; parseCollectionElements ( nl , target , bd , defaultElementType ) ; return target ; }
Parse a list element .
145
6
21,704
public Set < Object > parseSetElement ( Element collectionEle , BeanDefinition bd ) { String defaultElementType = collectionEle . getAttribute ( VALUE_TYPE_ATTRIBUTE ) ; NodeList nl = collectionEle . getChildNodes ( ) ; ManagedSet < Object > target = new ManagedSet < Object > ( nl . getLength ( ) ) ; target . setSource ( extractSource ( collectionEle ) ) ; target . setElementTypeName ( defaultElementType ) ; target . setMergeEnabled ( parseMergeAttribute ( collectionEle ) ) ; parseCollectionElements ( nl , target , bd , defaultElementType ) ; return target ; }
Parse a set element .
145
6
21,705
protected Object parseKeyElement ( Element keyEle , BeanDefinition bd , String defaultKeyTypeName ) { NodeList nl = keyEle . getChildNodes ( ) ; Element subElement = null ; for ( int i = 0 ; i < nl . getLength ( ) ; i ++ ) { Node node = nl . item ( i ) ; if ( node instanceof Element ) { // Child element is what we're looking for. if ( subElement != null ) error ( "<key> element must not contain more than one value sub-element" , keyEle ) ; else subElement = ( Element ) node ; } } return parsePropertySubElement ( subElement , bd , defaultKeyTypeName ) ; }
Parse a key sub - element of a map element .
152
12
21,706
public Properties parsePropsElement ( Element propsEle ) { ManagedProperties props = new ManagedProperties ( ) ; props . setSource ( extractSource ( propsEle ) ) ; props . setMergeEnabled ( parseMergeAttribute ( propsEle ) ) ; List < Element > propEles = DomUtils . getChildElementsByTagName ( propsEle , PROP_ELEMENT ) ; for ( Element propEle : propEles ) { String key = propEle . getAttribute ( KEY_ATTRIBUTE ) ; // Trim the text value to avoid unwanted whitespace // caused by typical XML formatting. String value = DomUtils . getTextValue ( propEle ) . trim ( ) ; TypedStringValue keyHolder = new TypedStringValue ( key ) ; keyHolder . setSource ( extractSource ( propEle ) ) ; TypedStringValue valueHolder = new TypedStringValue ( value ) ; valueHolder . setSource ( extractSource ( propEle ) ) ; props . put ( keyHolder , valueHolder ) ; } return props ; }
Parse a props element .
234
6
21,707
public boolean parseMergeAttribute ( Element collectionElement ) { String value = collectionElement . getAttribute ( MERGE_ATTRIBUTE ) ; return TRUE_VALUE . equals ( value ) ; }
Parse the merge attribute of a collection element if any .
41
12
21,708
public final void init ( FilterConfig filterConfig ) throws ServletException { Assert . notNull ( filterConfig , "FilterConfig must not be null" ) ; logger . debug ( "Initializing filter '{}'" , filterConfig . getFilterName ( ) ) ; this . filterConfig = filterConfig ; initParams ( filterConfig ) ; // Let subclasses do whatever initialization they like. initFilterBean ( ) ; logger . debug ( "Filter '{}' configured successfully" , filterConfig . getFilterName ( ) ) ; }
Standard way of initializing this filter . Map config parameters onto bean properties of this filter and invoke subclass initialization .
115
22
21,709
private Class < ? > getPropertyType ( PersistentClass pc , String propertyString ) { String [ ] properties = split ( propertyString , ' ' ) ; Property p = pc . getProperty ( properties [ 0 ] ) ; Component cp = ( ( Component ) p . getValue ( ) ) ; int i = 1 ; for ( ; i < properties . length ; i ++ ) { p = cp . getProperty ( properties [ i ] ) ; cp = ( ( Component ) p . getValue ( ) ) ; } return cp . getComponentClass ( ) ; }
get component class by component property string
118
7
21,710
protected final < T > T getId ( String name , Class < T > clazz ) { Object [ ] entityIds = getAll ( name + ".id" ) ; if ( Arrays . isEmpty ( entityIds ) ) entityIds = getAll ( name + "Id" ) ; if ( Arrays . isEmpty ( entityIds ) ) entityIds = getAll ( "id" ) ; if ( Arrays . isEmpty ( entityIds ) ) return null ; else { String entityId = entityIds [ 0 ] . toString ( ) ; int commaIndex = entityId . indexOf ( ' ' ) ; if ( commaIndex != - 1 ) entityId = entityId . substring ( 0 , commaIndex ) ; return Params . converter . convert ( entityId , clazz ) ; } }
Get entity s id from shortname . id shortnameId id
177
13
21,711
protected final < T > T [ ] getIds ( String name , Class < T > clazz ) { T [ ] datas = Params . getAll ( name + ".id" , clazz ) ; if ( null == datas ) { String datastring = Params . get ( name + ".ids" ) ; if ( null == datastring ) datastring = Params . get ( name + "Ids" ) ; if ( null == datastring ) Array . newInstance ( clazz , 0 ) ; else return Params . converter . convert ( Strings . split ( datastring , "," ) , clazz ) ; } return datas ; }
Get entity s id array from parameters shortname . id shortname . ids shortnameIds
143
20
21,712
@ Override public void evict ( K key ) { Object existed = store . getIfPresent ( key ) ; if ( null != existed ) store . invalidate ( key ) ; }
Evict specified key
38
4
21,713
public String constructLocalLoginServiceUrl ( final HttpServletRequest request , final HttpServletResponse response , final String service , final String serverName , final String artifactParameterName , final boolean encode ) { if ( Strings . isNotBlank ( service ) ) return encode ? response . encodeURL ( service ) : service ; final StringBuilder buffer = new StringBuilder ( ) ; if ( ! serverName . startsWith ( "https://" ) && ! serverName . startsWith ( "http://" ) ) { buffer . append ( request . isSecure ( ) ? "https://" : "http://" ) ; } buffer . append ( serverName ) ; buffer . append ( request . getContextPath ( ) ) ; buffer . append ( localLogin ) ; final String returnValue = encode ? response . encodeURL ( buffer . toString ( ) ) : buffer . toString ( ) ; return returnValue ; }
Construct local login Service Url
194
6
21,714
public String constructServiceUrl ( final HttpServletRequest request , final HttpServletResponse response , final String service , final String serverName ) { if ( Strings . isNotBlank ( service ) ) { return response . encodeURL ( service ) ; } final StringBuilder buffer = new StringBuilder ( ) ; if ( ! serverName . startsWith ( "https://" ) && ! serverName . startsWith ( "http://" ) ) { buffer . append ( request . isSecure ( ) ? "https://" : "http://" ) ; } buffer . append ( serverName ) ; buffer . append ( request . getRequestURI ( ) ) ; Set < String > reservedKeys = CollectUtils . newHashSet ( ) ; reservedKeys . add ( config . getArtifactName ( ) ) ; if ( null != sessionIdReader ) { reservedKeys . add ( sessionIdReader . idName ( ) ) ; } String queryString = request . getQueryString ( ) ; if ( Strings . isNotBlank ( queryString ) ) { String [ ] parts = Strings . split ( queryString , "&" ) ; Arrays . sort ( parts ) ; StringBuilder paramBuf = new StringBuilder ( ) ; for ( String part : parts ) { int equIdx = part . indexOf ( ' ' ) ; if ( equIdx > 0 ) { String key = part . substring ( 0 , equIdx ) ; if ( ! reservedKeys . contains ( key ) ) { paramBuf . append ( ' ' ) . append ( key ) . append ( part . substring ( equIdx ) ) ; } } } if ( paramBuf . length ( ) > 0 ) { paramBuf . setCharAt ( 0 , ' ' ) ; buffer . append ( paramBuf ) ; } } return response . encodeURL ( buffer . toString ( ) ) ; }
Constructs a service url from the HttpServletRequest or from the given serviceUrl . Prefers the serviceUrl provided if both a serviceUrl and a serviceName .
404
35
21,715
public String constructRedirectUrl ( final String casServerLoginUrl , final String serviceParameterName , final String serviceUrl , final boolean renew , final boolean gateway ) { try { return casServerLoginUrl + ( casServerLoginUrl . indexOf ( "?" ) != - 1 ? "&" : "?" ) + serviceParameterName + "=" + URLEncoder . encode ( serviceUrl , "UTF-8" ) + ( renew ? "&renew=true" : "" ) + ( gateway ? "&gateway=true" : "" ) + "&" + SessionIdReader . SessionIdName + "=" + sessionIdReader . idName ( ) ; } catch ( final UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } }
Constructs the URL to use to redirect to the CAS server .
164
13
21,716
@ Override public Resource createRelative ( String relativePath ) { String pathToUse = StringUtils . applyRelativePath ( this . path , relativePath ) ; return new ServletContextResource ( this . servletContext , pathToUse ) ; }
This implementation creates a ServletContextResource applying the given path relative to the path of the underlying file of this resource descriptor .
55
25
21,717
public static byte [ ] join ( List < byte [ ] > arrays ) { int maxlength = 0 ; for ( byte [ ] array : arrays ) { maxlength += array . length ; } byte [ ] rs = new byte [ maxlength ] ; int pos = 0 ; for ( byte [ ] array : arrays ) { System . arraycopy ( array , 0 , rs , pos , array . length ) ; pos += array . length ; } return rs ; }
join multi array
96
3
21,718
public ActionMapping getMapping ( HttpServletRequest request , ConfigurationManager configManager ) { ActionMapping mapping = new ActionMapping ( ) ; parseNameAndNamespace ( RequestUtils . getServletPath ( request ) , mapping ) ; String method = request . getParameter ( MethodParam ) ; if ( Strings . isNotEmpty ( method ) ) mapping . setMethod ( method ) ; return mapping ; }
reserved method parameter
90
4
21,719
public String encode ( String value ) { if ( value == null ) { return null ; } StringBuilder buffer = new StringBuilder ( ) ; buffer . append ( Prefix ) ; buffer . append ( charset ) ; buffer . append ( Sep ) ; buffer . append ( getEncoding ( ) ) ; buffer . append ( Sep ) ; buffer . append ( new String ( Base64 . encode ( value . getBytes ( charset ) ) ) ) ; buffer . append ( Postfix ) ; return buffer . toString ( ) ; }
Encodes a string into its Base64 form using the default charset . Unsafe characters are escaped .
111
21
21,720
public String decode ( String text ) { if ( text == null ) { return null ; } if ( ( ! text . startsWith ( Prefix ) ) || ( ! text . endsWith ( Postfix ) ) ) throw new IllegalArgumentException ( "RFC 1522 violation: malformed encoded content" ) ; int terminator = text . length ( ) - 2 ; int from = 2 ; int to = text . indexOf ( Sep , from ) ; if ( to == terminator ) throw new IllegalArgumentException ( "RFC 1522 violation: charset token not found" ) ; String charset = text . substring ( from , to ) ; if ( charset . equals ( "" ) ) throw new IllegalArgumentException ( "RFC 1522 violation: charset not specified" ) ; from = to + 1 ; to = text . indexOf ( Sep , from ) ; if ( to == terminator ) throw new IllegalArgumentException ( "RFC 1522 violation: encoding token not found" ) ; String encoding = text . substring ( from , to ) ; if ( ! getEncoding ( ) . equalsIgnoreCase ( encoding ) ) throw new IllegalArgumentException ( "This codec cannot decode " + encoding + " encoded content" ) ; from = to + 1 ; to = text . indexOf ( Sep , from ) ; return new String ( Base64 . decode ( text . substring ( from , to ) . toCharArray ( ) ) , Charset . forName ( charset ) ) ; }
Decodes a Base64 string into its original form . Escaped characters are converted back to their original representation .
321
22
21,721
public static Cookie getCookie ( HttpServletRequest request , String name ) { Cookie [ ] cookies = request . getCookies ( ) ; Cookie returnCookie = null ; if ( cookies == null ) { return returnCookie ; } for ( int i = 0 ; i < cookies . length ; i ++ ) { Cookie thisCookie = cookies [ i ] ; if ( thisCookie . getName ( ) . equals ( name ) && ! thisCookie . getValue ( ) . equals ( "" ) ) { returnCookie = thisCookie ; break ; } } return returnCookie ; }
Convenience method to get a cookie by name
128
10
21,722
public static void deleteCookie ( HttpServletResponse response , Cookie cookie , String path ) { if ( cookie != null ) { // Delete the cookie by setting its maximum age to zero cookie . setMaxAge ( 0 ) ; cookie . setPath ( path ) ; response . addCookie ( cookie ) ; } }
Convenience method for deleting a cookie by name
67
10
21,723
private long lastModified ( URL url ) { if ( url . getProtocol ( ) . equals ( "file" ) ) { return new File ( url . getFile ( ) ) . lastModified ( ) ; } else { try { URLConnection conn = url . openConnection ( ) ; if ( conn instanceof JarURLConnection ) { URL jarURL = ( ( JarURLConnection ) conn ) . getJarFileURL ( ) ; if ( jarURL . getProtocol ( ) . equals ( "file" ) ) { return new File ( jarURL . getFile ( ) ) . lastModified ( ) ; } } } catch ( IOException e1 ) { return - 1 ; } return - 1 ; } }
Return url s last modified date time . saves some opening and closing
152
13
21,724
protected String processLabel ( String label , String name ) { if ( null != label ) { if ( Strings . isEmpty ( label ) ) return null ; else return getText ( label ) ; } else return getText ( name ) ; }
Process label convert empty to null
51
6
21,725
public String edit ( ) { Entity < ? > entity = getEntity ( ) ; put ( getShortName ( ) , entity ) ; editSetting ( entity ) ; return forward ( ) ; }
Edit by entity . id or id
40
7
21,726
private int findIndexOfFrom ( String query ) { if ( query . startsWith ( "from" ) ) return 0 ; int fromIdx = query . indexOf ( " from " ) ; if ( - 1 == fromIdx ) return - 1 ; final int first = query . substring ( 0 , fromIdx ) . indexOf ( "(" ) ; if ( first > 0 ) { int leftCnt = 1 ; int i = first + 1 ; while ( leftCnt != 0 && i < query . length ( ) ) { if ( query . charAt ( i ) == ' ' ) leftCnt ++ ; else if ( query . charAt ( i ) == ' ' ) leftCnt -- ; i ++ ; } if ( leftCnt > 0 ) return - 1 ; else { fromIdx = query . indexOf ( " from " , i ) ; return ( fromIdx == - 1 ) ? - 1 : fromIdx + 1 ; } } else { return fromIdx + 1 ; } }
Find index of from
218
4
21,727
private TraversableCodeGenStrategy getTraversableStrategy ( JType rawType , Map < String , JClass > directClasses ) { if ( rawType . isPrimitive ( ) ) { // primitive types are never traversable return TraversableCodeGenStrategy . NO ; } JClass clazz = ( JClass ) rawType ; if ( clazz . isParameterized ( ) ) { // if it's a parameterized type, then we should use the parameter clazz = clazz . getTypeParameters ( ) . get ( 0 ) ; if ( clazz . name ( ) . startsWith ( "?" ) ) { // when we have a wildcard we should use the bounding class. clazz = clazz . _extends ( ) ; } } String name = clazz . fullName ( ) ; if ( name . equals ( "java.lang.Object" ) ) { // it could be anything so we'll test with an instanceof in the generated code return TraversableCodeGenStrategy . MAYBE ; } else if ( clazz . isInterface ( ) ) { // if it is an interface (like Serializable) it could also be anything // handle it like java.lang.Object return TraversableCodeGenStrategy . MAYBE ; } else if ( visitable . isAssignableFrom ( clazz ) ) { // it's a real type. if it's one of ours, then it'll be assignable from Visitable return TraversableCodeGenStrategy . VISITABLE ; } else if ( directClasses . containsKey ( name ) ) { return TraversableCodeGenStrategy . DIRECT ; } else { return TraversableCodeGenStrategy . NO ; } }
Tests to see if the rawType is traversable
367
11
21,728
public static Os parse ( String agentString ) { if ( Strings . isEmpty ( agentString ) ) { return Os . UNKNOWN ; } for ( OsCategory category : OsCategory . values ( ) ) { String version = category . match ( agentString ) ; if ( version != null ) { String key = category . getName ( ) + "/" + version ; Os os = osMap . get ( key ) ; if ( null == os ) { os = new Os ( category , version ) ; osMap . put ( key , os ) ; } return os ; } } return Os . UNKNOWN ; }
Parses user agent string and returns the best match . Returns Os . UNKNOWN if there is no match .
128
23
21,729
private Template getTemplate ( String templateName ) throws ParseException { try { return config . getTemplate ( templateName , "UTF-8" ) ; } catch ( ParseException e ) { throw e ; } catch ( IOException e ) { logger . error ( "Couldn't load template '{}',loader is {}" , templateName , config . getTemplateLoader ( ) . getClass ( ) ) ; throw Throwables . propagate ( e ) ; } }
Load template in hierarchical path
99
5
21,730
@ SuppressWarnings ( "unchecked" ) public < T extends R > Converter < S , T > getConverter ( Class < T > targetType ) { return ( Converter < S , T > ) converters . get ( targetType ) ; }
Return convert from S to T
58
6
21,731
public int getIndex ( String expression ) { if ( expression == null || expression . length ( ) == 0 ) { return - 1 ; } for ( int i = 0 ; i < expression . length ( ) ; i ++ ) { char c = expression . charAt ( i ) ; if ( c == Nested || c == MappedStart ) { return - 1 ; } else if ( c == IndexedStart ) { int end = expression . indexOf ( IndexedEnd , i ) ; if ( end < 0 ) { throw new IllegalArgumentException ( "Missing End Delimiter" ) ; } String value = expression . substring ( i + 1 , end ) ; if ( value . length ( ) == 0 ) { throw new IllegalArgumentException ( "No Index Value" ) ; } int index = 0 ; try { index = Integer . parseInt ( value , 10 ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( "Invalid index value '" + value + "'" ) ; } return index ; } } return - 1 ; }
Return the index value from the property expression or - 1 .
225
12
21,732
public String getProperty ( String expression ) { if ( expression == null || expression . length ( ) == 0 ) { return expression ; } for ( int i = 0 ; i < expression . length ( ) ; i ++ ) { char c = expression . charAt ( i ) ; if ( c == Nested ) { return expression . substring ( 0 , i ) ; } else if ( c == MappedStart || c == IndexedStart ) { return expression . substring ( 0 , i ) ; } } return expression ; }
Return the property name from the property expression .
111
9
21,733
public boolean hasNested ( String expression ) { if ( expression == null || expression . length ( ) == 0 ) return false ; else return remove ( expression ) != null ; }
Indicates whether or not the expression contains nested property expressions or not .
37
14
21,734
public boolean isIndexed ( String expression ) { if ( expression == null || expression . length ( ) == 0 ) { return false ; } for ( int i = 0 ; i < expression . length ( ) ; i ++ ) { char c = expression . charAt ( i ) ; if ( c == Nested || c == MappedStart ) { return false ; } else if ( c == IndexedStart ) { return true ; } } return false ; }
Indicate whether the expression is for an indexed property or not .
96
13
21,735
public String next ( String expression ) { if ( expression == null || expression . length ( ) == 0 ) { return null ; } boolean indexed = false ; boolean mapped = false ; for ( int i = 0 ; i < expression . length ( ) ; i ++ ) { char c = expression . charAt ( i ) ; if ( indexed ) { if ( c == IndexedEnd ) { return expression . substring ( 0 , i + 1 ) ; } } else if ( mapped ) { if ( c == MappedEnd ) { return expression . substring ( 0 , i + 1 ) ; } } else { if ( c == Nested ) { return expression . substring ( 0 , i ) ; } else if ( c == MappedStart ) { mapped = true ; } else if ( c == IndexedStart ) { indexed = true ; } } } return expression ; }
Extract the next property expression from the current expression .
184
11
21,736
public String remove ( String expression ) { if ( expression == null || expression . length ( ) == 0 ) { return null ; } String property = next ( expression ) ; if ( expression . length ( ) == property . length ( ) ) { return null ; } int start = property . length ( ) ; if ( expression . charAt ( start ) == Nested ) start ++ ; return expression . substring ( start ) ; }
Remove the last property expresson from the current expression .
89
11
21,737
public void initFrom ( SessionFactory sessionFactory ) { Assert . notNull ( sessionFactory ) ; Stopwatch watch = new Stopwatch ( ) . start ( ) ; Map < String , ClassMetadata > classMetadatas = sessionFactory . getAllClassMetadata ( ) ; int entityCount = entityTypes . size ( ) ; int collectionCount = collectionTypes . size ( ) ; for ( Iterator < ClassMetadata > iter = classMetadatas . values ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { ClassMetadata cm = ( ClassMetadata ) iter . next ( ) ; buildEntityType ( sessionFactory , cm . getEntityName ( ) ) ; } logger . info ( "Find {} entities,{} collections from hibernate in {}" , new Object [ ] { entityTypes . size ( ) - entityCount , collectionTypes . size ( ) - collectionCount , watch } ) ; if ( logger . isDebugEnabled ( ) ) loggerTypeInfo ( ) ; collectionTypes . clear ( ) ; }
Build context from session factory
222
5
21,738
public Object put ( Object key , Object value ) { return next . put ( key , value ) ; }
put value to next
22
4
21,739
public static int count ( final String host , final char charactor ) { int count = 0 ; for ( int i = 0 ; i < host . length ( ) ; i ++ ) { if ( host . charAt ( i ) == charactor ) { count ++ ; } } return count ; }
count char in host string
62
5
21,740
public static int count ( final String host , final String searchStr ) { int count = 0 ; for ( int startIndex = 0 ; startIndex < host . length ( ) ; startIndex ++ ) { int findLoc = host . indexOf ( searchStr , startIndex ) ; if ( findLoc == - 1 ) { break ; } else { count ++ ; startIndex = findLoc + searchStr . length ( ) - 1 ; } } return count ; }
count inner string in host string
96
6
21,741
protected static String getFileName ( String file_name ) { if ( file_name == null ) return "" ; file_name = file_name . trim ( ) ; int iPos = 0 ; iPos = file_name . lastIndexOf ( "\\" ) ; if ( iPos > - 1 ) file_name = file_name . substring ( iPos + 1 ) ; iPos = file_name . lastIndexOf ( "/" ) ; if ( iPos > - 1 ) file_name = file_name . substring ( iPos + 1 ) ; iPos = file_name . lastIndexOf ( File . separator ) ; if ( iPos > - 1 ) file_name = file_name . substring ( iPos + 1 ) ; return file_name ; }
Returns the file name by path .
171
7
21,742
public boolean isMultiSchema ( ) { Set < String > schemas = CollectUtils . newHashSet ( ) ; for ( TableNamePattern pattern : patterns ) { schemas . add ( ( null == pattern . getSchema ( ) ) ? "" : pattern . getSchema ( ) ) ; } return schemas . size ( ) > 1 ; }
is Multiple schema for entity
76
5
21,743
public static void setActive ( boolean active ) { if ( active ) System . setProperty ( ACTIVATE_PROPERTY , "true" ) ; else System . clearProperty ( ACTIVATE_PROPERTY ) ; TimerTrace . active = active ; }
Turn profiling on or off .
57
6
21,744
public void findStaticResource ( String path , HttpServletRequest request , HttpServletResponse response ) throws IOException { processor . process ( cleanupPath ( path ) , request , response ) ; }
Locate a static resource and copy directly to the response setting the appropriate caching headers .
43
17
21,745
public List < String > getBeanNames ( Class < ? > type ) { if ( typeNames . containsKey ( type ) ) { return typeNames . get ( type ) ; } List < String > names = CollectUtils . newArrayList ( ) ; for ( Map . Entry < String , Class < ? > > entry : nameTypes . entrySet ( ) ) { if ( type . isAssignableFrom ( entry . getValue ( ) ) ) { names . add ( entry . getKey ( ) ) ; } } typeNames . put ( type , names ) ; return names ; }
Get bean name list according given type
126
7
21,746
public ObjectAndType initProperty ( final Object target , Type type , final String attr ) { Object propObj = target ; Object property = null ; int index = 0 ; String [ ] attrs = Strings . split ( attr , "." ) ; while ( index < attrs . length ) { try { property = getProperty ( propObj , attrs [ index ] ) ; Type propertyType = null ; if ( attrs [ index ] . contains ( "[" ) && null != property ) { propertyType = new IdentifierType ( property . getClass ( ) ) ; } else { propertyType = type . getPropertyType ( attrs [ index ] ) ; if ( null == propertyType ) { logger . error ( "Cannot find property type [{}] of {}" , attrs [ index ] , propObj . getClass ( ) ) ; throw new RuntimeException ( "Cannot find property type " + attrs [ index ] + " of " + propObj . getClass ( ) . getName ( ) ) ; } } if ( null == property ) { property = propertyType . newInstance ( ) ; setProperty ( propObj , attrs [ index ] , property ) ; } index ++ ; propObj = property ; type = propertyType ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } return new ObjectAndType ( property , type ) ; }
Initialize target s attribuate path Return the last property value and type .
296
16
21,747
public static Browser parse ( final String agentString ) { if ( Strings . isEmpty ( agentString ) ) { return Browser . UNKNOWN ; } // first consider engine for ( Engine engine : Engine . values ( ) ) { String egineName = engine . name ; if ( agentString . contains ( egineName ) ) { for ( BrowserCategory category : engine . browserCategories ) { String version = category . match ( agentString ) ; if ( version != null ) { String key = category . getName ( ) + "/" + version ; Browser browser = browsers . get ( key ) ; if ( null == browser ) { browser = new Browser ( category , version ) ; browsers . put ( key , browser ) ; } return browser ; } } } } // for some usagent without suitable enginename; for ( BrowserCategory category : BrowserCategory . values ( ) ) { String version = category . match ( agentString ) ; if ( version != null ) { String key = category . getName ( ) + "/" + version ; Browser browser = browsers . get ( key ) ; if ( null == browser ) { browser = new Browser ( category , version ) ; browsers . put ( key , browser ) ; } return browser ; } } return Browser . UNKNOWN ; }
Iterates over all Browsers to compare the browser signature with the user agent string . If no match can be found Browser . UNKNOWN will be returned .
266
32
21,748
public boolean requireScreenshot ( final ExtendedSeleniumCommand command , boolean result ) { return ( ! command . isAssertCommand ( ) && ! command . isVerifyCommand ( ) && ! command . isWaitForCommand ( ) && screenshotPolicy == ScreenshotPolicy . STEP ) || ( ! result && ( screenshotPolicy == ScreenshotPolicy . FAILURE || ( command . isAssertCommand ( ) && screenshotPolicy == ScreenshotPolicy . ASSERTION ) ) ) ; }
Is a screenshot desired based on the command and the test result .
99
13
21,749
private void setTimeoutOnSelenium ( ) { executeCommand ( "setTimeout" , new String [ ] { "" + this . timeout } ) ; WebDriver . Timeouts timeouts = getWebDriver ( ) . manage ( ) . timeouts ( ) ; timeouts . setScriptTimeout ( this . timeout , TimeUnit . MILLISECONDS ) ; timeouts . pageLoadTimeout ( this . timeout , TimeUnit . MILLISECONDS ) ; }
Set the default timeout on the selenium instance .
97
11
21,750
public void addAliasForLocator ( String alias , String locator ) { LOG . info ( "Add alias: '" + alias + "' for '" + locator + "'" ) ; aliases . put ( alias , locator ) ; }
Add a new locator alias to the fixture .
52
10
21,751
public void startSeleniumServer ( final String args ) { if ( seleniumProxy != null ) { throw new IllegalStateException ( "There is already a Selenium remote server running" ) ; } try { final RemoteControlConfiguration configuration ; LOG . info ( "Starting server with arguments: '" + args + "'" ) ; //String[] argv = StringUtils.isNotBlank(args) ? StringUtils.split(args) : new String[] {}; String [ ] argv = StringUtils . split ( args ) ; configuration = SeleniumServer . parseLauncherOptions ( argv ) ; //checkArgsSanity(configuration); System . setProperty ( "org.openqa.jetty.http.HttpRequest.maxFormContentSize" , "0" ) ; // default max is 200k; zero is infinite seleniumProxy = new SeleniumServer ( isSlowConnection ( ) , configuration ) ; seleniumProxy . start ( ) ; } catch ( Exception e ) { //server.stop(); LOG . info ( "Server stopped" ) ; } }
Start server with arguments .
232
5
21,752
private Transactional readAnnotation ( MethodInvocation invocation ) { final Method method = invocation . getMethod ( ) ; if ( method . isAnnotationPresent ( Transactional . class ) ) { return method . getAnnotation ( Transactional . class ) ; } else { throw new RuntimeException ( "Could not find Transactional annotation" ) ; } }
Read the Transactional annotation for a given method invocation
77
11
21,753
private final void complete ( Transaction tx , boolean readOnly ) { if ( log . isTraceEnabled ( ) ) log . trace ( "Complete " + tx ) ; if ( ! readOnly ) tx . commit ( ) ; else tx . rollback ( ) ; }
Complete the transaction
56
3
21,754
private Connection getConnection ( final ICommandLine cl ) throws SQLException , InstantiationException , IllegalAccessException , ClassNotFoundException { String database = DEFAULT_TABLE ; if ( cl . hasOption ( "database" ) ) { database = cl . getOptionValue ( "database" ) ; } String hostname = DEFAULT_HOSTNAME ; if ( cl . hasOption ( "hostname" ) && ! "" . equals ( cl . getOptionValue ( "hostname" ) ) ) { hostname = cl . getOptionValue ( "hostname" ) ; } String port = DEFAULT_PORT ; if ( cl . hasOption ( "port" ) && ! "" . equals ( cl . getOptionValue ( "port" ) ) ) { port = cl . getOptionValue ( "port" ) ; } String password = "" ; if ( cl . hasOption ( "password" ) ) { password = cl . getOptionValue ( "password" ) ; } String username = "" ; if ( cl . hasOption ( "logname" ) ) { username = cl . getOptionValue ( "logname" ) ; } String timeout = DEFAULT_TIMEOUT ; if ( cl . getOptionValue ( "timeout" ) != null ) { timeout = cl . getOptionValue ( "timeout" ) ; } Properties props = new Properties ( ) ; props . setProperty ( "user" , username ) ; props . setProperty ( "password" , password ) ; props . setProperty ( "timeout" , timeout ) ; String url = "jdbc:postgresql://" + hostname + ":" + port + "/" + database ; DriverManager . registerDriver ( ( Driver ) Class . forName ( "org.postgresql.Driver" ) . newInstance ( ) ) ; return DriverManager . getConnection ( url , props ) ; }
Connect to the server .
398
5
21,755
protected void configureThresholdEvaluatorBuilder ( final ThresholdsEvaluatorBuilder thrb , final ICommandLine cl ) throws BadThresholdException { if ( cl . hasOption ( "th" ) ) { for ( Object obj : cl . getOptionValues ( "th" ) ) { thrb . withThreshold ( obj . toString ( ) ) ; } } }
Override this method if you don t use the new threshold syntax . Here you must tell the threshold evaluator all the threshold it must be able to evaluate . Give a look at the source of the CheckOracle plugin for an example of a plugin that supports both old and new syntax .
83
57
21,756
private boolean evaluate ( final Metric metric , final Prefixes prefix ) { if ( metric == null || metric . getMetricValue ( ) == null ) { throw new NullPointerException ( "Value can't be null" ) ; } BigDecimal value = metric . getMetricValue ( prefix ) ; if ( ! isNegativeInfinity ( ) ) { switch ( value . compareTo ( getLeftBoundary ( ) ) ) { case 0 : if ( ! isLeftInclusive ( ) ) { return false ; } break ; case - 1 : return false ; default : } } if ( ! isPositiveInfinity ( ) ) { switch ( value . compareTo ( getRightBoundary ( ) ) ) { case 0 : if ( ! isRightInclusive ( ) ) { return false ; } break ; case 1 : return false ; default : } } return true ; }
Evaluates if the passed in value falls inside the range . The negation is ignored .
186
19
21,757
public final ReturnValue execute ( final ICommandLine cl ) { File fProcessFile = new File ( cl . getOptionValue ( "executable" ) ) ; StreamManager streamMgr = new StreamManager ( ) ; if ( ! fProcessFile . exists ( ) ) { return new ReturnValue ( Status . UNKNOWN , "Could not exec executable : " + fProcessFile . getAbsolutePath ( ) ) ; } try { String [ ] vsParams = StringUtils . split ( cl . getOptionValue ( "args" , "" ) , false ) ; String [ ] vCommand = new String [ vsParams . length + 1 ] ; vCommand [ 0 ] = cl . getOptionValue ( "executable" ) ; System . arraycopy ( vsParams , 0 , vCommand , 1 , vsParams . length ) ; Process p = Runtime . getRuntime ( ) . exec ( vCommand ) ; BufferedReader br = ( BufferedReader ) streamMgr . handle ( new BufferedReader ( new InputStreamReader ( p . getInputStream ( ) ) ) ) ; StringBuilder msg = new StringBuilder ( ) ; for ( String line = br . readLine ( ) ; line != null ; line = br . readLine ( ) ) { if ( msg . length ( ) != 0 ) { msg . append ( System . lineSeparator ( ) ) ; } msg . append ( line ) ; } int iReturnCode = p . waitFor ( ) ; return new ReturnValue ( Status . fromIntValue ( iReturnCode ) , msg . toString ( ) ) ; } catch ( Exception e ) { String message = e . getMessage ( ) ; LOG . warn ( getContext ( ) , "Error executing the native plugin : " + message , e ) ; return new ReturnValue ( Status . UNKNOWN , "Could not exec executable : " + fProcessFile . getName ( ) + " - ERROR : " + message ) ; } finally { streamMgr . closeAll ( ) ; } }
The first parameter must be the full path to the executable .
428
12
21,758
public static void configureFiles ( Iterable < File > files ) { for ( File file : files ) { if ( file != null && file . exists ( ) && file . canRead ( ) ) { setup ( file ) ; return ; } } System . out . println ( "(No suitable log config file found)" ) ; }
Configures the logging environment to use the first available config file in the list printing an error if none of the files are suitable
68
25
21,759
public Set < CommandDefinition > getAllCommandDefinition ( final String pluginName ) { Set < CommandDefinition > res = new HashSet < CommandDefinition > ( ) ; for ( CommandDefinition cd : commandDefinitionsMap . values ( ) ) { if ( cd . getPluginName ( ) . equals ( pluginName ) ) { res . add ( cd ) ; } } return res ; }
Returns all the command definition that involves the given plugin .
80
11
21,760
public synchronized void initialiseFromAPIToken ( final String token ) { final String responseStr = authService . getToken ( UserManagerOAuthService . GRANT_TYPE_TOKEN_EXCHANGE , null , getOwnCallbackUri ( ) . toString ( ) , clientId , clientSecret , null , null , null , token ) ; loadAuthResponse ( responseStr ) ; }
Initialise this session reference by exchanging an API token for an access_token and refresh_token
83
19
21,761
public URI getOwnCallbackUri ( ) { String localEndpointStr = ( oauthSelfEndpoint != null ) ? oauthSelfEndpoint : localEndpoint . toString ( ) ; if ( ! localEndpointStr . endsWith ( "/" ) ) localEndpointStr += "/" ; return URI . create ( localEndpointStr + "oauth2/client/cb" ) ; }
Return the URI for this service s callback resource
86
9
21,762
public URI getAuthFlowStartEndpoint ( final String returnTo , final String scope ) { final String oauthServiceRoot = ( oauthServiceRedirectEndpoint != null ) ? oauthServiceRedirectEndpoint : oauthServiceEndpoint ; final String endpoint = oauthServiceRoot + "/oauth2/authorize" ; UriBuilder builder = UriBuilder . fromUri ( endpoint ) ; builder . replaceQueryParam ( "response_type" , "code" ) ; builder . replaceQueryParam ( "client_id" , clientId ) ; builder . replaceQueryParam ( "redirect_uri" , getOwnCallbackUri ( ) ) ; if ( scope != null ) builder . replaceQueryParam ( "scope" , scope ) ; if ( returnTo != null ) builder . replaceQueryParam ( "state" , encodeState ( callbackNonce + " " + returnTo ) ) ; return builder . build ( ) ; }
Get the endpoint to redirect a client to in order to start an OAuth2 Authorisation Flow
198
19
21,763
public URI getRedirectToFromState ( final String state ) { final String [ ] pieces = decodeState ( state ) . split ( " " , 2 ) ; if ( ! StringUtils . equals ( callbackNonce , pieces [ 0 ] ) ) { // The callback nonce is not what we expect; this is usually caused by: // - The user has followed a previous oauth callback entry from their history // - The user has accessed a service via a non-canonical endpoint and been redirected by the oauth server to the canonical one // which means the original nonce stored in the session is not available to this session. // To get around this, we simply redirect the user to the root of this service so they can start the oauth flow again throw new LiteralRestResponseException ( Response . seeOther ( URI . create ( "/" ) ) . build ( ) ) ; } if ( pieces . length == 2 ) return URI . create ( pieces [ 1 ] ) ; else return null ; }
Decode the state to retrieve the redirectTo value
209
10
21,764
public synchronized void refreshToken ( ) { final String refreshToken = this . response . refresh_token ; this . response = null ; this . cachedInfo = null ; final String responseStr = authService . getToken ( UserManagerOAuthService . GRANT_TYPE_REFRESH_TOKEN , null , null , clientId , clientSecret , refreshToken , null , null , null ) ; loadAuthResponse ( responseStr ) ; }
Use the refresh token to get a new token with a longer lifespan
92
13
21,765
public static void loadFromXmlPluginPackageDefinitions ( final IPluginRepository repo , final ClassLoader cl , final InputStream in ) throws PluginConfigurationException { for ( PluginDefinition pd : loadFromXmlPluginPackageDefinitions ( cl , in ) ) { repo . addPluginDefinition ( pd ) ; } }
Loads a full repository definition from an XML file .
68
11
21,766
@ SuppressWarnings ( "unchecked" ) public static Collection < PluginDefinition > loadFromXmlPluginPackageDefinitions ( final ClassLoader cl , final InputStream in ) throws PluginConfigurationException { List < PluginDefinition > res = new ArrayList < PluginDefinition > ( ) ; DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; Document document ; try { DocumentBuilder loader = factory . newDocumentBuilder ( ) ; DOMReader reader = new DOMReader ( ) ; document = reader . read ( loader . parse ( in ) ) ; } catch ( Exception e ) { throw new PluginConfigurationException ( e . getMessage ( ) , e ) ; } Element plugins = document . getRootElement ( ) ; // TODO : validate against schema // iterate through child elements of root for ( Iterator < Element > i = plugins . elementIterator ( ) ; i . hasNext ( ) ; ) { res . add ( parsePluginDefinition ( cl , i . next ( ) ) ) ; } return res ; }
Loads the plugins definitions from the jnrpe_plugins . xml file .
213
16
21,767
public static PluginDefinition parseXmlPluginDefinition ( final ClassLoader cl , final InputStream in ) throws PluginConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; Document document ; try { DocumentBuilder loader = factory . newDocumentBuilder ( ) ; DOMReader reader = new DOMReader ( ) ; document = reader . read ( loader . parse ( in ) ) ; } catch ( Exception e ) { throw new PluginConfigurationException ( e . getMessage ( ) , e ) ; } Element plugin = document . getRootElement ( ) ; // TODO : validate against schema return parsePluginDefinition ( cl , plugin ) ; }
Loads the definition of a single plugin from an XML file .
133
13
21,768
@ SuppressWarnings ( "rawtypes" ) private static PluginDefinition parsePluginDefinition ( final ClassLoader cl , final Element plugin ) throws PluginConfigurationException { // Check if the plugin definition is inside its own file if ( getAttributeValue ( plugin , "definedIn" , false ) != null ) { StreamManager sm = new StreamManager ( ) ; String sFileName = getAttributeValue ( plugin , "definedIn" , false ) ; try { InputStream in = sm . handle ( cl . getResourceAsStream ( sFileName ) ) ; return parseXmlPluginDefinition ( cl , in ) ; } finally { sm . closeAll ( ) ; } } String pluginClass = getAttributeValue ( plugin , "class" , true ) ; Class clazz ; try { clazz = LoadedClassCache . getClass ( cl , pluginClass ) ; if ( ! IPluginInterface . class . isAssignableFrom ( clazz ) ) { throw new PluginConfigurationException ( "Specified class '" + clazz . getName ( ) + "' in the plugin.xml file does not implement " + "the IPluginInterface interface" ) ; } if ( isAnnotated ( clazz ) ) { return loadFromPluginAnnotation ( clazz ) ; } } catch ( ClassNotFoundException e ) { throw new PluginConfigurationException ( e . getMessage ( ) , e ) ; } // The class is not annotated not has an external definition file... // Loading from current xml file... String sDescription = getAttributeValue ( plugin , "description" , false ) ; @ SuppressWarnings ( "unchecked" ) PluginDefinition pluginDef = new PluginDefinition ( getAttributeValue ( plugin , "name" , true ) , sDescription , clazz ) ; parseCommandLine ( pluginDef , plugin ) ; return pluginDef ; }
Parse an XML plugin definition .
387
7
21,769
@ SuppressWarnings ( "rawtypes" ) private static void parseCommandLine ( final PluginDefinition pluginDef , final Element xmlPluginElement ) { Element commandLine = xmlPluginElement . element ( "command-line" ) ; if ( commandLine != null ) { // The plugin has a command line... Element options = commandLine . element ( "options" ) ; if ( options == null ) { // The command line is empty... return ; } for ( Iterator < Element > i = options . elementIterator ( ) ; i . hasNext ( ) ; ) { pluginDef . addOption ( parsePluginOption ( i . next ( ) ) ) ; } } }
Updates the plugin definition with the commandline read from the xml file .
141
15
21,770
private static PluginOption parsePluginOption ( final Element option ) { PluginOption po = new PluginOption ( ) ; po . setArgName ( option . attributeValue ( "argName" ) ) ; po . setArgsCount ( Integer . valueOf ( option . attributeValue ( "argsCount" , "1" ) ) ) ; po . setArgsOptional ( Boolean . valueOf ( option . attributeValue ( "optionalArgs" , "false" ) ) ) ; po . setDescription ( option . attributeValue ( "description" ) ) ; po . setHasArgs ( Boolean . parseBoolean ( option . attributeValue ( "hasArgs" , "false" ) ) ) ; po . setLongOpt ( option . attributeValue ( "longName" ) ) ; po . setOption ( option . attributeValue ( "shortName" ) ) ; po . setRequired ( Boolean . parseBoolean ( option . attributeValue ( "required" , "false" ) ) ) ; po . setType ( option . attributeValue ( "type" ) ) ; po . setValueSeparator ( option . attributeValue ( "separator" ) ) ; return po ; }
Parses a plugin option XML definition .
244
9
21,771
private static PluginOption parsePluginOption ( final Option option ) { PluginOption po = new PluginOption ( ) ; po . setArgName ( option . argName ( ) ) ; po . setArgsOptional ( option . optionalArgs ( ) ) ; po . setDescription ( option . description ( ) ) ; po . setHasArgs ( option . hasArgs ( ) ) ; po . setLongOpt ( option . longName ( ) ) ; po . setOption ( option . shortName ( ) ) ; po . setRequired ( option . required ( ) ) ; return po ; }
Parses a plugin option from the annotation definition .
120
11
21,772
@ Override public Object invoke ( Object self , Method thisMethod , Method proceed , Object [ ] args ) throws Throwable { // Get an instance of the implementing class via Guice final Object instance = registry . getInjector ( ) . getInstance ( clazz ) ; return thisMethod . invoke ( instance , args ) ; }
A MethodHandler that proxies the Method invocation through to a Guice - acquired instance
69
16
21,773
public static void main ( String [ ] args ) throws Exception { final String name = args [ 0 ] ; final File sslCert = new File ( args [ 1 ] ) ; final File sslKey = new File ( args [ 2 ] ) ; final Map < File , Integer > foldersAndPorts = getFoldersAndPorts ( 3 , args ) ; NginxSiteGenerator generator = new NginxSiteGenerator ( ) ; final String config = generator . render ( name , sslCert , sslKey , foldersAndPorts ) ; System . out . println ( config ) ; }
Entry point for initial generation called from the commandline
127
10
21,774
public MultiXSDSchemaFiles encode ( ) { MultiXSDSchemaFiles files = new MultiXSDSchemaFiles ( ) ; for ( Map . Entry < String , DOMResult > entry : schemas . entrySet ( ) ) { MultiXSDSchemaFile file = new MultiXSDSchemaFile ( ) ; file . name = entry . getKey ( ) ; file . schema = getElement ( entry . getValue ( ) . getNode ( ) ) ; files . files . add ( file ) ; } // Now loosen xml:any namespace=##other to xml:any namespace=##any if ( loosenXmlAnyConstraints ) MultiXSDSchemaLoosener . loosenXmlAnyOtherNamespaceToXmlAnyAnyNamespace ( files ) ; return files ; }
Produces an XML Schema or a Stdlib SchemaFiles document containing the XML Schemas
175
21
21,775
@ Provides @ Singleton @ Named ( GuiceProperties . REST_SERVICES_PREFIX ) public String getRestServicesPrefix ( ServletContext context ) { String restPath = context . getInitParameter ( RESTEASY_MAPPING_PREFIX ) ; if ( restPath == null || restPath . isEmpty ( ) || restPath . equals ( "/" ) ) { return "" ; } else { return restPath ; } }
Retrieves the RESTeasy mapping prefix - this is the path under the webapp root where RESTeasy services are mapped .
97
25
21,776
@ Provides @ Singleton @ Named ( GuiceProperties . LOCAL_REST_SERVICES_ENDPOINT ) public URI getRestServicesEndpoint ( @ Named ( GuiceProperties . STATIC_ENDPOINT_CONFIG_NAME ) URI webappUri , @ Named ( GuiceProperties . REST_SERVICES_PREFIX ) String restPrefix , ServletContext context ) { if ( restPrefix . equals ( "" ) ) { // resteasy mapped to / return webappUri ; } else { // Strip the leading / from the restpath while ( restPrefix . startsWith ( "/" ) ) restPrefix = restPrefix . substring ( 1 ) ; final String webappPath = webappUri . toString ( ) ; if ( webappPath . endsWith ( "/" ) ) return URI . create ( webappPath + restPrefix ) ; else return URI . create ( webappPath + "/" + restPrefix ) ; } }
Return the base path for all REST services in this webapp
218
12
21,777
@ Provides @ Singleton @ Named ( GuiceProperties . STATIC_ENDPOINT_CONFIG_NAME ) public URI getRestServicesEndpoint ( LocalEndpointDiscovery localEndpointDiscovery ) { final URI base = localEndpointDiscovery . getLocalEndpoint ( ) ; return base ; }
Return the base path for this webapp
67
8
21,778
public List < Class < ? > > getSiblingClasses ( final Class < ? > clazz , boolean recursive , final Predicate < Class < ? > > predicate ) { return getClasses ( getPackages ( clazz ) [ 0 ] , recursive , predicate ) ; }
Find all the classes that are siblings of the provided class
59
11
21,779
public String [ ] getCommandLine ( ) { String [ ] argsAry = argsString != null ? split ( argsString ) : EMPTY_ARRAY ; List < String > argsList = new ArrayList < String > ( ) ; int startIndex = 0 ; for ( CommandOption opt : optionsList ) { String argName = opt . getName ( ) ; String argValueString = opt . getValue ( ) ; argsList . add ( ( argName . length ( ) == 1 ? "-" : "--" ) + argName ) ; if ( argValueString != null ) { argsList . add ( quote ( argValueString ) ) ; } } String [ ] resAry = new String [ argsAry . length + argsList . size ( ) ] ; for ( String argString : argsList ) { resAry [ startIndex ++ ] = argString ; } // vsRes = new String[args.length + m_vArguments.size()]; System . arraycopy ( argsAry , 0 , resAry , startIndex , argsAry . length ) ; return resAry ; }
Merges the command line definition read from the server config file with . the values received from check_nrpe and produces a clean command line .
238
29
21,780
private void parse ( final String definition ) throws BadThresholdException { String [ ] thresholdComponentAry = definition . split ( "," ) ; for ( String thresholdComponent : thresholdComponentAry ) { String [ ] nameValuePair = thresholdComponent . split ( "=" ) ; if ( nameValuePair . length != 2 || StringUtils . isEmpty ( nameValuePair [ 0 ] ) || StringUtils . isEmpty ( nameValuePair [ 1 ] ) ) { throw new BadThresholdException ( "Invalid threshold syntax : " + definition ) ; } if ( "metric" . equalsIgnoreCase ( nameValuePair [ 0 ] ) ) { metricName = nameValuePair [ 1 ] ; continue ; } if ( "ok" . equalsIgnoreCase ( nameValuePair [ 0 ] ) ) { Range thr = new Range ( nameValuePair [ 1 ] ) ; okThresholdList . add ( thr ) ; continue ; } if ( "warning" . equalsIgnoreCase ( nameValuePair [ 0 ] ) || "warn" . equalsIgnoreCase ( nameValuePair [ 0 ] ) || "w" . equalsIgnoreCase ( nameValuePair [ 0 ] ) ) { Range thr = new Range ( nameValuePair [ 1 ] ) ; warningThresholdList . add ( thr ) ; continue ; } if ( "critical" . equalsIgnoreCase ( nameValuePair [ 0 ] ) || "crit" . equalsIgnoreCase ( nameValuePair [ 0 ] ) || "c" . equalsIgnoreCase ( nameValuePair [ 0 ] ) ) { Range thr = new Range ( nameValuePair [ 1 ] ) ; criticalThresholdList . add ( thr ) ; continue ; } if ( "unit" . equalsIgnoreCase ( nameValuePair [ 0 ] ) ) { unit = nameValuePair [ 1 ] ; continue ; } if ( "prefix" . equalsIgnoreCase ( nameValuePair [ 0 ] ) ) { prefix = Prefixes . fromString ( nameValuePair [ 1 ] ) ; continue ; } // Threshold specification error } }
Parses a threshold definition .
458
7
21,781
public final String getRangesAsString ( final Status status ) { List < String > ranges = new ArrayList < String > ( ) ; List < Range > rangeList ; switch ( status ) { case OK : rangeList = okThresholdList ; break ; case WARNING : rangeList = warningThresholdList ; break ; case CRITICAL : default : rangeList = criticalThresholdList ; break ; } for ( Range r : rangeList ) { ranges . add ( r . getRangeString ( ) ) ; } if ( ranges . isEmpty ( ) ) { return null ; } return StringUtils . join ( ranges , "," ) ; }
Returns the requested range list as comma separated string .
136
10
21,782
public static BundleClassLoader newPriviledged ( final Bundle bundle , final ClassLoader parent ) { return AccessController . doPrivileged ( new PrivilegedAction < BundleClassLoader > ( ) { public BundleClassLoader run ( ) { return new BundleClassLoader ( bundle , parent ) ; } } ) ; }
Privileged factory method .
64
5
21,783
@ Override @ SuppressWarnings ( "unchecked" ) protected Enumeration < URL > findResources ( final String name ) throws IOException { Enumeration < URL > resources = m_bundle . getResources ( name ) ; // Bundle.getResources may return null, in such case return empty enumeration if ( resources == null ) { return EMPTY_URL_ENUMERATION ; } else { return resources ; } }
Use bundle to find resources .
94
6
21,784
public final void call ( T param ) { if ( ! run ) { run = true ; prepared = true ; try { this . run ( param ) ; } catch ( Throwable t ) { log . error ( "[ParamInvokeable] {prepare} : " + t . getMessage ( ) , t ) ; } } }
Synchronously executes this Invokeable
70
8
21,785
public synchronized List < GuiceRecurringDaemon > getRecurring ( ) { return daemons . stream ( ) . filter ( d -> d instanceof GuiceRecurringDaemon ) . map ( d -> ( GuiceRecurringDaemon ) d ) . sorted ( Comparator . comparing ( GuiceDaemon :: getName ) ) . collect ( Collectors . toList ( ) ) ; }
Return a list of all
85
5
21,786
public static final byte [ ] fromHex ( final String value ) { if ( value . length ( ) == 0 ) return new byte [ 0 ] ; else if ( value . indexOf ( ' ' ) != - 1 ) return fromHex ( ' ' , value ) ; else if ( value . length ( ) % 2 != 0 ) throw new IllegalArgumentException ( "Invalid hex specified: uneven number of digits passed for byte[] conversion" ) ; final byte [ ] buffer = new byte [ value . length ( ) / 2 ] ; // i tracks input position, j tracks output position int j = 0 ; for ( int i = 0 ; i < buffer . length ; i ++ ) { buffer [ i ] = ( byte ) Integer . parseInt ( value . substring ( j , j + 2 ) , 16 ) ; j += 2 ; } return buffer ; }
Decodes a hexidecimal string into a series of bytes
182
13
21,787
private String getHttpResponse ( final ICommandLine cl , final String hostname , final String port , final String method , final String path , final int timeout , final boolean ssl , final List < Metric > metrics ) throws MetricGatheringException { Properties props = null ; try { props = getRequestProperties ( cl , method ) ; } catch ( UnsupportedEncodingException e ) { throw new MetricGatheringException ( "Error occurred: " + e . getMessage ( ) , Status . CRITICAL , e ) ; } String response = null ; String redirect = cl . getOptionValue ( "onredirect" ) ; boolean ignoreBody = false ; try { String data = null ; if ( "POST" . equals ( method ) ) { data = getPostData ( cl ) ; } if ( cl . hasOption ( "no-body" ) ) { ignoreBody = true ; } String urlString = hostname + ":" + port + path ; if ( cl . hasOption ( "authorization" ) ) { urlString = cl . getOptionValue ( "authorization" ) + "@" + urlString ; } else if ( cl . hasOption ( "proxy-authorization" ) ) { urlString = cl . getOptionValue ( "proxy-authorization" ) + "@" + urlString ; } if ( ssl ) { urlString = "https://" + urlString ; } else { urlString = "http://" + urlString ; } URL url = new URL ( urlString ) ; if ( cl . getOptionValue ( "certificate" ) != null ) { checkCertificateExpiryDate ( url , metrics ) ; } else if ( redirect != null ) { response = checkRedirectResponse ( url , method , timeout , props , data , redirect , ignoreBody , metrics ) ; } else { try { if ( "GET" . equals ( method ) ) { response = HttpUtils . doGET ( url , props , timeout , true , ignoreBody ) ; } else if ( "POST" . equals ( method ) ) { response = HttpUtils . doPOST ( url , props , null , data , true , ignoreBody ) ; } else if ( "HEAD" . equals ( method ) ) { response = HttpUtils . doHEAD ( url , props , timeout , true , ignoreBody ) ; } // @TODO complete for other http methods } catch ( MalformedURLException e ) { LOG . error ( getContext ( ) , "Bad url" , e ) ; throw new MetricGatheringException ( "Bad url string : " + urlString , Status . CRITICAL , e ) ; } } } catch ( Exception e ) { LOG . error ( getContext ( ) , "Exception: " + e . getMessage ( ) , e ) ; throw new MetricGatheringException ( e . getClass ( ) . getName ( ) + ": " + e . getMessage ( ) , Status . CRITICAL , e ) ; } return response ; }
Do the actual http request and return the response string .
646
11
21,788
private String checkRedirectResponse ( final URL url , final String method , final Integer timeout , final Properties props , final String postData , final String redirect , final boolean ignoreBody , final List < Metric > metrics ) throws Exception { // @todo handle sticky/port and follow param options String response = null ; HttpURLConnection conn = ( HttpURLConnection ) url . openConnection ( ) ; conn . setRequestMethod ( method ) ; HttpUtils . setRequestProperties ( props , conn , timeout ) ; String initialUrl = String . valueOf ( conn . getURL ( ) ) ; String redirectedUrl = null ; if ( "POST" . equals ( method ) ) { HttpUtils . sendPostData ( conn , postData ) ; } response = HttpUtils . parseHttpResponse ( conn , false , ignoreBody ) ; redirectedUrl = String . valueOf ( conn . getURL ( ) ) ; if ( ! redirectedUrl . equals ( initialUrl ) ) { Metric metric = new Metric ( "onredirect" , "" , new BigDecimal ( 1 ) , null , null ) ; metrics . add ( metric ) ; } return response ; }
Apply the logic to check for url redirects .
250
10
21,789
private List < Metric > analyzeResponse ( final ICommandLine opt , final String response , final int elapsed ) throws MetricGatheringException { List < Metric > metrics = new ArrayList < Metric > ( ) ; metrics . add ( new Metric ( "time" , "" , new BigDecimal ( elapsed ) , null , null ) ) ; if ( ! opt . hasOption ( "certificate" ) ) { if ( opt . hasOption ( "string" ) ) { boolean found = false ; String string = opt . getOptionValue ( "string" ) ; found = response . contains ( string ) ; metrics . add ( new Metric ( "string" , "" , new BigDecimal ( Utils . getIntValue ( found ) ) , null , null ) ) ; } if ( opt . hasOption ( "expect" ) ) { int count = 0 ; String [ ] values = opt . getOptionValue ( "expect" ) . split ( "," ) ; for ( String value : values ) { if ( response . contains ( value ) ) { count ++ ; } } metrics . add ( new Metric ( "expect" , String . valueOf ( count ) + " times. " , new BigDecimal ( count ) , null , null ) ) ; } if ( opt . hasOption ( "regex" ) ) { String regex = opt . getOptionValue ( "regex" ) ; Pattern p = null ; int flags = 0 ; if ( opt . hasOption ( "eregi" ) ) { flags = Pattern . CASE_INSENSITIVE ; } if ( opt . hasOption ( "linespan" ) ) { flags = flags | Pattern . MULTILINE ; } p = Pattern . compile ( regex , flags ) ; boolean found = p . matcher ( response ) . find ( ) ; if ( opt . hasOption ( "invert-regex" ) ) { metrics . add ( new Metric ( "invert-regex" , String . valueOf ( found ) , new BigDecimal ( Utils . getIntValue ( found ) ) , null , null ) ) ; } else { metrics . add ( new Metric ( "regex" , String . valueOf ( found ) , new BigDecimal ( Utils . getIntValue ( found ) ) , null , null ) ) ; } } } return metrics ; }
Apply logic to the http response and build metrics .
507
10
21,790
private Properties getRequestProperties ( final ICommandLine cl , final String method ) throws UnsupportedEncodingException { Properties props = new Properties ( ) ; if ( cl . hasOption ( "useragent" ) ) { props . setProperty ( "User-Agent" , cl . getOptionValue ( "useragent" ) ) ; } else { props . setProperty ( "User-Agent" , DEFAULT_USER_AGENT ) ; } if ( cl . hasOption ( "content-type" ) && "POST" . equalsIgnoreCase ( method ) ) { props . setProperty ( "Content-Type" , cl . getOptionValue ( "content-type" ) ) ; } if ( cl . hasOption ( "header" ) ) { List headers = cl . getOptionValues ( "header" ) ; for ( Object obj : headers ) { String header = ( String ) obj ; String key = header . split ( ":" ) [ 0 ] . trim ( ) ; String value = header . split ( ":" ) [ 1 ] . trim ( ) ; props . setProperty ( key , value ) ; } } String auth = null ; String encoded = null ; if ( cl . hasOption ( "authorization" ) ) { encoded = Base64 . encodeBase64String ( cl . getOptionValue ( "authorization" ) . getBytes ( CHARSET ) ) ; auth = "Authorization" ; } else if ( cl . hasOption ( "proxy-authorization" ) ) { encoded = Base64 . encodeBase64String ( cl . getOptionValue ( "proxy-authorization" ) . getBytes ( CHARSET ) ) ; auth = "Proxy-Authorization" ; } if ( auth != null && encoded != null ) { props . setProperty ( auth , "Basic " + encoded ) ; } return props ; }
Set the http request properties and headers .
391
8
21,791
private String getPostData ( final ICommandLine cl ) throws Exception { // String encoded = ""; StringBuilder encoded = new StringBuilder ( ) ; String data = cl . getOptionValue ( "post" ) ; if ( data == null ) { return null ; } String [ ] values = data . split ( "&" ) ; for ( String value : values ) { String [ ] splitted = value . split ( "=" ) ; String key = splitted [ 0 ] ; String val = "" ; if ( splitted . length > 1 ) { val = splitted [ 1 ] ; } if ( encoded . length ( ) != 0 ) { encoded . append ( ' ' ) ; } encoded . append ( key ) . append ( ' ' ) . append ( URLEncoder . encode ( val , "UTF-8" ) ) ; // encoded += key + "=" + URLEncoder.encode(val, "UTF-8") + "&"; } // if (encoded.endsWith("&")) { // StringUtils.removeEnd(encoded, "&"); // } return encoded . toString ( ) ; }
Returns encoded post data .
242
5
21,792
private void checkCertificateExpiryDate ( URL url , List < Metric > metrics ) throws Exception { SSLContext ctx = SSLContext . getInstance ( "TLS" ) ; ctx . init ( new KeyManager [ 0 ] , new TrustManager [ ] { new DefaultTrustManager ( ) } , new SecureRandom ( ) ) ; SSLContext . setDefault ( ctx ) ; HttpsURLConnection conn = ( HttpsURLConnection ) url . openConnection ( ) ; conn . setHostnameVerifier ( new HostnameVerifier ( ) { public boolean verify ( final String arg0 , final SSLSession arg1 ) { return true ; } } ) ; List < Date > expiryDates = new ArrayList < Date > ( ) ; conn . getResponseCode ( ) ; Certificate [ ] certs = conn . getServerCertificates ( ) ; for ( Certificate cert : certs ) { X509Certificate x509 = ( X509Certificate ) cert ; Date expiry = x509 . getNotAfter ( ) ; expiryDates . add ( expiry ) ; } conn . disconnect ( ) ; Date today = new Date ( ) ; for ( Date date : expiryDates ) { int diffInDays = ( int ) ( ( date . getTime ( ) - today . getTime ( ) ) / ( 1000 * 60 * 60 * 24 ) ) ; metrics . add ( new Metric ( "certificate" , "" , new BigDecimal ( diffInDays ) , null , null ) ) ; } }
stuff for checking certificate
327
4
21,793
public static JNRPEConfiguration createConfiguration ( final String configurationFilePath ) throws ConfigurationException { JNRPEConfiguration conf = null ; if ( configurationFilePath . toLowerCase ( ) . endsWith ( ".conf" ) || configurationFilePath . toLowerCase ( ) . endsWith ( ".ini" ) ) { conf = new IniJNRPEConfiguration ( ) ; } else if ( configurationFilePath . toLowerCase ( ) . endsWith ( ".xml" ) ) { conf = new XmlJNRPEConfiguration ( ) ; } if ( conf == null ) { throw new ConfigurationException ( "Config file name must end with either '.ini' " + "(ini file) or '.xml' (xml file). Received file name is : " + new File ( configurationFilePath ) . getName ( ) ) ; } conf . load ( new File ( configurationFilePath ) ) ; return conf ; }
Creates a configuration object from the passed in configuration file .
202
12
21,794
public static BundleContext getBundleContext ( final Bundle bundle ) { try { // first try to find the getBundleContext method (OSGi spec >= 4.10) final Method method = Bundle . class . getDeclaredMethod ( "getBundleContext" ) ; if ( ! method . isAccessible ( ) ) { method . setAccessible ( true ) ; } return ( BundleContext ) method . invoke ( bundle ) ; } catch ( Exception e ) { // then try to find a field in the bundle that looks like a bundle context try { final Field [ ] fields = bundle . getClass ( ) . getDeclaredFields ( ) ; for ( Field field : fields ) { if ( BundleContext . class . isAssignableFrom ( field . getType ( ) ) ) { if ( ! field . isAccessible ( ) ) { field . setAccessible ( true ) ; } return ( BundleContext ) field . get ( bundle ) ; } } } catch ( Exception ignore ) { // ignore } } // well, discovery failed return null ; }
Discovers the bundle context for a bundle . If the bundle is an 4 . 1 . 0 or greater bundle it should have a method that just returns the bundle context . Otherwise uses reflection to look for an internal bundle context .
223
46
21,795
public static Bundle getBundle ( BundleContext bc , String symbolicName ) { return getBundle ( bc , symbolicName , null ) ; }
Returns any bundle with the given symbolic name or null if no such bundle exists . If there are multiple bundles with the same symbolic name and different version this method returns the first bundle found .
30
37
21,796
public static List < Bundle > getBundles ( BundleContext bc , String symbolicName ) { List < Bundle > bundles = new ArrayList < Bundle > ( ) ; for ( Bundle bundle : bc . getBundles ( ) ) { if ( bundle . getSymbolicName ( ) . equals ( symbolicName ) ) { bundles . add ( bundle ) ; } } return bundles ; }
Returns a list of all bundles with the given symbolic name .
82
12
21,797
public static Bundle getBundle ( BundleContext bc , String symbolicName , String version ) { for ( Bundle bundle : bc . getBundles ( ) ) { if ( bundle . getSymbolicName ( ) . equals ( symbolicName ) ) { if ( version == null || version . equals ( bundle . getVersion ( ) ) ) { return bundle ; } } } return null ; }
Returns the bundle with the given symbolic name and the given version or null if no such bundle exists
82
19
21,798
public String encodeValue ( ) { switch ( function ) { case EQ : if ( value != null && value . startsWith ( "_" ) ) return function . getPrefix ( ) + value ; else return value ; default : if ( function . hasBinaryParam ( ) ) return function . getPrefix ( ) + value + ".." + value2 ; else if ( function . hasParam ( ) ) return function . getPrefix ( ) + value ; else return function . getPrefix ( ) ; } }
Encode this constraint in the query string value format
109
10
21,799
public static WQConstraint decode ( final String field , final String rawValue ) { final WQFunctionType function ; final String value ; if ( StringUtils . equalsIgnoreCase ( rawValue , WQFunctionType . IS_NULL . getPrefix ( ) ) ) return new WQConstraint ( field , WQFunctionType . IS_NULL , null ) ; else if ( StringUtils . equalsIgnoreCase ( rawValue , WQFunctionType . NOT_NULL . getPrefix ( ) ) ) return new WQConstraint ( field , WQFunctionType . NOT_NULL , null ) ; else if ( rawValue . startsWith ( "_f_" ) ) { function = WQFunctionType . getByPrefix ( rawValue ) ; if ( function . hasParam ( ) ) { // Strip the function name from the value value = rawValue . substring ( function . getPrefix ( ) . length ( ) ) ; if ( function . hasBinaryParam ( ) ) { final String [ ] splitValues = StringUtils . split ( value , ".." , 2 ) ; final String left = splitValues [ 0 ] ; final String right = splitValues [ 1 ] ; return new WQConstraint ( field , function , left , right ) ; } } else { value = null ; } } else { function = WQFunctionType . EQ ; value = rawValue ; } return new WQConstraint ( field , function , value ) ; }
Produce a WebQueryConstraint from a Query String format parameter
320
14