idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
200 | public void makePrivate ( ) { if ( getPublicMarkerFile ( ) . exists ( ) ) { if ( getPublicMarkerFile ( ) . delete ( ) ) { publicAccessCache . put ( getName ( ) , false ) ; } else { Storage . LOG . WARN ( "Failed to delete public marker for bucket %s - it remains public!" , getName ( ) ) ; } } } | Marks the bucket as private accessible . |
201 | public void makePublic ( ) { if ( ! getPublicMarkerFile ( ) . exists ( ) ) { try { new FileOutputStream ( getPublicMarkerFile ( ) ) . close ( ) ; } catch ( IOException e ) { throw Exceptions . handle ( Storage . LOG , e ) ; } } publicAccessCache . put ( getName ( ) , true ) ; } | Marks the bucket as public accessible . |
202 | public StoredObject getObject ( String id ) { if ( id . contains ( ".." ) || id . contains ( "/" ) || id . contains ( "\\" ) ) { throw Exceptions . createHandled ( ) . withSystemErrorMessage ( "Invalid object name: %s. A object name must not contain '..' '/' or '\\'" , id ) . handle ( ) ; } return new StoredObject ( new File ( file , id ) ) ; } | Returns the child object with the given id . |
203 | public void start ( ) { if ( layout == null ) { initializationFailed = true ; addError ( "Invalid configuration - No layout for appender: " + name ) ; return ; } if ( streamName == null ) { initializationFailed = true ; addError ( "Invalid configuration - streamName cannot be null for appender: " + name ) ; return ; } ClientConfiguration clientConfiguration = new ClientConfiguration ( ) ; clientConfiguration . setMaxErrorRetry ( maxRetries ) ; clientConfiguration . setRetryPolicy ( new RetryPolicy ( PredefinedRetryPolicies . DEFAULT_RETRY_CONDITION , PredefinedRetryPolicies . DEFAULT_BACKOFF_STRATEGY , maxRetries , true ) ) ; clientConfiguration . setUserAgent ( AppenderConstants . USER_AGENT_STRING ) ; BlockingQueue < Runnable > taskBuffer = new LinkedBlockingDeque < Runnable > ( bufferSize ) ; threadPoolExecutor = new ThreadPoolExecutor ( threadCount , threadCount , AppenderConstants . DEFAULT_THREAD_KEEP_ALIVE_SEC , TimeUnit . SECONDS , taskBuffer , setupThreadFactory ( ) , new BlockFastProducerPolicy ( ) ) ; threadPoolExecutor . prestartAllCoreThreads ( ) ; this . client = createClient ( credentials , clientConfiguration , threadPoolExecutor ) ; client . setRegion ( findRegion ( ) ) ; if ( ! Validator . isBlank ( endpoint ) ) { if ( ! Validator . isBlank ( region ) ) { addError ( "Received configuration for both region as well as Amazon Kinesis endpoint. (" + endpoint + ") will be used as endpoint instead of default endpoint for region (" + region + ")" ) ; } client . setEndpoint ( endpoint ) ; } validateStreamName ( client , streamName ) ; super . start ( ) ; } | Configures appender instance and makes it ready for use by the consumers . It validates mandatory parameters and confirms if the configured stream is ready for publishing data yet . |
204 | public void stop ( ) { threadPoolExecutor . shutdown ( ) ; BlockingQueue < Runnable > taskQueue = threadPoolExecutor . getQueue ( ) ; int bufferSizeBeforeShutdown = threadPoolExecutor . getQueue ( ) . size ( ) ; boolean gracefulShutdown = true ; try { gracefulShutdown = threadPoolExecutor . awaitTermination ( shutdownTimeout , TimeUnit . SECONDS ) ; } catch ( InterruptedException e ) { } finally { int bufferSizeAfterShutdown = taskQueue . size ( ) ; if ( ! gracefulShutdown || bufferSizeAfterShutdown > 0 ) { String errorMsg = "Kinesis Log4J Appender (" + name + ") waited for " + shutdownTimeout + " seconds before terminating but could send only " + ( bufferSizeAfterShutdown - bufferSizeBeforeShutdown ) + " logevents, it failed to send " + bufferSizeAfterShutdown + " pending log events from it's processing queue" ; addError ( errorMsg ) ; } } client . shutdown ( ) ; } | Closes this appender instance . Before exiting the implementation tries to flush out buffered log events within configured shutdownTimeout seconds . If that doesn t finish within configured shutdownTimeout it would drop all the buffered log events . |
205 | private Region findRegion ( ) { boolean regionProvided = ! Validator . isBlank ( this . region ) ; if ( ! regionProvided ) { Region currentRegion = Regions . getCurrentRegion ( ) ; if ( currentRegion != null ) { return currentRegion ; } return Region . getRegion ( Regions . fromName ( AppenderConstants . DEFAULT_REGION ) ) ; } return Region . getRegion ( Regions . fromName ( this . region ) ) ; } | Determine region . If not specified tries to determine region from where the application is running or fall back to the default . |
206 | public void setStreamName ( String streamName ) { Validator . validate ( ! Validator . isBlank ( streamName ) , "streamName cannot be blank" ) ; this . streamName = streamName . trim ( ) ; } | Sets streamName for the kinesis stream to which data is to be published . |
207 | public void setEncoding ( String charset ) { Validator . validate ( ! Validator . isBlank ( charset ) , "encoding cannot be blank" ) ; this . encoding = charset . trim ( ) ; } | Sets encoding for the data to be published . If none specified default is UTF - 8 |
208 | @ SuppressWarnings ( "unchecked" ) public < T > T getProperty ( String key , Class < T > cls ) { if ( properties != null ) { if ( cls != null && cls != Object . class && cls != String . class && ! cls . isInterface ( ) && ! cls . isArray ( ) ) { key = key + "=" + cls . getName ( ) ; } Object value = properties . get ( key ) ; if ( value != null ) { if ( cls == String . class && value . getClass ( ) != String . class ) { return ( T ) value . getClass ( ) . getName ( ) ; } return ( T ) value ; } } return null ; } | Get config instantiated value . |
209 | public Map < String , Object > createContext ( final Map < String , Object > parent , Map < String , Object > current ) { return new DelegateMap < String , Object > ( parent , current ) { private static final long serialVersionUID = 1L ; public Object get ( Object key ) { Object value = super . get ( key ) ; if ( value == null && parent == null && resolver != null ) { return resolver . get ( ( String ) key ) ; } return value ; } } ; } | Create context map . |
210 | public Template parseTemplate ( String source , Object parameterTypes ) throws ParseException { String name = "/$" + Digest . getMD5 ( source ) ; if ( ! hasResource ( name ) ) { stringLoader . add ( name , source ) ; } try { return getTemplate ( name , parameterTypes ) ; } catch ( IOException e ) { throw new IllegalStateException ( e . getMessage ( ) , e ) ; } } | Parse string template . |
211 | public Resource getResource ( String name , Locale locale , String encoding ) throws IOException { name = UrlUtils . cleanName ( name ) ; locale = cleanLocale ( locale ) ; return loadResource ( name , locale , encoding ) ; } | Get resource . |
212 | public boolean hasResource ( String name , Locale locale ) { name = UrlUtils . cleanName ( name ) ; locale = cleanLocale ( locale ) ; return stringLoader . exists ( name , locale ) || loader . exists ( name , locale ) ; } | Tests whether the resource denoted by this abstract pathname exists . |
213 | public void init ( ) { if ( logger != null && StringUtils . isNotEmpty ( name ) ) { if ( logger . isWarnEnabled ( ) && ! ConfigUtils . isFilePath ( name ) ) { try { List < String > realPaths = new ArrayList < String > ( ) ; Enumeration < URL > e = Thread . currentThread ( ) . getContextClassLoader ( ) . getResources ( name ) ; while ( e . hasMoreElements ( ) ) { URL url = ( URL ) e . nextElement ( ) ; realPaths . add ( url . getFile ( ) ) ; } if ( realPaths . size ( ) > 1 ) { logger . warn ( "Multi httl config in classpath, conflict configs: " + realPaths + ". Please keep only one config." ) ; } } catch ( IOException e ) { logger . error ( e . getMessage ( ) , e ) ; } } if ( logger . isInfoEnabled ( ) ) { String realPath = ConfigUtils . getRealPath ( name ) ; if ( StringUtils . isNotEmpty ( realPath ) ) { logger . info ( "Load httl config from " + realPath + " in " + ( name . startsWith ( "/" ) ? "filesystem" : "classpath" ) + "." ) ; } } } } | Init the engine . |
214 | public void inited ( ) { if ( preload ) { try { int count = 0 ; if ( templateSuffix == null ) { templateSuffix = new String [ ] { ".httl" } ; } for ( String suffix : templateSuffix ) { List < String > list = loader . list ( suffix ) ; if ( list == null ) { continue ; } count += list . size ( ) ; for ( String name : list ) { try { if ( logger != null && logger . isDebugEnabled ( ) ) { logger . debug ( "Preload the template: " + name ) ; } getTemplate ( name , getDefaultEncoding ( ) ) ; } catch ( Exception e ) { if ( logger != null && logger . isErrorEnabled ( ) ) { logger . error ( e . getMessage ( ) , e ) ; } } } } if ( logger != null && logger . isInfoEnabled ( ) ) { logger . info ( "Preload " + count + " templates from directory " + ( templateDirectory == null ? "/" : templateDirectory ) + " with suffix " + Arrays . toString ( templateSuffix ) ) ; } } catch ( Exception e ) { if ( logger != null && logger . isErrorEnabled ( ) ) { logger . error ( e . getMessage ( ) , e ) ; } } } } | On all inited . |
215 | public JSONWriter objectBegin ( ) throws IOException { beforeValue ( ) ; writer . write ( JSON . LBRACE ) ; stack . push ( state ) ; state = new State ( OBJECT ) ; return this ; } | object begin . |
216 | public JSONWriter objectEnd ( ) throws IOException { writer . write ( JSON . RBRACE ) ; state = stack . pop ( ) ; return this ; } | object end . |
217 | public JSONWriter objectItem ( String name ) throws IOException { beforeObjectItem ( ) ; writer . write ( JSON . QUOTE ) ; writer . write ( escape ( name ) ) ; writer . write ( JSON . QUOTE ) ; writer . write ( JSON . COLON ) ; return this ; } | object item . |
218 | public JSONWriter arrayBegin ( ) throws IOException { beforeValue ( ) ; writer . write ( JSON . LSQUARE ) ; stack . push ( state ) ; state = new State ( ARRAY ) ; return this ; } | array begin . |
219 | public JSONWriter arrayEnd ( ) throws IOException { writer . write ( JSON . RSQUARE ) ; state = stack . pop ( ) ; return this ; } | array end return array value . |
220 | public MultiFormatter add ( Formatter < ? > ... formatters ) { if ( formatter != null ) { MultiFormatter copy = new MultiFormatter ( ) ; copy . formatters . putAll ( this . formatters ) ; copy . setFormatters ( formatters ) ; return copy ; } return this ; } | Add and copy the MultiFormatter . |
221 | public MultiFormatter remove ( Formatter < ? > ... formatters ) { if ( formatter != null ) { MultiFormatter copy = new MultiFormatter ( ) ; copy . formatters . putAll ( this . formatters ) ; if ( formatters != null && formatters . length > 0 ) { for ( Formatter < ? > formatter : formatters ) { if ( formatter != null ) { Class < ? > type = ClassUtils . getGenericClass ( formatter . getClass ( ) ) ; if ( type != null ) { this . formatters . remove ( type ) ; } } } } return copy ; } return this ; } | Remove and copy the MultiFormatter . |
222 | public static Properties loadProperties ( String path , boolean required ) { Properties properties = new Properties ( ) ; return loadProperties ( properties , path , required ) ; } | Load properties file |
223 | public static String json ( Object obj , boolean writeClass , Converter < Object , Map < String , Object > > mc ) throws IOException { if ( obj == null ) return NULL ; StringWriter sw = new StringWriter ( ) ; try { json ( obj , sw , writeClass , mc ) ; return sw . getBuffer ( ) . toString ( ) ; } finally { sw . close ( ) ; } } | json string . |
224 | void tryToDrainBuffers ( ) { if ( evictionLock . tryLock ( ) ) { try { drainStatus . set ( PROCESSING ) ; drainBuffers ( ) ; } finally { drainStatus . compareAndSet ( PROCESSING , IDLE ) ; evictionLock . unlock ( ) ; } } } | Attempts to acquire the eviction lock and apply the pending operations up to the amortized threshold to the page replacement policy . |
225 | void drainBuffers ( ) { int maxTaskIndex = moveTasksFromBuffers ( tasks ) ; updateDrainedOrder ( tasks , maxTaskIndex ) ; runTasks ( tasks , maxTaskIndex ) ; } | Drains the buffers up to the amortized threshold and applies the pending operations . |
226 | int moveTasksFromBuffers ( Task [ ] tasks ) { int maxTaskIndex = - 1 ; for ( int i = 0 ; i < buffers . length ; i ++ ) { int maxIndex = moveTasksFromBuffer ( tasks , i ) ; maxTaskIndex = Math . max ( maxIndex , maxTaskIndex ) ; } return maxTaskIndex ; } | Moves the tasks from the buffers into the output array . |
227 | int moveTasksFromBuffer ( Task [ ] tasks , int bufferIndex ) { Queue < Task > buffer = buffers [ bufferIndex ] ; int removedFromBuffer = 0 ; Task task ; int maxIndex = - 1 ; while ( ( task = buffer . poll ( ) ) != null ) { removedFromBuffer ++ ; int index = task . getOrder ( ) - drainedOrder ; if ( index < 0 ) { task . run ( ) ; } else if ( index >= tasks . length ) { maxIndex = tasks . length - 1 ; addTaskToChain ( tasks , task , maxIndex ) ; break ; } else { maxIndex = Math . max ( index , maxIndex ) ; addTaskToChain ( tasks , task , index ) ; } } bufferLengths . addAndGet ( bufferIndex , - removedFromBuffer ) ; return maxIndex ; } | Moves the tasks from the specified buffer into the output array . |
228 | void addTaskToChain ( Task [ ] tasks , Task task , int index ) { task . setNext ( tasks [ index ] ) ; tasks [ index ] = task ; } | Adds the task as the head of the chain at the index location . |
229 | void updateDrainedOrder ( Task [ ] tasks , int maxTaskIndex ) { if ( maxTaskIndex >= 0 ) { Task task = tasks [ maxTaskIndex ] ; drainedOrder = task . getOrder ( ) + 1 ; } } | Updates the order to start the next drain from . |
230 | V put ( K key , V value , boolean onlyIfAbsent ) { checkNotNull ( key ) ; checkNotNull ( value ) ; final int weight = weigher . weightOf ( key , value ) ; final WeightedValue < V > weightedValue = new WeightedValue < V > ( value , weight ) ; final Node node = new Node ( key , weightedValue ) ; for ( ; ; ) { final Node prior = data . putIfAbsent ( node . key , node ) ; if ( prior == null ) { afterCompletion ( new AddTask ( node , weight ) ) ; return null ; } else if ( onlyIfAbsent ) { afterCompletion ( new ReadTask ( prior ) ) ; return prior . getValue ( ) ; } for ( ; ; ) { final WeightedValue < V > oldWeightedValue = prior . get ( ) ; if ( ! oldWeightedValue . isAlive ( ) ) { break ; } if ( prior . compareAndSet ( oldWeightedValue , weightedValue ) ) { final int weightedDifference = weight - oldWeightedValue . weight ; final Task task = ( weightedDifference == 0 ) ? new ReadTask ( prior ) : new UpdateTask ( prior , weightedDifference ) ; afterCompletion ( task ) ; return oldWeightedValue . value ; } } } } | Adds a node to the list and the data store . If an existing node is found then its value is updated if allowed . |
231 | public static Engine getEngine ( String configPath , Properties configProperties ) { if ( StringUtils . isEmpty ( configPath ) ) { configPath = HTTL_PROPERTIES ; } VolatileReference < Engine > reference = ENGINES . get ( configPath ) ; if ( reference == null ) { reference = new VolatileReference < Engine > ( ) ; VolatileReference < Engine > old = ENGINES . putIfAbsent ( configPath , reference ) ; if ( old != null ) { reference = old ; } } assert ( reference != null ) ; Engine engine = reference . get ( ) ; if ( engine == null ) { synchronized ( reference ) { engine = reference . get ( ) ; if ( engine == null ) { engine = BeanFactory . createBean ( Engine . class , initProperties ( configPath , configProperties ) ) ; reference . set ( engine ) ; } } } assert ( engine != null ) ; return engine ; } | Get template engine singleton . |
232 | public String getProperty ( String key , String defaultValue ) { String value = getProperty ( key , String . class ) ; return StringUtils . isEmpty ( value ) ? defaultValue : value ; } | Get config value . |
233 | public int getProperty ( String key , int defaultValue ) { String value = getProperty ( key , String . class ) ; return StringUtils . isEmpty ( value ) ? defaultValue : Integer . parseInt ( value ) ; } | Get config int value . |
234 | public boolean getProperty ( String key , boolean defaultValue ) { String value = getProperty ( key , String . class ) ; return StringUtils . isEmpty ( value ) ? defaultValue : Boolean . parseBoolean ( value ) ; } | Get config boolean value . |
235 | private void processInput ( boolean endOfInput ) throws IOException { decoderIn . flip ( ) ; CoderResult coderResult ; while ( true ) { coderResult = decoder . decode ( decoderIn , decoderOut , endOfInput ) ; if ( coderResult . isOverflow ( ) ) { flushOutput ( ) ; } else if ( coderResult . isUnderflow ( ) ) { break ; } else { throw new IOException ( "Unexpected coder result" ) ; } } decoderIn . compact ( ) ; } | Decode the contents of the input ByteBuffer into a CharBuffer . |
236 | private void flushOutput ( ) throws IOException { if ( decoderOut . position ( ) > 0 ) { writer . write ( decoderOut . array ( ) , 0 , decoderOut . position ( ) ) ; decoderOut . rewind ( ) ; } } | Flush the output . |
237 | public static Context getContext ( ) { Context context = LOCAL . get ( ) ; if ( context == null ) { context = new Context ( null , null ) ; LOCAL . set ( context ) ; } return context ; } | Get the current context from thread local . |
238 | public static Context pushContext ( Map < String , Object > current ) { Context context = new Context ( getContext ( ) , current ) ; LOCAL . set ( context ) ; return context ; } | Push the current context to thread local . |
239 | public static void popContext ( ) { Context context = LOCAL . get ( ) ; if ( context != null ) { Context parent = context . getParent ( ) ; if ( parent != null ) { LOCAL . set ( parent ) ; } else { LOCAL . remove ( ) ; } } } | Pop the current context from thread local and restore parent context to thread local . |
240 | private void checkThread ( ) { if ( Thread . currentThread ( ) != thread ) { throw new IllegalStateException ( "Don't cross-thread using the " + Context . class . getName ( ) + " object, it's thread-local only. context thread: " + thread . getName ( ) + ", current thread: " + Thread . currentThread ( ) . getName ( ) ) ; } } | Check the cross - thread use . |
241 | private void setCurrent ( Map < String , Object > current ) { if ( current instanceof Context ) { throw new IllegalArgumentException ( "Don't using the " + Context . class . getName ( ) + " object as a parameters, it's implicitly delivery by thread-local. parameter context: " + ( ( Context ) current ) . thread . getName ( ) + ", current context: " + thread . getName ( ) ) ; } this . current = current ; } | Set the current context |
242 | public Context setTemplate ( Template template ) { checkThread ( ) ; if ( template != null ) { setEngine ( template . getEngine ( ) ) ; } this . template = template ; return this ; } | Set the current template . |
243 | public Context setEngine ( Engine engine ) { checkThread ( ) ; if ( engine != null ) { if ( template != null && template . getEngine ( ) != engine ) { throw new IllegalStateException ( "Failed to set the context engine, because is not the same to template engine. template engine: " + template . getEngine ( ) . getName ( ) + ", context engine: " + engine . getName ( ) + ", template: " + template . getName ( ) + ", context: " + thread . getName ( ) ) ; } if ( parent != null && parent . getEngine ( ) != engine ) { parent . setEngine ( engine ) ; } if ( this . engine == null ) { setCurrent ( engine . createContext ( parent , current ) ) ; } } this . engine = engine ; return this ; } | Set the current engine . |
244 | public Object get ( String key , Object defaultValue ) { Object value = get ( key ) ; return value == null ? defaultValue : value ; } | Get the variable value . |
245 | public static boolean showRateDialogIfNeeded ( final Context context , int themeId ) { if ( shouldShowRateDialog ( ) ) { showRateDialog ( context , themeId ) ; return true ; } else { return false ; } } | Show the rate dialog if the criteria is satisfied . |
246 | public static boolean shouldShowRateDialog ( ) { if ( mOptOut ) { return false ; } else { if ( mLaunchTimes >= sConfig . mCriteriaLaunchTimes ) { return true ; } long threshold = TimeUnit . DAYS . toMillis ( sConfig . mCriteriaInstallDays ) ; if ( new Date ( ) . getTime ( ) - mInstallDate . getTime ( ) >= threshold && new Date ( ) . getTime ( ) - mAskLaterDate . getTime ( ) >= threshold ) { return true ; } return false ; } } | Check whether the rate dialog should be shown or not . Developers may call this method directly if they want to show their own view instead of dialog provided by this library . |
247 | public static void showRateDialog ( final Context context ) { AlertDialog . Builder builder = new AlertDialog . Builder ( context ) ; showRateDialog ( context , builder ) ; } | Show the rate dialog |
248 | public static int getLaunchCount ( final Context context ) { SharedPreferences pref = context . getSharedPreferences ( PREF_NAME , Context . MODE_PRIVATE ) ; return pref . getInt ( KEY_LAUNCH_TIMES , 0 ) ; } | Get count number of the rate dialog launches |
249 | private static void storeInstallDate ( final Context context , SharedPreferences . Editor editor ) { Date installDate = new Date ( ) ; if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . GINGERBREAD ) { PackageManager packMan = context . getPackageManager ( ) ; try { PackageInfo pkgInfo = packMan . getPackageInfo ( context . getPackageName ( ) , 0 ) ; installDate = new Date ( pkgInfo . firstInstallTime ) ; } catch ( PackageManager . NameNotFoundException e ) { e . printStackTrace ( ) ; } } editor . putLong ( KEY_INSTALL_DATE , installDate . getTime ( ) ) ; log ( "First install: " + installDate . toString ( ) ) ; } | Store install date . Install date is retrieved from package manager if possible . |
250 | private static void storeAskLaterDate ( final Context context ) { SharedPreferences pref = context . getSharedPreferences ( PREF_NAME , Context . MODE_PRIVATE ) ; Editor editor = pref . edit ( ) ; editor . putLong ( KEY_ASK_LATER_DATE , System . currentTimeMillis ( ) ) ; editor . apply ( ) ; } | Store the date the user asked for being asked again later . |
251 | public static < T extends Pane > CompletionStage < T > setContent ( final T parent , final Node content ) { return FxAsync . doOnFxThread ( parent , parentNode -> { parentNode . getChildren ( ) . clear ( ) ; parentNode . getChildren ( ) . add ( content ) ; } ) ; } | Sets as the sole content of a pane another Node . This is supposed to work as having a first Pane being the wanted display zone and the second Node the displayed content . |
252 | public static CompletionStage < Stage > displayExceptionPane ( final String title , final String readable , final Throwable exception ) { final Pane exceptionPane = new ExceptionHandler ( exception ) . asPane ( readable ) ; final CompletionStage < Stage > exceptionStage = Stages . stageOf ( title , exceptionPane ) ; return exceptionStage . thenCompose ( Stages :: scheduleDisplaying ) ; } | Creates a pop - up and displays it based on a given exception pop - up title and custom error message . |
253 | public static CompletionStage < Stage > stageOf ( final String title , final Pane rootPane ) { return FxAsync . computeOnFxThread ( Tuple . of ( title , rootPane ) , titleAndPane -> { final Stage stage = new Stage ( StageStyle . DECORATED ) ; stage . setTitle ( title ) ; stage . setScene ( new Scene ( rootPane ) ) ; return stage ; } ) ; } | Creates a Stage . |
254 | public static CompletionStage < Stage > scheduleDisplaying ( final Stage stage ) { LOG . debug ( "Requested displaying of stage {} with title : \"{}\"" , stage , stage . getTitle ( ) ) ; return FxAsync . doOnFxThread ( stage , Stage :: show ) ; } | Schedules a stage for displaying . |
255 | public static CompletionStage < Stage > scheduleHiding ( final Stage stage ) { LOG . debug ( "Requested hiding of stage {} with title : \"{}\"" , stage , stage . getTitle ( ) ) ; return FxAsync . doOnFxThread ( stage , Stage :: hide ) ; } | Schedules a stage for hiding |
256 | public static CompletionStage < Stage > setStylesheet ( final Stage stage , final String stylesheet ) { LOG . info ( "Setting stylesheet {} for stage {}({})" , stylesheet , stage . toString ( ) , stage . getTitle ( ) ) ; return FxAsync . doOnFxThread ( stage , theStage -> { final Scene stageScene = theStage . getScene ( ) ; stageScene . getStylesheets ( ) . clear ( ) ; stageScene . getStylesheets ( ) . add ( stylesheet ) ; } ) ; } | Boilerplate for setting the stylesheet of a given stage via Java rather than FXML . |
257 | public static < T > CompletionStage < T > doOnFxThread ( final T element , final Consumer < T > action ) { return CompletableFuture . supplyAsync ( ( ) -> { action . accept ( element ) ; return element ; } , Platform :: runLater ) ; } | Asynchronously executes a consuming operation on the JavaFX thread . |
258 | public static < T , U > CompletionStage < U > computeOnFxThread ( final T element , final Function < T , U > compute ) { return CompletableFuture . supplyAsync ( ( ) -> compute . apply ( element ) , Platform :: runLater ) ; } | Asynchronously executes a computing operation on the JavaFX thread . |
259 | public static String capitalise ( String text ) { if ( empty ( text ) ) { return "" ; } return text . substring ( 0 , 1 ) . toUpperCase ( ) + text . substring ( 1 ) ; } | Capitalise the given text |
260 | public void startAsync ( ) { Thread thread = new Thread ( new Runnable ( ) { public void run ( ) { try { start ( ) ; } catch ( Exception e ) { LOG . error ( "Failed to connect to kubernetes: " + e , e ) ; } } } , "Jenkins X PipelineClient Thread" ) ; thread . start ( ) ; } | Starts listening in a background thread to avoid blocking the calling thread |
261 | public void start ( ) { doClose ( ) ; Watcher < PipelineActivity > listener = new Watcher < PipelineActivity > ( ) { public void eventReceived ( Action action , PipelineActivity pipelineActivity ) { onEventReceived ( action , pipelineActivity ) ; } public void onClose ( KubernetesClientException e ) { LOG . warn ( "Pipeline watcher is closed: " + e , e ) ; for ( Watcher < PipelineActivity > listener : listeners ) { listener . onClose ( e ) ; } } } ; this . watcher = this . pipelines . watch ( listener ) ; PipelineActivityList list = this . pipelines . list ( ) ; if ( list != null ) { List < PipelineActivity > items = list . getItems ( ) ; if ( items != null ) { for ( PipelineActivity item : items ) { onEventReceived ( Watcher . Action . ADDED , item ) ; } } } } | Starts listing and watching the pipelines in the namespace and firing events . |
262 | public static boolean isNewer ( HasMetadata newer , HasMetadata older ) { long n1 = parseResourceVersion ( newer ) ; long n2 = parseResourceVersion ( older ) ; return n1 >= n2 ; } | Returns true if the first parameter is newer than the second |
263 | public static long parseResourceVersion ( HasMetadata obj ) { ObjectMeta metadata = obj . getMetadata ( ) ; if ( metadata != null ) { String resourceVersion = metadata . getResourceVersion ( ) ; if ( notEmpty ( resourceVersion ) ) { try { return Long . parseLong ( resourceVersion ) ; } catch ( NumberFormatException e ) { } } } return 0 ; } | Returns the numeric resource version of the resource |
264 | public static String getPullRequestName ( String prUrl ) { if ( notEmpty ( prUrl ) ) { int idx = prUrl . lastIndexOf ( "/" ) ; if ( idx > 0 ) { return " #" + prUrl . substring ( idx + 1 ) ; } } return "" ; } | Returns the Pull Request name from the given URL prefixed with space or an empty string if there is no URL |
265 | public static String convertToKubernetesName ( String text , boolean allowDots ) { String lower = text . toLowerCase ( ) ; StringBuilder builder = new StringBuilder ( ) ; boolean started = false ; char lastCh = ' ' ; for ( int i = 0 , last = lower . length ( ) - 1 ; i <= last ; i ++ ) { char ch = lower . charAt ( i ) ; boolean digit = ch >= '0' && ch <= '9' ; if ( digit && builder . length ( ) == 0 ) { builder . append ( DIGIT_PREFIX ) ; } if ( ! ( ch >= 'a' && ch <= 'z' ) && ! digit ) { if ( ch == '/' ) { ch = '.' ; } else if ( ch != '.' && ch != '-' ) { ch = '-' ; } if ( ! allowDots && ch == '.' ) { ch = '-' ; } if ( ! started || lastCh == '-' || lastCh == '.' || i == last ) { continue ; } } builder . append ( ch ) ; started = true ; lastCh = ch ; } return builder . toString ( ) ; } | Lets convert the string to btw a valid kubernetes resource name |
266 | protected final SerializerFactory findSerializerFactory ( ) { SerializerFactory factory = _serializerFactory ; if ( factory == null ) { factory = SerializerFactory . createDefault ( ) ; _defaultSerializerFactory = factory ; _serializerFactory = factory ; } return factory ; } | Gets the serializer factory . |
267 | public Object readObject ( ) throws IOException { _is . startPacket ( ) ; Object obj = _in . readStreamingObject ( ) ; _is . endPacket ( ) ; return obj ; } | Read the next object |
268 | public void init ( OutputStream os ) { this . os = os ; _refs = null ; if ( _serializerFactory == null ) _serializerFactory = new SerializerFactory ( ) ; } | Initializes the output |
269 | public void writeRemote ( String type , String url ) throws IOException { os . write ( 'r' ) ; os . write ( 't' ) ; printLenString ( type ) ; os . write ( 'S' ) ; printLenString ( url ) ; } | Writes a remote object reference to the stream . The type is the type of the remote interface . |
270 | public boolean removeRef ( Object obj ) throws IOException { if ( _refs != null ) { _refs . remove ( obj ) ; return true ; } else return false ; } | Removes a reference . |
271 | public boolean readRequest ( MuxInputStream in , MuxOutputStream out ) throws IOException { int channel = isClient ? 3 : 2 ; in . init ( this , channel ) ; out . init ( this , channel ) ; if ( readChannel ( channel ) != null ) { in . setInputStream ( is ) ; in . readToData ( false ) ; return true ; } else return false ; } | Reads a server request . |
272 | OutputStream writeChannel ( int channel ) throws IOException { while ( os != null ) { boolean canWrite = false ; synchronized ( WRITE_LOCK ) { if ( ! isWriteLocked ) { isWriteLocked = true ; canWrite = true ; } else { try { WRITE_LOCK . wait ( 5000 ) ; } catch ( Exception e ) { } } } if ( canWrite ) { os . write ( 'C' ) ; os . write ( channel >> 8 ) ; os . write ( channel ) ; return os ; } } return null ; } | Grabs the channel for writing . |
273 | InputStream readChannel ( int channel ) throws IOException { while ( ! isClosed ) { if ( inputReady [ channel ] ) { inputReady [ channel ] = false ; return is ; } boolean canRead = false ; synchronized ( READ_LOCK ) { if ( ! isReadLocked ) { isReadLocked = true ; canRead = true ; } else { try { READ_LOCK . wait ( 5000 ) ; } catch ( Exception e ) { } } } if ( canRead ) { try { readData ( ) ; } catch ( IOException e ) { close ( ) ; } } } return null ; } | Reads data from a channel . |
274 | private void readData ( ) throws IOException { while ( ! isClosed ) { int code = is . read ( ) ; switch ( code ) { case ' ' : case '\t' : case '\n' : case '\r' : break ; case 'C' : { int channel = ( is . read ( ) << 8 ) + is . read ( ) ; inputReady [ channel ] = true ; return ; } case 'E' : { int channel = ( is . read ( ) << 8 ) + is . read ( ) ; int status = ( is . read ( ) << 8 ) + is . read ( ) ; inputReady [ channel ] = true ; return ; } case - 1 : close ( ) ; return ; default : close ( ) ; return ; } } return ; } | Reads data until a channel packet C or error E is received . |
275 | public void close ( ) throws IOException { isClosed = true ; OutputStream os = this . os ; this . os = null ; InputStream is = this . is ; this . is = null ; if ( os != null ) os . close ( ) ; if ( is != null ) is . close ( ) ; } | Close the mux |
276 | public static ClassNameResolver buildDefault ( ) { String enable = System . getProperty ( Constants . SERIALIZE_BLACKLIST_ENABLE , Constants . DEFAULT_SERIALIZE_BLACKLIST_ENABLE ) ; if ( Boolean . TRUE . toString ( ) . equalsIgnoreCase ( enable ) ) { ClassNameResolver resolver = new ClassNameResolver ( ) ; resolver . addFilter ( new InternalNameBlackListFilter ( ) ) ; return resolver ; } return null ; } | Build default ClassNameResolver |
277 | private boolean schedule ( Task task ) { int index = bufferIndex ( ) ; int buffered = bufferLengths . incrementAndGet ( index ) ; if ( task . isWrite ( ) ) { buffers [ index ] . add ( task ) ; drainStatus . set ( REQUIRED ) ; return false ; } if ( buffered <= MAXIMUM_BUFFER_SIZE ) { buffers [ index ] . add ( task ) ; return ( buffered <= BUFFER_THRESHOLD ) ; } else { bufferLengths . decrementAndGet ( index ) ; return false ; } } | Schedules the task to be applied to the page replacement policy . |
278 | boolean shouldDrainBuffers ( boolean delayable ) { if ( executor . isShutdown ( ) ) { DrainStatus status = drainStatus . get ( ) ; return ( status != PROCESSING ) && ( ! delayable || ( status == REQUIRED ) ) ; } return false ; } | Determines whether the buffers should be drained . |
279 | @ GuardedBy ( "evictionLock" ) void drainBuffers ( int maxToDrain ) { Task [ ] tasks = new Task [ maxToDrain ] ; int maxTaskIndex = moveTasksFromBuffers ( tasks ) ; runTasks ( tasks , maxTaskIndex ) ; updateDrainedOrder ( tasks , maxTaskIndex ) ; } | Drains the buffers and applies the pending operations . |
280 | @ GuardedBy ( "evictionLock" ) void runTasksInChain ( Task task ) { while ( task != null ) { Task current = task ; task = task . getNext ( ) ; current . setNext ( null ) ; current . run ( ) ; } } | Runs the pending operations on the linked chain . |
281 | protected String readStringImpl ( int length ) throws IOException { StringBuffer sb = new StringBuffer ( ) ; for ( int i = 0 ; i < length ; i ++ ) { int ch = is . read ( ) ; if ( ch < 0x80 ) sb . append ( ( char ) ch ) ; else if ( ( ch & 0xe0 ) == 0xc0 ) { int ch1 = is . read ( ) ; int v = ( ( ch & 0x1f ) << 6 ) + ( ch1 & 0x3f ) ; sb . append ( ( char ) v ) ; } else if ( ( ch & 0xf0 ) == 0xe0 ) { int ch1 = is . read ( ) ; int ch2 = is . read ( ) ; int v = ( ( ch & 0x0f ) << 12 ) + ( ( ch1 & 0x3f ) << 6 ) + ( ch2 & 0x3f ) ; sb . append ( ( char ) v ) ; } else throw new IOException ( "bad utf-8 encoding" ) ; } return sb . toString ( ) ; } | Reads a string from the underlying stream . |
282 | public void startEnvelope ( String method ) throws IOException { int offset = _offset ; if ( SIZE < offset + 32 ) { flushBuffer ( ) ; offset = _offset ; } _buffer [ _offset ++ ] = ( byte ) 'E' ; writeString ( method ) ; } | Starts an envelope . |
283 | public int writeObjectBegin ( String type ) throws IOException { int newRef = _classRefs . size ( ) ; int ref = _classRefs . put ( type , newRef , false ) ; if ( newRef != ref ) { if ( SIZE < _offset + 32 ) flushBuffer ( ) ; if ( ref <= OBJECT_DIRECT_MAX ) { _buffer [ _offset ++ ] = ( byte ) ( BC_OBJECT_DIRECT + ref ) ; } else { _buffer [ _offset ++ ] = ( byte ) 'O' ; writeInt ( ref ) ; } return ref ; } else { if ( SIZE < _offset + 32 ) flushBuffer ( ) ; _buffer [ _offset ++ ] = ( byte ) 'C' ; writeString ( type ) ; return - 1 ; } } | Writes the object definition |
284 | public void writeNull ( ) throws IOException { int offset = _offset ; byte [ ] buffer = _buffer ; if ( SIZE <= offset + 16 ) { flushBuffer ( ) ; offset = _offset ; } buffer [ offset ++ ] = 'N' ; _offset = offset ; } | Writes a null value to the stream . The null will be written with the following syntax |
285 | public void writeByteStream ( InputStream is ) throws IOException { while ( true ) { int len = SIZE - _offset - 3 ; if ( len < 16 ) { flushBuffer ( ) ; len = SIZE - _offset - 3 ; } len = is . read ( _buffer , _offset + 3 , len ) ; if ( len <= 0 ) { _buffer [ _offset ++ ] = BC_BINARY_DIRECT ; return ; } _buffer [ _offset + 0 ] = ( byte ) BC_BINARY_CHUNK ; _buffer [ _offset + 1 ] = ( byte ) ( len >> 8 ) ; _buffer [ _offset + 2 ] = ( byte ) ( len ) ; _offset += len + 3 ; } } | Writes a full output stream . |
286 | public void startPacket ( ) throws IOException { if ( _refs != null ) { _refs . clear ( ) ; _refCount = 0 ; } flushBuffer ( ) ; _isPacket = true ; _offset = 4 ; _buffer [ 0 ] = ( byte ) 0x05 ; _buffer [ 1 ] = ( byte ) 0x55 ; _buffer [ 2 ] = ( byte ) 0x55 ; _buffer [ 3 ] = ( byte ) 0x55 ; } | Starts a streaming packet |
287 | public void reset ( ) { if ( _refs != null ) { _refs . clear ( ) ; _refCount = 0 ; } _classRefs . clear ( ) ; _typeRefs = null ; _offset = 0 ; _isPacket = false ; _isUnshared = false ; } | Resets all counters and references |
288 | public int read ( ) throws IOException { int ch ; InputStream is = _is ; if ( is == null ) return - 1 ; else { ch = is . read ( ) ; } _state . next ( ch ) ; return ch ; } | Reads a character . |
289 | public void freeHessian2Input ( Hessian2Input in ) { if ( in == null ) return ; in . free ( ) ; _freeHessian2Input . free ( in ) ; } | Frees a Hessian 2 . 0 deserializer |
290 | public void freeHessian2Output ( Hessian2Output out ) { if ( out == null ) return ; out . free ( ) ; _freeHessian2Output . free ( out ) ; } | Frees a Hessian 2 . 0 serializer |
291 | public void init ( InputStream is ) { _is = is ; _method = null ; _isLastChunk = true ; _chunkLength = 0 ; _peek = - 1 ; _refs = null ; _replyFault = null ; if ( _serializerFactory == null ) _serializerFactory = new SerializerFactory ( ) ; } | Initialize the hessian stream with the underlying input stream . |
292 | public Object readReply ( Class expectedClass ) throws Throwable { int tag = read ( ) ; if ( tag != 'r' ) error ( "expected hessian reply at " + codeName ( tag ) ) ; int major = read ( ) ; int minor = read ( ) ; tag = read ( ) ; if ( tag == 'f' ) throw prepareFault ( ) ; else { _peek = tag ; Object value = readObject ( expectedClass ) ; completeValueReply ( ) ; return value ; } } | Reads a reply as an object . If the reply has a fault throws the exception . |
293 | private Throwable prepareFault ( ) throws IOException { HashMap fault = readFault ( ) ; Object detail = fault . get ( "detail" ) ; String message = ( String ) fault . get ( "message" ) ; if ( detail instanceof Throwable ) { _replyFault = ( Throwable ) detail ; if ( message != null && _detailMessageField != null ) { try { _detailMessageField . set ( _replyFault , message ) ; } catch ( Throwable e ) { } } return _replyFault ; } else { String code = ( String ) fault . get ( "code" ) ; _replyFault = new HessianServiceException ( message , code , detail ) ; return _replyFault ; } } | Prepares the fault . |
294 | public String readHeader ( ) throws IOException { int tag = read ( ) ; if ( tag == 'H' ) { _isLastChunk = true ; _chunkLength = ( read ( ) << 8 ) + read ( ) ; _sbuf . setLength ( 0 ) ; int ch ; while ( ( ch = parseChar ( ) ) >= 0 ) _sbuf . append ( ( char ) ch ) ; return _sbuf . toString ( ) ; } _peek = tag ; return null ; } | Reads a header returning null if there are no headers . |
295 | public long readUTCDate ( ) throws IOException { int tag = read ( ) ; if ( tag != 'd' ) throw error ( "expected date at " + codeName ( tag ) ) ; long b64 = read ( ) ; long b56 = read ( ) ; long b48 = read ( ) ; long b40 = read ( ) ; long b32 = read ( ) ; long b24 = read ( ) ; long b16 = read ( ) ; long b8 = read ( ) ; return ( ( b64 << 56 ) + ( b56 << 48 ) + ( b48 << 40 ) + ( b40 << 32 ) + ( b32 << 24 ) + ( b24 << 16 ) + ( b16 << 8 ) + b8 ) ; } | Reads a date . |
296 | public org . w3c . dom . Node readNode ( ) throws IOException { int tag = read ( ) ; switch ( tag ) { case 'N' : return null ; case 'S' : case 's' : case 'X' : case 'x' : _isLastChunk = tag == 'S' || tag == 'X' ; _chunkLength = ( read ( ) << 8 ) + read ( ) ; throw error ( "Can't handle string in this context" ) ; default : throw expect ( "string" , tag ) ; } } | Reads an XML node . |
297 | private HashMap readFault ( ) throws IOException { HashMap map = new HashMap ( ) ; int code = read ( ) ; for ( ; code > 0 && code != 'z' ; code = read ( ) ) { _peek = code ; Object key = readObject ( ) ; Object value = readObject ( ) ; if ( key != null && value != null ) map . put ( key , value ) ; } if ( code != 'z' ) throw expect ( "fault" , code ) ; return map ; } | Reads a fault . |
298 | public Object readObject ( Class cl ) throws IOException { if ( cl == null || cl == Object . class ) return readObject ( ) ; int tag = read ( ) ; switch ( tag ) { case 'N' : return null ; case 'M' : { String type = readType ( ) ; if ( "" . equals ( type ) ) { Deserializer reader ; reader = _serializerFactory . getDeserializer ( cl ) ; return reader . readMap ( this ) ; } else { Deserializer reader ; reader = _serializerFactory . getObjectDeserializer ( type ) ; return reader . readMap ( this ) ; } } case 'V' : { String type = readType ( ) ; int length = readLength ( ) ; Deserializer reader ; reader = _serializerFactory . getObjectDeserializer ( type ) ; if ( cl != reader . getType ( ) && cl . isAssignableFrom ( reader . getType ( ) ) ) return reader . readList ( this , length ) ; reader = _serializerFactory . getDeserializer ( cl ) ; Object v = reader . readList ( this , length ) ; return v ; } case 'R' : { int ref = parseInt ( ) ; return _refs . get ( ref ) ; } case 'r' : { String type = readType ( ) ; String url = readString ( ) ; return resolveRemote ( type , url ) ; } } _peek = tag ; Object value = _serializerFactory . getDeserializer ( cl ) . readObject ( this ) ; return value ; } | Reads an object from the input stream with an expected type . |
299 | public Object readObject ( ) throws IOException { int tag = read ( ) ; switch ( tag ) { case 'N' : return null ; case 'T' : return Boolean . valueOf ( true ) ; case 'F' : return Boolean . valueOf ( false ) ; case 'I' : return Integer . valueOf ( parseInt ( ) ) ; case 'L' : return Long . valueOf ( parseLong ( ) ) ; case 'D' : return Double . valueOf ( parseDouble ( ) ) ; case 'd' : return new Date ( parseLong ( ) ) ; case 'x' : case 'X' : { _isLastChunk = tag == 'X' ; _chunkLength = ( read ( ) << 8 ) + read ( ) ; return parseXML ( ) ; } case 's' : case 'S' : { _isLastChunk = tag == 'S' ; _chunkLength = ( read ( ) << 8 ) + read ( ) ; int data ; _sbuf . setLength ( 0 ) ; while ( ( data = parseChar ( ) ) >= 0 ) _sbuf . append ( ( char ) data ) ; return _sbuf . toString ( ) ; } case 'b' : case 'B' : { _isLastChunk = tag == 'B' ; _chunkLength = ( read ( ) << 8 ) + read ( ) ; int data ; ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; while ( ( data = parseByte ( ) ) >= 0 ) bos . write ( data ) ; return bos . toByteArray ( ) ; } case 'V' : { String type = readType ( ) ; int length = readLength ( ) ; return _serializerFactory . readList ( this , length , type ) ; } case 'M' : { String type = readType ( ) ; return _serializerFactory . readMap ( this , type ) ; } case 'R' : { int ref = parseInt ( ) ; return _refs . get ( ref ) ; } case 'r' : { String type = readType ( ) ; String url = readString ( ) ; return resolveRemote ( type , url ) ; } default : throw error ( "unknown code for readObject at " + codeName ( tag ) ) ; } } | Reads an arbitrary object from the input stream when the type is unknown . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.