idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
40,900
public static Dictionary < String , String > convertInitParams ( final WebAppInitParam [ ] initParams ) { if ( initParams == null || initParams . length == 0 ) { return null ; } Hashtable < String , String > dictionary = new Hashtable < > ( ) ; for ( WebAppInitParam initParam : initParams ) { dictionary . put ( initParam . getParamName ( ) , initParam . getParamValue ( ) ) ; } return dictionary ; }
Converts an array of init params to a Dictionary .
40,901
private void createManagedService ( final BundleContext context ) { ManagedService service = this :: scheduleUpdateConfig ; final Dictionary < String , String > props = new Hashtable < > ( ) ; props . put ( Constants . SERVICE_PID , org . ops4j . pax . web . service . WebContainerConstants . PID ) ; context . registerService ( ManagedService . class , service , props ) ; if ( context . getServiceReference ( ConfigurationAdmin . class . getName ( ) ) == null ) { try { service . updated ( null ) ; } catch ( ConfigurationException ignore ) { LOG . error ( "Internal error. Cannot set initial configuration resolver." , ignore ) ; } } }
Registers a managed service to listen on configuration updates .
40,902
private static String validateAlias ( final String alias ) { NullArgumentException . validateNotNull ( alias , "Alias" ) ; if ( ! alias . startsWith ( "/" ) ) { throw new IllegalArgumentException ( "Alias does not start with slash (/)" ) ; } if ( alias . length ( ) > 1 && alias . endsWith ( "/" ) ) { throw new IllegalArgumentException ( "Alias ends with slash (/)" ) ; } return alias ; }
Validates that aan alias conforms to OSGi specs requirements . See OSGi R4 Http Service specs for details about alias validation .
40,903
private static String aliasAsUrlPattern ( final String alias ) { String urlPattern = alias ; if ( urlPattern != null && ! urlPattern . equals ( "/" ) && ! urlPattern . contains ( "*" ) ) { if ( urlPattern . endsWith ( "/" ) ) { urlPattern = urlPattern + "*" ; } else { urlPattern = urlPattern + "/*" ; } } return urlPattern ; }
Transforms an alias into a url pattern .
40,904
public void registerServlet ( Class < ? extends Servlet > servletClass , String [ ] urlPatterns , Dictionary < String , ? > initParams , HttpContext httpContext ) throws ServletException { LOG . warn ( "Http service has already been stopped" ) ; }
Does nothing .
40,905
private String createResourceIdentifier ( final String localePrefix , final String resourceName , final String resourceVersion , final String libraryName , final String libraryVersion ) { final StringBuilder sb = new StringBuilder ( ) ; if ( StringUtils . isNotBlank ( localePrefix ) ) { sb . append ( localePrefix ) . append ( PATH_SEPARATOR ) ; } if ( StringUtils . isNotBlank ( libraryName ) ) { sb . append ( libraryName ) . append ( PATH_SEPARATOR ) ; } if ( StringUtils . isNotBlank ( libraryVersion ) ) { sb . append ( libraryVersion ) . append ( PATH_SEPARATOR ) ; } sb . append ( resourceName ) . append ( PATH_SEPARATOR ) ; if ( StringUtils . isNotBlank ( resourceVersion ) ) { sb . append ( resourceVersion ) . append ( PATH_SEPARATOR ) ; } return sb . toString ( ) ; }
Creates an ResourceIdentifier according to chapter 2 . 6 . 1 . 3 from the JSF 2 . 2 specification
40,906
public static String [ ] extractNameVersionType ( String url ) { Matcher m = ARTIFACT_MATCHER . matcher ( url ) ; if ( ! m . matches ( ) ) { return new String [ ] { url . split ( "\\." ) [ 0 ] , DEFAULT_VERSION } ; } else { StringBuilder v = new StringBuilder ( ) ; String d1 = m . group ( 1 ) ; String d2 = m . group ( 2 ) ; String d3 = m . group ( 3 ) ; String d4 = m . group ( 4 ) ; String d5 = m . group ( 5 ) ; String d6 = m . group ( 6 ) ; if ( d2 != null ) { v . append ( d2 ) ; if ( d3 != null ) { v . append ( '.' ) ; v . append ( d3 ) ; if ( d4 != null ) { v . append ( '.' ) ; v . append ( d4 ) ; if ( d5 != null ) { v . append ( "." ) ; cleanupModifier ( v , d5 ) ; } } else if ( d5 != null ) { v . append ( ".0." ) ; cleanupModifier ( v , d5 ) ; } } else if ( d5 != null ) { v . append ( ".0.0." ) ; cleanupModifier ( v , d5 ) ; } } return new String [ ] { d1 , v . toString ( ) , d6 } ; } }
Heuristic to compute the name and version of a file given it s name on disk
40,907
public void visit ( final WebAppServlet webAppServlet ) { NullArgumentException . validateNotNull ( webAppServlet , "Web app servlet" ) ; final String [ ] aliases = webAppServlet . getAliases ( ) ; if ( aliases != null && aliases . length > 0 ) { for ( String alias : aliases ) { try { httpService . unregister ( alias ) ; } catch ( Exception ignore ) { LOG . warn ( "Unregistration exception. Skipping." , ignore ) ; } } } else { LOG . warn ( "Servlet [" + webAppServlet + "] does not have any alias. Skipped." ) ; } }
Unregisters servlet from http context .
40,908
public void addServletMapping ( final WebAppServletMapping servletMapping ) { NullArgumentException . validateNotNull ( servletMapping , "Servlet mapping" ) ; NullArgumentException . validateNotNull ( servletMapping . getServletName ( ) , "Servlet name" ) ; NullArgumentException . validateNotNull ( servletMapping . getUrlPattern ( ) , "Url pattern" ) ; Set < WebAppServletMapping > webAppServletMappings = servletMappings . get ( servletMapping . getServletName ( ) ) ; if ( webAppServletMappings == null ) { webAppServletMappings = new HashSet < > ( ) ; servletMappings . put ( servletMapping . getServletName ( ) , webAppServletMappings ) ; } webAppServletMappings . add ( servletMapping ) ; final WebAppServlet servlet = servlets . get ( servletMapping . getServletName ( ) ) ; if ( servlet != null ) { servlet . addUrlPattern ( servletMapping . getUrlPattern ( ) ) ; } }
Add a servlet mapping .
40,909
public List < WebAppServletMapping > getServletMappings ( final String servletName ) { final Set < WebAppServletMapping > webAppServletMappings = servletMappings . get ( servletName ) ; if ( webAppServletMappings == null ) { return new ArrayList < > ( ) ; } return new ArrayList < > ( webAppServletMappings ) ; }
Returns a servlet mapping by servlet name .
40,910
public void addFilter ( final WebAppFilter filter ) { NullArgumentException . validateNotNull ( filter , "Filter" ) ; NullArgumentException . validateNotNull ( filter . getFilterName ( ) , "Filter name" ) ; NullArgumentException . validateNotNull ( filter . getFilterClass ( ) , "Filter class" ) ; filters . put ( filter . getFilterName ( ) , filter ) ; for ( WebAppFilterMapping mapping : getFilterMappings ( filter . getFilterName ( ) ) ) { if ( mapping . getUrlPattern ( ) != null && mapping . getUrlPattern ( ) . trim ( ) . length ( ) > 0 ) { filter . addUrlPattern ( mapping . getUrlPattern ( ) ) ; } if ( mapping . getServletName ( ) != null && mapping . getServletName ( ) . trim ( ) . length ( ) > 0 ) { filter . addServletName ( mapping . getServletName ( ) ) ; } } }
Add a filter .
40,911
public void addFilterMapping ( final WebAppFilterMapping filterMapping ) { NullArgumentException . validateNotNull ( filterMapping , "Filter mapping" ) ; NullArgumentException . validateNotNull ( filterMapping . getFilterName ( ) , "Filter name" ) ; final String filterName = filterMapping . getFilterName ( ) ; if ( ! orderedFilters . contains ( filterName ) ) { orderedFilters . add ( filterName ) ; } Set < WebAppFilterMapping > webAppFilterMappings = filterMappings . get ( filterName ) ; if ( webAppFilterMappings == null ) { webAppFilterMappings = new HashSet < > ( ) ; filterMappings . put ( filterName , webAppFilterMappings ) ; } webAppFilterMappings . add ( filterMapping ) ; final WebAppFilter filter = filters . get ( filterName ) ; if ( filter != null ) { if ( filterMapping . getUrlPattern ( ) != null && filterMapping . getUrlPattern ( ) . trim ( ) . length ( ) > 0 ) { filter . addUrlPattern ( filterMapping . getUrlPattern ( ) ) ; } if ( filterMapping . getServletName ( ) != null && filterMapping . getServletName ( ) . trim ( ) . length ( ) > 0 ) { filter . addServletName ( filterMapping . getServletName ( ) ) ; } if ( filterMapping . getDispatcherTypes ( ) != null && ! filterMapping . getDispatcherTypes ( ) . isEmpty ( ) ) { for ( DispatcherType dispatcherType : filterMapping . getDispatcherTypes ( ) ) { filter . addDispatcherType ( dispatcherType ) ; } } } }
Add a filter mapping .
40,912
public List < WebAppFilterMapping > getFilterMappings ( final String filterName ) { final Set < WebAppFilterMapping > webAppFilterMappings = filterMappings . get ( filterName ) ; if ( webAppFilterMappings == null ) { return new ArrayList < > ( ) ; } return new ArrayList < > ( webAppFilterMappings ) ; }
Returns filter mappings by filter name .
40,913
public void addErrorPage ( final WebAppErrorPage errorPage ) { NullArgumentException . validateNotNull ( errorPage , "Error page" ) ; if ( errorPage . getErrorCode ( ) == null && errorPage . getExceptionType ( ) == null ) { throw new NullPointerException ( "At least one of error type or exception code must be set" ) ; } errorPages . add ( errorPage ) ; }
Add an error page .
40,914
public void addContextParam ( final WebAppInitParam contextParam ) { NullArgumentException . validateNotNull ( contextParam , "Context param" ) ; NullArgumentException . validateNotNull ( contextParam . getParamName ( ) , "Context param name" ) ; NullArgumentException . validateNotNull ( contextParam . getParamValue ( ) , "Context param value" ) ; contextParams . add ( contextParam ) ; }
Add a context param .
40,915
public void addMimeMapping ( final WebAppMimeMapping mimeMapping ) { NullArgumentException . validateNotNull ( mimeMapping , "Mime mapping" ) ; NullArgumentException . validateNotNull ( mimeMapping . getExtension ( ) , "Mime mapping extension" ) ; NullArgumentException . validateNotNull ( mimeMapping . getMimeType ( ) , "Mime mapping type" ) ; mimeMappings . add ( mimeMapping ) ; }
Add a mime mapping .
40,916
public void addLoginConfig ( final WebAppLoginConfig webApploginConfig ) { NullArgumentException . validateNotNull ( webApploginConfig , "Login Config" ) ; NullArgumentException . validateNotNull ( webApploginConfig . getAuthMethod ( ) , "Login Config Authorization Method" ) ; loginConfig . add ( webApploginConfig ) ; }
Adds a login config
40,917
public void accept ( final WebAppVisitor visitor ) { visitor . visit ( this ) ; for ( WebAppListener listener : listeners ) { visitor . visit ( listener ) ; } if ( ! filters . isEmpty ( ) ) { final List < WebAppFilter > remainingFilters = new ArrayList < > ( filters . values ( ) ) ; for ( String filterName : orderedFilters ) { final WebAppFilter filter = filters . get ( filterName ) ; visitor . visit ( filter ) ; remainingFilters . remove ( filter ) ; } for ( WebAppFilter filter : remainingFilters ) { visitor . visit ( filter ) ; } } if ( ! servlets . isEmpty ( ) ) { for ( WebAppServlet servlet : getSortedWebAppServlet ( ) ) { visitor . visit ( servlet ) ; } } if ( ! constraintsMapping . isEmpty ( ) ) { for ( WebAppConstraintMapping constraintMapping : constraintsMapping ) { visitor . visit ( constraintMapping ) ; } } for ( WebAppErrorPage errorPage : errorPages ) { visitor . visit ( errorPage ) ; } visitor . end ( ) ; }
Accepts a visitor for inner elements .
40,918
private void configureSecurity ( ServletContextHandler context , String realmName , String authMethod , String formLoginPage , String formErrorPage ) { final SecurityHandler securityHandler = context . getSecurityHandler ( ) ; Authenticator authenticator = null ; if ( authMethod == null ) { LOG . warn ( "UNKNOWN AUTH METHOD: " + authMethod ) ; } else { switch ( authMethod ) { case Constraint . __FORM_AUTH : authenticator = new FormAuthenticator ( ) ; securityHandler . setInitParameter ( FormAuthenticator . __FORM_LOGIN_PAGE , formLoginPage ) ; securityHandler . setInitParameter ( FormAuthenticator . __FORM_ERROR_PAGE , formErrorPage ) ; break ; case Constraint . __BASIC_AUTH : authenticator = new BasicAuthenticator ( ) ; break ; case Constraint . __DIGEST_AUTH : authenticator = new DigestAuthenticator ( ) ; break ; case Constraint . __CERT_AUTH : authenticator = new ClientCertAuthenticator ( ) ; break ; case Constraint . __CERT_AUTH2 : authenticator = new ClientCertAuthenticator ( ) ; break ; case Constraint . __SPNEGO_AUTH : authenticator = new SpnegoAuthenticator ( ) ; break ; default : authenticator = getAuthenticator ( authMethod ) ; break ; } } securityHandler . setAuthenticator ( authenticator ) ; securityHandler . setRealmName ( realmName ) ; }
Sets the security authentication method and the realm name on the security handler . This has to be done before the context is started .
40,919
public void validate ( KeyStore keyStore ) throws CertificateException { try { Enumeration < String > aliases = keyStore . aliases ( ) ; for ( ; aliases . hasMoreElements ( ) ; ) { String alias = aliases . nextElement ( ) ; validate ( keyStore , alias ) ; } } catch ( KeyStoreException kse ) { throw new CertificateException ( "Unable to retrieve aliases from keystore" , kse ) ; } }
validates all aliases inside of a given keystore
40,920
public void visit ( final WebAppServlet webAppServlet ) { NullArgumentException . validateNotNull ( webAppServlet , "Web app servlet" ) ; Class < ? extends Servlet > servletClass = webAppServlet . getServletClass ( ) ; if ( servletClass == null && webAppServlet . getServletClassName ( ) != null ) { try { servletClass = RegisterWebAppVisitorHS . loadClass ( Servlet . class , bundleClassLoader , webAppServlet . getServletClassName ( ) ) ; } catch ( ClassNotFoundException | IllegalAccessException e ) { e . printStackTrace ( ) ; } } if ( servletClass != null ) { try { webContainer . unregisterServlets ( servletClass ) ; webAppServlet . setServletClass ( null ) ; } catch ( Exception ignore ) { LOG . warn ( "Unregistration exception. Skipping." , ignore ) ; } } }
Unregisters servlet from web container .
40,921
public void visit ( final WebAppFilter webAppFilter ) { NullArgumentException . validateNotNull ( webAppFilter , "Web app filter" ) ; String filterName = webAppFilter . getFilterName ( ) ; if ( filterName != null ) { try { webContainer . unregisterFilter ( filterName ) ; } catch ( Exception ignore ) { LOG . warn ( "Unregistration exception. Skipping." , ignore ) ; } } }
Unregisters filter from web container .
40,922
public void visit ( final WebAppListener webAppListener ) { NullArgumentException . validateNotNull ( webAppListener , "Web app listener" ) ; final EventListener listener = webAppListener . getListener ( ) ; if ( listener != null ) { try { webContainer . unregisterEventListener ( listener ) ; } catch ( Exception ignore ) { LOG . warn ( "Unregistration exception. Skipping." , ignore ) ; } } }
Unregisters listeners from web container .
40,923
public void visit ( final WebAppErrorPage webAppErrorPage ) { NullArgumentException . validateNotNull ( webAppErrorPage , "Web app error page" ) ; try { webContainer . unregisterErrorPage ( webAppErrorPage . getError ( ) , httpContext ) ; } catch ( Exception ignore ) { LOG . warn ( "Unregistration exception. Skipping." , ignore ) ; } }
Unregisters error pages from web container .
40,924
public void addEventListener ( final EventListener listener ) { super . addEventListener ( listener ) ; if ( ( listener instanceof HttpSessionActivationListener ) || ( listener instanceof HttpSessionAttributeListener ) || ( listener instanceof HttpSessionBindingListener ) || ( listener instanceof HttpSessionListener ) ) { if ( _sessionHandler != null ) { _sessionHandler . addEventListener ( listener ) ; } } }
If the listener is a servlet context listener and the context is already started notify the servlet context listener about the fact that context is started . This has to be done separately as the listener could be added after the context is already started case when servlet context listeners are not notified anymore .
40,925
public URL getResource ( final String name ) { final String normalizedName = Path . normalizeResourcePath ( rootPath + ( name . startsWith ( "/" ) ? "" : "/" ) + name ) . trim ( ) ; log . debug ( "Searching bundle " + bundle + " for resource [{}], normalized to [{}]" , name , normalizedName ) ; URL url = resourceCache . get ( normalizedName ) ; if ( url == null && ! normalizedName . isEmpty ( ) ) { url = bundle . getEntry ( normalizedName ) ; if ( url == null ) { log . debug ( "getEntry failed, trying with /META-INF/resources/ in bundle class space" ) ; Set < Bundle > bundlesInClassSpace = ClassPathUtil . getBundlesInClassSpace ( bundle , new HashSet < > ( ) ) ; for ( Bundle bundleInClassSpace : bundlesInClassSpace ) { url = bundleInClassSpace . getEntry ( "/META-INF/resources/" + normalizedName ) ; if ( url != null ) { break ; } } } if ( url == null ) { log . debug ( "getEntry failed, fallback to getResource" ) ; url = bundle . getResource ( normalizedName ) ; } if ( url == null ) { url = NO_URL ; } resourceCache . putIfAbsent ( normalizedName , url ) ; } if ( url != null && url != NO_URL ) { log . debug ( "Resource found as url [{}]" , url ) ; } else { log . debug ( "Resource not found" ) ; url = null ; } return url ; }
Searches for the resource in the bundle that published the service .
40,926
public String getMimeType ( final String name ) { String mimeType = null ; if ( name != null && name . length ( ) > 0 && name . contains ( "." ) ) { final String [ ] segments = name . split ( "\\." ) ; mimeType = mimeMappings . get ( segments [ segments . length - 1 ] ) ; } if ( mimeType == null ) { mimeType = httpContext . getMimeType ( name ) ; } return mimeType ; }
Find the mime type in the mime mappings . If not found delegate to wrapped http context .
40,927
public void publish ( final WebApp webApp ) { NullArgumentException . validateNotNull ( webApp , "Web app" ) ; LOG . debug ( "Publishing web application [{}]" , webApp ) ; final BundleContext webAppBundleContext = BundleUtils . getBundleContext ( webApp . getBundle ( ) ) ; if ( webAppBundleContext != null ) { try { Filter filter = webAppBundleContext . createFilter ( String . format ( "(&(objectClass=%s)(bundle.id=%d))" , WebAppDependencyHolder . class . getName ( ) , webApp . getBundle ( ) . getBundleId ( ) ) ) ; ServiceTracker < WebAppDependencyHolder , WebAppDependencyHolder > dependencyTracker = new ServiceTracker < WebAppDependencyHolder , WebAppDependencyHolder > ( webAppBundleContext , filter , new WebAppDependencyListener ( webApp , eventDispatcher , bundleContext ) ) ; webApps . put ( webApp , dependencyTracker ) ; dependencyTracker . open ( ) ; } catch ( InvalidSyntaxException exc ) { throw new IllegalArgumentException ( exc ) ; } } else { LOG . warn ( "Bundle context could not be discovered for bundle [" + webApp . getBundle ( ) + "]" + "Skipping publishing of web application [" + webApp + "]" ) ; } }
Publish a web application .
40,928
public void unpublish ( final WebApp webApp ) { NullArgumentException . validateNotNull ( webApp , "Web app" ) ; LOG . debug ( "Unpublishing web application [{}]" , webApp ) ; final ServiceTracker < WebAppDependencyHolder , WebAppDependencyHolder > tracker = webApps . remove ( webApp ) ; if ( tracker != null ) { tracker . close ( ) ; } }
Unpublish a web application .
40,929
public void registerServlet ( final String alias , final Servlet servlet , @ SuppressWarnings ( "rawtypes" ) final Dictionary initParams , final HttpContext httpContext ) throws ServletException , NamespaceException { synchronized ( lock ) { this . registerServlet ( alias , servlet , initParams , null , null , httpContext ) ; } }
From Http Service - cannot fix generics until underlying Http Service is corrected
40,930
private < T > T withWhiteboardDtoService ( Function < WhiteboardDtoService , T > function ) { final BundleContext bundleContext = serviceBundle . getBundleContext ( ) ; ServiceReference < WhiteboardDtoService > ref = bundleContext . getServiceReference ( WhiteboardDtoService . class ) ; if ( ref != null ) { WhiteboardDtoService service = bundleContext . getService ( ref ) ; if ( service != null ) { try { return function . apply ( service ) ; } finally { bundleContext . ungetService ( ref ) ; } } } throw new IllegalStateException ( String . format ( "Service '%s' could not be retrieved!" , WhiteboardDtoService . class . getName ( ) ) ) ; }
WhiteboardDtoService is registered as DS component . Should be removed if this class gets full DS support
40,931
protected void preDestroy ( Object instance , final Class < ? > clazz ) throws IllegalAccessException , InvocationTargetException { Class < ? > superClass = clazz . getSuperclass ( ) ; if ( superClass != Object . class ) { preDestroy ( instance , superClass ) ; } List < AnnotationCacheEntry > annotations = null ; synchronized ( annotationCache ) { annotations = annotationCache . get ( clazz ) ; } if ( annotations == null ) { return ; } for ( AnnotationCacheEntry entry : annotations ) { if ( entry . getType ( ) == AnnotationCacheEntryType . PRE_DESTROY ) { Method preDestroy = getMethod ( clazz , entry ) ; synchronized ( preDestroy ) { boolean accessibility = preDestroy . isAccessible ( ) ; preDestroy . setAccessible ( true ) ; preDestroy . invoke ( instance ) ; preDestroy . setAccessible ( accessibility ) ; } } } }
Call preDestroy method on the specified instance recursively from deepest superclass to actual class .
40,932
protected void populateAnnotationsCache ( Class < ? > clazz , Map < String , String > injections ) throws IllegalAccessException , InvocationTargetException { while ( clazz != null ) { List < AnnotationCacheEntry > annotations = null ; synchronized ( annotationCache ) { annotations = annotationCache . get ( clazz ) ; } if ( annotations == null ) { annotations = new ArrayList < > ( ) ; Method [ ] methods = null ; methods = clazz . getDeclaredMethods ( ) ; Method postConstruct = null ; Method preDestroy = null ; for ( Method method : methods ) { if ( method . isAnnotationPresent ( PostConstruct . class ) ) { if ( ( postConstruct != null ) || ( method . getParameterTypes ( ) . length != 0 ) || ( Modifier . isStatic ( method . getModifiers ( ) ) ) || ( method . getExceptionTypes ( ) . length > 0 ) || ( ! method . getReturnType ( ) . getName ( ) . equals ( "void" ) ) ) { throw new IllegalArgumentException ( "Invalid PostConstruct annotation" ) ; } postConstruct = method ; } if ( method . isAnnotationPresent ( PreDestroy . class ) ) { if ( ( preDestroy != null || method . getParameterTypes ( ) . length != 0 ) || ( Modifier . isStatic ( method . getModifiers ( ) ) ) || ( method . getExceptionTypes ( ) . length > 0 ) || ( ! method . getReturnType ( ) . getName ( ) . equals ( "void" ) ) ) { throw new IllegalArgumentException ( "Invalid PreDestroy annotation" ) ; } preDestroy = method ; } } if ( postConstruct != null ) { annotations . add ( new AnnotationCacheEntry ( postConstruct . getName ( ) , postConstruct . getParameterTypes ( ) , null , AnnotationCacheEntryType . POST_CONSTRUCT ) ) ; } if ( preDestroy != null ) { annotations . add ( new AnnotationCacheEntry ( preDestroy . getName ( ) , preDestroy . getParameterTypes ( ) , null , AnnotationCacheEntryType . PRE_DESTROY ) ) ; } if ( annotations . size ( ) == 0 ) { annotations = Collections . emptyList ( ) ; } synchronized ( annotationCache ) { annotationCache . put ( clazz , annotations ) ; } } clazz = clazz . getSuperclass ( ) ; } }
Make sure that the annotations cache has been populated for the provided class .
40,933
public static int pipeBytes ( InputStream in , OutputStream out , byte [ ] buffer ) throws IOException { int count = 0 ; int length ; while ( ( length = ( in . read ( buffer ) ) ) >= 0 ) { out . write ( buffer , 0 , length ) ; count += length ; } return count ; }
Reads the specified input stream into the provided byte array storage and writes it to the output stream .
40,934
private List < Deployment > managedDeployments ( List < Deployment > deployments ) { List < Deployment > managed = new ArrayList < Deployment > ( ) ; for ( Deployment deployment : deployments ) { if ( deployment . getDescription ( ) . managed ( ) ) { managed . add ( deployment ) ; } } return managed ; }
Filters the List of Deployments and returns the ones that are Managed deployments .
40,935
private List < Deployment > defaultDeployments ( List < Deployment > deployments ) { List < Deployment > defaults = new ArrayList < Deployment > ( ) ; for ( Deployment deployment : deployments ) { if ( deployment . getDescription ( ) . getName ( ) . equals ( DeploymentTargetDescription . DEFAULT . getName ( ) ) ) { defaults . add ( deployment ) ; } } return defaults ; }
Filters the List of Deployments and returns the ones that are DEFAULT deployments .
40,936
private List < Deployment > archiveDeployments ( List < Deployment > deployments ) { List < Deployment > archives = new ArrayList < Deployment > ( ) ; for ( Deployment deployment : deployments ) { if ( deployment . getDescription ( ) . isArchiveDeployment ( ) ) { archives . add ( deployment ) ; } } return archives ; }
Filters the List of Deployments and returns the ones that are Archive deployments .
40,937
private Deployment findMatchingDeployment ( DeploymentTargetDescription target ) { List < Deployment > matching = findMatchingDeployments ( target ) ; if ( matching . size ( ) == 0 ) { return null ; } if ( matching . size ( ) == 1 ) { return matching . get ( 0 ) ; } return archiveDeployments ( matching ) . get ( 0 ) ; }
Validation names except DEFAULT should be unique . See constructor
40,938
private void validateNotSameNameAndTypeOfDeployment ( DeploymentDescription deployment ) { for ( Deployment existing : deployments ) { if ( existing . getDescription ( ) . getName ( ) . equals ( deployment . getName ( ) ) ) { if ( ( existing . getDescription ( ) . isArchiveDeployment ( ) && deployment . isArchiveDeployment ( ) ) || ( existing . getDescription ( ) . isDescriptorDeployment ( ) && deployment . isDescriptorDeployment ( ) ) ) { throw new IllegalArgumentException ( "Can not add multiple " + Archive . class . getName ( ) + " deployments with the same name: " + deployment . getName ( ) ) ; } } } }
Validate that a deployment of same type is not already added
40,939
private void validateNotSameArchiveAndSameTarget ( DeploymentDescription deployment ) { if ( ! deployment . isArchiveDeployment ( ) ) { return ; } for ( Deployment existing : archiveDeployments ( deployments ) ) { if ( existing . getDescription ( ) . getArchive ( ) . getName ( ) . equals ( deployment . getArchive ( ) . getName ( ) ) ) { if ( existing . getDescription ( ) . getTarget ( ) . equals ( deployment . getTarget ( ) ) ) { throw new IllegalArgumentException ( "Can not add multiple " + Archive . class . getName ( ) + " archive deployments with the same archive name " + deployment . getName ( ) + " that target the same target " + deployment . getTarget ( ) ) ; } } } }
Validate that a deployment with a archive of the same name does not have the same taget
40,940
private List < Object > getRuleInstances ( Object testInstance ) throws Exception { List < Object > ruleInstances = new ArrayList < Object > ( ) ; List < Field > fieldsWithRuleAnnotation = SecurityActions . getFieldsWithAnnotation ( testInstance . getClass ( ) , Rule . class ) ; if ( fieldsWithRuleAnnotation . isEmpty ( ) ) { List < Method > methodsWithAnnotation = SecurityActions . getMethodsWithAnnotation ( testInstance . getClass ( ) , Rule . class ) ; if ( methodsWithAnnotation . isEmpty ( ) ) { return null ; } else { log . warning ( "Please note that methods annotated with @Rule are not fully supported in Arquillian. " + "Specifically, if you want to enrich a field in your Rule implementation class." ) ; return ruleInstances ; } } else { for ( Field field : fieldsWithRuleAnnotation ) { Object fieldInstance = field . get ( testInstance ) ; if ( isRule ( fieldInstance ) ) { ruleInstances . add ( fieldInstance ) ; } } } return ruleInstances ; }
Retrieves instances of the TestRule and MethodRule classes
40,941
public static void notNull ( final Object obj , final String message ) throws IllegalArgumentException { if ( obj == null ) { throw new IllegalArgumentException ( message ) ; } }
Checks that object is not null throws exception if it is .
40,942
public static void notNullOrEmpty ( final String string , final String message ) throws IllegalArgumentException { if ( string == null || string . length ( ) == 0 ) { throw new IllegalArgumentException ( message ) ; } }
Checks that the specified String is not null or empty throws exception if it is .
40,943
public static void stateNotNull ( final Object obj , final String message ) throws IllegalStateException { if ( obj == null ) { throw new IllegalStateException ( message ) ; } }
Checks that obj is not null throws exception if it is .
40,944
public static void configurationDirectoryExists ( final String string , final String message ) throws ConfigurationException { if ( string == null || string . length ( ) == 0 || new File ( string ) . isDirectory ( ) == false ) { throw new ConfigurationException ( message ) ; } }
Checks that string is not null and not empty and it represents a path to a valid directory
40,945
private static Object convert ( Class < ? > clazz , String value ) { if ( Integer . class . equals ( clazz ) || int . class . equals ( clazz ) ) { return Integer . valueOf ( value ) ; } else if ( Double . class . equals ( clazz ) || double . class . equals ( clazz ) ) { return Double . valueOf ( value ) ; } else if ( Long . class . equals ( clazz ) || long . class . equals ( clazz ) ) { return Long . valueOf ( value ) ; } else if ( Boolean . class . equals ( clazz ) || boolean . class . equals ( clazz ) ) { return Boolean . valueOf ( value ) ; } return value ; }
Converts a String value to the specified class .
40,946
private Object [ ] resolveArguments ( Manager manager , Object event ) { final Class < ? > [ ] argumentTypes = getMethod ( ) . getParameterTypes ( ) ; int numberOfArguments = argumentTypes . length ; Object [ ] arguments = new Object [ numberOfArguments ] ; arguments [ 0 ] = event ; for ( int i = 1 ; i < numberOfArguments ; i ++ ) { final Class < ? > argumentType = argumentTypes [ i ] ; arguments [ i ] = manager . resolve ( argumentType ) ; if ( RuntimeLogger . DEBUG && arguments [ i ] == null ) { log . warning ( String . format ( "Argument %d (of type %s) for %s#%s is null. Observer method won't be invoked." , i + 1 , argumentType . getSimpleName ( ) , getMethod ( ) . getDeclaringClass ( ) . getName ( ) , getMethod ( ) . getName ( ) ) ) ; } } return arguments ; }
Resolve all Observer method arguments . Unresolved argument types wil be null .
40,947
private boolean containsNull ( Object [ ] arguments ) { for ( Object argument : arguments ) { if ( argument == null ) { return true ; } } return false ; }
Check that all arguments were resolved . Do not invoke if not .
40,948
private void validateConfiguration ( ArquillianDescriptor desc ) { Object defaultConfig = null ; for ( ContainerDef container : desc . getContainers ( ) ) { if ( container . isDefault ( ) ) { if ( defaultConfig != null ) { throw new IllegalStateException ( "Multiple Containers defined as default, only one is allowed:\n" + defaultConfig + ":" + container ) ; } defaultConfig = container ; } } boolean containerMarkedAsDefault = defaultConfig != null ; for ( GroupDef group : desc . getGroups ( ) ) { if ( group . isGroupDefault ( ) ) { if ( defaultConfig != null ) { if ( containerMarkedAsDefault ) { throw new IllegalStateException ( "Multiple Containers/Groups defined as default, only one is allowed:\n" + defaultConfig + ":" + group ) ; } throw new IllegalStateException ( "Multiple Groups defined as default, only one is allowed:\n" + defaultConfig + ":" + group ) ; } defaultConfig = group ; } ContainerDef defaultInGroup = null ; for ( ContainerDef container : group . getGroupContainers ( ) ) { if ( container . isDefault ( ) ) { if ( defaultInGroup != null ) { throw new IllegalStateException ( "Multiple Containers within Group defined as default, only one is allowed:\n" + group ) ; } defaultInGroup = container ; } } } }
Validate that the Configuration given is sane
40,949
public static String fileAsString ( String filename ) { File classpathFile = getClasspathFile ( filename ) ; return fileAsString ( classpathFile ) ; }
Returns the content of a file with specified filename
40,950
public static InputStream fileAsStream ( String filename ) { File classpathFile = getClasspathFile ( filename ) ; return fileAsStream ( classpathFile ) ; }
Returns the input stream of a file with specified filename
40,951
public static InputStream fileAsStream ( File file ) { try { return new BufferedInputStream ( new FileInputStream ( file ) ) ; } catch ( FileNotFoundException e ) { throw LOG . fileNotFoundException ( file . getAbsolutePath ( ) , e ) ; } }
Returns the input stream of a file .
40,952
public static String join ( String delimiter , String ... parts ) { if ( parts == null ) { return null ; } if ( delimiter == null ) { delimiter = "" ; } StringBuilder stringBuilder = new StringBuilder ( ) ; for ( int i = 0 ; i < parts . length ; i ++ ) { if ( i > 0 ) { stringBuilder . append ( delimiter ) ; } stringBuilder . append ( parts [ i ] ) ; } return stringBuilder . toString ( ) ; }
Joins a list of Strings to a single one .
40,953
protected void logDebug ( String id , String messageTemplate , Object ... parameters ) { if ( delegateLogger . isDebugEnabled ( ) ) { String msg = formatMessageTemplate ( id , messageTemplate ) ; delegateLogger . debug ( msg , parameters ) ; } }
Logs a DEBUG message
40,954
protected void logInfo ( String id , String messageTemplate , Object ... parameters ) { if ( delegateLogger . isInfoEnabled ( ) ) { String msg = formatMessageTemplate ( id , messageTemplate ) ; delegateLogger . info ( msg , parameters ) ; } }
Logs an INFO message
40,955
protected void logWarn ( String id , String messageTemplate , Object ... parameters ) { if ( delegateLogger . isWarnEnabled ( ) ) { String msg = formatMessageTemplate ( id , messageTemplate ) ; delegateLogger . warn ( msg , parameters ) ; } }
Logs an WARN message
40,956
protected void logError ( String id , String messageTemplate , Object ... parameters ) { if ( delegateLogger . isErrorEnabled ( ) ) { String msg = formatMessageTemplate ( id , messageTemplate ) ; delegateLogger . error ( msg , parameters ) ; } }
Logs an ERROR message
40,957
protected String formatMessageTemplate ( String id , String messageTemplate ) { return projectCode + "-" + componentId + id + " " + messageTemplate ; }
Formats a message template
40,958
protected String exceptionMessage ( String id , String messageTemplate , Object ... parameters ) { String formattedTemplate = formatMessageTemplate ( id , messageTemplate ) ; if ( parameters == null || parameters . length == 0 ) { return formattedTemplate ; } else { return MessageFormatter . arrayFormat ( formattedTemplate , parameters ) . getMessage ( ) ; } }
Prepares an exception message
40,959
public static void ensureNotNull ( String parameterName , Object value ) { if ( value == null ) { throw LOG . parameterIsNullException ( parameterName ) ; } }
Ensures that the parameter is not null .
40,960
@ SuppressWarnings ( "unchecked" ) public static < T > T ensureParamInstanceOf ( String objectName , Object object , Class < T > type ) { if ( type . isAssignableFrom ( object . getClass ( ) ) ) { return ( T ) object ; } else { throw LOG . unsupportedParameterType ( objectName , object , type ) ; } }
Ensure the object is of a given type and return the casted object
40,961
private static int [ ] getFactors ( int _value , int _max ) { final int factors [ ] = new int [ MAX_GROUP_SIZE ] ; int factorIdx = 0 ; for ( int possibleFactor = 1 ; possibleFactor <= _max ; possibleFactor ++ ) { if ( ( _value % possibleFactor ) == 0 ) { factors [ factorIdx ++ ] = possibleFactor ; } } return ( Arrays . copyOf ( factors , factorIdx ) ) ; }
Determine the set of factors for a given value .
40,962
public int getNumGroups ( int _dim ) { return ( _dim == 0 ? ( globalSize_0 / localSize_0 ) : ( _dim == 1 ? ( globalSize_1 / localSize_1 ) : ( globalSize_2 / localSize_2 ) ) ) ; }
Get the number of groups for the given dimension .
40,963
public double getElapsedTimeCurrentThread ( int stage ) { if ( stage == ProfilingEvent . START . ordinal ( ) ) { return 0 ; } Accumulator acc = getAccForThread ( ) ; return acc == null ? Double . NaN : ( acc . currentTimes [ stage ] - acc . currentTimes [ stage - 1 ] ) / MILLION ; }
Elapsed time for a single event only and for the current thread i . e . since the previous stage rather than from the start .
40,964
public double getCumulativeElapsedTimeCurrrentThread ( ProfilingEvent stage ) { Accumulator acc = getAccForThread ( ) ; return acc == null ? Double . NaN : acc . accumulatedTimes [ stage . ordinal ( ) ] / MILLION ; }
Elapsed time for a single event only i . e . since the previous stage rather than from the start summed over all executions for the current thread if it has executed the kernel on the device assigned to this KernelDeviceProfile instance .
40,965
public double getCumulativeElapsedTimeAllCurrentThread ( ) { double sum = 0 ; Accumulator acc = getAccForThread ( ) ; if ( acc == null ) { return sum ; } for ( int i = 1 ; i <= ProfilingEvent . EXECUTED . ordinal ( ) ; ++ i ) { sum += acc . accumulatedTimes [ i ] ; } return sum ; }
Elapsed time of entire execution summed over all executions for the current thread if it has executed the kernel on the device assigned to this KernelDeviceProfile instance .
40,966
public double getElapsedTimeLastThread ( int stage ) { if ( stage == ProfilingEvent . START . ordinal ( ) ) { return 0 ; } Accumulator acc = lastAccumulator . get ( ) ; return acc == null ? Double . NaN : ( acc . currentTimes [ stage ] - acc . currentTimes [ stage - 1 ] ) / MILLION ; }
Elapsed time for a single event only and for the last thread that finished executing a kernel i . e . single event only - since the previous stage rather than from the start .
40,967
public double getCumulativeElapsedTimeGlobal ( ProfilingEvent stage ) { final long [ ] accumulatedTimesHolder = new long [ NUM_EVENTS ] ; globalAcc . consultAccumulatedTimes ( accumulatedTimesHolder ) ; return accumulatedTimesHolder [ stage . ordinal ( ) ] / MILLION ; }
Elapsed time for a single event only i . e . since the previous stage rather than from the start summed over all executions for the last thread that executed this KernelDeviceProfile instance respective kernel and device .
40,968
public double getCumulativeElapsedTimeAllGlobal ( ) { final long [ ] accumulatedTimesHolder = new long [ NUM_EVENTS ] ; globalAcc . consultAccumulatedTimes ( accumulatedTimesHolder ) ; double sum = 0 ; for ( int i = 1 ; i <= ProfilingEvent . EXECUTED . ordinal ( ) ; ++ i ) { sum += accumulatedTimesHolder [ i ] ; } return sum ; }
Elapsed time of entire execution summed over all executions for all the threads that executed the kernel on this device .
40,969
public boolean isSuperClass ( String otherClassName ) { if ( getClassWeAreModelling ( ) . getName ( ) . equals ( otherClassName ) ) { return true ; } else if ( superClazz != null ) { return superClazz . isSuperClass ( otherClassName ) ; } else { return false ; } }
Determine if this is the superclass of some other named class .
40,970
public boolean isSuperClass ( Class < ? > other ) { Class < ? > s = other . getSuperclass ( ) ; while ( s != null ) { if ( ( getClassWeAreModelling ( ) == s ) || ( getClassWeAreModelling ( ) . getName ( ) . equals ( s . getName ( ) ) ) ) { return true ; } s = s . getSuperclass ( ) ; } return false ; }
Determine if this is the superclass of some other class .
40,971
public Integer getPrivateMemorySize ( String fieldName ) throws ClassParseException { if ( CacheEnabler . areCachesEnabled ( ) ) return privateMemorySizes . computeIfAbsent ( fieldName ) ; return computePrivateMemorySize ( fieldName ) ; }
If a field does not satisfy the private memory conditions null otherwise the size of private memory required .
40,972
public ClassModelMethod getMethod ( MethodEntry _methodEntry , boolean _isSpecial ) { final String entryClassNameInDotForm = _methodEntry . getClassEntry ( ) . getNameUTF8Entry ( ) . getUTF8 ( ) . replace ( '/' , '.' ) ; if ( _isSpecial && ( superClazz != null ) && superClazz . isSuperClass ( entryClassNameInDotForm ) ) { if ( logger . isLoggable ( Level . FINE ) ) { logger . fine ( "going to look in super:" + superClazz . getClassWeAreModelling ( ) . getName ( ) + " on behalf of " + entryClassNameInDotForm ) ; } return superClazz . getMethod ( _methodEntry , false ) ; } NameAndTypeEntry nameAndTypeEntry = _methodEntry . getNameAndTypeEntry ( ) ; ClassModelMethod methodOrNull = getMethodOrNull ( nameAndTypeEntry . getNameUTF8Entry ( ) . getUTF8 ( ) , nameAndTypeEntry . getDescriptorUTF8Entry ( ) . getUTF8 ( ) ) ; if ( methodOrNull == null ) return superClazz != null ? superClazz . getMethod ( _methodEntry , false ) : ( null ) ; return methodOrNull ; }
Look up a ConstantPool MethodEntry and return the corresponding Method .
40,973
public MethodModel getMethodModel ( String _name , String _signature ) throws AparapiException { if ( CacheEnabler . areCachesEnabled ( ) ) return methodModelCache . computeIfAbsent ( MethodKey . of ( _name , _signature ) ) ; else { final ClassModelMethod method = getMethod ( _name , _signature ) ; return new MethodModel ( method ) ; } }
Create a MethodModel for a given method name and signature .
40,974
public void setProfileReport ( final long reportId , final long [ ] _currentTimes ) { id = reportId ; System . arraycopy ( _currentTimes , 0 , currentTimes , 0 , NUM_EVENTS ) ; }
Sets specific report data .
40,975
public double getElapsedTime ( int stage ) { if ( stage == ProfilingEvent . START . ordinal ( ) ) { return 0 ; } return ( currentTimes [ stage ] - currentTimes [ stage - 1 ] ) / MILLION ; }
Elapsed time for a single event only i . e . since the previous stage rather than from the start .
40,976
public void configure ( ) { if ( configurator != null && ! underConfiguration . get ( ) && underConfiguration . compareAndSet ( false , true ) ) { try { configurator . configure ( this ) ; } finally { underConfiguration . set ( false ) ; } } }
Called by the underlying Aparapi OpenCL platform upon device detection .
40,977
public static List < OpenCLDevice > listDevices ( TYPE type ) { final OpenCLPlatform platform = new OpenCLPlatform ( 0 , null , null , null ) ; final ArrayList < OpenCLDevice > results = new ArrayList < > ( ) ; for ( final OpenCLPlatform p : platform . getOpenCLPlatforms ( ) ) { for ( final OpenCLDevice device : p . getOpenCLDevices ( ) ) { if ( type == null || device . getType ( ) == type ) { results . add ( device ) ; } } } return results ; }
List OpenCLDevices of a given TYPE or all OpenCLDevices if type == null .
40,978
void onStart ( Device device ) { KernelDeviceProfile currentDeviceProfile = deviceProfiles . get ( device ) ; if ( currentDeviceProfile == null ) { currentDeviceProfile = new KernelDeviceProfile ( this , kernelClass , device ) ; KernelDeviceProfile existingProfile = deviceProfiles . putIfAbsent ( device , currentDeviceProfile ) ; if ( existingProfile != null ) { currentDeviceProfile = existingProfile ; } } currentDeviceProfile . onEvent ( ProfilingEvent . START ) ; currentDevice . set ( device ) ; }
Starts a profiling information gathering sequence for the current thread invoking this method regarding the specified execution device .
40,979
void onEvent ( Device device , ProfilingEvent event ) { if ( event == null ) { logger . log ( Level . WARNING , "Discarding profiling event " + event + " for null device, for Kernel class: " + kernelClass . getName ( ) ) ; return ; } final KernelDeviceProfile deviceProfile = deviceProfiles . get ( device ) ; switch ( event ) { case CLASS_MODEL_BUILT : case OPENCL_GENERATED : case INIT_JNI : case OPENCL_COMPILED : case PREPARE_EXECUTE : case EXECUTED : { if ( deviceProfile == null ) { logger . log ( Level . SEVERE , "Error in KernelProfile, no currentDevice (synchronization error?" ) ; } deviceProfile . onEvent ( event ) ; break ; } case START : throw new IllegalArgumentException ( "must use onStart(Device) to start profiling" ) ; default : throw new IllegalArgumentException ( "Unhandled event " + event ) ; } }
Updates the profiling information for the current thread invoking this method regarding the specified execution device .
40,980
public String convertType ( String _typeDesc , boolean useClassModel , boolean isLocal ) { if ( _typeDesc . equals ( "Z" ) || _typeDesc . equals ( "boolean" ) ) { return ( cvtBooleanToChar ) ; } else if ( _typeDesc . equals ( "[Z" ) || _typeDesc . equals ( "boolean[]" ) ) { return isLocal ? ( cvtBooleanArrayToChar ) : ( cvtBooleanArrayToCharStar ) ; } else if ( _typeDesc . equals ( "B" ) || _typeDesc . equals ( "byte" ) ) { return ( cvtByteToChar ) ; } else if ( _typeDesc . equals ( "[B" ) || _typeDesc . equals ( "byte[]" ) ) { return isLocal ? ( cvtByteArrayToChar ) : ( cvtByteArrayToCharStar ) ; } else if ( _typeDesc . equals ( "C" ) || _typeDesc . equals ( "char" ) ) { return ( cvtCharToShort ) ; } else if ( _typeDesc . equals ( "[C" ) || _typeDesc . equals ( "char[]" ) ) { return isLocal ? ( cvtCharArrayToShort ) : ( cvtCharArrayToShortStar ) ; } else if ( _typeDesc . equals ( "[I" ) || _typeDesc . equals ( "int[]" ) ) { return isLocal ? ( cvtIntArrayToInt ) : ( cvtIntArrayToIntStar ) ; } else if ( _typeDesc . equals ( "[F" ) || _typeDesc . equals ( "float[]" ) ) { return isLocal ? ( cvtFloatArrayToFloat ) : ( cvtFloatArrayToFloatStar ) ; } else if ( _typeDesc . equals ( "[D" ) || _typeDesc . equals ( "double[]" ) ) { return isLocal ? ( cvtDoubleArrayToDouble ) : ( cvtDoubleArrayToDoubleStar ) ; } else if ( _typeDesc . equals ( "[J" ) || _typeDesc . equals ( "long[]" ) ) { return isLocal ? ( cvtLongArrayToLong ) : ( cvtLongArrayToLongStar ) ; } else if ( _typeDesc . equals ( "[S" ) || _typeDesc . equals ( "short[]" ) ) { return isLocal ? ( cvtShortArrayToShort ) : ( cvtShortArrayToShortStar ) ; } else if ( "[Ljava/util/concurrent/atomic/AtomicInteger;" . equals ( _typeDesc ) || "[Ljava.util.concurrent.atomic.AtomicInteger;" . equals ( _typeDesc ) ) { return ( cvtIntArrayToIntStar ) ; } if ( useClassModel ) { return ( ClassModel . convert ( _typeDesc , "" , true ) ) ; } else { return _typeDesc ; } }
These three convert functions are here to perform any type conversion that may be required between Java and OpenCL .
40,981
private ClassModel getClassModelFromArg ( KernelArg arg , final Class < ? > arrayClass ) { ClassModel c = null ; if ( arg . getObjArrayElementModel ( ) == null ) { final String tmp = arrayClass . getName ( ) . substring ( 2 ) . replace ( '/' , '.' ) ; final String arrayClassInDotForm = tmp . substring ( 0 , tmp . length ( ) - 1 ) ; if ( logger . isLoggable ( Level . FINE ) ) { logger . fine ( "looking for type = " + arrayClassInDotForm ) ; } c = entryPoint . getObjectArrayFieldsClasses ( ) . get ( arrayClassInDotForm ) ; arg . setObjArrayElementModel ( c ) ; } else { c = arg . getObjArrayElementModel ( ) ; } assert c != null : "should find class for elements " + arrayClass . getName ( ) ; return c ; }
Helper method to retrieve the class model from a kernel argument .
40,982
public boolean allocateArrayBufferIfFirstTimeOrArrayChanged ( KernelArg arg , Object newRef , final int objArraySize , final int totalStructSize , final int totalBufferSize ) { boolean didReallocate = false ; if ( ( arg . getObjArrayBuffer ( ) == null ) || ( newRef != arg . getArray ( ) ) ) { final ByteBuffer structBuffer = ByteBuffer . allocate ( totalBufferSize ) ; arg . setObjArrayByteBuffer ( structBuffer . order ( ByteOrder . LITTLE_ENDIAN ) ) ; arg . setObjArrayBuffer ( arg . getObjArrayByteBuffer ( ) . array ( ) ) ; didReallocate = true ; if ( logger . isLoggable ( Level . FINEST ) ) { logger . finest ( "objArraySize = " + objArraySize + " totalStructSize= " + totalStructSize + " totalBufferSize=" + totalBufferSize ) ; } } else { arg . getObjArrayByteBuffer ( ) . clear ( ) ; } return didReallocate ; }
Helper method that manages the memory allocation for storing the kernel argument data so that the data can be exchanged between the host and the OpenCL device .
40,983
public boolean isDeviceAmongPreferredDevices ( Device device ) { maybeSetUpDefaultPreferredDevices ( ) ; boolean result = false ; synchronized ( this ) { result = preferredDevices . get ( ) . contains ( device ) ; } return result ; }
Validates if the specified devices is among the preferred devices for executing the kernel associated with the current kernel preferences .
40,984
public static OpenCLKernel createKernel ( OpenCLProgram _program , String _kernelName , List < OpenCLArgDescriptor > _args ) { final OpenCLArgDescriptor [ ] argArray = _args . toArray ( new OpenCLArgDescriptor [ 0 ] ) ; final OpenCLKernel oclk = new OpenCLKernel ( ) . createKernelJNI ( _program , _kernelName , argArray ) ; for ( final OpenCLArgDescriptor arg : argArray ) { arg . kernel = oclk ; } return oclk ; }
This method is used to create a new Kernel from JNI
40,985
public boolean doesNotContainContinueOrBreak ( Instruction _start , Instruction _extent ) { boolean ok = true ; boolean breakOrContinue = false ; for ( Instruction i = _start ; i != null ; i = i . getNextExpr ( ) ) { if ( i . isBranch ( ) ) { if ( i . asBranch ( ) . isForwardUnconditional ( ) && i . asBranch ( ) . getTarget ( ) . isAfter ( _extent ) ) { breakOrContinue = true ; } else { ok = false ; break ; } } } if ( ok ) { if ( breakOrContinue ) { for ( Instruction i = _start ; i != null ; i = i . getNextExpr ( ) ) { if ( i . isBranch ( ) && i . asBranch ( ) . isForwardUnconditional ( ) && i . asBranch ( ) . getTarget ( ) . isAfter ( _extent ) ) { i . asBranch ( ) . setBreakOrContinue ( true ) ; } } } } return ( ok ) ; }
Determine whether the sequence of instructions from _start to _extent is free of branches which extend beyond _extent .
40,986
public Instruction add ( Instruction _instruction ) { if ( head == null ) { head = _instruction ; } else { _instruction . setPrevExpr ( tail ) ; tail . setNextExpr ( _instruction ) ; } tail = _instruction ; logger . log ( Level . FINE , "After PUSH of " + _instruction + " tail=" + tail ) ; return ( tail ) ; }
Add this instruction to the end of the list .
40,987
public void replaceInclusive ( Instruction _head , Instruction _tail , Instruction _newOne ) { _newOne . setNextExpr ( null ) ; _newOne . setPrevExpr ( null ) ; final Instruction prevHead = _head . getPrevExpr ( ) ; if ( _tail == null ) { _newOne . setPrevExpr ( prevHead ) ; prevHead . setNextExpr ( _newOne ) ; tail = _newOne ; } else { final Instruction tailNext = _tail . getNextExpr ( ) ; if ( prevHead == null ) { if ( tailNext == null ) { head = tail = _newOne ; } else { _newOne . setNextExpr ( head ) ; head . setPrevExpr ( _newOne ) ; head = _newOne ; } } else if ( tailNext == null ) { _newOne . setPrevExpr ( prevHead ) ; prevHead . setNextExpr ( _newOne ) ; tail = _newOne ; _head . setPrevExpr ( null ) ; } else { _newOne . setNextExpr ( tailNext ) ; _newOne . setPrevExpr ( prevHead ) ; prevHead . setNextExpr ( _newOne ) ; tailNext . setPrevExpr ( _newOne ) ; } _tail . setNextExpr ( null ) ; _head . setPrevExpr ( null ) ; } }
Inclusive replace between _head and _tail with _newOne .
40,988
public static < T extends Kernel > T sharedKernelInstance ( Class < T > kernelClass ) { return instance ( ) . getSharedKernelInstance ( kernelClass ) ; }
This method returns a shared instance of a given Kernel subclass . The kernelClass needs a no - args constructor which need not be public .
40,989
public void deoptimizeReverseBranches ( ) { for ( Instruction instruction = pcHead ; instruction != null ; instruction = instruction . getNextPC ( ) ) { if ( instruction . isBranch ( ) ) { final Branch branch = instruction . asBranch ( ) ; if ( branch . isReverse ( ) ) { final Instruction target = branch . getTarget ( ) ; final LinkedList < Branch > list = target . getReverseUnconditionalBranches ( ) ; if ( ( list != null ) && ( list . size ( ) > 0 ) && ( list . get ( list . size ( ) - 1 ) != branch ) ) { final Branch unconditional = list . get ( list . size ( ) - 1 ) . asBranch ( ) ; branch . retarget ( unconditional ) ; } } } } }
Javac optimizes some branches to avoid goto - > goto branch - > goto etc .
40,990
void checkForSetter ( Map < Integer , Instruction > pcMap ) throws ClassParseException { final String methodName = getMethod ( ) . getName ( ) ; if ( methodName . startsWith ( "set" ) ) { final String rawVarNameCandidate = methodName . substring ( 3 ) ; final String firstLetter = rawVarNameCandidate . substring ( 0 , 1 ) . toLowerCase ( ) ; final String varNameCandidateCamelCased = rawVarNameCandidate . replaceFirst ( rawVarNameCandidate . substring ( 0 , 1 ) , firstLetter ) ; String accessedFieldName = null ; final Instruction instruction = expressionList . getHead ( ) ; if ( ( instruction instanceof AssignToInstanceField ) && ( expressionList . getTail ( ) instanceof Return ) && ( pcMap . size ( ) == 4 ) ) { final Instruction prev = instruction . getPrevPC ( ) ; if ( prev instanceof AccessLocalVariable ) { final FieldEntry field = ( ( AssignToInstanceField ) instruction ) . getConstantPoolFieldEntry ( ) ; accessedFieldName = field . getNameAndTypeEntry ( ) . getNameUTF8Entry ( ) . getUTF8 ( ) ; if ( accessedFieldName . equals ( varNameCandidateCamelCased ) ) { final String fieldType = field . getNameAndTypeEntry ( ) . getDescriptorUTF8Entry ( ) . getUTF8 ( ) ; final String setterArgType = getMethod ( ) . getDescriptor ( ) . substring ( 1 , 2 ) ; assert fieldType . length ( ) == 1 : " can only use basic type getters" ; if ( fieldType . equals ( setterArgType ) ) { if ( logger . isLoggable ( Level . FINE ) ) { logger . fine ( "Found " + methodName + " as a setter for " + varNameCandidateCamelCased . toLowerCase ( ) + " of type " + fieldType ) ; } methodIsSetter = true ; setAccessorVariableFieldEntry ( field ) ; if ( fieldType . equals ( "B" ) || fieldType . equals ( "Z" ) ) { usesByteWrites = true ; } assert methodIsGetter == false : " cannot be both" ; } else { throw new ClassParseException ( ClassParseException . TYPE . BADSETTERTYPEMISMATCH , methodName ) ; } } else { throw new ClassParseException ( ClassParseException . TYPE . BADSETTERTYPEMISMATCH , methodName ) ; } } } } }
Determine if this method is a setter and record the accessed field if so
40,991
public static String getSimpleName ( Class < ? > klass ) { String simpleName = klass . getSimpleName ( ) ; if ( simpleName . isEmpty ( ) ) { String fullName = klass . getName ( ) ; int index = fullName . lastIndexOf ( '.' ) ; simpleName = ( index < 0 ) ? fullName : fullName . substring ( index + 1 ) ; } return simpleName ; }
Avoids getting dumb empty names for anonymous inners .
40,992
public void loadFromResource ( String resource , Candidate . CandidateType type ) throws IOException { InputStream candidatesConfig = classloader . getResourceAsStream ( resource ) ; if ( candidatesConfig == null ) { throw new IOException ( "Resource '" + resource + "' not found" ) ; } try { loadFrom ( candidatesConfig , type ) ; } finally { candidatesConfig . close ( ) ; } }
Load a candidate property file
40,993
public static void main ( String [ ] args ) { TextReporter reporter = new TextReporter ( System . out , System . err ) ; run ( reporter ) ; if ( reporter . hasErrors ( ) ) { System . exit ( 1 ) ; } }
Main class of the TCK . Can also be called as a normal method from an application server .
40,994
public static void run ( Reporter reporter ) { TCK tck = new TCK ( new ObjenesisStd ( ) , new ObjenesisSerializer ( ) , reporter ) ; tck . runTests ( ) ; }
Run the full test suite using standard Objenesis instances
40,995
public static SortedSet < String > getClassesForPackage ( Package pkg , ClassLoader classLoader ) { SortedSet < String > classes = new TreeSet < > ( new Comparator < String > ( ) { public int compare ( String o1 , String o2 ) { String simpleName1 = getSimpleName ( o1 ) ; String simpleName2 = getSimpleName ( o2 ) ; return simpleName1 . compareTo ( simpleName2 ) ; } private String getSimpleName ( String className ) { return className . substring ( className . lastIndexOf ( '.' ) ) ; } } ) ; String pkgname = pkg . getName ( ) ; String relPath = pkgname . replace ( '.' , '/' ) ; Enumeration < URL > resources ; try { resources = classLoader . getResources ( relPath ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } while ( resources . hasMoreElements ( ) ) { URL resource = resources . nextElement ( ) ; if ( resource . toString ( ) . startsWith ( "jar:" ) ) { processJarfile ( resource , pkgname , classes ) ; } else { processDirectory ( new File ( resource . getPath ( ) ) , pkgname , classes ) ; } } return classes ; }
Return all the classes in this package recursively .
40,996
public static byte [ ] readClass ( String className ) throws IOException { className = ClassUtils . classNameToResource ( className ) ; byte [ ] b = new byte [ 2500 ] ; int length ; try ( InputStream in = ClassDefinitionUtils . class . getClassLoader ( ) . getResourceAsStream ( className ) ) { length = in . read ( b ) ; } if ( length >= 2500 ) { throw new IllegalArgumentException ( "The class is longer that 2500 bytes which is currently unsupported" ) ; } byte [ ] copy = new byte [ length ] ; System . arraycopy ( b , 0 , copy , 0 , length ) ; return copy ; }
Read the bytes of a class from the classpath
40,997
public static void writeClass ( String fileName , byte [ ] bytes ) throws IOException { try ( BufferedOutputStream out = new BufferedOutputStream ( new FileOutputStream ( fileName ) ) ) { out . write ( bytes ) ; } }
Write all class bytes to a file .
40,998
@ SuppressWarnings ( "unchecked" ) public static < T > Class < T > getExistingClass ( ClassLoader classLoader , String className ) { try { return ( Class < T > ) Class . forName ( className , true , classLoader ) ; } catch ( ClassNotFoundException e ) { return null ; } }
Check if this class already exists in the class loader and return it if it does
40,999
public void registerCandidate ( Class < ? > candidateClass , String description , Candidate . CandidateType type ) { Candidate candidate = new Candidate ( candidateClass , description , type ) ; int index = candidates . indexOf ( candidate ) ; if ( index >= 0 ) { Candidate existingCandidate = candidates . get ( index ) ; if ( ! description . equals ( existingCandidate . getDescription ( ) ) ) { throw new IllegalStateException ( "Two different descriptions for candidate " + candidateClass . getName ( ) ) ; } existingCandidate . getTypes ( ) . add ( type ) ; } else { candidates . add ( candidate ) ; } }
Register a candidate class to attempt to instantiate .