idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
21,800 | private Metric checkSlave ( final ICommandLine cl , final Mysql mysql , final Connection conn ) throws MetricGatheringException { Metric metric = null ; try { Map < String , Integer > status = getSlaveStatus ( conn ) ; if ( status . isEmpty ( ) ) { mysql . closeConnection ( conn ) ; throw new MetricGatheringException ( "CHECK_MYSQL - WARNING: No slaves defined. " , Status . CRITICAL , null ) ; } // check if slave is running int slaveIoRunning = status . get ( "Slave_IO_Running" ) ; int slaveSqlRunning = status . get ( "Slave_SQL_Running" ) ; int secondsBehindMaster = status . get ( "Seconds_Behind_Master" ) ; if ( slaveIoRunning == 0 || slaveSqlRunning == 0 ) { mysql . closeConnection ( conn ) ; throw new MetricGatheringException ( "CHECK_MYSQL - CRITICAL: Slave status unavailable. " , Status . CRITICAL , null ) ; } String slaveResult = "Slave IO: " + slaveIoRunning + " Slave SQL: " + slaveSqlRunning + " Seconds Behind Master: " + secondsBehindMaster ; metric = new Metric ( "secondsBehindMaster" , slaveResult , new BigDecimal ( secondsBehindMaster ) , null , null ) ; } catch ( SQLException e ) { String message = e . getMessage ( ) ; LOG . warn ( getContext ( ) , "Error executing the CheckMysql plugin: " + message , e ) ; throw new MetricGatheringException ( "CHECK_MYSQL - CRITICAL: Unable to check slave status: - " + message , Status . CRITICAL , e ) ; } return metric ; } | Check the status of mysql slave thread . | 388 | 8 |
21,801 | private Map < String , Integer > getSlaveStatus ( final Connection conn ) throws SQLException { Map < String , Integer > map = new HashMap < String , Integer > ( ) ; String query = SLAVE_STATUS_QRY ; Statement statement = null ; ResultSet rs = null ; try { if ( conn != null ) { statement = conn . createStatement ( ) ; rs = statement . executeQuery ( query ) ; while ( rs . next ( ) ) { map . put ( "Slave_IO_Running" , rs . getInt ( "Slave_IO_Running" ) ) ; map . put ( "Slave_SQL_Running" , rs . getInt ( "Slave_SQL_Running" ) ) ; map . put ( "Seconds_Behind_Master" , rs . getInt ( "Seconds_Behind_Master" ) ) ; } } } finally { DBUtils . closeQuietly ( rs ) ; DBUtils . closeQuietly ( statement ) ; } return map ; } | Get slave statuses . | 223 | 5 |
21,802 | public void updateCRC ( ) { this . crc32 = 0 ; CRC32 crcAlg = new CRC32 ( ) ; crcAlg . update ( this . toByteArray ( ) ) ; this . crc32 = ( int ) crcAlg . getValue ( ) ; } | Updates the CRC value . | 65 | 6 |
21,803 | private static Stage configureParser ( ) { Stage startStage = new StartStage ( ) ; Stage negativeInfinityStage = new NegativeInfinityStage ( ) ; Stage positiveInfinityStage = new PositiveInfinityStage ( ) ; NegateStage negateStage = new NegateStage ( ) ; BracketStage . OpenBracketStage openBraceStage = new BracketStage . OpenBracketStage ( ) ; NumberBoundaryStage . LeftBoundaryStage startBoundaryStage = new NumberBoundaryStage . LeftBoundaryStage ( ) ; NumberBoundaryStage . RightBoundaryStage rightBoundaryStage = new NumberBoundaryStage . RightBoundaryStage ( ) ; SeparatorStage separatorStage = new SeparatorStage ( ) ; BracketStage . ClosedBracketStage closedBraketStage = new BracketStage . ClosedBracketStage ( ) ; startStage . addTransition ( negateStage ) ; startStage . addTransition ( openBraceStage ) ; startStage . addTransition ( negativeInfinityStage ) ; startStage . addTransition ( startBoundaryStage ) ; negateStage . addTransition ( negativeInfinityStage ) ; negateStage . addTransition ( openBraceStage ) ; negateStage . addTransition ( startBoundaryStage ) ; openBraceStage . addTransition ( startBoundaryStage ) ; startBoundaryStage . addTransition ( separatorStage ) ; negativeInfinityStage . addTransition ( separatorStage ) ; separatorStage . addTransition ( positiveInfinityStage ) ; separatorStage . addTransition ( rightBoundaryStage ) ; rightBoundaryStage . addTransition ( closedBraketStage ) ; return startStage ; } | Configures the state machine . | 359 | 6 |
21,804 | public static void parse ( final String range , final RangeConfig tc ) throws RangeException { if ( range == null ) { throw new RangeException ( "Range can't be null" ) ; } ROOT_STAGE . parse ( range , tc ) ; checkBoundaries ( tc ) ; } | Parses the threshold . | 61 | 6 |
21,805 | private static void checkBoundaries ( final RangeConfig rc ) throws RangeException { if ( rc . isNegativeInfinity ( ) ) { // No other checks necessary. Negative infinity is less than any // number return ; } if ( rc . isPositiveInfinity ( ) ) { // No other checks necessary. Positive infinity is greater than any // number return ; } if ( rc . getLeftBoundary ( ) . compareTo ( rc . getRightBoundary ( ) ) > 0 ) { throw new RangeException ( "Left boundary must be less than right boundary (left:" + rc . getLeftBoundary ( ) + ", right:" + rc . getRightBoundary ( ) + ")" ) ; } } | Checks that right boundary is greater than left boundary . | 149 | 11 |
21,806 | public TimecodeBuilder withTimecode ( Timecode timecode ) { return this . withNegative ( timecode . isNegative ( ) ) . withDays ( timecode . getDaysPart ( ) ) . withHours ( timecode . getHoursPart ( ) ) . withMinutes ( timecode . getMinutesPart ( ) ) . withSeconds ( timecode . getSecondsPart ( ) ) . withFrames ( timecode . getFramesPart ( ) ) . withDropFrame ( timecode . isDropFrame ( ) ) . withRate ( timecode . getTimebase ( ) ) ; } | Reset this builder to the values in the provided Timecode | 128 | 12 |
21,807 | public Timecode build ( ) { // If drop-frame is not specified (and timebase is drop frame capable) default to true final boolean dropFrame = ( this . dropFrame != null ) ? this . dropFrame . booleanValue ( ) : getRate ( ) . canBeDropFrame ( ) ; return new Timecode ( negative , days , hours , minutes , seconds , frames , rate , dropFrame ) ; } | Constructs a Timecode instance with the fields defined in this builder | 87 | 13 |
21,808 | public void setAll ( final String name , final String email , final Map < String , Map < String , ConfigPropertyValue > > data , final String message ) { set ( name , email , data , ConfigChangeMode . WIPE_ALL , message ) ; } | Create a new commit reflecting the provided properties removing any property not mentioned here | 56 | 14 |
21,809 | public void set ( final String name , final String email , final Map < String , Map < String , ConfigPropertyValue > > data , final ConfigChangeMode changeMode , final String message ) { try { RepoHelper . write ( repo , name , email , data , changeMode , message ) ; } catch ( Exception e ) { try { RepoHelper . reset ( repo ) ; } catch ( Exception ee ) { throw new RuntimeException ( "Error writing updated repository, then could not reset work tree" , e ) ; } throw new RuntimeException ( "Error writing updated repository, work tree reset" , e ) ; } // Push the changes to the remote if ( hasRemote ) { try { RepoHelper . push ( repo , "origin" , credentials ) ; } catch ( Throwable t ) { throw new RuntimeException ( "Saved changes to the local repository but push to remote failed!" , t ) ; } } } | Create a new commit reflecting the provided properties | 195 | 8 |
21,810 | public static HttpCallContext get ( ) throws IllegalStateException { final HttpCallContext ctx = peek ( ) ; if ( ctx != null ) return ctx ; else throw new IllegalStateException ( "Not in an HttpCallContext!" ) ; } | Retrieve the HttpCallContext associated with this Thread | 56 | 11 |
21,811 | public static HttpCallContext set ( HttpServletRequest request , HttpServletResponse response , ServletContext servletContext ) { final HttpCallContext ctx = new HttpCallContext ( generateTraceId ( request ) , request , response , servletContext ) ; contexts . set ( ctx ) ; return ctx ; } | Creates and associates an HttpCallContext with the current Thread | 74 | 13 |
21,812 | public static void filterP12 ( File p12 , String p12Password ) throws IOException { if ( ! p12 . exists ( ) ) throw new IllegalArgumentException ( "p12 file does not exist: " + p12 . getPath ( ) ) ; final File pem ; if ( USE_GENERIC_TEMP_DIRECTORY ) pem = File . createTempFile ( UUID . randomUUID ( ) . toString ( ) , "" ) ; else pem = new File ( p12 . getAbsolutePath ( ) + ".pem.tmp" ) ; final String pemPassword = UUID . randomUUID ( ) . toString ( ) ; try { P12toPEM ( p12 , p12Password , pem , pemPassword ) ; PEMtoP12 ( pem , pemPassword , p12 , p12Password ) ; } finally { if ( pem . exists ( ) ) if ( ! pem . delete ( ) ) log . warn ( "[OpenSSLPKCS12] {filterP12} Could not delete temporary PEM file " + pem ) ; } } | Recreates a PKCS12 KeyStore using OpenSSL ; this is a workaround a BouncyCastle - Firefox compatibility bug | 245 | 27 |
21,813 | public < T > T runUnchecked ( Retryable < T > operation ) throws RuntimeException { try { return run ( operation ) ; } catch ( RuntimeException e ) { throw e ; } catch ( Exception e ) { throw new RuntimeException ( "Retryable " + operation + " failed: " + e . getMessage ( ) , e ) ; } } | Run the operation only throwing an unchecked exception on failure | 77 | 10 |
21,814 | public void trace ( final IJNRPEExecutionContext ctx , final String message ) { postEvent ( ctx , new LogEvent ( source , LogEventType . TRACE , message ) ) ; } | Sends trace level messages . | 44 | 6 |
21,815 | public void debug ( final IJNRPEExecutionContext ctx , final String message ) { postEvent ( ctx , new LogEvent ( source , LogEventType . DEBUG , message ) ) ; } | Sends debug level messages . | 43 | 6 |
21,816 | public void info ( final IJNRPEExecutionContext ctx , final String message ) { postEvent ( ctx , new LogEvent ( source , LogEventType . INFO , message ) ) ; } | Sends info level messages . | 43 | 6 |
21,817 | public void warn ( final IJNRPEExecutionContext ctx , final String message ) { postEvent ( ctx , new LogEvent ( source , LogEventType . WARNING , message ) ) ; } | Sends warn level messages . | 43 | 6 |
21,818 | @ Override public Map < RuleSet , List < Rule > > matching ( Rules rules , Map < String , Object > vars , boolean ignoreMethodErrors ) throws OgnlException { Map < RuleSet , List < Rule > > ret = new HashMap <> ( ) ; for ( RuleSet ruleSet : rules . ruleSets ) { try { OgnlContext context = createContext ( vars ) ; List < Rule > matching = match ( ruleSet , context ) ; if ( ! matching . isEmpty ( ) ) { ret . put ( ruleSet , matching ) ; } } catch ( MethodFailedException mfe ) { if ( ! ignoreMethodErrors ) { throw mfe ; } log . warn ( "Method failed for ruleset " + ruleSet . id , mfe ) ; } } return ret ; } | returns a list of the rules that match from the supplied Rules document | 177 | 14 |
21,819 | private List < Rule > match ( final RuleSet ruleSet , final OgnlContext ognlContext ) throws OgnlException { log . debug ( "Assessing input for ruleset : " + ruleSet . id ) ; //run the input commands ruleSet . runInput ( ognlContext ) ; final List < Rule > ret = new ArrayList <> ( ) ; //assess each rule against the input, return any that match for ( Rule rule : ruleSet . rules ) { Boolean bresult = rule . assessMatch ( ognlContext ) ; if ( bresult ) { log . debug ( rule . condition . getOriginalExpression ( ) + " matches" ) ; ret . add ( rule ) ; } } return ret ; } | returns a list of rules that match in the given rule set | 159 | 13 |
21,820 | public JNRPE build ( ) { JNRPE jnrpe = new JNRPE ( pluginRepository , commandRepository , charset , acceptParams , acceptedHosts , maxAcceptedConnections , readTimeout , writeTimeout ) ; IJNRPEEventBus eventBus = jnrpe . getExecutionContext ( ) . getEventBus ( ) ; for ( Object obj : eventListeners ) { eventBus . register ( obj ) ; } return jnrpe ; } | Builds the configured JNRPE instance . | 104 | 9 |
21,821 | public ResteasyClient getOrCreateClient ( final boolean fastFail , final AuthScope authScope , final Credentials credentials , final boolean preemptiveAuth , final boolean storeCookies , Consumer < HttpClientBuilder > customiser ) { customiser = createHttpClientCustomiser ( fastFail , authScope , credentials , preemptiveAuth , storeCookies , customiser ) ; return getOrCreateClient ( customiser , null ) ; } | Build a new Resteasy Client optionally with authentication credentials | 91 | 10 |
21,822 | public Consumer < HttpClientBuilder > createHttpClientCustomiser ( final boolean fastFail , final AuthScope authScope , final Credentials credentials , final boolean preemptiveAuth , final boolean storeCookies , Consumer < HttpClientBuilder > customiser ) { // Customise timeouts if fast fail mode is enabled if ( fastFail ) { customiser = concat ( customiser , b -> { RequestConfig . Builder requestBuilder = RequestConfig . custom ( ) ; requestBuilder . setConnectTimeout ( ( int ) fastFailConnectionTimeout . getMilliseconds ( ) ) . setSocketTimeout ( ( int ) fastFailSocketTimeout . getMilliseconds ( ) ) ; b . setDefaultRequestConfig ( requestBuilder . build ( ) ) ; } ) ; } // If credentials were supplied then we should set them up if ( credentials != null ) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider ( ) ; if ( authScope != null ) credentialsProvider . setCredentials ( authScope , credentials ) ; else credentialsProvider . setCredentials ( AuthScope . ANY , credentials ) ; // Set up bearer auth scheme provider if we're using bearer credentials if ( credentials instanceof BearerCredentials ) { customiser = concat ( customiser , b -> { Registry < AuthSchemeProvider > authSchemeRegistry = RegistryBuilder . < AuthSchemeProvider > create ( ) . register ( "Bearer" , new BearerAuthSchemeProvider ( ) ) . build ( ) ; b . setDefaultAuthSchemeRegistry ( authSchemeRegistry ) ; } ) ; } // Set up the credentials customisation customiser = concat ( customiser , b -> b . setDefaultCredentialsProvider ( credentialsProvider ) ) ; if ( preemptiveAuth && credentials instanceof BearerCredentials ) customiser = concat ( customiser , b -> b . addInterceptorFirst ( new PreemptiveBearerAuthInterceptor ( ) ) ) ; else customiser = concat ( customiser , b -> b . addInterceptorLast ( new PreemptiveBasicAuthInterceptor ( ) ) ) ; } // If cookies are enabled then set up a cookie store if ( storeCookies ) customiser = concat ( customiser , b -> b . setDefaultCookieStore ( new BasicCookieStore ( ) ) ) ; return customiser ; } | N . B . This method signature may change in the future to add new parameters | 500 | 16 |
21,823 | public CloseableHttpClient createHttpClient ( final Consumer < HttpClientBuilder > customiser ) { final HttpClientBuilder builder = HttpClientBuilder . create ( ) ; // By default set long call timeouts { RequestConfig . Builder requestBuilder = RequestConfig . custom ( ) ; requestBuilder . setConnectTimeout ( ( int ) connectionTimeout . getMilliseconds ( ) ) . setSocketTimeout ( ( int ) socketTimeout . getMilliseconds ( ) ) ; builder . setDefaultRequestConfig ( requestBuilder . build ( ) ) ; } // Set the default keepalive setting if ( noKeepalive ) builder . setConnectionReuseStrategy ( new NoConnectionReuseStrategy ( ) ) ; // By default share the common connection provider builder . setConnectionManager ( connectionManager ) ; // By default use the JRE default route planner for proxies builder . setRoutePlanner ( new SystemDefaultRoutePlanner ( ProxySelector . getDefault ( ) ) ) ; // Allow customisation if ( customiser != null ) customiser . accept ( builder ) ; return builder . build ( ) ; } | Build an HttpClient | 232 | 5 |
21,824 | public StorageSize multiply ( BigInteger by ) { final BigInteger result = getBits ( ) . multiply ( by ) ; return new StorageSize ( getUnit ( ) , result ) ; } | Multiplies the storage size by a certain amount | 40 | 10 |
21,825 | public StorageSize subtract ( StorageSize that ) { StorageUnit smallestUnit = StorageUnit . smallest ( this . getUnit ( ) , that . getUnit ( ) ) ; final BigInteger a = this . getBits ( ) ; final BigInteger b = that . getBits ( ) ; final BigInteger result = a . subtract ( b ) ; return new StorageSize ( smallestUnit , result ) ; } | Subtracts a storage size from the current object using the smallest unit as the resulting StorageSize s unit | 85 | 22 |
21,826 | private boolean isHtmlAcceptable ( HttpServletRequest request ) { @ SuppressWarnings ( "unchecked" ) final List < String > accepts = ListUtility . list ( ListUtility . iterate ( request . getHeaders ( HttpHeaderNames . ACCEPT ) ) ) ; for ( String accept : accepts ) { if ( StringUtils . startsWithIgnoreCase ( accept , "text/html" ) ) return true ; } return false ; } | Decides if an HTML response is acceptable to the client | 103 | 11 |
21,827 | public static Injector createInjector ( final PropertyFile configuration , final GuiceSetup setup ) { return new GuiceBuilder ( ) . withConfig ( configuration ) . withSetup ( setup ) . build ( ) ; } | Creates an Injector by taking a preloaded service . properties and a pre - constructed GuiceSetup | 47 | 22 |
21,828 | public String getMessage ( ) { if ( performanceDataList . isEmpty ( ) ) { return messageString ; } StringBuilder res = new StringBuilder ( messageString ) . append ( ' ' ) ; for ( PerformanceData pd : performanceDataList ) { res . append ( pd . toPerformanceString ( ) ) . append ( ' ' ) ; } return res . toString ( ) ; } | Returns the message . If the performance data has been passed in they are attached at the end of the message accordingly to the Nagios specifications | 84 | 27 |
21,829 | private void start ( final ResourceInstanceEntity instance ) { azure . start ( instance . getProviderInstanceId ( ) ) ; instance . setState ( ResourceInstanceState . PROVISIONING ) ; } | Start the instance | 41 | 3 |
21,830 | private void stop ( final ResourceInstanceEntity instance ) { azure . stop ( instance ) ; instance . setState ( ResourceInstanceState . DISCARDING ) ; } | Stop the instance | 35 | 3 |
21,831 | private void updateState ( final ResourceInstanceEntity instance ) { ResourceInstanceState actual = azure . determineState ( instance ) ; instance . setState ( actual ) ; } | Check in with Azure on the instance state | 35 | 8 |
21,832 | @ Override public void userEventTriggered ( final ChannelHandlerContext ctx , final Object evt ) { if ( evt instanceof IdleStateEvent ) { IdleStateEvent e = ( IdleStateEvent ) evt ; if ( e . state ( ) == IdleState . READER_IDLE ) { ctx . close ( ) ; LOG . warn ( jnrpeContext , "Read Timeout" ) ; //jnrpeContext.getEventBus().post(new LogEvent(this, LogEventType.INFO, "Read Timeout")); //EventsUtil.sendEvent(this.jnrpeContext, this, LogEvent.INFO, "Read Timeout"); } else if ( e . state ( ) == IdleState . WRITER_IDLE ) { LOG . warn ( jnrpeContext , "Write Timeout" ) ; //jnrpeContext.getEventBus().post(new LogEvent(this, LogEventType.INFO, "Write Timeout")); //EventsUtil.sendEvent(jnrpeContext, this, LogEvent.INFO, "Write Timeout"); ctx . close ( ) ; } } } | Method userEventTriggered . | 248 | 7 |
21,833 | static String truncatePath ( String path , String commonPrefix ) { final int nextSlash = path . indexOf ( ' ' , commonPrefix . length ( ) ) ; final int nextOpenCurly = path . indexOf ( ' ' , commonPrefix . length ( ) ) ; if ( nextSlash > 0 ) return path . substring ( 0 , nextSlash ) ; else if ( nextOpenCurly > 0 ) return path . substring ( 0 , nextOpenCurly ) ; else return path ; } | Truncate path to the completion of the segment ending with the common prefix | 112 | 15 |
21,834 | public void setFilterGUIDs ( List < String > filterGUIDs ) { int i = 0 ; for ( String filterGUID : filterGUIDs ) { // Remove filters (we're replacing them) removeFilter ( "Filter_" + i ) ; // Build a new Filter_0 element Element filter = buildFilterElement ( "Filter_" + i , filterGUID ) ; element . addContent ( filter ) ; i ++ ; } } | Set the filter GUID replacing any filter that is currently defined | 96 | 12 |
21,835 | public static OgnlEvaluator getInstance ( final Object root , final String expression ) { final OgnlEvaluatorCollection collection = INSTANCE . getEvaluators ( getRootClass ( root ) ) ; return collection . get ( expression ) ; } | Get an OGNL Evaluator for a particular expression with a given input | 58 | 16 |
21,836 | public static PropertyFile find ( final ClassLoader classloader , final String ... fileNames ) { URL resolvedResource = null ; String resolvedFile = null ; for ( String fileName : fileNames ) { if ( fileName . charAt ( 0 ) == ' ' ) { File file = new File ( fileName ) ; if ( file . exists ( ) ) { try { return PropertyFile . readOnly ( file ) ; } catch ( IOException e ) { throw new IllegalArgumentException ( "Error loading property file: " + fileName + ". Error: " + e . getMessage ( ) , e ) ; } } } else { // Try to resolve the filename (for logging any errors) final URL resource = classloader . getResource ( fileName ) ; if ( resource != null ) { resolvedFile = fileName ; resolvedResource = resource ; break ; } } } if ( resolvedFile == null ) { if ( fileNames . length == 1 ) throw new IllegalArgumentException ( "Error finding property file in classpath: " + fileNames [ 0 ] ) ; else throw new IllegalArgumentException ( "Error finding property files in classpath: " + Arrays . asList ( fileNames ) ) ; } else if ( log . isInfoEnabled ( ) ) log . info ( "{find} Loading properties from " + resolvedFile ) ; return openResource ( classloader , resolvedResource , resolvedFile ) ; } | Find a property file | 297 | 4 |
21,837 | private List < Class < ? > > getClassesByDiscriminators ( Collection < String > discriminators ) { Map < String , Class < ? > > entitiesByName = new HashMap <> ( ) ; // Prepare a Map of discriminator name -> entity class for ( QEntity child : entity . getSubEntities ( ) ) { entitiesByName . put ( child . getDiscriminatorValue ( ) , child . getEntityClass ( ) ) ; } // If the root class isn't abstract then add it to the list of possible discriminators too if ( ! entity . isEntityClassAbstract ( ) ) entitiesByName . put ( entity . getDiscriminatorValue ( ) , entity . getEntityClass ( ) ) ; // Translate the discriminator string values to classes List < Class < ? > > classes = new ArrayList <> ( discriminators . size ( ) ) ; for ( String discriminator : discriminators ) { final Class < ? > clazz = entitiesByName . get ( discriminator ) ; if ( clazz != null ) classes . add ( clazz ) ; else throw new IllegalArgumentException ( "Invalid class discriminator '" + discriminator + "', expected one of: " + entitiesByName . keySet ( ) ) ; } return classes ; } | Translates the set of string discriminators into entity classes | 272 | 12 |
21,838 | @ Override public Expression < ? > getProperty ( final WQPath path ) { final JPAJoin join = getOrCreateJoin ( path . getTail ( ) ) ; return join . property ( path . getHead ( ) . getPath ( ) ) ; } | Get a property automatically creating any joins along the way as needed | 57 | 12 |
21,839 | @ Override public JPAJoin getOrCreateJoin ( final WQPath path ) { if ( path == null ) return new JPAJoin ( criteriaBuilder , entity , root , false ) ; if ( ! joins . containsKey ( path . getPath ( ) ) ) { final JPAJoin parent = getOrCreateJoin ( path . getTail ( ) ) ; final JPAJoin join = parent . join ( path . getHead ( ) . getPath ( ) ) ; joins . put ( path . getPath ( ) , join ) ; return join ; } else { return joins . get ( path . getPath ( ) ) ; } } | Ensure a join has been set up for a path | 136 | 11 |
21,840 | public boolean hasCollectionFetch ( ) { if ( fetches != null ) for ( String fetch : fetches ) { QEntity parent = entity ; final String [ ] parts = StringUtils . split ( fetch , ' ' ) ; for ( int i = 0 ; i < parts . length ; i ++ ) { // If this is a fully supported relation then continue checking if ( parent . hasRelation ( parts [ i ] ) ) { final QRelation relation = parent . getRelation ( parts [ i ] ) ; parent = relation . getEntity ( ) ; if ( relation . isCollection ( ) ) { if ( log . isTraceEnabled ( ) ) log . trace ( "Encountered fetch " + fetch + ". This resolves to " + relation + " which is a collection" ) ; return true ; } } // This covers partially-supported things like Map and other basic collections that don't have a QRelation description else if ( parent . hasNonEntityRelation ( parts [ i ] ) ) { if ( parent . isNonEntityRelationCollection ( parts [ i ] ) ) return true ; } else { log . warn ( "Encountered relation " + parts [ i ] + " on " + parent . getName ( ) + " as part of path " + fetch + ". Assuming QEntity simply does not know this relation. Assuming worst case scenario (collection join is involved)" ) ; return true ; } } } return false ; } | Returns true if one of the fetches specified will result in a collection being pulled back | 306 | 17 |
21,841 | public Timecode subtract ( SampleCount samples ) { final SampleCount mySamples = getSampleCount ( ) ; final SampleCount result = mySamples . subtract ( samples ) ; return Timecode . getInstance ( result , dropFrame ) ; } | Subtract some samples from this timecode | 51 | 9 |
21,842 | public Timecode add ( SampleCount samples ) { final SampleCount mySamples = getSampleCount ( ) ; final SampleCount totalSamples = mySamples . add ( samples ) ; return TimecodeBuilder . fromSamples ( totalSamples , dropFrame ) . build ( ) ; } | Add some samples to this timecode | 61 | 7 |
21,843 | public Timecode addPrecise ( SampleCount samples ) throws ResamplingException { final SampleCount mySamples = getSampleCount ( ) ; final SampleCount totalSamples = mySamples . addPrecise ( samples ) ; return TimecodeBuilder . fromSamples ( totalSamples , dropFrame ) . build ( ) ; } | Add some samples to this timecode throwing an exception if precision would be lost | 70 | 15 |
21,844 | public void addCommand ( final String commandName , final String pluginName , final String commandLine ) { commandsList . add ( new Command ( commandName , pluginName , commandLine ) ) ; } | Adds a command to the section . | 41 | 7 |
21,845 | public List < ManifestEntry > scan ( final Bundle bundle ) { NullArgumentException . validateNotNull ( bundle , "Bundle" ) ; final Dictionary bundleHeaders = bundle . getHeaders ( ) ; if ( bundleHeaders != null && ! bundleHeaders . isEmpty ( ) ) { return asManifestEntryList ( m_manifestFilter . match ( dictionaryToMap ( bundleHeaders ) ) ) ; } else { return Collections . emptyList ( ) ; } } | Scans bundle manifest for matches against configured manifest headers . | 102 | 11 |
21,846 | public double resample ( final double samples , final Timebase oldRate ) { if ( samples == 0 ) { return 0 ; } else if ( ! this . equals ( oldRate ) ) { final double resampled = resample ( samples , oldRate , this ) ; return resampled ; } else { return samples ; } } | Convert a sample count from one timebase to another | 70 | 11 |
21,847 | private RestException buildKnown ( Constructor < RestException > constructor , RestFailure failure ) { try { return constructor . newInstance ( failure . exception . detail , null ) ; } catch ( Exception e ) { return buildUnknown ( failure ) ; } } | Build an exception for a known exception type | 52 | 8 |
21,848 | private UnboundRestException buildUnknown ( RestFailure failure ) { // We need to build up exception detail that reasonably accurately describes the source exception final String msg = failure . exception . shortName + ": " + failure . exception . detail + " (" + failure . id + ")" ; return new UnboundRestException ( msg ) ; } | Build an exception to represent an unknown or problematic exception type | 70 | 11 |
21,849 | public static ByteBuffer blockingRead ( SocketChannel so , long timeout , byte [ ] bytes ) throws IOException { ByteBuffer b = ByteBuffer . wrap ( bytes ) ; if ( bytes . length == 0 ) return b ; final long timeoutTime = ( timeout > 0 ) ? ( System . currentTimeMillis ( ) + timeout ) : ( Long . MAX_VALUE ) ; while ( b . remaining ( ) != 0 && System . currentTimeMillis ( ) < timeoutTime ) { if ( ! so . isConnected ( ) ) throw new IOException ( "Socket closed during read operation!" ) ; so . read ( b ) ; if ( b . remaining ( ) != 0 ) { // sleep for a short time try { Thread . sleep ( 20 ) ; } catch ( InterruptedException e ) { } } } if ( System . currentTimeMillis ( ) >= timeoutTime ) { return null ; } b . rewind ( ) ; // make it easy for the caller to read from the buffer (if they're interested) return b ; } | Read a number of bytes from a socket terminating when complete after timeout milliseconds or if an error occurs | 219 | 19 |
21,850 | public < T > T deserialise ( final Class < T > clazz , final InputSource source ) { final Object obj = deserialise ( source ) ; if ( clazz . isInstance ( obj ) ) return clazz . cast ( obj ) ; else throw new JAXBRuntimeException ( "XML deserialised to " + obj . getClass ( ) + ", could not cast to the expected " + clazz ) ; } | Deserialise an input and cast to a particular type | 93 | 11 |
21,851 | public < T > T deserialise ( final Class < T > clazz , final String xml ) { final Object obj = deserialise ( new InputSource ( new StringReader ( xml ) ) ) ; if ( clazz . isInstance ( obj ) ) return clazz . cast ( obj ) ; else throw new JAXBRuntimeException ( "XML deserialised to " + obj . getClass ( ) + ", could not cast to the expected " + clazz ) ; } | Deserialise and cast to a particular type | 102 | 9 |
21,852 | public Document serialiseToDocument ( final Object obj ) { final Document document = DOMUtils . createDocumentBuilder ( ) . newDocument ( ) ; serialise ( obj , document ) ; return document ; } | Helper method to serialise an Object to an org . w3c . dom . Document | 43 | 18 |
21,853 | public void reload ( ) { try { final Execed process = Exec . rootUtility ( new File ( binPath , "nginx-reload" ) . getAbsolutePath ( ) ) ; process . waitForExit ( new Timeout ( 30 , TimeUnit . SECONDS ) . start ( ) , 0 ) ; } catch ( IOException e ) { throw new RuntimeException ( "Error executing nginx-reload command" , e ) ; } } | Reload the nginx configuration | 98 | 6 |
21,854 | public void reconfigure ( final String config ) { try { final File tempFile = File . createTempFile ( "nginx" , ".conf" ) ; try { FileHelper . write ( tempFile , config ) ; final Execed process = Exec . rootUtility ( new File ( binPath , "nginx-reconfigure" ) . getAbsolutePath ( ) , tempFile . getAbsolutePath ( ) ) ; process . waitForExit ( new Timeout ( 30 , TimeUnit . SECONDS ) . start ( ) , 0 ) ; } finally { FileUtils . deleteQuietly ( tempFile ) ; } } catch ( IOException e ) { throw new RuntimeException ( "Error executing nginx-reload command" , e ) ; } reload ( ) ; } | Rewrite the nginx site configuration and reload | 168 | 9 |
21,855 | public void installCertificates ( final String key , final String cert , final String chain ) { try { final File keyFile = File . createTempFile ( "key" , ".pem" ) ; final File certFile = File . createTempFile ( "cert" , ".pem" ) ; final File chainFile = File . createTempFile ( "chain" , ".pem" ) ; try { FileHelper . write ( keyFile , key ) ; FileHelper . write ( certFile , cert ) ; FileHelper . write ( chainFile , chain ) ; final Execed process = Exec . rootUtility ( new File ( binPath , "cert-update" ) . getAbsolutePath ( ) , keyFile . getAbsolutePath ( ) , certFile . getAbsolutePath ( ) , chainFile . getAbsolutePath ( ) ) ; process . waitForExit ( new Timeout ( 30 , TimeUnit . SECONDS ) . start ( ) , 0 ) ; } finally { FileUtils . deleteQuietly ( keyFile ) ; FileUtils . deleteQuietly ( certFile ) ; FileUtils . deleteQuietly ( chainFile ) ; } } catch ( IOException e ) { throw new RuntimeException ( "Error executing cert-update command" , e ) ; } } | Install new SSL Certificates for the host | 279 | 9 |
21,856 | public static PropertyFile get ( Class < ? > clazz ) { try { // If we get a guice-enhanced class then we should go up one level to get the class name from the user's code if ( clazz . getName ( ) . contains ( "$$EnhancerByGuice$$" ) ) clazz = clazz . getSuperclass ( ) ; final String classFileName = clazz . getSimpleName ( ) + ".class" ; final String classFilePathAndName = clazz . getName ( ) . replace ( ' ' , ' ' ) + ".class" ; URL url = clazz . getResource ( classFileName ) ; if ( log . isTraceEnabled ( ) ) log . trace ( "getResource(" + classFileName + ") = " + url ) ; if ( url == null ) { return null ; } else { String classesUrl = url . toString ( ) ; // Get the classes base classesUrl = classesUrl . replace ( classFilePathAndName , "" ) ; // Special-case: classes in a webapp are at /WEB-INF/classes/ rather than / if ( classesUrl . endsWith ( "WEB-INF/classes/" ) ) { classesUrl = classesUrl . replace ( "WEB-INF/classes/" , "" ) ; } final URL manifestURL = new URL ( classesUrl + "META-INF/MANIFEST.MF" ) ; try { final InputStream is = manifestURL . openStream ( ) ; try { final PropertyFile props = new PropertyFile ( ) ; final Manifest manifest = new Manifest ( is ) ; for ( Object key : manifest . getMainAttributes ( ) . keySet ( ) ) { final Object value = manifest . getMainAttributes ( ) . get ( key ) ; props . set ( key . toString ( ) , value . toString ( ) ) ; } return props ; } finally { IOUtils . closeQuietly ( is ) ; } } catch ( FileNotFoundException e ) { log . warn ( "Could not find: " + manifestURL , e ) ; return null ; } } } catch ( Throwable t ) { log . warn ( "Error acquiring MANIFEST.MF for " + clazz , t ) ; return null ; } } | Attempt to find the MANIFEST . MF associated with a particular class | 491 | 14 |
21,857 | private static void saveClass ( final ClassLoader cl , final Class c ) { if ( LOADED_PLUGINS . get ( cl ) == null ) { LOADED_PLUGINS . put ( cl , new ClassesData ( ) ) ; } ClassesData cd = LOADED_PLUGINS . get ( cl ) ; cd . addClass ( c ) ; } | Stores a class in the cache . | 80 | 8 |
21,858 | public static Class getClass ( final ClassLoader cl , final String className ) throws ClassNotFoundException { if ( LOADED_PLUGINS . get ( cl ) == null ) { LOADED_PLUGINS . put ( cl , new ClassesData ( ) ) ; } ClassesData cd = LOADED_PLUGINS . get ( cl ) ; Class clazz = cd . getClass ( className ) ; if ( clazz == null ) { clazz = cl . loadClass ( className ) ; saveClass ( cl , clazz ) ; } return clazz ; } | Returns a class object . If the class is new a new Class object is created otherwise the cached object is returned . | 125 | 23 |
21,859 | final Status evaluate ( final Metric metric ) { if ( metric == null || metric . getMetricValue ( ) == null ) { throw new NullPointerException ( "Metric value can't be null" ) ; } IThreshold thr = thresholdsMap . get ( metric . getMetricName ( ) ) ; if ( thr == null ) { return Status . OK ; } return thr . evaluate ( metric ) ; } | Evaluates the passed in metric against the threshold configured inside this evaluator . If the threshold do not refer the passed in metric then it is ignored and the next threshold is checked . | 89 | 38 |
21,860 | public final String executeSystemCommandAndGetOutput ( final String [ ] command , final String encoding ) throws IOException { Process p = Runtime . getRuntime ( ) . exec ( command ) ; StreamManager sm = new StreamManager ( ) ; try { InputStream input = sm . handle ( p . getInputStream ( ) ) ; StringBuffer lines = new StringBuffer ( ) ; String line ; BufferedReader in = ( BufferedReader ) sm . handle ( new BufferedReader ( new InputStreamReader ( input , encoding ) ) ) ; while ( ( line = in . readLine ( ) ) != null ) { lines . append ( line ) . append ( ' ' ) ; } return lines . toString ( ) ; } finally { sm . closeAll ( ) ; } } | Executes a system command with arguments and returns the output . | 162 | 12 |
21,861 | public synchronized Thread startThread ( String name ) throws IllegalThreadStateException { if ( ! running ) { log . info ( "[Daemon] {startThread} Starting thread " + name ) ; this . running = true ; thisThread = new Thread ( this , name ) ; thisThread . setDaemon ( shouldStartAsDaemon ( ) ) ; // Set whether we're a daemon thread (false by default) thisThread . start ( ) ; return thisThread ; } else { throw new IllegalThreadStateException ( "Daemon must be stopped before it may be started" ) ; } } | Starts this daemon creating a new thread for it | 123 | 10 |
21,862 | public synchronized void stopThread ( ) { if ( isRunning ( ) ) { if ( log . isInfoEnabled ( ) ) log . info ( "[Daemon] {stopThread} Requesting termination of thread " + thisThread . getName ( ) ) ; this . running = false ; synchronized ( this ) { this . notifyAll ( ) ; } } else { throw new IllegalThreadStateException ( "Daemon must be started before it may be stopped." ) ; } } | Requests the daemon terminate by setting a flag and sending an interrupt to the thread | 99 | 16 |
21,863 | @ Inject public void guiceSetupComplete ( ) { // Force us to re-register with guice-supplied values this . registered = false ; // Normally guice would call this but we must call it manually because the object was created manually postConstruct ( ) ; if ( onGuiceTakeover != null ) { onGuiceTakeover . run ( ) ; onGuiceTakeover = null ; } } | Called when Guice takes over this Daemon notifies the original constructor that the temporary services are no longer required | 87 | 23 |
21,864 | @ Override public void shutdown ( ) { // Stop the appender from delivering new messages to us ServiceManagerAppender . shutdown ( ) ; // Before shutting down synchronously transfer all the pending logs try { final LinkedList < LogLine > copy ; synchronized ( incoming ) { if ( ! incoming . isEmpty ( ) ) { // Take all the logs as they stand currently and forward them synchronously before shutdown copy = new LinkedList <> ( incoming ) ; incoming . clear ( ) ; } else { copy = null ; } } if ( copy != null ) { // Keep forwarding logs until we encounter an error (or run out of logs to forward) 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 | 241 | 6 |
21,865 | 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 | 93 | 9 |
21,866 | 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 | 64 | 9 |
21,867 | public final ReturnValue sendCommand ( final String sCommandName , final String ... arguments ) throws JNRPEClientException { return sendRequest ( new JNRPERequest ( sCommandName , arguments ) ) ; } | Inovoke a command installed in JNRPE . | 45 | 11 |
21,868 | 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 . | 95 | 6 |
21,869 | @ 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 ( ' ' ) ; } // DISPLAY SETTING Set displaySettings = hf . getDisplaySettings ( ) ; displaySettings . clear ( ) ; displaySettings . add ( DisplaySetting . DISPLAY_GROUP_EXPANDED ) ; displaySettings . add ( DisplaySetting . DISPLAY_PARENT_CHILDREN ) ; // USAGE SETTING 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 . | 323 | 16 |
21,870 | 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 | 49 | 9 |
21,871 | 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 | 121 | 5 |
21,872 | protected void configure ( ServletContainerDispatcher dispatcher ) throws ServletException { // Make sure we are registered with the Guice registry registry . register ( this , true ) ; // Configure the dispatcher 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 ( ) ; } // Register the REST provider classes for ( Class < ? > providerClass : ResteasyProviderRegistry . getClasses ( ) ) { log . debug ( "Registering REST providers: " + providerClass . getName ( ) ) ; providerFactory . registerProvider ( providerClass ) ; } // Register the REST provider singletons for ( Object provider : ResteasyProviderRegistry . getSingletons ( ) ) { log . debug ( "Registering REST provider singleton: " + provider ) ; providerFactory . registerProviderInstance ( provider ) ; } providerFactory . registerProviderInstance ( new LogReportMessageBodyReader ( ) ) ; // Register the JAXBContext provider providerFactory . registerProviderInstance ( jaxbContextResolver ) ; // Register the exception mapper { // Register the ExceptionMapper for ApplicationException providerFactory . register ( this . exceptionMapper ) ; log . trace ( "ExceptionMapper registered for ApplicationException" ) ; } // Register the REST resources 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 | 481 | 20 |
21,873 | 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 . | 72 | 7 |
21,874 | 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 | 120 | 6 |
21,875 | @ Deprecated 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 | 125 | 19 |
21,876 | 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 | 56 | 10 |
21,877 | 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 ; // all subfiles are equal } else { return true ; } } else { return false ; } } // Otherwise, the File objects are Files 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 ) ; } } // One is a directory and the other is not else { return false ; } } | Determines if 2 files or directories are equivalent by looking inside them | 318 | 14 |
21,878 | 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 | 72 | 3 |
21,879 | 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 . | 92 | 16 |
21,880 | 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 . | 88 | 16 |
21,881 | @ Override protected void onStart ( ) { m_serviceCollection = new ServiceCollection < T > ( m_context , m_serviceClass , new CollectionListener ( ) ) ; m_serviceCollection . start ( ) ; } | Creates a service collection and starts it . | 48 | 9 |
21,882 | @ Override protected void onStop ( ) { if ( m_serviceCollection != null ) { m_serviceCollection . stop ( ) ; m_serviceCollection = null ; } setService ( null ) ; } | Stops the service collection and releases resources . | 44 | 9 |
21,883 | public ProcessBuilder getProcessBuilder ( ) { if ( spawned ) return builder ; // throw new IllegalStateException("Cannot call spawn twice!"); 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 + "'" ) ; // Pass the environment in through an "env" 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 ) ; } // cmd.add(0,"env"); addToCmd ( 0 , "env" ) ; } // cmd.add(0, "--"); // doesn't work everywhere // cmd.add(0, runAs); // cmd.add(0, "-u"); // cmd.add(0, "-n"); // Never prompt for a password: we simply cannot provide one // cmd.add(0, "sudo"); if ( SudoFeature . hasArgumentsEnd ( ) ) addToCmd ( 0 , "--" ) ; // If possible tell sudo to run non-interactively 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 | 461 | 10 |
21,884 | 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 . | 68 | 6 |
21,885 | 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 . | 48 | 10 |
21,886 | 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 | 164 | 15 |
21,887 | 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 | 90 | 35 |
21,888 | 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 | 57 | 8 |
21,889 | 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 | 97 | 8 |
21,890 | 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 . | 216 | 12 |
21,891 | 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 | 131 | 8 |
21,892 | 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 ( ' ' ) ; 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 ( ' ' ) ; ++ 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 | 280 | 7 |
21,893 | 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 ( ) ) { // Should never happen... 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 . | 244 | 10 |
21,894 | private List < Metric > checkTablespace ( final Connection c , final ICommandLine cl ) throws BadThresholdException , SQLException { // Metric : tblspace_usage List < Metric > metricList = new ArrayList < Metric > ( ) ; String sTablespace = cl . getOptionValue ( "tablespace" ) . toUpperCase ( ) ; // FIXME : a prepared satement should be used 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 . | 422 | 5 |
21,895 | private List < Metric > checkCache ( final Connection c , final ICommandLine cl ) throws BadThresholdException , SQLException { List < Metric > metricList = new ArrayList < Metric > ( ) ; // Metrics cache_buf, cache_lib 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 . | 461 | 6 |
21,896 | @ Transactional public void rotateUserAccessKey ( final int id ) { final UserEntity account = getById ( id ) ; if ( account != null ) { // Set the secondary token to the old primary token account . setAccessKeySecondary ( account . getAccessKey ( ) ) ; // Now regenerate the primary token 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 | 120 | 24 |
21,897 | private String hashPassword ( String password ) { return BCrypt . hash ( password . toCharArray ( ) , BCrypt . DEFAULT_COST ) ; } | Creates a BCrypted hash for a password | 34 | 9 |
21,898 | 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 . | 115 | 8 |
21,899 | 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 | 165 | 17 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.