idx
int64 0
41.2k
| question
stringlengths 83
4.15k
| target
stringlengths 5
715
|
|---|---|---|
35,000
|
public static Object newInstance ( Class clazz , ArgumentResolver resolver ) { Validate . argumentIsNotNull ( clazz ) ; for ( Constructor constructor : clazz . getDeclaredConstructors ( ) ) { if ( isPrivate ( constructor ) || isProtected ( constructor ) ) { continue ; } Class [ ] types = constructor . getParameterTypes ( ) ; Object [ ] params = new Object [ types . length ] ; for ( int i = 0 ; i < types . length ; i ++ ) { try { params [ i ] = resolver . resolve ( types [ i ] ) ; } catch ( JaversException e ) { logger . error ( "failed to create new instance of " + clazz . getName ( ) + ", argument resolver for arg[" + i + "] " + types [ i ] . getName ( ) + " thrown exception: " + e . getMessage ( ) ) ; throw e ; } } try { constructor . setAccessible ( true ) ; return constructor . newInstance ( params ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } throw new JaversException ( JaversExceptionCode . NO_PUBLIC_CONSTRUCTOR , clazz . getName ( ) ) ; }
|
Creates new instance of public or package - private class . Calls first not - private constructor
|
35,001
|
JaversType spawn ( Type baseJavaType ) { try { Constructor c = this . getClass ( ) . getConstructor ( Type . class ) ; return ( JaversType ) c . newInstance ( new Object [ ] { baseJavaType } ) ; } catch ( ReflectiveOperationException exception ) { throw new RuntimeException ( "error calling Constructor for " + this . getClass ( ) . getName ( ) , exception ) ; } }
|
Factory method delegates to self constructor
|
35,002
|
private String formatMaybeIpv6 ( String address ) { String openBracket = "[" ; String closeBracket = "]" ; if ( address . contains ( ":" ) && ! address . startsWith ( openBracket ) && ! address . endsWith ( closeBracket ) ) { return openBracket + address + closeBracket ; } return address ; }
|
This isn t very precise ; org . jboss . as . network . NetworkUtils has better implementation but that s in a private module .
|
35,003
|
public void handleRequest ( HttpServerExchange exchange ) throws Exception { Account account = exchange . getSecurityContext ( ) . getAuthenticatedAccount ( ) ; if ( account != null && account . getPrincipal ( ) instanceof JsonWebToken ) { JsonWebToken token = ( JsonWebToken ) account . getPrincipal ( ) ; PrincipalProducer myInstance = CDI . current ( ) . select ( PrincipalProducer . class ) . get ( ) ; myInstance . setJsonWebToken ( token ) ; } next . handleRequest ( exchange ) ; }
|
If there is a JWTAccount installed in the exchange security context create
|
35,004
|
public static Options defaultOptions ( ) { return new Options ( HELP , CONFIG_HELP , YAML_HELP , VERSION , PROPERTY , PROPERTIES_URL , SERVER_CONFIG , CONFIG , PROFILES , BIND ) ; }
|
Default set of options
|
35,005
|
public < T > void put ( Option < T > key , T value ) { this . values . put ( key , value ) ; }
|
Put a value under a given key .
|
35,006
|
@ SuppressWarnings ( "unchecked" ) public < T > T get ( Option < T > key ) { T v = ( T ) this . values . get ( key ) ; if ( v == null ) { v = key . defaultValue ( ) ; this . values . put ( key , v ) ; } return v ; }
|
Retrieve a value under a given key .
|
35,007
|
public void applyProperties ( Swarm swarm ) throws IOException { URL propsUrl = get ( PROPERTIES_URL ) ; if ( propsUrl != null ) { Properties urlProps = new Properties ( ) ; urlProps . load ( propsUrl . openStream ( ) ) ; for ( String name : urlProps . stringPropertyNames ( ) ) { swarm . withProperty ( name , urlProps . getProperty ( name ) ) ; } } Properties props = get ( PROPERTY ) ; for ( String name : props . stringPropertyNames ( ) ) { swarm . withProperty ( name , props . getProperty ( name ) ) ; } if ( get ( BIND ) != null ) { swarm . withProperty ( SwarmProperties . BIND_ADDRESS , get ( BIND ) ) ; } }
|
Apply properties to the system properties .
|
35,008
|
public void applyConfigurations ( Swarm swarm ) throws IOException { if ( get ( SERVER_CONFIG ) != null ) { swarm . withXmlConfig ( get ( SERVER_CONFIG ) ) ; } if ( get ( CONFIG ) != null ) { List < URL > configs = get ( CONFIG ) ; for ( URL config : configs ) { swarm . withConfig ( config ) ; } } if ( get ( PROFILES ) != null ) { List < String > profiles = get ( PROFILES ) ; for ( String profile : profiles ) { swarm . withProfile ( profile ) ; } } }
|
Apply configuration to the container .
|
35,009
|
public void apply ( Swarm swarm ) throws IOException , ModuleLoadException { applyProperties ( swarm ) ; applyConfigurations ( swarm ) ; if ( get ( HELP ) ) { displayVersion ( System . err ) ; System . err . println ( ) ; displayHelp ( System . err ) ; System . exit ( 0 ) ; } if ( get ( CONFIG_HELP ) != null ) { displayConfigHelp ( System . err , get ( CONFIG_HELP ) ) ; System . exit ( 0 ) ; } if ( get ( YAML_HELP ) != null ) { dumpYaml ( System . err , get ( YAML_HELP ) ) ; System . exit ( 0 ) ; } if ( get ( VERSION ) ) { displayVersion ( System . err ) ; } }
|
Apply properties and configuration from the parsed commandline to a container .
|
35,010
|
public static CommandLine parse ( Options options , String ... args ) throws Exception { return CommandLineParser . parse ( options , args ) ; }
|
Parse an array of arguments using specific options .
|
35,011
|
public static ResourceLoader getModuleResourceLoader ( final String rootPath , final String loaderPath , final String loaderName ) { if ( Holder . JAR_FILE != null ) { return new JarFileResourceLoader ( loaderName , Holder . JAR_FILE , Holder . FILE_SYSTEM . getPath ( rootPath , loaderPath ) . toString ( ) ) ; } return ResourceLoaders . createFileResourceLoader ( loaderPath , new File ( rootPath ) ) ; }
|
Creates a new resource loader for the environment .
|
35,012
|
public AuthenticationMechanismOutcome authenticate ( HttpServerExchange exchange , SecurityContext securityContext ) { List < String > authHeaders = exchange . getRequestHeaders ( ) . get ( AUTHORIZATION ) ; if ( authHeaders != null ) { String bearerToken = null ; for ( String current : authHeaders ) { if ( current . toLowerCase ( Locale . ENGLISH ) . startsWith ( "bearer " ) ) { bearerToken = current . substring ( 7 ) ; if ( UndertowLogger . SECURITY_LOGGER . isTraceEnabled ( ) ) { UndertowLogger . SECURITY_LOGGER . tracef ( "Bearer token: %s" , bearerToken ) ; } try { identityManager = securityContext . getIdentityManager ( ) ; JWTCredential credential = new JWTCredential ( bearerToken , authContextInfo ) ; if ( UndertowLogger . SECURITY_LOGGER . isTraceEnabled ( ) ) { UndertowLogger . SECURITY_LOGGER . tracef ( "Bearer token: %s" , bearerToken ) ; } Account account = identityManager . verify ( credential . getName ( ) , credential ) ; if ( account != null ) { JsonWebToken jwtPrincipal = ( JsonWebToken ) account . getPrincipal ( ) ; securityContext . authenticationComplete ( account , "MP-JWT" , false ) ; org . jboss . security . SecurityContext jbSC = SecurityContextAssociation . getSecurityContext ( ) ; Subject subject = jbSC . getUtil ( ) . getSubject ( ) ; jbSC . getUtil ( ) . createSubjectInfo ( jwtPrincipal , bearerToken , subject ) ; RoleGroup roles = extract ( subject ) ; jbSC . getUtil ( ) . setRoles ( roles ) ; UndertowLogger . SECURITY_LOGGER . debugf ( "Authenticated caller(%s) for path(%s) with roles: %s" , credential . getName ( ) , exchange . getRequestPath ( ) , account . getRoles ( ) ) ; return AuthenticationMechanismOutcome . AUTHENTICATED ; } else { UndertowLogger . SECURITY_LOGGER . info ( "Failed to authenticate JWT bearer token" ) ; return AuthenticationMechanismOutcome . NOT_AUTHENTICATED ; } } catch ( Exception e ) { UndertowLogger . SECURITY_LOGGER . infof ( e , "Failed to validate JWT bearer token" ) ; return AuthenticationMechanismOutcome . NOT_AUTHENTICATED ; } } } } return AuthenticationMechanismOutcome . NOT_ATTEMPTED ; }
|
Extract the Authorization header and validate the bearer token if it exists . If it does and is validated this builds the org . jboss . security . SecurityContext authenticated Subject that drives the container APIs as well as the authorization layers .
|
35,013
|
protected RoleGroup extract ( Subject subject ) { Optional < Principal > match = subject . getPrincipals ( ) . stream ( ) . filter ( g -> g . getName ( ) . equals ( SecurityConstants . ROLES_IDENTIFIER ) ) . findFirst ( ) ; Group rolesGroup = ( Group ) match . get ( ) ; RoleGroup roles = new SimpleRoleGroup ( rolesGroup ) ; return roles ; }
|
Extract the Roles group and return it as a RoleGroup
|
35,014
|
public ConfigViewImpl withProperties ( Properties properties ) { if ( properties != null ) { this . properties = properties ; this . strategy . withProperties ( properties ) ; } return this ; }
|
Supply explicit properties object for introspection and outrespection .
|
35,015
|
private Set < String > getPackagesForScanning ( WARArchive deployment ) { final Set < String > packages = new TreeSet < > ( ) ; if ( indexView != null ) { DotName dotName = DotName . createSimple ( Api . class . getName ( ) ) ; Collection < AnnotationInstance > instances = indexView . getAnnotations ( dotName ) ; instances . forEach ( ai -> { AnnotationTarget target = ai . target ( ) ; if ( target . kind ( ) == AnnotationTarget . Kind . CLASS ) { extractAndAddPackageInfo ( target . asClass ( ) , packages , indexView ) ; } } ) ; dotName = DotName . createSimple ( Path . class . getName ( ) ) ; instances = indexView . getAnnotations ( dotName ) ; instances . forEach ( ai -> { AnnotationTarget target = ai . target ( ) ; switch ( target . kind ( ) ) { case CLASS : extractAndAddPackageInfo ( target . asClass ( ) , packages , indexView ) ; break ; case METHOD : extractAndAddPackageInfo ( target . asMethod ( ) . declaringClass ( ) , packages , indexView ) ; break ; default : } } ) ; Set < String > tmp = new HashSet < > ( packages ) ; Iterator < String > itr = packages . iterator ( ) ; while ( itr . hasNext ( ) ) { String current = itr . next ( ) ; boolean remove = false ; if ( current . startsWith ( "org.wildfly.swarm" ) ) { remove = true ; } else { for ( String s : tmp ) { if ( s . length ( ) < current . length ( ) && current . startsWith ( s ) ) { remove = true ; break ; } } } if ( remove ) { itr . remove ( ) ; } } } else { String packageName = null ; for ( Map . Entry < ArchivePath , Node > entry : deployment . getContent ( ) . entrySet ( ) ) { final ArchivePath key = entry . getKey ( ) ; if ( key . get ( ) . endsWith ( ".class" ) ) { String parentPath = key . getParent ( ) . get ( ) ; parentPath = parentPath . replaceFirst ( "/" , "" ) ; String parentPackage = parentPath . replaceFirst ( ".*/classes/" , "" ) ; parentPackage = parentPackage . replaceAll ( "/" , "." ) ; if ( parentPackage . startsWith ( "org.wildfly.swarm" ) ) { SwaggerMessages . MESSAGES . ignoringPackage ( parentPackage ) ; } else { packageName = parentPackage ; break ; } } } packages . add ( packageName ) ; } return packages ; }
|
Get the packages that should be scanned by Swagger . This method attempts to determine the root packages by leveraging the IndexView of the deployment . If the IndexView is unavailable then this method will fallback to the scanning the classes manually .
|
35,016
|
public void stop ( ) throws Exception { final CountDownLatch latch = new CountDownLatch ( 1 ) ; this . serviceContainer . addTerminateListener ( info -> latch . countDown ( ) ) ; this . serviceContainer . shutdown ( ) ; latch . await ( ) ; executor . submit ( new Runnable ( ) { public void run ( ) { TempFileManager . deleteRecursively ( tmpDir ) ; } } ) ; executor . shutdown ( ) ; }
|
Stops the service container and cleans up all file system resources .
|
35,017
|
public void beforeShutdown ( final BeforeShutdown bs ) { monitor . unregisterHealthReporter ( ) ; monitor . unregisterContextClassLoader ( ) ; reporter = null ; reporterInstance . preDestroy ( ) . dispose ( ) ; reporterInstance = null ; }
|
Called when the deployment is undeployed .
|
35,018
|
void setup ( final Map < String , Object > properties ) { final List < SetupAction > successfulActions = new ArrayList < SetupAction > ( ) ; for ( final SetupAction action : setupActions ) { try { action . setup ( properties ) ; successfulActions . add ( action ) ; } catch ( final Throwable e ) { for ( SetupAction s : successfulActions ) { try { s . teardown ( properties ) ; } catch ( final Throwable t ) { } } throw new RuntimeException ( e ) ; } } }
|
Sets up the contexts . If any of the setup actions fail then any setup contexts are torn down and then the exception is wrapped and thrown
|
35,019
|
private void resolveDependenciesInParallel ( List < DependencyNode > nodes ) { List < ArtifactRequest > artifactRequests = nodes . stream ( ) . map ( node -> new ArtifactRequest ( node . getArtifact ( ) , this . remoteRepositories , null ) ) . collect ( Collectors . toList ( ) ) ; try { this . resolver . resolveArtifacts ( this . session , artifactRequests ) ; } catch ( ArtifactResolutionException e ) { } }
|
This is needed to speed up things .
|
35,020
|
public Swarm outboundSocketBinding ( String socketBindingGroup , OutboundSocketBinding binding ) { this . outboundSocketBindings . add ( new OutboundSocketBindingRequest ( socketBindingGroup , binding ) ) ; return this ; }
|
Add an outbound socket - binding to the container .
|
35,021
|
public Swarm socketBinding ( String socketBindingGroup , SocketBinding binding ) { this . socketBindings . add ( new SocketBindingRequest ( socketBindingGroup , binding ) ) ; return this ; }
|
Add an inbound socket - binding to the container .
|
35,022
|
public Swarm start ( ) throws Exception { INSTANCE = this ; try ( AutoCloseable handle = Performance . time ( "Thorntail.start()" ) ) { Module module = Module . getBootModuleLoader ( ) . loadModule ( CONTAINER_MODULE_NAME ) ; Class < ? > bootstrapClass = module . getClassLoader ( ) . loadClass ( "org.wildfly.swarm.container.runtime.ServerBootstrapImpl" ) ; ServerBootstrap bootstrap = ( ServerBootstrap ) bootstrapClass . newInstance ( ) ; bootstrap . withArguments ( this . args ) . withBootstrapDebug ( this . debugBootstrap ) . withExplicitlyInstalledFractions ( this . explicitlyInstalledFractions ) . withSocketBindings ( this . socketBindings ) . withOutboundSocketBindings ( this . outboundSocketBindings ) . withUserComponents ( this . userComponentClasses ) . withXmlConfig ( this . xmlConfig ) . withConfigView ( this . configView . get ( true ) ) ; this . server = bootstrap . bootstrap ( ) ; return this ; } }
|
Start the container .
|
35,023
|
public Swarm stop ( ) throws Exception { if ( this . server == null ) { throw SwarmMessages . MESSAGES . containerNotStarted ( "stop()" ) ; } this . server . stop ( ) ; this . server = null ; Module module = Module . getBootModuleLoader ( ) . loadModule ( CONTAINER_MODULE_NAME ) ; Class < ? > shutdownClass = module . getClassLoader ( ) . loadClass ( "org.wildfly.swarm.container.runtime.WeldShutdownImpl" ) ; WeldShutdown shutdown = ( WeldShutdown ) shutdownClass . newInstance ( ) ; shutdown . shutdown ( ) ; return this ; }
|
Stop the container first undeploying all deployments .
|
35,024
|
public Swarm deploy ( ) throws IllegalStateException , DeploymentException { if ( this . server == null ) { throw SwarmMessages . MESSAGES . containerNotStarted ( "deploy()" ) ; } if ( ApplicationEnvironment . get ( ) . isHollow ( ) ) { this . server . deployer ( ) . deploy ( getCommandLine ( ) . extraArguments ( ) . stream ( ) . map ( e -> Paths . get ( e ) ) . collect ( Collectors . toList ( ) ) ) ; } else { this . server . deployer ( ) . deploy ( ) ; } return this ; }
|
Perform a default deployment .
|
35,025
|
public Archive < ? > createDefaultDeployment ( ) throws Exception { if ( this . server == null ) { throw SwarmMessages . MESSAGES . containerNotStarted ( "createDefaultDeployment()" ) ; } return this . server . deployer ( ) . createDefaultDeployment ( ) ; }
|
Retrieve the default ShrinkWrap deployment .
|
35,026
|
public static JavaArchive artifact ( String gav , String asName ) throws Exception { return artifactLookup ( ) . artifact ( gav , asName ) ; }
|
Retrieve an artifact that was part of the original build using a full or simplified Maven GAV specifier returning an archive with a specified name .
|
35,027
|
private void installModuleMBeanServer ( ) { try { Method method = ModuleLoader . class . getDeclaredMethod ( "installMBeanServer" ) ; method . setAccessible ( true ) ; method . invoke ( null ) ; } catch ( Exception e ) { SwarmMessages . MESSAGES . moduleMBeanServerNotInstalled ( e ) ; } }
|
Installs the Module MBeanServer .
|
35,028
|
File downloadFromRemoteRepository ( ArtifactCoordinates artifactCoordinates , String packaging , Path artifactDirectory ) { String artifactRelativeHttpPath = toGradleArtifactPath ( artifactCoordinates ) ; String artifactRelativeMetadataHttpPath = artifactCoordinates . relativeMetadataPath ( '/' ) ; for ( String remoteRepos : remoteRepositories ) { String artifactAbsoluteHttpPath = remoteRepos + artifactRelativeHttpPath + "." ; File targetArtifactPomDirectory = artifactDirectory . resolve ( computeGradleUUID ( artifactCoordinates + ":pom" ) ) . toFile ( ) ; File targetArtifactDirectory = artifactDirectory . resolve ( computeGradleUUID ( artifactCoordinates + ":" + packaging ) ) . toFile ( ) ; File artifactFile = doDownload ( remoteRepos , artifactAbsoluteHttpPath , artifactRelativeHttpPath , artifactCoordinates , packaging , targetArtifactPomDirectory , targetArtifactDirectory ) ; if ( artifactFile != null ) { return artifactFile ; } if ( artifactCoordinates . isSnapshot ( ) ) { String remoteMetadataPath = remoteRepos + artifactRelativeMetadataHttpPath ; try { String timestamp = MavenArtifactUtil . downloadTimestampVersion ( artifactCoordinates + ":" + packaging , remoteMetadataPath ) ; String timestampedArtifactRelativePath = artifactCoordinates . relativeArtifactPath ( '/' , timestamp ) ; String artifactTimestampedAbsoluteHttpPath = remoteRepos + timestampedArtifactRelativePath + "." ; File targetTimestampedArtifactPomDirectory = artifactDirectory . resolve ( computeGradleUUID ( artifactCoordinates + ":" + timestamp + ":pom" ) ) . toFile ( ) ; File targetTimestampedArtifactDirectory = artifactDirectory . resolve ( computeGradleUUID ( artifactCoordinates + ":" + packaging ) ) . toFile ( ) ; File snapshotArtifactFile = doDownload ( remoteRepos , artifactTimestampedAbsoluteHttpPath , timestampedArtifactRelativePath , artifactCoordinates , packaging , targetTimestampedArtifactPomDirectory , targetTimestampedArtifactDirectory ) ; if ( snapshotArtifactFile != null ) { return snapshotArtifactFile ; } } catch ( XPathExpressionException | IOException ex ) { Module . getModuleLogger ( ) . trace ( ex , "Could not doDownload '%s' from '%s' repository" , artifactRelativeHttpPath , remoteRepos ) ; } } } return null ; }
|
Download artifact from remote repository .
|
35,029
|
File doDownload ( String remoteRepos , String artifactAbsoluteHttpPath , String artifactRelativeHttpPath , ArtifactCoordinates artifactCoordinates , String packaging , File targetArtifactPomDirectory , File targetArtifactDirectory ) { File targetArtifactPomFile = new File ( targetArtifactPomDirectory , toGradleArtifactFileName ( artifactCoordinates , "pom" ) ) ; try { MavenArtifactUtil . downloadFile ( artifactCoordinates + ":pom" , artifactAbsoluteHttpPath + "pom" , targetArtifactPomFile ) ; } catch ( IOException e ) { Module . getModuleLogger ( ) . trace ( e , "Could not doDownload '%s' from '%s' repository" , artifactRelativeHttpPath , remoteRepos ) ; } File targetArtifactFile = new File ( targetArtifactDirectory , toGradleArtifactFileName ( artifactCoordinates , packaging ) ) ; try { MavenArtifactUtil . downloadFile ( artifactCoordinates + ":" + packaging , artifactAbsoluteHttpPath + packaging , targetArtifactFile ) ; if ( targetArtifactFile . exists ( ) ) { return targetArtifactFile ; } } catch ( IOException e ) { Module . getModuleLogger ( ) . trace ( e , "Could not doDownload '%s' from '%s' repository" , artifactRelativeHttpPath , remoteRepos ) ; } return null ; }
|
Download the POM and the artifact file and return it .
|
35,030
|
String toGradleArtifactFileName ( ArtifactCoordinates artifactCoordinates , String packaging ) { StringBuilder sbFileFilter = new StringBuilder ( ) ; sbFileFilter . append ( artifactCoordinates . getArtifactId ( ) ) . append ( "-" ) . append ( artifactCoordinates . getVersion ( ) ) ; if ( artifactCoordinates . getClassifier ( ) != null && artifactCoordinates . getClassifier ( ) . length ( ) > 0 ) { sbFileFilter . append ( "-" ) . append ( artifactCoordinates . getClassifier ( ) ) ; } sbFileFilter . append ( "." ) . append ( packaging ) ; return sbFileFilter . toString ( ) ; }
|
Build file name for artifact .
|
35,031
|
String toGradleArtifactPath ( ArtifactCoordinates artifactCoordinates ) { String pathWithMissingClassifier = artifactCoordinates . relativeArtifactPath ( '/' ) ; StringBuilder sb = new StringBuilder ( pathWithMissingClassifier ) ; if ( artifactCoordinates . getClassifier ( ) != null && artifactCoordinates . getClassifier ( ) . length ( ) > 0 ) { sb . append ( "-" ) . append ( artifactCoordinates . getClassifier ( ) ) ; } return sb . toString ( ) ; }
|
Build the artifact path including the classifier .
|
35,032
|
String computeGradleUUID ( String content ) { try { MessageDigest md = MessageDigest . getInstance ( MD5_ALGORITHM ) ; md . reset ( ) ; byte [ ] bytes = content . trim ( ) . toLowerCase ( Locale . US ) . getBytes ( "UTF-8" ) ; md . update ( bytes , 0 , bytes . length ) ; return byteArrayToHexString ( md . digest ( ) ) ; } catch ( NoSuchAlgorithmException e ) { throw new IllegalArgumentException ( "unknown algorithm " + MD5_ALGORITHM , e ) ; } catch ( UnsupportedEncodingException e ) { throw new IllegalArgumentException ( "unknown charset UTF-8" , e ) ; } }
|
Compute gradle uuid for artifacts .
|
35,033
|
private DeclaredDependencies getDependenciesViaIdeaModel ( ProjectConnection connection ) { DeclaredDependencies declaredDependencies = new DeclaredDependencies ( ) ; IdeaProject prj = connection . getModel ( IdeaProject . class ) ; prj . getModules ( ) . forEach ( this :: computeProjectDependencies ) ; Optional < ? extends IdeaModule > prjModule = prj . getModules ( ) . stream ( ) . filter ( m -> m . getGradleProject ( ) . getProjectDirectory ( ) . toPath ( ) . equals ( rootPath ) ) . findFirst ( ) ; Set < ArtifactSpec > collectedDependencies = new HashSet < > ( ) ; prjModule . ifPresent ( m -> { Map < String , Set < ArtifactSpec > > currentPrjDeps = ARTIFACT_DEPS_OF_PRJ . get ( m . getName ( ) ) ; Set < String > upstreamProjects = PRJ_DEPS_OF_PRJ . getOrDefault ( m . getName ( ) , emptySet ( ) ) ; collectedDependencies . addAll ( currentPrjDeps . getOrDefault ( DEP_SCOPE_COMPILE , emptySet ( ) ) ) ; collectedDependencies . addAll ( currentPrjDeps . getOrDefault ( DEP_SCOPE_TEST , emptySet ( ) ) ) ; upstreamProjects . forEach ( moduleName -> { Map < String , Set < ArtifactSpec > > moduleDeps = ARTIFACT_DEPS_OF_PRJ . getOrDefault ( moduleName , emptyMap ( ) ) ; collectedDependencies . addAll ( moduleDeps . getOrDefault ( DEP_SCOPE_COMPILE , emptySet ( ) ) ) ; } ) ; Set < ArtifactSpec > providedScopeDeps = currentPrjDeps . getOrDefault ( DEP_SCOPE_PROVIDED , emptySet ( ) ) ; providedScopeDeps . removeAll ( collectedDependencies ) ; if ( ! providedScopeDeps . isEmpty ( ) ) { List < ArtifactSpec > testScopedLibs = new ArrayList < > ( ) ; upstreamProjects . forEach ( moduleName -> testScopedLibs . addAll ( ARTIFACT_DEPS_OF_PRJ . getOrDefault ( moduleName , emptyMap ( ) ) . getOrDefault ( DEP_SCOPE_TEST , emptySet ( ) ) ) ) ; providedScopeDeps . stream ( ) . filter ( testScopedLibs :: contains ) . forEach ( collectedDependencies :: add ) ; } } ) ; collectedDependencies . forEach ( declaredDependencies :: add ) ; return declaredDependencies ; }
|
Get the dependencies via the Gradle IDEA model .
|
35,034
|
private static ArtifactSpec toArtifactSpec ( DependencyDescriptor desc , String scope ) { return new ArtifactSpec ( scope , desc . getGroup ( ) , desc . getName ( ) , desc . getVersion ( ) , desc . getType ( ) , desc . getClassifier ( ) , desc . getFile ( ) ) ; }
|
Translate the given dependency descriptor to the an artifact specification while overriding the scope as well .
|
35,035
|
void activate ( ) { nodes ( ) . flatMap ( e -> e . allKeysRecursively ( ) ) . distinct ( ) . forEach ( key -> { activate ( key ) ; } ) ; }
|
Activate the strategy .
|
35,036
|
public static ResourceLoader createMavenArtifactLoader ( final MavenResolver mavenResolver , final String name ) throws IOException { return createMavenArtifactLoader ( mavenResolver , ArtifactCoordinates . fromString ( name ) , name ) ; }
|
A utility method to create a Maven artifact resource loader for the given artifact name .
|
35,037
|
public static ResourceLoader createMavenArtifactLoader ( final MavenResolver mavenResolver , final ArtifactCoordinates coordinates , final String rootName ) throws IOException { File fp = mavenResolver . resolveJarArtifact ( coordinates ) ; if ( fp == null ) return null ; JarFile jarFile = JDKSpecific . getJarFile ( fp , true ) ; return ResourceLoaders . createJarResourceLoader ( rootName , jarFile ) ; }
|
A utility method to create a Maven artifact resource loader for the given artifact coordinates .
|
35,038
|
protected JWTCallerPrincipal validate ( JWTCredential jwtCredential ) throws ParseException { JWTCallerPrincipalFactory factory = JWTCallerPrincipalFactory . instance ( ) ; JWTCallerPrincipal callerPrincipal = factory . parse ( jwtCredential . getBearerToken ( ) , jwtCredential . getAuthContextInfo ( ) ) ; return callerPrincipal ; }
|
Validate the bearer token passed in with the authorization header
|
35,039
|
@ SuppressWarnings ( "deprecation" ) private HttpHandler secureHandler ( final HttpHandler toWrap , SecurityRealm securityRealm ) { HttpHandler handler = toWrap ; handler = new AuthenticationCallHandler ( handler ) ; handler = new AuthenticationConstraintHandler ( handler ) ; RealmIdentityManager idm = new RealmIdentityManager ( securityRealm ) ; Set < AuthMechanism > mechanisms = securityRealm . getSupportedAuthenticationMechanisms ( ) ; List < AuthenticationMechanism > undertowMechanisms = new ArrayList < AuthenticationMechanism > ( mechanisms . size ( ) ) ; undertowMechanisms . add ( wrap ( new CachedAuthenticatedSessionMechanism ( ) , null ) ) ; for ( AuthMechanism current : mechanisms ) { switch ( current ) { case DIGEST : List < DigestAlgorithm > digestAlgorithms = Collections . singletonList ( DigestAlgorithm . MD5 ) ; List < DigestQop > digestQops = Collections . singletonList ( DigestQop . AUTH ) ; undertowMechanisms . add ( wrap ( new DigestAuthenticationMechanism ( digestAlgorithms , digestQops , securityRealm . getName ( ) , "Monitor" , new SimpleNonceManager ( ) ) , current ) ) ; break ; case PLAIN : undertowMechanisms . add ( wrap ( new BasicAuthenticationMechanism ( securityRealm . getName ( ) ) , current ) ) ; break ; case LOCAL : break ; default : } } handler = new AuthenticationMechanismsHandler ( handler , undertowMechanisms ) ; handler = new SecurityInitialHandler ( AuthenticationMode . PRO_ACTIVE , idm , handler ) ; handler = new PredicateHandler ( exchange -> { if ( ! monitor . getSecurityRealm ( ) . isPresent ( ) ) { return false ; } if ( Queries . isAggregatorEndpoint ( monitor , exchange . getRelativePath ( ) ) ) { return true ; } if ( Queries . isDirectAccessToHealthEndpoint ( monitor , exchange . getRelativePath ( ) ) ) { if ( ! hasTokenAuth ( exchange ) ) { return true ; } return false ; } if ( HttpContexts . getDefaultContextNames ( ) . contains ( exchange . getRelativePath ( ) ) ) { return true ; } return false ; } , handler , toWrap ) ; return handler ; }
|
Wraps the target handler and makes it inheritSecurity . Includes a predicate for relevant web contexts .
|
35,040
|
private boolean isWar ( String path ) { String currentDir = Paths . get ( "." ) . toAbsolutePath ( ) . normalize ( ) . toString ( ) ; String classesDirPath = Paths . get ( path ) . toAbsolutePath ( ) . normalize ( ) . toString ( ) ; return classesDirPath . startsWith ( currentDir ) ; }
|
the assumption is that the Runner is invoked in the WAR module s directory
|
35,041
|
public static String determinePluginVersion ( ) { if ( pluginVersion == null ) { final String fileName = "META-INF/gradle-plugins/thorntail.properties" ; ClassLoader loader = Thread . currentThread ( ) . getContextClassLoader ( ) ; String version ; try ( InputStream stream = loader . getResourceAsStream ( fileName ) ) { Properties props = new Properties ( ) ; props . load ( stream ) ; version = props . getProperty ( "implementation-version" ) ; } catch ( IOException e ) { throw new IllegalStateException ( "Unable to locate file: " + fileName , e ) ; } pluginVersion = version ; } return pluginVersion ; }
|
Parse the plugin definition file and extract the version details from it .
|
35,042
|
public static boolean isProject ( Project project , DependencyDescriptor descriptor ) { final String specGAV = String . format ( "%s:%s:%s" , descriptor . getGroup ( ) , descriptor . getName ( ) , descriptor . getVersion ( ) ) ; return getAllProjects ( project ) . containsKey ( specGAV ) || getIncludedProjectIdentifiers ( project ) . contains ( specGAV ) ; }
|
Convenience method to determine if the given dependency descriptor represents an internal Gradle project or not .
|
35,043
|
public static Set < ArtifactSpec > resolveArtifacts ( Project project , Collection < ArtifactSpec > specs , boolean transitive , boolean excludeDefaults ) { if ( project == null ) { throw new IllegalArgumentException ( "Gradle project reference cannot be null." ) ; } if ( specs == null ) { project . getLogger ( ) . warn ( "Artifact specification collection is null." ) ; return Collections . emptySet ( ) ; } final Configuration config = project . getConfigurations ( ) . detachedConfiguration ( ) . setTransitive ( transitive ) ; final DependencySet dependencySet = config . getDependencies ( ) ; final Map < String , Project > projectGAVCoordinates = getAllProjects ( project ) ; final ProjectAccessListener listener = new DefaultProjectAccessListener ( ) ; Set < ArtifactSpec > result = new HashSet < > ( ) ; specs . forEach ( s -> { final String specGAV = String . format ( "%s:%s:%s" , s . groupId ( ) , s . artifactId ( ) , s . version ( ) ) ; boolean resolved = s . file != null ; boolean projectEntry = projectGAVCoordinates . containsKey ( specGAV ) ; if ( excludeDefaults && FractionDescriptor . THORNTAIL_GROUP_ID . equals ( s . groupId ( ) ) && ! projectEntry ) { return ; } if ( ! resolved || transitive ) { if ( projectGAVCoordinates . containsKey ( specGAV ) ) { dependencySet . add ( new DefaultProjectDependency ( ( ProjectInternal ) projectGAVCoordinates . get ( specGAV ) , listener , false ) ) ; } else { DefaultExternalModuleDependency d = new DefaultExternalModuleDependency ( s . groupId ( ) , s . artifactId ( ) , s . version ( ) ) ; DefaultDependencyArtifact da = new DefaultDependencyArtifact ( s . artifactId ( ) , s . type ( ) , s . type ( ) , s . classifier ( ) , null ) ; d . addArtifact ( da ) ; dependencySet . add ( d ) ; } } else { result . add ( s ) ; } } ) ; if ( ! dependencySet . isEmpty ( ) ) { config . getResolvedConfiguration ( ) . getResolvedArtifacts ( ) . stream ( ) . map ( ra -> asDescriptor ( "compile" , ra ) . toArtifactSpec ( ) ) . forEach ( result :: add ) ; } return result ; }
|
Resolve the given artifact specifications .
|
35,044
|
public static Map < DependencyDescriptor , Set < DependencyDescriptor > > determineProjectDependencies ( Project project , String configuration , boolean resolveChildrenTransitively ) { if ( project == null ) { throw new IllegalArgumentException ( "Gradle project reference cannot be null." ) ; } project . getLogger ( ) . info ( "Requesting dependencies for configuration: {}" , configuration ) ; Configuration requestedConfiguration = project . getConfigurations ( ) . findByName ( configuration ) ; if ( requestedConfiguration == null ) { project . getLogger ( ) . warn ( "Unable to locate dependency configuration with name: {}" , configuration ) ; return Collections . emptyMap ( ) ; } Map < String , String > dependencyScopeMap = new HashMap < > ( ) ; String defaultScopeForUnknownConfigurations = REMAPPED_SCOPES . computeIfAbsent ( requestedConfiguration . getName ( ) , cfgName -> { throw new IllegalStateException ( "Unknown configuration name provided: " + cfgName ) ; } ) ; requestedConfiguration . getHierarchy ( ) . forEach ( cfg -> { cfg . getDependencies ( ) . forEach ( dep -> { String key = String . format ( "%s:%s" , dep . getGroup ( ) , dep . getName ( ) ) ; dependencyScopeMap . put ( key , REMAPPED_SCOPES . getOrDefault ( cfg . getName ( ) , defaultScopeForUnknownConfigurations ) ) ; } ) ; } ) ; ResolvedConfiguration resolvedConfig = requestedConfiguration . getResolvedConfiguration ( ) ; Map < DependencyDescriptor , Set < DependencyDescriptor > > dependencyMap = new HashMap < > ( ) ; resolvedConfig . getFirstLevelModuleDependencies ( ) . forEach ( resolvedDep -> { String lookup = String . format ( "%s:%s" , resolvedDep . getModuleGroup ( ) , resolvedDep . getModuleName ( ) ) ; String scope = dependencyScopeMap . get ( lookup ) ; if ( scope == null ) { throw new IllegalStateException ( "Gradle dependency resolution logic is broken. Unable to get scope for dependency: " + lookup ) ; } DependencyDescriptor key = asDescriptor ( scope , resolvedDep ) ; Set < DependencyDescriptor > value ; if ( resolveChildrenTransitively ) { value = getDependenciesTransitively ( scope , resolvedDep ) ; } else { value = resolvedDep . getChildren ( ) . stream ( ) . map ( rd -> asDescriptor ( scope , rd ) ) . collect ( Collectors . toSet ( ) ) ; } dependencyMap . put ( key , value ) ; } ) ; printDependencyMap ( dependencyMap , project ) ; return dependencyMap ; }
|
Determine the dependencies associated with a Gradle project . This method returns a Map whose key represents a top level dependency associated with this project and the value represents a collection of dependencies that the key requires .
|
35,045
|
private static void printDependencyMap ( Map < DependencyDescriptor , Set < DependencyDescriptor > > map , Project project ) { final String NEW_LINE = "\n" ; if ( project . getLogger ( ) . isEnabled ( LogLevel . INFO ) ) { StringBuilder builder = new StringBuilder ( 100 ) ; builder . append ( "Resolved dependencies:" ) . append ( NEW_LINE ) ; map . forEach ( ( k , v ) -> { builder . append ( k ) . append ( NEW_LINE ) ; v . forEach ( e -> builder . append ( "\t" ) . append ( e ) . append ( NEW_LINE ) ) ; builder . append ( NEW_LINE ) ; } ) ; project . getLogger ( ) . info ( builder . toString ( ) ) ; } }
|
Temp method for printing out the dependency map .
|
35,046
|
private static Map < String , Project > getAllProjects ( final Project project ) { return getCachedReference ( project , "thorntail_project_gav_collection" , ( ) -> { Map < String , Project > gavMap = new HashMap < > ( ) ; project . getRootProject ( ) . getAllprojects ( ) . forEach ( p -> { gavMap . put ( p . getGroup ( ) + ":" + p . getName ( ) + ":" + p . getVersion ( ) , p ) ; } ) ; return gavMap ; } ) ; }
|
Get the collection of Gradle projects along with their GAV definitions . This collection is used for determining if an artifact specification represents a Gradle project or not .
|
35,047
|
public void ifPresent ( Consumer < ? super T > consumer ) { T value = get ( false ) ; if ( value != null ) { consumer . accept ( value ) ; } }
|
If a default or explicit value is present invoke the supplied consumer with it .
|
35,048
|
public static FileSystemLayout create ( ) { String userDir = System . getProperty ( USER_DIR ) ; if ( null == userDir ) { throw SwarmMessages . MESSAGES . systemPropertyNotFound ( USER_DIR ) ; } return create ( userDir ) ; }
|
Derived form user . dir
|
35,049
|
public static FileSystemLayout create ( String root ) { String implClassName = System . getProperty ( CUSTOM_LAYOUT_CLASS ) ; if ( implClassName != null ) { implClassName = implClassName . trim ( ) ; if ( ! implClassName . isEmpty ( ) ) { FileSystemLayout layout = null ; ClassLoader loader = Thread . currentThread ( ) . getContextClassLoader ( ) ; try { Class < ? > clazz = loader . loadClass ( implClassName ) ; if ( FileSystemLayout . class . isAssignableFrom ( clazz ) ) { Class < ? extends FileSystemLayout > implClazz = clazz . asSubclass ( FileSystemLayout . class ) ; Constructor < ? extends FileSystemLayout > ctor = implClazz . getDeclaredConstructor ( String . class ) ; layout = ctor . newInstance ( root ) ; } else { String msg = String . format ( "%s does not subclass %s" , implClassName , FileSystemLayout . class . getName ( ) ) ; LOG . warn ( SwarmMessages . MESSAGES . invalidFileSystemLayoutProvided ( msg ) ) ; } } catch ( ReflectiveOperationException e ) { Throwable cause = e . getCause ( ) ; String msg = String . format ( "Unable to instantiate layout class (%s) due to: %s" , implClassName , cause != null ? cause . getMessage ( ) : e . getMessage ( ) ) ; LOG . warn ( SwarmMessages . MESSAGES . invalidFileSystemLayoutProvided ( msg ) ) ; LOG . debug ( SwarmMessages . MESSAGES . invalidFileSystemLayoutProvided ( msg ) , e ) ; throw SwarmMessages . MESSAGES . cannotIdentifyFileSystemLayout ( msg ) ; } if ( layout != null ) { return layout ; } } else { LOG . warn ( SwarmMessages . MESSAGES . invalidFileSystemLayoutProvided ( "Implementation class name is empty." ) ) ; } } String mavenBuildFile = resolveMavenBuildFileName ( ) ; if ( Files . exists ( Paths . get ( root , mavenBuildFile ) ) ) { return new MavenFileSystemLayout ( root ) ; } else if ( Files . exists ( Paths . get ( root , BUILD_GRADLE ) ) ) { return new GradleFileSystemLayout ( root ) ; } throw SwarmMessages . MESSAGES . cannotIdentifyFileSystemLayout ( root ) ; }
|
Derived from explicit path
|
35,050
|
public void process ( ) throws Exception { if ( deploymentContext != null && deploymentContext . isImplicit ( ) ) { return ; } try { WARArchive warArchive = archive . as ( WARArchive . class ) ; warArchive . findWebXmlAsset ( ) . addListener ( LISTENER_CLASS ) ; } catch ( Exception e ) { throw new RuntimeException ( "Failed to register OpenAPI listener" , e ) ; } OpenApiStaticFile staticFile = ArchiveUtil . archiveToStaticFile ( archive ) ; OpenApiDocument openApiDocument = OpenApiDocument . INSTANCE ; openApiDocument . config ( config ) ; openApiDocument . modelFromStaticFile ( OpenApiProcessor . modelFromStaticFile ( staticFile ) ) ; openApiDocument . modelFromAnnotations ( OpenApiProcessor . modelFromAnnotations ( config , index ) ) ; }
|
Process the deployment in order to produce an OpenAPI document .
|
35,051
|
public static URL toURL ( String value ) throws MalformedURLException { try { URL url = new URL ( value ) ; return url ; } catch ( MalformedURLException e ) { try { return new File ( value ) . toURI ( ) . toURL ( ) ; } catch ( MalformedURLException e2 ) { throw e ; } } }
|
Helper to attempt forming a URL from a String in a sensible fashion .
|
35,052
|
public static void explodeJar ( JarFile jarFile , String destDir ) throws IOException { Enumeration < java . util . jar . JarEntry > enu = jarFile . entries ( ) ; while ( enu . hasMoreElements ( ) ) { JarEntry je = enu . nextElement ( ) ; File fl = new File ( destDir , je . getName ( ) ) ; if ( ! fl . exists ( ) ) { fl . getParentFile ( ) . mkdirs ( ) ; fl = new File ( destDir , je . getName ( ) ) ; } if ( je . isDirectory ( ) ) { continue ; } InputStream is = null ; try { is = jarFile . getInputStream ( je ) ; Files . copy ( is , fl . toPath ( ) , StandardCopyOption . REPLACE_EXISTING ) ; } finally { if ( is != null ) { is . close ( ) ; } } } }
|
Extracts a jar file into a target destination directory
|
35,053
|
public void scan ( PathSource fileSource , Collection < FractionDetector < PathSource > > detectors , Consumer < File > handleFileAsZip ) throws IOException { detectors . stream ( ) . filter ( d -> FileDetector . class . isAssignableFrom ( d . getClass ( ) ) ) . forEach ( d -> d . detect ( fileSource ) ) ; }
|
scans all xml files
|
35,054
|
void observesAfterBeanDiscovery ( final AfterBeanDiscovery event , final BeanManager beanManager ) { log . debugf ( "observesAfterBeanDiscovery, %s" , claims ) ; installClaimValueProducerMethodsViaSyntheticBeans ( event , beanManager ) ; }
|
Create producer methods for each ClaimValue injection site
|
35,055
|
public Collection < ArtifactSpec > getDirectDependencies ( boolean includeUnsolved , boolean includePresolved ) { Set < ArtifactSpec > deps = new LinkedHashSet < > ( ) ; if ( includeUnsolved ) { deps . addAll ( getDirectDeps ( ) ) ; } if ( includePresolved ) { deps . addAll ( presolvedDependencies . getDirectDeps ( ) ) ; } return deps ; }
|
Get the collection of direct dependencies included in this instance .
|
35,056
|
public Set < ArtifactSpec > getTransientDependencies ( ) { if ( null == allTransient ) { allTransient = getTransientDependencies ( true , true ) ; } return allTransient ; }
|
Get the collection of all transient dependencies defined in this instance .
|
35,057
|
public Set < ArtifactSpec > getTransientDependencies ( boolean includeUnsolved , boolean includePresolved ) { Set < ArtifactSpec > deps = new HashSet < > ( ) ; List < DependencyTree < ArtifactSpec > > sources = new ArrayList < > ( ) ; if ( includeUnsolved ) { sources . add ( this ) ; } if ( includePresolved ) { sources . add ( presolvedDependencies ) ; } sources . forEach ( s -> s . getDirectDeps ( ) . stream ( ) . filter ( d -> ! isThorntailRunner ( d ) ) . forEach ( d -> deps . addAll ( s . getTransientDeps ( d ) ) ) ) ; return deps ; }
|
Get the collection of transient dependencies defined in this instance .
|
35,058
|
public Collection < ArtifactSpec > getTransientDependencies ( ArtifactSpec artifact ) { Set < ArtifactSpec > deps = new HashSet < > ( ) ; if ( this . isDirectDep ( artifact ) ) { deps . addAll ( getTransientDeps ( artifact ) ) ; } if ( presolvedDependencies . isDirectDep ( artifact ) ) { deps . addAll ( presolvedDependencies . getTransientDeps ( artifact ) ) ; } return deps ; }
|
Get the transient dependencies defined for the given artifact specification .
|
35,059
|
public EnhancedServer remoteConnection ( String name ) { return remoteConnection ( name , ( config ) -> { } ) ; }
|
Setup a default named remote connection to a remote message broker .
|
35,060
|
public JsonValue generalJsonValueProducer ( InjectionPoint ip ) { String name = getName ( ip ) ; Object value = getValue ( name , false ) ; JsonValue jsonValue = wrapValue ( value ) ; return jsonValue ; }
|
Return the indicated claim value as a JsonValue
|
35,061
|
private void cleanup ( ) throws IOException { JarFileManager . INSTANCE . close ( ) ; TempFileManager . INSTANCE . close ( ) ; MavenResolvers . close ( ) ; }
|
Clean up all open resources .
|
35,062
|
private void closeRemoteResources ( ) { if ( reader != null ) { try { reader . close ( ) ; } catch ( final IOException ignore ) { } reader = null ; } if ( writer != null ) { writer . close ( ) ; writer = null ; } if ( socketOutstream != null ) { try { socketOutstream . close ( ) ; } catch ( final IOException ignore ) { } socketOutstream = null ; } if ( socketInstream != null ) { try { socketInstream . close ( ) ; } catch ( final IOException ignore ) { } socketInstream = null ; } if ( socket != null ) { try { socket . close ( ) ; } catch ( final IOException ignore ) { } socket = null ; } }
|
Safely close remote resources
|
35,063
|
public static ArtifactCoordinates fromString ( String string ) { final Matcher matcher = VALID_PATTERN . matcher ( string ) ; if ( matcher . matches ( ) ) { if ( matcher . group ( 4 ) != null ) { return new ArtifactCoordinates ( matcher . group ( 1 ) , matcher . group ( 2 ) , matcher . group ( 3 ) , matcher . group ( 4 ) ) ; } else { return new ArtifactCoordinates ( matcher . group ( 1 ) , matcher . group ( 2 ) , matcher . group ( 3 ) ) ; } } else { throw new IllegalArgumentException ( string ) ; } }
|
Parse a string and produce artifact coordinates from it .
|
35,064
|
public String relativeArtifactPath ( char separator ) { String artifactId1 = getArtifactId ( ) ; String version1 = getVersion ( ) ; StringBuilder builder = new StringBuilder ( getGroupId ( ) . replace ( '.' , separator ) ) ; builder . append ( separator ) . append ( artifactId1 ) . append ( separator ) ; String pathVersion ; final Matcher versionMatcher = snapshotPattern . matcher ( version1 ) ; if ( versionMatcher . find ( ) ) { pathVersion = version1 . substring ( 0 , versionMatcher . start ( ) ) + "-SNAPSHOT" ; } else { pathVersion = version1 ; } builder . append ( pathVersion ) . append ( separator ) . append ( artifactId1 ) . append ( '-' ) . append ( version1 ) ; return builder . toString ( ) ; }
|
Create a relative repository path for the given artifact coordinates .
|
35,065
|
public Module withImportIncludePath ( String path ) { checkList ( this . imports , INCLUDE ) ; this . imports . get ( INCLUDE ) . add ( path ) ; return this ; }
|
Add a path to import from this module .
|
35,066
|
public Module withImportExcludePath ( String path ) { checkList ( this . imports , EXCLUDE ) ; this . imports . get ( EXCLUDE ) . add ( path ) ; return this ; }
|
Add a path to exclude from importing from this module .
|
35,067
|
public Module withExportIncludePath ( String path ) { checkList ( this . exports , INCLUDE ) ; this . exports . get ( INCLUDE ) . add ( path ) ; return this ; }
|
Add a path to export from this module .
|
35,068
|
public Module withExportExcludePath ( String path ) { checkList ( this . exports , EXCLUDE ) ; this . exports . get ( EXCLUDE ) . add ( path ) ; return this ; }
|
Add a path to exclude from exporting from this module .
|
35,069
|
public String getRelativePath ( ) { if ( basePath == null ) { return source . toString ( ) ; } return basePath . relativize ( source ) . toString ( ) ; }
|
Gets the relative file path instead of the absolute .
|
35,070
|
public Section mbean ( String name , MBeanRule . Consumer config ) { MBeanRule rule = new MBeanRule ( name ) ; config . accept ( rule ) ; this . rules . add ( rule ) ; return this ; }
|
Define a rule for a given MBean .
|
35,071
|
public URLConnection openConnection ( URL url ) throws IOException { Proxy proxy = getProxyFor ( url ) ; URLConnection conn = null ; if ( proxy != null ) { conn = url . openConnection ( proxy . getProxy ( ) ) ; proxy . authenticate ( conn ) ; } else { conn = url . openConnection ( ) ; } return conn ; }
|
Opens a connection with appropriate proxy and credentials if required .
|
35,072
|
public static JoseFactory instance ( ) { if ( instance == null ) { synchronized ( JoseFactory . class ) { if ( instance != null ) { return instance ; } ClassLoader cl = AccessController . doPrivileged ( ( PrivilegedAction < ClassLoader > ) ( ) -> Thread . currentThread ( ) . getContextClassLoader ( ) ) ; if ( cl == null ) { cl = JoseFactory . class . getClassLoader ( ) ; } JoseFactory newInstance = loadSpi ( cl ) ; if ( newInstance == null && cl != JoseFactory . class . getClassLoader ( ) ) { cl = JoseFactory . class . getClassLoader ( ) ; newInstance = loadSpi ( cl ) ; } if ( newInstance == null ) { newInstance = new DefaultJoseFactory ( ) ; } instance = newInstance ; } } return instance ; }
|
Obtain the JoseFactory using the ServiceLoader pattern .
|
35,073
|
private static JoseFactory loadSpi ( ClassLoader cl ) { if ( cl == null ) { return null ; } JoseFactory instance = loadSpi ( cl . getParent ( ) ) ; if ( instance == null ) { ServiceLoader < JoseFactory > sl = ServiceLoader . load ( JoseFactory . class , cl ) ; URL u = cl . getResource ( "/META-INF/services/org.wildfly.swarm.jose.provider.JoseFactory" ) ; log . debugf ( "loadSpi, cl=%s, u=%s, sl=%s" , cl , u , sl ) ; try { for ( Object spi : sl ) { if ( spi instanceof JoseFactory ) { if ( instance != null ) { log . warn ( "Multiple JoseFactory implementations found: " + spi . getClass ( ) . getName ( ) + " and " + instance . getClass ( ) . getName ( ) ) ; break ; } else { log . debugf ( "sl=%s, loaded=%s" , sl , spi ) ; instance = ( JoseFactory ) spi ; } } } } catch ( Throwable e ) { log . warn ( "Failed to locate JoseFactory provider" , e ) ; } } return instance ; }
|
Look for a JoseFactory service implementation using the ServiceLoader .
|
35,074
|
public static void addService ( ServiceTarget serviceTarget , SwarmContentRepository repository ) { serviceTarget . addService ( SERVICE_NAME , repository ) . setInitialMode ( ServiceController . Mode . ACTIVE ) . install ( ) ; }
|
Install the service .
|
35,075
|
public void proxyService ( String serviceName , String contextPath ) { if ( proxiedServiceMappings ( ) . containsValue ( contextPath ) ) { throw new IllegalArgumentException ( "Cannot proxy multiple services under the same context path" ) ; } proxiedServiceMappings . put ( serviceName , contextPath ) ; }
|
Set up a load - balancing reverse proxy for the given service at the given context path . Requests to this proxy will be load - balanced among all instances of the service as provided by our Topology .
|
35,076
|
private File buildWar ( List < ArtifactOrFile > classPathEntries ) { try { List < String > classesUrls = classPathEntries . stream ( ) . map ( ArtifactOrFile :: file ) . filter ( this :: isDirectory ) . filter ( url -> url . contains ( "classes" ) ) . collect ( Collectors . toList ( ) ) ; List < File > classpathJars = classPathEntries . stream ( ) . map ( ArtifactOrFile :: file ) . filter ( file -> file . endsWith ( ".jar" ) ) . map ( File :: new ) . collect ( Collectors . toList ( ) ) ; return WarBuilder . build ( classesUrls , classpathJars ) ; } catch ( IOException e ) { throw new RuntimeException ( "failed to build war" , e ) ; } }
|
builds war with classes inside
|
35,077
|
private static void resolveDependencies ( Collection < ArtifactSpec > collection , ShrinkwrapArtifactResolvingHelper helper ) { collection . forEach ( spec -> { if ( spec . file == null ) { ArtifactSpec resolved = helper . resolve ( spec ) ; if ( resolved != null ) { spec . file = resolved . file ; } else { throw new IllegalStateException ( "Unable to resolve artifact: " + spec . toString ( ) ) ; } } } ) ; }
|
Resolve the given collection of ArtifactSpec references . This method attempts the resolution and ensures that the references are updated to be as complete as possible .
|
35,078
|
public SocketBinding socketBinding ( String name ) { return this . socketBindings . stream ( ) . filter ( e -> e . name ( ) . equals ( name ) ) . findFirst ( ) . orElse ( null ) ; }
|
Retrieve a socket - binding by name .
|
35,079
|
public void handleDeployment ( DeploymentInfo deploymentInfo , ServletContext servletContext ) { deploymentInfo . addAuthenticationMechanism ( "MP-JWT" , new JWTAuthMechanismFactory ( ) ) ; deploymentInfo . addInnerHandlerChainWrapper ( MpJwtPrincipalHandler :: new ) ; }
|
This registers the JWTAuthMechanismFactory under the MP - JWT mechanism name
|
35,080
|
public long alloc ( int chunks , long prevPos , int prevChunks ) { long ret = s . allocReturnCode ( chunks ) ; if ( prevPos >= 0 ) s . free ( prevPos , prevChunks ) ; if ( ret >= 0 ) return ret ; while ( true ) { s . nextTier ( ) ; ret = s . allocReturnCode ( chunks ) ; if ( ret >= 0 ) return ret ; } }
|
Move only to next tiers to avoid double visiting of relocated entries during iteration
|
35,081
|
private static String getVersionFromPom ( ) { final String absolutePath = new File ( BuildVersion . class . getResource ( BuildVersion . class . getSimpleName ( ) + ".class" ) . getPath ( ) ) . getParentFile ( ) . getParentFile ( ) . getParentFile ( ) . getParentFile ( ) . getParentFile ( ) . getParentFile ( ) . getParentFile ( ) . getAbsolutePath ( ) ; final File file = new File ( absolutePath + "/pom.xml" ) ; try ( InputStreamReader reader = new InputStreamReader ( new FileInputStream ( file ) , StandardCharsets . UTF_8 ) ) { final MavenXpp3Reader xpp3Reader = new MavenXpp3Reader ( ) ; Model model = xpp3Reader . read ( reader ) ; return model . getVersion ( ) ; } catch ( NoClassDefFoundError e ) { return null ; } catch ( Exception e ) { return null ; } }
|
reads the pom file to get this version only to be used for development or within the IDE .
|
35,082
|
public void setupStyleable ( Context context , AttributeSet attrs ) { TypedArray typedArray = context . obtainStyledAttributes ( attrs , R . styleable . RoundCornerProgress ) ; radius = ( int ) typedArray . getDimension ( R . styleable . RoundCornerProgress_rcRadius , dp2px ( DEFAULT_PROGRESS_RADIUS ) ) ; padding = ( int ) typedArray . getDimension ( R . styleable . RoundCornerProgress_rcBackgroundPadding , dp2px ( DEFAULT_BACKGROUND_PADDING ) ) ; isReverse = typedArray . getBoolean ( R . styleable . RoundCornerProgress_rcReverse , false ) ; max = typedArray . getFloat ( R . styleable . RoundCornerProgress_rcMax , DEFAULT_MAX_PROGRESS ) ; progress = typedArray . getFloat ( R . styleable . RoundCornerProgress_rcProgress , DEFAULT_PROGRESS ) ; secondaryProgress = typedArray . getFloat ( R . styleable . RoundCornerProgress_rcSecondaryProgress , DEFAULT_SECONDARY_PROGRESS ) ; int colorBackgroundDefault = context . getResources ( ) . getColor ( R . color . round_corner_progress_bar_background_default ) ; colorBackground = typedArray . getColor ( R . styleable . RoundCornerProgress_rcBackgroundColor , colorBackgroundDefault ) ; int colorProgressDefault = context . getResources ( ) . getColor ( R . color . round_corner_progress_bar_progress_default ) ; colorProgress = typedArray . getColor ( R . styleable . RoundCornerProgress_rcProgressColor , colorProgressDefault ) ; int colorSecondaryProgressDefault = context . getResources ( ) . getColor ( R . color . round_corner_progress_bar_secondary_progress_default ) ; colorSecondaryProgress = typedArray . getColor ( R . styleable . RoundCornerProgress_rcSecondaryProgressColor , colorSecondaryProgressDefault ) ; typedArray . recycle ( ) ; initStyleable ( context , attrs ) ; }
|
Retrieve initial parameter from view attribute
|
35,083
|
protected void onSizeChanged ( int newWidth , int newHeight , int oldWidth , int oldHeight ) { super . onSizeChanged ( newWidth , newHeight , oldWidth , oldHeight ) ; if ( ! isInEditMode ( ) ) { totalWidth = newWidth ; drawAll ( ) ; postDelayed ( new Runnable ( ) { public void run ( ) { drawPrimaryProgress ( ) ; drawSecondaryProgress ( ) ; } } , 5 ) ; } }
|
Progress bar always refresh when view size has changed
|
35,084
|
@ SuppressWarnings ( "deprecation" ) private void drawBackgroundProgress ( ) { GradientDrawable backgroundDrawable = createGradientDrawable ( colorBackground ) ; int newRadius = radius - ( padding / 2 ) ; backgroundDrawable . setCornerRadii ( new float [ ] { newRadius , newRadius , newRadius , newRadius , newRadius , newRadius , newRadius , newRadius } ) ; if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . JELLY_BEAN ) { layoutBackground . setBackground ( backgroundDrawable ) ; } else { layoutBackground . setBackgroundDrawable ( backgroundDrawable ) ; } }
|
Draw progress background
|
35,085
|
protected GradientDrawable createGradientDrawable ( int color ) { GradientDrawable gradientDrawable = new GradientDrawable ( ) ; gradientDrawable . setShape ( GradientDrawable . RECTANGLE ) ; gradientDrawable . setColor ( color ) ; return gradientDrawable ; }
|
Create an empty color rectangle gradient drawable
|
35,086
|
private void setupReverse ( LinearLayout layoutProgress ) { RelativeLayout . LayoutParams progressParams = ( RelativeLayout . LayoutParams ) layoutProgress . getLayoutParams ( ) ; removeLayoutParamsRule ( progressParams ) ; if ( isReverse ) { progressParams . addRule ( RelativeLayout . ALIGN_PARENT_RIGHT ) ; if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . JELLY_BEAN_MR1 ) progressParams . addRule ( RelativeLayout . ALIGN_PARENT_END ) ; } else { progressParams . addRule ( RelativeLayout . ALIGN_PARENT_LEFT ) ; if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . JELLY_BEAN_MR1 ) progressParams . addRule ( RelativeLayout . ALIGN_PARENT_START ) ; } layoutProgress . setLayoutParams ( progressParams ) ; }
|
Change progress position by depending on isReverse flag
|
35,087
|
private void removeLayoutParamsRule ( RelativeLayout . LayoutParams layoutParams ) { if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . JELLY_BEAN_MR1 ) { layoutParams . removeRule ( RelativeLayout . ALIGN_PARENT_RIGHT ) ; layoutParams . removeRule ( RelativeLayout . ALIGN_PARENT_END ) ; layoutParams . removeRule ( RelativeLayout . ALIGN_PARENT_LEFT ) ; layoutParams . removeRule ( RelativeLayout . ALIGN_PARENT_START ) ; } else { layoutParams . addRule ( RelativeLayout . ALIGN_PARENT_RIGHT , 0 ) ; layoutParams . addRule ( RelativeLayout . ALIGN_PARENT_LEFT , 0 ) ; } }
|
Remove all of relative align rule
|
35,088
|
public int sendTCP ( Object object ) { if ( object == null ) throw new IllegalArgumentException ( "object cannot be null." ) ; try { int length = tcp . send ( this , object ) ; if ( length == 0 ) { if ( TRACE ) trace ( "kryonet" , this + " TCP had nothing to send." ) ; } else if ( DEBUG ) { String objectString = object == null ? "null" : object . getClass ( ) . getSimpleName ( ) ; if ( ! ( object instanceof FrameworkMessage ) ) { debug ( "kryonet" , this + " sent TCP: " + objectString + " (" + length + ")" ) ; } else if ( TRACE ) { trace ( "kryonet" , this + " sent TCP: " + objectString + " (" + length + ")" ) ; } } return length ; } catch ( IOException ex ) { if ( DEBUG ) debug ( "kryonet" , "Unable to send TCP with connection: " + this , ex ) ; close ( ) ; return 0 ; } catch ( KryoNetException ex ) { if ( ERROR ) error ( "kryonet" , "Unable to send TCP with connection: " + this , ex ) ; close ( ) ; return 0 ; } }
|
Sends the object over the network using TCP .
|
35,089
|
public int sendUDP ( Object object ) { if ( object == null ) throw new IllegalArgumentException ( "object cannot be null." ) ; SocketAddress address = udpRemoteAddress ; if ( address == null && udp != null ) address = udp . connectedAddress ; if ( address == null && isConnected ) throw new IllegalStateException ( "Connection is not connected via UDP." ) ; try { if ( address == null ) throw new SocketException ( "Connection is closed." ) ; int length = udp . send ( this , object , address ) ; if ( length == 0 ) { if ( TRACE ) trace ( "kryonet" , this + " UDP had nothing to send." ) ; } else if ( DEBUG ) { if ( length != - 1 ) { String objectString = object == null ? "null" : object . getClass ( ) . getSimpleName ( ) ; if ( ! ( object instanceof FrameworkMessage ) ) { debug ( "kryonet" , this + " sent UDP: " + objectString + " (" + length + ")" ) ; } else if ( TRACE ) { trace ( "kryonet" , this + " sent UDP: " + objectString + " (" + length + ")" ) ; } } else debug ( "kryonet" , this + " was unable to send, UDP socket buffer full." ) ; } return length ; } catch ( IOException ex ) { if ( DEBUG ) debug ( "kryonet" , "Unable to send UDP with connection: " + this , ex ) ; close ( ) ; return 0 ; } catch ( KryoNetException ex ) { if ( ERROR ) error ( "kryonet" , "Unable to send UDP with connection: " + this , ex ) ; close ( ) ; return 0 ; } }
|
Sends the object over the network using UDP .
|
35,090
|
public InetSocketAddress getRemoteAddressTCP ( ) { SocketChannel socketChannel = tcp . socketChannel ; if ( socketChannel != null ) { Socket socket = tcp . socketChannel . socket ( ) ; if ( socket != null ) { return ( InetSocketAddress ) socket . getRemoteSocketAddress ( ) ; } } return null ; }
|
Returns the IP address and port of the remote end of the TCP connection or null if this connection is not connected .
|
35,091
|
public InetSocketAddress getRemoteAddressUDP ( ) { InetSocketAddress connectedAddress = udp . connectedAddress ; if ( connectedAddress != null ) return connectedAddress ; return udpRemoteAddress ; }
|
Returns the IP address and port of the remote end of the UDP connection or null if this connection is not connected .
|
35,092
|
public void close ( ) { Connection [ ] connections = this . connections ; for ( int i = 0 ; i < connections . length ; i ++ ) connections [ i ] . removeListener ( invokeListener ) ; synchronized ( instancesLock ) { ArrayList < ObjectSpace > temp = new ArrayList ( Arrays . asList ( instances ) ) ; temp . remove ( this ) ; instances = temp . toArray ( new ObjectSpace [ temp . size ( ) ] ) ; } if ( TRACE ) trace ( "kryonet" , "Closed ObjectSpace." ) ; }
|
Causes this ObjectSpace to stop listening to the connections for method invocation messages .
|
35,093
|
public void addConnection ( Connection connection ) { if ( connection == null ) throw new IllegalArgumentException ( "connection cannot be null." ) ; synchronized ( connectionsLock ) { Connection [ ] newConnections = new Connection [ connections . length + 1 ] ; newConnections [ 0 ] = connection ; System . arraycopy ( connections , 0 , newConnections , 1 , connections . length ) ; connections = newConnections ; } connection . addListener ( invokeListener ) ; if ( TRACE ) trace ( "kryonet" , "Added connection to ObjectSpace: " + connection ) ; }
|
Allows the remote end of the specified connection to access objects registered in this ObjectSpace .
|
35,094
|
public void removeConnection ( Connection connection ) { if ( connection == null ) throw new IllegalArgumentException ( "connection cannot be null." ) ; connection . removeListener ( invokeListener ) ; synchronized ( connectionsLock ) { ArrayList < Connection > temp = new ArrayList ( Arrays . asList ( connections ) ) ; temp . remove ( connection ) ; connections = temp . toArray ( new Connection [ temp . size ( ) ] ) ; } if ( TRACE ) trace ( "kryonet" , "Removed connection from ObjectSpace: " + connection ) ; }
|
Removes the specified connection it will no longer be able to access objects registered in this ObjectSpace .
|
35,095
|
static Object getRegisteredObject ( Connection connection , int objectID ) { ObjectSpace [ ] instances = ObjectSpace . instances ; for ( int i = 0 , n = instances . length ; i < n ; i ++ ) { ObjectSpace objectSpace = instances [ i ] ; Connection [ ] connections = objectSpace . connections ; for ( int j = 0 ; j < connections . length ; j ++ ) { if ( connections [ j ] != connection ) continue ; Object object = objectSpace . idToObject . get ( objectID ) ; if ( object != null ) return object ; } } return null ; }
|
Returns the first object registered with the specified ID in any of the ObjectSpaces the specified connection belongs to .
|
35,096
|
static int getRegisteredID ( Connection connection , Object object ) { ObjectSpace [ ] instances = ObjectSpace . instances ; for ( int i = 0 , n = instances . length ; i < n ; i ++ ) { ObjectSpace objectSpace = instances [ i ] ; Connection [ ] connections = objectSpace . connections ; for ( int j = 0 ; j < connections . length ; j ++ ) { if ( connections [ j ] != connection ) continue ; int id = objectSpace . objectToID . get ( object , Integer . MAX_VALUE ) ; if ( id != Integer . MAX_VALUE ) return id ; } } return Integer . MAX_VALUE ; }
|
Returns the first ID registered for the specified object with any of the ObjectSpaces the specified connection belongs to or Integer . MAX_VALUE if not found .
|
35,097
|
static public void registerClasses ( final Kryo kryo ) { kryo . register ( Object [ ] . class ) ; kryo . register ( InvokeMethod . class ) ; FieldSerializer < InvokeMethodResult > resultSerializer = new FieldSerializer < InvokeMethodResult > ( kryo , InvokeMethodResult . class ) { public void write ( Kryo kryo , Output output , InvokeMethodResult result ) { super . write ( kryo , output , result ) ; output . writeInt ( result . objectID , true ) ; } public InvokeMethodResult read ( Kryo kryo , Input input , Class < InvokeMethodResult > type ) { InvokeMethodResult result = super . read ( kryo , input , type ) ; result . objectID = input . readInt ( true ) ; return result ; } } ; resultSerializer . removeField ( "objectID" ) ; kryo . register ( InvokeMethodResult . class , resultSerializer ) ; kryo . register ( InvocationHandler . class , new Serializer ( ) { public void write ( Kryo kryo , Output output , Object object ) { RemoteInvocationHandler handler = ( RemoteInvocationHandler ) Proxy . getInvocationHandler ( object ) ; output . writeInt ( handler . objectID , true ) ; } public Object read ( Kryo kryo , Input input , Class type ) { int objectID = input . readInt ( true ) ; Connection connection = ( Connection ) kryo . getContext ( ) . get ( "connection" ) ; Object object = getRegisteredObject ( connection , objectID ) ; if ( WARN && object == null ) warn ( "kryonet" , "Unknown object ID " + objectID + " for connection: " + connection ) ; return object ; } } ) ; }
|
Registers the classes needed to use ObjectSpaces . This should be called before any connections are opened .
|
35,098
|
public void ensureCapacity ( int additionalCapacity ) { int sizeNeeded = size + additionalCapacity ; if ( sizeNeeded >= threshold ) resize ( ObjectMap . nextPowerOfTwo ( ( int ) ( sizeNeeded / loadFactor ) ) ) ; }
|
Increases the size of the backing array to acommodate the specified number of additional items . Useful before adding many items to avoid multiple backing array resizes .
|
35,099
|
public InetAddress discoverHost ( int udpPort , int timeoutMillis ) { DatagramSocket socket = null ; try { socket = new DatagramSocket ( ) ; broadcast ( udpPort , socket ) ; socket . setSoTimeout ( timeoutMillis ) ; DatagramPacket packet = discoveryHandler . onRequestNewDatagramPacket ( ) ; try { socket . receive ( packet ) ; } catch ( SocketTimeoutException ex ) { if ( INFO ) info ( "kryonet" , "Host discovery timed out." ) ; return null ; } if ( INFO ) info ( "kryonet" , "Discovered server: " + packet . getAddress ( ) ) ; discoveryHandler . onDiscoveredHost ( packet , getKryo ( ) ) ; return packet . getAddress ( ) ; } catch ( IOException ex ) { if ( ERROR ) error ( "kryonet" , "Host discovery failed." , ex ) ; return null ; } finally { if ( socket != null ) socket . close ( ) ; discoveryHandler . onFinally ( ) ; } }
|
Broadcasts a UDP message on the LAN to discover any running servers . The address of the first server to respond is returned .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.