idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
23,000
public synchronized static ServiceFactory getInstance ( Class < ? > aClass , String configurationPath ) { if ( configurationPath == null ) { configurationPath = "" ; } if ( instances . get ( configurationPath ) == null ) { instances . put ( configurationPath , createServiceFactory ( aClass , configurationPath ) ) ; } return ( ServiceFactory ) instances . get ( configurationPath ) ; }
Singleton factory method
23,001
public String getText ( ) { Object key = null ; try { String bindTemplate = getTemplate ( ) ; Map < Object , String > textMap = new Hashtable < Object , String > ( ) ; for ( Map . Entry < String , Textable > entry : map . entrySet ( ) ) { key = entry . getKey ( ) ; try { textMap . put ( key , ( entry . getValue ( ) ) . getText ( ) ) ; } catch ( Exception e ) { throw new SystemException ( "Unable to build text for key:" + key + " error:" + e . getMessage ( ) , e ) ; } } Debugger . println ( this , "bindTemplate=" + bindTemplate ) ; String formattedOutput = Text . format ( bindTemplate , textMap ) ; Debugger . println ( this , "formattedOutput=" + formattedOutput ) ; return formattedOutput ; } catch ( RuntimeException e ) { throw e ; } catch ( Exception e ) { throw new SetupException ( e . getMessage ( ) , e ) ; } }
Convert get text output from each Textable in map . Return the format output using Text . format .
23,002
public < T > Collection < T > startWorking ( Callable < T > [ ] callables ) { List < Future < T > > list = new ArrayList < Future < T > > ( ) ; for ( int i = 0 ; i < callables . length ; i ++ ) { list . add ( executor . submit ( callables [ i ] ) ) ; } ArrayList < T > resultList = new ArrayList < T > ( callables . length ) ; T output ; for ( Future < T > future : list ) { try { output = future . get ( ) ; if ( output != null ) resultList . add ( output ) ; } catch ( InterruptedException e ) { throw new SystemException ( e ) ; } catch ( ExecutionException e ) { throw new SystemException ( e ) ; } } return resultList ; }
Start the array of the callables
23,003
public Collection < Future < ? > > startWorking ( WorkQueue queue , boolean background ) { ArrayList < Future < ? > > futures = new ArrayList < Future < ? > > ( queue . size ( ) ) ; while ( queue . hasMoreTasks ( ) ) { futures . add ( executor . submit ( queue . nextTask ( ) ) ) ; } if ( background ) return futures ; try { for ( Future < ? > future : futures ) { future . get ( ) ; } return futures ; } catch ( InterruptedException e ) { throw new SystemException ( e ) ; } catch ( ExecutionException e ) { throw new SystemException ( e ) ; } }
The start the work threads
23,004
public static Mirror newInstanceForClassName ( String className ) throws ClassNotFoundException , InstantiationException , IllegalAccessException { className = className . trim ( ) ; Class < ? > objClass = Class . forName ( className ) ; return new Mirror ( ClassPath . newInstance ( objClass ) ) ; }
Create an instance of the given object
23,005
public static void waitFor ( File aFile ) { if ( aFile == null ) return ; String path = aFile . getAbsolutePath ( ) ; long previousSize = IO . getFileSize ( path ) ; long currentSize = previousSize ; long sleepTime = Config . getPropertyLong ( "file.monitor.file.wait.time" , 100 ) . longValue ( ) ; while ( true ) { try { Thread . sleep ( sleepTime ) ; } catch ( InterruptedException e ) { } currentSize = IO . getFileSize ( path ) ; if ( currentSize == previousSize ) return ; previousSize = currentSize ; } }
Used to wait for transferred file s content length to stop changes for 5 seconds
23,006
protected synchronized void notifyChange ( File file ) { System . out . println ( "Notify change file=" + file . getAbsolutePath ( ) ) ; this . notify ( FileEvent . createChangedEvent ( file ) ) ; }
Notify observers that the file has changed
23,007
public UserProfile convert ( File file ) { if ( file == null ) return null ; try { String text = IO . readFile ( file ) ; if ( text == null || text . length ( ) == 0 ) return null ; return converter . convert ( text ) ; } catch ( IOException e ) { throw new SystemException ( "Unable to convert file:" + file . getAbsolutePath ( ) + " to user profile ERROR:" + e . getMessage ( ) , e ) ; } }
Convert the user profile
23,008
public < T > void register ( String subjectName , SubjectObserver < T > subjectObserver , Subject < T > subject ) { subject . add ( subjectObserver ) ; this . registry . put ( subjectName , subject ) ; }
Add subject observer to a subject
23,009
@ SuppressWarnings ( { "unchecked" , "rawtypes" } ) public < T > void removeRegistraion ( String subjectName , SubjectObserver < T > subjectObserver ) { Subject subject = ( Subject ) this . registry . get ( subjectName ) ; if ( subject == null ) return ; subject . remove ( subjectObserver ) ; }
Remove an observer for a registered observer
23,010
@ SuppressWarnings ( { "Duplicates" } ) public static BufferByteOutput < ByteBuffer > of ( final int capacity , final WritableByteChannel channel ) { if ( capacity <= 0 ) { throw new IllegalArgumentException ( "capacity(" + capacity + ") <= 0" ) ; } if ( channel == null ) { throw new NullPointerException ( "channel is null" ) ; } return new BufferByteOutput < ByteBuffer > ( null ) { public void write ( final int value ) throws IOException { if ( target == null ) { target = ByteBuffer . allocate ( capacity ) ; } if ( ! target . hasRemaining ( ) ) { target . flip ( ) ; do { channel . write ( target ) ; } while ( target . position ( ) == 0 ) ; target . compact ( ) ; } super . write ( value ) ; } public void setTarget ( final ByteBuffer target ) { throw new UnsupportedOperationException ( ) ; } } ; }
Creates a new instance which writes bytes to specified channel using a byte buffer of given capacity .
23,011
public static int flush ( final BufferByteOutput < ? > output , final WritableByteChannel channel ) throws IOException { final ByteBuffer buffer = output . getTarget ( ) ; if ( buffer == null ) { return 0 ; } int written = 0 ; for ( buffer . flip ( ) ; buffer . hasRemaining ( ) ; ) { written += channel . write ( buffer ) ; } buffer . clear ( ) ; return written ; }
Flushes the internal byte buffer of given byte output to specified channel and returns the number of bytes written .
23,012
public static long durationMS ( LocalDateTime start , LocalDateTime end ) { if ( start == null || end == null ) { return 0 ; } return Duration . between ( start , end ) . toMillis ( ) ; }
The time between two dates
23,013
public static double durationSeconds ( LocalDateTime start , LocalDateTime end ) { return Duration . between ( start , end ) . getSeconds ( ) ; }
1 millisecond = 0 . 001 seconds
23,014
public static long durationHours ( LocalDateTime start , LocalDateTime end ) { if ( start == null || end == null ) return ZERO ; return Duration . between ( start , end ) . toHours ( ) ; }
1 Hours = 60 minutes
23,015
public void scheduleRecurring ( Runnable runnable , Date firstTime , long period ) { timer . scheduleAtFixedRate ( toTimerTask ( runnable ) , firstTime , period ) ; }
Schedule runnable to run a given interval
23,016
public static TimerTask toTimerTask ( Runnable runnable ) { if ( runnable instanceof TimerTask ) return ( TimerTask ) runnable ; return new TimerTaskRunnerAdapter ( runnable ) ; }
Convert timer task to a runnable
23,017
public String getText ( ) { if ( this . target == null ) throw new RequiredException ( "this.target in ReplaceTextDecorator" ) ; return Text . replaceForRegExprWith ( this . target . getText ( ) , regExp , replacement ) ; }
replace the text based on a RegExpr
23,018
public Integer getInteger ( Class < ? > aClass , String key , int defaultValue ) { return getInteger ( aClass . getName ( ) + ".key" , defaultValue ) ; }
Get a Setting property as an Integer object .
23,019
public Character getCharacter ( Class < ? > aClass , String key , char defaultValue ) { String results = getText ( aClass , key , "" ) ; if ( results . length ( ) == 0 ) return Character . valueOf ( defaultValue ) ; else return Character . valueOf ( results . charAt ( 0 ) ) ; }
Get a Settings property as an c object .
23,020
public Integer getInteger ( String key ) { Integer iVal = null ; String sVal = getText ( key ) ; if ( ( sVal != null ) && ( sVal . length ( ) > 0 ) ) { iVal = Integer . valueOf ( sVal ) ; } return iVal ; }
Get a Settings property as an Integer object .
23,021
public Boolean getBoolean ( String key ) { Boolean bVal = null ; String sVal = getText ( key ) ; if ( ( sVal != null ) && ( sVal . length ( ) > 0 ) ) { bVal = Boolean . valueOf ( sVal ) ; } return bVal ; }
Get a Setting property as a Boolean object .
23,022
public synchronized void playMethodCalls ( Memento memento , String [ ] savePoints ) { String savePoint = null ; MethodCallFact methodCallFact = null ; SummaryException exceptions = new SummaryException ( ) ; for ( int i = 0 ; i < savePoints . length ; i ++ ) { savePoint = savePoints [ i ] ; if ( savePoint == null || savePoint . length ( ) == 0 || savePoint . trim ( ) . length ( ) == 0 ) continue ; Debugger . println ( this , "processing savepoint=" + savePoint ) ; methodCallFact = ( MethodCallFact ) memento . restore ( savePoint , MethodCallFact . class ) ; try { ObjectProxy . executeMethod ( prepareObject ( methodCallFact , savePoint ) , methodCallFact ) ; } catch ( Exception e ) { exceptions . addException ( new SystemException ( "savePoint=" + savePoint + " methodCallFact=" + methodCallFact + " exception=" + Debugger . stackTrace ( e ) ) ) ; throw new SystemException ( e ) ; } } if ( ! exceptions . isEmpty ( ) ) throw exceptions ; }
Redo the method calls of a target object
23,023
public static void printError ( Object caller , Object message ) { StringBuilder text = new StringBuilder ( ) ; Class < ? > c = callerBuilder ( caller , text ) ; if ( message instanceof Throwable ) getLog ( c ) . error ( text . append ( stackTrace ( ( Throwable ) message ) ) ) ; else getLog ( c ) . error ( text . append ( message ) ) ; }
Print a error message . The stack trace will be printed if the given message is an exception .
23,024
public static void printError ( Object errorMessage ) { if ( errorMessage instanceof Throwable ) { Throwable e = ( Throwable ) errorMessage ; getLog ( Debugger . class ) . error ( stackTrace ( e ) ) ; } else getLog ( Debugger . class ) . error ( errorMessage ) ; }
Print error message using the configured log . The stack trace will be printed if the given message is an exception .
23,025
public static void printFatal ( Object message ) { if ( message instanceof Throwable ) { Throwable e = ( Throwable ) message ; e . printStackTrace ( ) ; } Log log = getLog ( Debugger . class ) ; if ( log != null ) log . fatal ( message ) ; else System . err . println ( message ) ; }
Print a fatal level message . The stack trace will be printed if the given message is an exception .
23,026
public static void printFatal ( Object caller , Object message ) { StringBuilder text = new StringBuilder ( ) ; Class < ? > c = callerBuilder ( caller , text ) ; if ( message instanceof Throwable ) getLog ( c ) . fatal ( text . append ( stackTrace ( ( Throwable ) message ) ) ) ; else getLog ( c ) . fatal ( text . append ( message ) ) ; }
Print a fatal message . The stack trace will be printed if the given message is an exception .
23,027
public static void printInfo ( Object caller , Object message ) { StringBuilder text = new StringBuilder ( ) ; Class < ? > c = callerBuilder ( caller , text ) ; if ( message instanceof Throwable ) getLog ( c ) . info ( text . append ( stackTrace ( ( Throwable ) message ) ) ) ; else getLog ( c ) . info ( text . append ( message ) ) ; }
Print an INFO message
23,028
public static void printInfo ( Object message ) { if ( message instanceof Throwable ) { Throwable e = ( Throwable ) message ; getLog ( Debugger . class ) . info ( stackTrace ( e ) ) ; } else getLog ( Debugger . class ) . info ( message ) ; }
Print a INFO level message
23,029
public static void printWarn ( Object caller , Object message ) { StringBuilder text = new StringBuilder ( ) ; Class < ? > c = callerBuilder ( caller , text ) ; if ( message instanceof Throwable ) getLog ( c ) . warn ( text . append ( stackTrace ( ( Throwable ) message ) ) ) ; else getLog ( c ) . warn ( text . append ( message ) ) ; }
Print a warning level message . The stack trace will be printed if the given message is an exception .
23,030
public static void printWarn ( Object message ) { if ( message instanceof Throwable ) { Throwable e = ( Throwable ) message ; getLog ( Debugger . class ) . warn ( stackTrace ( e ) ) ; } else getLog ( Debugger . class ) . warn ( message ) ; }
Print A WARN message . The stack trace will be printed if the given message is an exception .
23,031
public void registerMemoryNotifications ( NotificationListener notificationListener , Object handback ) { NotificationEmitter emitter = ( NotificationEmitter ) this . getMemory ( ) ; emitter . addNotificationListener ( notificationListener , null , handback ) ; }
Allows a listener to be registered within the MemoryMXBean as a notification listener usage threshold exceeded notification - for notifying that the memory usage of a memory pool is increased and has reached or exceeded its usage threshold value .
23,032
public ProcessInfo execute ( boolean background , String ... command ) { ProcessBuilder pb = new ProcessBuilder ( command ) ; return executeProcess ( background , pb ) ; }
Executes a giving shell command
23,033
private ProcessInfo executeProcess ( boolean background , ProcessBuilder pb ) { try { pb . directory ( workingDirectory ) ; pb . redirectErrorStream ( false ) ; if ( log != null ) pb . redirectOutput ( Redirect . appendTo ( log ) ) ; pb . environment ( ) . putAll ( envMap ) ; Process p = pb . start ( ) ; String out = null ; String error = null ; if ( background ) { out = IO . readText ( p . getInputStream ( ) , true , defaultBackgroundReadSize ) ; error = IO . readText ( p . getErrorStream ( ) , true , 20 ) ; } else { out = IO . readText ( p . getInputStream ( ) , true ) ; error = IO . readText ( p . getErrorStream ( ) , true ) ; } if ( background ) return new ProcessInfo ( 0 , out , error ) ; return new ProcessInfo ( p . waitFor ( ) , out , error ) ; } catch ( Exception e ) { return new ProcessInfo ( - 1 , null , Debugger . stackTrace ( e ) ) ; } }
Executes a process
23,034
public static void main ( String [ ] args ) { if ( args . length != 4 ) { System . err . println ( "Usage java " + SumStatsByMillisecondsFormular . class . getName ( ) + " file msSecColumn calculateCol sumByMillisec" ) ; System . exit ( - 1 ) ; } File file = Paths . get ( args [ 0 ] ) . toFile ( ) ; try { if ( ! file . exists ( ) ) { throw new FileNotFoundException ( file . getAbsolutePath ( ) ) ; } int timeMsIndex = Integer . parseInt ( args [ 1 ] ) ; int calculateColumn = Integer . parseInt ( args [ 2 ] ) ; long milliseconds = Long . parseLong ( args [ 3 ] ) ; SumStatsByMillisecondsFormular formular = new SumStatsByMillisecondsFormular ( timeMsIndex , calculateColumn , milliseconds ) ; new CsvReader ( file ) . calc ( formular ) ; System . out . println ( formular ) ; } catch ( NumberFormatException e ) { System . err . println ( "Checks timeMsIndex:" + args [ 1 ] + ",calculateColumn:" + args [ 2 ] + " and milliseconds:" + args [ 3 ] + " are valids numbers error:" + e ) ; } catch ( FileNotFoundException e ) { e . printStackTrace ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } }
Usages file msSecColumn calculateCol sumByMillisec
23,035
public static String decorateEncryption ( char [ ] password ) { if ( password == null || password . length == 0 ) return null ; return new StringBuilder ( ENCRYPTED_PASSWORD_PREFIX ) . append ( encrypt ( password ) ) . append ( ENCRYPTED_PASSWORD_SUFFIX ) . toString ( ) ; }
Surround encrypted password with a prefix and suffix to indicate it has been encrypted
23,036
public static char [ ] decrypt ( char [ ] password ) { if ( password == null || password . length == 0 ) return null ; String passwordString = String . valueOf ( password ) ; try { byte [ ] decrypted = null ; if ( passwordString . startsWith ( "encrypted(" ) && passwordString . endsWith ( ")" ) ) { passwordString = passwordString . substring ( 10 , passwordString . length ( ) - 1 ) ; } SecretKeySpec key = new SecretKeySpec ( init , "Blowfish" ) ; Cipher cipher = Cipher . getInstance ( CIPHER_INSTANCE ) ; cipher . init ( Cipher . DECRYPT_MODE , key ) ; decrypted = cipher . doFinal ( hexStringToByteArray ( passwordString ) ) ; return new String ( decrypted , Charset . forName ( "UTF8" ) ) . toCharArray ( ) ; } catch ( Exception e ) { throw new SecurityException ( "Unable to decrypt password. Check that the password has been encrypted." , e ) ; } }
decrypt an encrypted password string .
23,037
public static void rotateImage ( File input , File output , String format , int degrees ) throws IOException { BufferedImage inputImage = ImageIO . read ( input ) ; Graphics2D g = ( Graphics2D ) inputImage . getGraphics ( ) ; g . drawImage ( inputImage , 0 , 0 , null ) ; AffineTransform at = new AffineTransform ( ) ; at . rotate ( degrees * Math . PI / 180.0 , inputImage . getWidth ( ) / 2.0 , inputImage . getHeight ( ) / 2.0 ) ; AffineTransform translationTransform ; translationTransform = findTranslation ( at , inputImage ) ; at . preConcatenate ( translationTransform ) ; BufferedImageOp bio = new AffineTransformOp ( at , AffineTransformOp . TYPE_BILINEAR ) ; BufferedImage destinationBI = bio . filter ( inputImage , null ) ; ImageIO . write ( destinationBI , format , output ) ; }
Rotate a file a given number of degrees
23,038
public void close ( ) { try { if ( is != null ) is . close ( ) ; } catch ( IOException e ) { log . error ( null , e ) ; throw new RuntimeException ( e ) ; } isClosed = true ; }
Closes the Workbook manually .
23,039
public Iterable < String > toCSV ( ) { checkState ( ! isClosed , WORKBOOK_CLOSED ) ; Joiner joiner = Joiner . on ( "," ) . useForNull ( "" ) ; Iterable < String > CSVIterable = Iterables . transform ( sheet , item -> joiner . join ( rowToList ( item , true ) ) ) ; return hasHeader ? Iterables . skip ( CSVIterable , 1 ) : CSVIterable ; }
Converts the spreadsheet to CSV by a String Iterable .
23,040
public Iterable < List < String > > toLists ( ) { checkState ( ! isClosed , WORKBOOK_CLOSED ) ; Iterable < List < String > > listsIterable = Iterables . transform ( sheet , item -> { return rowToList ( item ) ; } ) ; return hasHeader ? Iterables . skip ( listsIterable , 1 ) : listsIterable ; }
Converts the spreadsheet to String Lists by a List Iterable .
23,041
public Iterable < String [ ] > toArrays ( ) { checkState ( ! isClosed , WORKBOOK_CLOSED ) ; Iterable < String [ ] > arraysIterable = Iterables . transform ( sheet , item -> { List < String > list = rowToList ( item ) ; return list . toArray ( new String [ list . size ( ) ] ) ; } ) ; return hasHeader ? Iterables . skip ( arraysIterable , 1 ) : arraysIterable ; }
Converts the spreadsheet to String Arrays by an Array Iterable .
23,042
public Iterable < Map < String , String > > toMaps ( ) { checkState ( ! isClosed , WORKBOOK_CLOSED ) ; checkState ( hasHeader , NO_HEADER ) ; return Iterables . skip ( Iterables . transform ( sheet , item -> { Map < String , String > map = newLinkedHashMap ( ) ; List < String > row = rowToList ( item ) ; for ( int i = 0 ; i < getHeader ( ) . size ( ) ; i ++ ) { map . put ( getHeader ( ) . get ( i ) , row . get ( i ) ) ; } return map ; } ) , 1 ) ; }
Converts the spreadsheet to Maps by a Map Iterable . All Maps are implemented by LinkedHashMap which implies the order of all fields is kept .
23,043
@ SuppressWarnings ( "unchecked" ) public void start ( final Listener < ? > listener , final Infrastructure infra ) throws MessageTransportException { this . listener = ( Listener < Object > ) listener ; }
A receiver is started with a Listener and a threading model .
23,044
@ SuppressWarnings ( { "rawtypes" , "unchecked" } ) public synchronized void start ( final Listener listener , final Infrastructure infra ) { if ( listener == null ) throw new IllegalArgumentException ( "Cannot pass null to " + BlockingQueueReceiver . class . getSimpleName ( ) + ".setListener" ) ; if ( this . listener != null ) throw new IllegalStateException ( "Cannot set a new Listener (" + SafeString . objectDescription ( listener ) + ") on a " + BlockingQueueReceiver . class . getSimpleName ( ) + " when there's one already set (" + SafeString . objectDescription ( this . listener ) + ")" ) ; this . listener = listener ; infra . getThreadingModel ( ) . runDaemon ( this , "BQReceiver-" + address . toString ( ) ) ; }
A BlockingQueueAdaptor requires a MessageTransportListener to be set in order to adapt a client side .
23,045
public static void unwindMessages ( final Object message , final List < Object > messages ) { if ( message instanceof Iterable ) { @ SuppressWarnings ( "rawtypes" ) final Iterator it = ( ( Iterable ) message ) . iterator ( ) ; while ( it . hasNext ( ) ) unwindMessages ( it . next ( ) , messages ) ; } else messages . add ( message ) ; }
Return values from invoke s may be Iterables in which case there are many messages to be sent out .
23,046
private Set < Integer > perNodeRelease ( final C thisNodeAddress , final C [ ] currentState , final int nodeCount , final int nodeRank ) { final int numberIShouldHave = howManyShouldIHave ( totalNumShards , nodeCount , minNodes , nodeRank ) ; final List < Integer > destinationsAcquired = buildDestinationsAcquired ( thisNodeAddress , currentState ) ; final int numHad = destinationsAcquired . size ( ) ; final Set < Integer > ret = new HashSet < > ( ) ; if ( destinationsAcquired . size ( ) > numberIShouldHave ) { final Random random = new Random ( ) ; while ( destinationsAcquired . size ( ) > numberIShouldHave ) { final int index = random . nextInt ( destinationsAcquired . size ( ) ) ; ret . add ( destinationsAcquired . remove ( index ) ) ; } } if ( LOGGER . isTraceEnabled ( ) && ret . size ( ) > 0 ) LOGGER . trace ( thisNodeAddress . toString ( ) + " removing shards " + ret + " because I have " + numHad + " but shouldn't have more than " + numberIShouldHave + "." ) ; return ret ; }
go through and determine which nodes to give up ... if any
23,047
private boolean registerAndConfirmIfImIt ( ) throws ClusterInfoException { final Collection < String > imItSubdirs = utils . persistentGetSubdir ( utils . leaderDir , this ) ; if ( imItSubdirs . size ( ) > 1 ) throw new ClusterInfoException ( "This is IMPOSSIBLE. There's more than one subdir of " + utils . leaderDir + ". They include " + imItSubdirs ) ; @ SuppressWarnings ( "unchecked" ) final C registered = ( C ) session . getData ( utils . masterDetermineDir , null ) ; return utils . thisNodeAddress . equals ( registered ) ; }
whether or not imIt and return that .
23,048
public void send ( final Object message ) throws MessageTransportException { if ( shutdown . get ( ) ) throw new MessageTransportException ( "send called on shutdown queue." ) ; if ( blocking ) { while ( true ) { try { queue . put ( message ) ; if ( statsCollector != null ) statsCollector . messageSent ( message ) ; break ; } catch ( final InterruptedException ie ) { if ( shutdown . get ( ) ) throw new MessageTransportException ( "Shutting down durring send." ) ; } } } else { if ( ! queue . offer ( message ) ) { if ( statsCollector != null ) statsCollector . messageNotSent ( ) ; throw new MessageTransportException ( "Failed to queue message due to capacity." ) ; } else if ( statsCollector != null ) statsCollector . messageSent ( message ) ; } }
Send a message into the BlockingQueueAdaptor .
23,049
public static < A extends Annotation > List < AnnotatedClass < A > > allTypeAnnotations ( final Class < ? > clazz , final Class < A > annotation , final boolean recurse ) { final List < AnnotatedClass < A > > ret = new ArrayList < > ( ) ; final A curClassAnnotation = clazz . getAnnotation ( annotation ) ; if ( curClassAnnotation != null ) ret . add ( new AnnotatedClass < A > ( clazz , curClassAnnotation ) ) ; if ( ! recurse ) return ret ; final Class < ? > superClazz = clazz . getSuperclass ( ) ; if ( superClazz != null ) ret . addAll ( allTypeAnnotations ( superClazz , annotation , recurse ) ) ; final Class < ? > [ ] ifaces = clazz . getInterfaces ( ) ; if ( ifaces != null && ifaces . length > 0 ) Arrays . stream ( ifaces ) . forEach ( iface -> ret . addAll ( allTypeAnnotations ( iface , annotation , recurse ) ) ) ; return ret ; }
Get all annotation on the given class plus all annotations on the parent classes
23,050
private final void cleanupAfterExceptionDuringNodeDirCheck ( ) { if ( nodeDirectory != null ) { try { if ( session . exists ( nodeDirectory , this ) ) { session . rmdir ( nodeDirectory ) ; } nodeDirectory = null ; } catch ( final ClusterInfoException cie2 ) { } } }
called from the catch clauses in checkNodeDirectory
23,051
public Cluster destination ( final String ... destinations ) { final String applicationName = clusterId . applicationName ; return destination ( Arrays . stream ( destinations ) . map ( d -> new ClusterId ( applicationName , d ) ) . toArray ( ClusterId [ ] :: new ) ) ; }
Set the list of explicit destination that outgoing messages should be limited to .
23,052
void setAppName ( final String appName ) { if ( clusterId . applicationName != null && ! clusterId . applicationName . equals ( appName ) ) throw new IllegalStateException ( "Restting the application name on a cluster is not allowed." ) ; clusterId = new ClusterId ( appName , clusterId . clusterName ) ; }
This is called from Node
23,053
protected String getName ( final String key ) { return MetricRegistry . name ( DropwizardClusterStatsCollector . class , "cluster" , clusterId . applicationName , clusterId . clusterName , key ) ; }
protected access for testing purposes
23,054
@ SuppressWarnings ( "unchecked" ) public T newInstance ( ) throws DempsyException { return wrap ( ( ) -> ( T ) cloneMethod . invoke ( prototype ) ) ; }
Creates a new instance from the prototype .
23,055
public void activate ( final T instance , final Object key ) throws DempsyException { wrap ( ( ) -> activationMethod . invoke ( instance , key ) ) ; }
Invokes the activation method of the passed instance .
23,056
public boolean invokeEvictable ( final T instance ) throws DempsyException { return isEvictionSupported ( ) ? ( Boolean ) wrap ( ( ) -> evictableMethod . invoke ( instance ) ) : false ; }
Invokes the evictable method on the provided instance . If the evictable is not implemented returns false .
23,057
public JobDetail getJobDetail ( OutputInvoker outputInvoker ) { JobBuilder jobBuilder = JobBuilder . newJob ( OutputJob . class ) ; JobDetail jobDetail = jobBuilder . build ( ) ; jobDetail . getJobDataMap ( ) . put ( OUTPUT_JOB_NAME , outputInvoker ) ; return jobDetail ; }
Gets the job detail .
23,058
public Trigger getSimpleTrigger ( TimeUnit timeUnit , int timeInterval ) { SimpleScheduleBuilder simpleScheduleBuilder = null ; simpleScheduleBuilder = SimpleScheduleBuilder . simpleSchedule ( ) ; switch ( timeUnit ) { case MILLISECONDS : simpleScheduleBuilder . withIntervalInMilliseconds ( timeInterval ) . repeatForever ( ) ; break ; case SECONDS : simpleScheduleBuilder . withIntervalInSeconds ( timeInterval ) . repeatForever ( ) ; break ; case MINUTES : simpleScheduleBuilder . withIntervalInMinutes ( timeInterval ) . repeatForever ( ) ; break ; case HOURS : simpleScheduleBuilder . withIntervalInHours ( timeInterval ) . repeatForever ( ) ; break ; case DAYS : simpleScheduleBuilder . withIntervalInHours ( timeInterval * 24 ) . repeatForever ( ) ; break ; default : simpleScheduleBuilder . withIntervalInSeconds ( 1 ) . repeatForever ( ) ; } Trigger simpleTrigger = TriggerBuilder . newTrigger ( ) . withSchedule ( simpleScheduleBuilder ) . build ( ) ; return simpleTrigger ; }
Gets the simple trigger .
23,059
public Trigger getCronTrigger ( String cronExpression ) { CronScheduleBuilder cronScheduleBuilder = null ; Trigger cronTrigger = null ; try { cronScheduleBuilder = CronScheduleBuilder . cronSchedule ( cronExpression ) ; cronScheduleBuilder . withMisfireHandlingInstructionFireAndProceed ( ) ; TriggerBuilder < Trigger > cronTtriggerBuilder = TriggerBuilder . newTrigger ( ) ; cronTtriggerBuilder . withSchedule ( cronScheduleBuilder ) ; cronTrigger = cronTtriggerBuilder . build ( ) ; } catch ( Exception pe ) { logger . error ( "Error occurred while builiding the cronTrigger : " + pe . getMessage ( ) , pe ) ; } return cronTrigger ; }
Gets the cron trigger .
23,060
public static < T > ListenableFuture < T > createListenableFuture ( ValueSourceFuture < T > valueSourceFuture ) { if ( valueSourceFuture instanceof ListenableFutureBackedValueSourceFuture ) { return ( ( ListenableFutureBackedValueSourceFuture < T > ) valueSourceFuture ) . getWrappedFuture ( ) ; } else { return new ValueSourceFutureBackedListenableFuture < > ( valueSourceFuture ) ; } }
Creates listenable future from ValueSourceFuture . We have to send all Future API calls to ValueSourceFuture .
23,061
public static < T > ApiFuture < T > createApiFuture ( ValueSourceFuture < T > valueSourceFuture ) { if ( valueSourceFuture instanceof ApiFutureBackedValueSourceFuture ) { return ( ( ApiFutureBackedValueSourceFuture < T > ) valueSourceFuture ) . getWrappedFuture ( ) ; } else { return new ValueSourceFutureBackedApiFuture < > ( valueSourceFuture ) ; } }
Creates api future from ValueSourceFuture . We have to send all Future API calls to ValueSourceFuture .
23,062
private void getLastChild ( ) { final long parent = getNode ( ) . getDataKey ( ) ; if ( ( ( ITreeStructData ) getNode ( ) ) . hasFirstChild ( ) ) { while ( ( ( ITreeStructData ) getNode ( ) ) . hasFirstChild ( ) ) { mStack . push ( getNode ( ) . getDataKey ( ) ) ; moveTo ( ( ( ITreeStructData ) getNode ( ) ) . getFirstChildKey ( ) ) ; } while ( ( ( ITreeStructData ) getNode ( ) ) . hasRightSibling ( ) ) { mStack . push ( getNode ( ) . getDataKey ( ) ) ; moveTo ( ( ( ITreeStructData ) getNode ( ) ) . getRightSiblingKey ( ) ) ; getLastChild ( ) ; } if ( getNode ( ) . hasParent ( ) && ( getNode ( ) . getParentKey ( ) != parent ) ) { mStack . push ( getNode ( ) . getDataKey ( ) ) ; while ( getNode ( ) . hasParent ( ) && ( getNode ( ) . getParentKey ( ) != parent ) ) { moveTo ( getNode ( ) . getParentKey ( ) ) ; while ( ( ( ITreeStructData ) getNode ( ) ) . hasRightSibling ( ) ) { moveTo ( ( ( ITreeStructData ) getNode ( ) ) . getRightSiblingKey ( ) ) ; getLastChild ( ) ; mStack . push ( getNode ( ) . getDataKey ( ) ) ; } } moveTo ( mStack . pop ( ) ) ; } } }
Moves the transaction to the node in the current subtree that is last in document order and pushes all other node key on a stack . At the end the stack contains all node keys except for the last one in reverse document order .
23,063
public static JaxRx getInstance ( final String impl ) { final String path = Systems . getSystems ( ) . get ( impl ) ; if ( path == null ) { throw new JaxRxException ( 404 , "Unknown implementation: " + impl ) ; } JaxRx jaxrx = INSTANCES . get ( path ) ; if ( jaxrx == null ) { try { jaxrx = ( JaxRx ) Class . forName ( path ) . newInstance ( ) ; INSTANCES . put ( path , jaxrx ) ; } catch ( final Exception ex ) { throw new JaxRxException ( ex ) ; } } return jaxrx ; }
Returns the instance for the specified implementation . If the system is unknown throws an exception .
23,064
public void add ( final String prefix , final String uri ) { if ( prefix == null ) { defaultNS = uri ; } addToMap ( prefix , uri ) ; }
Add a namespace to the maps
23,065
public void appendNsName ( final StringBuilder sb , final QName nm ) { String uri = nm . getNamespaceURI ( ) ; String abbr ; if ( ( defaultNS != null ) && uri . equals ( defaultNS ) ) { abbr = null ; } else { abbr = keyUri . get ( uri ) ; if ( abbr == null ) { abbr = uri ; } } if ( abbr != null ) { sb . append ( abbr ) ; sb . append ( ":" ) ; } sb . append ( nm . getLocalPart ( ) ) ; }
Append the name with abbreviated namespace .
23,066
public static String generate ( final int length ) { final StringBuilder password = new StringBuilder ( length ) ; double pik = random . nextDouble ( ) ; long ranno = ( long ) ( pik * sigma ) ; long sum = 0 ; outer : for ( int c1 = 0 ; c1 < 26 ; c1 ++ ) { for ( int c2 = 0 ; c2 < 26 ; c2 ++ ) { for ( int c3 = 0 ; c3 < 26 ; c3 ++ ) { sum += get ( c1 , c2 , c3 ) ; if ( sum > ranno ) { password . append ( alphabet . charAt ( c1 ) ) ; password . append ( alphabet . charAt ( c2 ) ) ; password . append ( alphabet . charAt ( c3 ) ) ; break outer ; } } } } int nchar = 3 ; while ( nchar < length ) { final int c1 = alphabet . indexOf ( password . charAt ( nchar - 2 ) ) ; final int c2 = alphabet . indexOf ( password . charAt ( nchar - 1 ) ) ; sum = 0 ; for ( int c3 = 0 ; c3 < 26 ; c3 ++ ) { sum += get ( c1 , c2 , c3 ) ; } if ( sum == 0 ) { break ; } pik = random . nextDouble ( ) ; ranno = ( long ) ( pik * sum ) ; sum = 0 ; for ( int c3 = 0 ; c3 < 26 ; c3 ++ ) { sum += get ( c1 , c2 , c3 ) ; if ( sum > ranno ) { password . append ( alphabet . charAt ( c3 ) ) ; break ; } } nchar ++ ; } return password . toString ( ) ; }
Generates a new password .
23,067
public void parseQuery ( ) throws TTXPathException { do { mToken = mScanner . nextToken ( ) ; } while ( mToken . getType ( ) == TokenType . SPACE ) ; parseExpression ( ) ; if ( mToken . getType ( ) != TokenType . END ) { throw new IllegalStateException ( "The query has not been processed completely." ) ; } }
Starts parsing the query .
23,068
private boolean isReservedKeyword ( ) { final String content = mToken . getContent ( ) ; return isKindTest ( ) || "item" . equals ( content ) || "if" . equals ( content ) || "empty-sequence" . equals ( content ) || "typeswitch" . equals ( content ) ; }
Although XPath is supposed to have no reserved words some keywords are not allowed as function names in an unprefixed form because expression syntax takes precedence .
23,069
private boolean isForwardAxis ( ) { final String content = mToken . getContent ( ) ; return ( mToken . getType ( ) == TokenType . TEXT && ( "child" . equals ( content ) || ( "descendant" . equals ( content ) || "descendant-or-self" . equals ( content ) || "attribute" . equals ( content ) || "self" . equals ( content ) || "following" . equals ( content ) || "following-sibling" . equals ( content ) || "namespace" . equals ( content ) ) ) ) ; }
Checks if a given token represents a ForwardAxis .
23,070
private void consume ( final TokenType mType , final boolean mIgnoreWhitespace ) { if ( ! is ( mType , mIgnoreWhitespace ) ) { throw new IllegalStateException ( "Wrong token after " + mScanner . begin ( ) + " at position " + mScanner . getPos ( ) + " found " + mToken . getType ( ) + " expected " + mType + "." ) ; } }
Consumes a token . Tests if it really has the expected type and if not returns an error message . Otherwise gets a new token from the scanner . If that new token is of type whitespace and the ignoreWhitespace parameter is true a new token is retrieved until the current token is not of type whitespace .
23,071
private void consume ( final String mName , final boolean mIgnoreWhitespace ) { if ( ! is ( mName , mIgnoreWhitespace ) ) { throw new IllegalStateException ( "Wrong token after " + mScanner . begin ( ) + " found " + mToken . getContent ( ) + ". Expected " + mName ) ; } }
Consumes a token . Tests if it really has the expected name and if not returns an error message . Otherwise gets a new token from the scanner . If that new token is of type whitespace and the ignoreWhitespace parameter is true a new token is retrieved until the current token is not of type whitespace .
23,072
private boolean is ( final String mName , final boolean mIgnoreWhitespace ) { if ( ! mName . equals ( mToken . getContent ( ) ) ) { return false ; } if ( mToken . getType ( ) == TokenType . COMP || mToken . getType ( ) == TokenType . EQ || mToken . getType ( ) == TokenType . N_EQ || mToken . getType ( ) == TokenType . PLUS || mToken . getType ( ) == TokenType . MINUS || mToken . getType ( ) == TokenType . STAR ) { return is ( mToken . getType ( ) , mIgnoreWhitespace ) ; } else { return is ( TokenType . TEXT , mIgnoreWhitespace ) ; } }
Returns true or false if a token has the expected name . If the token has the given name it gets a new token from the scanner . If that new token is of type whitespace and the ignoreWhitespace parameter is true a new token is retrieved until the current token is not of type whitespace .
23,073
private boolean is ( final TokenType mType , final boolean mIgnoreWhitespace ) { if ( mType != mToken . getType ( ) ) { return false ; } do { mToken = mScanner . nextToken ( ) ; } while ( mIgnoreWhitespace && mToken . getType ( ) == TokenType . SPACE ) ; return true ; }
Returns true or false if a token has the expected type . If so a new token is retrieved from the scanner . If that new token is of type whitespace and the ignoreWhitespace parameter is true a new token is retrieved until the current token is not of type whitespace .
23,074
public String newIndex ( final String name , final String mappingPath ) throws IndexException { try { final String newName = name + newIndexSuffix ( ) ; final IndicesAdminClient idx = getAdminIdx ( ) ; final CreateIndexRequestBuilder cirb = idx . prepareCreate ( newName ) ; final File f = new File ( mappingPath ) ; final byte [ ] sbBytes = Streams . copyToByteArray ( f ) ; cirb . setSource ( sbBytes ) ; final CreateIndexRequest cir = cirb . request ( ) ; final ActionFuture < CreateIndexResponse > af = idx . create ( cir ) ; af . actionGet ( ) ; info ( "Index created" ) ; return newName ; } catch ( final ElasticsearchException ese ) { error ( ese ) ; return null ; } catch ( final IndexException ie ) { throw ie ; } catch ( final Throwable t ) { error ( t ) ; throw new IndexException ( t ) ; } }
create a new index and return its name . No alias will point to the new index .
23,075
public List < String > purgeIndexes ( final Set < String > prefixes ) throws IndexException { final Set < IndexInfo > indexes = getIndexInfo ( ) ; final List < String > purged = new ArrayList < > ( ) ; if ( Util . isEmpty ( indexes ) ) { return purged ; } purge : for ( final IndexInfo ii : indexes ) { final String idx = ii . getIndexName ( ) ; if ( ! hasPrefix ( idx , prefixes ) ) { continue purge ; } if ( ! Util . isEmpty ( ii . getAliases ( ) ) ) { continue purge ; } purged . add ( idx ) ; } deleteIndexes ( purged ) ; return purged ; }
Remove any index that doesn t have an alias and starts with the given prefix
23,076
public int swapIndex ( final String index , final String alias ) throws IndexException { try { final IndicesAdminClient idx = getAdminIdx ( ) ; final GetAliasesRequestBuilder igarb = idx . prepareGetAliases ( alias ) ; final ActionFuture < GetAliasesResponse > getAliasesAf = idx . getAliases ( igarb . request ( ) ) ; final GetAliasesResponse garesp = getAliasesAf . actionGet ( ) ; final ImmutableOpenMap < String , List < AliasMetaData > > aliasesmeta = garesp . getAliases ( ) ; final IndicesAliasesRequestBuilder iarb = idx . prepareAliases ( ) ; final Iterator < String > it = aliasesmeta . keysIt ( ) ; while ( it . hasNext ( ) ) { final String indexName = it . next ( ) ; for ( final AliasMetaData amd : aliasesmeta . get ( indexName ) ) { if ( amd . getAlias ( ) . equals ( alias ) ) { iarb . removeAlias ( indexName , alias ) ; } } } iarb . addAlias ( index , alias ) ; final ActionFuture < IndicesAliasesResponse > af = idx . aliases ( iarb . request ( ) ) ; af . actionGet ( ) ; return 0 ; } catch ( final ElasticsearchException ese ) { error ( ese ) ; return - 1 ; } catch ( final IndexException ie ) { throw ie ; } catch ( final Throwable t ) { throw new IndexException ( t ) ; } }
Changes the givenm alias to refer tot eh supplied index name
23,077
public Collection < DavChild > syncReport ( final BasicHttpClient cl , final String path , final String syncToken , final Collection < QName > props ) throws Throwable { final StringWriter sw = new StringWriter ( ) ; final XmlEmit xml = getXml ( ) ; addNs ( xml , WebdavTags . namespace ) ; xml . startEmit ( sw ) ; xml . openTag ( WebdavTags . syncCollection ) ; if ( syncToken == null ) { xml . emptyTag ( WebdavTags . syncToken ) ; } else { xml . property ( WebdavTags . syncToken , syncToken ) ; } xml . property ( WebdavTags . synclevel , "1" ) ; xml . openTag ( WebdavTags . prop ) ; xml . emptyTag ( WebdavTags . getetag ) ; if ( props != null ) { for ( final QName pr : props ) { if ( pr . equals ( WebdavTags . getetag ) ) { continue ; } addNs ( xml , pr . getNamespaceURI ( ) ) ; xml . emptyTag ( pr ) ; } } xml . closeTag ( WebdavTags . prop ) ; xml . closeTag ( WebdavTags . syncCollection ) ; final byte [ ] content = sw . toString ( ) . getBytes ( ) ; final int res = sendRequest ( cl , "REPORT" , path , depth0 , "text/xml" , content . length , content ) ; if ( res == HttpServletResponse . SC_NOT_FOUND ) { return null ; } final int SC_MULTI_STATUS = 207 ; if ( res != SC_MULTI_STATUS ) { if ( debug ( ) ) { debug ( "Got response " + res + " for path " + path ) ; } return null ; } final Document doc = parseContent ( cl . getResponseBodyAsStream ( ) ) ; final Element root = doc . getDocumentElement ( ) ; expect ( root , WebdavTags . multistatus ) ; return processResponses ( getChildren ( root ) , null ) ; }
Do a synch report on the targeted collection .
23,078
protected void addNs ( final XmlEmit xml , final String val ) throws Throwable { if ( xml . getNameSpace ( val ) == null ) { xml . addNs ( new NameSpace ( val , null ) , false ) ; } }
Add a namespace
23,079
protected Document parseContent ( final InputStream in ) throws Throwable { DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; factory . setNamespaceAware ( true ) ; DocumentBuilder builder = factory . newDocumentBuilder ( ) ; return builder . parse ( new InputSource ( new InputStreamReader ( in ) ) ) ; }
Parse the content and return the DOM representation .
23,080
public Element parseError ( final InputStream in ) { try { final Document doc = parseContent ( in ) ; final Element root = doc . getDocumentElement ( ) ; expect ( root , WebdavTags . error ) ; final List < Element > els = getChildren ( root ) ; if ( els . size ( ) != 1 ) { return null ; } return els . get ( 0 ) ; } catch ( final Throwable ignored ) { return null ; } }
Parse a DAV error response
23,081
private static Element createResultElement ( final Document document ) { final Element ttResponse = document . createElementNS ( "http://jaxrx.org/" , "result" ) ; ttResponse . setPrefix ( "jaxrx" ) ; return ttResponse ; }
This method creates the TreeTank response XML element .
23,082
public static StreamingOutput buildResponseOfDomLR ( final IStorage pDatabase , final IBackendFactory pStorageFac , final IRevisioning pRevision ) { final StreamingOutput sOutput = new StreamingOutput ( ) { public void write ( final OutputStream output ) throws IOException , WebApplicationException { Document document ; try { document = createSurroundingXMLResp ( ) ; final Element resElement = RESTResponseHelper . createResultElement ( document ) ; List < Element > collections ; try { collections = RESTResponseHelper . createCollectionElementDBs ( pDatabase , document , pStorageFac , pRevision ) ; } catch ( final TTException exce ) { throw new WebApplicationException ( exce ) ; } for ( final Element resource : collections ) { resElement . appendChild ( resource ) ; } document . appendChild ( resElement ) ; final DOMSource domSource = new DOMSource ( document ) ; final StreamResult streamResult = new StreamResult ( output ) ; final Transformer transformer = TransformerFactory . newInstance ( ) . newTransformer ( ) ; transformer . transform ( domSource , streamResult ) ; } catch ( final ParserConfigurationException exce ) { throw new WebApplicationException ( exce ) ; } catch ( final TransformerConfigurationException exce ) { throw new WebApplicationException ( exce ) ; } catch ( final TransformerFactoryConfigurationError exce ) { throw new WebApplicationException ( exce ) ; } catch ( final TransformerException exce ) { throw new WebApplicationException ( exce ) ; } } } ; return sOutput ; }
This method builds the overview for the resources and collection we offer in our implementation .
23,083
public static String getUrl ( final HttpServletRequest request ) { try { final StringBuffer sb = request . getRequestURL ( ) ; if ( sb != null ) { return sb . toString ( ) ; } return request . getRequestURI ( ) ; } catch ( Throwable t ) { return "BogusURL.this.is.probably.a.portal" ; } }
Returns the String url from the request .
23,084
protected void logSessionCounts ( final HttpSession sess , final boolean start ) { StringBuffer sb ; String appname = getAppName ( sess ) ; Counts ct = getCounts ( appname ) ; if ( start ) { sb = new StringBuffer ( "SESSION-START:" ) ; } else { sb = new StringBuffer ( "SESSION-END:" ) ; } sb . append ( getSessionId ( sess ) ) ; sb . append ( ":" ) ; sb . append ( appname ) ; sb . append ( ":" ) ; sb . append ( ct . activeSessions ) ; sb . append ( ":" ) ; sb . append ( ct . totalSessions ) ; sb . append ( ":" ) ; sb . append ( Runtime . getRuntime ( ) . freeMemory ( ) / ( 1024 * 1024 ) ) ; sb . append ( "M:" ) ; sb . append ( Runtime . getRuntime ( ) . totalMemory ( ) / ( 1024 * 1024 ) ) ; sb . append ( "M" ) ; info ( sb . toString ( ) ) ; }
Log the session counters for applications that maintain them .
23,085
private String getSessionId ( final HttpSession sess ) { try { if ( sess == null ) { return "NO-SESSIONID" ; } else { return sess . getId ( ) ; } } catch ( Throwable t ) { return "SESSION-ID-EXCEPTION" ; } }
Get the session id for the loggers .
23,086
public void checkBrowserType ( final HttpServletRequest request ) { String reqpar = request . getParameter ( getBrowserTypeRequestName ( ) ) ; if ( reqpar != null ) { if ( reqpar . equals ( "!" ) ) { setBrowserTypeSticky ( false ) ; } else { setBrowserType ( reqpar ) ; setBrowserTypeSticky ( false ) ; } } reqpar = request . getParameter ( getBrowserTypeStickyRequestName ( ) ) ; if ( reqpar != null ) { if ( reqpar . equals ( "!" ) ) { setBrowserTypeSticky ( false ) ; } else { setBrowserType ( reqpar ) ; setBrowserTypeSticky ( true ) ; } } }
Allow user to explicitly set the browser type .
23,087
public void checkContentType ( final HttpServletRequest request ) { String reqpar = request . getParameter ( getContentTypeRequestName ( ) ) ; if ( reqpar != null ) { if ( reqpar . equals ( "!" ) ) { setContentTypeSticky ( false ) ; } else { setContentType ( reqpar ) ; setContentTypeSticky ( false ) ; } } reqpar = request . getParameter ( getContentTypeStickyRequestName ( ) ) ; if ( reqpar != null ) { if ( reqpar . equals ( "!" ) ) { setContentTypeSticky ( false ) ; } else { setContentType ( reqpar ) ; setContentTypeSticky ( true ) ; } } }
Allow user to explicitly set the content type .
23,088
public void checkContentName ( final HttpServletRequest request ) { String reqpar = request . getParameter ( getContentNameRequestName ( ) ) ; setContentName ( reqpar ) ; }
Allow user to explicitly set the filename of the content .
23,089
public void checkSkinName ( final HttpServletRequest request ) { String reqpar = request . getParameter ( getSkinNameRequestName ( ) ) ; if ( reqpar != null ) { if ( reqpar . equals ( "!" ) ) { setSkinNameSticky ( false ) ; } else { setSkinName ( reqpar ) ; setSkinNameSticky ( false ) ; } } reqpar = request . getParameter ( getSkinNameStickyRequestName ( ) ) ; if ( reqpar != null ) { if ( reqpar . equals ( "!" ) ) { setSkinNameSticky ( false ) ; } else { setSkinName ( reqpar ) ; setSkinNameSticky ( true ) ; } } }
Allow user to explicitly set the skin name .
23,090
public void checkRefreshXslt ( final HttpServletRequest request ) { String reqpar = request . getParameter ( getRefreshXSLTRequestName ( ) ) ; if ( reqpar == null ) { return ; } if ( reqpar . equals ( "yes" ) ) { setForceXSLTRefresh ( true ) ; } if ( reqpar . equals ( "always" ) ) { setForceXSLTRefreshAlways ( true ) ; } if ( reqpar . equals ( "!" ) ) { setForceXSLTRefreshAlways ( false ) ; } }
Allow user to indicate how we should refresh the xslt .
23,091
public void checkNoXSLT ( final HttpServletRequest request ) { String reqpar = request . getParameter ( getNoXSLTRequestName ( ) ) ; if ( reqpar != null ) { if ( reqpar . equals ( "!" ) ) { setNoXSLTSticky ( false ) ; } else { setNoXSLT ( true ) ; } } reqpar = request . getParameter ( getNoXSLTStickyRequestName ( ) ) ; if ( reqpar != null ) { if ( reqpar . equals ( "!" ) ) { setNoXSLTSticky ( false ) ; } else { setNoXSLT ( true ) ; setNoXSLTSticky ( true ) ; } } }
Allow user to suppress XSLT transform for one request . Used for debugging - provides the raw xml .
23,092
public static Map < Long , LogEntry > getBranchLog ( String [ ] branches , long startRevision , long endRevision , String baseUrl , String user , String pwd ) throws IOException , SAXException { try ( InputStream inStr = getBranchLogStream ( branches , startRevision , endRevision , baseUrl , user , pwd ) ) { return new SVNLogFileParser ( branches ) . parseContent ( inStr ) ; } catch ( SAXException e ) { throw new SAXException ( "While parsing branch-log of " + Arrays . toString ( branches ) + ", start: " + startRevision + ", end: " + endRevision + " with user " + user , e ) ; } }
Retrieve the XML - log of changes on the given branch in a specified range of revisions .
23,093
public static InputStream getRemoteFileContent ( String file , long revision , String baseUrl , String user , String pwd ) throws IOException { CommandLine cmdLine = new CommandLine ( SVN_CMD ) ; cmdLine . addArgument ( CMD_CAT ) ; addDefaultArguments ( cmdLine , user , pwd ) ; cmdLine . addArgument ( "-r" ) ; cmdLine . addArgument ( Long . toString ( revision ) ) ; cmdLine . addArgument ( baseUrl + file ) ; return ExecutionHelper . getCommandResult ( cmdLine , new File ( "." ) , 0 , 120000 ) ; }
Retrieve the contents of a file from the web - interface of the SVN server .
23,094
public static boolean branchExists ( String branch , String baseUrl ) { CommandLine cmdLine = new CommandLine ( SVN_CMD ) ; cmdLine . addArgument ( CMD_LOG ) ; cmdLine . addArgument ( OPT_XML ) ; addDefaultArguments ( cmdLine , null , null ) ; cmdLine . addArgument ( "-r" ) ; cmdLine . addArgument ( "HEAD:HEAD" ) ; cmdLine . addArgument ( baseUrl + branch ) ; try ( InputStream inStr = ExecutionHelper . getCommandResult ( cmdLine , new File ( "." ) , 0 , 120000 ) ) { return true ; } catch ( IOException e ) { log . log ( Level . FINE , "Branch " + branch + " not found or other error" , e ) ; return false ; } }
Check if the given branch already exists
23,095
public static long getBranchRevision ( String branch , String baseUrl ) throws IOException { CommandLine cmdLine = new CommandLine ( SVN_CMD ) ; cmdLine . addArgument ( CMD_LOG ) ; cmdLine . addArgument ( OPT_XML ) ; addDefaultArguments ( cmdLine , null , null ) ; cmdLine . addArgument ( "-v" ) ; cmdLine . addArgument ( "-r0:HEAD" ) ; cmdLine . addArgument ( "--stop-on-copy" ) ; cmdLine . addArgument ( "--limit" ) ; cmdLine . addArgument ( "1" ) ; cmdLine . addArgument ( baseUrl + branch ) ; try ( InputStream inStr = ExecutionHelper . getCommandResult ( cmdLine , new File ( "." ) , 0 , 120000 ) ) { String xml = IOUtils . toString ( inStr , "UTF-8" ) ; log . info ( "XML:\n" + xml ) ; Matcher matcher = Pattern . compile ( "copyfrom-rev=\"([0-9]+)\"" ) . matcher ( xml ) ; if ( ! matcher . find ( ) ) { throw new IOException ( "Could not find copyfrom-rev entry in xml: " + xml ) ; } log . info ( "Found copyfrom-rev: " + matcher . group ( 1 ) ) ; return Long . parseLong ( matcher . group ( 1 ) ) ; } }
Return the revision from which the branch was branched off .
23,096
public static long getLastRevision ( String branch , String baseUrl , String user , String pwd ) throws IOException { CommandLine cmdLine = new CommandLine ( SVN_CMD ) ; cmdLine . addArgument ( "info" ) ; addDefaultArguments ( cmdLine , user , pwd ) ; cmdLine . addArgument ( baseUrl + branch ) ; try ( InputStream inStr = ExecutionHelper . getCommandResult ( cmdLine , new File ( "." ) , 0 , 120000 ) ) { String info = IOUtils . toString ( inStr , "UTF-8" ) ; log . info ( "Info:\n" + info ) ; Matcher matcher = Pattern . compile ( "Revision: ([0-9]+)" ) . matcher ( info ) ; if ( ! matcher . find ( ) ) { throw new IOException ( "Could not find Revision entry in info-output: " + info ) ; } log . info ( "Found rev: " + matcher . group ( 1 ) + " for branch " + branch ) ; return Long . parseLong ( matcher . group ( 1 ) ) ; } }
Return the last revision of the given branch . Uses the full svn repository if branch is
23,097
public static InputStream getPendingCheckins ( File directory ) throws IOException { CommandLine cmdLine = new CommandLine ( SVN_CMD ) ; cmdLine . addArgument ( CMD_STATUS ) ; addDefaultArguments ( cmdLine , null , null ) ; return ExecutionHelper . getCommandResult ( cmdLine , directory , - 1 , 120000 ) ; }
Performs a svn status and returns the list of changes in the svn tree at the given directory in the format that the svn command provides them .
23,098
public static InputStream recordMerge ( File directory , String branchName , long ... revisions ) throws IOException { CommandLine cmdLine = new CommandLine ( SVN_CMD ) ; cmdLine . addArgument ( CMD_MERGE ) ; addDefaultArguments ( cmdLine , null , null ) ; cmdLine . addArgument ( "--record-only" ) ; cmdLine . addArgument ( "-c" ) ; StringBuilder revs = new StringBuilder ( ) ; for ( long revision : revisions ) { revs . append ( revision ) . append ( "," ) ; } cmdLine . addArgument ( revs . toString ( ) ) ; cmdLine . addArgument ( "^" + branchName ) ; return ExecutionHelper . getCommandResult ( cmdLine , directory , 0 , 120000 ) ; }
Record a manual merge from one branch to the local working directory .
23,099
public static boolean verifyNoPendingChanges ( File directory ) throws IOException { log . info ( "Checking that there are no pending changes on trunk-working copy" ) ; try ( InputStream inStr = getPendingCheckins ( directory ) ) { List < String > lines = IOUtils . readLines ( inStr , "UTF-8" ) ; if ( lines . size ( ) > 0 ) { log . info ( "Found the following checkouts:\n" + ArrayUtils . toString ( lines . toArray ( ) , "\n" ) ) ; return true ; } } return false ; }
Check if there are pending changes on the branch returns true if changes are found .