idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
30,100
public void messageSent ( IoSession session , Object message ) throws Exception { log . debug ( "{} , message , session ) ; if ( this . sensorIoAdapter == null ) { log . warn ( "No SensorIoAdapter defined. Ignoring message to {}: {}" , session , message ) ; return ; } if ( message instanceof HandshakeMessage ) { log . debug ( "Handshake message sent to {}: {}" , session , message ) ; if ( this . sensorIoAdapter != null ) { this . sensorIoAdapter . handshakeMessageSent ( session , ( HandshakeMessage ) message ) ; } } else if ( message instanceof SampleMessage ) { if ( this . sensorIoAdapter != null ) { this . sensorIoAdapter . sensorSampleSent ( session , ( SampleMessage ) message ) ; } } else { log . warn ( "Unhandled message type sent to {}: {}" , session , message ) ; } }
Demultiplexes the sent message and passes it to the appropriate method of the IOAdapter .
30,101
public void sessionClosed ( IoSession session ) throws Exception { log . debug ( "Session closed for sensor {}." , session ) ; if ( this . sensorIoAdapter != null ) { this . sensorIoAdapter . sensorDisconnected ( session ) ; } }
Notifies the IOAdapter that the session has closed .
30,102
public void sessionOpened ( IoSession session ) throws Exception { log . debug ( "Session opened for sensor {}." , session ) ; if ( this . sensorIoAdapter != null ) { this . sensorIoAdapter . sensorConnected ( session ) ; } }
Notifies the IOAdapter that the session has connected .
30,103
protected Corpus onComplete ( Corpus corpus , ProcessorContext context , Counter < String > counts ) { return corpus ; }
On complete corpus .
30,104
public String getDefaultMimeType ( Property binaryProperty ) throws RepositoryException { try { Binary binary = binaryProperty . getBinary ( ) ; return binary instanceof org . modeshape . jcr . api . Binary ? ( ( org . modeshape . jcr . api . Binary ) binary ) . getMimeType ( ) : DEFAULT_MIME_TYPE ; } catch ( IOException e ) { logger . warn ( "Cannot determine default mime-type" , e ) ; return DEFAULT_MIME_TYPE ; } }
Returns the default mime - type of a given binary property .
30,105
public static CharSequence ltrim ( CharSequence str ) { int len ; int i ; if ( str == null || ( len = str . length ( ) ) <= 0 ) return "" ; for ( i = 0 ; i < len ; i ++ ) if ( ! Character . isWhitespace ( str . charAt ( i ) ) ) break ; if ( i >= len ) return "" ; return str . subSequence ( i , len ) ; }
Trim horizontal whitespace from left side .
30,106
public static TrackingExecutorService createTrackingExecutorService ( ExecutorService executorService , Identifiable identifiable ) throws IllegalIDException { return new TrackingExecutorService ( executorService , identifiable ) ; }
creates a new ExecutorService
30,107
@ SuppressWarnings ( "unchecked" ) public V getComponent ( ) { if ( this . component == null ) { try { this . component = ( V ) Application . getControllerManager ( ) . getComponentBuilder ( ) . build ( this ) ; } catch ( Exception e ) { throw new ControllerException ( "Component Build Error" , e ) ; } if ( this . component == null ) { throw new ControllerException ( "NULL Component." ) ; } } return this . component ; }
Get the controlled component .
30,108
public final Controller getRoot ( ) { Controller superController = this ; while ( superController . getParent ( ) != null ) { superController = superController . getParent ( ) ; } return superController ; }
Get the root controller in the hierarchy group .
30,109
public static Range valueOf ( final String value ) { final Optional < Integer [ ] > vals = parse ( value ) ; if ( vals . isPresent ( ) ) { return new Range ( vals . get ( ) [ 0 ] , vals . get ( ) [ 1 ] ) ; } return null ; }
Get a Range object from a header value
30,110
public static String toCamelCase ( String str ) { String [ ] wordList = str . toLowerCase ( ) . split ( "_" ) ; String finalStr = "" ; for ( String word : wordList ) { finalStr += capitalize ( word ) ; } return finalStr ; }
Convert a string to CamelCase
30,111
public < T > AppEngineUpdate < E > set ( Property < ? , T > property , T value ) { if ( property == null ) { throw new IllegalArgumentException ( "'property' must not be [" + property + "]" ) ; } properties . put ( property , value ) ; return this ; }
Qualifies property and the value to be updated .
30,112
public < T > Update < E > set ( Property < ? , T > property , Modification < T > modification ) { if ( property == null ) { throw new IllegalArgumentException ( "'property' must not be [" + property + "]" ) ; } properties . put ( property , modification ) ; return this ; }
Qualifies property to be updated and the modification function .
30,113
synchronized public void write ( final byte data [ ] , final int off , final int len ) throws IOException { final byte [ ] encoded = CommonUtils . encode ( this . key , data , off , len ) ; os . write ( encoded ) ; }
Write the data out NOW .
30,114
private String mapToFogbugzUrl ( Map < String , String > params ) throws UnsupportedEncodingException { String output = this . getFogbugzUrl ( ) ; for ( String key : params . keySet ( ) ) { String value = params . get ( key ) ; if ( ! value . isEmpty ( ) ) { output += "&" + URLEncoder . encode ( key , "UTF-8" ) + "=" + URLEncoder . encode ( value , "UTF-8" ) ; } } FogbugzManager . log . info ( "Generated URL to send to Fogbugz: " + output ) ; return output ; }
Helper method to create API url from Map with proper encoding .
30,115
private Document getFogbugzDocument ( Map < String , String > parameters ) throws IOException , ParserConfigurationException , SAXException { URL uri = new URL ( this . mapToFogbugzUrl ( parameters ) ) ; HttpURLConnection con = ( HttpURLConnection ) uri . openConnection ( ) ; DocumentBuilderFactory dbFactory = DocumentBuilderFactory . newInstance ( ) ; DocumentBuilder dBuilder = dbFactory . newDocumentBuilder ( ) ; return dBuilder . parse ( con . getInputStream ( ) ) ; }
Fetches the XML from the Fogbugz API and returns a Document object with the response XML in it so we can use that .
30,116
public FogbugzCase getCaseById ( int id ) throws InvalidResponseException , NoSuchCaseException { List < FogbugzCase > caseList = this . searchForCases ( Integer . toString ( id ) ) ; if ( caseList . size ( ) > 1 ) { throw new InvalidResponseException ( "Expected one case, found multiple, aborting." ) ; } return caseList . get ( 0 ) ; }
Retrieves a case using the Fogbugz API by caseId .
30,117
public List < FogbugzCase > searchForCases ( String query ) throws InvalidResponseException , NoSuchCaseException { HashMap < String , String > params = new HashMap < String , String > ( ) ; params . put ( "cmd" , "search" ) ; params . put ( "q" , query ) ; params . put ( "cols" , "ixBug,tags,fOpen,sTitle,sFixFor,ixPersonOpenedBy,ixPersonAssignedTo" + this . getCustomFieldsCSV ( ) ) ; Document doc = null ; try { doc = this . getFogbugzDocument ( params ) ; } catch ( Exception e ) { throw new InvalidResponseException ( e . getMessage ( ) ) ; } int caseCount = 0 ; try { Node casesContainer = doc . getElementsByTagName ( "cases" ) . item ( 0 ) ; caseCount = Integer . parseInt ( casesContainer . getAttributes ( ) . getNamedItem ( "count" ) . getTextContent ( ) ) ; } catch ( NumberFormatException e ) { log . log ( Level . INFO , "No valid number in case count XML response." , e ) ; } if ( caseCount < 1 ) { throw new NoSuchCaseException ( "Fogbugz did not return a case for query id " + query ) ; } NodeList caseNodes = doc . getElementsByTagName ( "case" ) ; ArrayList < FogbugzCase > caseList = new ArrayList < FogbugzCase > ( ) ; for ( int i = 0 ; i < caseNodes . getLength ( ) ; i ++ ) { caseList . add ( this . constructCaseFromXmlNode ( caseNodes . item ( i ) ) ) ; } return caseList ; }
Retrieves cases using the Fogbugz API by a query
30,118
public List < FogbugzEvent > getEventsForCase ( int id ) { try { HashMap < String , String > params = new HashMap < String , String > ( ) ; params . put ( "cmd" , "search" ) ; params . put ( "q" , Integer . toString ( id ) ) ; params . put ( "cols" , "events" ) ; Document doc = this . getFogbugzDocument ( params ) ; List < FogbugzEvent > eventList = new ArrayList < FogbugzEvent > ( ) ; NodeList eventsNodeList = doc . getElementsByTagName ( "event" ) ; if ( eventsNodeList != null && eventsNodeList . getLength ( ) != 0 ) { for ( int i = 0 ; i < eventsNodeList . getLength ( ) ; i ++ ) { Element currentNode = ( Element ) eventsNodeList . item ( i ) ; eventList . add ( new FogbugzEvent ( Integer . parseInt ( currentNode . getElementsByTagName ( "ixBugEvent" ) . item ( 0 ) . getTextContent ( ) ) , id , currentNode . getElementsByTagName ( "sVerb" ) . item ( 0 ) . getTextContent ( ) , Integer . parseInt ( currentNode . getElementsByTagName ( "ixPerson" ) . item ( 0 ) . getTextContent ( ) ) , Integer . parseInt ( currentNode . getElementsByTagName ( "ixPersonAssignedTo" ) . item ( 0 ) . getTextContent ( ) ) , DatatypeConverter . parseDateTime ( currentNode . getElementsByTagName ( "dt" ) . item ( 0 ) . getTextContent ( ) ) . getTime ( ) , currentNode . getElementsByTagName ( "evtDescription" ) . item ( 0 ) . getTextContent ( ) , currentNode . getElementsByTagName ( "sPerson" ) . item ( 0 ) . getTextContent ( ) ) ) ; } } return eventList ; } catch ( Exception e ) { FogbugzManager . log . log ( Level . SEVERE , "Exception while fetching case " + Integer . toString ( id ) , e ) ; } return null ; }
Retrieves all events for a certain case .
30,119
public boolean saveCase ( FogbugzCase fbCase , String comment ) { try { HashMap < String , String > params = new HashMap < String , String > ( ) ; if ( fbCase . getId ( ) == 0 ) { params . put ( "cmd" , "new" ) ; params . put ( "sTitle" , fbCase . getTitle ( ) ) ; } else { params . put ( "cmd" , "edit" ) ; params . put ( "ixBug" , Integer . toString ( fbCase . getId ( ) ) ) ; } params . put ( "ixPersonAssignedTo" , Integer . toString ( fbCase . getAssignedTo ( ) ) ) ; params . put ( "ixPersonOpenedBy" , Integer . toString ( fbCase . getOpenedBy ( ) ) ) ; params . put ( "sTags" , fbCase . tagsToCSV ( ) ) ; if ( this . featureBranchFieldname != null && ! this . featureBranchFieldname . isEmpty ( ) ) { params . put ( this . featureBranchFieldname , fbCase . getFeatureBranch ( ) ) ; } if ( this . originalBranchFieldname != null && ! this . originalBranchFieldname . isEmpty ( ) ) { params . put ( this . originalBranchFieldname , fbCase . getOriginalBranch ( ) ) ; } if ( this . targetBranchFieldname != null && ! this . targetBranchFieldname . isEmpty ( ) ) { params . put ( this . targetBranchFieldname , fbCase . getTargetBranch ( ) ) ; } if ( this . approvedRevisionFieldname != null && ! this . approvedRevisionFieldname . isEmpty ( ) ) { params . put ( this . approvedRevisionFieldname , fbCase . getApprovedRevision ( ) ) ; } if ( this . ciProjectFieldName != null && ! this . ciProjectFieldName . isEmpty ( ) ) { params . put ( this . ciProjectFieldName , fbCase . getCiProject ( ) ) ; } params . put ( "sFixFor" , fbCase . getMilestone ( ) ) ; params . put ( "sEvent" , comment ) ; Document doc = this . getFogbugzDocument ( params ) ; FogbugzManager . log . info ( "Fogbugz response got when saving case: " + doc . toString ( ) ) ; return true ; } catch ( Exception e ) { FogbugzManager . log . log ( Level . SEVERE , "Exception while creating/saving case " + Integer . toString ( fbCase . getId ( ) ) , e ) ; } return false ; }
Saves a case to fogbugz using its API . Supports creating new cases by setting caseId to 0 on case object .
30,120
private String getCustomFieldsCSV ( ) { String toReturn = "" ; if ( this . featureBranchFieldname != null && ! this . featureBranchFieldname . isEmpty ( ) ) { toReturn += "," + this . featureBranchFieldname ; } if ( this . originalBranchFieldname != null && ! this . originalBranchFieldname . isEmpty ( ) ) { toReturn += "," + this . originalBranchFieldname ; } if ( this . targetBranchFieldname != null && ! this . targetBranchFieldname . isEmpty ( ) ) { toReturn += "," + this . targetBranchFieldname ; } if ( this . approvedRevisionFieldname != null && ! this . approvedRevisionFieldname . isEmpty ( ) ) { toReturn += "," + this . approvedRevisionFieldname ; } if ( this . ciProjectFieldName != null && ! this . ciProjectFieldName . isEmpty ( ) ) { toReturn += "," + this . ciProjectFieldName ; } return toReturn ; }
Returns a list of custom field names comma separated . Starts with a comma .
30,121
public List < FogbugzMilestone > getMilestones ( ) { try { HashMap < String , String > params = new HashMap < String , String > ( ) ; params . put ( "cmd" , "listFixFors" ) ; Document doc = this . getFogbugzDocument ( params ) ; List < FogbugzMilestone > milestoneList = new ArrayList < FogbugzMilestone > ( ) ; NodeList milestonesNodeList = doc . getElementsByTagName ( "fixfor" ) ; if ( milestonesNodeList != null && milestonesNodeList . getLength ( ) != 0 ) { for ( int i = 0 ; i < milestonesNodeList . getLength ( ) ; i ++ ) { Element currentNode = ( Element ) milestonesNodeList . item ( i ) ; milestoneList . add ( new FogbugzMilestone ( Integer . parseInt ( currentNode . getElementsByTagName ( "ixFixFor" ) . item ( 0 ) . getTextContent ( ) ) , currentNode . getElementsByTagName ( "sFixFor" ) . item ( 0 ) . getTextContent ( ) , Boolean . valueOf ( currentNode . getElementsByTagName ( "fDeleted" ) . item ( 0 ) . getTextContent ( ) ) , Boolean . valueOf ( currentNode . getElementsByTagName ( "fReallyDeleted" ) . item ( 0 ) . getTextContent ( ) ) ) ) ; } } return milestoneList ; } catch ( Exception e ) { FogbugzManager . log . log ( Level . SEVERE , "Exception while fetching milestones" , e ) ; } return new ArrayList < FogbugzMilestone > ( ) ; }
Retrieves all milestones and returns them in a nice List of FogbugzMilestone objects .
30,122
public boolean createMilestone ( FogbugzMilestone milestone ) { try { HashMap < String , String > params = new HashMap < String , String > ( ) ; if ( milestone . getId ( ) != 0 ) { throw new Exception ( "Editing existing milestones is not supported, please set the id to 0." ) ; } params . put ( "cmd" , "newFixFor" ) ; params . put ( "ixProject" , "-1" ) ; params . put ( "fAssignable" , "1" ) ; params . put ( "sFixFor" , milestone . getName ( ) ) ; Document doc = this . getFogbugzDocument ( params ) ; FogbugzManager . log . info ( "Fogbugz response got when saving milestone: " + doc . toString ( ) ) ; return true ; } catch ( Exception e ) { FogbugzManager . log . log ( Level . SEVERE , "Exception while creating milestone " + milestone . getName ( ) , e ) ; } return false ; }
Creates new Milestone in Fogbugz . Please leave id of milestone object empty . Only creates global milestones .
30,123
public InputStream getAsStream ( ) throws CacheException { try { if ( file . exists ( ) && file . isFile ( ) ) { logger . debug ( "retrieving file as a stream" ) ; return new FileInputStream ( file ) ; } } catch ( IOException e ) { logger . error ( "file '{}' does not exist or is not a file" , file . getAbsolutePath ( ) ) ; throw new CacheException ( "File " + file . getAbsolutePath ( ) + " does not exist or is not a regular file" , e ) ; } return null ; }
Returns the given file as a stream .
30,124
public static String footprint ( String stringToFootprint ) { try { MessageDigest md = MessageDigest . getInstance ( "SHA-1" ) ; return byteArrayToHexString ( md . digest ( stringToFootprint . getBytes ( ) ) ) ; } catch ( NoSuchAlgorithmException nsae ) { LOGGER . warn ( "Unable to calculate the footprint for string [{}]." , stringToFootprint ) ; return null ; } }
Calculate a footprint of a string
30,125
public String toHexString ( ) { final StringBuilder buf = new StringBuilder ( 24 ) ; for ( final byte b : toByteArray ( ) ) { buf . append ( String . format ( "%02x" , b & 0xff ) ) ; } return buf . toString ( ) ; }
Converts this instance into a 24 - byte hexadecimal string representation .
30,126
public static < T > T firstNotNull ( T ... args ) { for ( T arg : args ) { if ( arg != null ) return arg ; } return null ; }
Selects first non - null argument .
30,127
private static < E > boolean removeOccurrencesImpl ( Multiset < E > multisetToModify , Multiset < ? > occurrencesToRemove ) { checkNotNull ( multisetToModify ) ; checkNotNull ( occurrencesToRemove ) ; boolean changed = false ; Iterator < Entry < E > > entryIterator = multisetToModify . entrySet ( ) . iterator ( ) ; while ( entryIterator . hasNext ( ) ) { Entry < E > entry = entryIterator . next ( ) ; int removeCount = occurrencesToRemove . count ( entry . getElement ( ) ) ; if ( removeCount >= entry . getCount ( ) ) { entryIterator . remove ( ) ; changed = true ; } else if ( removeCount > 0 ) { multisetToModify . remove ( entry . getElement ( ) , removeCount ) ; changed = true ; } } return changed ; }
Delegate that cares about the element types in multisetToModify .
30,128
public final Thread launch ( ) { if ( state != RUN ) { onLaunch ( ) ; state = RUN ; Thread thread = ( new Thread ( this ) ) ; thread . start ( ) ; return thread ; } else { return null ; } }
Launch the module .
30,129
ConnectionWrapper obtainConnection ( ) { synchronized ( allConnections ) { if ( ! availableConnections . isEmpty ( ) ) { ConnectionWrapper connWrap = ( ConnectionWrapper ) availableConnections . remove ( 0 ) ; usedConnections . add ( connWrap ) ; if ( usedConnections . size ( ) > maxNrOfConcurrentConnectionsCounted ) { maxNrOfConcurrentConnectionsCounted = usedConnections . size ( ) ; } return connWrap ; } else { if ( ( allConnections . size ( ) < initialNrofConnections ) || ( allConnections . size ( ) < maxNrofConnections ) ) { try { ConnectionWrapper connWrap = createConnectionWrapper ( dbUrl , dbUsername , dbUserpassword ) ; allConnections . add ( connWrap ) ; usedConnections . add ( connWrap ) ; System . out . println ( new LogEntry ( "Creating new Connection, now " + allConnections . size ( ) + " in use" ) ) ; return connWrap ; } catch ( SQLException sqle ) { nrofErrors ++ ; System . out . println ( new LogEntry ( "Cannot create new connection to " + dbUrl + " unreachable or useless connection settings" , sqle ) ) ; throw new ResourceException ( "Cannot create new connection to " + dbUrl + " unreachable or useless connection settings" , sqle ) ; } } else { System . out . println ( new LogEntry ( "maximum nr of connections (" + maxNrofConnections + ") reached while Application demands another" ) ) ; } return null ; } } }
To be invoked by ConnectionWrapper and StandardConnectionPool only only
30,130
void replaceConnection ( ConnectionWrapper connWrap ) { synchronized ( allConnections ) { try { if ( usedConnections . remove ( connWrap ) ) { nrofReset ++ ; allConnections . remove ( connWrap ) ; connWrap . getConnection ( ) . close ( ) ; System . out . println ( new LogEntry ( Level . CRITICAL , "Connection reset" + ( connWrap . getLastStatement ( ) != null ? " while executing '" + connWrap . getLastStatement ( ) + '\'' : "" ) ) ) ; ConnectionWrapper newConnWrap = createConnectionWrapper ( dbUrl , dbUsername , dbUserpassword ) ; availableConnections . add ( newConnWrap ) ; allConnections . add ( newConnWrap ) ; } else { nrofErrors ++ ; System . out . println ( new LogEntry ( Level . CRITICAL , "error in connection pool: attempt to close a Connection that does not exist in pool" ) ) ; } } catch ( SQLException sqle ) { nrofErrors ++ ; System . out . println ( new LogEntry ( Level . CRITICAL , "can not create new connection to " + dbUrl + " unreachable or useless connection settings" , sqle ) ) ; } try { if ( ! connWrap . isClosed ( ) ) { connWrap . getConnection ( ) . close ( ) ; } } catch ( SQLException sqle ) { nrofErrors ++ ; System . out . println ( new LogEntry ( Level . CRITICAL , "" , sqle ) ) ; } } }
Closes the connection and replaces it in the pool To be invoked by ConnectionWrapper and StandardConnectionPool only only
30,131
public void stop ( ) { isStarted = false ; Iterator i = allConnections . iterator ( ) ; while ( i . hasNext ( ) ) { ConnectionWrapper connWrap = ( ConnectionWrapper ) i . next ( ) ; try { connWrap . getConnection ( ) . close ( ) ; } catch ( SQLException e ) { nrofErrors ++ ; System . out . println ( new LogEntry ( e ) ) ; } } allConnections . clear ( ) ; availableConnections . clear ( ) ; usedConnections . clear ( ) ; }
Stops the component and closes all connections
30,132
public void setProperties ( Properties properties ) throws ConfigurationException { String dbDriver = properties . getProperty ( "dbdriver" ) . toString ( ) ; if ( dbDriver == null ) { throw new ConfigurationException ( "please specify dbDriver for connectionpool" ) ; } dbUrl = properties . getProperty ( "dburl" ) . toString ( ) ; dbUsername = properties . getProperty ( "dbusername" ) . toString ( ) ; dbUserpassword = properties . getProperty ( "dbuserpassword" ) . toString ( ) ; if ( properties . getProperty ( "nrof_connections" ) != null ) { initialNrofConnections = Integer . valueOf ( properties . getProperty ( "nrof_connections" ) ) ; maxNrofConnections = Integer . valueOf ( properties . getProperty ( "nrof_connections" ) ) ; } else { initialNrofConnections = Integer . valueOf ( properties . getProperty ( "initial_nrof_connections" , "" + initialNrofConnections ) ) ; maxNrofConnections = Integer . valueOf ( properties . getProperty ( "max_nrof_connections" , "" + maxNrofConnections ) ) ; } connectionRequestTimeout = Integer . valueOf ( properties . getProperty ( "connection_request_timeout" , "" + connectionRequestTimeout ) ) ; connectionTimeout = Integer . valueOf ( properties . getProperty ( "connection_timeout" , "" + connectionTimeout ) ) ; connectionTimeoutCheck = Integer . valueOf ( properties . getProperty ( "connection_timeout_check_interval" , "" + connectionTimeoutCheck ) ) ; connectionTestStatement = properties . getProperty ( "connection_test_statement" , connectionTestStatement ) . toString ( ) ; createReadOnlyConnections = Boolean . valueOf ( properties . getProperty ( "create_readonly_connections" , "" + createReadOnlyConnections ) ) ; defaultIsolationLevel = isolationLevelStrings . indexOf ( properties . getProperty ( "default_isolaton_level" , "" + defaultIsolationLevel ) ) ; try { Class . forName ( dbDriver ) ; Enumeration drivers = DriverManager . getDrivers ( ) ; driverInfo = "" ; int count = 0 ; while ( drivers . hasMoreElements ( ) ) { count ++ ; Driver driver = ( Driver ) drivers . nextElement ( ) ; driverInfo += "driver " + count + ": " + driver . getMajorVersion ( ) + '.' + driver . getMinorVersion ( ) + "\n" ; } } catch ( ClassNotFoundException cnfe ) { throw new ConfigurationException ( "ERROR: Driver \"" + dbDriver + "\" not found..." ) ; } resetStatistics ( ) ; }
Initializes the connection pool
30,133
public HashMap < String , Object > getFunctions ( ClassModel classModel ) { HashMap < String , Object > result = newHashMap ( ) ; for ( String name : functions . keySet ( ) ) { result . put ( name , new TemplateFunction ( functions . get ( name ) , classModel ) ) ; } return result ; }
Return a freemarker model containing the user defined functions .
30,134
private RestTemplate _newRestTemplate ( ) { RestTemplate template = new RestTemplate ( ) ; List < HttpMessageConverter < ? > > converters = getMessageConverters ( ) ; if ( converters != null ) { template . setMessageConverters ( getMessageConverters ( ) ) ; } return template ; }
scope = prototype ; i . e . each time this method is called a new instance is created .
30,135
public static void copyFile ( File sourceFile , File destinationFile ) throws FileNotFoundException , IOException { Streams . copyStream ( new FileInputStream ( sourceFile ) , new FileOutputStream ( destinationFile ) , true ) ; }
Kopiert eine Datei
30,136
private Registry startRmiRegistryProcess ( Configuration configuration , final int port ) { try { final String javaHome = System . getProperty ( JAVA_HOME ) ; String command = null ; if ( javaHome == null ) { command = "rmiregistry" ; } else { if ( javaHome . endsWith ( "bin" ) ) { command = javaHome + "/rmiregistry " ; } else { command = javaHome + "/bin/rmiregistry " ; } } return internalProcessStart ( configuration , port , command ) ; } catch ( Exception e1 ) { LOGGER . error ( "The RMI Registry cannot be started." , e1 ) ; throw new UnsupportedOperationException ( "could not start rmiregistry!!! Reason: " + e1 . toString ( ) , e1 ) ; } }
start new rmiregistry using PrcessBuilder
30,137
@ SuppressWarnings ( { "SynchronizationOnLocalVariableOrMethodParameter" } ) public Optional < EventCallable > registerCaller ( Identification identification ) throws IllegalIDException { if ( identification == null || callers . containsKey ( identification ) ) return Optional . empty ( ) ; EventCaller eventCaller = new EventCaller ( events ) ; callers . put ( identification , eventCaller ) ; return Optional . of ( eventCaller ) ; }
Registers with the EventManager to fire an event .
30,138
@ SuppressWarnings ( "SynchronizationOnLocalVariableOrMethodParameter" ) public void unregisterCaller ( Identification identification ) { if ( ! callers . containsKey ( identification ) ) return ; callers . get ( identification ) . localEvents = null ; callers . remove ( identification ) ; }
Unregister with the EventManager .
30,139
public void fireEvent ( EventModel event ) throws IllegalIDException , org . intellimate . izou . events . MultipleEventsException { if ( events == null ) return ; if ( events . isEmpty ( ) ) { events . add ( event ) ; } else { throw new org . intellimate . izou . events . MultipleEventsException ( ) ; } }
This method fires an Event
30,140
public static byte [ ] hexToByte ( String s ) throws IOException { int l = s . length ( ) / 2 ; byte data [ ] = new byte [ l ] ; int j = 0 ; if ( s . length ( ) % 2 != 0 ) { throw new IOException ( "hexadecimal string with odd number of characters" ) ; } for ( int i = 0 ; i < l ; i ++ ) { char c = s . charAt ( j ++ ) ; int n , b ; n = HEXINDEX . indexOf ( c ) ; if ( n == - 1 ) { throw new IOException ( "hexadecimal string contains non hex character" ) ; } b = ( n & 0xf ) << 4 ; c = s . charAt ( j ++ ) ; n = HEXINDEX . indexOf ( c ) ; b += ( n & 0xf ) ; data [ i ] = ( byte ) b ; } return data ; }
Compacts a hexadecimal string into a byte array
30,141
public void close ( ) { Set < PhynixxXAResource < T > > tmpXAResources = new HashSet < PhynixxXAResource < T > > ( ) ; synchronized ( xaresources ) { if ( this . xaresources . size ( ) > 0 ) { tmpXAResources . addAll ( xaresources ) ; } } for ( Iterator < PhynixxXAResource < T > > iterator = tmpXAResources . iterator ( ) ; iterator . hasNext ( ) ; ) { PhynixxXAResource < T > xaresource = iterator . next ( ) ; xaresource . close ( ) ; } this . getXATransactionalBranchRepository ( ) . close ( ) ; }
Closes all pending XAResources and all reopen but unused connections
30,142
public void setGenericPoolConfig ( GenericObjectPoolConfig cfg ) throws Exception { if ( this . genericObjectPool != null ) { this . genericObjectPool . close ( ) ; } if ( cfg == null ) { cfg = new GenericObjectPoolConfig ( ) ; } this . genericObjectPool = new GenericObjectPool < IPhynixxManagedConnection < C > > ( new MyPoolableObjectFactory < C > ( this ) , cfg ) ; }
closes the current pool - if existing - and instanciates a new pool
30,143
public void releaseConnection ( IPhynixxManagedConnection < C > connection ) { if ( connection == null || ! connection . hasCoreConnection ( ) ) { return ; } try { this . genericObjectPool . returnObject ( connection ) ; } catch ( Exception e ) { throw new DelegatedRuntimeException ( e ) ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Proxy " + connection + " returned to Pool" ) ; } }
closes the connection an releases it to the pool
30,144
public void connectionReleased ( IManagedConnectionEvent < C > event ) { IPhynixxManagedConnection < C > proxy = event . getManagedConnection ( ) ; if ( ! proxy . hasCoreConnection ( ) ) { return ; } else { this . releaseConnection ( proxy ) ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Proxy " + proxy + " released" ) ; } }
the connection is sent back to the pool
30,145
public void connectionFreed ( IManagedConnectionEvent < C > event ) { IPhynixxManagedConnection < C > proxy = event . getManagedConnection ( ) ; if ( ! proxy . hasCoreConnection ( ) ) { return ; } else { this . freeConnection ( proxy ) ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Proxy " + proxy + " released" ) ; } }
the connection is set free an released from the pool
30,146
public static < K , V > Multimap < K , V > constrainedMultimap ( Multimap < K , V > multimap , MapConstraint < ? super K , ? super V > constraint ) { return new ConstrainedMultimap < K , V > ( multimap , constraint ) ; }
Returns a constrained view of the specified multimap using the specified constraint . Any operations that add new mappings will call the provided constraint . However this method does not verify that existing mappings satisfy the constraint .
30,147
public static < K , V > SetMultimap < K , V > constrainedSetMultimap ( SetMultimap < K , V > multimap , MapConstraint < ? super K , ? super V > constraint ) { return new ConstrainedSetMultimap < K , V > ( multimap , constraint ) ; }
Returns a constrained view of the specified set multimap using the specified constraint . Any operations that add new mappings will call the provided constraint . However this method does not verify that existing mappings satisfy the constraint .
30,148
public static < K , V > SortedSetMultimap < K , V > constrainedSortedSetMultimap ( SortedSetMultimap < K , V > multimap , MapConstraint < ? super K , ? super V > constraint ) { return new ConstrainedSortedSetMultimap < K , V > ( multimap , constraint ) ; }
Returns a constrained view of the specified sorted - set multimap using the specified constraint . Any operations that add new mappings will call the provided constraint . However this method does not verify that existing mappings satisfy the constraint .
30,149
public static < K , V > BiMap < K , V > constrainedBiMap ( BiMap < K , V > map , MapConstraint < ? super K , ? super V > constraint ) { return new ConstrainedBiMap < K , V > ( map , null , constraint ) ; }
Returns a constrained view of the specified bimap using the specified constraint . Any operations that modify the bimap will have the associated keys and values verified with the constraint .
30,150
public void release ( ) { IPhynixxManagedConnection < C > con = this . connection ; if ( connection != null ) { this . connection . removeConnectionListener ( this ) ; } this . connection = null ; }
releases the accociated connection . It can be reuse . It ist not closed
30,151
private static Document createXML ( String root , boolean useNamespace ) { try { org . w3c . dom . Document doc = getDocumentBuilder ( null , useNamespace ) . newDocument ( ) ; doc . appendChild ( doc . createElement ( root ) ) ; return new DocumentImpl ( doc ) ; } catch ( Exception e ) { throw new DomException ( e ) ; } }
Helper method for XML document creation .
30,152
public Document parseXML ( String string ) { try { return loadXML ( new ByteArrayInputStream ( string . getBytes ( "UTF-8" ) ) ) ; } catch ( UnsupportedEncodingException e ) { throw new BugError ( "JVM with missing support for UTF-8." ) ; } }
parse XML document from string source
30,153
private static Document loadXML ( InputSource source , boolean useNamespace ) { try { org . w3c . dom . Document doc = getDocumentBuilder ( null , useNamespace ) . parse ( source ) ; return new DocumentImpl ( doc ) ; } catch ( Exception e ) { throw new DomException ( e ) ; } finally { close ( source ) ; } }
Helper method to load XML document from input source .
30,154
private Document loadXML ( URL url , boolean useNamespace ) { InputStream stream = null ; try { stream = url . openConnection ( ) . getInputStream ( ) ; InputSource source = new InputSource ( stream ) ; return useNamespace ? loadXMLNS ( source ) : loadXML ( source ) ; } catch ( Exception e ) { throw new DomException ( e ) ; } finally { close ( stream ) ; } }
Helper method to load XML document from URL .
30,155
public Document loadHTML ( Reader reader ) { return loadHTML ( reader , Charset . defaultCharset ( ) . name ( ) ) ; }
load HTML document from reader
30,156
private static Document loadHTML ( InputSource source , boolean useNamespace ) throws SAXException , IOException { DOMParser parser = new DOMParser ( ) ; parser . setFeature ( FEAT_NAMESPACES , useNamespace ) ; parser . parse ( source ) ; return new DocumentImpl ( parser . getDocument ( ) ) ; }
Helper for loading HTML document from input source .
30,157
private static Document loadHTML ( URL url , boolean useNamespace ) { InputStream stream = null ; try { stream = url . openConnection ( ) . getInputStream ( ) ; return loadHTML ( new InputSource ( stream ) , useNamespace ) ; } catch ( Exception e ) { throw new DomException ( e ) ; } finally { close ( stream ) ; } }
Helper method for HTML loading from URL .
30,158
private static javax . xml . parsers . DocumentBuilder getDocumentBuilder ( Schema schema , boolean useNamespace ) throws ParserConfigurationException { DocumentBuilderFactory dbf = DocumentBuilderFactory . newInstance ( ) ; dbf . setIgnoringComments ( true ) ; dbf . setIgnoringElementContentWhitespace ( true ) ; dbf . setCoalescing ( true ) ; if ( schema != null ) { dbf . setFeature ( FEAT_DOCTYPE_DECL , true ) ; dbf . setValidating ( false ) ; dbf . setFeature ( FEAT_SCHEMA_VALIDATION , true ) ; dbf . setNamespaceAware ( true ) ; dbf . setSchema ( schema ) ; } else { dbf . setFeature ( FEAT_SCHEMA_VALIDATION , false ) ; dbf . setValidating ( false ) ; dbf . setNamespaceAware ( useNamespace ) ; } javax . xml . parsers . DocumentBuilder db = dbf . newDocumentBuilder ( ) ; db . setEntityResolver ( new EntityResolverImpl ( ) ) ; db . setErrorHandler ( new ErrorHandlerImpl ( ) ) ; return db ; }
Get XML document builder .
30,159
private void readObject ( ObjectInputStream in ) throws IOException , ClassNotFoundException { in . defaultReadObject ( ) ; try { init ( ) ; } catch ( ServletException e ) { throw new IllegalStateException ( "Unable to reinitialize dispatcher after deserialization." , e ) ; } }
Custom deserialization . This handles setting transient fields through
30,160
protected Dataset < Sequence > loadDataset ( ) throws Exception { return Dataset . sequence ( ) . type ( DatasetType . InMemory ) . source ( Corpus . builder ( ) . source ( corpus ) . format ( corpusFormat ) . build ( ) . stream ( ) . filter ( d -> d . getAnnotationSet ( ) . isCompleted ( Types . PART_OF_SPEECH ) ) . flatMap ( d -> d . sentences ( ) . stream ( ) ) . map ( sentence -> { SequenceInput < Annotation > input = new SequenceInput < > ( ) ; for ( int i = 0 ; i < sentence . tokenLength ( ) ; i ++ ) { POS pos = sentence . tokenAt ( i ) . getPOS ( ) ; if ( pos == null ) { return null ; } input . add ( sentence . tokenAt ( i ) , pos . asString ( ) ) ; } return featurizer . get ( ) . extractSequence ( input . iterator ( ) ) ; } ) . filter ( Objects :: nonNull ) ) ; }
Load dataset dataset .
30,161
public String format ( int index ) { StringBuilder sb = new StringBuilder ( ) ; final RomanNumeral [ ] values = RomanNumeral . values ( ) ; for ( int i = values . length - 1 ; i >= 0 ; i -- ) { while ( index >= values [ i ] . weight ) { sb . append ( values [ i ] ) ; index -= values [ i ] . weight ; } } return sb . toString ( ) ; }
Format index as upper case Roman numeral .
30,162
private static void reportError ( List messages , String fileName , int lineNr , String line , String errorMessage ) { messages . add ( new Date ( ) + " ERROR in \"" + fileName + "\" at line " + lineNr + ':' ) ; messages . add ( errorMessage ) ; }
Adds a message to the list .
30,163
public void addFile ( String zipEntry , InputStream input ) throws IOException { if ( input != null ) { stream . putNextEntry ( new ZipEntry ( zipEntry ) ) ; Streams . copy ( input , stream ) ; } }
Adds a file to the ZIP archive given its content as an input stream .
30,164
public void addFile ( String zipEntry , byte [ ] data ) throws IOException { stream . putNextEntry ( new ZipEntry ( zipEntry ) ) ; stream . write ( data ) ; }
Adds a file to the ZIP archive given its content as an array of bytes .
30,165
public void addFile ( String zipEntry , ByteArrayOutputStream baos ) throws IOException { addFile ( zipEntry , baos . toByteArray ( ) ) ; }
Adds the contents of a ByteArrayOutputStream to the ZIP archive .
30,166
public void addFile ( String zipEntry , File file ) throws IOException { String zipEntryName = Strings . isValid ( zipEntry ) ? zipEntry : file . getName ( ) ; logger . debug ( "adding '{}' as '{}'" , file . getName ( ) , zipEntryName ) ; try ( InputStream input = new FileInputStream ( file ) ) { addFile ( zipEntryName , input ) ; } }
Adds a file to a ZIP archive .
30,167
public void addFile ( String zipEntry , String filename ) throws IOException { addFile ( zipEntry , new File ( filename ) ) ; }
Adds a file to a ZIP archive given its path .
30,168
public static byte [ ] append ( byte [ ] a , byte [ ] b ) { byte [ ] z = new byte [ a . length + b . length ] ; System . arraycopy ( a , 0 , z , 0 , a . length ) ; System . arraycopy ( b , 0 , z , a . length , b . length ) ; return z ; }
Appends two bytes array into one .
30,169
public static long toLong ( byte [ ] b ) { return ( ( ( ( long ) b [ 7 ] ) & 0xFF ) + ( ( ( ( long ) b [ 6 ] ) & 0xFF ) << 8 ) + ( ( ( ( long ) b [ 5 ] ) & 0xFF ) << 16 ) + ( ( ( ( long ) b [ 4 ] ) & 0xFF ) << 24 ) + ( ( ( ( long ) b [ 3 ] ) & 0xFF ) << 32 ) + ( ( ( ( long ) b [ 2 ] ) & 0xFF ) << 40 ) + ( ( ( ( long ) b [ 1 ] ) & 0xFF ) << 48 ) + ( ( ( ( long ) b [ 0 ] ) & 0xFF ) << 56 ) ) ; }
Build a long from first 8 bytes of the array .
30,170
public static boolean areEqual ( byte [ ] a , byte [ ] b ) { int aLength = a . length ; if ( aLength != b . length ) { return false ; } for ( int i = 0 ; i < aLength ; i ++ ) { if ( a [ i ] != b [ i ] ) { return false ; } } return true ; }
Compares two byte arrays for equality .
30,171
public static ByteBuffer allocateAndReadAll ( int size , ReadableByteChannel channel ) throws IOException { ByteBuffer buf = ByteBuffer . allocate ( size ) ; int justRead ; int totalRead = 0 ; while ( totalRead < size ) { logger . debug ( "reading totalRead={}" , totalRead ) ; if ( ( justRead = channel . read ( buf ) ) < 0 ) throw new EOFException ( "Unexpected end of stream after reading " + totalRead + " bytes" ) ; totalRead += justRead ; } buf . rewind ( ) ; return buf ; }
Allocate a buffer and fill it from a channel . The returned buffer will be rewound to the begining .
30,172
public static ByteBuffer slice ( ByteBuffer buf , int off , int len ) { ByteBuffer localBuf = buf . duplicate ( ) ; logger . debug ( "off={} len={}" , off , len ) ; localBuf . position ( off ) ; localBuf . limit ( off + len ) ; logger . debug ( "pre-slice: localBuf.position()={} localBuf.limit()={}" , localBuf . position ( ) , localBuf . limit ( ) ) ; localBuf = localBuf . slice ( ) ; logger . debug ( "post-slice: localBuf.position()={} localBuf.limit()={}" , localBuf . position ( ) , localBuf . limit ( ) ) ; return localBuf ; }
Sane ByteBuffer slice
30,173
public static String readEnvironment ( String environmentName ) throws MnoConfigurationException { String property = System . getenv ( environmentName ) ; if ( isNullOrEmpty ( property ) ) { throw new MnoConfigurationException ( "Could not environment variable: " + environmentName ) ; } return property ; }
Return the value from the properties and if not found try to find in the System environment variable if not found throws a MnoConfigurationException
30,174
public static String readEnvironment ( String environmentName , String defaultValue ) { String property = System . getenv ( environmentName ) ; if ( isNullOrEmpty ( property ) ) { return defaultValue ; } return property ; }
Read from the System environment variable if not found throws a MnoConfigurationException
30,175
private void create ( Connection conn ) throws SQLException { logger . debug ( "enter - create()" ) ; try { PreparedStatement stmt = null ; ResultSet rs = null ; try { stmt = conn . prepareStatement ( CREATE_SEQ ) ; stmt . setString ( INS_NAME , getName ( ) ) ; stmt . setLong ( INS_NEXT_KEY , nextKey ) ; stmt . setLong ( INS_INTERVAL , interval ) ; stmt . setLong ( INS_UPDATE , System . currentTimeMillis ( ) ) ; if ( stmt . executeUpdate ( ) != 1 ) { logger . warn ( "Unable to create sequence " + getName ( ) + "." ) ; sequence = - 1L ; } } finally { if ( rs != null ) { try { rs . close ( ) ; } catch ( SQLException ignore ) { } } if ( stmt != null ) { try { stmt . close ( ) ; } catch ( SQLException ignore ) { } } } } finally { logger . debug ( "exit - create()" ) ; } }
Creates a new entry in the database for this sequence . This method will throw an error if two threads are simultaneously trying to create a sequence . This state should never occur if you go ahead and create the sequence in the database before deploying the application . It could be avoided by checking SQL exceptions for the proper XOPEN SQLState for duplicate keys . Unfortunately that approach is error prone due to the lack of consistency in proper XOPEN SQLState reporting in JDBC drivers .
30,176
private void reseed ( Connection conn ) throws SQLException { logger . debug ( "enter - reseed()" ) ; try { PreparedStatement stmt = null ; ResultSet rs = null ; try { do { stmt = conn . prepareStatement ( FIND_SEQ ) ; stmt . setString ( SEL_NAME , getName ( ) ) ; rs = stmt . executeQuery ( ) ; if ( ! rs . next ( ) ) { logger . info ( "No sequence in DB for " + getName ( ) + "." ) ; { try { rs . close ( ) ; } catch ( SQLException ignore ) { } rs = null ; try { stmt . close ( ) ; } catch ( SQLException ignore ) { } stmt = null ; } sequence = 100L ; nextKey = sequence + interval ; create ( conn ) ; } else { long ts ; sequence = rs . getLong ( SEL_NEXT_KEY ) ; interval = rs . getLong ( SEL_INTERVAL ) ; if ( interval < 1 ) { interval = defaultInterval ; } nextKey = sequence + interval ; ts = rs . getLong ( SEL_UPDATE ) ; { try { rs . close ( ) ; } catch ( SQLException ignore ) { } rs = null ; try { stmt . close ( ) ; } catch ( SQLException ignore ) { } stmt = null ; } stmt = conn . prepareStatement ( UPDATE_SEQ ) ; stmt . setLong ( UPD_NEXT_KEY , nextKey ) ; stmt . setLong ( UPD_SET_UPDATE , System . currentTimeMillis ( ) ) ; stmt . setString ( UPD_NAME , getName ( ) ) ; stmt . setLong ( UPD_WHERE_KEY , sequence ) ; stmt . setLong ( UPD_WHERE_UPDATE , ts ) ; if ( stmt . executeUpdate ( ) != 1 ) { sequence = - 1L ; logger . warn ( "Concurrency error, requerying DB." ) ; } else { if ( ! conn . getAutoCommit ( ) ) { conn . commit ( ) ; } } } } while ( sequence == - 1L ) ; logger . info ( "Sequence set to " + sequence + ", next_key is " + nextKey + "." ) ; } finally { if ( rs != null ) { try { rs . close ( ) ; } catch ( SQLException ignore ) { } } if ( stmt != null ) { try { stmt . close ( ) ; } catch ( SQLException ignore ) { } } } } finally { logger . debug ( "exit - reseed()" ) ; } }
Gets the next seed from the database for this sequence .
30,177
protected void initResourceConfig ( WebConfig webConfig ) throws ServletException { try { Field field = ServletContainer . class . getDeclaredField ( "resourceConfig" ) ; field . setAccessible ( true ) ; field . set ( this , createResourceConfig ( webConfig ) ) ; } catch ( ReflectiveOperationException e ) { throw new ServletException ( "Failed to createResourceConfig." , e ) ; } catch ( BeansException e ) { throw new ServletException ( "Failed to create bean." , e ) ; } }
Inits the resource config .
30,178
protected ResourceConfig createResourceConfig ( WebConfig webConfig ) throws BeansException { return WebApplicationContextUtils . getWebApplicationContext ( webConfig . getServletContext ( ) ) . getBean ( webConfig . getServletConfig ( ) . getInitParameter ( REST_APPLICATION ) , ResourceConfig . class ) ; }
Creates the resource config .
30,179
public void closeLogger ( String loggerName ) { if ( this . openLoggers . containsKey ( loggerName ) ) { try { this . openLoggers . get ( loggerName ) . close ( ) ; } catch ( Exception e ) { throw new DelegatedRuntimeException ( e ) ; } this . openLoggers . remove ( loggerName ) ; } }
cloes a logger . This logger can be re - reopen
30,180
public synchronized void close ( ) { Map < String , IDataLogger > copiedLoggers = new HashMap < String , IDataLogger > ( this . openLoggers ) ; for ( IDataLogger dataLogger : copiedLoggers . values ( ) ) { try { dataLogger . close ( ) ; } catch ( Exception e ) { } } this . openLoggers . clear ( ) ; }
closes all reopen loggers
30,181
public static Pipe newPipe ( byte [ ] data , int offset , int length , boolean numeric ) throws IOException { final IOContext context = new IOContext ( DEFAULT_SMILE_FACTORY . _getBufferRecycler ( ) , data , false ) ; final SmileParser parser = newSmileParser ( null , data , offset , offset + length , false , context ) ; return JsonIOUtil . newPipe ( parser , numeric ) ; }
Creates a smile pipe from a byte array .
30,182
public Object invoke ( final Invocation invocation ) throws Exception { if ( invocation == null ) throw new NullPointerException ( "invocation" ) ; MethodDescriptor < ? , ? > method = invocation . getMethod ( ) ; DataTypeDescriptor < ? > resultd = ( DataTypeDescriptor < ? > ) method . getResult ( ) ; MessageDescriptor < ? extends Message > excd = descriptor . getExc ( ) ; RpcRequest request = protocol . getRequest ( invocation ) ; return session . send ( request , resultd , excd ) ; }
Serializes an invocation sends an rpc request and returns the result .
30,183
protected String generateETagHeaderValue ( byte [ ] bytes ) { StringBuilder builder = new StringBuilder ( "\"0" ) ; DigestUtils . appendMd5DigestAsHex ( bytes , builder ) ; builder . append ( '"' ) ; return builder . toString ( ) ; }
Generate the ETag header value from the given response body byte array .
30,184
public Set < ClassModel > getAllClassDependencies ( ) { HashSet < ClassModel > result = new HashSet < > ( ) ; for ( ModuleModel module : allModuleDependencies ) { for ( ClassModel clazz : module . classes ) { ClassModel . getAllClassDependencies ( result , clazz ) ; } } return result ; }
All classes this module depends upon . Includes all transitive dependencies of the classes in this module even if the dependencies are not in a module themselves
30,185
List < ? extends E > list ( ) { List < E > result = new ArrayList < E > ( ) ; while ( hasNext ( ) ) { result . add ( next ( ) ) ; } return result ; }
Returns a List with all matching elements .
30,186
public Object create ( Class < ? > iface , ClassLoader proxyLoader ) { return create ( new Class [ ] { iface } , proxyLoader ) ; }
Creates a proxy for the given interface .
30,187
public Object create ( Class < ? > [ ] ifaces , ClassLoader proxyLoader ) { return Proxy . newProxyInstance ( proxyLoader , ifaces , new XRemotingInvocationHandler ( serializer , requester ) ) ; }
Creates a proxy for the given interfaces .
30,188
private String determinateLocalIP ( ) throws IOException { Socket socket = null ; try { URL url = new URL ( defaultRepositoryUrl ) ; int port = url . getPort ( ) > - 1 ? url . getPort ( ) : url . getDefaultPort ( ) ; log . debug ( "Determinating local IP-Adress by connect to {}:{}" , defaultRepositoryUrl , port ) ; InetAddress address = Inet4Address . getByName ( url . getHost ( ) ) ; socket = new Socket ( ) ; socket . connect ( new InetSocketAddress ( address , port ) , 3000 ) ; InputStream stream = socket . getInputStream ( ) ; InetAddress localAddress = socket . getLocalAddress ( ) ; stream . close ( ) ; String localIp = localAddress . getHostAddress ( ) ; log . info ( "Local IP-Adress is {}" , localIp ) ; return localIp ; } finally { if ( socket != null ) { socket . close ( ) ; } } }
Ermittelt anhand der Default - Repository - URL die IP - Adresse der Netzwerkkarte die Verbindung zum Repository hat .
30,189
@ SuppressWarnings ( "unchecked" ) static < T > Pipe . Schema < T > resolvePipeSchema ( Schema < T > schema , Class < ? super T > clazz , boolean throwIfNone ) { if ( Message . class . isAssignableFrom ( clazz ) ) { try { java . lang . reflect . Method m = clazz . getDeclaredMethod ( "getPipeSchema" , new Class [ ] { } ) ; return ( Pipe . Schema < T > ) m . invoke ( null , new Object [ ] { } ) ; } catch ( Exception e ) { } } if ( MappedSchema . class . isAssignableFrom ( schema . getClass ( ) ) ) return ( ( MappedSchema < T > ) schema ) . pipeSchema ; if ( throwIfNone ) throw new RuntimeException ( "No pipe schema for: " + clazz ) ; return null ; }
Invoked only when applications are having pipe io operations .
30,190
public static OAuthRequest attachFile ( File file , OAuthRequest request ) throws IOException { String boundary = generateBoundaryString ( ) ; request . addHeader ( "Content-Type" , "multipart/form-data; boundary=" + boundary ) ; request . addBodyParameter ( "file" , file . getName ( ) ) ; StringBuilder boundaryMessage = new StringBuilder ( "--" ) ; boundaryMessage . append ( boundary ) . append ( "\r\n" ) . append ( "Content-Disposition: form-data; name=\"file\"; filename=\"" ) . append ( file . getName ( ) ) . append ( "\"\r\n" ) . append ( "Content-Type: " ) . append ( "application/x-unknown" ) . append ( "\r\n\r\n" ) ; String endBoundary = "\r\n--" + boundary + "--\r\n" ; ByteArrayOutputStream buffer = new ByteArrayOutputStream ( ) ; buffer . write ( boundaryMessage . toString ( ) . getBytes ( CHARSET_NAME ) ) ; buffer . write ( Files . readFile ( file ) ) ; buffer . write ( endBoundary . getBytes ( CHARSET_NAME ) ) ; request . addPayload ( buffer . toByteArray ( ) ) ; buffer . close ( ) ; return request ; }
Correct attaching specified file to existing request .
30,191
public E next ( ) throws NoSuchElementException { if ( ! more ) throw new NoSuchElementException ( "No more rows to return" ) ; try { E ret = converter . resultSetIteratorRow2Obj ( rs ) ; advance ( ) ; return ret ; } catch ( NoSuchElementException e ) { throw e ; } catch ( SQLException e ) { throw new IllegalStateException ( "SQLException which cannot be rethrown caught" , e ) ; } catch ( Exception e ) { throw new IllegalStateException ( "Exception which cannot be rethrown caught" , e ) ; } }
Return the next result .
30,192
public List < ISubmission > omit ( List < ISubmission > submissions , ISubmitter submitter ) { ArrayList < ISubmission > filteredSubmissions = new ArrayList < ISubmission > ( ) ; for ( ISubmission submission : submissions ) { if ( ! submission . getSubmitter ( ) . equals ( submitter ) ) { filteredSubmissions . add ( submission ) ; } } return filteredSubmissions ; }
Filter a set of submissions removing any from the supplied submitter
30,193
public List < ISubmission > include ( List < ISubmission > submissions , List < String > submitters ) { ArrayList < ISubmission > filteredSubmissions = new ArrayList < ISubmission > ( ) ; for ( ISubmission submission : submissions ) { if ( submission . getSubmitter ( ) != null ) { if ( submitters . contains ( submission . getSubmitter ( ) . getSubmitter ( ) ) ) filteredSubmissions . add ( submission ) ; } } return filteredSubmissions ; }
Filter a set of submissions including only submissions from submitters whose names are in the include list
30,194
private static < K , V > ImmutableSortedMap < K , V > of ( Comparator < ? super K > comparator , K k1 , V v1 ) { return new RegularImmutableSortedMap < K , V > ( new RegularImmutableSortedSet < K > ( ImmutableList . of ( k1 ) , checkNotNull ( comparator ) ) , ImmutableList . of ( v1 ) ) ; }
Returns an immutable map containing a single entry .
30,195
public String getString ( String key , Supplier < String > notFound ) { Object object = getObject ( key ) ; return ( object instanceof String ) ? ( String ) object : notFound . get ( ) ; }
Retrieve a mapped element and return it as a String .
30,196
public BagObject getBagObject ( String key , Supplier < BagObject > notFound ) { Object object = getObject ( key ) ; return ( object instanceof BagObject ) ? ( BagObject ) object : notFound . get ( ) ; }
Retrieve a mapped element and return it as a BagObject .
30,197
public BagArray getBagArray ( String key , Supplier < BagArray > notFound ) { Object object = getObject ( key ) ; return ( object instanceof BagArray ) ? ( BagArray ) object : notFound . get ( ) ; }
Retrieve a mapped element and return it as a BagArray .
30,198
public Boolean getBoolean ( String key , Supplier < Boolean > notFound ) { return getParsed ( key , Boolean :: new , notFound ) ; }
Retrieve a mapped element and return it as a Boolean .
30,199
public Long getLong ( String key , Supplier < Long > notFound ) { return getParsed ( key , Long :: new , notFound ) ; }
Retrieve a mapped element and return it as a Long .