idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
19,000
public void publishSubmissions ( List < ISubmission > submissions ) throws Exception { ParadataPublisher publisher = new ParadataPublisher ( node ) ; for ( ISubmission submission : submissions ) { publisher . publish ( submission ) ; } }
Publish a collection of submissions ; this can be a mix of submission types and be about different resources
19,001
public Future < ActivityData > submit ( ActivityCallable callable ) throws ActivityException { logger . info ( "submitting activity to asynchronous EJB..." ) ; return new AsyncResult < ActivityData > ( callable . call ( ) ) ; }
Assigns the given activity to the asynchronous EJB for background execution .
19,002
public RpcRequest getRequest ( final Invocation invocation ) { if ( invocation == null ) throw new NullPointerException ( "invocation" ) ; MethodDescriptor < ? , ? > method = invocation . getMethod ( ) ; if ( ! method . isTerminal ( ) ) { throw new IllegalArgumentException ( "Last invocation method must be terminal" ) ; } RpcRequest request = new RpcRequest ( method . isPost ( ) ? RpcRequest . POST : RpcRequest . GET ) ; for ( Invocation invocation1 : invocation . toChain ( ) ) { writeInvocation ( request , invocation1 ) ; } return request ; }
Converts an invocation into an rpc request .
19,003
< V > String toJson ( final DataTypeDescriptor < V > descriptor , final V arg ) { String s = format . write ( arg , descriptor , false ) ; TypeEnum type = descriptor . getType ( ) ; if ( type == TypeEnum . STRING || type == TypeEnum . ENUM || type == TypeEnum . DATETIME ) { s = s . substring ( 1 , s . length ( ) - 1 ) ; } return s ; }
Serializes an argument to JSON strips the quotes .
19,004
public Invocation getInvocation ( final RpcRequest request , InterfaceDescriptor < ? > descriptor ) { if ( request == null ) throw new NullPointerException ( "request" ) ; if ( descriptor == null ) throw new NullPointerException ( "descriptor" ) ; Invocation invocation = null ; LinkedList < String > parts = splitPath ( request . getRelativePath ( ) ) ; while ( ! parts . isEmpty ( ) ) { String part = parts . removeFirst ( ) ; MethodDescriptor < ? , ? > method = descriptor . getMethod ( part ) ; if ( method == null ) { throw RpcException . badRequest ( "Method is not found: " + part ) ; } if ( method . isPost ( ) && ! request . isPost ( ) ) { throw RpcException . methodNotAllowed ( "Method not allowed, POST required" ) ; } List < Object > args = readArgs ( method , parts , request . getQuery ( ) , request . getPost ( ) ) ; invocation = invocation != null ? invocation . next ( method , args . toArray ( ) ) : Invocation . root ( method , args . toArray ( ) ) ; if ( method . isTerminal ( ) ) { break ; } descriptor = ( InterfaceDescriptor < ? > ) method . getResult ( ) ; } if ( ! parts . isEmpty ( ) ) { throw RpcException . badRequest ( "Failed to parse an invocation chain" ) ; } if ( invocation == null ) { throw RpcException . badRequest ( "Invocation chain required" ) ; } if ( ! invocation . getMethod ( ) . isTerminal ( ) ) { throw RpcException . badRequest ( "The last method must be a terminal one. " + "It must return a data type or be void." ) ; } return invocation ; }
Parses an invocation from an rpc request .
19,005
< V > V fromJson ( final DataTypeDescriptor < V > descriptor , String value ) { if ( value == null ) { return null ; } TypeEnum type = descriptor . getType ( ) ; if ( type == TypeEnum . STRING || type == TypeEnum . DATETIME || type == TypeEnum . ENUM ) { if ( ! value . startsWith ( "\"" ) && ! value . endsWith ( "\"" ) ) { value = "\"" + value + "\"" ; } } return format . read ( value , descriptor ) ; }
Parses an argument from an unquoted JSON string .
19,006
static String urlencode ( final String s ) { try { return URLEncoder . encode ( s , CHARSET_NAME ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } }
Url - encodes a string .
19,007
static String urldecode ( final String s ) { try { return URLDecoder . decode ( s , CHARSET_NAME ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } }
Url - decodes a string .
19,008
public String getMessage ( final String messageKey , final Object ... objects ) { return getFormattedMessage ( getMessagePattern ( messageKey ) , objects ) ; }
Gets the message as defined by the provided messageKey and substitutes the provided object values in the message .
19,009
public List < RegistryListener < K , V > > getListeners ( ) { return new LinkedList < RegistryListener < K , V > > ( listeners ) ; }
Retrieve a copy of the list of listeners to this registry .
19,010
public V put ( K putKey , V putValue ) { V oldValue = this . store . put ( putKey , putValue ) ; if ( oldValue == null ) { this . notificationExecutor . firePutNotification ( this . listeners . iterator ( ) , putKey , putValue ) ; } else { this . notificationExecutor . fireReplaceNotification ( this . listeners . iterator ( ) , putKey , oldValue , putValue ) ; } return oldValue ; }
Put the given entry into the registry under the specified key .
19,011
public V putIfAbsent ( K putKey , V putValue ) { V existingValue = this . store . putIfAbsent ( putKey , putValue ) ; if ( existingValue == null ) { this . notificationExecutor . firePutNotification ( this . listeners . iterator ( ) , putKey , putValue ) ; } return existingValue ; }
Add the given entry into the registry under the specified key but only if the key is not already registered .
19,012
public V remove ( K removeKey ) { V removedValue = this . store . remove ( removeKey ) ; if ( removedValue != null ) { this . notificationExecutor . fireRemoveNotification ( this . listeners . iterator ( ) , removeKey , removedValue ) ; } return removedValue ; }
Remove the given entry from the registry under the specified key .
19,013
public boolean remove ( K removeKey , V removeValue ) { boolean removedInd = this . store . remove ( removeKey , removeValue ) ; if ( removedInd ) { this . notificationExecutor . fireRemoveNotification ( this . listeners . iterator ( ) , removeKey , removeValue ) ; } return removedInd ; }
Remove the given entry from the registry under the specified key only if the value matches the one given .
19,014
void set ( Instant effectiveFrom , T value ) { T oldValue = get ( ) ; values . put ( effectiveFrom , value ) ; notifyListeners ( oldValue , value ) ; }
Sets the value of the property at the specified time .
19,015
public void purge ( Instant limit ) { Instant firstKeeper = values . floorKey ( limit ) ; if ( firstKeeper == null ) return ; Set < Instant > purgables = values . headMap ( firstKeeper ) . keySet ( ) ; if ( purgables == null ) return ; for ( Instant purgable : purgables ) { values . remove ( purgable ) ; } }
Removes values no longer in effect at the specified point in time .
19,016
public static void register ( final MBeanServer mbs , final Object obj ) { final ObjectName mBeanName = JmxUtils . getObjectName ( obj . getClass ( ) ) ; try { mbs . registerMBean ( obj , mBeanName ) ; } catch ( final InstanceAlreadyExistsException e ) { LOG . error ( "Could not start JMX" , e ) ; } catch ( final MBeanRegistrationException e ) { LOG . error ( "Could not register" , e ) ; } catch ( final NotCompliantMBeanException e ) { LOG . error ( "MBean error" , e ) ; } }
Registers the specified object as an MBean with the specified server using standard conventions for the bean name .
19,017
public String getUid ( String category , String projectName , String projectVersion , boolean force ) { String uid = null ; if ( ! force ) { uid = readUid ( new File ( uidDirectory , "latest" ) ) ; } if ( uid != null && uidAlreadyUsed ( category , projectName , uid ) ) { uid = null ; } if ( uid == null ) { uid = generateUid ( ) ; writeUid ( new File ( uidDirectory , "latest" ) , uid ) ; } writeUid ( getUidFile ( category , projectName , projectVersion ) , uid ) ; return uid ; }
Generate a UID or retrieve the latest if it is valid depending the context given by the category project name and project version
19,018
private void writeUid ( File uidFile , String uid ) { BufferedWriter bw = null ; try { bw = new BufferedWriter ( new FileWriter ( uidFile ) ) ; bw . write ( uid ) ; } catch ( IOException ioe ) { } finally { if ( bw != null ) { try { bw . close ( ) ; } catch ( IOException ioe ) { } } } }
Write a UID file
19,019
private boolean uidAlreadyUsed ( String category , String projectName , String uid ) { if ( uid == null ) { return false ; } else { for ( File versionDirectory : getUidFilesForProject ( category , projectName ) ) { String uidRead = readUid ( new File ( versionDirectory , "latest" ) ) ; if ( uidRead != null && ! uidRead . isEmpty ( ) ) { if ( uidRead . equals ( uid ) ) { return true ; } } } return false ; } }
Check if a UID was already used in any context
19,020
private List < File > getUidFilesForProject ( String category , String projectName ) { File categoryDirectory = new File ( uidDirectory , category ) ; if ( ! categoryDirectory . exists ( ) || ( categoryDirectory . exists ( ) && categoryDirectory . isFile ( ) ) ) { return new ArrayList < > ( ) ; } File projectDirectory = new File ( categoryDirectory , projectName ) ; if ( ! projectDirectory . exists ( ) || ( projectDirectory . exists ( ) && projectDirectory . isFile ( ) ) ) { return new ArrayList < > ( ) ; } List < File > versionDirectories = new ArrayList < > ( ) ; for ( File electableDirectory : projectDirectory . listFiles ( ) ) { if ( electableDirectory . isDirectory ( ) ) { versionDirectories . add ( electableDirectory ) ; } } return versionDirectories ; }
Retrieve the list of the version directories for the project
19,021
private File getUidFile ( String category , String projectName , String projectVersion ) { File categoryDirectory = new File ( uidDirectory , category ) ; if ( categoryDirectory . exists ( ) && categoryDirectory . isFile ( ) ) { throw new IllegalArgumentException ( "The category file for the UID storage is not a directory" ) ; } else if ( ! categoryDirectory . exists ( ) ) { categoryDirectory . mkdir ( ) ; } File projectDirectory = new File ( categoryDirectory , projectName ) ; if ( projectDirectory . exists ( ) && projectDirectory . isFile ( ) ) { throw new IllegalArgumentException ( "The project file for the UID store is not a directory" ) ; } else if ( ! projectDirectory . exists ( ) ) { projectDirectory . mkdir ( ) ; } File versionDirectory = new File ( projectDirectory , projectVersion ) ; if ( versionDirectory . exists ( ) && versionDirectory . isFile ( ) ) { throw new IllegalArgumentException ( "The version file for the UID store is not a directory" ) ; } else if ( ! versionDirectory . exists ( ) ) { versionDirectory . mkdir ( ) ; } return new File ( versionDirectory , "latest" ) ; }
Get the UID file regarding the category project name and project version
19,022
protected final MapDelta < K , V > genRemove ( final Collection < K > toRemove ) { return toRemove . isEmpty ( ) ? Nop . instance ( ) : new Remove < > ( toRemove ) ; }
Create a delta consisting of items to remove .
19,023
protected final MapDelta < K , V > genUpdates ( final K key , final Function < ? super V , ? extends V > mutate ) { return new Update < > ( key , mutate ) ; }
Create a delta consisting of a single update .
19,024
protected final MapDelta < K , V > genUpdates ( final Map < K , Function < ? super V , ? extends V > > mutators ) { return mutators . isEmpty ( ) ? Nop . instance ( ) : new Update < > ( mutators ) ; }
Create a delta consisting of updates .
19,025
protected final String getPrimaryUserAttribute ( PortletRequest request ) { final PortletPreferences preferences = request . getPreferences ( ) ; @ SuppressWarnings ( "unchecked" ) final Map < String , String > userAttributes = ( Map < String , String > ) request . getAttribute ( PortletRequest . USER_INFO ) ; final String [ ] attributeNames = preferences . getValues ( primaryUserAttributesPreference , new String [ 0 ] ) ; for ( final String attributeName : attributeNames ) { final String emplid = userAttributes . get ( attributeName ) ; if ( StringUtils . isNotEmpty ( emplid ) ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Found emplid '" + emplid + "' for under attribute: " + attributeName ) ; } return emplid ; } } logger . warn ( "Could not find a value for any of the user attributes " + Arrays . toString ( attributeNames ) + " specified by preference: " + primaryUserAttributesPreference ) ; throw new AccessDeniedException ( "No primary attribute found in attributes: " + Arrays . toString ( attributeNames ) ) ; }
Get the user s primary attribute .
19,026
public static String getScheme ( final URI uri ) throws NormalizationException { final String scheme = Strings . emptyToNull ( uri . getScheme ( ) ) ; if ( scheme == null && hasPort ( uri ) ) { return NetProtocol . find ( getPort ( uri ) , DEFAULT_PROTOCOL ) . getScheme ( ) ; } else if ( scheme == null ) { return DEFAULT_PROTOCOL . getScheme ( ) ; } return scheme ; }
Returns the scheme of the given URI or the scheme of the URI s port if there is a port . If there is no default then the scheme of the default protocol is returned .
19,027
public static String getHost ( final URI uri ) throws NormalizationException { final String host = Strings . emptyToNull ( uri . getHost ( ) ) ; if ( host == null ) { throw new NormalizationException ( uri . toString ( ) , "No host in URI" ) ; } return host ; }
Returns the host of the given URI or throws an exception if the URI has no host .
19,028
public static int getPort ( final URI uri ) throws NormalizationException { if ( hasPort ( uri ) ) { return uri . getPort ( ) ; } Integer port = NetProtocol . find ( getScheme ( uri ) ) . getPort ( ) ; if ( null == port ) { throw new NormalizationException ( uri . toString ( ) , "Cannot determine port" ) ; } return port ; }
Returns the port of the given URI . If not specified it returns the default port based on scheme . If the default port cannot be determined then it throws an exception .
19,029
private static String prependSlash ( final String path ) { if ( path . length ( ) == 0 || path . charAt ( 0 ) != '/' ) { return "/" + path ; } return path ; }
Prepends a string with a slash if there isn t one already
19,030
public static String toRawString ( final URI uri , final boolean strict ) throws NormalizationException { final StringBuffer sb = new StringBuffer ( getScheme ( uri ) ) . append ( "://" ) ; if ( hasUserInfo ( uri ) ) { sb . append ( getRawUserInfo ( uri ) ) . append ( '@' ) ; } sb . append ( getHost ( uri ) ) . append ( ':' ) . append ( getPort ( uri ) ) . append ( getRawPath ( uri , strict ) ) ; if ( hasQuery ( uri ) ) { sb . append ( '?' ) . append ( getRawQuery ( uri , strict ) ) ; } if ( hasFragment ( uri ) ) { sb . append ( '#' ) . append ( getRawFragment ( uri , strict ) ) ; } return sb . toString ( ) ; }
Returns the entire URL as a string with its raw components normalized
19,031
public static URI replaceHost ( final URI uri , final String newHost , final boolean strict ) throws URISyntaxException { final URI hostUri = newUri ( newHost , strict ) ; return newUri ( uri . toString ( ) . replaceFirst ( Pattern . quote ( uri . getHost ( ) ) , Matcher . quoteReplacement ( hostUri . getHost ( ) ) ) , strict ) ; }
Returns a new URI with the host portion replaced by the new host portion
19,032
public static URI toDirectory ( final URI uri , final boolean strict ) throws NormalizationException { return resolve ( uri , getRawDirectory ( uri , strict ) , strict ) ; }
Returns a URI that has been truncated to its directory .
19,033
public static URI toPath ( final URI uri , final boolean strict ) throws NormalizationException { return resolve ( uri , getRawPath ( uri , strict ) , strict ) ; }
Returns a URI that has been truncated to its path .
19,034
public static boolean isNormalized ( final URI uri , final boolean strict ) { return ! Strings . isNullOrEmpty ( uri . getScheme ( ) ) && Objects . equal ( Uris . getRawUserInfo ( uri ) , uri . getRawUserInfo ( ) ) && ! Strings . isNullOrEmpty ( uri . getHost ( ) ) && hasPort ( uri ) && Objects . equal ( Uris . getRawPath ( uri , strict ) , uri . getRawPath ( ) ) && Objects . equal ( Uris . getRawQuery ( uri , strict ) , uri . getRawQuery ( ) ) && Objects . equal ( Uris . getRawFragment ( uri , strict ) , uri . getRawFragment ( ) ) ; }
Returns whether or not the given URI is normalized according to our rules .
19,035
public static URI createUri ( final String url , final boolean strict ) { try { return newUri ( url , strict ) ; } catch ( URISyntaxException e ) { throw new AssertionError ( "Error creating URI: " + e . getMessage ( ) ) ; } }
Creates a new URI based off the given string . This function differs from newUri in that it throws an AssertionError instead of a URISyntaxException - so it is suitable for use in static locations as long as you can be sure it is a valid string that is being parsed .
19,036
public void resize ( int newSize ) { if ( newSize > elements . length ) { reallocate ( Math . max ( newSize , 2 * elements . length ) ) ; } else { for ( int i = size ; i < newSize ; i ++ ) { elements [ i ] = 0 ; } } size = newSize ; }
Resizes the array to the specified length truncating or zero - padding the array as necessary .
19,037
public void ensureCapacity ( int size ) { if ( size > elements . length ) { reallocate ( Math . max ( size , 2 * elements . length ) ) ; } }
Ensures that there is enough room in the array to hold the specified number of elements .
19,038
public void handleNotification ( Notification notification , Object handback ) { if ( notification instanceof MBeanServerNotification ) { MBeanServerNotification mbeanNotification = ( MBeanServerNotification ) notification ; if ( mbeanNotification . getType ( ) . equals ( "JMX.mbean.registered" ) ) { jmxTree = null ; registerAsNotificationListener ( mbeanNotification . getMBeanName ( ) ) ; } else if ( mbeanNotification . getType ( ) . equals ( "JMX.mbean.unregistered" ) ) { jmxTree = null ; } } for ( NotificationListener listener : listeners ) { listener . handleNotification ( notification , handback ) ; } }
Handles JMX Notifications and relays notifications to the notification listers registered with this service .
19,039
public static < T > Iterator < T > cycle ( T ... elements ) { return cycle ( Lists . newArrayList ( elements ) ) ; }
Returns an iterator that cycles indefinitely over the provided elements .
19,040
public void setValue ( Object value , long timeout ) { _value = value ; _expiration = System . currentTimeMillis ( ) + timeout ; }
Sets a new value and extends its expiration .
19,041
public static void trustAllHosts ( ) { TrustManager [ ] trustAllCerts = new TrustManager [ ] { new X509TrustManager ( ) { public X509Certificate [ ] getAcceptedIssuers ( ) { return new X509Certificate [ ] { } ; } public void checkClientTrusted ( X509Certificate [ ] chain , String authType ) throws CertificateException { } public void checkServerTrusted ( X509Certificate [ ] chain , String authType ) throws CertificateException { } } } ; try { SSLContext sslContext = SSLContext . getInstance ( "TLS" ) ; sslContext . init ( null , trustAllCerts , new java . security . SecureRandom ( ) ) ; HttpsURLConnection . setDefaultSSLSocketFactory ( sslContext . getSocketFactory ( ) ) ; HttpsURLConnection . setDefaultHostnameVerifier ( ( String var1 , SSLSession var2 ) -> { return true ; } ) ; } catch ( Exception exception ) { log . error ( exception ) ; } }
Sometimes a remote source is self - signed or not otherwise trusted
19,042
public AccountInfo getAccountInfo ( ) { OAuthRequest request = new OAuthRequest ( Verb . GET , INFO_URL ) ; service . signRequest ( accessToken , request ) ; String content = check ( request . send ( ) ) . getBody ( ) ; return Json . parse ( content , AccountInfo . class ) ; }
Returns information about current user s account .
19,043
public Entry getMetadata ( String path , int fileLimit ) { return getMetadata ( path , fileLimit , null , true ) ; }
Returns metadata information about specified resource with specified maximum child entries count .
19,044
public Entry copy ( String from , String to ) { OAuthRequest request = new OAuthRequest ( Verb . GET , FILE_OPS_COPY_URL ) ; request . addQuerystringParameter ( "root" , "dropbox" ) ; request . addQuerystringParameter ( "from_path" , encode ( from ) ) ; request . addQuerystringParameter ( "to_path" , encode ( to ) ) ; service . signRequest ( accessToken , request ) ; String content = checkCopy ( request . send ( ) ) . getBody ( ) ; return Json . parse ( content , Entry . class ) ; }
Copy file from specified source to specified target .
19,045
public Entry move ( String from , String to ) { OAuthRequest request = new OAuthRequest ( Verb . GET , FILE_OPS_MOVE_URL ) ; request . addQuerystringParameter ( "root" , "dropbox" ) ; request . addQuerystringParameter ( "from_path" , encode ( from ) ) ; request . addQuerystringParameter ( "to_path" , encode ( to ) ) ; service . signRequest ( accessToken , request ) ; String content = checkMove ( request . send ( ) ) . getBody ( ) ; return Json . parse ( content , Entry . class ) ; }
Move file from specified source to specified target .
19,046
public Entry createFolder ( String path ) { OAuthRequest request = new OAuthRequest ( Verb . GET , FILE_OPS_CREATE_FOLDER_URL ) ; request . addQuerystringParameter ( "root" , "dropbox" ) ; request . addQuerystringParameter ( "path" , encode ( path ) ) ; service . signRequest ( accessToken , request ) ; String content = checkCreateFolder ( request . send ( ) ) . getBody ( ) ; return Json . parse ( content , Entry . class ) ; }
Create folder with specified path .
19,047
public void putFile ( File file , String path ) throws IOException { OAuthRequest request = new OAuthRequest ( Verb . POST , FILES_URL + encode ( path ) ) ; Multipart . attachFile ( file , request ) ; service . signRequest ( accessToken , request ) ; checkFiles ( request . send ( ) ) ; }
Upload specified file to specified folder .
19,048
public EntryDownload getFile ( String path ) { OAuthRequest request = new OAuthRequest ( Verb . GET , FILES_URL + encode ( path ) ) ; service . signRequest ( accessToken , request ) ; Response response = checkFiles ( request . send ( ) ) ; return new EntryDownload ( response , path ) ; }
Download file with specified path .
19,049
public Corpus getCorpus ( ) { return Corpus . builder ( ) . distributed ( distributed ) . source ( inputFormat , input ) . build ( ) ; }
Creates a corpus based on the command line parameters .
19,050
@ SuppressWarnings ( "unchecked" ) public < B , T extends B , D extends B > B resolveBeanWithDefaultClass ( Class < T > typeToResolve , Class < D > defaultType ) { if ( typeToResolve == null ) { return null ; } Set < Bean < ? > > candidates = this . manager . getBeans ( typeToResolve ) ; if ( ! candidates . iterator ( ) . hasNext ( ) ) { this . logger . trace ( "No candidates for: {}" , typeToResolve . getName ( ) ) ; return resolveBeanWithDefaultClass ( defaultType , null ) ; } this . logger . trace ( "Requesting resolution on: {}" , typeToResolve . getName ( ) ) ; Bean < ? > bean = candidates . iterator ( ) . next ( ) ; CreationalContext < ? > context = this . manager . createCreationalContext ( bean ) ; Type type = ( Type ) bean . getTypes ( ) . iterator ( ) . next ( ) ; B result = ( B ) this . manager . getReference ( bean , type , context ) ; this . logger . trace ( "Resolved to: {}" , result . getClass ( ) . getName ( ) ) ; return result ; }
Resolve managed bean for given type
19,051
String createDeleteAllPreparedSQLStatement ( ) { final StringGrabber sgSQL = new StringGrabber ( ) ; final DBTable table = mModelClazz . getAnnotation ( DBTable . class ) ; final String tableName = table . tableName ( ) ; sgSQL . append ( "DELETE FROM " + tableName ) ; return sgSQL . toString ( ) ; }
Create the all - delete statement
19,052
public static String start ( String id ) { if ( idLocal . get ( ) != null ) { return null ; } else { MDC . put ( "sessionId" , id ) ; if ( LOG . isDebugEnabled ( ) ) LOG . debug ( "Initialize session id = " + id ) ; idLocal . set ( id ) ; return id ; } }
Run some code in session
19,053
public static SessionBean getSessionBean ( ) { String id = idLocal . get ( ) ; if ( id == null ) return null ; SessionBean s = getSessionMap ( ) . get ( id ) ; if ( s != null && ( System . currentTimeMillis ( ) - s . lastUsed ) > TTL ) { if ( LOG . isDebugEnabled ( ) ) LOG . debug ( "Discarding session " + id + " with livetime=" + ( System . currentTimeMillis ( ) - s . lastUsed ) + "ms" ) ; s = null ; } if ( s == null ) s = new SessionBean ( ) ; s . lastUsed = System . currentTimeMillis ( ) ; updateSessionBean ( s ) ; s . id = id ; return s ; }
Return current session data
19,054
public ResultFunction < M , G , R > resultFunction ( ) throws MethodAmbiguouslyDefinedException { final MasterClass masterClass = new MasterClass ( this . master . getClass ( ) ) ; final GuestClass guestClass = new GuestClass ( this . guest . getClass ( ) ) ; final GenericsContext context = GenericsResolver . resolve ( this . getClass ( ) ) . type ( Dispatch . class ) ; final ReturnClass returnClass = new ReturnClass ( context . generics ( ) . get ( 2 ) ) ; ResultFunction < M , G , R > method ; final Set < Method > methods = new ByParameterClass ( masterClass , guestClass , this . methodName , returnClass , new ByParameterInterfaces ( masterClass , guestClass , this . methodName , returnClass , new ByParameterSuperClass ( masterClass , guestClass , this . methodName , returnClass , new EmptyMethods ( ) ) ) ) . findMethods ( ) ; if ( methods . isEmpty ( ) ) { method = new ResultFunction < M , G , R > ( ) { public String toString ( ) { return "default method" ; } public R apply ( final M m , final G g ) { return Dispatch . this . defaultMethod . apply ( m , g ) ; } } ; } else { final Iterator < Method > iterator = methods . iterator ( ) ; MethodRepresentation currentMethod = new OneMethod ( iterator . next ( ) ) ; while ( iterator . hasNext ( ) ) { final MethodRepresentation nextMethod = new OneMethod ( iterator . next ( ) ) ; currentMethod = new OneOfTwoMethods ( currentMethod , nextMethod ) ; } final Method finalMethod = currentMethod . toMethod ( ) ; method = new MethodFunction < > ( finalMethod ) ; } return method ; }
the result function
19,055
private synchronized void registerWatchdog ( Long key , Watchdog wd ) { if ( wd == null ) { throw new NullPointerException ( "Thread" ) ; } if ( wd . getThread ( ) == null ) { wd . restart ( ) ; } registeredWachdogs . put ( key , wd ) ; }
Fuegt einen Thread hinzu
19,056
private void kill ( ) { Set copy = new HashSet ( registeredWachdogs . values ( ) ) ; Iterator iter = copy . iterator ( ) ; while ( iter . hasNext ( ) ) { Watchdog th = ( Watchdog ) iter . next ( ) ; if ( th . isAlive ( ) ) { if ( log . isInfoEnabled ( ) ) { log . info ( ". . . Killing Watchdog " + th . getId ( ) ) ; } th . kill ( ) ; } } this . joinAllThreads ( ) ; iter = copy . iterator ( ) ; while ( iter . hasNext ( ) ) { this . deregisterWatchdog ( ( IWatchdog ) iter . next ( ) ) ; } }
killt alle Threads der Gruppe
19,057
public synchronized void shutdown ( ) { this . shutdownManagementWatchdogs ( ) ; Iterator iter = registeredWachdogs . values ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { IWatchdog th = ( IWatchdog ) iter . next ( ) ; th . deactivate ( ) ; if ( log . isInfoEnabled ( ) ) { log . info ( ". . . Deactivating Watchdog " + th . getId ( ) ) ; } } this . kill ( ) ; }
killt alle Threads der Gruppe und wartet bis auch der letzte beendet ist . Es wird der evtl . Exceptionhandler geschlossen .
19,058
private void joinAllThreads ( ) { Iterator iter = registeredWachdogs . values ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { Watchdog th = ( Watchdog ) iter . next ( ) ; boolean isJoining = true ; if ( ! th . isAlive ( ) && log . isDebugEnabled ( ) ) { log . debug ( "Thread " + th + " finished" ) ; } while ( th . isAlive ( ) && isJoining ) { try { th . getThread ( ) . join ( ) ; isJoining = false ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Thread " + th + " joined and finished" ) ; } } catch ( InterruptedException e ) { } } } }
wartet bis auch der letzte Thread beendet ist
19,059
public void shutdown ( Long id ) { Watchdog wd = ( Watchdog ) this . registeredWachdogs . get ( id ) ; if ( wd == null ) { throw new IllegalStateException ( "Watchdog " + id + " ist not registered" ) ; } wd . kill ( ) ; this . deregisterWatchdog ( id ) ; }
stops the the Watchdog with the given id The executing thread of the watchdog is stopped and the watchdog is removed from the registry . It can nor be restarted
19,060
public void restart ( Long id ) { Watchdog wd = ( Watchdog ) this . registeredWachdogs . get ( id ) ; if ( wd == null ) { throw new IllegalStateException ( "Watchdog " + id + " ist not registered" ) ; } wd . restart ( ) ; }
restart the Watchdog with the given id
19,061
public SecretKey generateKey ( ) { SecretKey key = null ; try { KeyGenerator generator = KeyGenerator . getInstance ( "AES" ) ; generator . init ( 128 ) ; key = generator . generateKey ( ) ; } catch ( NoSuchAlgorithmException e ) { logger . error ( "Unable to generate AES key" , e ) ; } return key ; }
Generates a key for the AES encryption
19,062
public final Response setStatusLine ( final String statusLine ) { this . statusLine = statusLine ; final String [ ] statusPieces = statusLine . split ( " " ) ; if ( statusPieces . length > 1 ) { responseCode = Integer . parseInt ( statusPieces [ 1 ] ) ; } return this ; }
Specifies the HTTP status line
19,063
public static < K , V > ImmutableBiMap < K , V > copyOf ( Iterable < ? extends Entry < ? extends K , ? extends V > > entries ) { Entry < ? , ? > [ ] entryArray = Iterables . toArray ( entries , EMPTY_ENTRY_ARRAY ) ; switch ( entryArray . length ) { case 0 : return of ( ) ; case 1 : @ SuppressWarnings ( "unchecked" ) Entry < K , V > entry = ( Entry < K , V > ) entryArray [ 0 ] ; return of ( entry . getKey ( ) , entry . getValue ( ) ) ; default : return new RegularImmutableBiMap < K , V > ( entryArray ) ; } }
Returns an immutable bimap containing the given entries .
19,064
public void addActivator ( ActivatorModel activatorModel ) throws IllegalIDException { activatorModels . add ( activatorModel ) ; crashCounter . put ( activatorModel , new AtomicInteger ( 0 ) ) ; permissionDeniedCounter . put ( activatorModel , new AtomicInteger ( 0 ) ) ; submitActivator ( activatorModel ) ; }
adds an activator and automatically submits it to the Thread - Pool
19,065
public void removeActivator ( ActivatorModel activatorModel ) { activatorModels . remove ( activatorModel ) ; CompletableFuture remove = futures . remove ( activatorModel ) ; if ( remove != null ) { remove . cancel ( true ) ; } crashCounter . remove ( activatorModel ) ; permissionDeniedCounter . remove ( activatorModel ) ; }
removes the activator and stops the Thread
19,066
private void submitActivator ( ActivatorModel activatorModel ) { CompletableFuture < Void > future = submit ( ( ) -> { try { return activatorModel . call ( ) ; } catch ( Throwable e ) { if ( e instanceof IzouPermissionException ) { error ( "Activator: " + activatorModel . getID ( ) + " was denied permission." , e ) ; return null ; } else if ( e instanceof SecurityException ) { error ( "Activator: " + activatorModel . getID ( ) + " was denied access." , e ) ; return false ; } error ( "Activator: " + activatorModel . getID ( ) + " crashed" , e ) ; return true ; } } ) . thenAccept ( restart -> { if ( restart != null && restart . equals ( false ) ) { debug ( "Activator: " + activatorModel . getID ( ) + " returned false, will not restart" ) ; } else if ( restart == null ) { error ( "Activator: " + activatorModel . getID ( ) + " returned not true" ) ; if ( permissionDeniedCounter . get ( activatorModel ) . get ( ) < MAX_PERMISSION_DENIED ) { error ( "Until now activator: " + activatorModel . getID ( ) + " was restarted: " + permissionDeniedCounter . get ( activatorModel ) . get ( ) + " times, attempting restart." ) ; permissionDeniedCounter . get ( activatorModel ) . incrementAndGet ( ) ; submitActivator ( activatorModel ) ; } else { error ( "Activator: " + activatorModel . getID ( ) + " reached permission based restarting limit with " + permissionDeniedCounter . get ( activatorModel ) . get ( ) + " restarts." ) ; } } else { if ( crashCounter . get ( activatorModel ) . get ( ) < MAX_CRASH ) { error ( "Until now activator: " + activatorModel . getID ( ) + " was restarted: " + crashCounter . get ( activatorModel ) . get ( ) + " times, attempting restart." ) ; crashCounter . get ( activatorModel ) . incrementAndGet ( ) ; submitActivator ( activatorModel ) ; } else { error ( "Activator: " + activatorModel . getID ( ) + " reached crash based restarting limit with " + crashCounter . get ( activatorModel ) . get ( ) + " restarts." ) ; } } } ) ; CompletableFuture existing = futures . put ( activatorModel , future ) ; if ( existing != null && ! existing . isDone ( ) ) existing . cancel ( true ) ; }
submits the activator to the ThreadPool
19,067
private URL getUrl ( ) { ClassLoader loader = Thread . currentThread ( ) . getContextClassLoader ( ) ; URL url = loader . getResource ( this . getPath ( ) ) ; return url ; }
Get the url to find out if the resource is available
19,068
private Directory processDir ( File dirFile ) { List < Item > items = new ArrayList < Item > ( ) ; File [ ] files = dirFile . listFiles ( ) ; logger . info ( "processing directory {} with {} entries" , dirFile , files . length ) ; for ( File file : files ) { if ( file . getName ( ) . equals ( UpdateJob . LOCK_FILE ) ) { logger . info ( "skipping lockfile {}" , file ) ; } else if ( file . isDirectory ( ) ) { logger . debug ( "adding directory {}" , file ) ; items . add ( new DirectoryItem ( file . getName ( ) , processDir ( file ) ) ) ; } else { long lastModified = ( file . lastModified ( ) / 1000 ) * 1000 ; logger . debug ( "adding blob {}, lastModified: " , file , lastModified ) ; items . add ( new FileItem ( file . getName ( ) , processBlob ( file ) , lastModified ) ) ; } } Directory dir = new Directory ( items . toArray ( new Item [ items . size ( ) ] ) ) ; try { String id = writingRepository . store ( dir ) ; logger . info ( "added directory {} -> {}" , dirFile , id ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } return dir ; }
Verarbeitet ein Verzeichnis
19,069
public void start ( ) { if ( ( schedulerThread == null || ! schedulerThread . isAlive ( ) ) && interval > 0 ) { schedulerThread = new Thread ( this ) ; schedulerThread . start ( ) ; System . out . println ( new LogEntry ( "scheduler thread started..." ) ) ; } }
Starts scheduler thread that pages pageables .
19,070
public void stop ( ) { if ( schedulerThread != null ) { schedulerThread . interrupt ( ) ; try { schedulerThread . join ( 1000 ) ; } catch ( InterruptedException ie ) { } schedulerThread = null ; System . out . println ( new LogEntry ( "scheduler thread stopped..." ) ) ; } }
Stops scheduler thread .
19,071
public void register ( Pageable pageable ) { System . out . println ( pagedSystemObjectNames ) ; if ( ! pagedSystemObjectNames . contains ( pageable . toString ( ) ) ) { if ( pageable . getPageIntervalInMinutes ( ) <= 0 ) { System . out . println ( new LogEntry ( Level . VERBOSE , "scheduler will not page " + StringSupport . trim ( pageable . toString ( ) + "'" , 80 , "..." ) + ": interval in minutes (" + pageable . getPageIntervalInMinutes ( ) + ") is not valid" ) ) ; } else { System . out . println ( new LogEntry ( Level . VERBOSE , "scheduler will page " + StringSupport . trim ( pageable . toString ( ) + "'" , 80 , "..." ) + " every " + pageable . getPageIntervalInMinutes ( ) + " minute(s)" ) ) ; } synchronized ( pagedSystems ) { pagedSystems . add ( pageable ) ; pagedSystemObjectNames . add ( pageable . toString ( ) ) ; } } else { System . out . println ( new LogEntry ( "pageable " + pageable + " already registered in scheduler" ) ) ; } }
Registers pageables . If the pageable has specified a page interval > 0 it will be paged regularly .
19,072
public void run ( ) { currentState = SCHEDULER_WAIT ; long currentTime = System . currentTimeMillis ( ) ; while ( currentState == SCHEDULER_WAIT ) { try { long interval2 = SchedulingSupport . getTimeTillIntervalStart ( System . currentTimeMillis ( ) , interval ) ; if ( interval2 < TimeSupport . SECOND_IN_MS ) { interval2 += interval * TimeSupport . MINUTE_IN_MS ; } Thread . sleep ( interval2 ) ; } catch ( InterruptedException ie ) { System . out . println ( new LogEntry ( Level . CRITICAL , ( "scheduler interrupted..." ) ) ) ; currentState = SCHEDULER_HALT ; } if ( currentState == SCHEDULER_WAIT ) { currentState = SCHEDULER_BUSY ; currentTime = System . currentTimeMillis ( ) ; final long officialTime = TimeSupport . roundToMinute ( currentTime ) ; synchronized ( pagedSystems ) { Iterator i = pagedSystems . iterator ( ) ; while ( i . hasNext ( ) ) { final Pageable pageable = ( Pageable ) i . next ( ) ; if ( pageable . getPageIntervalInMinutes ( ) <= 0 ) { } else if ( SchedulingSupport . isWithinMinuteOfIntervalStart ( officialTime , pageable . getPageIntervalInMinutes ( ) , pageable . getPageOffsetInMinutes ( ) ) && pageable . isStarted ( ) ) { System . out . println ( new LogEntry ( "scheduler about to page " + StringSupport . trim ( pageable . toString ( ) + "'" , 80 , "..." ) ) ) ; if ( runAsync ) { new Executable ( ) { public Object execute ( ) { try { pageable . onPageEvent ( officialTime ) ; } catch ( Exception e ) { System . out . println ( new LogEntry ( Level . CRITICAL , "exception while paging pageable '" + StringSupport . trim ( pageable . toString ( ) + "'" , 80 , "..." ) , e ) ) ; } return null ; } } . executeAsync ( ) ; } else { try { pageable . onPageEvent ( officialTime ) ; } catch ( UndeclaredThrowableException e ) { System . out . println ( new LogEntry ( Level . CRITICAL , "undeclared exception while paging pageable '" + StringSupport . trim ( pageable . toString ( ) + "'" , 80 , "..." ) , e . getCause ( ) ) ) ; } catch ( Exception e ) { System . out . println ( new LogEntry ( Level . CRITICAL , "exception while paging pageable '" + StringSupport . trim ( pageable . toString ( ) + "'" , 80 , "..." ) , e ) ) ; } } } } lastCall = officialTime ; } currentState = SCHEDULER_WAIT ; } } currentState = SCHEDULER_HALT ; }
Code executed by scheduler thread .
19,073
public void initSystem ( ) { createIzouPropertiesFile ( ) ; setSystemProperties ( ) ; reloadFile ( null ) ; try { if ( System . getProperty ( IZOU_CONFIGURED ) . equals ( "false" ) ) { fatal ( "Izou not completely configured, please configure Izou and launch again." ) ; System . exit ( 0 ) ; } } catch ( NullPointerException e ) { fatal ( "Izou not completely configured, please configure Izou by editing izou.properties in the " + "properties folder and launch again." ) ; System . exit ( 0 ) ; } }
Initializes the system by calling all init methods
19,074
public void registerWithPropertiesManager ( ) { try { main . getFileManager ( ) . registerFileDir ( propertiesFile . getParentFile ( ) . toPath ( ) , propertiesFile . getName ( ) , this ) ; } catch ( IOException e ) { error ( "Unable to register " ) ; } }
This method registers the SystemInitializer with the Properties manager but this can only be done once the properties manager has been created thus this method is called later .
19,075
private void createIzouPropertiesFile ( ) { String propertiesPath = getMain ( ) . getFileSystemManager ( ) . getPropertiesLocation ( ) + File . separator + IZOU_PROPERTIES_FILE_NAME ; propertiesFile = new File ( propertiesPath ) ; if ( ! propertiesFile . exists ( ) ) try ( PrintWriter writer = new PrintWriter ( propertiesFile . getAbsolutePath ( ) , "UTF-8" ) ) { propertiesFile . createNewFile ( ) ; writer . println ( "# --------------------" ) ; writer . println ( "# Izou Properties File" ) ; writer . println ( "# --------------------" ) ; writer . println ( "#" ) ; writer . println ( "# This file has some general configuration options that have to be configured before" ) ; writer . println ( "# Izou can run successfully." ) ; } catch ( IOException e ) { error ( "Error while trying to create the new Properties file" , e ) ; } }
Creates the propreties file for Izou . This is the file that has to be configured before Izou can run and it contains some basic configuartion for Izou .
19,076
private void setLocalHostProperty ( ) { String hostName = "unkown" ; try { hostName = InetAddress . getLocalHost ( ) . getHostName ( ) ; } catch ( UnknownHostException e ) { error ( "Unable to resolve hostname, setting hostname as 'unkown'" ) ; } System . setProperty ( "host.name" , hostName ) ; }
Gets the local host if it can and sets it as a system property
19,077
private void reloadProperties ( ) { Properties temp = new Properties ( ) ; BufferedReader bufferedReader = null ; try { bufferedReader = new BufferedReader ( new InputStreamReader ( new FileInputStream ( propertiesFile ) , "UTF8" ) ) ; temp . load ( bufferedReader ) ; this . properties = temp ; } catch ( IOException e ) { error ( "Error while trying to load the Properties-File: " + propertiesFile . getAbsolutePath ( ) , e ) ; } finally { if ( bufferedReader != null ) { try { bufferedReader . close ( ) ; } catch ( IOException e ) { error ( "Unable to close input stream" , e ) ; } } } }
Reload the properties from the properties file into the system properties
19,078
public static byte [ ] toByteArray ( final long l ) { final byte [ ] bytes = new byte [ 8 ] ; bytes [ 0 ] = ( byte ) ( ( l >>> 56 ) & 0xff ) ; bytes [ 1 ] = ( byte ) ( ( l >>> 48 ) & 0xff ) ; bytes [ 2 ] = ( byte ) ( ( l >>> 40 ) & 0xff ) ; bytes [ 3 ] = ( byte ) ( ( l >>> 32 ) & 0xff ) ; bytes [ 4 ] = ( byte ) ( ( l >>> 24 ) & 0xff ) ; bytes [ 5 ] = ( byte ) ( ( l >>> 16 ) & 0xff ) ; bytes [ 6 ] = ( byte ) ( ( l >>> 8 ) & 0xff ) ; bytes [ 7 ] = ( byte ) ( ( l >>> 0 ) & 0xff ) ; return bytes ; }
Converts the specified long to an array of bytes .
19,079
public String mkString ( String start , String sep , String end ) { StringBuilder ret = new StringBuilder ( start ) ; for ( int i = 0 ; i < inner . size ( ) ; i ++ ) { ret . append ( inner . get ( i ) ) ; if ( i != ( inner . size ( ) - 1 ) ) { ret . append ( sep ) ; } } return ret . append ( end ) . toString ( ) ; }
Looping without creating in iterator is faster so we reimplement some methods for speed
19,080
public static Session loadFromHttpSession ( Preset preset , HttpSession httpSession ) { String mnoSessEntry = ( String ) httpSession . getAttribute ( MAESTRANO_SESSION_ID ) ; if ( mnoSessEntry == null ) { return new Session ( preset ) ; } Map < String , String > sessionObj ; try { Gson gson = new Gson ( ) ; String decryptedSession = new String ( DatatypeConverter . parseBase64Binary ( mnoSessEntry ) , "UTF-8" ) ; Type type = new TypeToken < Map < String , String > > ( ) { } . getType ( ) ; sessionObj = gson . fromJson ( decryptedSession , type ) ; } catch ( Exception e ) { logger . error ( "could not deserialized maestrano session: " + mnoSessEntry , e ) ; throw new RuntimeException ( "could not deserialized maestrano session: " + mnoSessEntry , e ) ; } String uid = sessionObj . get ( "uid" ) ; String groupUid = sessionObj . get ( "group_uid" ) ; String sessionToken = sessionObj . get ( "session" ) ; Date recheck ; try { recheck = MnoDateHelper . fromIso8601 ( sessionObj . get ( "session_recheck" ) ) ; } catch ( Exception e ) { recheck = new Date ( ( new Date ( ) ) . getTime ( ) - 1 * 60 * 1000 ) ; } return new Session ( preset , uid , groupUid , recheck , sessionToken ) ; }
Retrieving Maestrano session from httpSession returns an empty Session if there is no Session
19,081
public boolean isValid ( MnoHttpClient httpClient ) { if ( uid == null ) { return false ; } if ( isRemoteCheckRequired ( ) ) { if ( this . performRemoteCheck ( httpClient ) ) { return true ; } else { return false ; } } return true ; }
Return whether the session is valid or not . Perform remote check to maestrano if recheck is overdue .
19,082
public void save ( HttpSession httpSession ) { String sessionSerialized = serializeSession ( ) ; httpSession . setAttribute ( MAESTRANO_SESSION_ID , sessionSerialized ) ; }
Save the Maestrano session in HTTP Session
19,083
boolean performRemoteCheck ( MnoHttpClient httpClient ) { String url = sso . getSessionCheckUrl ( this . uid , this . sessionToken ) ; String respStr ; try { respStr = httpClient . get ( url ) ; } catch ( AuthenticationException e1 ) { e1 . printStackTrace ( ) ; return false ; } catch ( ApiException e1 ) { e1 . printStackTrace ( ) ; return false ; } Gson gson = new Gson ( ) ; Type type = new TypeToken < Map < String , String > > ( ) { } . getType ( ) ; Map < String , String > respObj = gson . fromJson ( respStr , type ) ; Boolean isValid = ( respObj . get ( "valid" ) != null && respObj . get ( "valid" ) . equals ( "true" ) ) ; if ( isValid ) { try { this . recheck = MnoDateHelper . fromIso8601 ( respObj . get ( "recheck" ) ) ; } catch ( Exception e ) { return false ; } return true ; } return false ; }
Check whether the remote maestrano session is still valid
19,084
private void dealWithFile ( File file ) { SelectiveFileScannerObserver specificFileScanner = selectiveFileScannerMap . get ( file . getName ( ) ) ; if ( specificFileScanner != null ) { logger . debug ( "Launching fileScanner={} for file={}" , specificFileScanner . getClass ( ) , file . getAbsoluteFile ( ) ) ; specificFileScanner . scanFile ( file ) ; } for ( FileScannerObserver fileScanner : fileScanners ) { logger . debug ( "Launching fileScanner={} for file={}" , fileScanner . getClass ( ) , file . getAbsoluteFile ( ) ) ; fileScanner . scanFile ( file ) ; } }
deal with the file that need to be parsed specific
19,085
public List < Double > getSplits ( ) { List < Double > splits = new ArrayList < Double > ( ) ; for ( Node curNode : getVisibleChildren ( ) ) { splits . add ( nodeSplits . get ( curNode ) ) ; } return splits ; }
Gets the child node splits .
19,086
public double getChildSpan ( ) { double span = 0.0 ; for ( Node node : getVisibleChildren ( ) ) { span += nodeSplits . get ( node ) ; } return span ; }
Gets the sum of the visible child node splits .
19,087
public List < Node > getVisibleChildren ( ) { List < Node > visibleChildren = new ArrayList < Node > ( ) ; for ( Node curChild : children ) { if ( curChild . isVisible ( ) ) { visibleChildren . add ( curChild ) ; } } return visibleChildren ; }
Gets a list of visible child nodes .
19,088
protected void addChild ( Node child , int index , double split ) { children . add ( index , child ) ; nodeSplits . put ( child , split ) ; child . setParent ( this ) ; }
Adds a child of this node .
19,089
public void replaceChild ( Node current , Node with ) { double currentSplit = nodeSplits . get ( current ) ; int index = children . indexOf ( current ) ; children . remove ( current ) ; addChild ( with , index , currentSplit ) ; notifyStateChange ( ) ; }
Replaces a child node with another node
19,090
public static String valueOf ( Traits trait ) { synchronized ( Commons . class ) { if ( singleton == null ) { singleton = new Commons ( ) ; } } return singleton . get ( trait ) ; }
Returns the value of the give trait .
19,091
protected static void checkDeleted ( final Resource res , final String identifier ) { if ( RdfUtils . isDeleted ( res ) ) { throw new WebApplicationException ( status ( GONE ) . links ( MementoResource . getMementoLinks ( identifier , res . getMementos ( ) ) . toArray ( Link [ ] :: new ) ) . build ( ) ) ; } }
Check if this is a deleted resource and if so return an appropriate response
19,092
protected static void checkCache ( final Request request , final Instant modified , final EntityTag etag ) { final ResponseBuilder builder = request . evaluatePreconditions ( from ( modified ) , etag ) ; if ( nonNull ( builder ) ) { throw new WebApplicationException ( builder . build ( ) ) ; } }
Check the request for a cache - related response
19,093
private Command < ? super T > createOption ( String fieldName , Class < ? > type ) { if ( type == Integer . class || type == int . class ) { return new IntegerFieldOption < T > ( fieldName ) ; } else if ( type == Long . class || type == long . class ) { return new LongFieldOption < T > ( fieldName ) ; } else if ( type == Boolean . class || type == boolean . class ) { return new BooleanFieldOption < T > ( fieldName ) ; } else if ( type == String . class ) { return new StringFieldOption < T > ( fieldName ) ; } else if ( type == Double . class || type == double . class ) { return new DoubleFieldOption < T > ( fieldName ) ; } else if ( type == Float . class || type == float . class ) { return new FloatFieldOption < T > ( fieldName ) ; } else if ( type == File . class ) { return new FileFieldOption < T > ( fieldName ) ; } throw new IllegalArgumentException ( "Cannot create option for parameter of type `" + type . getName ( ) + "'" ) ; }
Creates an option for the specified field and type .
19,094
private void processCommandField ( final Field field , String key , String prompt ) { String name = field . getName ( ) ; Class < ? > type = field . getType ( ) ; if ( key . equals ( "" ) ) { key = name ; } if ( prompt != null && prompt . equals ( "" ) ) { prompt = key ; } final ArgumentProcessor < Object > argProcessor = new ArgumentProcessor < Object > ( prompt ) ; argProcessor . setDefaultCommand ( UnrecognizedCommand . getInstance ( ) ) ; argProcessor . processAnnotations ( type ) ; addCommand ( key , new Command < T > ( ) { public void process ( Queue < String > argq , T state ) { try { Object value = field . get ( state ) ; argProcessor . process ( argq , value ) ; } catch ( IllegalArgumentException e ) { throw new UnexpectedException ( e ) ; } catch ( IllegalAccessException e ) { throw new UnexpectedException ( e ) ; } } } ) ; }
Adds a command that passes control to the specified field .
19,095
private void processField ( Field field ) { OptionArgument optAnnotation = field . getAnnotation ( OptionArgument . class ) ; if ( optAnnotation != null ) { processOptionField ( field , optAnnotation . value ( ) , optAnnotation . shortKey ( ) ) ; } else { CommandArgument cmdAnnotation = field . getAnnotation ( CommandArgument . class ) ; if ( cmdAnnotation != null ) { processCommandField ( field , cmdAnnotation . value ( ) , null ) ; } else { ShellArgument shellAnnotation = field . getAnnotation ( ShellArgument . class ) ; if ( shellAnnotation != null ) { processCommandField ( field , shellAnnotation . value ( ) , shellAnnotation . prompt ( ) ) ; } } } }
Processes the relevant annotations on the given field and adds the required options or commands .
19,096
public void addOption ( String key , char shortKey , Command < ? super T > handler ) { options . put ( key , handler ) ; shortcuts . put ( shortKey , key ) ; }
Add a command line option handler .
19,097
public void addCommand ( String key , Command < ? super T > handler ) { commands . put ( key , handler ) ; }
Adds a new command handler .
19,098
public static < T extends Annotation > T trimEnd ( T annotation , char ... ws ) { char [ ] s = annotation . getCoveredText ( ) . toCharArray ( ) ; if ( s . length == 0 ) return annotation ; int e = 0 ; while ( ArrayUtils . contains ( ws , s [ ( s . length - 1 ) - e ] ) ) { e ++ ; } annotation . setEnd ( annotation . getEnd ( ) - e ) ; return annotation ; }
Moves the end - index as long a character that is contained in the array is at the end .
19,099
synchronized void stop ( ) { if ( status . equals ( "stopped" ) ) return ; long t = System . currentTimeMillis ( ) ; run = false ; try { serverSocket . close ( ) ; } catch ( IOException e ) { throw S1SystemError . wrap ( e ) ; } executor . shutdown ( ) ; while ( ! executor . isTerminated ( ) ) { } status = "stopped" ; LOG . info ( "Node " + nodeId + " file server stopped (" + ( System . currentTimeMillis ( ) - t ) + " ms.)" ) ; }
Stop file server