idx int64 0 41.2k | question stringlengths 74 4.04k | target stringlengths 7 750 |
|---|---|---|
21,900 | public void shutdown ( ) { ServiceManagerAppender . shutdown ( ) ; try { final LinkedList < LogLine > copy ; synchronized ( incoming ) { if ( ! incoming . isEmpty ( ) ) { copy = new LinkedList < > ( incoming ) ; incoming . clear ( ) ; } else { copy = null ; } } if ( copy != null ) { while ( ! copy . isEmpty ( ) && ( forwardLogs ( copy ) > 0 ) ) ; if ( ! copy . isEmpty ( ) ) log . warn ( "Shutdown called but failed to transfer all pending logs at time of shutdown to Service Manager: there are " + copy . size ( ) + " remaining" ) ; } } catch ( Throwable t ) { log . warn ( "Logging system encountered a problem during shutdown" , t ) ; } super . shutdown ( ) ; } | Shuts down the log forwarding |
21,901 | public List < CarbonProfile > getProfileList ( ) { final List < CarbonProfile > profiles = new ArrayList < CarbonProfile > ( ) ; Element profileList = element . getChild ( "ProfileList" ) ; if ( profileList != null ) { for ( Element profileElement : profileList . getChildren ( ) ) { CarbonProfile profile = new CarbonProfile ( profileElement ) ; profiles . add ( profile ) ; } } return profiles ; } | Return the list of profiles contained within the response |
21,902 | Node compile ( final Object root ) { if ( compiled == null ) { compiled = compileExpression ( root , this . expr ) ; parsed = null ; if ( this . notifyOnCompiled != null ) this . notifyOnCompiled . accept ( this . expr , this ) ; } return compiled ; } | Eagerly compile this OGNL expression |
21,903 | public final ReturnValue sendCommand ( final String sCommandName , final String ... arguments ) throws JNRPEClientException { return sendRequest ( new JNRPERequest ( sCommandName , arguments ) ) ; } | Inovoke a command installed in JNRPE . |
21,904 | private static void printVersion ( ) { System . out . println ( "jcheck_nrpe version " + JNRPEClient . class . getPackage ( ) . getImplementationVersion ( ) ) ; System . out . println ( "Copyright (c) 2013 Massimiliano Ziccardi" ) ; System . out . println ( "Licensed under the Apache License, Version 2.0" ) ; System . out . println ( ) ; } | Prints the application version . |
21,905 | @ SuppressWarnings ( "unchecked" ) private static void printUsage ( final Exception e ) { printVersion ( ) ; StringBuilder sbDivider = new StringBuilder ( "=" ) ; if ( e != null ) { System . out . println ( e . getMessage ( ) + "\n" ) ; } HelpFormatter hf = new HelpFormatter ( ) ; while ( sbDivider . length ( ) < hf . getPageWidth ( ) ) { sbDivider . append ( '=' ) ; } Set displaySettings = hf . getDisplaySettings ( ) ; displaySettings . clear ( ) ; displaySettings . add ( DisplaySetting . DISPLAY_GROUP_EXPANDED ) ; displaySettings . add ( DisplaySetting . DISPLAY_PARENT_CHILDREN ) ; Set usageSettings = hf . getFullUsageSettings ( ) ; usageSettings . clear ( ) ; usageSettings . add ( DisplaySetting . DISPLAY_PARENT_ARGUMENT ) ; usageSettings . add ( DisplaySetting . DISPLAY_ARGUMENT_BRACKETED ) ; usageSettings . add ( DisplaySetting . DISPLAY_PARENT_CHILDREN ) ; usageSettings . add ( DisplaySetting . DISPLAY_GROUP_EXPANDED ) ; hf . setDivider ( sbDivider . toString ( ) ) ; hf . setGroup ( configureCommandLine ( ) ) ; hf . print ( ) ; } | Prints usage instrunctions and eventually an error message about the latest execution . |
21,906 | public boolean isFinished ( ) { if ( finished ) return true ; try { final int code = exitCode ( ) ; finished ( code ) ; return true ; } catch ( IllegalThreadStateException e ) { return false ; } } | Determines if the application has completed yet |
21,907 | protected Thread copy ( final InputStream in , final Writer out ) { Runnable r = ( ) -> { try { StreamUtil . streamCopy ( in , out ) ; } catch ( IOException e ) { try { out . flush ( ) ; } catch ( Throwable t ) { } unexpectedFailure ( e ) ; } } ; Thread t = new Thread ( r ) ; t . setName ( this + " - IOCopy " + in + " to " + out ) ; t . setDaemon ( true ) ; t . start ( ) ; return t ; } | Commence a background copy |
21,908 | protected void configure ( ServletContainerDispatcher dispatcher ) throws ServletException { registry . register ( this , true ) ; final Registry resteasyRegistry ; final ResteasyProviderFactory providerFactory ; { final ResteasyRequestResponseFactory converter = new ResteasyRequestResponseFactory ( dispatcher ) ; dispatcher . init ( context , bootstrap , converter , converter ) ; if ( filterConfig != null ) dispatcher . getDispatcher ( ) . getDefaultContextObjects ( ) . put ( FilterConfig . class , filterConfig ) ; if ( servletConfig != null ) dispatcher . getDispatcher ( ) . getDefaultContextObjects ( ) . put ( ServletConfig . class , servletConfig ) ; resteasyRegistry = dispatcher . getDispatcher ( ) . getRegistry ( ) ; providerFactory = dispatcher . getDispatcher ( ) . getProviderFactory ( ) ; } for ( Class < ? > providerClass : ResteasyProviderRegistry . getClasses ( ) ) { log . debug ( "Registering REST providers: " + providerClass . getName ( ) ) ; providerFactory . registerProvider ( providerClass ) ; } for ( Object provider : ResteasyProviderRegistry . getSingletons ( ) ) { log . debug ( "Registering REST provider singleton: " + provider ) ; providerFactory . registerProviderInstance ( provider ) ; } providerFactory . registerProviderInstance ( new LogReportMessageBodyReader ( ) ) ; providerFactory . registerProviderInstance ( jaxbContextResolver ) ; { providerFactory . register ( this . exceptionMapper ) ; log . trace ( "ExceptionMapper registered for ApplicationException" ) ; } for ( RestResource resource : RestResourceRegistry . getResources ( ) ) { log . debug ( "Registering REST resource: " + resource . getResourceClass ( ) . getName ( ) ) ; resteasyRegistry . addResourceFactory ( new ResteasyGuiceResource ( injector , resource . getResourceClass ( ) ) ) ; } } | Try to initialise a ServletContainerDispatcher with the connection to the Guice REST services |
21,909 | private static String parseExpecting ( final Stage stage ) { StringBuilder expected = new StringBuilder ( ) ; for ( String key : stage . getTransitionNames ( ) ) { expected . append ( ',' ) . append ( stage . getTransition ( key ) . expects ( ) ) ; } return expected . substring ( 1 ) ; } | Utility method for error messages . |
21,910 | public static File createTempFile ( final String prefix , final String suffix ) { try { File tempFile = File . createTempFile ( prefix , suffix ) ; if ( tempFile . exists ( ) ) { if ( ! tempFile . delete ( ) ) throw new RuntimeException ( "Could not delete new temp file: " + tempFile ) ; } return tempFile ; } catch ( IOException e ) { log . error ( "[FileHelper] {createTempFile} Error creating temp file: " + e . getMessage ( ) , e ) ; return null ; } } | Creates a temporary file name |
21,911 | public static boolean safeMove ( File src , File dest ) throws SecurityException { assert ( src . exists ( ) ) ; final boolean createDestIfNotExist = true ; try { if ( src . isFile ( ) ) FileUtils . moveFile ( src , dest ) ; else FileUtils . moveDirectoryToDirectory ( src , dest , createDestIfNotExist ) ; return true ; } catch ( IOException e ) { log . error ( "{safeMove} Error during move operation: " + e . getMessage ( ) , e ) ; return false ; } } | Safely moves a file from one place to another ensuring the filesystem is left in a consistent state |
21,912 | public static boolean delete ( File f ) throws IOException { assert ( f . exists ( ) ) ; if ( f . isDirectory ( ) ) { FileUtils . deleteDirectory ( f ) ; return true ; } else { return f . delete ( ) ; } } | Deletes a local file or directory from the filesystem |
21,913 | public static boolean smartEquals ( File one , File two , boolean checkName ) throws IOException { if ( checkName ) { if ( ! one . getName ( ) . equals ( two . getName ( ) ) ) { return false ; } } if ( one . isDirectory ( ) == two . isDirectory ( ) ) { if ( one . isDirectory ( ) ) { File [ ] filesOne = one . listFiles ( ) ; File [ ] filesTwo = two . listFiles ( ) ; if ( filesOne . length == filesTwo . length ) { if ( filesOne . length > 0 ) { for ( int i = 0 ; i < filesOne . length ; i ++ ) { if ( ! smartEquals ( filesOne [ i ] , filesTwo [ i ] , checkName ) ) { return false ; } } return true ; } else { return true ; } } else { return false ; } } else if ( one . isFile ( ) && two . isFile ( ) ) { if ( one . length ( ) == two . length ( ) ) { return FileUtils . contentEquals ( one , two ) ; } else { return false ; } } else { throw new IOException ( "I don't know how to handle a non-file non-directory File: one=" + one + " two=" + two ) ; } } else { return false ; } } | Determines if 2 files or directories are equivalent by looking inside them |
21,914 | public CarbonReply send ( Element element ) throws CarbonException { try { final String responseXml = send ( serialise ( element ) ) ; return new CarbonReply ( deserialise ( responseXml ) ) ; } catch ( CarbonException e ) { throw e ; } catch ( Exception e ) { throw new CarbonException ( e ) ; } } | Send some XML |
21,915 | private synchronized void setService ( final T newService ) { if ( m_service != newService ) { LOG . debug ( "Service changed [" + m_service + "] -> [" + newService + "]" ) ; final T oldService = m_service ; m_service = newService ; if ( m_serviceListener != null ) { m_serviceListener . serviceChanged ( oldService , m_service ) ; } } } | Sets the new service and notifies the listener that the service was changed . |
21,916 | private synchronized void resolveService ( ) { T newService = null ; final Iterator < T > it = m_serviceCollection . iterator ( ) ; while ( newService == null && it . hasNext ( ) ) { final T candidateService = it . next ( ) ; if ( ! candidateService . equals ( getService ( ) ) ) { newService = candidateService ; } } setService ( newService ) ; } | Resolves a new service by serching the services collection for first available service . |
21,917 | protected void onStart ( ) { m_serviceCollection = new ServiceCollection < T > ( m_context , m_serviceClass , new CollectionListener ( ) ) ; m_serviceCollection . start ( ) ; } | Creates a service collection and starts it . |
21,918 | protected void onStop ( ) { if ( m_serviceCollection != null ) { m_serviceCollection . stop ( ) ; m_serviceCollection = null ; } setService ( null ) ; } | Stops the service collection and releases resources . |
21,919 | public ProcessBuilder getProcessBuilder ( ) { if ( spawned ) return builder ; if ( runAs != null ) { String command = cmd . get ( 0 ) ; if ( command . charAt ( 0 ) == '-' && ! SudoFeature . hasArgumentsEnd ( ) ) throw new IllegalArgumentException ( "Command to runAs starts with - but this version of sudo does not support the -- argument end token: this command cannot, therefore, be executed securely. Command was: '" + command + "'" ) ; if ( this . environment . size ( ) > 0 ) { for ( final String key : this . environment . keySet ( ) ) { final String value = this . environment . get ( key ) ; final String var = key + "=" + value ; addToCmd ( 0 , var ) ; } addToCmd ( 0 , "env" ) ; } if ( SudoFeature . hasArgumentsEnd ( ) ) addToCmd ( 0 , "--" ) ; String noninteractive = SudoFeature . hasNonInteractive ( ) ? "-n" : null ; if ( this . runAs . equals ( SUPERUSER_IDENTIFIER ) ) { addToCmd ( 0 , "sudo" , noninteractive ) ; } else addToCmd ( 0 , "sudo" , noninteractive , "-u" , runAs ) ; } else { builder . environment ( ) . putAll ( this . environment ) ; } spawned = true ; if ( log . isInfoEnabled ( ) ) { log . info ( "ProcessBuilder created for command: " + join ( " " , cmd ) ) ; } return builder ; } | Returns a ProcessBuilder for use in a manual launching |
21,920 | private int percent ( final long val , final long total ) { if ( total == 0 ) { return 100 ; } if ( val == 0 ) { return 0 ; } double dVal = ( double ) val ; double dTotal = ( double ) total ; return ( int ) ( dVal / dTotal * 100 ) ; } | Compute the percent values . |
21,921 | private String format ( final long bytes ) { if ( bytes > MB ) { return String . valueOf ( bytes / MB ) + " MB" ; } return String . valueOf ( bytes / KB ) + " KB" ; } | Format the size returning it as MB or KB . |
21,922 | private boolean passes ( final AuthScope scope , final AuthConstraint constraint , final CurrentUser user ) { if ( scope . getSkip ( constraint ) ) { if ( log . isTraceEnabled ( ) ) log . trace ( "Allowing method invocation (skip=true)." ) ; return true ; } else { final boolean pass = user . hasRole ( scope . getRole ( constraint ) ) ; if ( log . isTraceEnabled ( ) ) if ( pass ) log . trace ( "Allow method invocation: user " + user + " has role " + scope . getRole ( constraint ) ) ; else log . trace ( "Deny method invocation: user " + user + " does not have role " + scope . getRole ( constraint ) ) ; return pass ; } } | Determines whether a given user has the necessary role to pass a constraint |
21,923 | void addInstance ( final Class < ? > discoveredType , final Object newlyConstructed ) { WeakHashMap < Object , Void > map ; synchronized ( instances ) { map = instances . get ( discoveredType ) ; if ( map == null ) { map = new WeakHashMap < > ( ) ; instances . put ( discoveredType , map ) ; } } synchronized ( map ) { map . put ( newlyConstructed , null ) ; } } | Register an instance of a property - consuming type ; the registry will use a weak reference to hold on to this instance so that it can be discarded if it has a short lifespan |
21,924 | public static String doGET ( final URL url , final Properties requestProps , final Integer timeout , boolean includeHeaders , boolean ignoreBody ) throws Exception { return doRequest ( url , requestProps , timeout , includeHeaders , ignoreBody , "GET" ) ; } | Do a http get request and return response |
21,925 | public static String doPOST ( final URL url , final Properties requestProps , final Integer timeout , final String encodedData , boolean includeHeaders , boolean ignoreBody ) throws IOException { HttpURLConnection conn = ( HttpURLConnection ) url . openConnection ( ) ; setRequestProperties ( requestProps , conn , timeout ) ; sendPostData ( conn , encodedData ) ; return parseHttpResponse ( conn , includeHeaders , ignoreBody ) ; } | Do a http post request and return response |
21,926 | public static void sendPostData ( HttpURLConnection conn , String encodedData ) throws IOException { StreamManager sm = new StreamManager ( ) ; try { conn . setDoOutput ( true ) ; conn . setRequestMethod ( "POST" ) ; if ( conn . getRequestProperty ( "Content-Type" ) == null ) { conn . setRequestProperty ( "Content-Type" , "application/x-www-form-urlencoded" ) ; } if ( encodedData != null ) { if ( conn . getRequestProperty ( "Content-Length" ) == null ) { conn . setRequestProperty ( "Content-Length" , String . valueOf ( encodedData . getBytes ( "UTF-8" ) . length ) ) ; } DataOutputStream out = new DataOutputStream ( sm . handle ( conn . getOutputStream ( ) ) ) ; out . write ( encodedData . getBytes ( ) ) ; out . close ( ) ; } } finally { sm . closeAll ( ) ; } } | Submits http post data to an HttpURLConnection . |
21,927 | public static void setRequestProperties ( final Properties props , HttpURLConnection conn , Integer timeout ) { if ( props != null ) { if ( props . get ( "User-Agent" ) == null ) { conn . setRequestProperty ( "User-Agent" , "Java" ) ; } for ( Entry entry : props . entrySet ( ) ) { conn . setRequestProperty ( String . valueOf ( entry . getKey ( ) ) , String . valueOf ( entry . getValue ( ) ) ) ; } } if ( timeout != null ) { conn . setConnectTimeout ( timeout * 1000 ) ; } } | Sets request headers for an http connection |
21,928 | public static String parseHttpResponse ( HttpURLConnection conn , boolean includeHeaders , boolean ignoreBody ) throws IOException { StringBuilder buff = new StringBuilder ( ) ; if ( includeHeaders ) { buff . append ( conn . getResponseCode ( ) ) . append ( ' ' ) . append ( conn . getResponseMessage ( ) ) . append ( '\n' ) ; int idx = ( conn . getHeaderFieldKey ( 0 ) == null ) ? 1 : 0 ; while ( true ) { String key = conn . getHeaderFieldKey ( idx ) ; if ( key == null ) { break ; } buff . append ( key ) . append ( ": " ) . append ( conn . getHeaderField ( idx ) ) . append ( '\n' ) ; ++ idx ; } } StreamManager sm = new StreamManager ( ) ; try { if ( ! ignoreBody ) { BufferedReader in = ( BufferedReader ) sm . handle ( new BufferedReader ( new InputStreamReader ( conn . getInputStream ( ) ) ) ) ; String inputLine ; while ( ( inputLine = in . readLine ( ) ) != null ) { buff . append ( inputLine ) ; } in . close ( ) ; } } finally { sm . closeAll ( ) ; } return buff . toString ( ) ; } | Parses an http request response |
21,929 | private List < Metric > checkAlive ( final Connection c , final ICommandLine cl ) throws BadThresholdException , SQLException { List < Metric > metricList = new ArrayList < Metric > ( ) ; Statement stmt = null ; ResultSet rs = null ; long lStart = System . currentTimeMillis ( ) ; try { stmt = c . createStatement ( ) ; rs = stmt . executeQuery ( QRY_CHECK_ALIVE ) ; if ( ! rs . next ( ) ) { throw new SQLException ( "Unable to execute a 'SELECT SYSDATE FROM DUAL' query" ) ; } long elapsed = ( System . currentTimeMillis ( ) - lStart ) / 1000L ; metricList . add ( new Metric ( "conn" , "Connection time : " + elapsed + "s" , new BigDecimal ( elapsed ) , new BigDecimal ( 0 ) , null ) ) ; return metricList ; } finally { DBUtils . closeQuietly ( rs ) ; DBUtils . closeQuietly ( stmt ) ; } } | Checks if the database is reacheble . |
21,930 | private List < Metric > checkTablespace ( final Connection c , final ICommandLine cl ) throws BadThresholdException , SQLException { List < Metric > metricList = new ArrayList < Metric > ( ) ; String sTablespace = cl . getOptionValue ( "tablespace" ) . toUpperCase ( ) ; final String sQry = String . format ( QRY_CHECK_TBLSPACE_PATTERN , sTablespace ) ; Statement stmt = null ; ResultSet rs = null ; try { stmt = c . createStatement ( ) ; rs = stmt . executeQuery ( sQry ) ; boolean bFound = rs . next ( ) ; if ( ! bFound ) { throw new SQLException ( "Tablespace " + cl . getOptionValue ( "tablespace" ) + " not found." ) ; } BigDecimal tsFree = rs . getBigDecimal ( 1 ) ; BigDecimal tsTotal = rs . getBigDecimal ( 2 ) ; BigDecimal tsPct = rs . getBigDecimal ( 3 ) ; metricList . add ( new Metric ( "tblspace_freepct" , cl . getOptionValue ( "tablespace" ) + " : " + tsPct + "% free" , tsPct , new BigDecimal ( 0 ) , new BigDecimal ( 100 ) ) ) ; metricList . add ( new Metric ( "tblspace_free" , cl . getOptionValue ( "tablespace" ) + " : " + tsFree + "MB free" , tsPct , new BigDecimal ( 0 ) , tsTotal ) ) ; return metricList ; } finally { DBUtils . closeQuietly ( rs ) ; DBUtils . closeQuietly ( stmt ) ; } } | Checks database usage . |
21,931 | private List < Metric > checkCache ( final Connection c , final ICommandLine cl ) throws BadThresholdException , SQLException { List < Metric > metricList = new ArrayList < Metric > ( ) ; String sQry1 = "select (1-(pr.value/(dbg.value+cg.value)))*100" + " from v$sysstat pr, v$sysstat dbg, v$sysstat cg" + " where pr.name='physical reads'" + " and dbg.name='db block gets'" + " and cg.name='consistent gets'" ; String sQry2 = "select sum(lc.pins)/(sum(lc.pins)" + "+sum(lc.reloads))*100 from v$librarycache lc" ; Statement stmt = null ; ResultSet rs = null ; try { stmt = c . createStatement ( ) ; rs = stmt . executeQuery ( sQry1 ) ; rs . next ( ) ; BigDecimal buf_hr = rs . getBigDecimal ( 1 ) ; rs = stmt . executeQuery ( sQry2 ) ; rs . next ( ) ; BigDecimal lib_hr = rs . getBigDecimal ( 1 ) ; String libHitRate = "Cache Hit Rate {1,number,0.#}% Lib" ; String buffHitRate = "Cache Hit Rate {1,number,0.#}% Buff" ; metricList . add ( new Metric ( "cache_buf" , MessageFormat . format ( buffHitRate , buf_hr ) , buf_hr , new BigDecimal ( 0 ) , new BigDecimal ( 100 ) ) ) ; metricList . add ( new Metric ( "cache_lib" , MessageFormat . format ( libHitRate , lib_hr ) , lib_hr , new BigDecimal ( 0 ) , new BigDecimal ( 100 ) ) ) ; return metricList ; } finally { DBUtils . closeQuietly ( rs ) ; DBUtils . closeQuietly ( stmt ) ; } } | Checks cache hit rates . |
21,932 | public void rotateUserAccessKey ( final int id ) { final UserEntity account = getById ( id ) ; if ( account != null ) { account . setAccessKeySecondary ( account . getAccessKey ( ) ) ; account . setAccessKey ( SimpleId . alphanumeric ( UserManagerBearerToken . PREFIX , 100 ) ) ; update ( account ) ; } else { throw new IllegalArgumentException ( "No such user: " + id ) ; } } | Rotate the primary access key - > secondary access key dropping the old secondary access key and generating a new primary access key |
21,933 | private String hashPassword ( String password ) { return BCrypt . hash ( password . toCharArray ( ) , BCrypt . DEFAULT_COST ) ; } | Creates a BCrypted hash for a password |
21,934 | public static String formatSize ( final long value ) { double size = value ; DecimalFormat df = new DecimalFormat ( "#.##" ) ; if ( size >= GB ) { return df . format ( size / GB ) + " GB" ; } if ( size >= MB ) { return df . format ( size / MB ) + " MB" ; } if ( size >= KB ) { return df . format ( size / KB ) + " KB" ; } return String . valueOf ( ( int ) size ) + " bytes" ; } | Returns formatted size of a file size . |
21,935 | public static boolean extractArchive ( File tarFile , File extractTo ) { try { TarArchive ta = getArchive ( tarFile ) ; try { if ( ! extractTo . exists ( ) ) if ( ! extractTo . mkdir ( ) ) throw new RuntimeException ( "Could not create extract dir: " + extractTo ) ; ta . extractContents ( extractTo ) ; } finally { ta . closeArchive ( ) ; } return true ; } catch ( FileNotFoundException e ) { log . error ( "File not found exception: " + e . getMessage ( ) , e ) ; return false ; } catch ( Exception e ) { log . error ( "Exception while extracting archive: " + e . getMessage ( ) , e ) ; return false ; } } | Extracts a . tar or . tar . gz archive to a given folder |
21,936 | public static boolean addFilesToExistingJar ( File jarFile , String basePathWithinJar , Map < String , File > files , ActionOnConflict action ) throws IOException { File tempFile = FileHelper . createTempFile ( jarFile . getName ( ) , null ) ; boolean renamed = jarFile . renameTo ( tempFile ) ; if ( ! renamed ) { throw new RuntimeException ( "[ArchiveHelper] {addFilesToExistingJar} " + "Could not rename the file " + jarFile . getAbsolutePath ( ) + " to " + tempFile . getAbsolutePath ( ) ) ; } ZipInputStream jarInput = new ZipInputStream ( new FileInputStream ( tempFile ) ) ; ZipOutputStream jarOutput = new ZipOutputStream ( new FileOutputStream ( jarFile ) ) ; try { switch ( action ) { case OVERWRITE : overwriteFiles ( jarInput , jarOutput , basePathWithinJar , files ) ; break ; case CONFLICT : conflictFiles ( jarInput , jarOutput , basePathWithinJar , files ) ; break ; default : throw new IOException ( "An invalid ActionOnConflict action was received" ) ; } } finally { if ( ! tempFile . delete ( ) ) log . warn ( "Could not delete temp file " + tempFile ) ; } return true ; } | Adds a file or files to a jar file replacing the original one |
21,937 | public static < T > List < T > list ( Iterable < T > iterable ) { List < T > list = new ArrayList < T > ( ) ; for ( T item : iterable ) { list . add ( item ) ; } return list ; } | Converts an Iterable into a List |
21,938 | public static < T > List < T > last ( final List < T > src , int count ) { if ( count >= src . size ( ) ) { return new ArrayList < T > ( src ) ; } else { final List < T > dest = new ArrayList < T > ( count ) ; final int size = src . size ( ) ; for ( int i = size - count ; i < size ; i ++ ) { dest . add ( src . get ( i ) ) ; } return dest ; } } | Return at most the last n items from the source list |
21,939 | public static < T > List < T > tail ( List < T > list ) { if ( list . isEmpty ( ) ) return Collections . emptyList ( ) ; else return list . subList ( 1 , list . size ( ) ) ; } | Returns a sublist containing all the items in the list after the first |
21,940 | public static int [ ] flip ( int [ ] src , int [ ] dest , final int start , final int length ) { if ( dest == null || dest . length < length ) dest = new int [ length ] ; int srcIndex = start + length ; for ( int i = 0 ; i < length ; i ++ ) { dest [ i ] = src [ -- srcIndex ] ; } return dest ; } | Reverses an integer array |
21,941 | public static < T > List < T > concat ( final Collection < ? extends T > ... lists ) { ArrayList < T > al = new ArrayList < T > ( ) ; for ( Collection < ? extends T > list : lists ) if ( list != null ) al . addAll ( list ) ; return al ; } | Concatenates a number of Collections into a single List |
21,942 | public static < T > Set < T > union ( final Collection < ? extends T > ... lists ) { Set < T > s = new HashSet < T > ( ) ; for ( Collection < ? extends T > list : lists ) if ( list != null ) s . addAll ( list ) ; return s ; } | Concatenates a number of Collections into a single Set |
21,943 | private ThymeleafTemplater getOrCreateTemplater ( ) { ThymeleafTemplater templater = this . templater . get ( ) ; if ( templater == null ) { final TemplateEngine engine = getOrCreateEngine ( ) ; templater = new ThymeleafTemplater ( engine , configuration , metrics , userProvider ) ; templater . set ( "coreRestPrefix" , coreRestPrefix ) ; templater . set ( "coreRestEndpoint" , coreRestEndpoint . toString ( ) ) ; templater . set ( "coreServices" , services ) ; templater . set ( "currentUser" , new ThymeleafCurrentUserUtils ( userProvider ) ) ; this . templater = new WeakReference < > ( templater ) ; } return templater ; } | Retrieve or build a Thymeleaf templater |
21,944 | public static boolean isPrimitive ( final Object value ) { return ( value == null || value instanceof String || value instanceof Number || value instanceof Boolean || value instanceof DateTime || value instanceof Date || value instanceof SampleCount || value instanceof Timecode || value . getClass ( ) . isEnum ( ) || value . getClass ( ) . isPrimitive ( ) ) ; } | Helper method that returns True if the provided value should be represented as a String |
21,945 | public String toPerformanceString ( ) { final StringBuilder res = new StringBuilder ( ) . append ( quote ( metric . getMetricName ( ) ) ) . append ( '=' ) . append ( ( metric . getMetricValue ( prefix ) ) . toPrettyPrintedString ( ) ) ; if ( unitOfMeasure != null ) { switch ( unitOfMeasure ) { case milliseconds : res . append ( "ms" ) ; break ; case microseconds : res . append ( "us" ) ; break ; case seconds : res . append ( 's' ) ; break ; case bytes : res . append ( 'B' ) ; break ; case kilobytes : res . append ( "KB" ) ; break ; case megabytes : res . append ( "MB" ) ; break ; case gigabytes : res . append ( "GB" ) ; break ; case terabytes : res . append ( "TB" ) ; break ; case percentage : res . append ( '%' ) ; break ; case counter : res . append ( 'c' ) ; break ; default : } } if ( unit != null ) { res . append ( unit ) ; } res . append ( ';' ) ; if ( warningRange != null ) { res . append ( warningRange ) ; } res . append ( ';' ) ; if ( criticalRange != null ) { res . append ( criticalRange ) ; } res . append ( ';' ) ; if ( metric . getMinValue ( ) != null ) { res . append ( metric . getMinValue ( prefix ) . toPrettyPrintedString ( ) ) ; } res . append ( ';' ) ; if ( metric . getMaxValue ( ) != null ) { res . append ( metric . getMaxValue ( prefix ) . toPrettyPrintedString ( ) ) ; } while ( res . charAt ( res . length ( ) - 1 ) == ';' ) { res . deleteCharAt ( res . length ( ) - 1 ) ; } return res . toString ( ) ; } | Produce a performance string according to Nagios specification based on the value of this performance data object . |
21,946 | private String quote ( final String lbl ) { if ( lbl . indexOf ( ' ' ) == - 1 ) { return lbl ; } return new StringBuffer ( "'" ) . append ( lbl ) . append ( '\'' ) . toString ( ) ; } | Quotes the label if required . |
21,947 | public String getSchema ( Class < ? > clazz ) { if ( clazz == Integer . class || clazz == Integer . TYPE ) { return "integer [" + Integer . MIN_VALUE + " to " + Integer . MAX_VALUE + "]" ; } else if ( clazz == Long . class || clazz == Long . TYPE ) { return "long [" + Long . MIN_VALUE + " to " + Long . MAX_VALUE + "]" ; } else if ( clazz == Double . class || clazz == Double . TYPE ) { return "double [" + Double . MIN_VALUE + " to " + Double . MAX_VALUE + "]" ; } else if ( clazz == Boolean . class || clazz == Boolean . TYPE ) { return "boolean [true, false]" ; } else if ( clazz == Void . class ) { return "void" ; } else if ( clazz == Byte [ ] . class || clazz == byte [ ] . class ) { return "binary stream" ; } else if ( clazz . isEnum ( ) ) { return "enum " + Arrays . asList ( clazz . getEnumConstants ( ) ) ; } else if ( clazz . isAnnotationPresent ( XmlRootElement . class ) ) { try { final JAXBSerialiser serialiser = JAXBSerialiser . getMoxy ( clazz ) ; return generate ( serialiser ) ; } catch ( Exception e ) { return "error generating schema for " + clazz + ": " + e . getMessage ( ) ; } } else if ( clazz . isAnnotationPresent ( XmlType . class ) || clazz . isAnnotationPresent ( XmlEnum . class ) ) { try { final JAXBSerialiser serialiser = JAXBSerialiser . getMoxy ( clazz . getPackage ( ) . getName ( ) ) ; return generate ( serialiser ) ; } catch ( Exception e ) { return "error generating schema for XSD-To-Java package schema for class " + clazz + ": " + e . getMessage ( ) ; } } else { return clazz . toString ( ) ; } } | Retrieve a schema description for a type |
21,948 | public MetricBuilder withValue ( Number value , String prettyPrintFormat ) { current = new MetricValue ( value . toString ( ) , prettyPrintFormat ) ; return this ; } | Sets the value of the metric to be built . |
21,949 | public MetricBuilder withMinValue ( Number value , String prettyPrintFormat ) { min = new MetricValue ( value . toString ( ) , prettyPrintFormat ) ; return this ; } | Sets the minimum value of the metric to be built . |
21,950 | public MetricBuilder withMaxValue ( Number value , String prettyPrintFormat ) { max = new MetricValue ( value . toString ( ) , prettyPrintFormat ) ; return this ; } | Sets the maximum value of the metric to be built . |
21,951 | public MetricBuilder withMessage ( String messagePattern , Object ... params ) { this . metricMessage = MessageFormat . format ( messagePattern , params ) ; return this ; } | Sets the message to be associated with this metric . |
21,952 | public ResultSetConstraint build ( Map < String , List < String > > constraints ) { return builder ( constraints ) . build ( ) ; } | Convenience method to build based on a Map of constraints quickly |
21,953 | @ SuppressWarnings ( "unchecked" ) public void setTypeLiteral ( TypeLiteral < T > clazz ) { if ( clazz == null ) throw new IllegalArgumentException ( "Cannot set null TypeLiteral on " + this ) ; if ( this . clazz != null && ! this . clazz . equals ( clazz . getRawType ( ) ) ) throw new IllegalStateException ( "Cannot call setTypeLiteral twice! Already has value " + this . clazz + ", will not overwrite with " + clazz . getRawType ( ) ) ; this . clazz = ( Class < T > ) clazz . getRawType ( ) ; isLargeTable = this . clazz . isAnnotationPresent ( LargeTable . class ) ; } | Called by guice to provide the Class associated with T |
21,954 | public Collection < ID > getIds ( final WebQuery constraints ) { return ( Collection < ID > ) find ( constraints , JPASearchStrategy . ID ) . getList ( ) ; } | Get a list of IDs matching a WebQuery |
21,955 | private SSLEngine getSSLEngine ( ) throws KeyStoreException , CertificateException , IOException , UnrecoverableKeyException , KeyManagementException { final StreamManager streamManager = new StreamManager ( ) ; SSLContext ctx ; KeyManagerFactory kmf ; try { final InputStream ksStream = getClass ( ) . getClassLoader ( ) . getResourceAsStream ( KEYSTORE_NAME ) ; streamManager . handle ( ksStream ) ; ctx = SSLContext . getInstance ( "SSLv3" ) ; kmf = KeyManagerFactory . getInstance ( KeyManagerFactory . getDefaultAlgorithm ( ) ) ; final KeyStore ks = KeyStore . getInstance ( "JKS" ) ; char [ ] passphrase = KEYSTORE_PWD . toCharArray ( ) ; ks . load ( ksStream , passphrase ) ; kmf . init ( ks , passphrase ) ; ctx . init ( kmf . getKeyManagers ( ) , null , new java . security . SecureRandom ( ) ) ; } catch ( NoSuchAlgorithmException e ) { throw new SSLException ( "Unable to initialize SSLSocketFactory" + e . getMessage ( ) , e ) ; } finally { streamManager . closeAll ( ) ; } return ctx . createSSLEngine ( ) ; } | Creates configures and returns the SSL engine . |
21,956 | private ServerBootstrap getServerBootstrap ( final boolean useSSL ) { final CommandInvoker invoker = new CommandInvoker ( pluginRepository , commandRepository , acceptParams , getExecutionContext ( ) ) ; final ServerBootstrap serverBootstrap = new ServerBootstrap ( ) ; serverBootstrap . group ( bossGroup , workerGroup ) . channel ( NioServerSocketChannel . class ) . childHandler ( new ChannelInitializer < SocketChannel > ( ) { public void initChannel ( final SocketChannel ch ) throws Exception { if ( useSSL ) { final SSLEngine engine = getSSLEngine ( ) ; engine . setEnabledCipherSuites ( engine . getSupportedCipherSuites ( ) ) ; engine . setUseClientMode ( false ) ; engine . setNeedClientAuth ( false ) ; ch . pipeline ( ) . addLast ( "ssl" , new SslHandler ( engine ) ) ; } ch . pipeline ( ) . addLast ( new JNRPERequestDecoder ( ) , new JNRPEResponseEncoder ( ) , new JNRPEServerHandler ( invoker , context ) ) . addLast ( "idleStateHandler" , new IdleStateHandler ( readTimeout , writeTimeout , 0 ) ) . addLast ( "jnrpeIdleStateHandler" , new JNRPEIdleStateHandler ( context ) ) ; } } ) . option ( ChannelOption . SO_BACKLOG , maxAcceptedConnections ) . childOption ( ChannelOption . SO_KEEPALIVE , Boolean . TRUE ) ; return serverBootstrap ; } | Creates and returns a configured NETTY ServerBootstrap object . |
21,957 | public SampleCount resample ( Timebase newRate ) { if ( ! this . rate . equals ( newRate ) ) { final long newSamples = getSamples ( newRate ) ; return new SampleCount ( newSamples , newRate ) ; } else { return this ; } } | Resample this sample count to another rate |
21,958 | protected void onStart ( ) { m_mappings = new HashMap < Bundle , List < T > > ( ) ; m_context . addBundleListener ( m_bundleListener = new SynchronousBundleListener ( ) { public void bundleChanged ( final BundleEvent bundleEvent ) { switch ( bundleEvent . getType ( ) ) { case BundleEvent . STARTED : register ( bundleEvent . getBundle ( ) ) ; break ; case BundleEvent . STOPPED : unregister ( bundleEvent . getBundle ( ) ) ; break ; } } } ) ; Bundle [ ] bundles = m_context . getBundles ( ) ; if ( bundles != null ) { for ( Bundle bundle : bundles ) { if ( bundle . getState ( ) == Bundle . ACTIVE ) { register ( bundle ) ; } } } } | Registers a listener for bundle events and scans already active bundles . |
21,959 | protected void onStop ( ) { m_context . removeBundleListener ( m_bundleListener ) ; final Bundle [ ] toBeRemoved = m_mappings . keySet ( ) . toArray ( new Bundle [ m_mappings . keySet ( ) . size ( ) ] ) ; for ( Bundle bundle : toBeRemoved ) { unregister ( bundle ) ; } m_bundleListener = null ; m_mappings = null ; } | Un - register the bundle listener releases resources |
21,960 | public final CommandRepository createCommandRepository ( ) { CommandRepository cr = new CommandRepository ( ) ; for ( Command c : commandSection . getAllCommands ( ) ) { CommandDefinition cd = new CommandDefinition ( c . getName ( ) , c . getPlugin ( ) ) ; cd . setArgs ( c . getCommandLine ( ) ) ; cr . addCommandDefinition ( cd ) ; } return cr ; } | Returns a command repository containing all the commands configured inside the configuration file . |
21,961 | private void init ( final String commandName , final String ... arguments ) { if ( arguments != null ) { if ( arguments . length == 1 ) { init ( commandName , arguments [ 0 ] ) ; return ; } String [ ] ary = new String [ arguments . length ] ; for ( int i = 0 ; i < arguments . length ; i ++ ) { if ( arguments [ i ] . indexOf ( '!' ) == - 1 ) { ary [ i ] = arguments [ i ] ; } else { ary [ i ] = "'" + arguments [ i ] + "'" ; } } init ( commandName , StringUtils . join ( ary , '!' ) ) ; } else { init ( commandName , ( String ) null ) ; } } | Initializes the object with the given command and the given arguments . |
21,962 | private void init ( final String commandName , final String argumentsString ) { String fullCommandString ; String tmpArgumentsString = argumentsString ; if ( tmpArgumentsString != null && ! tmpArgumentsString . isEmpty ( ) && tmpArgumentsString . charAt ( 0 ) == '!' ) { tmpArgumentsString = tmpArgumentsString . substring ( 1 ) ; } if ( ! StringUtils . isBlank ( tmpArgumentsString ) ) { fullCommandString = commandName + "!" + tmpArgumentsString ; } else { fullCommandString = commandName ; } this . packet . setType ( PacketType . QUERY ) ; this . packet . setBuffer ( fullCommandString ) ; } | Initializes the object with the given command and the given list of ! separated list of arguments . |
21,963 | public final String [ ] getArguments ( ) { String [ ] partsAry = split ( this . packet . getBufferAsString ( ) ) ; String [ ] argsAry = new String [ partsAry . length - 1 ] ; System . arraycopy ( partsAry , 1 , argsAry , 0 , argsAry . length ) ; return argsAry ; } | Returns the command arguments . |
21,964 | private String [ ] split ( final String sCommandLine ) { return it . jnrpe . utils . StringUtils . split ( sCommandLine , '!' , false ) ; } | Utility method that splits using the ! character and handling quoting by and . |
21,965 | private UserEntity ensureRolesFetched ( final UserEntity user ) { if ( user != null ) user . getRoles ( ) . stream ( ) . map ( r -> r . getId ( ) ) . collect ( Collectors . toList ( ) ) ; return user ; } | Make sure the roles have been fetched from the database |
21,966 | private UserLogin tryBasicAuthLogin ( UserLogin login , UserAuthenticationService authService , HttpServletRequest request ) { final String header = request . getHeader ( HttpHeaderNames . AUTHORIZATION ) ; if ( header != null ) { final String [ ] credentials = BasicAuthHelper . parseHeader ( header ) ; if ( credentials != null ) { final String username = credentials [ 0 ] ; final String password = credentials [ 1 ] ; final Future < UserEntity > future = asynchService . get ( ) . submit ( ( ) -> tryLogin ( authService , username , password , true ) ) ; try { UserEntity user = LOGIN_TIMEOUT . start ( ) . resolveFuture ( future , true ) ; login . reload ( user ) ; } catch ( Exception e ) { throw new RuntimeException ( "Error attempting asynchronous BASIC auth login: " + e . getMessage ( ) , e ) ; } } } return null ; } | Support proactive HTTP BASIC authentication |
21,967 | private void prune ( ) { if ( useSoftReferences ) { Iterator < Map . Entry < String , Object > > it = cache . entrySet ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { final Map . Entry < String , Object > entry = it . next ( ) ; if ( dereference ( entry . getValue ( ) ) == null ) it . remove ( ) ; } } } | Finds stale entries in the map |
21,968 | public final ThresholdsEvaluatorBuilder withLegacyThreshold ( final String metric , final String okRange , final String warnRange , final String critRange ) throws BadThresholdException { LegacyRange ok = null , warn = null , crit = null ; if ( okRange != null ) { ok = new LegacyRange ( okRange ) ; } if ( warnRange != null ) { warn = new LegacyRange ( warnRange ) ; } if ( critRange != null ) { crit = new LegacyRange ( critRange ) ; } thresholds . addThreshold ( new LegacyThreshold ( metric , ok , warn , crit ) ) ; return this ; } | This method allows to specify thresholds using the old format . |
21,969 | public static synchronized void register ( Class < ? > clazz ) { if ( clazz . isAnnotationPresent ( javax . ws . rs . ext . Provider . class ) ) { classes . add ( clazz ) ; revision ++ ; } else { throw new RuntimeException ( "Class " + clazz . getName ( ) + " is not annotated with javax.ws.rs.ext.Provider" ) ; } } | Register a provider class |
21,970 | private static PipedInputStream createInputStream ( final Jar jar ) throws IOException { final CloseAwarePipedInputStream pin = new CloseAwarePipedInputStream ( ) ; final PipedOutputStream pout = new PipedOutputStream ( pin ) ; new Thread ( ) { public void run ( ) { try { jar . write ( pout ) ; } catch ( Exception e ) { if ( pin . closed ) { LOG . debug ( "Bundle cannot be generated, pipe closed by reader" , e ) ; } else { LOG . warn ( "Bundle cannot be generated" , e ) ; } } finally { try { jar . close ( ) ; pout . close ( ) ; } catch ( IOException ignore ) { LOG . error ( "Bundle cannot be generated" , ignore ) ; } } } } . start ( ) ; return pin ; } | Creates an piped input stream for the wrapped jar . This is done in a thread so we can return quickly . |
21,971 | private static void checkMandatoryProperties ( final Analyzer analyzer , final Jar jar , final String symbolicName ) { final String importPackage = analyzer . getProperty ( Analyzer . IMPORT_PACKAGE ) ; if ( importPackage == null || importPackage . trim ( ) . length ( ) == 0 ) { analyzer . setProperty ( Analyzer . IMPORT_PACKAGE , "*;resolution:=optional" ) ; } final String exportPackage = analyzer . getProperty ( Analyzer . EXPORT_PACKAGE ) ; if ( exportPackage == null || exportPackage . trim ( ) . length ( ) == 0 ) { analyzer . setProperty ( Analyzer . EXPORT_PACKAGE , "*" ) ; } final String localSymbolicName = analyzer . getProperty ( Analyzer . BUNDLE_SYMBOLICNAME , symbolicName ) ; analyzer . setProperty ( Analyzer . BUNDLE_SYMBOLICNAME , generateSymbolicName ( localSymbolicName ) ) ; } | Check if manadatory properties are present otherwise generate default . |
21,972 | public static Properties parseInstructions ( final String query ) throws MalformedURLException { final Properties instructions = new Properties ( ) ; if ( query != null ) { try { final String segments [ ] = query . split ( "&" ) ; for ( String segment : segments ) { if ( segment . trim ( ) . length ( ) > 0 ) { final Matcher matcher = INSTRUCTIONS_PATTERN . matcher ( segment ) ; if ( matcher . matches ( ) ) { String key = matcher . group ( 1 ) ; String val = matcher . group ( 2 ) ; instructions . setProperty ( verifyKey ( key ) , val != null ? URLDecoder . decode ( val , "UTF-8" ) : "" ) ; } else { throw new MalformedURLException ( "Invalid syntax for instruction [" + segment + "]. Take a look at http://www.aqute.biz/Code/Bnd." ) ; } } } } catch ( UnsupportedEncodingException e ) { throwAsMalformedURLException ( "Could not retrieve the instructions from [" + query + "]" , e ) ; } } return instructions ; } | Parses bnd instructions out of an url query string . |
21,973 | private static void throwAsMalformedURLException ( final String message , final Exception cause ) throws MalformedURLException { final MalformedURLException exception = new MalformedURLException ( message ) ; exception . initCause ( cause ) ; throw exception ; } | Creates an MalformedURLException with a message and a cause . |
21,974 | private void validateHibernateProperties ( final GuiceConfig configuration , final Properties hibernateProperties ) { final boolean allowCreateSchema = configuration . getBoolean ( GuiceProperties . HIBERNATE_ALLOW_HBM2DDL_CREATE , false ) ; if ( ! allowCreateSchema ) { final String hbm2ddl = hibernateProperties . getProperty ( "hibernate.hbm2ddl.auto" ) ; if ( hbm2ddl != null && ( hbm2ddl . equalsIgnoreCase ( "create" ) || hbm2ddl . equalsIgnoreCase ( "create-drop" ) ) ) { throw new IllegalArgumentException ( "Value '" + hbm2ddl + "' is not permitted for hibernate property 'hibernate.hbm2ddl.auto' under the current configuration, consider using 'update' instead. If you must use the value 'create' then set configuration parameter '" + GuiceProperties . HIBERNATE_ALLOW_HBM2DDL_CREATE + "' to 'true'" ) ; } } } | Checks whether hbm2ddl is set to a prohibited value throwing an exception if it is |
21,975 | public static ReturnValueBuilder forPlugin ( final String name , final ThresholdsEvaluator thr ) { if ( thr != null ) { return new ReturnValueBuilder ( name , thr ) ; } return new ReturnValueBuilder ( name , new ThresholdsEvaluatorBuilder ( ) . create ( ) ) ; } | Constructs the object with the given threshold evaluator . |
21,976 | private void formatResultMessage ( final Metric pluginMetric ) { if ( StringUtils . isEmpty ( pluginMetric . getMessage ( ) ) ) { return ; } if ( StringUtils . isEmpty ( retValMessage ) ) { retValMessage = pluginMetric . getMessage ( ) ; return ; } retValMessage += " " + pluginMetric . getMessage ( ) ; } | Formats the message to return to Nagios according to the specifications contained inside the pluginMetric object . |
21,977 | public static String getLocalhost ( ) throws RuntimeException { String hostname = null ; try { InetAddress addr = InetAddress . getLocalHost ( ) ; hostname = addr . getHostName ( ) ; } catch ( UnknownHostException e ) { throw new RuntimeException ( "[FileHelper] {getLocalhost}: Can't get local hostname" ) ; } return hostname ; } | Gets the hostname of localhost |
21,978 | public static String getLocalIp ( ) throws RuntimeException { try { InetAddress addr = getLocalIpAddress ( ) ; return addr . getHostAddress ( ) ; } catch ( RuntimeException e ) { throw new RuntimeException ( "[FileHelper] {getLocalIp}: Unable to find the local machine" , e ) ; } } | Gets the local IP address |
21,979 | public static InetAddress getLocalIpAddress ( ) throws RuntimeException { try { List < InetAddress > ips = getLocalIpAddresses ( false , true ) ; for ( InetAddress ip : ips ) { log . debug ( "[IpHelper] {getLocalIpAddress} Considering locality of " + ip . getHostAddress ( ) ) ; if ( ! ip . isAnyLocalAddress ( ) && ( ip instanceof Inet4Address ) ) { if ( ! ip . getHostAddress ( ) . startsWith ( "127.0." ) ) { log . debug ( "[IpHelper] {getLocalIpAddress} Found nonloopback IP: " + ip . getHostAddress ( ) ) ; return ip ; } } } log . trace ( "[IpHelper] {getLocalIpAddress} Couldn't find a public IP in the ip (size " + ips . size ( ) + ")" ) ; return InetAddress . getLocalHost ( ) ; } catch ( UnknownHostException e ) { throw new RuntimeException ( "[FileHelper] {getLocalIp}: Unable to acquire the current machine's InetAddress" , e ) ; } } | Returns the primary InetAddress of localhost |
21,980 | public static InetAddress getLocalIpAddress ( String iface ) throws RuntimeException { try { NetworkInterface nic = NetworkInterface . getByName ( iface ) ; Enumeration < InetAddress > ips = nic . getInetAddresses ( ) ; InetAddress firstIP = null ; while ( ips != null && ips . hasMoreElements ( ) ) { InetAddress ip = ips . nextElement ( ) ; if ( firstIP == null ) firstIP = ip ; if ( log . isDebugEnabled ( ) ) log . debug ( "[IpHelper] {getLocalIpAddress} Considering locality: " + ip . getHostAddress ( ) ) ; if ( ! ip . isAnyLocalAddress ( ) ) { return ip ; } } return firstIP ; } catch ( SocketException e ) { throw new RuntimeException ( "[IpHelper] {getLocalIpAddress}: Unable to acquire an IP" , e ) ; } } | Returns the IP address associated with iface |
21,981 | public static List < InetAddress > getLocalIpAddresses ( boolean pruneSiteLocal , boolean pruneDown ) throws RuntimeException { try { Enumeration < NetworkInterface > nics = NetworkInterface . getNetworkInterfaces ( ) ; List < InetAddress > addresses = new Vector < InetAddress > ( ) ; while ( nics . hasMoreElements ( ) ) { NetworkInterface iface = nics . nextElement ( ) ; Enumeration < InetAddress > addrs = iface . getInetAddresses ( ) ; if ( ! pruneDown || iface . isUp ( ) ) { while ( addrs . hasMoreElements ( ) ) { InetAddress addr = addrs . nextElement ( ) ; if ( ! addr . isLoopbackAddress ( ) && ! addr . isLinkLocalAddress ( ) ) { if ( ! pruneSiteLocal || ( pruneSiteLocal && ! addr . isSiteLocalAddress ( ) ) ) { addresses . add ( addr ) ; } } } } } return addresses ; } catch ( SocketException e ) { throw new RuntimeException ( e . getMessage ( ) , e ) ; } } | Returns a list of local InetAddresses for this machine |
21,982 | public static String getMacFor ( NetworkInterface iface ) throws SocketException , NoMacAddressException { assert ( iface != null ) ; byte [ ] hwaddr = iface . getHardwareAddress ( ) ; if ( hwaddr == null || hwaddr . length == 0 ) { throw new NoMacAddressException ( "Interface " + iface . getName ( ) + " has no physical address specified." ) ; } else { return physicalAddressToString ( hwaddr ) ; } } | Given a network interface determines its mac address |
21,983 | public static NetworkInterface getInterfaceForLocalIp ( InetAddress addr ) throws SocketException , NoInterfaceException { assert ( getLocalIpAddresses ( false ) . contains ( addr ) ) : "IP is not local" ; NetworkInterface iface = NetworkInterface . getByInetAddress ( addr ) ; if ( iface != null ) return iface ; else throw new NoInterfaceException ( "No network interface for IP: " + addr . toString ( ) ) ; } | Given a local IP address returns the Interface it corresponds to |
21,984 | public static InetAddress ntoa ( final int address ) { try { final byte [ ] addr = new byte [ 4 ] ; addr [ 0 ] = ( byte ) ( ( address >>> 24 ) & 0xFF ) ; addr [ 1 ] = ( byte ) ( ( address >>> 16 ) & 0xFF ) ; addr [ 2 ] = ( byte ) ( ( address >>> 8 ) & 0xFF ) ; addr [ 3 ] = ( byte ) ( address & 0xFF ) ; return InetAddress . getByAddress ( addr ) ; } catch ( UnknownHostException e ) { throw new Error ( e ) ; } } | Converts numeric address to an InetAddress |
21,985 | public static boolean isPubliclyRoutable ( final InetAddress addrIP ) { if ( addrIP == null ) throw new NullPointerException ( "isPubliclyRoutable requires an IP address be passed to it!" ) ; return ! addrIP . isSiteLocalAddress ( ) && ! addrIP . isLinkLocalAddress ( ) && ! addrIP . isLoopbackAddress ( ) ; } | Determines whether a particular IP address is publicly routable on the internet |
21,986 | public WebQuery buildQuery ( ) { Map < String , List < String > > map = new HashMap < > ( constraints ) ; applyDefault ( WQUriControlField . FETCH , map , defaultFetch ) ; applyDefault ( WQUriControlField . EXPAND , map , defaultExpand ) ; applyDefault ( WQUriControlField . ORDER , map , defaultOrder ) ; applyDefault ( WQUriControlField . OFFSET , map , "0" ) ; applyDefault ( WQUriControlField . LIMIT , map , Integer . toString ( defaultLimit ) ) ; return new WebQuery ( ) . decode ( map ) ; } | Construct a WebQueryDefinition from this applying the web query semantics |
21,987 | private void configurePlugins ( final File fDir ) throws PluginConfigurationException { LOG . trace ( "READING PLUGIN CONFIGURATION FROM DIRECTORY {}" , fDir . getName ( ) ) ; StreamManager streamMgr = new StreamManager ( ) ; File [ ] vfJars = fDir . listFiles ( JAR_FILE_FILTER ) ; if ( vfJars == null || vfJars . length == 0 ) { return ; } List < URL > vUrls = new ArrayList < URL > ( vfJars . length ) ; ClassLoader ul = null ; for ( int j = 0 ; j < vfJars . length ; j ++ ) { try { vUrls . add ( vfJars [ j ] . toURI ( ) . toURL ( ) ) ; } catch ( MalformedURLException e ) { throw new IllegalStateException ( e . getMessage ( ) , e ) ; } } ul = new JNRPEClassLoader ( vUrls ) ; try { for ( File file : vfJars ) { JarFile jarFile = null ; try { jarFile = new JarFile ( file ) ; JarEntry entry = jarFile . getJarEntry ( "plugin.xml" ) ; if ( entry == null ) { entry = jarFile . getJarEntry ( "jnrpe_plugins.xml" ) ; } if ( entry == null ) { continue ; } InputStream in = streamMgr . handle ( jarFile . getInputStream ( entry ) ) ; PluginRepositoryUtil . loadFromXmlPluginPackageDefinitions ( this , ul , in ) ; in . close ( ) ; } catch ( Exception e ) { LOG . error ( "Skipping plugin package contained in file '{}' because of the following error : {}" , new String [ ] { file . getName ( ) , e . getMessage ( ) } , e ) ; } finally { try { jarFile . close ( ) ; } catch ( Exception e ) { LOG . warn ( "An error has occurred closing jar file '{}'" , file . getName ( ) , e ) ; } } } } finally { streamMgr . closeAll ( ) ; } } | Loads all the plugins definitions from the given directory . |
21,988 | public final void load ( final File fDirectory ) throws PluginConfigurationException { File [ ] vFiles = fDirectory . listFiles ( ) ; if ( vFiles != null ) { for ( File f : vFiles ) { if ( f . isDirectory ( ) ) { configurePlugins ( f ) ; } } } } | Loops through all the directories present inside the JNRPE plugin directory . |
21,989 | public static Session getSession ( final ICommandLine cl ) throws Exception { JSch jsch = new JSch ( ) ; Session session = null ; int timeout = DEFAULT_TIMEOUT ; int port = cl . hasOption ( "port" ) ? Integer . parseInt ( cl . getOptionValue ( "port" ) ) : + DEFAULT_PORT ; String hostname = cl . getOptionValue ( "hostname" ) ; String username = cl . getOptionValue ( "username" ) ; String password = cl . getOptionValue ( "password" ) ; String key = cl . getOptionValue ( "key" ) ; if ( cl . hasOption ( "timeout" ) ) { try { timeout = Integer . parseInt ( cl . getOptionValue ( "timeout" ) ) ; } catch ( NumberFormatException e ) { throw new MetricGatheringException ( "Invalid numeric value for timeout." , Status . CRITICAL , e ) ; } } session = jsch . getSession ( username , hostname , port ) ; if ( key == null ) { session . setConfig ( "StrictHostKeyChecking" , "no" ) ; session . setPassword ( password ) ; } else { jsch . addIdentity ( key ) ; } session . connect ( timeout * 1000 ) ; return session ; } | Starts an ssh session |
21,990 | public Timeout getTimeoutLeft ( ) { final long left = getTimeLeft ( ) ; if ( left != 0 ) return new Timeout ( left , TimeUnit . MILLISECONDS ) ; else return Timeout . ZERO ; } | Determines the amount of time leftuntil the deadline and returns it as a timeout |
21,991 | public static Deadline soonest ( Deadline ... deadlines ) { Deadline min = null ; if ( deadlines != null ) for ( Deadline deadline : deadlines ) { if ( deadline != null ) { if ( min == null ) min = deadline ; else if ( deadline . getTimeLeft ( ) < min . getTimeLeft ( ) ) { min = deadline ; } } } return min ; } | Retrieve the deadline with the least time remaining until it expires |
21,992 | public RestFailure renderFailure ( Throwable e ) { if ( e . getCause ( ) != null && ( e instanceof ApplicationException ) ) { return renderFailure ( e . getCause ( ) ) ; } RestFailure failure = new RestFailure ( ) ; failure . id = getOrGenerateFailureId ( ) ; failure . date = new Date ( ) ; if ( e instanceof RestException ) { RestException re = ( RestException ) e ; failure . httpCode = re . getHttpCode ( ) ; failure . exception = renderThrowable ( e ) ; } else { failure . httpCode = 500 ; failure . exception = renderThrowable ( e ) ; } return failure ; } | Render a Throwable as a RestFailure |
21,993 | public HibernateTransaction start ( ) { final Session session = sessionProvider . get ( ) ; final Transaction tx = session . beginTransaction ( ) ; return new HibernateTransaction ( tx ) ; } | Starts a new Hibernate transaction . Note that the caller accepts responsibility for closing the transaction |
21,994 | public void execute ( Runnable statements ) { try ( HibernateTransaction tx = start ( ) . withAutoRollback ( ) ) { statements . run ( ) ; tx . commit ( ) ; } } | Execute the provided Runnable within a transaction committing if no exceptions are thrown |
21,995 | public void addCommitAction ( final Runnable action ) throws HibernateException { if ( action == null ) return ; addAction ( new BaseSessionEventListener ( ) { public void transactionCompletion ( final boolean successful ) { if ( successful ) action . run ( ) ; } } ) ; } | Register an action to run on the successful commit of the transaction |
21,996 | public void deleteOnRollback ( final Collection < File > files ) { addRollbackAction ( new Runnable ( ) { public void run ( ) { for ( File file : files ) { if ( log . isTraceEnabled ( ) ) log . trace ( "Delete file on transaction rollback: " + file ) ; final boolean success = FileUtils . deleteQuietly ( file ) ; if ( ! success ) log . warn ( "Failed to delete file on transaction rollback: " + file ) ; } } } ) ; } | Adds an action to the transaction to delete a set of files once rollback completes |
21,997 | public Object newInstanceWithId ( final Object id ) { try { final Object o = clazz . newInstance ( ) ; idProperty . set ( o , id ) ; return o ; } catch ( Throwable e ) { throw new RuntimeException ( "Cannot create new instance of " + clazz + " with ID " + id + " (of type " + id . getClass ( ) + ") populated!" , e ) ; } } | Create a new instance of this entity setting only the ID field |
21,998 | public EntityGraph getDefaultGraph ( final Session session ) { if ( this . defaultExpandGraph == null ) { final EntityGraph < ? > graph = session . createEntityGraph ( clazz ) ; populateGraph ( graph , getEagerFetch ( ) ) ; this . defaultExpandGraph = graph ; return graph ; } else { return this . defaultExpandGraph ; } } | Build or return the default Entity Graph that represents defaultExpand |
21,999 | private void populateGraph ( final EntityGraph < ? > graph , final Set < String > fetches ) { Map < String , Subgraph < ? > > created = new HashMap < > ( ) ; for ( String fetch : fetches ) { final String [ ] parts = StringUtils . split ( fetch , '.' ) ; Subgraph < ? > parent = null ; for ( int i = 0 ; i < parts . length ; i ++ ) { final String path = StringUtils . join ( parts , '.' , 0 , i + 1 ) ; final boolean isLeaf = ( i == parts . length - 1 ) ; final Subgraph < ? > existing = created . get ( path ) ; if ( existing == null ) { if ( parent == null ) { try { graph . addAttributeNodes ( parts [ i ] ) ; if ( ! isLeaf ) parent = graph . addSubgraph ( parts [ i ] ) ; } catch ( IllegalArgumentException e ) { throw new IllegalArgumentException ( "Error adding graph member " + parts [ i ] + " with isLeaf=" + isLeaf + " to root as part of " + fetch , e ) ; } } else { try { parent . addAttributeNodes ( parts [ i ] ) ; if ( ! isLeaf ) parent = parent . addSubgraph ( parts [ i ] ) ; } catch ( IllegalArgumentException e ) { throw new IllegalArgumentException ( "Error adding graph member " + parts [ i ] + " with isLeaf=" + isLeaf + " as part of " + fetch + " with parent.class=" + parent . getClassType ( ) , e ) ; } } if ( ! isLeaf ) created . put ( path , parent ) ; } else { parent = existing ; } } } } | Creates an EntityGraph representing the |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.