idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
21,800
public synchronized void refreshToken ( ) { final String refreshToken = this . response . refresh_token ; this . response = null ; this . cachedInfo = null ; final String responseStr = authService . getToken ( UserManagerOAuthService . GRANT_TYPE_REFRESH_TOKEN , null , null , clientId , clientSecret , refreshToken , null , null , null ) ; loadAuthResponse ( responseStr ) ; }
Use the refresh token to get a new token with a longer lifespan
21,801
public static void loadFromXmlPluginPackageDefinitions ( final IPluginRepository repo , final ClassLoader cl , final InputStream in ) throws PluginConfigurationException { for ( PluginDefinition pd : loadFromXmlPluginPackageDefinitions ( cl , in ) ) { repo . addPluginDefinition ( pd ) ; } }
Loads a full repository definition from an XML file .
21,802
@ SuppressWarnings ( "unchecked" ) public static Collection < PluginDefinition > loadFromXmlPluginPackageDefinitions ( final ClassLoader cl , final InputStream in ) throws PluginConfigurationException { List < PluginDefinition > res = new ArrayList < PluginDefinition > ( ) ; DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; Document document ; try { DocumentBuilder loader = factory . newDocumentBuilder ( ) ; DOMReader reader = new DOMReader ( ) ; document = reader . read ( loader . parse ( in ) ) ; } catch ( Exception e ) { throw new PluginConfigurationException ( e . getMessage ( ) , e ) ; } Element plugins = document . getRootElement ( ) ; for ( Iterator < Element > i = plugins . elementIterator ( ) ; i . hasNext ( ) ; ) { res . add ( parsePluginDefinition ( cl , i . next ( ) ) ) ; } return res ; }
Loads the plugins definitions from the jnrpe_plugins . xml file .
21,803
public static PluginDefinition parseXmlPluginDefinition ( final ClassLoader cl , final InputStream in ) throws PluginConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; Document document ; try { DocumentBuilder loader = factory . newDocumentBuilder ( ) ; DOMReader reader = new DOMReader ( ) ; document = reader . read ( loader . parse ( in ) ) ; } catch ( Exception e ) { throw new PluginConfigurationException ( e . getMessage ( ) , e ) ; } Element plugin = document . getRootElement ( ) ; return parsePluginDefinition ( cl , plugin ) ; }
Loads the definition of a single plugin from an XML file .
21,804
@ SuppressWarnings ( "rawtypes" ) private static PluginDefinition parsePluginDefinition ( final ClassLoader cl , final Element plugin ) throws PluginConfigurationException { if ( getAttributeValue ( plugin , "definedIn" , false ) != null ) { StreamManager sm = new StreamManager ( ) ; String sFileName = getAttributeValue ( plugin , "definedIn" , false ) ; try { InputStream in = sm . handle ( cl . getResourceAsStream ( sFileName ) ) ; return parseXmlPluginDefinition ( cl , in ) ; } finally { sm . closeAll ( ) ; } } String pluginClass = getAttributeValue ( plugin , "class" , true ) ; Class clazz ; try { clazz = LoadedClassCache . getClass ( cl , pluginClass ) ; if ( ! IPluginInterface . class . isAssignableFrom ( clazz ) ) { throw new PluginConfigurationException ( "Specified class '" + clazz . getName ( ) + "' in the plugin.xml file does not implement " + "the IPluginInterface interface" ) ; } if ( isAnnotated ( clazz ) ) { return loadFromPluginAnnotation ( clazz ) ; } } catch ( ClassNotFoundException e ) { throw new PluginConfigurationException ( e . getMessage ( ) , e ) ; } String sDescription = getAttributeValue ( plugin , "description" , false ) ; @ SuppressWarnings ( "unchecked" ) PluginDefinition pluginDef = new PluginDefinition ( getAttributeValue ( plugin , "name" , true ) , sDescription , clazz ) ; parseCommandLine ( pluginDef , plugin ) ; return pluginDef ; }
Parse an XML plugin definition .
21,805
@ SuppressWarnings ( "rawtypes" ) private static void parseCommandLine ( final PluginDefinition pluginDef , final Element xmlPluginElement ) { Element commandLine = xmlPluginElement . element ( "command-line" ) ; if ( commandLine != null ) { Element options = commandLine . element ( "options" ) ; if ( options == null ) { return ; } for ( Iterator < Element > i = options . elementIterator ( ) ; i . hasNext ( ) ; ) { pluginDef . addOption ( parsePluginOption ( i . next ( ) ) ) ; } } }
Updates the plugin definition with the commandline read from the xml file .
21,806
private static PluginOption parsePluginOption ( final Element option ) { PluginOption po = new PluginOption ( ) ; po . setArgName ( option . attributeValue ( "argName" ) ) ; po . setArgsCount ( Integer . valueOf ( option . attributeValue ( "argsCount" , "1" ) ) ) ; po . setArgsOptional ( Boolean . valueOf ( option . attributeValue ( "optionalArgs" , "false" ) ) ) ; po . setDescription ( option . attributeValue ( "description" ) ) ; po . setHasArgs ( Boolean . parseBoolean ( option . attributeValue ( "hasArgs" , "false" ) ) ) ; po . setLongOpt ( option . attributeValue ( "longName" ) ) ; po . setOption ( option . attributeValue ( "shortName" ) ) ; po . setRequired ( Boolean . parseBoolean ( option . attributeValue ( "required" , "false" ) ) ) ; po . setType ( option . attributeValue ( "type" ) ) ; po . setValueSeparator ( option . attributeValue ( "separator" ) ) ; return po ; }
Parses a plugin option XML definition .
21,807
private static PluginOption parsePluginOption ( final Option option ) { PluginOption po = new PluginOption ( ) ; po . setArgName ( option . argName ( ) ) ; po . setArgsOptional ( option . optionalArgs ( ) ) ; po . setDescription ( option . description ( ) ) ; po . setHasArgs ( option . hasArgs ( ) ) ; po . setLongOpt ( option . longName ( ) ) ; po . setOption ( option . shortName ( ) ) ; po . setRequired ( option . required ( ) ) ; return po ; }
Parses a plugin option from the annotation definition .
21,808
public Object invoke ( Object self , Method thisMethod , Method proceed , Object [ ] args ) throws Throwable { final Object instance = registry . getInjector ( ) . getInstance ( clazz ) ; return thisMethod . invoke ( instance , args ) ; }
A MethodHandler that proxies the Method invocation through to a Guice - acquired instance
21,809
public static void main ( String [ ] args ) throws Exception { final String name = args [ 0 ] ; final File sslCert = new File ( args [ 1 ] ) ; final File sslKey = new File ( args [ 2 ] ) ; final Map < File , Integer > foldersAndPorts = getFoldersAndPorts ( 3 , args ) ; NginxSiteGenerator generator = new NginxSiteGenerator ( ) ; final String config = generator . render ( name , sslCert , sslKey , foldersAndPorts ) ; System . out . println ( config ) ; }
Entry point for initial generation called from the commandline
21,810
public MultiXSDSchemaFiles encode ( ) { MultiXSDSchemaFiles files = new MultiXSDSchemaFiles ( ) ; for ( Map . Entry < String , DOMResult > entry : schemas . entrySet ( ) ) { MultiXSDSchemaFile file = new MultiXSDSchemaFile ( ) ; file . name = entry . getKey ( ) ; file . schema = getElement ( entry . getValue ( ) . getNode ( ) ) ; files . files . add ( file ) ; } if ( loosenXmlAnyConstraints ) MultiXSDSchemaLoosener . loosenXmlAnyOtherNamespaceToXmlAnyAnyNamespace ( files ) ; return files ; }
Produces an XML Schema or a Stdlib SchemaFiles document containing the XML Schemas
21,811
@ Named ( GuiceProperties . REST_SERVICES_PREFIX ) public String getRestServicesPrefix ( ServletContext context ) { String restPath = context . getInitParameter ( RESTEASY_MAPPING_PREFIX ) ; if ( restPath == null || restPath . isEmpty ( ) || restPath . equals ( "/" ) ) { return "" ; } else { return restPath ; } }
Retrieves the RESTeasy mapping prefix - this is the path under the webapp root where RESTeasy services are mapped .
21,812
@ Named ( GuiceProperties . LOCAL_REST_SERVICES_ENDPOINT ) public URI getRestServicesEndpoint ( @ Named ( GuiceProperties . STATIC_ENDPOINT_CONFIG_NAME ) URI webappUri , @ Named ( GuiceProperties . REST_SERVICES_PREFIX ) String restPrefix , ServletContext context ) { if ( restPrefix . equals ( "" ) ) { return webappUri ; } else { while ( restPrefix . startsWith ( "/" ) ) restPrefix = restPrefix . substring ( 1 ) ; final String webappPath = webappUri . toString ( ) ; if ( webappPath . endsWith ( "/" ) ) return URI . create ( webappPath + restPrefix ) ; else return URI . create ( webappPath + "/" + restPrefix ) ; } }
Return the base path for all REST services in this webapp
21,813
@ Named ( GuiceProperties . STATIC_ENDPOINT_CONFIG_NAME ) public URI getRestServicesEndpoint ( LocalEndpointDiscovery localEndpointDiscovery ) { final URI base = localEndpointDiscovery . getLocalEndpoint ( ) ; return base ; }
Return the base path for this webapp
21,814
public List < Class < ? > > getSiblingClasses ( final Class < ? > clazz , boolean recursive , final Predicate < Class < ? > > predicate ) { return getClasses ( getPackages ( clazz ) [ 0 ] , recursive , predicate ) ; }
Find all the classes that are siblings of the provided class
21,815
public String [ ] getCommandLine ( ) { String [ ] argsAry = argsString != null ? split ( argsString ) : EMPTY_ARRAY ; List < String > argsList = new ArrayList < String > ( ) ; int startIndex = 0 ; for ( CommandOption opt : optionsList ) { String argName = opt . getName ( ) ; String argValueString = opt . getValue ( ) ; argsList . add ( ( argName . length ( ) == 1 ? "-" : "--" ) + argName ) ; if ( argValueString != null ) { argsList . add ( quote ( argValueString ) ) ; } } String [ ] resAry = new String [ argsAry . length + argsList . size ( ) ] ; for ( String argString : argsList ) { resAry [ startIndex ++ ] = argString ; } System . arraycopy ( argsAry , 0 , resAry , startIndex , argsAry . length ) ; return resAry ; }
Merges the command line definition read from the server config file with . the values received from check_nrpe and produces a clean command line .
21,816
private void parse ( final String definition ) throws BadThresholdException { String [ ] thresholdComponentAry = definition . split ( "," ) ; for ( String thresholdComponent : thresholdComponentAry ) { String [ ] nameValuePair = thresholdComponent . split ( "=" ) ; if ( nameValuePair . length != 2 || StringUtils . isEmpty ( nameValuePair [ 0 ] ) || StringUtils . isEmpty ( nameValuePair [ 1 ] ) ) { throw new BadThresholdException ( "Invalid threshold syntax : " + definition ) ; } if ( "metric" . equalsIgnoreCase ( nameValuePair [ 0 ] ) ) { metricName = nameValuePair [ 1 ] ; continue ; } if ( "ok" . equalsIgnoreCase ( nameValuePair [ 0 ] ) ) { Range thr = new Range ( nameValuePair [ 1 ] ) ; okThresholdList . add ( thr ) ; continue ; } if ( "warning" . equalsIgnoreCase ( nameValuePair [ 0 ] ) || "warn" . equalsIgnoreCase ( nameValuePair [ 0 ] ) || "w" . equalsIgnoreCase ( nameValuePair [ 0 ] ) ) { Range thr = new Range ( nameValuePair [ 1 ] ) ; warningThresholdList . add ( thr ) ; continue ; } if ( "critical" . equalsIgnoreCase ( nameValuePair [ 0 ] ) || "crit" . equalsIgnoreCase ( nameValuePair [ 0 ] ) || "c" . equalsIgnoreCase ( nameValuePair [ 0 ] ) ) { Range thr = new Range ( nameValuePair [ 1 ] ) ; criticalThresholdList . add ( thr ) ; continue ; } if ( "unit" . equalsIgnoreCase ( nameValuePair [ 0 ] ) ) { unit = nameValuePair [ 1 ] ; continue ; } if ( "prefix" . equalsIgnoreCase ( nameValuePair [ 0 ] ) ) { prefix = Prefixes . fromString ( nameValuePair [ 1 ] ) ; continue ; } } }
Parses a threshold definition .
21,817
public final String getRangesAsString ( final Status status ) { List < String > ranges = new ArrayList < String > ( ) ; List < Range > rangeList ; switch ( status ) { case OK : rangeList = okThresholdList ; break ; case WARNING : rangeList = warningThresholdList ; break ; case CRITICAL : default : rangeList = criticalThresholdList ; break ; } for ( Range r : rangeList ) { ranges . add ( r . getRangeString ( ) ) ; } if ( ranges . isEmpty ( ) ) { return null ; } return StringUtils . join ( ranges , "," ) ; }
Returns the requested range list as comma separated string .
21,818
public static BundleClassLoader newPriviledged ( final Bundle bundle , final ClassLoader parent ) { return AccessController . doPrivileged ( new PrivilegedAction < BundleClassLoader > ( ) { public BundleClassLoader run ( ) { return new BundleClassLoader ( bundle , parent ) ; } } ) ; }
Privileged factory method .
21,819
@ SuppressWarnings ( "unchecked" ) protected Enumeration < URL > findResources ( final String name ) throws IOException { Enumeration < URL > resources = m_bundle . getResources ( name ) ; if ( resources == null ) { return EMPTY_URL_ENUMERATION ; } else { return resources ; } }
Use bundle to find resources .
21,820
public final void call ( T param ) { if ( ! run ) { run = true ; prepared = true ; try { this . run ( param ) ; } catch ( Throwable t ) { log . error ( "[ParamInvokeable] {prepare} : " + t . getMessage ( ) , t ) ; } } }
Synchronously executes this Invokeable
21,821
public synchronized List < GuiceRecurringDaemon > getRecurring ( ) { return daemons . stream ( ) . filter ( d -> d instanceof GuiceRecurringDaemon ) . map ( d -> ( GuiceRecurringDaemon ) d ) . sorted ( Comparator . comparing ( GuiceDaemon :: getName ) ) . collect ( Collectors . toList ( ) ) ; }
Return a list of all
21,822
public static final byte [ ] fromHex ( final String value ) { if ( value . length ( ) == 0 ) return new byte [ 0 ] ; else if ( value . indexOf ( ':' ) != - 1 ) return fromHex ( ':' , value ) ; else if ( value . length ( ) % 2 != 0 ) throw new IllegalArgumentException ( "Invalid hex specified: uneven number of digits passed for byte[] conversion" ) ; final byte [ ] buffer = new byte [ value . length ( ) / 2 ] ; int j = 0 ; for ( int i = 0 ; i < buffer . length ; i ++ ) { buffer [ i ] = ( byte ) Integer . parseInt ( value . substring ( j , j + 2 ) , 16 ) ; j += 2 ; } return buffer ; }
Decodes a hexidecimal string into a series of bytes
21,823
private String getHttpResponse ( final ICommandLine cl , final String hostname , final String port , final String method , final String path , final int timeout , final boolean ssl , final List < Metric > metrics ) throws MetricGatheringException { Properties props = null ; try { props = getRequestProperties ( cl , method ) ; } catch ( UnsupportedEncodingException e ) { throw new MetricGatheringException ( "Error occurred: " + e . getMessage ( ) , Status . CRITICAL , e ) ; } String response = null ; String redirect = cl . getOptionValue ( "onredirect" ) ; boolean ignoreBody = false ; try { String data = null ; if ( "POST" . equals ( method ) ) { data = getPostData ( cl ) ; } if ( cl . hasOption ( "no-body" ) ) { ignoreBody = true ; } String urlString = hostname + ":" + port + path ; if ( cl . hasOption ( "authorization" ) ) { urlString = cl . getOptionValue ( "authorization" ) + "@" + urlString ; } else if ( cl . hasOption ( "proxy-authorization" ) ) { urlString = cl . getOptionValue ( "proxy-authorization" ) + "@" + urlString ; } if ( ssl ) { urlString = "https://" + urlString ; } else { urlString = "http://" + urlString ; } URL url = new URL ( urlString ) ; if ( cl . getOptionValue ( "certificate" ) != null ) { checkCertificateExpiryDate ( url , metrics ) ; } else if ( redirect != null ) { response = checkRedirectResponse ( url , method , timeout , props , data , redirect , ignoreBody , metrics ) ; } else { try { if ( "GET" . equals ( method ) ) { response = HttpUtils . doGET ( url , props , timeout , true , ignoreBody ) ; } else if ( "POST" . equals ( method ) ) { response = HttpUtils . doPOST ( url , props , null , data , true , ignoreBody ) ; } else if ( "HEAD" . equals ( method ) ) { response = HttpUtils . doHEAD ( url , props , timeout , true , ignoreBody ) ; } } catch ( MalformedURLException e ) { LOG . error ( getContext ( ) , "Bad url" , e ) ; throw new MetricGatheringException ( "Bad url string : " + urlString , Status . CRITICAL , e ) ; } } } catch ( Exception e ) { LOG . error ( getContext ( ) , "Exception: " + e . getMessage ( ) , e ) ; throw new MetricGatheringException ( e . getClass ( ) . getName ( ) + ": " + e . getMessage ( ) , Status . CRITICAL , e ) ; } return response ; }
Do the actual http request and return the response string .
21,824
private String checkRedirectResponse ( final URL url , final String method , final Integer timeout , final Properties props , final String postData , final String redirect , final boolean ignoreBody , final List < Metric > metrics ) throws Exception { String response = null ; HttpURLConnection conn = ( HttpURLConnection ) url . openConnection ( ) ; conn . setRequestMethod ( method ) ; HttpUtils . setRequestProperties ( props , conn , timeout ) ; String initialUrl = String . valueOf ( conn . getURL ( ) ) ; String redirectedUrl = null ; if ( "POST" . equals ( method ) ) { HttpUtils . sendPostData ( conn , postData ) ; } response = HttpUtils . parseHttpResponse ( conn , false , ignoreBody ) ; redirectedUrl = String . valueOf ( conn . getURL ( ) ) ; if ( ! redirectedUrl . equals ( initialUrl ) ) { Metric metric = new Metric ( "onredirect" , "" , new BigDecimal ( 1 ) , null , null ) ; metrics . add ( metric ) ; } return response ; }
Apply the logic to check for url redirects .
21,825
private List < Metric > analyzeResponse ( final ICommandLine opt , final String response , final int elapsed ) throws MetricGatheringException { List < Metric > metrics = new ArrayList < Metric > ( ) ; metrics . add ( new Metric ( "time" , "" , new BigDecimal ( elapsed ) , null , null ) ) ; if ( ! opt . hasOption ( "certificate" ) ) { if ( opt . hasOption ( "string" ) ) { boolean found = false ; String string = opt . getOptionValue ( "string" ) ; found = response . contains ( string ) ; metrics . add ( new Metric ( "string" , "" , new BigDecimal ( Utils . getIntValue ( found ) ) , null , null ) ) ; } if ( opt . hasOption ( "expect" ) ) { int count = 0 ; String [ ] values = opt . getOptionValue ( "expect" ) . split ( "," ) ; for ( String value : values ) { if ( response . contains ( value ) ) { count ++ ; } } metrics . add ( new Metric ( "expect" , String . valueOf ( count ) + " times. " , new BigDecimal ( count ) , null , null ) ) ; } if ( opt . hasOption ( "regex" ) ) { String regex = opt . getOptionValue ( "regex" ) ; Pattern p = null ; int flags = 0 ; if ( opt . hasOption ( "eregi" ) ) { flags = Pattern . CASE_INSENSITIVE ; } if ( opt . hasOption ( "linespan" ) ) { flags = flags | Pattern . MULTILINE ; } p = Pattern . compile ( regex , flags ) ; boolean found = p . matcher ( response ) . find ( ) ; if ( opt . hasOption ( "invert-regex" ) ) { metrics . add ( new Metric ( "invert-regex" , String . valueOf ( found ) , new BigDecimal ( Utils . getIntValue ( found ) ) , null , null ) ) ; } else { metrics . add ( new Metric ( "regex" , String . valueOf ( found ) , new BigDecimal ( Utils . getIntValue ( found ) ) , null , null ) ) ; } } } return metrics ; }
Apply logic to the http response and build metrics .
21,826
private Properties getRequestProperties ( final ICommandLine cl , final String method ) throws UnsupportedEncodingException { Properties props = new Properties ( ) ; if ( cl . hasOption ( "useragent" ) ) { props . setProperty ( "User-Agent" , cl . getOptionValue ( "useragent" ) ) ; } else { props . setProperty ( "User-Agent" , DEFAULT_USER_AGENT ) ; } if ( cl . hasOption ( "content-type" ) && "POST" . equalsIgnoreCase ( method ) ) { props . setProperty ( "Content-Type" , cl . getOptionValue ( "content-type" ) ) ; } if ( cl . hasOption ( "header" ) ) { List headers = cl . getOptionValues ( "header" ) ; for ( Object obj : headers ) { String header = ( String ) obj ; String key = header . split ( ":" ) [ 0 ] . trim ( ) ; String value = header . split ( ":" ) [ 1 ] . trim ( ) ; props . setProperty ( key , value ) ; } } String auth = null ; String encoded = null ; if ( cl . hasOption ( "authorization" ) ) { encoded = Base64 . encodeBase64String ( cl . getOptionValue ( "authorization" ) . getBytes ( CHARSET ) ) ; auth = "Authorization" ; } else if ( cl . hasOption ( "proxy-authorization" ) ) { encoded = Base64 . encodeBase64String ( cl . getOptionValue ( "proxy-authorization" ) . getBytes ( CHARSET ) ) ; auth = "Proxy-Authorization" ; } if ( auth != null && encoded != null ) { props . setProperty ( auth , "Basic " + encoded ) ; } return props ; }
Set the http request properties and headers .
21,827
private String getPostData ( final ICommandLine cl ) throws Exception { StringBuilder encoded = new StringBuilder ( ) ; String data = cl . getOptionValue ( "post" ) ; if ( data == null ) { return null ; } String [ ] values = data . split ( "&" ) ; for ( String value : values ) { String [ ] splitted = value . split ( "=" ) ; String key = splitted [ 0 ] ; String val = "" ; if ( splitted . length > 1 ) { val = splitted [ 1 ] ; } if ( encoded . length ( ) != 0 ) { encoded . append ( '&' ) ; } encoded . append ( key ) . append ( '=' ) . append ( URLEncoder . encode ( val , "UTF-8" ) ) ; } return encoded . toString ( ) ; }
Returns encoded post data .
21,828
private void checkCertificateExpiryDate ( URL url , List < Metric > metrics ) throws Exception { SSLContext ctx = SSLContext . getInstance ( "TLS" ) ; ctx . init ( new KeyManager [ 0 ] , new TrustManager [ ] { new DefaultTrustManager ( ) } , new SecureRandom ( ) ) ; SSLContext . setDefault ( ctx ) ; HttpsURLConnection conn = ( HttpsURLConnection ) url . openConnection ( ) ; conn . setHostnameVerifier ( new HostnameVerifier ( ) { public boolean verify ( final String arg0 , final SSLSession arg1 ) { return true ; } } ) ; List < Date > expiryDates = new ArrayList < Date > ( ) ; conn . getResponseCode ( ) ; Certificate [ ] certs = conn . getServerCertificates ( ) ; for ( Certificate cert : certs ) { X509Certificate x509 = ( X509Certificate ) cert ; Date expiry = x509 . getNotAfter ( ) ; expiryDates . add ( expiry ) ; } conn . disconnect ( ) ; Date today = new Date ( ) ; for ( Date date : expiryDates ) { int diffInDays = ( int ) ( ( date . getTime ( ) - today . getTime ( ) ) / ( 1000 * 60 * 60 * 24 ) ) ; metrics . add ( new Metric ( "certificate" , "" , new BigDecimal ( diffInDays ) , null , null ) ) ; } }
stuff for checking certificate
21,829
public static JNRPEConfiguration createConfiguration ( final String configurationFilePath ) throws ConfigurationException { JNRPEConfiguration conf = null ; if ( configurationFilePath . toLowerCase ( ) . endsWith ( ".conf" ) || configurationFilePath . toLowerCase ( ) . endsWith ( ".ini" ) ) { conf = new IniJNRPEConfiguration ( ) ; } else if ( configurationFilePath . toLowerCase ( ) . endsWith ( ".xml" ) ) { conf = new XmlJNRPEConfiguration ( ) ; } if ( conf == null ) { throw new ConfigurationException ( "Config file name must end with either '.ini' " + "(ini file) or '.xml' (xml file). Received file name is : " + new File ( configurationFilePath ) . getName ( ) ) ; } conf . load ( new File ( configurationFilePath ) ) ; return conf ; }
Creates a configuration object from the passed in configuration file .
21,830
public static BundleContext getBundleContext ( final Bundle bundle ) { try { final Method method = Bundle . class . getDeclaredMethod ( "getBundleContext" ) ; if ( ! method . isAccessible ( ) ) { method . setAccessible ( true ) ; } return ( BundleContext ) method . invoke ( bundle ) ; } catch ( Exception e ) { try { final Field [ ] fields = bundle . getClass ( ) . getDeclaredFields ( ) ; for ( Field field : fields ) { if ( BundleContext . class . isAssignableFrom ( field . getType ( ) ) ) { if ( ! field . isAccessible ( ) ) { field . setAccessible ( true ) ; } return ( BundleContext ) field . get ( bundle ) ; } } } catch ( Exception ignore ) { } } return null ; }
Discovers the bundle context for a bundle . If the bundle is an 4 . 1 . 0 or greater bundle it should have a method that just returns the bundle context . Otherwise uses reflection to look for an internal bundle context .
21,831
public static Bundle getBundle ( BundleContext bc , String symbolicName ) { return getBundle ( bc , symbolicName , null ) ; }
Returns any bundle with the given symbolic name or null if no such bundle exists . If there are multiple bundles with the same symbolic name and different version this method returns the first bundle found .
21,832
public static List < Bundle > getBundles ( BundleContext bc , String symbolicName ) { List < Bundle > bundles = new ArrayList < Bundle > ( ) ; for ( Bundle bundle : bc . getBundles ( ) ) { if ( bundle . getSymbolicName ( ) . equals ( symbolicName ) ) { bundles . add ( bundle ) ; } } return bundles ; }
Returns a list of all bundles with the given symbolic name .
21,833
public static Bundle getBundle ( BundleContext bc , String symbolicName , String version ) { for ( Bundle bundle : bc . getBundles ( ) ) { if ( bundle . getSymbolicName ( ) . equals ( symbolicName ) ) { if ( version == null || version . equals ( bundle . getVersion ( ) ) ) { return bundle ; } } } return null ; }
Returns the bundle with the given symbolic name and the given version or null if no such bundle exists
21,834
public String encodeValue ( ) { switch ( function ) { case EQ : if ( value != null && value . startsWith ( "_" ) ) return function . getPrefix ( ) + value ; else return value ; default : if ( function . hasBinaryParam ( ) ) return function . getPrefix ( ) + value + ".." + value2 ; else if ( function . hasParam ( ) ) return function . getPrefix ( ) + value ; else return function . getPrefix ( ) ; } }
Encode this constraint in the query string value format
21,835
public static WQConstraint decode ( final String field , final String rawValue ) { final WQFunctionType function ; final String value ; if ( StringUtils . equalsIgnoreCase ( rawValue , WQFunctionType . IS_NULL . getPrefix ( ) ) ) return new WQConstraint ( field , WQFunctionType . IS_NULL , null ) ; else if ( StringUtils . equalsIgnoreCase ( rawValue , WQFunctionType . NOT_NULL . getPrefix ( ) ) ) return new WQConstraint ( field , WQFunctionType . NOT_NULL , null ) ; else if ( rawValue . startsWith ( "_f_" ) ) { function = WQFunctionType . getByPrefix ( rawValue ) ; if ( function . hasParam ( ) ) { value = rawValue . substring ( function . getPrefix ( ) . length ( ) ) ; if ( function . hasBinaryParam ( ) ) { final String [ ] splitValues = StringUtils . split ( value , ".." , 2 ) ; final String left = splitValues [ 0 ] ; final String right = splitValues [ 1 ] ; return new WQConstraint ( field , function , left , right ) ; } } else { value = null ; } } else { function = WQFunctionType . EQ ; value = rawValue ; } return new WQConstraint ( field , function , value ) ; }
Produce a WebQueryConstraint from a Query String format parameter
21,836
private Metric checkSlave ( final ICommandLine cl , final Mysql mysql , final Connection conn ) throws MetricGatheringException { Metric metric = null ; try { Map < String , Integer > status = getSlaveStatus ( conn ) ; if ( status . isEmpty ( ) ) { mysql . closeConnection ( conn ) ; throw new MetricGatheringException ( "CHECK_MYSQL - WARNING: No slaves defined. " , Status . CRITICAL , null ) ; } int slaveIoRunning = status . get ( "Slave_IO_Running" ) ; int slaveSqlRunning = status . get ( "Slave_SQL_Running" ) ; int secondsBehindMaster = status . get ( "Seconds_Behind_Master" ) ; if ( slaveIoRunning == 0 || slaveSqlRunning == 0 ) { mysql . closeConnection ( conn ) ; throw new MetricGatheringException ( "CHECK_MYSQL - CRITICAL: Slave status unavailable. " , Status . CRITICAL , null ) ; } String slaveResult = "Slave IO: " + slaveIoRunning + " Slave SQL: " + slaveSqlRunning + " Seconds Behind Master: " + secondsBehindMaster ; metric = new Metric ( "secondsBehindMaster" , slaveResult , new BigDecimal ( secondsBehindMaster ) , null , null ) ; } catch ( SQLException e ) { String message = e . getMessage ( ) ; LOG . warn ( getContext ( ) , "Error executing the CheckMysql plugin: " + message , e ) ; throw new MetricGatheringException ( "CHECK_MYSQL - CRITICAL: Unable to check slave status: - " + message , Status . CRITICAL , e ) ; } return metric ; }
Check the status of mysql slave thread .
21,837
private Map < String , Integer > getSlaveStatus ( final Connection conn ) throws SQLException { Map < String , Integer > map = new HashMap < String , Integer > ( ) ; String query = SLAVE_STATUS_QRY ; Statement statement = null ; ResultSet rs = null ; try { if ( conn != null ) { statement = conn . createStatement ( ) ; rs = statement . executeQuery ( query ) ; while ( rs . next ( ) ) { map . put ( "Slave_IO_Running" , rs . getInt ( "Slave_IO_Running" ) ) ; map . put ( "Slave_SQL_Running" , rs . getInt ( "Slave_SQL_Running" ) ) ; map . put ( "Seconds_Behind_Master" , rs . getInt ( "Seconds_Behind_Master" ) ) ; } } } finally { DBUtils . closeQuietly ( rs ) ; DBUtils . closeQuietly ( statement ) ; } return map ; }
Get slave statuses .
21,838
public void updateCRC ( ) { this . crc32 = 0 ; CRC32 crcAlg = new CRC32 ( ) ; crcAlg . update ( this . toByteArray ( ) ) ; this . crc32 = ( int ) crcAlg . getValue ( ) ; }
Updates the CRC value .
21,839
private static Stage configureParser ( ) { Stage startStage = new StartStage ( ) ; Stage negativeInfinityStage = new NegativeInfinityStage ( ) ; Stage positiveInfinityStage = new PositiveInfinityStage ( ) ; NegateStage negateStage = new NegateStage ( ) ; BracketStage . OpenBracketStage openBraceStage = new BracketStage . OpenBracketStage ( ) ; NumberBoundaryStage . LeftBoundaryStage startBoundaryStage = new NumberBoundaryStage . LeftBoundaryStage ( ) ; NumberBoundaryStage . RightBoundaryStage rightBoundaryStage = new NumberBoundaryStage . RightBoundaryStage ( ) ; SeparatorStage separatorStage = new SeparatorStage ( ) ; BracketStage . ClosedBracketStage closedBraketStage = new BracketStage . ClosedBracketStage ( ) ; startStage . addTransition ( negateStage ) ; startStage . addTransition ( openBraceStage ) ; startStage . addTransition ( negativeInfinityStage ) ; startStage . addTransition ( startBoundaryStage ) ; negateStage . addTransition ( negativeInfinityStage ) ; negateStage . addTransition ( openBraceStage ) ; negateStage . addTransition ( startBoundaryStage ) ; openBraceStage . addTransition ( startBoundaryStage ) ; startBoundaryStage . addTransition ( separatorStage ) ; negativeInfinityStage . addTransition ( separatorStage ) ; separatorStage . addTransition ( positiveInfinityStage ) ; separatorStage . addTransition ( rightBoundaryStage ) ; rightBoundaryStage . addTransition ( closedBraketStage ) ; return startStage ; }
Configures the state machine .
21,840
public static void parse ( final String range , final RangeConfig tc ) throws RangeException { if ( range == null ) { throw new RangeException ( "Range can't be null" ) ; } ROOT_STAGE . parse ( range , tc ) ; checkBoundaries ( tc ) ; }
Parses the threshold .
21,841
private static void checkBoundaries ( final RangeConfig rc ) throws RangeException { if ( rc . isNegativeInfinity ( ) ) { return ; } if ( rc . isPositiveInfinity ( ) ) { return ; } if ( rc . getLeftBoundary ( ) . compareTo ( rc . getRightBoundary ( ) ) > 0 ) { throw new RangeException ( "Left boundary must be less than right boundary (left:" + rc . getLeftBoundary ( ) + ", right:" + rc . getRightBoundary ( ) + ")" ) ; } }
Checks that right boundary is greater than left boundary .
21,842
public TimecodeBuilder withTimecode ( Timecode timecode ) { return this . withNegative ( timecode . isNegative ( ) ) . withDays ( timecode . getDaysPart ( ) ) . withHours ( timecode . getHoursPart ( ) ) . withMinutes ( timecode . getMinutesPart ( ) ) . withSeconds ( timecode . getSecondsPart ( ) ) . withFrames ( timecode . getFramesPart ( ) ) . withDropFrame ( timecode . isDropFrame ( ) ) . withRate ( timecode . getTimebase ( ) ) ; }
Reset this builder to the values in the provided Timecode
21,843
public Timecode build ( ) { final boolean dropFrame = ( this . dropFrame != null ) ? this . dropFrame . booleanValue ( ) : getRate ( ) . canBeDropFrame ( ) ; return new Timecode ( negative , days , hours , minutes , seconds , frames , rate , dropFrame ) ; }
Constructs a Timecode instance with the fields defined in this builder
21,844
public void setAll ( final String name , final String email , final Map < String , Map < String , ConfigPropertyValue > > data , final String message ) { set ( name , email , data , ConfigChangeMode . WIPE_ALL , message ) ; }
Create a new commit reflecting the provided properties removing any property not mentioned here
21,845
public void set ( final String name , final String email , final Map < String , Map < String , ConfigPropertyValue > > data , final ConfigChangeMode changeMode , final String message ) { try { RepoHelper . write ( repo , name , email , data , changeMode , message ) ; } catch ( Exception e ) { try { RepoHelper . reset ( repo ) ; } catch ( Exception ee ) { throw new RuntimeException ( "Error writing updated repository, then could not reset work tree" , e ) ; } throw new RuntimeException ( "Error writing updated repository, work tree reset" , e ) ; } if ( hasRemote ) { try { RepoHelper . push ( repo , "origin" , credentials ) ; } catch ( Throwable t ) { throw new RuntimeException ( "Saved changes to the local repository but push to remote failed!" , t ) ; } } }
Create a new commit reflecting the provided properties
21,846
public static HttpCallContext get ( ) throws IllegalStateException { final HttpCallContext ctx = peek ( ) ; if ( ctx != null ) return ctx ; else throw new IllegalStateException ( "Not in an HttpCallContext!" ) ; }
Retrieve the HttpCallContext associated with this Thread
21,847
public static HttpCallContext set ( HttpServletRequest request , HttpServletResponse response , ServletContext servletContext ) { final HttpCallContext ctx = new HttpCallContext ( generateTraceId ( request ) , request , response , servletContext ) ; contexts . set ( ctx ) ; return ctx ; }
Creates and associates an HttpCallContext with the current Thread
21,848
public static void filterP12 ( File p12 , String p12Password ) throws IOException { if ( ! p12 . exists ( ) ) throw new IllegalArgumentException ( "p12 file does not exist: " + p12 . getPath ( ) ) ; final File pem ; if ( USE_GENERIC_TEMP_DIRECTORY ) pem = File . createTempFile ( UUID . randomUUID ( ) . toString ( ) , "" ) ; else pem = new File ( p12 . getAbsolutePath ( ) + ".pem.tmp" ) ; final String pemPassword = UUID . randomUUID ( ) . toString ( ) ; try { P12toPEM ( p12 , p12Password , pem , pemPassword ) ; PEMtoP12 ( pem , pemPassword , p12 , p12Password ) ; } finally { if ( pem . exists ( ) ) if ( ! pem . delete ( ) ) log . warn ( "[OpenSSLPKCS12] {filterP12} Could not delete temporary PEM file " + pem ) ; } }
Recreates a PKCS12 KeyStore using OpenSSL ; this is a workaround a BouncyCastle - Firefox compatibility bug
21,849
public < T > T runUnchecked ( Retryable < T > operation ) throws RuntimeException { try { return run ( operation ) ; } catch ( RuntimeException e ) { throw e ; } catch ( Exception e ) { throw new RuntimeException ( "Retryable " + operation + " failed: " + e . getMessage ( ) , e ) ; } }
Run the operation only throwing an unchecked exception on failure
21,850
public void trace ( final IJNRPEExecutionContext ctx , final String message ) { postEvent ( ctx , new LogEvent ( source , LogEventType . TRACE , message ) ) ; }
Sends trace level messages .
21,851
public void debug ( final IJNRPEExecutionContext ctx , final String message ) { postEvent ( ctx , new LogEvent ( source , LogEventType . DEBUG , message ) ) ; }
Sends debug level messages .
21,852
public void info ( final IJNRPEExecutionContext ctx , final String message ) { postEvent ( ctx , new LogEvent ( source , LogEventType . INFO , message ) ) ; }
Sends info level messages .
21,853
public void warn ( final IJNRPEExecutionContext ctx , final String message ) { postEvent ( ctx , new LogEvent ( source , LogEventType . WARNING , message ) ) ; }
Sends warn level messages .
21,854
public Map < RuleSet , List < Rule > > matching ( Rules rules , Map < String , Object > vars , boolean ignoreMethodErrors ) throws OgnlException { Map < RuleSet , List < Rule > > ret = new HashMap < > ( ) ; for ( RuleSet ruleSet : rules . ruleSets ) { try { OgnlContext context = createContext ( vars ) ; List < Rule > matching = match ( ruleSet , context ) ; if ( ! matching . isEmpty ( ) ) { ret . put ( ruleSet , matching ) ; } } catch ( MethodFailedException mfe ) { if ( ! ignoreMethodErrors ) { throw mfe ; } log . warn ( "Method failed for ruleset " + ruleSet . id , mfe ) ; } } return ret ; }
returns a list of the rules that match from the supplied Rules document
21,855
private List < Rule > match ( final RuleSet ruleSet , final OgnlContext ognlContext ) throws OgnlException { log . debug ( "Assessing input for ruleset : " + ruleSet . id ) ; ruleSet . runInput ( ognlContext ) ; final List < Rule > ret = new ArrayList < > ( ) ; for ( Rule rule : ruleSet . rules ) { Boolean bresult = rule . assessMatch ( ognlContext ) ; if ( bresult ) { log . debug ( rule . condition . getOriginalExpression ( ) + " matches" ) ; ret . add ( rule ) ; } } return ret ; }
returns a list of rules that match in the given rule set
21,856
public JNRPE build ( ) { JNRPE jnrpe = new JNRPE ( pluginRepository , commandRepository , charset , acceptParams , acceptedHosts , maxAcceptedConnections , readTimeout , writeTimeout ) ; IJNRPEEventBus eventBus = jnrpe . getExecutionContext ( ) . getEventBus ( ) ; for ( Object obj : eventListeners ) { eventBus . register ( obj ) ; } return jnrpe ; }
Builds the configured JNRPE instance .
21,857
public ResteasyClient getOrCreateClient ( final boolean fastFail , final AuthScope authScope , final Credentials credentials , final boolean preemptiveAuth , final boolean storeCookies , Consumer < HttpClientBuilder > customiser ) { customiser = createHttpClientCustomiser ( fastFail , authScope , credentials , preemptiveAuth , storeCookies , customiser ) ; return getOrCreateClient ( customiser , null ) ; }
Build a new Resteasy Client optionally with authentication credentials
21,858
public Consumer < HttpClientBuilder > createHttpClientCustomiser ( final boolean fastFail , final AuthScope authScope , final Credentials credentials , final boolean preemptiveAuth , final boolean storeCookies , Consumer < HttpClientBuilder > customiser ) { if ( fastFail ) { customiser = concat ( customiser , b -> { RequestConfig . Builder requestBuilder = RequestConfig . custom ( ) ; requestBuilder . setConnectTimeout ( ( int ) fastFailConnectionTimeout . getMilliseconds ( ) ) . setSocketTimeout ( ( int ) fastFailSocketTimeout . getMilliseconds ( ) ) ; b . setDefaultRequestConfig ( requestBuilder . build ( ) ) ; } ) ; } if ( credentials != null ) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider ( ) ; if ( authScope != null ) credentialsProvider . setCredentials ( authScope , credentials ) ; else credentialsProvider . setCredentials ( AuthScope . ANY , credentials ) ; if ( credentials instanceof BearerCredentials ) { customiser = concat ( customiser , b -> { Registry < AuthSchemeProvider > authSchemeRegistry = RegistryBuilder . < AuthSchemeProvider > create ( ) . register ( "Bearer" , new BearerAuthSchemeProvider ( ) ) . build ( ) ; b . setDefaultAuthSchemeRegistry ( authSchemeRegistry ) ; } ) ; } customiser = concat ( customiser , b -> b . setDefaultCredentialsProvider ( credentialsProvider ) ) ; if ( preemptiveAuth && credentials instanceof BearerCredentials ) customiser = concat ( customiser , b -> b . addInterceptorFirst ( new PreemptiveBearerAuthInterceptor ( ) ) ) ; else customiser = concat ( customiser , b -> b . addInterceptorLast ( new PreemptiveBasicAuthInterceptor ( ) ) ) ; } if ( storeCookies ) customiser = concat ( customiser , b -> b . setDefaultCookieStore ( new BasicCookieStore ( ) ) ) ; return customiser ; }
N . B . This method signature may change in the future to add new parameters
21,859
public CloseableHttpClient createHttpClient ( final Consumer < HttpClientBuilder > customiser ) { final HttpClientBuilder builder = HttpClientBuilder . create ( ) ; { RequestConfig . Builder requestBuilder = RequestConfig . custom ( ) ; requestBuilder . setConnectTimeout ( ( int ) connectionTimeout . getMilliseconds ( ) ) . setSocketTimeout ( ( int ) socketTimeout . getMilliseconds ( ) ) ; builder . setDefaultRequestConfig ( requestBuilder . build ( ) ) ; } if ( noKeepalive ) builder . setConnectionReuseStrategy ( new NoConnectionReuseStrategy ( ) ) ; builder . setConnectionManager ( connectionManager ) ; builder . setRoutePlanner ( new SystemDefaultRoutePlanner ( ProxySelector . getDefault ( ) ) ) ; if ( customiser != null ) customiser . accept ( builder ) ; return builder . build ( ) ; }
Build an HttpClient
21,860
public StorageSize multiply ( BigInteger by ) { final BigInteger result = getBits ( ) . multiply ( by ) ; return new StorageSize ( getUnit ( ) , result ) ; }
Multiplies the storage size by a certain amount
21,861
public StorageSize subtract ( StorageSize that ) { StorageUnit smallestUnit = StorageUnit . smallest ( this . getUnit ( ) , that . getUnit ( ) ) ; final BigInteger a = this . getBits ( ) ; final BigInteger b = that . getBits ( ) ; final BigInteger result = a . subtract ( b ) ; return new StorageSize ( smallestUnit , result ) ; }
Subtracts a storage size from the current object using the smallest unit as the resulting StorageSize s unit
21,862
private boolean isHtmlAcceptable ( HttpServletRequest request ) { @ SuppressWarnings ( "unchecked" ) final List < String > accepts = ListUtility . list ( ListUtility . iterate ( request . getHeaders ( HttpHeaderNames . ACCEPT ) ) ) ; for ( String accept : accepts ) { if ( StringUtils . startsWithIgnoreCase ( accept , "text/html" ) ) return true ; } return false ; }
Decides if an HTML response is acceptable to the client
21,863
public static Injector createInjector ( final PropertyFile configuration , final GuiceSetup setup ) { return new GuiceBuilder ( ) . withConfig ( configuration ) . withSetup ( setup ) . build ( ) ; }
Creates an Injector by taking a preloaded service . properties and a pre - constructed GuiceSetup
21,864
public String getMessage ( ) { if ( performanceDataList . isEmpty ( ) ) { return messageString ; } StringBuilder res = new StringBuilder ( messageString ) . append ( '|' ) ; for ( PerformanceData pd : performanceDataList ) { res . append ( pd . toPerformanceString ( ) ) . append ( ' ' ) ; } return res . toString ( ) ; }
Returns the message . If the performance data has been passed in they are attached at the end of the message accordingly to the Nagios specifications
21,865
private void start ( final ResourceInstanceEntity instance ) { azure . start ( instance . getProviderInstanceId ( ) ) ; instance . setState ( ResourceInstanceState . PROVISIONING ) ; }
Start the instance
21,866
private void stop ( final ResourceInstanceEntity instance ) { azure . stop ( instance ) ; instance . setState ( ResourceInstanceState . DISCARDING ) ; }
Stop the instance
21,867
private void updateState ( final ResourceInstanceEntity instance ) { ResourceInstanceState actual = azure . determineState ( instance ) ; instance . setState ( actual ) ; }
Check in with Azure on the instance state
21,868
public void userEventTriggered ( final ChannelHandlerContext ctx , final Object evt ) { if ( evt instanceof IdleStateEvent ) { IdleStateEvent e = ( IdleStateEvent ) evt ; if ( e . state ( ) == IdleState . READER_IDLE ) { ctx . close ( ) ; LOG . warn ( jnrpeContext , "Read Timeout" ) ; } else if ( e . state ( ) == IdleState . WRITER_IDLE ) { LOG . warn ( jnrpeContext , "Write Timeout" ) ; ctx . close ( ) ; } } }
Method userEventTriggered .
21,869
static String truncatePath ( String path , String commonPrefix ) { final int nextSlash = path . indexOf ( '/' , commonPrefix . length ( ) ) ; final int nextOpenCurly = path . indexOf ( '{' , commonPrefix . length ( ) ) ; if ( nextSlash > 0 ) return path . substring ( 0 , nextSlash ) ; else if ( nextOpenCurly > 0 ) return path . substring ( 0 , nextOpenCurly ) ; else return path ; }
Truncate path to the completion of the segment ending with the common prefix
21,870
public void setFilterGUIDs ( List < String > filterGUIDs ) { int i = 0 ; for ( String filterGUID : filterGUIDs ) { removeFilter ( "Filter_" + i ) ; Element filter = buildFilterElement ( "Filter_" + i , filterGUID ) ; element . addContent ( filter ) ; i ++ ; } }
Set the filter GUID replacing any filter that is currently defined
21,871
public static OgnlEvaluator getInstance ( final Object root , final String expression ) { final OgnlEvaluatorCollection collection = INSTANCE . getEvaluators ( getRootClass ( root ) ) ; return collection . get ( expression ) ; }
Get an OGNL Evaluator for a particular expression with a given input
21,872
public static PropertyFile find ( final ClassLoader classloader , final String ... fileNames ) { URL resolvedResource = null ; String resolvedFile = null ; for ( String fileName : fileNames ) { if ( fileName . charAt ( 0 ) == '/' ) { File file = new File ( fileName ) ; if ( file . exists ( ) ) { try { return PropertyFile . readOnly ( file ) ; } catch ( IOException e ) { throw new IllegalArgumentException ( "Error loading property file: " + fileName + ". Error: " + e . getMessage ( ) , e ) ; } } } else { final URL resource = classloader . getResource ( fileName ) ; if ( resource != null ) { resolvedFile = fileName ; resolvedResource = resource ; break ; } } } if ( resolvedFile == null ) { if ( fileNames . length == 1 ) throw new IllegalArgumentException ( "Error finding property file in classpath: " + fileNames [ 0 ] ) ; else throw new IllegalArgumentException ( "Error finding property files in classpath: " + Arrays . asList ( fileNames ) ) ; } else if ( log . isInfoEnabled ( ) ) log . info ( "{find} Loading properties from " + resolvedFile ) ; return openResource ( classloader , resolvedResource , resolvedFile ) ; }
Find a property file
21,873
private List < Class < ? > > getClassesByDiscriminators ( Collection < String > discriminators ) { Map < String , Class < ? > > entitiesByName = new HashMap < > ( ) ; for ( QEntity child : entity . getSubEntities ( ) ) { entitiesByName . put ( child . getDiscriminatorValue ( ) , child . getEntityClass ( ) ) ; } if ( ! entity . isEntityClassAbstract ( ) ) entitiesByName . put ( entity . getDiscriminatorValue ( ) , entity . getEntityClass ( ) ) ; List < Class < ? > > classes = new ArrayList < > ( discriminators . size ( ) ) ; for ( String discriminator : discriminators ) { final Class < ? > clazz = entitiesByName . get ( discriminator ) ; if ( clazz != null ) classes . add ( clazz ) ; else throw new IllegalArgumentException ( "Invalid class discriminator '" + discriminator + "', expected one of: " + entitiesByName . keySet ( ) ) ; } return classes ; }
Translates the set of string discriminators into entity classes
21,874
public Expression < ? > getProperty ( final WQPath path ) { final JPAJoin join = getOrCreateJoin ( path . getTail ( ) ) ; return join . property ( path . getHead ( ) . getPath ( ) ) ; }
Get a property automatically creating any joins along the way as needed
21,875
public JPAJoin getOrCreateJoin ( final WQPath path ) { if ( path == null ) return new JPAJoin ( criteriaBuilder , entity , root , false ) ; if ( ! joins . containsKey ( path . getPath ( ) ) ) { final JPAJoin parent = getOrCreateJoin ( path . getTail ( ) ) ; final JPAJoin join = parent . join ( path . getHead ( ) . getPath ( ) ) ; joins . put ( path . getPath ( ) , join ) ; return join ; } else { return joins . get ( path . getPath ( ) ) ; } }
Ensure a join has been set up for a path
21,876
public boolean hasCollectionFetch ( ) { if ( fetches != null ) for ( String fetch : fetches ) { QEntity parent = entity ; final String [ ] parts = StringUtils . split ( fetch , '.' ) ; for ( int i = 0 ; i < parts . length ; i ++ ) { if ( parent . hasRelation ( parts [ i ] ) ) { final QRelation relation = parent . getRelation ( parts [ i ] ) ; parent = relation . getEntity ( ) ; if ( relation . isCollection ( ) ) { if ( log . isTraceEnabled ( ) ) log . trace ( "Encountered fetch " + fetch + ". This resolves to " + relation + " which is a collection" ) ; return true ; } } else if ( parent . hasNonEntityRelation ( parts [ i ] ) ) { if ( parent . isNonEntityRelationCollection ( parts [ i ] ) ) return true ; } else { log . warn ( "Encountered relation " + parts [ i ] + " on " + parent . getName ( ) + " as part of path " + fetch + ". Assuming QEntity simply does not know this relation. Assuming worst case scenario (collection join is involved)" ) ; return true ; } } } return false ; }
Returns true if one of the fetches specified will result in a collection being pulled back
21,877
public Timecode subtract ( SampleCount samples ) { final SampleCount mySamples = getSampleCount ( ) ; final SampleCount result = mySamples . subtract ( samples ) ; return Timecode . getInstance ( result , dropFrame ) ; }
Subtract some samples from this timecode
21,878
public Timecode add ( SampleCount samples ) { final SampleCount mySamples = getSampleCount ( ) ; final SampleCount totalSamples = mySamples . add ( samples ) ; return TimecodeBuilder . fromSamples ( totalSamples , dropFrame ) . build ( ) ; }
Add some samples to this timecode
21,879
public Timecode addPrecise ( SampleCount samples ) throws ResamplingException { final SampleCount mySamples = getSampleCount ( ) ; final SampleCount totalSamples = mySamples . addPrecise ( samples ) ; return TimecodeBuilder . fromSamples ( totalSamples , dropFrame ) . build ( ) ; }
Add some samples to this timecode throwing an exception if precision would be lost
21,880
public void addCommand ( final String commandName , final String pluginName , final String commandLine ) { commandsList . add ( new Command ( commandName , pluginName , commandLine ) ) ; }
Adds a command to the section .
21,881
public List < ManifestEntry > scan ( final Bundle bundle ) { NullArgumentException . validateNotNull ( bundle , "Bundle" ) ; final Dictionary bundleHeaders = bundle . getHeaders ( ) ; if ( bundleHeaders != null && ! bundleHeaders . isEmpty ( ) ) { return asManifestEntryList ( m_manifestFilter . match ( dictionaryToMap ( bundleHeaders ) ) ) ; } else { return Collections . emptyList ( ) ; } }
Scans bundle manifest for matches against configured manifest headers .
21,882
public double resample ( final double samples , final Timebase oldRate ) { if ( samples == 0 ) { return 0 ; } else if ( ! this . equals ( oldRate ) ) { final double resampled = resample ( samples , oldRate , this ) ; return resampled ; } else { return samples ; } }
Convert a sample count from one timebase to another
21,883
private RestException buildKnown ( Constructor < RestException > constructor , RestFailure failure ) { try { return constructor . newInstance ( failure . exception . detail , null ) ; } catch ( Exception e ) { return buildUnknown ( failure ) ; } }
Build an exception for a known exception type
21,884
private UnboundRestException buildUnknown ( RestFailure failure ) { final String msg = failure . exception . shortName + ": " + failure . exception . detail + " (" + failure . id + ")" ; return new UnboundRestException ( msg ) ; }
Build an exception to represent an unknown or problematic exception type
21,885
public static ByteBuffer blockingRead ( SocketChannel so , long timeout , byte [ ] bytes ) throws IOException { ByteBuffer b = ByteBuffer . wrap ( bytes ) ; if ( bytes . length == 0 ) return b ; final long timeoutTime = ( timeout > 0 ) ? ( System . currentTimeMillis ( ) + timeout ) : ( Long . MAX_VALUE ) ; while ( b . remaining ( ) != 0 && System . currentTimeMillis ( ) < timeoutTime ) { if ( ! so . isConnected ( ) ) throw new IOException ( "Socket closed during read operation!" ) ; so . read ( b ) ; if ( b . remaining ( ) != 0 ) { try { Thread . sleep ( 20 ) ; } catch ( InterruptedException e ) { } } } if ( System . currentTimeMillis ( ) >= timeoutTime ) { return null ; } b . rewind ( ) ; return b ; }
Read a number of bytes from a socket terminating when complete after timeout milliseconds or if an error occurs
21,886
public < T > T deserialise ( final Class < T > clazz , final InputSource source ) { final Object obj = deserialise ( source ) ; if ( clazz . isInstance ( obj ) ) return clazz . cast ( obj ) ; else throw new JAXBRuntimeException ( "XML deserialised to " + obj . getClass ( ) + ", could not cast to the expected " + clazz ) ; }
Deserialise an input and cast to a particular type
21,887
public < T > T deserialise ( final Class < T > clazz , final String xml ) { final Object obj = deserialise ( new InputSource ( new StringReader ( xml ) ) ) ; if ( clazz . isInstance ( obj ) ) return clazz . cast ( obj ) ; else throw new JAXBRuntimeException ( "XML deserialised to " + obj . getClass ( ) + ", could not cast to the expected " + clazz ) ; }
Deserialise and cast to a particular type
21,888
public Document serialiseToDocument ( final Object obj ) { final Document document = DOMUtils . createDocumentBuilder ( ) . newDocument ( ) ; serialise ( obj , document ) ; return document ; }
Helper method to serialise an Object to an org . w3c . dom . Document
21,889
public void reload ( ) { try { final Execed process = Exec . rootUtility ( new File ( binPath , "nginx-reload" ) . getAbsolutePath ( ) ) ; process . waitForExit ( new Timeout ( 30 , TimeUnit . SECONDS ) . start ( ) , 0 ) ; } catch ( IOException e ) { throw new RuntimeException ( "Error executing nginx-reload command" , e ) ; } }
Reload the nginx configuration
21,890
public void reconfigure ( final String config ) { try { final File tempFile = File . createTempFile ( "nginx" , ".conf" ) ; try { FileHelper . write ( tempFile , config ) ; final Execed process = Exec . rootUtility ( new File ( binPath , "nginx-reconfigure" ) . getAbsolutePath ( ) , tempFile . getAbsolutePath ( ) ) ; process . waitForExit ( new Timeout ( 30 , TimeUnit . SECONDS ) . start ( ) , 0 ) ; } finally { FileUtils . deleteQuietly ( tempFile ) ; } } catch ( IOException e ) { throw new RuntimeException ( "Error executing nginx-reload command" , e ) ; } reload ( ) ; }
Rewrite the nginx site configuration and reload
21,891
public void installCertificates ( final String key , final String cert , final String chain ) { try { final File keyFile = File . createTempFile ( "key" , ".pem" ) ; final File certFile = File . createTempFile ( "cert" , ".pem" ) ; final File chainFile = File . createTempFile ( "chain" , ".pem" ) ; try { FileHelper . write ( keyFile , key ) ; FileHelper . write ( certFile , cert ) ; FileHelper . write ( chainFile , chain ) ; final Execed process = Exec . rootUtility ( new File ( binPath , "cert-update" ) . getAbsolutePath ( ) , keyFile . getAbsolutePath ( ) , certFile . getAbsolutePath ( ) , chainFile . getAbsolutePath ( ) ) ; process . waitForExit ( new Timeout ( 30 , TimeUnit . SECONDS ) . start ( ) , 0 ) ; } finally { FileUtils . deleteQuietly ( keyFile ) ; FileUtils . deleteQuietly ( certFile ) ; FileUtils . deleteQuietly ( chainFile ) ; } } catch ( IOException e ) { throw new RuntimeException ( "Error executing cert-update command" , e ) ; } }
Install new SSL Certificates for the host
21,892
public static PropertyFile get ( Class < ? > clazz ) { try { if ( clazz . getName ( ) . contains ( "$$EnhancerByGuice$$" ) ) clazz = clazz . getSuperclass ( ) ; final String classFileName = clazz . getSimpleName ( ) + ".class" ; final String classFilePathAndName = clazz . getName ( ) . replace ( '.' , '/' ) + ".class" ; URL url = clazz . getResource ( classFileName ) ; if ( log . isTraceEnabled ( ) ) log . trace ( "getResource(" + classFileName + ") = " + url ) ; if ( url == null ) { return null ; } else { String classesUrl = url . toString ( ) ; classesUrl = classesUrl . replace ( classFilePathAndName , "" ) ; if ( classesUrl . endsWith ( "WEB-INF/classes/" ) ) { classesUrl = classesUrl . replace ( "WEB-INF/classes/" , "" ) ; } final URL manifestURL = new URL ( classesUrl + "META-INF/MANIFEST.MF" ) ; try { final InputStream is = manifestURL . openStream ( ) ; try { final PropertyFile props = new PropertyFile ( ) ; final Manifest manifest = new Manifest ( is ) ; for ( Object key : manifest . getMainAttributes ( ) . keySet ( ) ) { final Object value = manifest . getMainAttributes ( ) . get ( key ) ; props . set ( key . toString ( ) , value . toString ( ) ) ; } return props ; } finally { IOUtils . closeQuietly ( is ) ; } } catch ( FileNotFoundException e ) { log . warn ( "Could not find: " + manifestURL , e ) ; return null ; } } } catch ( Throwable t ) { log . warn ( "Error acquiring MANIFEST.MF for " + clazz , t ) ; return null ; } }
Attempt to find the MANIFEST . MF associated with a particular class
21,893
private static void saveClass ( final ClassLoader cl , final Class c ) { if ( LOADED_PLUGINS . get ( cl ) == null ) { LOADED_PLUGINS . put ( cl , new ClassesData ( ) ) ; } ClassesData cd = LOADED_PLUGINS . get ( cl ) ; cd . addClass ( c ) ; }
Stores a class in the cache .
21,894
public static Class getClass ( final ClassLoader cl , final String className ) throws ClassNotFoundException { if ( LOADED_PLUGINS . get ( cl ) == null ) { LOADED_PLUGINS . put ( cl , new ClassesData ( ) ) ; } ClassesData cd = LOADED_PLUGINS . get ( cl ) ; Class clazz = cd . getClass ( className ) ; if ( clazz == null ) { clazz = cl . loadClass ( className ) ; saveClass ( cl , clazz ) ; } return clazz ; }
Returns a class object . If the class is new a new Class object is created otherwise the cached object is returned .
21,895
final Status evaluate ( final Metric metric ) { if ( metric == null || metric . getMetricValue ( ) == null ) { throw new NullPointerException ( "Metric value can't be null" ) ; } IThreshold thr = thresholdsMap . get ( metric . getMetricName ( ) ) ; if ( thr == null ) { return Status . OK ; } return thr . evaluate ( metric ) ; }
Evaluates the passed in metric against the threshold configured inside this evaluator . If the threshold do not refer the passed in metric then it is ignored and the next threshold is checked .
21,896
public final String executeSystemCommandAndGetOutput ( final String [ ] command , final String encoding ) throws IOException { Process p = Runtime . getRuntime ( ) . exec ( command ) ; StreamManager sm = new StreamManager ( ) ; try { InputStream input = sm . handle ( p . getInputStream ( ) ) ; StringBuffer lines = new StringBuffer ( ) ; String line ; BufferedReader in = ( BufferedReader ) sm . handle ( new BufferedReader ( new InputStreamReader ( input , encoding ) ) ) ; while ( ( line = in . readLine ( ) ) != null ) { lines . append ( line ) . append ( '\n' ) ; } return lines . toString ( ) ; } finally { sm . closeAll ( ) ; } }
Executes a system command with arguments and returns the output .
21,897
public synchronized Thread startThread ( String name ) throws IllegalThreadStateException { if ( ! running ) { log . info ( "[Daemon] {startThread} Starting thread " + name ) ; this . running = true ; thisThread = new Thread ( this , name ) ; thisThread . setDaemon ( shouldStartAsDaemon ( ) ) ; thisThread . start ( ) ; return thisThread ; } else { throw new IllegalThreadStateException ( "Daemon must be stopped before it may be started" ) ; } }
Starts this daemon creating a new thread for it
21,898
public synchronized void stopThread ( ) { if ( isRunning ( ) ) { if ( log . isInfoEnabled ( ) ) log . info ( "[Daemon] {stopThread} Requesting termination of thread " + thisThread . getName ( ) ) ; this . running = false ; synchronized ( this ) { this . notifyAll ( ) ; } } else { throw new IllegalThreadStateException ( "Daemon must be started before it may be stopped." ) ; } }
Requests the daemon terminate by setting a flag and sending an interrupt to the thread
21,899
public void guiceSetupComplete ( ) { this . registered = false ; postConstruct ( ) ; if ( onGuiceTakeover != null ) { onGuiceTakeover . run ( ) ; onGuiceTakeover = null ; } }
Called when Guice takes over this Daemon notifies the original constructor that the temporary services are no longer required