idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
21,900 | public static boolean addFilesToExistingJar ( File jarFile , String basePathWithinJar , Map < String , File > files , ActionOnConflict action ) throws IOException { // get a temp file 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 : // This should never happen with validation of action taking place in WarDriver class 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 | 305 | 13 |
21,901 | 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 | 56 | 8 |
21,902 | 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 | 109 | 11 |
21,903 | 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 | 52 | 14 |
21,904 | 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 | 86 | 6 |
21,905 | 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 | 69 | 12 |
21,906 | 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 | 67 | 12 |
21,907 | private ThymeleafTemplater getOrCreateTemplater ( ) { ThymeleafTemplater templater = this . templater . get ( ) ; // Lazy-create a ThymeleafTemplater 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 | 197 | 11 |
21,908 | 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 | 84 | 15 |
21,909 | 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 ( ' ' ) ; break ; case bytes : res . append ( ' ' ) ; 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 ( ' ' ) ; 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 . | 423 | 20 |
21,910 | private String quote ( final String lbl ) { if ( lbl . indexOf ( ' ' ) == - 1 ) { return lbl ; } return new StringBuffer ( "'" ) . append ( lbl ) . append ( ' ' ) . toString ( ) ; } | Quotes the label if required . | 58 | 6 |
21,911 | 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 ) { // Ignore return "error generating schema for " + clazz + ": " + e . getMessage ( ) ; } } else if ( clazz . isAnnotationPresent ( XmlType . class ) || clazz . isAnnotationPresent ( XmlEnum . class ) ) { // Class generated by JAXB XSD To Java (as a result we have to emit the entire schema rather than being able to provide a specific sub-schema for the type in question because XmlRootElement is not specified) try { final JAXBSerialiser serialiser = JAXBSerialiser . getMoxy ( clazz . getPackage ( ) . getName ( ) ) ; return generate ( serialiser ) ; } catch ( Exception e ) { // Ignore 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 | 520 | 8 |
21,912 | public MetricBuilder withValue ( Number value , String prettyPrintFormat ) { current = new MetricValue ( value . toString ( ) , prettyPrintFormat ) ; return this ; } | Sets the value of the metric to be built . | 39 | 11 |
21,913 | 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 . | 40 | 12 |
21,914 | 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 . | 40 | 12 |
21,915 | public MetricBuilder withMessage ( String messagePattern , Object ... params ) { this . metricMessage = MessageFormat . format ( messagePattern , params ) ; return this ; } | Sets the message to be associated with this metric . | 36 | 11 |
21,916 | @ Deprecated public ResultSetConstraint build ( Map < String , List < String > > constraints ) { return builder ( constraints ) . build ( ) ; } | Convenience method to build based on a Map of constraints quickly | 34 | 13 |
21,917 | @ Inject @ 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 ( ) ) ; // Guice sets a Class<? super T> but we know we can cast to Class<T> by convention this . clazz = ( Class < T > ) clazz . getRawType ( ) ; isLargeTable = this . clazz . isAnnotationPresent ( LargeTable . class ) ; } | Called by guice to provide the Class associated with T | 198 | 12 |
21,918 | public Collection < ID > getIds ( final WebQuery constraints ) { return ( Collection < ID > ) find ( constraints , JPASearchStrategy . ID ) . getList ( ) ; } | Get a list of IDs matching a WebQuery | 41 | 9 |
21,919 | private SSLEngine getSSLEngine ( ) throws KeyStoreException , CertificateException , IOException , UnrecoverableKeyException , KeyManagementException { // Open the KeyStore Stream 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 . | 297 | 10 |
21,920 | 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 > ( ) { @ Override 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 . | 343 | 13 |
21,921 | public SampleCount resample ( Timebase newRate ) { if ( ! this . rate . equals ( newRate ) ) { final long newSamples = getSamples ( newRate ) ; return new SampleCount ( newSamples , newRate ) ; } else { // Same rate, no need to resample return this ; } } | Resample this sample count to another rate | 70 | 8 |
21,922 | @ Override protected void onStart ( ) { m_mappings = new HashMap < Bundle , List < T > > ( ) ; // listen to bundles events 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 ; } } } ) ; // scan already started bundles 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 . | 191 | 13 |
21,923 | @ Override 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 | 99 | 8 |
21,924 | 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 . | 91 | 14 |
21,925 | 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 ] + "'" ; } } // sCommandBytes = StringUtils.join(ary, '!'); init ( commandName , StringUtils . join ( ary , ' ' ) ) ; } else { init ( commandName , ( String ) null ) ; } } | Initializes the object with the given command and the given arguments . | 178 | 13 |
21,926 | 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 ) ; // updateCRC(); } | Initializes the object with the given command and the given list of ! separated list of arguments . | 158 | 19 |
21,927 | public final String [ ] getArguments ( ) { // extracting params 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 . | 84 | 5 |
21,928 | 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 . | 40 | 15 |
21,929 | 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 | 61 | 11 |
21,930 | 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 ) ; } } } // No authorisation (or unsupported authorisation type) return null ; } | Support proactive HTTP BASIC authentication | 212 | 6 |
21,931 | 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 | 90 | 7 |
21,932 | 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 . | 137 | 11 |
21,933 | 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 | 94 | 4 |
21,934 | 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 ) { // logging the message at DEBUG logging instead // -- reading thread probably stopped reading 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 ) { // if we get here something is very wrong 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 . | 208 | 24 |
21,935 | 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 . | 227 | 12 |
21,936 | public static Properties parseInstructions ( final String query ) throws MalformedURLException { final Properties instructions = new Properties ( ) ; if ( query != null ) { try { // just ignore for the moment and try out if we have valid properties separated by "&" final String segments [ ] = query . split ( "&" ) ; for ( String segment : segments ) { // do not parse empty strings 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 ) { // thrown by URLDecoder but it should never happen throwAsMalformedURLException ( "Could not retrieve the instructions from [" + query + "]" , e ) ; } } return instructions ; } | Parses bnd instructions out of an url query string . | 285 | 13 |
21,937 | 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 . | 60 | 16 |
21,938 | private void validateHibernateProperties ( final GuiceConfig configuration , final Properties hibernateProperties ) { final boolean allowCreateSchema = configuration . getBoolean ( GuiceProperties . HIBERNATE_ALLOW_HBM2DDL_CREATE , false ) ; if ( ! allowCreateSchema ) { // Check that hbm2ddl is not set to a prohibited value, throwing an exception if it is 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 | 275 | 20 |
21,939 | 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 . | 68 | 12 |
21,940 | 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 . | 85 | 21 |
21,941 | 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 | 84 | 8 |
21,942 | 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 | 73 | 6 |
21,943 | 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 ) ) { // Ubuntu sets the unix hostname to resolve to 127.0.1.1; this is annoying so treat it as a loopback 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 | 286 | 9 |
21,944 | 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 the first IP (or null if no IPs were returned) return firstIP ; } catch ( SocketException e ) { throw new RuntimeException ( "[IpHelper] {getLocalIpAddress}: Unable to acquire an IP" , e ) ; } } | Returns the IP address associated with iface | 222 | 8 |
21,945 | 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 | 249 | 12 |
21,946 | 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 | 106 | 8 |
21,947 | 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 | 102 | 11 |
21,948 | 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 ) { // will never be thrown throw new Error ( e ) ; } } | Converts numeric address to an InetAddress | 139 | 9 |
21,949 | 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 | 85 | 15 |
21,950 | 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 | 141 | 12 |
21,951 | 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 ; } // Initializing classloader 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 ) { // should never happen 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 ) { // The jar do not contain a jnrpe_plugins.xml nor a // plugin.xml file... 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 ) { // Intentionally ignored... LOG . warn ( "An error has occurred closing jar file '{}'" , file . getName ( ) , e ) ; } } } } finally { streamMgr . closeAll ( ) ; } } | Loads all the plugins definitions from the given directory . | 514 | 11 |
21,952 | 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 . | 67 | 15 |
21,953 | 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 | 281 | 5 |
21,954 | 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 | 51 | 17 |
21,955 | 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 | 78 | 12 |
21,956 | public RestFailure renderFailure ( Throwable e ) { // Strip away ApplicationException wrappers 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 ; // by default failure . exception = renderThrowable ( e ) ; } return failure ; } | Render a Throwable as a RestFailure | 155 | 8 |
21,957 | 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 | 44 | 20 |
21,958 | public void execute ( Runnable statements ) { try ( HibernateTransaction tx = start ( ) . withAutoRollback ( ) ) { statements . run ( ) ; // Success, perform a TX commit tx . commit ( ) ; } } | Execute the provided Runnable within a transaction committing if no exceptions are thrown | 52 | 16 |
21,959 | public void addCommitAction ( final Runnable action ) throws HibernateException { if ( action == null ) return ; // ignore null actions addAction ( new BaseSessionEventListener ( ) { @ Override public void transactionCompletion ( final boolean successful ) { if ( successful ) action . run ( ) ; } } ) ; } | Register an action to run on the successful commit of the transaction | 72 | 12 |
21,960 | public void deleteOnRollback ( final Collection < File > files ) { addRollbackAction ( new Runnable ( ) { @ Override 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 | 119 | 16 |
21,961 | 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 | 94 | 12 |
21,962 | 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 | 81 | 12 |
21,963 | 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 , ' ' ) ; // Starts of null (meaning parent is the root graph), updated as we go through path segments to refer to the last path segment Subgraph < ? > parent = null ; // Iterate over the path segments, adding attributes subgraphs 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 { // Relation under root graph . addAttributeNodes ( parts [ i ] ) ; // Only set up a subgraph if this is not a leaf node // This prevents us trying to add a Subgraph for a List of Embeddable 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 { // Relation under parent parent . addAttributeNodes ( parts [ i ] ) ; // Only set up a subgraph if this is not a leaf node // This prevents us trying to add a Subgraph for a List of Embeddable 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 { // Already seen this graph node before parent = existing ; } } } } | Creates an EntityGraph representing the | 504 | 7 |
21,964 | @ Subscribe public final void receive ( final LogEvent logEvent ) { final String sClassName = logEvent . getSource ( ) . getClass ( ) . getName ( ) ; Logger logger = loggersMap . get ( sClassName ) ; if ( logger == null ) { logger = LoggerFactory . getLogger ( logEvent . getSource ( ) . getClass ( ) ) ; loggersMap . put ( sClassName , logger ) ; } final Throwable error = logEvent . getCause ( ) ; switch ( logEvent . getLogType ( ) ) { case TRACE : logger . trace ( logEvent . getMessage ( ) , error ) ; break ; case DEBUG : logger . debug ( logEvent . getMessage ( ) , error ) ; break ; case INFO : logger . info ( logEvent . getMessage ( ) , error ) ; break ; case WARNING : logger . warn ( logEvent . getMessage ( ) , error ) ; break ; case ERROR : logger . error ( logEvent . getMessage ( ) , error ) ; break ; case FATAL : logger . error ( logEvent . getMessage ( ) , error ) ; break ; } } | This method receives the log event and logs it . | 247 | 10 |
21,965 | public static InputStream routeStreamThroughProcess ( final Process p , final InputStream origin , final boolean closeInput ) { InputStream processSTDOUT = p . getInputStream ( ) ; OutputStream processSTDIN = p . getOutputStream ( ) ; // Kick off a background copy to the process StreamUtil . doBackgroundCopy ( origin , processSTDIN , DUMMY_MONITOR , true , closeInput ) ; return processSTDOUT ; } | Given a Process this function will route the flow of data through it & out again | 93 | 16 |
21,966 | public static long eatInputStream ( InputStream is ) { try { long eaten = 0 ; try { Thread . sleep ( STREAM_SLEEP_TIME ) ; } catch ( InterruptedException e ) { // ignore } int avail = Math . min ( is . available ( ) , CHUNKSIZE ) ; byte [ ] eatingArray = new byte [ CHUNKSIZE ] ; while ( avail > 0 ) { is . read ( eatingArray , 0 , avail ) ; eaten += avail ; if ( avail < CHUNKSIZE ) { // If the buffer wasn't full, wait a short amount of time to let it fill up if ( STREAM_SLEEP_TIME != 0 ) try { Thread . sleep ( STREAM_SLEEP_TIME ) ; } catch ( InterruptedException e ) { // ignore } } avail = Math . min ( is . available ( ) , CHUNKSIZE ) ; } return eaten ; } catch ( IOException e ) { log . error ( e . getMessage ( ) , e ) ; return - 1 ; } } | Eats an inputstream discarding its contents | 225 | 9 |
21,967 | public static void streamCopy ( InputStream input , Writer output ) throws IOException { if ( input == null ) throw new IllegalArgumentException ( "Must provide something to read from" ) ; if ( output == null ) throw new IllegalArgumentException ( "Must provide something to write to" ) ; streamCopy ( new InputStreamReader ( input ) , output ) ; } | Copies the contents of an InputStream using the default encoding into a Writer | 78 | 15 |
21,968 | private void recache ( ) { // If we've already cached the values then don't bother recalculating; we // assume a mask of 0 means a recompute is needed (unless prefix is also 0) // We skip the computation completely is prefix is 0 - this is fine, since // the mask and maskedNetwork for prefix 0 result in 0, the default values. // We need to special-case /0 because our mask generation code doesn't work for // prefix=0 (since -1 << 32 != 0) if ( mask == 0 && prefix != 0 ) { this . mask = - 1 << ( 32 - prefix ) ; this . maskedNetwork = IpHelper . aton ( network ) & mask ; } } | Repopulates the transient fields based on the IP and prefix | 150 | 12 |
21,969 | public long get ( final TimeUnit toUnit ) { if ( this . unit == toUnit ) return period ; else return toUnit . convert ( period , this . unit ) ; } | Get this timeout represented in a different unit | 38 | 8 |
21,970 | public static Timeout max ( Timeout ... timeouts ) { Timeout max = null ; for ( Timeout timeout : timeouts ) { if ( timeout != null ) if ( max == null || max . getMilliseconds ( ) < timeout . getMilliseconds ( ) ) max = timeout ; } if ( max != null ) return max ; else throw new IllegalArgumentException ( "Must specify at least one non-null timeout!" ) ; } | Filter through a number of timeouts to find the one with the longest period | 95 | 15 |
21,971 | public static Timeout min ( Timeout ... timeouts ) { Timeout min = null ; for ( Timeout timeout : timeouts ) { if ( timeout != null ) if ( min == null || min . getMilliseconds ( ) > timeout . getMilliseconds ( ) ) min = timeout ; } if ( min != null ) return min ; else throw new IllegalArgumentException ( "Must specify at least one non-null timeout!" ) ; } | Filter through a number of timeouts to find the one with the shortest period | 95 | 15 |
21,972 | public static Timeout sum ( Timeout ... timeouts ) { long sum = 0 ; for ( Timeout timeout : timeouts ) if ( timeout != null ) sum += timeout . getMilliseconds ( ) ; if ( sum != 0 ) return new Timeout ( sum ) ; else return Timeout . ZERO ; } | Adds together all the supplied timeouts | 67 | 7 |
21,973 | public synchronized static boolean hasSudo ( ) { if ( ! sudoTested ) { String [ ] cmdArr = new String [ ] { "which" , "sudo" } ; List < String > cmd = new ArrayList < String > ( cmdArr . length ) ; Collections . addAll ( cmd , cmdArr ) ; ProcessBuilder whichsudo = new ProcessBuilder ( cmd ) ; try { Process p = whichsudo . start ( ) ; try { Execed e = new Execed ( cmd , p , false ) ; // Let it run int returnCode = e . waitForExit ( new Deadline ( 3 , TimeUnit . SECONDS ) ) ; sudoSupported = ( returnCode == 0 ) ; sudoTested = true ; } finally { p . destroy ( ) ; } } catch ( Throwable t ) { sudoSupported = false ; sudoTested = true ; } } return sudoSupported ; } | Determines whether sudo is supported on the local machine | 192 | 11 |
21,974 | @ Override public final void channelRead ( final ChannelHandlerContext ctx , final Object msg ) { try { JNRPERequest req = ( JNRPERequest ) msg ; ReturnValue ret = commandInvoker . invoke ( req . getCommand ( ) , req . getArguments ( ) ) ; JNRPEResponse res = new JNRPEResponse ( ) ; res . setResult ( ret . getStatus ( ) . intValue ( ) , ret . getMessage ( ) ) ; ChannelFuture channelFuture = ctx . writeAndFlush ( res ) ; channelFuture . addListener ( ChannelFutureListener . CLOSE ) ; } catch ( RuntimeException re ) { re . printStackTrace ( ) ; } finally { ReferenceCountUtil . release ( msg ) ; } } | Method channelRead . | 168 | 4 |
21,975 | private static void applyConfigs ( final ClassLoader classloader , final GuiceConfig config ) { // Load all the local configs for ( String configFile : getPropertyFiles ( config ) ) { try { for ( PropertyFile properties : loadConfig ( classloader , configFile ) ) config . setAll ( properties ) ; } catch ( IOException e ) { throw new IllegalArgumentException ( "Error loading configuration URLs from " + configFile , e ) ; } } // Load the network config (if enabled) try { applyNetworkConfiguration ( config ) ; } catch ( Throwable t ) { throw new RuntimeException ( "Failed to retrieve configuration from network!" , t ) ; } } | Discover and add to the configuration any properties on disk and on the network | 144 | 14 |
21,976 | @ Override public String parse ( final String threshold , final RangeConfig tc ) { configure ( tc ) ; return threshold . substring ( 1 ) ; } | Parses the threshold to remove the matched braket . | 32 | 12 |
21,977 | public String getOptionValue ( final String optionName ) { if ( optionName . length ( ) == 1 ) { return getOptionValue ( optionName . charAt ( 0 ) ) ; } return ( String ) commandLine . getValue ( "--" + optionName ) ; } | Returns the value of the specified option . | 59 | 8 |
21,978 | public String getOptionValue ( final char shortOption , final String defaultValue ) { return ( String ) commandLine . getValue ( "-" + shortOption , defaultValue ) ; } | Returns the value of the specified option If the option is not present returns the default value . | 38 | 18 |
21,979 | public TimecodeRange add ( SampleCount samples ) { final Timecode newStart = start . add ( samples ) ; final Timecode newEnd = end . add ( samples ) ; return new TimecodeRange ( newStart , newEnd ) ; } | Move the range right by the specified number of samples | 51 | 10 |
21,980 | public synchronized void opportunisticallyRefreshUserData ( final String username , final String password ) { if ( shouldOpportunisticallyRefreshUserData ( ) ) { this . lastOpportunisticUserDataRefresh = System . currentTimeMillis ( ) ; Thread thread = new Thread ( ( ) -> refreshAllUserData ( ldap . parseUser ( username ) , password , true ) ) ; thread . setDaemon ( true ) ; thread . setName ( "UserManager_OpportunisticRefresh" ) ; thread . start ( ) ; } } | Temporarily borrow a user s credentials to run an opportunistic user data refresh | 117 | 16 |
21,981 | public String relative ( String url ) { try { final URI uri = absolute ( url ) . build ( ) ; return new URI ( null , null , uri . getPath ( ) , uri . getQuery ( ) , uri . getFragment ( ) ) . toString ( ) ; } catch ( URISyntaxException e ) { throw new IllegalArgumentException ( e ) ; } } | Return only the path for a given URL | 86 | 8 |
21,982 | void reload ( NetworkConfig config ) { try { log . trace ( "Load config data from " + config . path + " into " + config ) ; final ConfigPropertyData read = configService . read ( config . path , configInstanceId , config . getLastRevision ( ) ) ; // Abort if the server returns no config - we have the latest revision if ( read == null || read . properties == null || read . properties . isEmpty ( ) ) return ; for ( ConfigPropertyValue property : read . properties ) { config . properties . set ( property . getName ( ) , property . getValue ( ) ) ; } config . setLastRevision ( read . revision ) ; } catch ( Throwable t ) { log . warn ( "Error loading config from path " + config . path , t ) ; } } | Called to initiate an intelligent reload of a particular config | 174 | 11 |
21,983 | @ Provides @ Named ( "logdata" ) public CloudTable getLogDataTable ( @ Named ( "azure.storage-connection-string" ) String storageConnectionString , @ Named ( "azure.logging-table" ) String logTableName ) throws URISyntaxException , StorageException , InvalidKeyException { // Retrieve storage account from connection-string. CloudStorageAccount storageAccount = CloudStorageAccount . parse ( storageConnectionString ) ; // Create the table client. CloudTableClient tableClient = storageAccount . createCloudTableClient ( ) ; // Create the table if it doesn't exist. CloudTable table = tableClient . getTableReference ( logTableName ) ; table . createIfNotExists ( ) ; return table ; } | For the Azure Log Store the underlying table to use | 158 | 10 |
21,984 | public final ReturnValue execute ( final ICommandLine cl ) { if ( cl . hasOption ( ' ' ) ) { setUrl ( cl . getOptionValue ( ' ' ) ) ; } if ( cl . hasOption ( ' ' ) ) { setObject ( cl . getOptionValue ( ' ' ) ) ; } if ( cl . hasOption ( ' ' ) ) { setAttribute ( cl . getOptionValue ( ' ' ) ) ; } if ( cl . hasOption ( ' ' ) ) { setInfo_attribute ( cl . getOptionValue ( ' ' ) ) ; } if ( cl . hasOption ( ' ' ) ) { setInfo_key ( cl . getOptionValue ( ' ' ) ) ; } if ( cl . hasOption ( ' ' ) ) { setAttribute_key ( cl . getOptionValue ( ' ' ) ) ; } if ( cl . hasOption ( ' ' ) ) { setWarning ( cl . getOptionValue ( ' ' ) ) ; } if ( cl . hasOption ( ' ' ) ) { setCritical ( cl . getOptionValue ( ' ' ) ) ; } if ( cl . hasOption ( "username" ) ) { setUsername ( cl . getOptionValue ( "username" ) ) ; } if ( cl . hasOption ( "password" ) ) { setPassword ( cl . getOptionValue ( "password" ) ) ; } setVerbatim ( 2 ) ; // setVerbatim(4); try { connect ( ) ; execute ( ) ; ByteArrayOutputStream bout = new ByteArrayOutputStream ( ) ; PrintStream ps = new PrintStream ( bout ) ; Status status = report ( ps ) ; ps . flush ( ) ; ps . close ( ) ; return new ReturnValue ( status , new String ( bout . toByteArray ( ) ) ) ; } catch ( Exception ex ) { LOG . warn ( getContext ( ) , "An error has occurred during execution " + "of the CHECK_JMX plugin : " + ex . getMessage ( ) , ex ) ; ByteArrayOutputStream bout = new ByteArrayOutputStream ( ) ; PrintStream ps = new PrintStream ( bout ) ; Status status = report ( ex , ps ) ; ps . flush ( ) ; ps . close ( ) ; return new ReturnValue ( status , new String ( bout . toByteArray ( ) ) ) ; } finally { try { disconnect ( ) ; } catch ( IOException e ) { LOG . warn ( getContext ( ) , "An error has occurred during execution (disconnect) of the CHECK_JMX plugin : " + e . getMessage ( ) , e ) ; // ByteArrayOutputStream bout = new ByteArrayOutputStream(); // PrintStream ps = new PrintStream(bout); // // Status status = report(e, ps); // ps.flush(); // ps.close(); // return new ReturnValue(status, new String(bout.toByteArray())); } } } | Executes the plugin . | 625 | 5 |
21,985 | public static boolean overlapping ( Version min1 , Version max1 , Version min2 , Version max2 ) { // Versions overlap if: // - either Min or Max values are identical (fast test for real scenarios) // - Min1|Max1 are within the range Min2-Max2 // - Min2|Max2 are within the range Min1-Max1 return min1 . equals ( min2 ) || max1 . equals ( max2 ) || min2 . within ( min1 , max1 ) || max2 . within ( min1 , min2 ) || min1 . within ( min2 , max2 ) || max1 . within ( min2 , max2 ) ; } | Determines if 2 version ranges have any overlap | 144 | 10 |
21,986 | public String createPartitionAndRowQuery ( final DateTime from , final DateTime to ) { final String parMin = TableQuery . generateFilterCondition ( "PartitionKey" , TableQuery . QueryComparisons . GREATER_THAN_OR_EQUAL , from . toLocalDate ( ) . toString ( ) ) ; final String rowMin = TableQuery . generateFilterCondition ( "RowKey" , TableQuery . QueryComparisons . GREATER_THAN_OR_EQUAL , LogLineTableEntity . toRowKey ( from , null ) ) ; if ( to == null || from . toLocalDate ( ) . equals ( to . toLocalDate ( ) ) || to . isAfterNow ( ) ) { // There's no upper bound (or the upper bound doesn't make sense to include in the query) return andFilters ( parMin , rowMin ) ; } else { // From and To required final String parMax = TableQuery . generateFilterCondition ( "PartitionKey" , TableQuery . QueryComparisons . LESS_THAN , to . toLocalDate ( ) . plusDays ( 1 ) . toString ( ) ) ; final String rowMax = TableQuery . generateFilterCondition ( "RowKey" , TableQuery . QueryComparisons . LESS_THAN , LogLineTableEntity . toRowKey ( to . plusSeconds ( 1 ) , null ) ) ; return andFilters ( parMin , parMax , rowMin , rowMax ) ; } } | Create a filter condition that returns log lines between two dates . Designed to be used in addition to other criteria | 320 | 21 |
21,987 | public ServiceInstanceEntity get ( final String serviceId ) { try { return serviceCache . get ( serviceId , ( ) -> dao . getById ( serviceId ) ) ; } catch ( Exception e ) { throw new RuntimeException ( "Error loading service: " + serviceId , e ) ; } } | Get service information reading from cache if possible | 64 | 8 |
21,988 | public ReturnValue execute ( final String [ ] argsAry ) throws BadThresholdException { // CommandLineParser clp = new PosixParser(); try { HelpFormatter hf = new HelpFormatter ( ) ; // configure a parser Parser cliParser = new Parser ( ) ; cliParser . setGroup ( mainOptionsGroup ) ; cliParser . setHelpFormatter ( hf ) ; CommandLine cl = cliParser . parse ( argsAry ) ; // Inject the context... InjectionUtils . inject ( proxiedPlugin , getContext ( ) ) ; Thread . currentThread ( ) . setContextClassLoader ( proxiedPlugin . getClass ( ) . getClassLoader ( ) ) ; ReturnValue retValue = proxiedPlugin . execute ( new PluginCommandLine ( cl ) ) ; if ( retValue == null ) { String msg = "Plugin [" + getPluginName ( ) + "] with args [" + StringUtils . join ( argsAry ) + "] returned null" ; retValue = new ReturnValue ( Status . UNKNOWN , msg ) ; } return retValue ; } catch ( OptionException e ) { String msg = e . getMessage ( ) ; LOG . error ( getContext ( ) , "Error parsing plugin '" + getPluginName ( ) + "' command line : " + msg , e ) ; return new ReturnValue ( Status . UNKNOWN , msg ) ; } } | Executes the proxied plugin passing the received arguments as parameters . | 303 | 13 |
21,989 | public void printHelp ( final PrintWriter out ) { HelpFormatter hf = new HelpFormatter ( ) ; StringBuilder sbDivider = new StringBuilder ( "=" ) ; while ( sbDivider . length ( ) < hf . getPageWidth ( ) ) { sbDivider . append ( ' ' ) ; } out . println ( sbDivider . toString ( ) ) ; out . println ( "PLUGIN NAME : " + proxyedPluginDefinition . getName ( ) ) ; if ( description != null && description . trim ( ) . length ( ) != 0 ) { out . println ( sbDivider . toString ( ) ) ; out . println ( "Description : " ) ; out . println ( ) ; out . println ( description ) ; } hf . setGroup ( mainOptionsGroup ) ; // hf.setHeader(m_pluginDef.getName()); hf . setDivider ( sbDivider . toString ( ) ) ; hf . setPrintWriter ( out ) ; hf . print ( ) ; // hf.printHelp(m_pluginDef.getName(), m_Options); } | Prints the help related to the plugin to a specified output . | 249 | 13 |
21,990 | public static Timecode max ( final Timecode ... timecodes ) { Timecode max = null ; for ( Timecode timecode : timecodes ) if ( max == null || lt ( max , timecode ) ) max = timecode ; return max ; } | Returns the larger of a number of timecodes | 54 | 9 |
21,991 | public static Timecode min ( final Timecode ... timecodes ) { Timecode min = null ; for ( Timecode timecode : timecodes ) if ( min == null || ge ( min , timecode ) ) min = timecode ; return min ; } | Returns the smaller of some timecodes | 53 | 7 |
21,992 | public long getDurationMillis ( ) { List < Element > durations = element . getChildren ( "Duration" ) ; if ( durations . size ( ) != 0 ) { final String durationString = durations . get ( 0 ) . getValue ( ) ; final long duration = Long . parseLong ( durationString ) ; return duration ; } else { throw new RuntimeException ( "No Duration elements present on track!" ) ; } } | Gets duration of video track in milliseconds . | 92 | 9 |
21,993 | private static Group configureCommandLine ( ) { DefaultOptionBuilder oBuilder = new DefaultOptionBuilder ( ) ; ArgumentBuilder aBuilder = new ArgumentBuilder ( ) ; GroupBuilder gBuilder = new GroupBuilder ( ) ; DefaultOption listOption = oBuilder . withLongName ( "list" ) . withShortName ( "l" ) . withDescription ( "Lists all the installed plugins" ) . create ( ) ; DefaultOption versionOption = oBuilder . withLongName ( "version" ) . withShortName ( "v" ) . withDescription ( "Print the server version number" ) . create ( ) ; DefaultOption helpOption = oBuilder . withLongName ( "help" ) . withShortName ( "h" ) . withDescription ( "Show this help" ) . create ( ) ; // DefaultOption pluginNameOption = oBuilder.withLongName("plugin") // .withShortName("p").withDescription("The plugin name") // .withArgument( // aBuilder.withName("name").withMinimum(1).withMaximum(1) // .create()).create(); DefaultOption pluginHelpOption = oBuilder . withLongName ( "help" ) . withShortName ( "h" ) . withDescription ( "Shows help about a plugin" ) . withArgument ( aBuilder . withName ( "name" ) . withMinimum ( 1 ) . withMaximum ( 1 ) . create ( ) ) . create ( ) ; Group alternativeOptions = gBuilder . withOption ( listOption ) . withOption ( pluginHelpOption ) . create ( ) ; DefaultOption confOption = oBuilder . withLongName ( "conf" ) . withShortName ( "c" ) . withDescription ( "Specifies the JNRPE configuration file" ) . withArgument ( aBuilder . withName ( "path" ) . withMinimum ( 1 ) . withMaximum ( 1 ) . create ( ) ) . withChildren ( alternativeOptions ) . withRequired ( true ) . create ( ) ; DefaultOption interactiveOption = oBuilder . withLongName ( "interactive" ) . withShortName ( "i" ) . withDescription ( "Starts JNRPE in command line mode" ) . create ( ) ; Group jnrpeOptions = gBuilder . withOption ( confOption ) . withOption ( interactiveOption ) . withMinimum ( 1 ) . create ( ) ; return gBuilder . withOption ( versionOption ) . withOption ( helpOption ) . withOption ( jnrpeOptions ) . create ( ) ; } | Configure the command line parser . | 536 | 7 |
21,994 | private static void printHelp ( final IPluginRepository pr , final String pluginName ) { try { PluginProxy pp = ( PluginProxy ) pr . getPlugin ( pluginName ) ; // CPluginProxy pp = // CPluginFactory.getInstance().getPlugin(sPluginName); if ( pp == null ) { System . out . println ( "Plugin " + pluginName + " does not exists." ) ; } else { pp . printHelp ( ) ; } } catch ( Exception e ) { // TODO Auto-generated catch block e . printStackTrace ( ) ; } System . exit ( 0 ) ; } | Prints the help about a plugin . | 130 | 8 |
21,995 | private static void printVersion ( ) { System . out . println ( "JNRPE version " + VERSION ) ; System . out . println ( "Copyright (c) 2011 Massimiliano Ziccardi" ) ; System . out . println ( "Licensed under the Apache License, Version 2.0" ) ; System . out . println ( ) ; } | Prints the JNRPE Server version . | 77 | 9 |
21,996 | @ SuppressWarnings ( "unchecked" ) private static void printUsage ( final Exception e ) { printVersion ( ) ; if ( e != null ) { System . out . println ( e . getMessage ( ) + "\n" ) ; } HelpFormatter hf = new HelpFormatter ( ) ; StringBuilder sbDivider = new StringBuilder ( "=" ) ; while ( sbDivider . length ( ) < hf . getPageWidth ( ) ) { sbDivider . append ( "=" ) ; } // DISPLAY SETTING hf . getDisplaySettings ( ) . clear ( ) ; hf . getDisplaySettings ( ) . add ( DisplaySetting . DISPLAY_GROUP_EXPANDED ) ; hf . getDisplaySettings ( ) . add ( DisplaySetting . DISPLAY_PARENT_CHILDREN ) ; // USAGE SETTING hf . getFullUsageSettings ( ) . clear ( ) ; hf . getFullUsageSettings ( ) . add ( DisplaySetting . DISPLAY_PARENT_ARGUMENT ) ; hf . getFullUsageSettings ( ) . add ( DisplaySetting . DISPLAY_ARGUMENT_BRACKETED ) ; hf . getFullUsageSettings ( ) . add ( DisplaySetting . DISPLAY_PARENT_CHILDREN ) ; hf . getFullUsageSettings ( ) . add ( DisplaySetting . DISPLAY_GROUP_EXPANDED ) ; hf . setDivider ( sbDivider . toString ( ) ) ; hf . setGroup ( configureCommandLine ( ) ) ; hf . print ( ) ; System . exit ( 0 ) ; } | Prints the JNRPE Server usage and eventually the error about the last invocation . | 356 | 17 |
21,997 | private static JNRPEConfiguration loadConfiguration ( final String configurationFilePath ) throws ConfigurationException { File confFile = new File ( configurationFilePath ) ; if ( ! confFile . exists ( ) || ! confFile . canRead ( ) ) { throw new ConfigurationException ( "Cannot access config file : " + configurationFilePath ) ; } return JNRPEConfigurationFactory . createConfiguration ( configurationFilePath ) ; } | Loads the JNRPE configuration from the INI or the XML file . | 93 | 16 |
21,998 | private static IPluginRepository loadPluginDefinitions ( final String sPluginDirPath ) throws PluginConfigurationException { File fDir = new File ( sPluginDirPath ) ; DynaPluginRepository repo = new DynaPluginRepository ( ) ; repo . load ( fDir ) ; return repo ; } | Loads a plugin repository from a directory . | 64 | 9 |
21,999 | private static void printPluginList ( final IPluginRepository pr ) { System . out . println ( "List of installed plugins : " ) ; for ( PluginDefinition pd : pr . getAllPlugins ( ) ) { System . out . println ( " * " + pd . getName ( ) ) ; } System . exit ( 0 ) ; } | Prints the list of installed plugins . | 75 | 8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.