idx
int64 0
165k
| question
stringlengths 73
4.15k
| target
stringlengths 5
918
| len_question
int64 21
890
| len_target
int64 3
255
|
|---|---|---|---|---|
158,400
|
public Archive < ? > createDefaultDeployment ( ) throws Exception { if ( this . server == null ) { throw SwarmMessages . MESSAGES . containerNotStarted ( "createDefaultDeployment()" ) ; } return this . server . deployer ( ) . createDefaultDeployment ( ) ; }
|
Retrieve the default ShrinkWrap deployment .
| 66
| 11
|
158,401
|
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
| 30
|
158,402
|
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 .
| 81
| 9
|
158,403
|
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 ; // Success } //Try to doDownload the snapshot version 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 ; //Success } } catch ( XPathExpressionException | IOException ex ) { Module . getModuleLogger ( ) . trace ( ex , "Could not doDownload '%s' from '%s' repository" , artifactRelativeHttpPath , remoteRepos ) ; // try next one } } } return null ; }
|
Download artifact from remote repository .
| 577
| 6
|
158,404
|
File doDownload ( String remoteRepos , String artifactAbsoluteHttpPath , String artifactRelativeHttpPath , ArtifactCoordinates artifactCoordinates , String packaging , File targetArtifactPomDirectory , File targetArtifactDirectory ) { //Download POM 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 ) ; // try next one } //Download Artifact 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 ) ; // try next one } return null ; }
|
Download the POM and the artifact file and return it .
| 335
| 12
|
158,405
|
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 .
| 161
| 6
|
158,406
|
String toGradleArtifactPath ( ArtifactCoordinates artifactCoordinates ) { // e.g.: org/jboss/ws/cxf/jbossws-cxf-resources/5.1.5.Final/jbossws-cxf-resources-5.1.5.Final String pathWithMissingClassifier = artifactCoordinates . relativeArtifactPath ( ' ' ) ; StringBuilder sb = new StringBuilder ( pathWithMissingClassifier ) ; if ( artifactCoordinates . getClassifier ( ) != null && artifactCoordinates . getClassifier ( ) . length ( ) > 0 ) { // org/jboss/ws/cxf/jbossws-cxf-resources/5.1.5.Final/jbossws-cxf-resources-5.1.5.Final-wildfly1000 sb . append ( "-" ) . append ( artifactCoordinates . getClassifier ( ) ) ; } return sb . toString ( ) ; }
|
Build the artifact path including the classifier .
| 218
| 9
|
158,407
|
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 ) { // Impossible throw new IllegalArgumentException ( "unknown algorithm " + MD5_ALGORITHM , e ) ; } catch ( UnsupportedEncodingException e ) { // Impossible except with IBM :) throw new IllegalArgumentException ( "unknown charset UTF-8" , e ) ; } }
|
Compute gradle uuid for artifacts .
| 175
| 9
|
158,408
|
private DeclaredDependencies getDependenciesViaIdeaModel ( ProjectConnection connection ) { DeclaredDependencies declaredDependencies = new DeclaredDependencies ( ) ; // 1. Get the IdeaProject model from the Gradle connection. IdeaProject prj = connection . getModel ( IdeaProject . class ) ; prj . getModules ( ) . forEach ( this :: computeProjectDependencies ) ; // 2. Find the IdeaModule that maps to the project that we are looking at. Optional < ? extends IdeaModule > prjModule = prj . getModules ( ) . stream ( ) . filter ( m -> m . getGradleProject ( ) . getProjectDirectory ( ) . toPath ( ) . equals ( rootPath ) ) . findFirst ( ) ; // We need to return the following collection of dependencies, // 1. For the current project, return all artifacts that are marked as ["COMPILE", "TEST"] // 2. From the upstream-projects, add all dependencies that are marked as ["COMPILE"] // 3. For the current project, iterate through each dependencies marked as ["PROVIDED"] and do the following, // a.) Check if they are already available from 1 & 2. If yes, then nothing to do here. // b.) Check if this entry is defined as ["TEST"] in the upstream-projects. If yes, then include it. // -- The reason for doing this is because of the optimization that Gradle does on the IdeaModule library set. 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 .
| 785
| 11
|
158,409
|
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 .
| 72
| 18
|
158,410
|
void activate ( ) { nodes ( ) . flatMap ( e -> e . allKeysRecursively ( ) ) . distinct ( ) . forEach ( key -> { activate ( key ) ; } ) ; }
|
Activate the strategy .
| 44
| 5
|
158,411
|
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 .
| 57
| 17
|
158,412
|
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 .
| 101
| 17
|
158,413
|
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
| 97
| 11
|
158,414
|
@ 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 ) ; // the predicate handler takes care that all of the above // will only be enacted on relevant web contexts 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 .
| 541
| 19
|
158,415
|
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
| 82
| 14
|
158,416
|
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 .
| 152
| 14
|
158,417
|
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 .
| 94
| 20
|
158,418
|
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 -> { // 1. Do we need to resolve this entry? final String specGAV = String . format ( "%s:%s:%s" , s . groupId ( ) , s . artifactId ( ) , s . version ( ) ) ; boolean resolved = s . file != null ; boolean projectEntry = projectGAVCoordinates . containsKey ( specGAV ) ; // 2. Should we skip this spec? if ( excludeDefaults && FractionDescriptor . THORNTAIL_GROUP_ID . equals ( s . groupId ( ) ) && ! projectEntry ) { return ; } // 3. Should this entry be resolved? if ( ! resolved || transitive ) { // a.) Does this entry represent a project dependency? 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 { // 4. Nothing else to do, just add the spec to the result. result . add ( s ) ; } } ) ; // 5. Are there any specs that need resolution? if ( ! dependencySet . isEmpty ( ) ) { config . getResolvedConfiguration ( ) . getResolvedArtifacts ( ) . stream ( ) . map ( ra -> asDescriptor ( "compile" , ra ) . toArtifactSpec ( ) ) . forEach ( result :: add ) ; } return result ; }
|
Resolve the given artifact specifications .
| 619
| 7
|
158,419
|
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 ( ) ; } // // Step 1 // ------ // Iterate through the hierarchy of the given configuration and determine the correct scope of all // "top-level" dependencies. // Map < String , String > dependencyScopeMap = new HashMap <> ( ) ; // In case of custom configurations, we will assign the scope to what has been requested 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 ) ) ; } ) ; } ) ; // // Step 2 // ------ // Assuming that the given configuration can be resolved, get the resolved artifacts and populate the return Map. // 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 ) { // Should never happen. 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 .
| 683
| 41
|
158,420
|
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 .
| 177
| 9
|
158,421
|
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 .
| 130
| 32
|
158,422
|
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 .
| 38
| 15
|
158,423
|
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
| 62
| 6
|
158,424
|
public static FileSystemLayout create ( String root ) { // THORN-2178: Check if a System property has been set to a specific implementation class. String implClassName = System . getProperty ( CUSTOM_LAYOUT_CLASS ) ; if ( implClassName != null ) { implClassName = implClassName . trim ( ) ; if ( ! implClassName . isEmpty ( ) ) { FileSystemLayout layout = null ; // Attempt to load the specified class implementation. ClassLoader loader = Thread . currentThread ( ) . getContextClassLoader ( ) ; try { Class < ? > clazz = loader . loadClass ( implClassName ) ; // Check if clazz is an implementation of FileSystemLayout or not. if ( FileSystemLayout . class . isAssignableFrom ( clazz ) ) { Class < ? extends FileSystemLayout > implClazz = clazz . asSubclass ( FileSystemLayout . class ) ; // Check if we have an appropriate constructor or not. 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
| 601
| 5
|
158,425
|
@ Override public void process ( ) throws Exception { // if the deployment is Implicit, we don't want to process it if ( deploymentContext != null && deploymentContext . isImplicit ( ) ) { return ; } try { // First register OpenApiServletContextListener which triggers the final init 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 ) ; // Set models from annotations and static file 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 .
| 238
| 12
|
158,426
|
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 the original throw e ; } } }
|
Helper to attempt forming a URL from a String in a sensible fashion .
| 85
| 14
|
158,427
|
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
| 203
| 11
|
158,428
|
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
| 81
| 5
|
158,429
|
void observesAfterBeanDiscovery ( @ Observes final AfterBeanDiscovery event , final BeanManager beanManager ) { log . debugf ( "observesAfterBeanDiscovery, %s" , claims ) ; installClaimValueProducerMethodsViaSyntheticBeans ( event , beanManager ) ; }
|
Create producer methods for each ClaimValue injection site
| 68
| 9
|
158,430
|
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 .
| 98
| 11
|
158,431
|
public Set < ArtifactSpec > getTransientDependencies ( ) { if ( null == allTransient ) { allTransient = getTransientDependencies ( true , true ) ; } return allTransient ; }
|
Get the collection of all transient dependencies defined in this instance .
| 47
| 12
|
158,432
|
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 .
| 161
| 11
|
158,433
|
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 .
| 107
| 11
|
158,434
|
public EnhancedServer remoteConnection ( String name ) { return remoteConnection ( name , ( config ) - > { } ) ; } /** * Setup a named remote connection to a remote message broker. * * @param name The name of the connection. * @param config The configuration. * @return This server. */ public EnhancedServer remoteConnection ( String name , RemoteConnection . Consumer config ) { return remoteConnection ( ( ) -> { RemoteConnection connection = new RemoteConnection ( name ) ; config . accept ( connection ) ; return connection ; } ) ; } /** * Setup a remote connection to a remote message broker. * * @param supplier The supplier of the configuration. * @return This server. */ public EnhancedServer remoteConnection ( RemoteConnection . Supplier supplier ) { RemoteConnection connection = supplier . get ( ) ; this . remoteConnections . add ( connection ) ; return this ; } public EnhancedServer enableRemote ( ) { enableHTTPConnections ( ) ; connectionFactory ( new ConnectionFactory <> ( "RemoteConnectionFactory" ) . connectors ( Collections . singletonList ( "http-connector" ) ) . entries ( "java:/RemoteConnectionFactory" , "java:jboss/exported/jms/RemoteConnectionFactory" ) ) ; return this ; } private EnhancedServer enableHTTPConnections ( ) { if ( this . subresources ( ) . acceptor ( ( "http-acceptor" ) ) != null ) { return this ; } httpAcceptor ( new HTTPAcceptor ( "http-acceptor" ) . httpListener ( "default" ) ) ; httpAcceptor ( new HTTPAcceptor ( "http-acceptor-throughput" ) . httpListener ( "default" ) . param ( "batch-delay" , "50" ) . param ( "direct-deliver" , "false" ) ) ; httpConnector ( new HTTPConnector ( HTTP_CONNECTOR ) . socketBinding ( "http" ) . endpoint ( "http-acceptor" ) ) ; httpConnector ( new HTTPConnector ( "http-connector-throughput" ) . socketBinding ( "http" ) . endpoint ( "http-acceptor-throughput" ) . param ( "batch-delay" , "50" ) ) ; return this ; } @ SuppressWarnings ( "unchecked" ) @ Override public EnhancedServer jmsQueue ( String childKey , JMSQueueConsumer config ) { return super . jmsQueue ( childKey , ( q ) - > { if ( config != null ) { config . accept ( q ) ; } if ( q . entries ( ) == null || q . entries ( ) . isEmpty ( ) ) { q . entry ( "java:/jms/queue/" + childKey ) ; } } ) ; }
|
Setup a default named remote connection to a remote message broker .
| 588
| 12
|
158,435
|
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
| 54
| 10
|
158,436
|
private void cleanup ( ) throws IOException { JarFileManager . INSTANCE . close ( ) ; TempFileManager . INSTANCE . close ( ) ; MavenResolvers . close ( ) ; }
|
Clean up all open resources .
| 42
| 6
|
158,437
|
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
| 159
| 5
|
158,438
|
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 .
| 146
| 11
|
158,439
|
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 ( ) ) { // it's really a snapshot 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 .
| 195
| 11
|
158,440
|
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 .
| 46
| 9
|
158,441
|
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 .
| 46
| 11
|
158,442
|
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 .
| 46
| 9
|
158,443
|
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 .
| 46
| 11
|
158,444
|
public String getRelativePath ( ) { if ( basePath == null ) { return source . toString ( ) ; } return basePath . relativize ( source ) . toString ( ) ; }
|
Gets the relative file path instead of the absolute .
| 43
| 11
|
158,445
|
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 .
| 52
| 11
|
158,446
|
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 .
| 76
| 12
|
158,447
|
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 .
| 180
| 11
|
158,448
|
private static JoseFactory loadSpi ( ClassLoader cl ) { if ( cl == null ) { return null ; } // start from the root CL and go back down to the TCCL 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 .
| 294
| 12
|
158,449
|
public static void addService ( ServiceTarget serviceTarget , SwarmContentRepository repository ) { serviceTarget . addService ( SERVICE_NAME , repository ) . setInitialMode ( ServiceController . Mode . ACTIVE ) . install ( ) ; }
|
Install the service .
| 49
| 4
|
158,450
|
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 .
| 70
| 41
|
158,451
|
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
| 179
| 6
|
158,452
|
private static void resolveDependencies ( Collection < ArtifactSpec > collection , ShrinkwrapArtifactResolvingHelper helper ) { // Identify the artifact specs that need resolution. // Ideally, there should be none at this point. collection . forEach ( spec -> { if ( spec . file == null ) { // Resolve it. 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 .
| 128
| 29
|
158,453
|
public SocketBinding socketBinding ( String name ) { return this . socketBindings . stream ( ) . filter ( e -> e . name ( ) . equals ( name ) ) . findFirst ( ) . orElse ( null ) ; }
|
Retrieve a socket - binding by name .
| 51
| 9
|
158,454
|
@ Override 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
| 74
| 18
|
158,455
|
@ Override 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
| 94
| 14
|
158,456
|
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 ) { // if you want to get the version possibly in development add in to your pom // pax-url-aether.jar 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 .
| 243
| 20
|
158,457
|
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
| 469
| 7
|
158,458
|
@ Override 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 ( ) { @ Override public void run ( ) { drawPrimaryProgress ( ) ; drawSecondaryProgress ( ) ; } } , 5 ) ; } }
|
Progress bar always refresh when view size has changed
| 108
| 9
|
158,459
|
@ 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
| 158
| 3
|
158,460
|
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
| 65
| 8
|
158,461
|
private void setupReverse ( LinearLayout layoutProgress ) { RelativeLayout . LayoutParams progressParams = ( RelativeLayout . LayoutParams ) layoutProgress . getLayoutParams ( ) ; removeLayoutParamsRule ( progressParams ) ; if ( isReverse ) { progressParams . addRule ( RelativeLayout . ALIGN_PARENT_RIGHT ) ; // For support with RTL on API 17 or more if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . JELLY_BEAN_MR1 ) progressParams . addRule ( RelativeLayout . ALIGN_PARENT_END ) ; } else { progressParams . addRule ( RelativeLayout . ALIGN_PARENT_LEFT ) ; // For support with RTL on API 17 or more 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
| 239
| 11
|
158,462
|
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
| 178
| 6
|
158,463
|
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 .
| 279
| 10
|
158,464
|
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 .
| 387
| 10
|
158,465
|
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 .
| 72
| 23
|
158,466
|
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 .
| 44
| 23
|
158,467
|
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 .
| 120
| 16
|
158,468
|
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 .
| 124
| 17
|
158,469
|
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 .
| 118
| 20
|
158,470
|
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 ] ; // Check if the connection is in this ObjectSpace. Connection [ ] connections = objectSpace . connections ; for ( int j = 0 ; j < connections . length ; j ++ ) { if ( connections [ j ] != connection ) continue ; // Find an object with the objectID. 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 .
| 145
| 22
|
158,471
|
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 ] ; // Check if the connection is in this ObjectSpace. Connection [ ] connections = objectSpace . connections ; for ( int j = 0 ; j < connections . length ; j ++ ) { if ( connections [ j ] != connection ) continue ; // Find an ID with the object. 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 .
| 156
| 31
|
158,472
|
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 .
| 396
| 21
|
158,473
|
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 .
| 56
| 32
|
158,474
|
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 .
| 227
| 25
|
158,475
|
public List < InetAddress > discoverHosts ( int udpPort , int timeoutMillis ) { List < InetAddress > hosts = new ArrayList < InetAddress > ( ) ; DatagramSocket socket = null ; try { socket = new DatagramSocket ( ) ; broadcast ( udpPort , socket ) ; socket . setSoTimeout ( timeoutMillis ) ; while ( true ) { DatagramPacket packet = discoveryHandler . onRequestNewDatagramPacket ( ) ; try { socket . receive ( packet ) ; } catch ( SocketTimeoutException ex ) { if ( INFO ) info ( "kryonet" , "Host discovery timed out." ) ; return hosts ; } if ( INFO ) info ( "kryonet" , "Discovered server: " + packet . getAddress ( ) ) ; discoveryHandler . onDiscoveredHost ( packet , getKryo ( ) ) ; hosts . add ( packet . getAddress ( ) ) ; } } catch ( IOException ex ) { if ( ERROR ) error ( "kryonet" , "Host discovery failed." , ex ) ; return hosts ; } finally { if ( socket != null ) socket . close ( ) ; discoveryHandler . onFinally ( ) ; } }
|
Broadcasts a UDP message on the LAN to discover any running servers .
| 260
| 14
|
158,476
|
public void sendToAllTCP ( Object object ) { Connection [ ] connections = this . connections ; for ( int i = 0 , n = connections . length ; i < n ; i ++ ) { Connection connection = connections [ i ] ; connection . sendTCP ( object ) ; } }
|
BOZO - Provide mechanism for sending to multiple clients without serializing multiple times .
| 61
| 17
|
158,477
|
@ Override public void internalWrite ( Server server , Query query , ImmutableList < Result > results ) throws Exception { checkFile ( query ) ; List < String > typeNames = getTypeNames ( ) ; for ( Result result : results ) { String [ ] keyString = KeyUtils . getKeyString ( server , query , result , typeNames , null ) . split ( "\\." ) ; if ( isNumeric ( result . getValue ( ) ) && filters . contains ( keyString [ 2 ] ) ) { int thresholdPos = filters . indexOf ( keyString [ 2 ] ) ; StringBuilder sb = new StringBuilder ( ) ; sb . append ( "[" ) ; sb . append ( result . getEpoch ( ) ) ; sb . append ( "] PROCESS_SERVICE_CHECK_RESULT;" ) ; sb . append ( nagiosHost ) ; sb . append ( ";" ) ; if ( prefix != null ) { sb . append ( prefix ) ; } sb . append ( keyString [ 2 ] ) ; if ( suffix != null ) { sb . append ( suffix ) ; } sb . append ( ";" ) ; sb . append ( nagiosCheckValue ( result . getValue ( ) . toString ( ) , thresholds . get ( thresholdPos ) ) ) ; sb . append ( ";" ) ; //Missing the performance information logger . info ( sb . toString ( ) ) ; } } }
|
The meat of the output . Nagios format ..
| 317
| 10
|
158,478
|
protected String nagiosCheckValue ( String value , String composeRange ) { List < String > simpleRange = Arrays . asList ( composeRange . split ( "," ) ) ; double doubleValue = Double . parseDouble ( value ) ; if ( composeRange . isEmpty ( ) ) { return "0" ; } if ( simpleRange . size ( ) == 1 ) { if ( composeRange . endsWith ( "," ) ) { if ( valueCheck ( doubleValue , simpleRange . get ( 0 ) ) ) { return "1" ; } else { return "0" ; } } else if ( valueCheck ( doubleValue , simpleRange . get ( 0 ) ) ) { return "2" ; } else { return "0" ; } } if ( valueCheck ( doubleValue , simpleRange . get ( 1 ) ) ) { return "2" ; } if ( valueCheck ( doubleValue , simpleRange . get ( 0 ) ) ) { return "1" ; } return "0" ; }
|
Define if a value is in a critical warning or ok state .
| 214
| 14
|
158,479
|
@ Override public void prepareSender ( ) throws LifecycleException { if ( host == null || port == null ) { throw new LifecycleException ( "Host and port for " + this . getClass ( ) . getSimpleName ( ) + " output can't be null" ) ; } try { this . dgSocket = new DatagramSocket ( ) ; this . address = new InetSocketAddress ( host , port ) ; } catch ( SocketException sockExc ) { log . error ( "Failed to create a datagram socket" , sockExc ) ; throw new LifecycleException ( sockExc ) ; } }
|
Setup at start of the writer .
| 132
| 7
|
158,480
|
@ Override protected void sendOutput ( String metricLine ) throws IOException { DatagramPacket packet ; byte [ ] data ; data = metricLine . getBytes ( "UTF-8" ) ; packet = new DatagramPacket ( data , 0 , data . length , this . address ) ; this . dgSocket . send ( packet ) ; }
|
Send a single metric to TCollector .
| 75
| 9
|
158,481
|
public static boolean isNumeric ( Object value ) { if ( value == null ) return false ; if ( value instanceof Number ) return true ; if ( value instanceof String ) { String stringValue = ( String ) value ; if ( isNullOrEmpty ( stringValue ) ) return true ; return isNumber ( stringValue ) ; } return false ; }
|
Useful for figuring out if an Object is a number .
| 74
| 12
|
158,482
|
@ Override public void internalWrite ( Server server , Query query , ImmutableList < Result > results ) throws Exception { this . startOutput ( ) ; for ( String formattedResult : messageFormatter . formatResults ( results , server ) ) { log . debug ( "Sending result: {}" , formattedResult ) ; this . sendOutput ( formattedResult ) ; } this . finishOutput ( ) ; }
|
Write the results of the query .
| 85
| 7
|
158,483
|
public static String getKeyString ( Server server , Query query , Result result , List < String > typeNames , String rootPrefix ) { StringBuilder sb = new StringBuilder ( ) ; addRootPrefix ( rootPrefix , sb ) ; addAlias ( server , sb ) ; addSeparator ( sb ) ; addMBeanIdentifier ( query , result , sb ) ; addSeparator ( sb ) ; addTypeName ( query , result , typeNames , sb ) ; addKeyString ( query , result , sb ) ; return sb . toString ( ) ; }
|
Gets the key string .
| 132
| 6
|
158,484
|
public static String getKeyString ( Query query , Result result , List < String > typeNames ) { StringBuilder sb = new StringBuilder ( ) ; addMBeanIdentifier ( query , result , sb ) ; addSeparator ( sb ) ; addTypeName ( query , result , typeNames , sb ) ; addKeyString ( query , result , sb ) ; return sb . toString ( ) ; }
|
Gets the key string without rootPrefix nor Alias
| 93
| 12
|
158,485
|
public static String getPrefixedKeyString ( Query query , Result result , List < String > typeNames ) { StringBuilder sb = new StringBuilder ( ) ; addTypeName ( query , result , typeNames , sb ) ; addKeyString ( query , result , sb ) ; return sb . toString ( ) ; }
|
Gets the key string without rootPrefix or Alias
| 71
| 12
|
158,486
|
private static void addMBeanIdentifier ( Query query , Result result , StringBuilder sb ) { if ( result . getKeyAlias ( ) != null ) { sb . append ( result . getKeyAlias ( ) ) ; } else if ( query . isUseObjDomainAsKey ( ) ) { sb . append ( StringUtils . cleanupStr ( result . getObjDomain ( ) , query . isAllowDottedKeys ( ) ) ) ; } else { sb . append ( StringUtils . cleanupStr ( result . getClassName ( ) ) ) ; } }
|
Adds a key to the StringBuilder
| 124
| 7
|
158,487
|
@ Override public void validateSetup ( Server server , Query query ) throws ValidationException { // Determine the spoofed hostname spoofedHostName = getSpoofedHostName ( server . getHost ( ) , server . getAlias ( ) ) ; log . debug ( "Validated Ganglia metric [" + HOST + ": " + host + ", " + PORT + ": " + port + ", " + ADDRESSING_MODE + ": " + addressingMode + ", " + TTL + ": " + ttl + ", " + V31 + ": " + v31 + ", " + UNITS + ": '" + units + "', " + SLOPE + ": " + slope + ", " + TMAX + ": " + tmax + ", " + DMAX + ": " + dmax + ", " + SPOOF_NAME + ": " + spoofedHostName + ", " + GROUP_NAME + ": '" + groupName + "']" ) ; }
|
Parse and validate settings .
| 220
| 6
|
158,488
|
@ Override public void internalWrite ( Server server , Query query , ImmutableList < Result > results ) throws Exception { for ( final Result result : results ) { final String name = KeyUtils . getKeyString ( query , result , getTypeNames ( ) ) ; Object transformedValue = valueTransformer . apply ( result . getValue ( ) ) ; GMetricType dataType = getType ( result . getValue ( ) ) ; log . debug ( "Sending Ganglia metric {}={} [type={}]" , name , transformedValue , dataType ) ; try ( GMetric metric = new GMetric ( host , port , addressingMode , ttl , v31 , null , spoofedHostName ) ) { metric . announce ( name , transformedValue . toString ( ) , dataType , units , slope , tmax , dmax , groupName ) ; } } }
|
Send query result values to Ganglia .
| 186
| 8
|
158,489
|
private static GMetricType getType ( final Object obj ) { // FIXME This is far from covering all cases. // FIXME Wasteful use of high capacity types (eg Short => INT32) // Direct mapping when possible if ( obj instanceof Long || obj instanceof Integer || obj instanceof Byte || obj instanceof Short ) return GMetricType . INT32 ; if ( obj instanceof Float ) return GMetricType . FLOAT ; if ( obj instanceof Double ) return GMetricType . DOUBLE ; // Convert to double or int if possible try { Double . parseDouble ( obj . toString ( ) ) ; return GMetricType . DOUBLE ; } catch ( NumberFormatException e ) { // Not a double } try { Integer . parseInt ( obj . toString ( ) ) ; return GMetricType . UINT32 ; } catch ( NumberFormatException e ) { // Not an int } return GMetricType . STRING ; }
|
Guess the Ganglia gmetric type to use for a given object .
| 201
| 16
|
158,490
|
public static Boolean getBooleanSetting ( Map < String , Object > settings , String key , Boolean defaultVal ) { final Object value = settings . get ( key ) ; if ( value == null ) { return defaultVal ; } if ( value instanceof Boolean ) { return ( Boolean ) value ; } if ( value instanceof String ) { return Boolean . valueOf ( ( String ) value ) ; } return defaultVal ; }
|
Gets a Boolean value for the key returning the default value given if not specified or not a valid boolean value .
| 88
| 23
|
158,491
|
public static Integer getIntegerSetting ( Map < String , Object > settings , String key , Integer defaultVal ) { final Object value = settings . get ( key ) ; if ( value == null ) { return defaultVal ; } if ( value instanceof Number ) { return ( ( Number ) value ) . intValue ( ) ; } if ( value instanceof String ) { try { return Integer . parseInt ( ( String ) value ) ; } catch ( NumberFormatException e ) { return defaultVal ; } } return defaultVal ; }
|
Gets an Integer value for the key returning the default value given if not specified or not a valid numeric value .
| 110
| 23
|
158,492
|
public static String getStringSetting ( Map < String , Object > settings , String key , String defaultVal ) { final Object value = settings . get ( key ) ; return value != null ? value . toString ( ) : defaultVal ; }
|
Gets a String value for the setting returning the default value if not specified .
| 50
| 16
|
158,493
|
protected static int getIntSetting ( Map < String , Object > settings , String key , int defaultVal ) throws IllegalArgumentException { if ( settings . containsKey ( key ) ) { final Object objectValue = settings . get ( key ) ; if ( objectValue == null ) { throw new IllegalArgumentException ( "Setting '" + key + " null" ) ; } final String value = objectValue . toString ( ) ; try { return Integer . parseInt ( value ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( "Setting '" + key + "=" + value + "' is not an integer" , e ) ; } } else { return defaultVal ; } }
|
Gets an int value for the setting returning the default value if not specified .
| 148
| 16
|
158,494
|
protected VelocityEngine getVelocityEngine ( List < String > paths ) { VelocityEngine ve = new VelocityEngine ( ) ; ve . setProperty ( RuntimeConstants . RESOURCE_LOADER , "file" ) ; ve . setProperty ( "cp.resource.loader.class" , "org.apache.velocity.runtime.resource.loader.FileResourceLoader" ) ; ve . setProperty ( "cp.resource.loader.cache" , "true" ) ; ve . setProperty ( "cp.resource.loader.path" , StringUtils . join ( paths , "," ) ) ; ve . setProperty ( "cp.resource.loader.modificationCheckInterval " , "10" ) ; ve . setProperty ( "input.encoding" , "UTF-8" ) ; ve . setProperty ( "output.encoding" , "UTF-8" ) ; ve . setProperty ( "runtime.log" , "" ) ; return ve ; }
|
Sets velocity up to load resources from a list of paths .
| 208
| 13
|
158,495
|
public JmxProcess parseProcess ( File file ) throws IOException { String fileName = file . getName ( ) ; ObjectMapper mapper = fileName . endsWith ( ".yml" ) || fileName . endsWith ( ".yaml" ) ? yamlMapper : jsonMapper ; JsonNode jsonNode = mapper . readTree ( file ) ; JmxProcess jmx = mapper . treeToValue ( jsonNode , JmxProcess . class ) ; jmx . setName ( fileName ) ; return jmx ; }
|
Uses jackson to load json configuration from a File into a full object tree representation of that json .
| 117
| 21
|
158,496
|
void addTags ( StringBuilder resultString , Server server ) { if ( hostnameTag ) { addTag ( resultString , "host" , server . getLabel ( ) ) ; } // Add the constant tag names and values. for ( Map . Entry < String , String > tagEntry : tags . entrySet ( ) ) { addTag ( resultString , tagEntry . getKey ( ) , tagEntry . getValue ( ) ) ; } }
|
Add tags to the given result string including a host tag with the name of the server and all of the tags defined in the settings entry in the configuration file within the tag element .
| 94
| 36
|
158,497
|
void addTag ( StringBuilder resultString , String tagName , String tagValue ) { resultString . append ( " " ) ; resultString . append ( sanitizeString ( tagName ) ) ; resultString . append ( "=" ) ; resultString . append ( sanitizeString ( tagValue ) ) ; }
|
Add one tag with the provided name and value to the given result string .
| 67
| 15
|
158,498
|
private void formatResultString ( StringBuilder resultString , String metricName , long epoch , Object value ) { resultString . append ( sanitizeString ( metricName ) ) ; resultString . append ( " " ) ; resultString . append ( Long . toString ( epoch ) ) ; resultString . append ( " " ) ; resultString . append ( sanitizeString ( value . toString ( ) ) ) ; }
|
Format the result string given the class name and attribute name of the source value the timestamp and the value .
| 89
| 21
|
158,499
|
protected void processOneMetric ( List < String > resultStrings , Server server , Result result , Object value , String addTagName , String addTagValue ) { String metricName = this . metricNameStrategy . formatName ( result ) ; // // Skip any non-numeric values since OpenTSDB only supports numeric metrics. // if ( isNumeric ( value ) ) { StringBuilder resultString = new StringBuilder ( ) ; formatResultString ( resultString , metricName , result . getEpoch ( ) / 1000L , value ) ; addTags ( resultString , server ) ; if ( addTagName != null ) { addTag ( resultString , addTagName , addTagValue ) ; } if ( ! typeNames . isEmpty ( ) ) { this . addTypeNamesTags ( resultString , result ) ; } resultStrings . add ( resultString . toString ( ) ) ; } else { log . debug ( "Skipping non-numeric value for metric {}; value={}" , metricName , value ) ; } }
|
Process a single metric from the given JMX query result with the specified value .
| 223
| 16
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.