idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
21,700
public Short getShort ( Map < String , Object > data , String name ) { return get ( data , name , Short . class ) ; }
Get Short .
21,701
protected Method findGetter ( Object data , String property ) throws IntrospectionException { Class < ? > clazz = getClass ( data ) ; String key = clazz . getName ( ) + ":" + property ; Method method = methods . get ( key ) ; if ( method == null ) { Method newMethod = null ; PropertyDescriptor [ ] props = Introspector . getBeanInfo ( clazz ) . getPropertyDescriptors ( ) ; for ( PropertyDescriptor prop : props ) { if ( prop . getName ( ) . equalsIgnoreCase ( property ) ) { newMethod = prop . getReadMethod ( ) ; } } method = methods . putIfAbsent ( key , newMethod ) ; if ( method == null ) { method = newMethod ; } } return method ; }
Cache the method if possible using the classname and property name to allow for similar named methods .
21,702
public final int getReadIndex ( String property ) { MethodInfo method = propertyReadMethods . get ( property ) ; return ( null == method ) ? - 1 : method . index ; }
Return property read index return - 1 when not found .
21,703
public final Class < ? > getPropertyType ( String property ) { MethodInfo info = propertyWriteMethods . get ( property ) ; if ( null == info ) return null ; else return info . parameterTypes [ 0 ] ; }
Return property type return null when not found .
21,704
public final int getWriteIndex ( String property ) { MethodInfo method = propertyWriteMethods . get ( property ) ; return ( null == method ) ? - 1 : method . index ; }
Return property write index return - 1 if not found .
21,705
public final int getIndex ( String name , Object ... args ) { Integer defaultIndex = methodIndexs . get ( name ) ; if ( null != defaultIndex ) return defaultIndex . intValue ( ) ; else { final List < MethodInfo > exists = methods . get ( name ) ; if ( null != exists ) { for ( MethodInfo info : exists ) if ( info . matches ( args ) ) return info . index ; } return - 1 ; } }
Return method index return - 1 if not found .
21,706
public final List < MethodInfo > getMethods ( String name ) { List < MethodInfo > namedMethod = methods . get ( name ) ; if ( null == namedMethod ) return Collections . emptyList ( ) ; else return namedMethod ; }
Return public metheds according to given name
21,707
public final List < MethodInfo > getMethods ( ) { List < MethodInfo > methodInfos = CollectUtils . newArrayList ( ) ; for ( Map . Entry < String , List < MethodInfo > > entry : methods . entrySet ( ) ) { for ( MethodInfo info : entry . getValue ( ) ) methodInfos . add ( info ) ; } Collections . sort ( methodInfos ) ; return methodInfos ; }
Return all public methods .
21,708
public static < T > List < T > getAll ( Collection < Option < T > > values ) { List < T > results = CollectUtils . newArrayList ( values . size ( ) ) ; for ( Option < T > op : values ) { if ( op . isDefined ( ) ) results . add ( op . get ( ) ) ; } return results ; }
Return all value from Option Collection
21,709
public static List < Method > getBeanSetters ( Class < ? > clazz ) { List < Method > methods = CollectUtils . newArrayList ( ) ; for ( Method m : clazz . getMethods ( ) ) { if ( m . getName ( ) . startsWith ( "set" ) && m . getName ( ) . length ( ) > 3 ) { if ( Modifier . isPublic ( m . getModifiers ( ) ) && ! Modifier . isStatic ( m . getModifiers ( ) ) && m . getParameterTypes ( ) . length == 1 ) { methods . add ( m ) ; } } } return methods ; }
Return list of setters
21,710
protected List < ResultConfig > buildResultConfigs ( Class < ? > clazz , PackageConfig . Builder pcb ) { List < ResultConfig > configs = CollectUtils . newArrayList ( ) ; Result [ ] results = new Result [ 0 ] ; Results rs = clazz . getAnnotation ( Results . class ) ; if ( null == rs ) { org . beangle . struts2 . annotation . Action an = clazz . getAnnotation ( org . beangle . struts2 . annotation . Action . class ) ; if ( null != an ) results = an . results ( ) ; } else { results = rs . value ( ) ; } Set < String > annotationResults = CollectUtils . newHashSet ( ) ; if ( null != results ) { for ( Result result : results ) { String resultType = result . type ( ) ; if ( Strings . isEmpty ( resultType ) ) resultType = "dispatcher" ; ResultTypeConfig rtc = pcb . getResultType ( resultType ) ; ResultConfig . Builder rcb = new ResultConfig . Builder ( result . name ( ) , rtc . getClassName ( ) ) ; if ( null != rtc . getDefaultResultParam ( ) ) rcb . addParam ( rtc . getDefaultResultParam ( ) , result . location ( ) ) ; configs . add ( rcb . build ( ) ) ; annotationResults . add ( result . name ( ) ) ; } } if ( ! preloadftl || null == profileService ) return configs ; String extention = profileService . getProfile ( clazz . getName ( ) ) . getViewExtension ( ) ; if ( ! extention . equals ( "ftl" ) ) return configs ; ResultTypeConfig rtc = pcb . getResultType ( "freemarker" ) ; for ( Method m : clazz . getMethods ( ) ) { String methodName = m . getName ( ) ; if ( ! annotationResults . contains ( methodName ) && shouldGenerateResult ( m ) ) { String path = templateFinder . find ( clazz , methodName , methodName , extention ) ; if ( null != path ) { configs . add ( new ResultConfig . Builder ( m . getName ( ) , rtc . getClassName ( ) ) . addParam ( rtc . getDefaultResultParam ( ) , path ) . build ( ) ) ; } } } return configs ; }
generator default results by method name
21,711
public Stopwatch start ( ) { Assert . isTrue ( ! isRunning ) ; isRunning = true ; startTick = ticker . read ( ) ; return this ; }
Starts the stopwatch .
21,712
protected void populateValue ( Object entity , EntityType type , String attr , Object value ) { if ( Strings . contains ( attr , '.' ) ) { if ( null != foreignerKeys ) { boolean isForeigner = isForeigner ( attr ) ; if ( isForeigner ) { String parentPath = Strings . substringBeforeLast ( attr , "." ) ; ObjectAndType propertyType = populator . initProperty ( entity , type , parentPath ) ; Object property = propertyType . getObj ( ) ; if ( property instanceof Entity < ? > ) { if ( ( ( Entity < ? > ) property ) . isPersisted ( ) ) { populator . populateValue ( entity , type , parentPath , null ) ; populator . initProperty ( entity , type , parentPath ) ; } } } } } if ( ! populator . populateValue ( entity , type , attr , value ) ) { transferResult . addFailure ( descriptions . get ( attr ) + " data format error." , value ) ; } }
Populate single attribute
21,713
@ SuppressWarnings ( "rawtypes" ) protected ModelFactory getModelFactory ( Class clazz ) { if ( altMapWrapper && Map . class . isAssignableFrom ( clazz ) ) { return FriendlyMapModel . FACTORY ; } return super . getModelFactory ( clazz ) ; }
of FM .
21,714
protected final Pair < ? , ? > entry ( Object key , Object value ) { return Pair . of ( key , value ) ; }
Return new map entry
21,715
protected final Definition bean ( Class < ? > clazz ) { Definition def = new Definition ( clazz . getName ( ) , clazz , Scope . SINGLETON . toString ( ) ) ; def . beanName = clazz . getName ( ) + "#" + Math . abs ( System . identityHashCode ( def ) ) ; return def ; }
Generate a inner bean definition
21,716
protected Option < TextBundle > loadJavaBundle ( String bundleName , Locale locale ) { Properties properties = new Properties ( ) ; String resource = toJavaResourceName ( bundleName , locale ) ; try { InputStream is = ClassLoaders . getResourceAsStream ( resource , getClass ( ) ) ; if ( null == is ) return Option . none ( ) ; properties . load ( is ) ; is . close ( ) ; } catch ( IOException e ) { return Option . none ( ) ; } finally { } return Option . < TextBundle > from ( new DefaultTextBundle ( locale , resource , properties ) ) ; }
Load java properties bundle with iso - 8859 - 1
21,717
protected final String toJavaResourceName ( String bundleName , Locale locale ) { String fullName = bundleName ; final String localeName = toLocaleStr ( locale ) ; final String suffix = "properties" ; if ( ! "" . equals ( localeName ) ) fullName = fullName + "_" + localeName ; StringBuilder sb = new StringBuilder ( fullName . length ( ) + 1 + suffix . length ( ) ) ; sb . append ( fullName . replace ( '.' , '/' ) ) . append ( '.' ) . append ( suffix ) ; return sb . toString ( ) ; }
java properties bundle name
21,718
private String getComponentName ( ) { Class < ? > c = getClass ( ) ; String name = c . getName ( ) ; int dot = name . lastIndexOf ( '.' ) ; return name . substring ( dot + 1 ) . toLowerCase ( ) ; }
Gets the name of this component .
21,719
protected Stack < Component > getComponentStack ( ) { @ SuppressWarnings ( "unchecked" ) Stack < Component > componentStack = ( Stack < Component > ) stack . getContext ( ) . get ( COMPONENT_STACK ) ; if ( componentStack == null ) { componentStack = new Stack < Component > ( ) ; stack . getContext ( ) . put ( COMPONENT_STACK , componentStack ) ; } return componentStack ; }
Gets the component stack of this component .
21,720
@ SuppressWarnings ( "unchecked" ) protected < T extends Component > T findAncestor ( Class < T > clazz ) { Stack < ? extends Component > componentStack = getComponentStack ( ) ; for ( int i = componentStack . size ( ) - 2 ; i >= 0 ; i -- ) { Component component = componentStack . get ( i ) ; if ( clazz . equals ( component . getClass ( ) ) ) return ( T ) component ; } return null ; }
Finds the nearest ancestor of this component stack .
21,721
public static List < String > readLines ( File file , Charset charset ) throws IOException { InputStream in = null ; try { in = new FileInputStream ( file ) ; if ( null == charset ) { return IOs . readLines ( new InputStreamReader ( in ) ) ; } else { InputStreamReader reader = new InputStreamReader ( in , charset . name ( ) ) ; return IOs . readLines ( reader ) ; } } finally { IOs . close ( in ) ; } }
Reads the contents of a file line by line to a List of Strings . The file is always closed .
21,722
public String getParamstring ( ) { StringWriter sw = new StringWriter ( ) ; Enumeration < ? > em = req . getParameterNames ( ) ; while ( em . hasMoreElements ( ) ) { String attr = ( String ) em . nextElement ( ) ; if ( attr . equals ( "method" ) ) continue ; String value = req . getParameter ( attr ) ; if ( attr . equals ( "x-requested-with" ) ) continue ; sw . write ( attr ) ; sw . write ( '=' ) ; sw . write ( StringUtil . javaScriptStringEnc ( value ) ) ; if ( em . hasMoreElements ( ) ) sw . write ( '&' ) ; } return sw . toString ( ) ; }
query string and form control
21,723
protected void error ( String message , Element source , Throwable cause ) { logger . error ( message ) ; }
Report an error with the given message for the given source element .
21,724
protected void checkNameUniqueness ( String beanName , List < String > aliases , Element beanElement ) { String foundName = null ; if ( StringUtils . hasText ( beanName ) && this . usedNames . contains ( beanName ) ) foundName = beanName ; if ( foundName == null ) foundName = ( String ) CollectionUtils . findFirstMatch ( this . usedNames , aliases ) ; if ( foundName != null ) error ( "Bean name '" + foundName + "' is already used in this file" , beanElement ) ; this . usedNames . add ( beanName ) ; this . usedNames . addAll ( aliases ) ; }
Validate that the specified bean name and aliases have not been used already .
21,725
protected AbstractBeanDefinition createBeanDefinition ( String className , String parentName ) throws ClassNotFoundException { return BeanDefinitionReaderUtils . createBeanDefinition ( parentName , className , null ) ; }
Create a bean definition for the given class name and parent name .
21,726
public void parseConstructorArgElements ( Element beanEle , BeanDefinition bd ) { NodeList nl = beanEle . getChildNodes ( ) ; for ( int i = 0 ; i < nl . getLength ( ) ; i ++ ) { Node node = nl . item ( i ) ; if ( node instanceof Element && nodeNameEquals ( node , CONSTRUCTOR_ARG_ELEMENT ) ) parseConstructorArgElement ( ( Element ) node , bd ) ; } }
Parse constructor - arg sub - elements of the given bean element .
21,727
public void parsePropertyElements ( Element beanEle , BeanDefinition bd ) { NodeList nl = beanEle . getChildNodes ( ) ; for ( int i = 0 ; i < nl . getLength ( ) ; i ++ ) { Node node = nl . item ( i ) ; if ( node instanceof Element && nodeNameEquals ( node , PROPERTY_ELEMENT ) ) parsePropertyElement ( ( Element ) node , bd ) ; } }
Parse property sub - elements of the given bean element .
21,728
public void parseQualifierElements ( Element beanEle , AbstractBeanDefinition bd ) { NodeList nl = beanEle . getChildNodes ( ) ; for ( int i = 0 ; i < nl . getLength ( ) ; i ++ ) { Node node = nl . item ( i ) ; if ( node instanceof Element && nodeNameEquals ( node , QUALIFIER_ELEMENT ) ) parseQualifierElement ( ( Element ) node , bd ) ; } }
Parse qualifier sub - elements of the given bean element .
21,729
public void parseLookupOverrideSubElements ( Element beanEle , MethodOverrides overrides ) { NodeList nl = beanEle . getChildNodes ( ) ; for ( int i = 0 ; i < nl . getLength ( ) ; i ++ ) { Node node = nl . item ( i ) ; if ( node instanceof Element && nodeNameEquals ( node , LOOKUP_METHOD_ELEMENT ) ) { Element ele = ( Element ) node ; String methodName = ele . getAttribute ( NAME_ATTRIBUTE ) ; String beanRef = ele . getAttribute ( BEAN_ELEMENT ) ; LookupOverride override = new LookupOverride ( methodName , beanRef ) ; override . setSource ( extractSource ( ele ) ) ; overrides . addOverride ( override ) ; } } }
Parse lookup - override sub - elements of the given bean element .
21,730
public void parseReplacedMethodSubElements ( Element beanEle , MethodOverrides overrides ) { NodeList nl = beanEle . getChildNodes ( ) ; for ( int i = 0 ; i < nl . getLength ( ) ; i ++ ) { Node node = nl . item ( i ) ; if ( node instanceof Element && nodeNameEquals ( node , REPLACED_METHOD_ELEMENT ) ) { Element replacedMethodEle = ( Element ) node ; String name = replacedMethodEle . getAttribute ( NAME_ATTRIBUTE ) ; String callback = replacedMethodEle . getAttribute ( REPLACER_ATTRIBUTE ) ; ReplaceOverride replaceOverride = new ReplaceOverride ( name , callback ) ; List < Element > argTypeEles = DomUtils . getChildElementsByTagName ( replacedMethodEle , ARG_TYPE_ELEMENT ) ; for ( Element argTypeEle : argTypeEles ) { replaceOverride . addTypeIdentifier ( argTypeEle . getAttribute ( ARG_TYPE_MATCH_ATTRIBUTE ) ) ; } replaceOverride . setSource ( extractSource ( replacedMethodEle ) ) ; overrides . addOverride ( replaceOverride ) ; } } }
Parse replaced - method sub - elements of the given bean element .
21,731
public void parseConstructorArgElement ( Element ele , BeanDefinition bd ) { String indexAttr = ele . getAttribute ( INDEX_ATTRIBUTE ) ; String typeAttr = ele . getAttribute ( TYPE_ATTRIBUTE ) ; String nameAttr = ele . getAttribute ( NAME_ATTRIBUTE ) ; if ( StringUtils . hasLength ( indexAttr ) ) { try { int index = Integer . parseInt ( indexAttr ) ; if ( index < 0 ) { error ( "'index' cannot be lower than 0" , ele ) ; } else { try { this . parseState . push ( new ConstructorArgumentEntry ( index ) ) ; Object value = parsePropertyValue ( ele , bd , null ) ; ConstructorArgumentValues . ValueHolder valueHolder = new ConstructorArgumentValues . ValueHolder ( value ) ; if ( StringUtils . hasLength ( typeAttr ) ) valueHolder . setType ( typeAttr ) ; if ( StringUtils . hasLength ( nameAttr ) ) valueHolder . setName ( nameAttr ) ; valueHolder . setSource ( extractSource ( ele ) ) ; if ( bd . getConstructorArgumentValues ( ) . hasIndexedArgumentValue ( index ) ) { error ( "Ambiguous constructor-arg entries for index " + index , ele ) ; } else { bd . getConstructorArgumentValues ( ) . addIndexedArgumentValue ( index , valueHolder ) ; } } finally { this . parseState . pop ( ) ; } } } catch ( NumberFormatException ex ) { error ( "Attribute 'index' of tag 'constructor-arg' must be an integer" , ele ) ; } } else { try { this . parseState . push ( new ConstructorArgumentEntry ( ) ) ; Object value = parsePropertyValue ( ele , bd , null ) ; ConstructorArgumentValues . ValueHolder valueHolder = new ConstructorArgumentValues . ValueHolder ( value ) ; if ( StringUtils . hasLength ( typeAttr ) ) valueHolder . setType ( typeAttr ) ; if ( StringUtils . hasLength ( nameAttr ) ) valueHolder . setName ( nameAttr ) ; valueHolder . setSource ( extractSource ( ele ) ) ; bd . getConstructorArgumentValues ( ) . addGenericArgumentValue ( valueHolder ) ; } finally { this . parseState . pop ( ) ; } } }
Parse a constructor - arg element .
21,732
public void parsePropertyElement ( Element ele , BeanDefinition bd ) { String propertyName = ele . getAttribute ( NAME_ATTRIBUTE ) ; if ( ! StringUtils . hasLength ( propertyName ) ) { error ( "Tag 'property' must have a 'name' attribute" , ele ) ; return ; } this . parseState . push ( new PropertyEntry ( propertyName ) ) ; try { if ( bd . getPropertyValues ( ) . contains ( propertyName ) ) { error ( "Multiple 'property' definitions for property '" + propertyName + "'" , ele ) ; return ; } Object val = parsePropertyValue ( ele , bd , propertyName ) ; PropertyValue pv = new PropertyValue ( propertyName , val ) ; parseMetaElements ( ele , pv ) ; pv . setSource ( extractSource ( ele ) ) ; bd . getPropertyValues ( ) . addPropertyValue ( pv ) ; } finally { this . parseState . pop ( ) ; } }
Parse a property element .
21,733
public void parseQualifierElement ( Element ele , AbstractBeanDefinition bd ) { String typeName = ele . getAttribute ( TYPE_ATTRIBUTE ) ; if ( ! StringUtils . hasLength ( typeName ) ) { error ( "Tag 'qualifier' must have a 'type' attribute" , ele ) ; return ; } this . parseState . push ( new QualifierEntry ( typeName ) ) ; try { AutowireCandidateQualifier qualifier = new AutowireCandidateQualifier ( typeName ) ; qualifier . setSource ( extractSource ( ele ) ) ; String value = ele . getAttribute ( VALUE_ATTRIBUTE ) ; if ( StringUtils . hasLength ( value ) ) { qualifier . setAttribute ( AutowireCandidateQualifier . VALUE_KEY , value ) ; } NodeList nl = ele . getChildNodes ( ) ; for ( int i = 0 ; i < nl . getLength ( ) ; i ++ ) { Node node = nl . item ( i ) ; if ( node instanceof Element && nodeNameEquals ( node , QUALIFIER_ATTRIBUTE_ELEMENT ) ) { Element attributeEle = ( Element ) node ; String attributeName = attributeEle . getAttribute ( KEY_ATTRIBUTE ) ; String attributeValue = attributeEle . getAttribute ( VALUE_ATTRIBUTE ) ; if ( StringUtils . hasLength ( attributeName ) && StringUtils . hasLength ( attributeValue ) ) { BeanMetadataAttribute attribute = new BeanMetadataAttribute ( attributeName , attributeValue ) ; attribute . setSource ( extractSource ( attributeEle ) ) ; qualifier . addMetadataAttribute ( attribute ) ; } else { error ( "Qualifier 'attribute' tag must have a 'name' and 'value'" , attributeEle ) ; return ; } } } bd . addQualifier ( qualifier ) ; } finally { this . parseState . pop ( ) ; } }
Parse a qualifier element .
21,734
public Object parsePropertyValue ( Element ele , BeanDefinition bd , String propertyName ) { String elementName = ( propertyName != null ) ? "<property> element for property '" + propertyName + "'" : "<constructor-arg> element" ; NodeList nl = ele . getChildNodes ( ) ; Element subElement = null ; for ( int i = 0 ; i < nl . getLength ( ) ; i ++ ) { Node node = nl . item ( i ) ; if ( node instanceof Element && ! nodeNameEquals ( node , DESCRIPTION_ELEMENT ) && ! nodeNameEquals ( node , META_ELEMENT ) ) { if ( subElement != null ) error ( elementName + " must not contain more than one sub-element" , ele ) ; else subElement = ( Element ) node ; } } boolean hasRefAttribute = ele . hasAttribute ( REF_ATTRIBUTE ) ; boolean hasValueAttribute = ele . hasAttribute ( VALUE_ATTRIBUTE ) ; if ( ( hasRefAttribute && hasValueAttribute ) || ( ( hasRefAttribute || hasValueAttribute ) && subElement != null ) ) { error ( elementName + " is only allowed to contain either 'ref' attribute OR 'value' attribute OR sub-element" , ele ) ; } if ( hasRefAttribute ) { String refName = ele . getAttribute ( REF_ATTRIBUTE ) ; if ( ! StringUtils . hasText ( refName ) ) error ( elementName + " contains empty 'ref' attribute" , ele ) ; RuntimeBeanReference ref = new RuntimeBeanReference ( refName ) ; ref . setSource ( extractSource ( ele ) ) ; return ref ; } else if ( hasValueAttribute ) { TypedStringValue valueHolder = new TypedStringValue ( ele . getAttribute ( VALUE_ATTRIBUTE ) ) ; valueHolder . setSource ( extractSource ( ele ) ) ; return valueHolder ; } else if ( subElement != null ) { return parsePropertySubElement ( subElement , bd ) ; } else { error ( elementName + " must specify a ref or value" , ele ) ; return null ; } }
Get the value of a property element . May be a list etc . Also used for constructor arguments propertyName being null in this case .
21,735
public Object parsePropertySubElement ( Element ele , BeanDefinition bd , String defaultValueType ) { if ( ! isDefaultNamespace ( getNamespaceURI ( ele ) ) ) { error ( "Cannot support nested element ." , ele ) ; return null ; } else if ( nodeNameEquals ( ele , BEAN_ELEMENT ) ) { BeanDefinitionHolder nestedBd = parseBeanDefinitionElement ( ele , bd ) ; if ( nestedBd != null ) nestedBd = decorateBeanDefinitionIfRequired ( ele , nestedBd , bd ) ; return nestedBd ; } else if ( nodeNameEquals ( ele , REF_ELEMENT ) ) { String refName = ele . getAttribute ( BEAN_REF_ATTRIBUTE ) ; boolean toParent = false ; if ( ! StringUtils . hasLength ( refName ) ) { refName = ele . getAttribute ( LOCAL_REF_ATTRIBUTE ) ; if ( ! StringUtils . hasLength ( refName ) ) { refName = ele . getAttribute ( PARENT_REF_ATTRIBUTE ) ; toParent = true ; if ( ! StringUtils . hasLength ( refName ) ) { error ( "'bean', 'local' or 'parent' is required for <ref> element" , ele ) ; return null ; } } } if ( ! StringUtils . hasText ( refName ) ) { error ( "<ref> element contains empty target attribute" , ele ) ; return null ; } RuntimeBeanReference ref = new RuntimeBeanReference ( refName , toParent ) ; ref . setSource ( extractSource ( ele ) ) ; return ref ; } else if ( nodeNameEquals ( ele , IDREF_ELEMENT ) ) { return parseIdRefElement ( ele ) ; } else if ( nodeNameEquals ( ele , VALUE_ELEMENT ) ) { return parseValueElement ( ele , defaultValueType ) ; } else if ( nodeNameEquals ( ele , NULL_ELEMENT ) ) { TypedStringValue nullHolder = new TypedStringValue ( null ) ; nullHolder . setSource ( extractSource ( ele ) ) ; return nullHolder ; } else if ( nodeNameEquals ( ele , ARRAY_ELEMENT ) ) { return parseArrayElement ( ele , bd ) ; } else if ( nodeNameEquals ( ele , LIST_ELEMENT ) ) { return parseListElement ( ele , bd ) ; } else if ( nodeNameEquals ( ele , SET_ELEMENT ) ) { return parseSetElement ( ele , bd ) ; } else if ( nodeNameEquals ( ele , MAP_ELEMENT ) ) { return parseMapElement ( ele , bd ) ; } else if ( nodeNameEquals ( ele , PROPS_ELEMENT ) ) { return parsePropsElement ( ele ) ; } else { error ( "Unknown property sub-element: [" + ele . getNodeName ( ) + "]" , ele ) ; return null ; } }
Parse a value ref or collection sub - element of a property or constructor - arg element .
21,736
public Object parseIdRefElement ( Element ele ) { String refName = ele . getAttribute ( BEAN_REF_ATTRIBUTE ) ; if ( ! StringUtils . hasLength ( refName ) ) { 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 .
21,737
public Object parseValueElement ( Element ele , String defaultTypeName ) { 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 .
21,738
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 .
21,739
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 .
21,740
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 .
21,741
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 ) { 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 .
21,742
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 ) ; 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 .
21,743
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 .
21,744
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 ) ; 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 .
21,745
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
21,746
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
21,747
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
21,748
public void evict ( K key ) { Object existed = store . getIfPresent ( key ) ; if ( null != existed ) store . invalidate ( key ) ; }
Evict specified key
21,749
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
21,750
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 .
21,751
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 .
21,752
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 .
21,753
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
21,754
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
21,755
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 .
21,756
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 .
21,757
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
21,758
public static void deleteCookie ( HttpServletResponse response , Cookie cookie , String path ) { if ( cookie != null ) { cookie . setMaxAge ( 0 ) ; cookie . setPath ( path ) ; response . addCookie ( cookie ) ; } }
Convenience method for deleting a cookie by name
21,759
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
21,760
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
21,761
public String edit ( ) { Entity < ? > entity = getEntity ( ) ; put ( getShortName ( ) , entity ) ; editSetting ( entity ) ; return forward ( ) ; }
Edit by entity . id or id
21,762
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
21,763
private TraversableCodeGenStrategy getTraversableStrategy ( JType rawType , Map < String , JClass > directClasses ) { if ( rawType . isPrimitive ( ) ) { return TraversableCodeGenStrategy . NO ; } JClass clazz = ( JClass ) rawType ; if ( clazz . isParameterized ( ) ) { clazz = clazz . getTypeParameters ( ) . get ( 0 ) ; if ( clazz . name ( ) . startsWith ( "?" ) ) { clazz = clazz . _extends ( ) ; } } String name = clazz . fullName ( ) ; if ( name . equals ( "java.lang.Object" ) ) { return TraversableCodeGenStrategy . MAYBE ; } else if ( clazz . isInterface ( ) ) { return TraversableCodeGenStrategy . MAYBE ; } else if ( visitable . isAssignableFrom ( clazz ) ) { return TraversableCodeGenStrategy . VISITABLE ; } else if ( directClasses . containsKey ( name ) ) { return TraversableCodeGenStrategy . DIRECT ; } else { return TraversableCodeGenStrategy . NO ; } }
Tests to see if the rawType is traversable
21,764
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 .
21,765
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
21,766
@ 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
21,767
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 .
21,768
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 .
21,769
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 .
21,770
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 .
21,771
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 .
21,772
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 .
21,773
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
21,774
public Object put ( Object key , Object value ) { return next . put ( key , value ) ; }
put value to next
21,775
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
21,776
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
21,777
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 .
21,778
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
21,779
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 .
21,780
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 .
21,781
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
21,782
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 .
21,783
public static Browser parse ( final String agentString ) { if ( Strings . isEmpty ( agentString ) ) { return Browser . UNKNOWN ; } 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 ( 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 .
21,784
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 .
21,785
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 .
21,786
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 .
21,787
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 . split ( args ) ; configuration = SeleniumServer . parseLauncherOptions ( argv ) ; System . setProperty ( "org.openqa.jetty.http.HttpRequest.maxFormContentSize" , "0" ) ; seleniumProxy = new SeleniumServer ( isSlowConnection ( ) , configuration ) ; seleniumProxy . start ( ) ; } catch ( Exception e ) { LOG . info ( "Server stopped" ) ; } }
Start server with arguments .
21,788
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
21,789
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
21,790
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 .
21,791
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 .
21,792
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 .
21,793
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 .
21,794
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
21,795
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 .
21,796
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
21,797
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
21,798
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
21,799
public URI getRedirectToFromState ( final String state ) { final String [ ] pieces = decodeState ( state ) . split ( " " , 2 ) ; if ( ! StringUtils . equals ( callbackNonce , pieces [ 0 ] ) ) { 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