idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
11,500
@ Transactional ( readOnly = true ) public List < Permission > loadRolesAndPermissions ( ) throws Exception { return _persistence . getResults ( _qRoleAuthorizations , null ) ; }
Loads all role permissions into memory .
11,501
public static AbstractConfiguration [ ] execute ( String applicationNamespace , ClassLoader loader , Logger log ) throws Exception { String packageName = "de.jiac.micro.internal.latebind" ; MicroJIACToolContext context = new MicroJIACToolContext ( loader ) ; ConfigurationGenerator generator = new ConfigurationGenerator ( context . getLoader ( ) , log ) ; MergedConfiguration conf = context . createResolver ( ) . resolveAndMerge ( applicationNamespace ) ; CheckerResult checkerResult = context . createChecker ( ) . flattenAndCheck ( conf ) ; for ( String warning : checkerResult . warnings ) { log . warn ( warning ) ; } for ( String error : checkerResult . errors ) { log . error ( error ) ; } if ( checkerResult . hasErrors ( ) ) { throw new GeneratorException ( "checker has found errors" ) ; } return generator . generate ( packageName , conf ) ; }
Return the array of generated node configurations .
11,502
public static void generate ( ConfigurationImpl configuration , String profileName ) { ProfilePackageIndexFrameWriter profpackgen ; DocPath filename = DocPaths . profileFrame ( profileName ) ; try { profpackgen = new ProfilePackageIndexFrameWriter ( configuration , filename ) ; profpackgen . buildProfilePackagesIndexFile ( "doclet.Window_Overview" , false , profileName ) ; profpackgen . close ( ) ; } catch ( IOException exc ) { configuration . standardmessage . error ( "doclet.exception_encountered" , exc . toString ( ) , filename ) ; throw new DocletAbortException ( exc ) ; } }
Generate the profile package index file .
11,503
static String getTypeString ( DocEnv env , Type t , boolean full ) { if ( t . isAnnotated ( ) ) { t = t . unannotatedType ( ) ; } switch ( t . getTag ( ) ) { case ARRAY : StringBuilder s = new StringBuilder ( ) ; while ( t . hasTag ( ARRAY ) ) { s . append ( "[]" ) ; t = env . types . elemtype ( t ) ; } s . insert ( 0 , getTypeString ( env , t , full ) ) ; return s . toString ( ) ; case CLASS : return ParameterizedTypeImpl . parameterizedTypeToString ( env , ( ClassType ) t , full ) ; case WILDCARD : Type . WildcardType a = ( Type . WildcardType ) t ; return WildcardTypeImpl . wildcardTypeToString ( env , a , full ) ; default : return t . tsym . getQualifiedName ( ) . toString ( ) ; } }
Return the string representation of a type use . Bounds of type variables are not included ; bounds of wildcard types are . Class names are qualified if full is true .
11,504
public static String getWebProjectPath ( Object currentObject ) { Class < ? extends Object > class1 = currentObject . getClass ( ) ; ClassLoader classLoader = class1 . getClassLoader ( ) ; URL resource = classLoader . getResource ( "/" ) ; String path = resource . getPath ( ) ; int webRootIndex = StringUtils . indexOfIgnoreCase ( path , "WEB-INF" ) ; if ( path . indexOf ( ":/" ) > 0 ) { return path . substring ( 1 , webRootIndex ) ; } else { return path . substring ( 0 , webRootIndex ) ; } }
The parameter currentObject recommend to user this because of can not be a object which build by manually with new ;
11,505
public void flattenPackagesSourcesAndArtifacts ( Map < String , Module > m ) { modules = m ; for ( Module i : modules . values ( ) ) { for ( Map . Entry < String , Package > j : i . packages ( ) . entrySet ( ) ) { Package p = packages . get ( j . getKey ( ) ) ; assert ( p == null || p == j . getValue ( ) ) ; if ( p == null ) { p = j . getValue ( ) ; packages . put ( j . getKey ( ) , j . getValue ( ) ) ; } for ( Map . Entry < String , Source > k : p . sources ( ) . entrySet ( ) ) { Source s = sources . get ( k . getKey ( ) ) ; assert ( s == null || s == k . getValue ( ) ) ; if ( s == null ) { s = k . getValue ( ) ; sources . put ( k . getKey ( ) , k . getValue ( ) ) ; } } for ( Map . Entry < String , File > g : p . artifacts ( ) . entrySet ( ) ) { File f = artifacts . get ( g . getKey ( ) ) ; assert ( f == null || f == g . getValue ( ) ) ; if ( f == null ) { f = g . getValue ( ) ; artifacts . put ( g . getKey ( ) , g . getValue ( ) ) ; } } } } }
Store references to all packages sources and artifacts for all modules into the build state . I . e . flatten the module tree structure into global maps stored in the BuildState for easy access .
11,506
public void checkInternalState ( String msg , boolean linkedOnly , Map < String , Source > srcs ) { boolean baad = false ; Map < String , Source > original = new HashMap < String , Source > ( ) ; Map < String , Source > calculated = new HashMap < String , Source > ( ) ; for ( String s : sources . keySet ( ) ) { Source ss = sources . get ( s ) ; if ( ss . isLinkedOnly ( ) == linkedOnly ) { calculated . put ( s , ss ) ; } } for ( String s : srcs . keySet ( ) ) { Source ss = srcs . get ( s ) ; if ( ss . isLinkedOnly ( ) == linkedOnly ) { original . put ( s , ss ) ; } } if ( original . size ( ) != calculated . size ( ) ) { Log . error ( "INTERNAL ERROR " + msg + " original and calculated are not the same size!" ) ; baad = true ; } if ( ! original . keySet ( ) . equals ( calculated . keySet ( ) ) ) { Log . error ( "INTERNAL ERROR " + msg + " original and calculated do not have the same domain!" ) ; baad = true ; } if ( ! baad ) { for ( String s : original . keySet ( ) ) { Source s1 = original . get ( s ) ; Source s2 = calculated . get ( s ) ; if ( s1 == null || s2 == null || ! s1 . equals ( s2 ) ) { Log . error ( "INTERNAL ERROR " + msg + " original and calculated have differing elements for " + s ) ; } baad = true ; } } if ( baad ) { for ( String s : original . keySet ( ) ) { Source ss = original . get ( s ) ; Source sss = calculated . get ( s ) ; if ( sss == null ) { Log . error ( "The file " + s + " does not exist in calculated tree of sources." ) ; } } for ( String s : calculated . keySet ( ) ) { Source ss = calculated . get ( s ) ; Source sss = original . get ( s ) ; if ( sss == null ) { Log . error ( "The file " + s + " does not exist in original set of found sources." ) ; } } } }
Verify that the setModules method above did the right thing when running through the module - > package - > source structure .
11,507
public RepositoryAdmin getRepositoryAdmin ( BundleContext context , ObrClassFinderService autoStartNotify ) throws InvalidSyntaxException { RepositoryAdmin admin = null ; ServiceReference [ ] ref = context . getServiceReferences ( RepositoryAdmin . class . getName ( ) , null ) ; if ( ( ref != null ) && ( ref . length > 0 ) ) admin = ( RepositoryAdmin ) context . getService ( ref [ 0 ] ) ; if ( admin == null ) if ( autoStartNotify != null ) if ( waitingForRepositoryAdmin == false ) { context . addServiceListener ( new RepositoryAdminServiceListener ( autoStartNotify , context ) , "(" + Constants . OBJECTCLASS + "=" + RepositoryAdmin . class . getName ( ) + ")" ) ; waitingForRepositoryAdmin = true ; } return admin ; }
Get the repository admin service .
11,508
public void addBootstrapRepository ( RepositoryAdmin repositoryAdmin , BundleContext context ) { if ( repositoryAdmin == null ) return ; String repository = context . getProperty ( "jbundle.repository.url" ) ; if ( repository != null ) if ( repository . length ( ) > 0 ) this . addRepository ( repositoryAdmin , repository ) ; }
Add the standard obr repository so I can get the bundles that I need .
11,509
public void addRepository ( RepositoryAdmin repositoryAdmin , String repository ) { try { if ( repository != null ) { boolean duplicate = false ; for ( Repository repo : repositoryAdmin . listRepositories ( ) ) { if ( repository . equalsIgnoreCase ( repo . getURI ( ) ) ) duplicate = true ; } if ( ! duplicate ) { Repository repo = repositoryAdmin . addRepository ( repository ) ; if ( repo == null ) repositoryAdmin . removeRepository ( repository ) ; } } } catch ( Exception e ) { } }
Add this repository to my available repositories .
11,510
public boolean startClassFinderActivator ( BundleContext context ) { if ( ClassFinderActivator . getClassFinder ( context , 0 ) == this ) return true ; String packageName = ClassFinderActivator . getPackageName ( ClassFinderActivator . class . getName ( ) , false ) ; Bundle bundle = this . findBundle ( null , context , packageName , null ) ; if ( bundle == null ) { Resource resource = ( Resource ) this . deployThisResource ( packageName , null , false ) ; bundle = this . findBundle ( resource , context , packageName , null ) ; } if ( bundle != null ) { if ( ( ( bundle . getState ( ) & Bundle . ACTIVE ) == 0 ) && ( ( bundle . getState ( ) & Bundle . STARTING ) == 0 ) ) { try { bundle . start ( ) ; } catch ( BundleException e ) { e . printStackTrace ( ) ; } } ClassFinderActivator . setClassFinder ( this ) ; return true ; } return false ; }
Convenience method to start the class finder utility service . If admin service is not up yet this starts it .
11,511
public Object deployThisResource ( String packageName , String versionRange , boolean start ) { int options = 0 ; if ( repositoryAdmin == null ) return null ; DataModelHelper helper = repositoryAdmin . getHelper ( ) ; if ( this . getResourceFromCache ( packageName ) != null ) return this . getResourceFromCache ( packageName ) ; String filter = "(package=" + packageName + ")" ; filter = ClassFinderActivator . addVersionFilter ( filter , versionRange ) ; Requirement requirement = helper . requirement ( "package" , filter ) ; Requirement [ ] requirements = { requirement } ; Resource [ ] resources = repositoryAdmin . discoverResources ( requirements ) ; Resource bestResource = null ; if ( resources != null ) { Version bestVersion = null ; for ( Resource resource : resources ) { Version resourceVersion = resource . getVersion ( ) ; if ( ! isValidVersion ( resourceVersion , versionRange ) ) continue ; if ( ( bestVersion == null ) || ( resourceVersion . compareTo ( bestVersion ) >= 0 ) ) { bestVersion = resourceVersion ; bestResource = resource ; } } } if ( bestResource != null ) { this . deployResource ( bestResource , options ) ; Bundle bundle = this . findBundle ( bestResource , bundleContext , packageName , versionRange ) ; if ( start ) this . startBundle ( bundle ) ; this . addResourceToCache ( packageName , bestResource ) ; } return bestResource ; }
Find this resource in the repository then deploy and optionally start it .
11,512
public void deployResources ( Resource [ ] resources , int options ) { if ( resources != null ) { for ( Resource resource : resources ) { this . deployResource ( resource , options ) ; } } }
Deploy this list of resources .
11,513
public void deployResource ( Resource resource , int options ) { String name = resource . getSymbolicName ( ) + "/" + resource . getVersion ( ) ; Lock lock = this . getLock ( name ) ; try { boolean acquired = lock . tryLock ( ) ; if ( acquired ) { try { Resolver resolver = repositoryAdmin . resolver ( ) ; resolver . add ( resource ) ; int resolveAttempt = 5 ; while ( resolveAttempt -- > 0 ) { try { if ( resolver . resolve ( options ) ) { resolver . deploy ( options ) ; break ; } else { Reason [ ] reqs = resolver . getUnsatisfiedRequirements ( ) ; for ( int i = 0 ; i < reqs . length ; i ++ ) { ClassServiceUtility . log ( bundleContext , LogService . LOG_ERROR , "Unable to resolve: " + reqs [ i ] ) ; } break ; } } catch ( IllegalStateException e ) { if ( resolveAttempt == 0 ) e . printStackTrace ( ) ; } } } finally { lock . unlock ( ) ; } } else { acquired = lock . tryLock ( secondsToWait , TimeUnit . SECONDS ) ; if ( acquired ) { try { } finally { lock . unlock ( ) ; } } else { } } } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } finally { this . removeLock ( name ) ; } }
Deploy this resource .
11,514
public boolean isResourceBundleMatch ( Object objResource , Bundle bundle ) { Resource resource = ( Resource ) objResource ; return ( ( bundle . getSymbolicName ( ) . equals ( resource . getSymbolicName ( ) ) ) && ( isValidVersion ( bundle . getVersion ( ) , resource . getVersion ( ) . toString ( ) ) ) ) ; }
Does this resource match this bundle?
11,515
@ SuppressWarnings ( "unchecked" ) public List < RpcResponse > request ( List < RpcRequest > reqList ) { List < RpcResponse > respList = new ArrayList < RpcResponse > ( ) ; List < Map > marshaledReqs = new ArrayList < Map > ( ) ; Map < String , RpcRequest > byReqId = new HashMap < String , RpcRequest > ( ) ; for ( RpcRequest req : reqList ) { try { marshaledReqs . add ( req . marshal ( contract ) ) ; byReqId . put ( req . getId ( ) , req ) ; } catch ( RpcException e ) { respList . add ( new RpcResponse ( req , e ) ) ; } } InputStream is = null ; try { ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; serializer . write ( marshaledReqs , bos ) ; bos . close ( ) ; byte [ ] data = bos . toByteArray ( ) ; is = requestRaw ( data ) ; List < Map > responses = serializer . readList ( is ) ; for ( Map map : responses ) { String id = ( String ) map . get ( "id" ) ; if ( id != null ) { RpcRequest req = byReqId . get ( id ) ; if ( req == null ) { } else { byReqId . remove ( id ) ; respList . add ( unmarshal ( req , map ) ) ; } } else { } } if ( byReqId . size ( ) > 0 ) { for ( RpcRequest req : byReqId . values ( ) ) { String msg = "No response in batch for request " + req . getId ( ) ; RpcException exc = RpcException . Error . INVALID_RESP . exc ( msg ) ; RpcResponse resp = new RpcResponse ( req , exc ) ; respList . add ( resp ) ; } } } catch ( IOException e ) { String msg = "IOException requesting batch " + " from: " + endpoint + " - " + e . getMessage ( ) ; RpcException exc = RpcException . Error . INTERNAL . exc ( msg ) ; respList . add ( new RpcResponse ( null , exc ) ) ; } finally { closeQuietly ( is ) ; } return respList ; }
Makes JSON - RPC batch request against the remote server as a single HTTP request .
11,516
public URLConnection createURLConnection ( URL url ) throws IOException { URLConnection conn = url . openConnection ( ) ; return conn ; }
Returns an URLConnection for the given URL . Subclasses may override this and customize the connection with custom timeouts headers etc .
11,517
public Content getSignature ( MethodDoc method ) { Content pre = new HtmlTree ( HtmlTag . PRE ) ; writer . addAnnotationInfo ( method , pre ) ; addModifiers ( method , pre ) ; addTypeParameters ( method , pre ) ; addReturnType ( method , pre ) ; if ( configuration . linksource ) { Content methodName = new StringContent ( method . name ( ) ) ; writer . addSrcLink ( method , methodName , pre ) ; } else { addName ( method . name ( ) , pre ) ; } int indent = pre . charCount ( ) ; addParameters ( method , pre , indent ) ; addExceptions ( method , pre , indent ) ; return pre ; }
Get the signature for the given method .
11,518
public String generateTemporaryToken ( String key , int secondsToLive , Object context ) { checkNotNull ( key ) ; String token = tokenGenerator . generate ( ) ; tokenCache . put ( key , Triplet . of ( token , DateTime . now ( ) . plusSeconds ( secondsToLive ) . getMillis ( ) , context ) ) ; return token ; }
Same as above but will also store a context that can be retried later .
11,519
public Optional < Object > getContextForToken ( String key , String token ) { Object context = validateTokenAndGetContext ( key , token ) . second ( ) ; return null != context ? Optional . of ( context ) : Optional . absent ( ) ; }
Validate a short lived token and returning the associated context The token is removed if found and valid .
11,520
public Object put ( Object key , Object value ) { long objectStamp = System . currentTimeMillis ( ) ; synchronized ( objects ) { objectTimeStamps . put ( key , objectStamp ) ; if ( nextTimeSomeExpired == NO_OBJECTS ) { nextTimeSomeExpired = objectStamp ; } return objects . put ( key , value ) ; } }
Method to store value in cache if this value first in cache - also mark nextTimeSomeExpired as its creating time ;
11,521
public Object remove ( Object key ) { synchronized ( objects ) { Object remove = objects . remove ( key ) ; objectTimeStamps . remove ( key ) ; if ( remove != null ) { findNextExpireTime ( ) ; } return remove ; } }
When we remove any object we must found again nextTimeSomeExpired .
11,522
private void findNextExpireTime ( ) { if ( objects . size ( ) == 0 ) { nextTimeSomeExpired = NO_OBJECTS ; } else { nextTimeSomeExpired = NO_OBJECTS ; Collection < Long > longs = null ; synchronized ( objects ) { longs = new ArrayList ( objectTimeStamps . values ( ) ) ; } for ( Iterator < Long > iterator = longs . iterator ( ) ; iterator . hasNext ( ) ; ) { Long next = iterator . next ( ) + timeToLive ; if ( nextTimeSomeExpired == NO_OBJECTS || next < nextTimeSomeExpired ) { nextTimeSomeExpired = next ; } } } }
Internal - use method finds out when next object will expire and store this as nextTimeSomeExpired . If there s no items in cache - let s store NO_OBJECTS
11,523
@ SuppressWarnings ( "unchecked" ) public static < M extends Enum < M > > void attach ( Service service , String milestore , ServiceMilestone . Evaluation evaluation ) throws Exception { for ( Field field : Beans . getKnownInstanceFields ( service . getClass ( ) ) ) { if ( ServiceMilestone . class . isAssignableFrom ( field . getType ( ) ) ) { try { ( ( ServiceMilestone < M > ) field . get ( service ) ) . attach ( Enum . valueOf ( ( Class < M > ) getMilestoneEnum ( field . getDeclaringClass ( ) ) , milestore ) , evaluation ) ; return ; } catch ( ClassNotFoundException x ) { } catch ( IllegalArgumentException x ) { } } } throw new IllegalArgumentException ( "NoSuchMilestone" ) ; }
Attaches a ServiceMilestone . Evaluation onto a service .
11,524
public void attach ( M m , Evaluation eval ) { _evaluations [ m . ordinal ( ) ] = _evaluations [ m . ordinal ( ) ] == null ? eval : new CompoundMilestoneEvaluation ( eval , _evaluations [ m . ordinal ( ) ] ) ; }
Attaches a ServiceMilestone . Evaluation .
11,525
public void detach ( M m , Evaluation eval ) { _evaluations [ m . ordinal ( ) ] = CompoundMilestoneEvaluation . cleanse ( _evaluations [ m . ordinal ( ) ] , eval ) ; }
Detaches a ServiceMilestone . Evaluation .
11,526
@ SuppressWarnings ( "unchecked" ) public Recommendation evaluate ( M milestone , DataBinder binder , Reifier dict , Persistence persist ) { Evaluation evaluation = _evaluations [ milestone . ordinal ( ) ] ; return evaluation != null ? evaluation . evaluate ( ( Class < M > ) milestone . getClass ( ) , milestone . toString ( ) , binder , dict , persist ) : Recommendation . CONTINUE ; }
Executes evaluations at a milestone .
11,527
public DocumentType findByReference ( final String reference ) { return queryResultsCache . execute ( ( ) -> repositoryService . firstMatch ( new QueryDefault < > ( DocumentType . class , "findByReference" , "reference" , reference ) ) , DocumentTypeRepository . class , "findByReference" , reference ) ; }
region > findByReference
11,528
public Name xClassName ( Type t ) { if ( t . hasTag ( CLASS ) ) { return names . fromUtf ( externalize ( t . tsym . flatName ( ) ) ) ; } else if ( t . hasTag ( ARRAY ) ) { return typeSig ( types . erasure ( t ) ) ; } else { throw new AssertionError ( "xClassName" ) ; } }
Given a type t return the extended class name of its erasure in external representation .
11,529
Name fieldName ( Symbol sym ) { if ( scramble && ( sym . flags ( ) & PRIVATE ) != 0 || scrambleAll && ( sym . flags ( ) & ( PROTECTED | PUBLIC ) ) == 0 ) return names . fromString ( "_$" + sym . name . getIndex ( ) ) ; else return sym . name ; }
Given a field return its name .
11,530
void writeMethod ( MethodSymbol m ) { int flags = adjustFlags ( m . flags ( ) ) ; databuf . appendChar ( flags ) ; if ( dumpMethodModifiers ) { PrintWriter pw = log . getWriter ( Log . WriterKind . ERROR ) ; pw . println ( "METHOD " + fieldName ( m ) ) ; pw . println ( "---" + flagNames ( m . flags ( ) ) ) ; } databuf . appendChar ( pool . put ( fieldName ( m ) ) ) ; databuf . appendChar ( pool . put ( typeSig ( m . externalType ( types ) ) ) ) ; int acountIdx = beginAttrs ( ) ; int acount = 0 ; if ( m . code != null ) { int alenIdx = writeAttr ( names . Code ) ; writeCode ( m . code ) ; m . code = null ; endAttr ( alenIdx ) ; acount ++ ; } List < Type > thrown = m . erasure ( types ) . getThrownTypes ( ) ; if ( thrown . nonEmpty ( ) ) { int alenIdx = writeAttr ( names . Exceptions ) ; databuf . appendChar ( thrown . length ( ) ) ; for ( List < Type > l = thrown ; l . nonEmpty ( ) ; l = l . tail ) databuf . appendChar ( pool . put ( l . head . tsym ) ) ; endAttr ( alenIdx ) ; acount ++ ; } if ( m . defaultValue != null ) { int alenIdx = writeAttr ( names . AnnotationDefault ) ; m . defaultValue . accept ( awriter ) ; endAttr ( alenIdx ) ; acount ++ ; } if ( options . isSet ( PARAMETERS ) ) acount += writeMethodParametersAttr ( m ) ; acount += writeMemberAttrs ( m ) ; acount += writeParameterAttrs ( m ) ; endAttrs ( acountIdx , acount ) ; }
Write method symbol entering all references into constant pool .
11,531
public static Set < String > getPrimaryKey ( DatabaseMetaData metadata , String tableName ) throws Exception { Set < String > columns = new HashSet < String > ( ) ; ResultSet keys = metadata . getPrimaryKeys ( metadata . getConnection ( ) . getCatalog ( ) , metadata . getUserName ( ) , tableName ) ; while ( keys . next ( ) ) { columns . add ( keys . getString ( PRIMARY_PK_COL_NAME ) ) ; } keys . close ( ) ; return columns ; }
Returns a table s primary key columns as a Set of strings .
11,532
public static Map < String , ForeignKey > getExportedKeys ( DatabaseMetaData metadata , String tableName ) throws Exception { ResultSet keys = metadata . getExportedKeys ( metadata . getConnection ( ) . getCatalog ( ) , metadata . getUserName ( ) , tableName ) ; Map < String , ForeignKey > map = new HashMap < String , ForeignKey > ( ) ; while ( keys . next ( ) ) { String table = keys . getString ( EXPORTED_FK_TAB_NAME ) ; String name = keys . getString ( EXPORTED_FK_KEY_NAME ) ; if ( name == null || name . length ( ) == 0 ) name = "UNNAMED_FK_" + table ; ForeignKey key = map . get ( name ) ; if ( key == null ) { map . put ( name , key = new ForeignKey ( table ) ) ; } key . add ( keys . getString ( EXPORTED_FK_COL_NAME ) ) ; } keys . close ( ) ; return map ; }
Returns a table s exported keys and their columns as a Map from the key name to the ForeignKey object .
11,533
public static Map < String , ForeignKey > getForeignKeys ( DatabaseMetaData metadata , String tableName ) throws Exception { ResultSet keys = metadata . getImportedKeys ( metadata . getConnection ( ) . getCatalog ( ) , metadata . getUserName ( ) , tableName ) ; Map < String , ForeignKey > map = new HashMap < String , ForeignKey > ( ) ; while ( keys . next ( ) ) { String table = keys . getString ( IMPORTED_PK_TAB_NAME ) ; String name = keys . getString ( IMPORTED_FK_KEY_NAME ) ; if ( name == null || name . length ( ) == 0 ) name = "UNNAMED_FK_" + table ; ForeignKey key = map . get ( name ) ; if ( key == null ) { map . put ( name , key = new ForeignKey ( table ) ) ; } key . add ( keys . getString ( IMPORTED_FK_COL_NAME ) ) ; } keys . close ( ) ; return map ; }
Returns a table s foreign keys and their columns as a Map from the key name to the ForeignKey object .
11,534
public static List < Column > getColumns ( DatabaseMetaData metadata , String tableName ) throws Exception { List < Column > columns = new ArrayList < Column > ( ) ; PreparedStatement stmt = metadata . getConnection ( ) . prepareStatement ( "SELECT * FROM " + tableName ) ; ResultSetMetaData rsmeta = stmt . getMetaData ( ) ; for ( int i = 1 , ii = rsmeta . getColumnCount ( ) ; i <= ii ; ++ i ) { columns . add ( new Column ( rsmeta , i ) ) ; } stmt . close ( ) ; return columns ; }
Returns a table s columns
11,535
public static Table getTable ( DatabaseMetaData metadata , String tableName ) throws Exception { return new Table ( tableName , getPrimaryKey ( metadata , tableName ) , getForeignKeys ( metadata , tableName ) , getExportedKeys ( metadata , tableName ) , getColumns ( metadata , tableName ) ) ; }
Returns a table s structure
11,536
public static String getClassName ( ResultSetMetaData meta , int index ) throws SQLException { switch ( meta . getColumnType ( index ) ) { case Types . NUMERIC : int precision = meta . getPrecision ( index ) ; if ( meta . getScale ( index ) == 0 ) { if ( precision > 18 ) { return "java.math.BigInteger" ; } else if ( precision > 9 ) { return "java.lang.Long" ; } else if ( precision > 4 ) { return "java.lang.Integer" ; } else if ( precision > 2 ) { return "java.lang.Short" ; } else { return "java.lang.Byte" ; } } else { if ( precision > 16 ) { return "java.math.BigDecimal" ; } else if ( precision > 7 ) { return "java.lang.Double" ; } else { return "java.lang.Float" ; } } case Types . TIMESTAMP : if ( meta . getScale ( index ) == 0 ) { return "java.sql.Date" ; } else { return "java.sql.Timestamp" ; } default : return meta . getColumnClassName ( index ) ; } }
Returns a column s java class name .
11,537
public void add ( Collection < Monitor > monitors ) { for ( Monitor monitor : monitors ) this . monitors . put ( monitor . getId ( ) , monitor ) ; }
Adds the monitor list to the monitors for the account .
11,538
public LabelCache labels ( String monitorId ) { LabelCache cache = labels . get ( monitorId ) ; if ( cache == null ) labels . put ( monitorId , cache = new LabelCache ( monitorId ) ) ; return cache ; }
Returns the cache of labels for the given monitor creating one if it doesn t exist .
11,539
public TabbedPanel put ( Widget widget , String name , int index ) { if ( index < 0 || index >= content . length ) throw new IndexOutOfBoundsException ( ) ; if ( widget == null ) return this ; attach ( widget ) ; content [ index ] = new Tab ( widget , name ) ; this . sendElement ( ) ; return this ; }
Puts new widget to the container
11,540
public final EChange setAddress ( final String sAddress ) { ValueEnforcer . notNull ( sAddress , "Address" ) ; final String sRealAddress = EmailAddressHelper . getUnifiedEmailAddress ( sAddress ) ; if ( EqualsHelper . equals ( sRealAddress , m_sAddress ) ) return EChange . UNCHANGED ; if ( sRealAddress != null && ! EmailAddressHelper . isValid ( sRealAddress ) ) { if ( LOGGER . isErrorEnabled ( ) ) LOGGER . error ( "Found an illegal email address: '" + sRealAddress + "'" ) ; return EChange . UNCHANGED ; } m_sAddress = sRealAddress ; return EChange . CHANGED ; }
Set the address part of the email address . Performs a validity check of the email address .
11,541
public static void preRegister ( Context context ) { context . put ( JavaFileManager . class , new Context . Factory < JavaFileManager > ( ) { public JavaFileManager make ( Context c ) { return new JavacFileManager ( c , true , null ) ; } } ) ; }
Register a Context . Factory to create a JavacFileManager .
11,542
private void listDirectory ( File directory , RelativeDirectory subdirectory , Set < JavaFileObject . Kind > fileKinds , boolean recurse , ListBuffer < JavaFileObject > resultList ) { File d = subdirectory . getFile ( directory ) ; if ( ! caseMapCheck ( d , subdirectory ) ) return ; File [ ] files = d . listFiles ( ) ; if ( files == null ) return ; if ( sortFiles != null ) Arrays . sort ( files , sortFiles ) ; for ( File f : files ) { String fname = f . getName ( ) ; if ( f . isDirectory ( ) ) { if ( recurse && SourceVersion . isIdentifier ( fname ) ) { listDirectory ( directory , new RelativeDirectory ( subdirectory , fname ) , fileKinds , recurse , resultList ) ; } } else { if ( isValidFile ( fname , fileKinds ) ) { JavaFileObject fe = new RegularFileObject ( this , fname , new File ( d , fname ) ) ; resultList . append ( fe ) ; } } } }
Insert all files in subdirectory subdirectory of directory directory which match fileKinds into resultList
11,543
private void listArchive ( Archive archive , RelativeDirectory subdirectory , Set < JavaFileObject . Kind > fileKinds , boolean recurse , ListBuffer < JavaFileObject > resultList ) { List < String > files = archive . getFiles ( subdirectory ) ; if ( files != null ) { for ( ; ! files . isEmpty ( ) ; files = files . tail ) { String file = files . head ; if ( isValidFile ( file , fileKinds ) ) { resultList . append ( archive . getFileObject ( subdirectory , file ) ) ; } } } if ( recurse ) { for ( RelativeDirectory s : archive . getSubdirectories ( ) ) { if ( subdirectory . contains ( s ) ) { listArchive ( archive , s , fileKinds , false , resultList ) ; } } } }
Insert all files in subdirectory subdirectory of archive archive which match fileKinds into resultList
11,544
private void listContainer ( File container , RelativeDirectory subdirectory , Set < JavaFileObject . Kind > fileKinds , boolean recurse , ListBuffer < JavaFileObject > resultList ) { Archive archive = archives . get ( container ) ; if ( archive == null ) { if ( fsInfo . isDirectory ( container ) ) { listDirectory ( container , subdirectory , fileKinds , recurse , resultList ) ; return ; } try { archive = openArchive ( container ) ; } catch ( IOException ex ) { log . error ( "error.reading.file" , container , getMessage ( ex ) ) ; return ; } } listArchive ( archive , subdirectory , fileKinds , recurse , resultList ) ; }
container is a directory a zip file or a non - existant path . Insert all files in subdirectory subdirectory of container which match fileKinds into resultList
11,545
private Archive openArchive ( File zipFileName , boolean useOptimizedZip ) throws IOException { File origZipFileName = zipFileName ; if ( symbolFileEnabled && locations . isDefaultBootClassPathRtJar ( zipFileName ) ) { File file = zipFileName . getParentFile ( ) . getParentFile ( ) ; if ( new File ( file . getName ( ) ) . equals ( new File ( "jre" ) ) ) file = file . getParentFile ( ) ; for ( String name : symbolFileLocation ) file = new File ( file , name ) ; if ( file . exists ( ) ) zipFileName = file ; } Archive archive ; try { ZipFile zdir = null ; boolean usePreindexedCache = false ; String preindexCacheLocation = null ; if ( ! useOptimizedZip ) { zdir = new ZipFile ( zipFileName ) ; } else { usePreindexedCache = options . isSet ( "usezipindex" ) ; preindexCacheLocation = options . get ( "java.io.tmpdir" ) ; String optCacheLoc = options . get ( "cachezipindexdir" ) ; if ( optCacheLoc != null && optCacheLoc . length ( ) != 0 ) { if ( optCacheLoc . startsWith ( "\"" ) ) { if ( optCacheLoc . endsWith ( "\"" ) ) { optCacheLoc = optCacheLoc . substring ( 1 , optCacheLoc . length ( ) - 1 ) ; } else { optCacheLoc = optCacheLoc . substring ( 1 ) ; } } File cacheDir = new File ( optCacheLoc ) ; if ( cacheDir . exists ( ) && cacheDir . canWrite ( ) ) { preindexCacheLocation = optCacheLoc ; if ( ! preindexCacheLocation . endsWith ( "/" ) && ! preindexCacheLocation . endsWith ( File . separator ) ) { preindexCacheLocation += File . separator ; } } } } if ( origZipFileName == zipFileName ) { if ( ! useOptimizedZip ) { archive = new ZipArchive ( this , zdir ) ; } else { archive = new ZipFileIndexArchive ( this , zipFileIndexCache . getZipFileIndex ( zipFileName , null , usePreindexedCache , preindexCacheLocation , options . isSet ( "writezipindexfiles" ) ) ) ; } } else { if ( ! useOptimizedZip ) { archive = new SymbolArchive ( this , origZipFileName , zdir , symbolFilePrefix ) ; } else { archive = new ZipFileIndexArchive ( this , zipFileIndexCache . getZipFileIndex ( zipFileName , symbolFilePrefix , usePreindexedCache , preindexCacheLocation , options . isSet ( "writezipindexfiles" ) ) ) ; } } } catch ( FileNotFoundException ex ) { archive = new MissingArchive ( zipFileName ) ; } catch ( ZipFileIndex . ZipFormatException zfe ) { throw zfe ; } catch ( IOException ex ) { if ( zipFileName . exists ( ) ) log . error ( "error.reading.file" , zipFileName , getMessage ( ex ) ) ; archive = new MissingArchive ( zipFileName ) ; } archives . put ( origZipFileName , archive ) ; return archive ; }
Open a new zip file directory and cache it .
11,546
public void add ( Collection < KeyTransaction > keyTransactions ) { for ( KeyTransaction keyTransaction : keyTransactions ) this . keyTransactions . put ( keyTransaction . getId ( ) , keyTransaction ) ; }
Adds the key transaction list to the key transactions for the account .
11,547
public static VATINStructure getFromValidVATIN ( final String sVATIN ) { if ( StringHelper . getLength ( sVATIN ) > 2 ) for ( final VATINStructure aStructure : s_aList ) if ( aStructure . isValid ( sVATIN ) ) return aStructure ; return null ; }
Determine the structure for a given VATIN .
11,548
public static VATINStructure getFromVATINCountry ( final String sVATIN ) { if ( StringHelper . getLength ( sVATIN ) >= 2 ) { final String sCountry = sVATIN . substring ( 0 , 2 ) ; for ( final VATINStructure aStructure : s_aList ) if ( aStructure . getExamples ( ) . get ( 0 ) . substring ( 0 , 2 ) . equalsIgnoreCase ( sCountry ) ) return aStructure ; } return null ; }
Resolve the VATIN structure only from the country part of the given VATIN . This should help indicate how the VATIN is valid .
11,549
protected Iterable < JavaFileObject > wrap ( Iterable < JavaFileObject > fileObjects ) { List < JavaFileObject > mapped = new ArrayList < JavaFileObject > ( ) ; for ( JavaFileObject fileObject : fileObjects ) mapped . add ( wrap ( fileObject ) ) ; return Collections . unmodifiableList ( mapped ) ; }
This implementation maps the given list of file objects by calling wrap on each . Subclasses may override this behavior .
11,550
public static Control createInstance ( ControlVersion version ) { switch ( version ) { case _0_24 : return new Control0_24 ( ) ; case _0_25 : return new Control0_25 ( ) ; default : throw new IllegalArgumentException ( "Unknown control version: " + version ) ; } }
Create a new instance of the frontend network control for the desired version .
11,551
protected final void attach ( Attachable widget ) { if ( user != null ) { widget . addTo ( user ) ; } else { if ( waitingForUser == null ) waitingForUser = new LinkedList < Attachable > ( ) ; waitingForUser . add ( widget ) ; } }
Used to declare that instance of widget is held by this widget . If this widget is container it must invoke this method for all widgets it stores
11,552
public org . jbundle . util . osgi . ClassFinder getClassFinder ( Object context ) { if ( ! classServiceAvailable ) return null ; try { if ( classFinder == null ) { Class . forName ( "org.osgi.framework.BundleActivator" ) ; try { Class < ? > clazz = Class . forName ( "org.jbundle.util.osgi.finder.ClassFinderActivator" ) ; if ( clazz != null ) { java . lang . reflect . Method method = clazz . getMethod ( "getClassFinder" , Object . class , int . class ) ; if ( method != null ) classFinder = ( org . jbundle . util . osgi . ClassFinder ) method . invoke ( null , context , - 1 ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } } return classFinder ; } catch ( ClassNotFoundException ex ) { classServiceAvailable = false ; return null ; } catch ( Exception ex ) { ex . printStackTrace ( ) ; return null ; } }
Doesn t need to be static since this is only created once
11,553
public final ResourceBundle getResourceBundle ( String className , Locale locale , String version , ClassLoader classLoader ) throws MissingResourceException { MissingResourceException ex = null ; ResourceBundle resourceBundle = null ; try { resourceBundle = ResourceBundle . getBundle ( className , locale ) ; } catch ( MissingResourceException e ) { ex = e ; } if ( resourceBundle == null ) { try { if ( this . getClassFinder ( null ) != null ) resourceBundle = this . getClassFinder ( null ) . findResourceBundle ( className , locale , version ) ; } catch ( MissingResourceException e ) { ex = e ; } } if ( resourceBundle == null ) if ( ex != null ) throw ex ; return resourceBundle ; }
Gets a resource bundle using the specified base name and locale
11,554
public static String getFullClassName ( String packageName , String className ) { return ClassServiceUtility . getFullClassName ( null , packageName , className ) ; }
If class name starts with . append base package .
11,555
public String find ( String name ) { String value = null ; for ( DataBinder top = this ; top != null && ( value = top . get ( name ) ) == null ; top = top . getLower ( ) ) ; return value ; }
Finds a string value from all data binders starting from the current binder searching downwards .
11,556
public String put ( String name , String value , String alternative ) { return put ( name , value != null ? value : alternative ) ; }
Puts a new string value into this binder but using an alternative value if the given one is null .
11,557
public CachedResultSet putResultSet ( String name , CachedResultSet rs ) { return _rsets . put ( name , rs ) ; }
Puts a new result set into this binder .
11,558
@ SuppressWarnings ( "unchecked" ) public < T , V > T putNamedObject ( String name , V object ) { return ( T ) _named . put ( name , object ) ; }
Puts a named object into this binder returning the original object under the name if any .
11,559
@ SuppressWarnings ( "unchecked" ) public < T > T getNamedObject ( String name ) { return ( T ) _named . get ( name ) ; }
Retrieves a named object from this binder .
11,560
public < T > T getNamedObject ( String name , Class < T > type ) { return type . cast ( _named . get ( name ) ) ; }
Retrieves a named object of a specific type from this binder .
11,561
public < K , V > Map < K , V > map ( String name , Class < K > ktype , Class < V > vtype ) { Map < K , V > map = getNamedObject ( name ) ; if ( map == null ) putNamedObject ( name , map = new HashMap < K , V > ( ) ) ; return map ; }
Introduces a HashMap under the given name if one does not exist yet .
11,562
public < K , V > Multimap < K , V > mul ( String name , Class < K > ktype , Class < V > vtype ) { Multimap < K , V > map = getNamedObject ( name ) ; if ( map == null ) putNamedObject ( name , map = new Multimap < K , V > ( ) ) ; return map ; }
Introduces a Multimap under the given name if one does not exist yet .
11,563
public DataBinder process ( ResultSet rset ) throws Exception { try { if ( rset . next ( ) ) { ResultSetMetaData meta = rset . getMetaData ( ) ; int width = meta . getColumnCount ( ) ; for ( int i = 1 ; i <= width ; ++ i ) { Object value = rset . getObject ( i ) ; if ( value != null ) { put ( Strings . toLowerCamelCase ( meta . getColumnLabel ( i ) , '_' ) , value . toString ( ) ) ; } } } else { throw new NoSuchElementException ( "NoSuchRow" ) ; } return this ; } finally { rset . close ( ) ; } }
Fills the data binder with columns in the current row of a result set .
11,564
public DataBinder put ( Object object ) throws Exception { for ( Field field : Beans . getKnownInstanceFields ( object . getClass ( ) ) ) { Object value = field . get ( object ) ; if ( value != null ) { put ( field . getName ( ) , value . toString ( ) ) ; } } return this ; }
Fills the data binder with non - static non - transient fields of an Object excluding null values .
11,565
public < T extends DataObject > DataBinder put ( T object , String ... names ) throws Exception { Class < ? > type = object . getClass ( ) ; Object value ; for ( String name : names ) { Field field = Beans . getKnownField ( type , name ) ; if ( ! Modifier . isStatic ( field . getModifiers ( ) ) && ! Modifier . isTransient ( field . getModifiers ( ) ) && ( value = field . get ( object ) ) != null ) { put ( field . getName ( ) , value . toString ( ) ) ; } } return this ; }
Fills the data binder with a subset of non - static non - transient fields of an Object excluding null values .
11,566
public DataBinder load ( String [ ] args , int offset ) { for ( int i = offset ; i < args . length ; ++ i ) { int equal = args [ i ] . indexOf ( '=' ) ; if ( equal > 0 ) { put ( args [ i ] . substring ( 0 , equal ) , args [ i ] . substring ( equal + 1 ) ) ; } else { throw new RuntimeException ( "***InvalidParameter{" + args [ i ] + '}' ) ; } } return this ; }
Loads parameters from an array of strings each in the form of name = value .
11,567
public DataBinder load ( String filename ) throws IOException { Properties props = new Properties ( ) ; Reader reader = new FileReader ( filename ) ; props . load ( reader ) ; reader . close ( ) ; return load ( props ) ; }
Loads parameters from a property file .
11,568
public DataBinder load ( Properties props ) { Enumeration < ? > enumeration = props . propertyNames ( ) ; while ( enumeration . hasMoreElements ( ) ) { String key = ( String ) enumeration . nextElement ( ) ; put ( key , props . getProperty ( key ) ) ; } return this ; }
Loads parameters from a Properties object .
11,569
public int estimateMaximumBytes ( ) { int count = this . size ( ) ; for ( String key : _rsets . keySet ( ) ) { CachedResultSet crs = _rsets . get ( key ) ; if ( crs . rows != null ) { count += crs . columns . length * crs . rows . size ( ) ; } } return count * 64 ; }
Provides a very rough estimate of how big a JSON representative of this binder might be .
11,570
public String toJSON ( ) { JSONBuilder jb = new JSONBuilder ( estimateMaximumBytes ( ) ) . append ( '{' ) ; appendParams ( jb ) . append ( ',' ) ; appendTables ( jb ) ; jb . append ( '}' ) ; return jb . toString ( ) ; }
Returns a JSON string representing the contents of this data binder excluding named objects .
11,571
private static long getDateForHour ( long dt , TimeZone tz , int hour , int dayoffset ) { Calendar c = getCalendar ( tz ) ; c . setTimeInMillis ( dt ) ; int dd = c . get ( Calendar . DAY_OF_MONTH ) ; int mm = c . get ( Calendar . MONTH ) ; int yy = c . get ( Calendar . YEAR ) ; c . set ( yy , mm , dd , hour , 0 , 0 ) ; c . set ( Calendar . MILLISECOND , 0 ) ; if ( dayoffset != 0 ) c . add ( Calendar . DAY_OF_MONTH , dayoffset ) ; return c . getTimeInMillis ( ) ; }
Returns the date for the given hour .
11,572
public static Calendar getCalendar ( TimeZone tz , Locale locale ) { if ( tz == null ) tz = getCurrentTimeZone ( ) ; if ( locale == null ) locale = getCurrentLocale ( ) ; return Calendar . getInstance ( tz , locale ) ; }
Returns a new calendar object using the given timezone and locale .
11,573
public static Locale getLocale ( String country ) { if ( country == null || country . length ( ) == 0 ) country = Locale . getDefault ( ) . getCountry ( ) ; List < Locale > locales = LocaleUtils . languagesByCountry ( country ) ; Locale locale = Locale . getDefault ( ) ; if ( locales . size ( ) > 0 ) locale = locales . get ( 0 ) ; return locale ; }
Returns the locale for the given country .
11,574
public static void setCalendarData ( Calendar calendar , Locale locale ) { int [ ] array = ( int [ ] ) localeData . get ( locale ) ; if ( array == null ) { Calendar c = Calendar . getInstance ( locale ) ; array = new int [ 2 ] ; array [ 0 ] = c . getFirstDayOfWeek ( ) ; array [ 1 ] = c . getMinimalDaysInFirstWeek ( ) ; localeData . putIfAbsent ( locale , array ) ; } calendar . setFirstDayOfWeek ( array [ 0 ] ) ; calendar . setMinimalDaysInFirstWeek ( array [ 1 ] ) ; }
Set the attributes of the given calendar from the given locale .
11,575
public static Date addDays ( long dt , int days ) { Calendar c = getCalendar ( ) ; if ( dt > 0L ) c . setTimeInMillis ( dt ) ; c . add ( Calendar . DATE , days ) ; return c . getTime ( ) ; }
Returns the given date adding the given number of days .
11,576
public static long convertToUtc ( long millis , String tz ) { long ret = millis ; if ( tz != null && tz . length ( ) > 0 ) { DateTime dt = new DateTime ( millis , DateTimeZone . forID ( tz ) ) ; ret = dt . withZoneRetainFields ( DateTimeZone . forID ( "UTC" ) ) . getMillis ( ) ; } return ret ; }
Returns the given date converted to UTC using the given timezone .
11,577
public static int useServer ( String settings , String [ ] args , Set < URI > sourcesToCompile , Set < URI > visibleSources , Map < URI , Set < String > > visibleClasses , Map < String , Set < URI > > packageArtifacts , Map < String , Set < String > > packageDependencies , Map < String , String > packagePubapis , SysInfo sysinfo , PrintStream out , PrintStream err ) { try { String id = Util . extractStringOption ( "id" , settings ) ; String portfile = Util . extractStringOption ( "portfile" , settings ) ; String logfile = Util . extractStringOption ( "logfile" , settings ) ; String stdouterrfile = Util . extractStringOption ( "stdouterrfile" , settings ) ; String background = Util . extractStringOption ( "background" , settings ) ; if ( background == null || ! background . equals ( "false" ) ) { background = "true" ; } String sjavac = Util . extractStringOption ( "sjavac" , settings ) ; int poolsize = Util . extractIntOption ( "poolsize" , settings ) ; int keepalive = Util . extractIntOption ( "keepalive" , settings ) ; if ( keepalive <= 0 ) { keepalive = 120 ; } if ( portfile == null ) { err . println ( "No portfile was specified!" ) ; return - 1 ; } if ( logfile == null ) { logfile = portfile + ".javaclog" ; } if ( stdouterrfile == null ) { stdouterrfile = portfile + ".stdouterr" ; } if ( sjavac == null ) { sjavac = "sjavac" ; } int attempts = 0 ; int rc = - 1 ; do { PortFile port_file = getPortFile ( portfile ) ; synchronized ( port_file ) { port_file . lock ( ) ; port_file . getValues ( ) ; port_file . unlock ( ) ; } if ( ! port_file . containsPortInfo ( ) ) { String cmd = fork ( sjavac , port_file . getFilename ( ) , logfile , poolsize , keepalive , err , stdouterrfile , background ) ; if ( background . equals ( "true" ) && ! port_file . waitForValidValues ( ) ) { printFailedAttempt ( cmd , stdouterrfile , err ) ; return - 1 ; } } rc = connectAndCompile ( port_file , id , args , sourcesToCompile , visibleSources , packageArtifacts , packageDependencies , packagePubapis , sysinfo , out , err ) ; if ( rc == ERROR_BUT_TRY_AGAIN ) { attempts ++ ; try { Thread . sleep ( WAIT_BETWEEN_CONNECT_ATTEMPTS ) ; } catch ( InterruptedException e ) { } } } while ( rc == ERROR_BUT_TRY_AGAIN && attempts < MAX_NUM_CONNECT_ATTEMPTS ) ; return rc ; } catch ( Exception e ) { e . printStackTrace ( err ) ; return - 1 ; } }
Dispatch a compilation request to a javac server .
11,578
private static String fork ( String sjavac , String portfile , String logfile , int poolsize , int keepalive , final PrintStream err , String stdouterrfile , String background ) throws IOException , ProblemException { if ( stdouterrfile != null && stdouterrfile . trim ( ) . equals ( "" ) ) { stdouterrfile = null ; } final String startserver = "--startserver:portfile=" + portfile + ",logfile=" + logfile + ",stdouterrfile=" + stdouterrfile + ",poolsize=" + poolsize + ",keepalive=" + keepalive ; if ( background . equals ( "true" ) ) { sjavac += "%20" + startserver ; sjavac = sjavac . replaceAll ( "%20" , " " ) ; sjavac = sjavac . replaceAll ( "%2C" , "," ) ; String [ ] cmd = { "/bin/sh" , "-c" , sjavac + " >> " + stdouterrfile + " 2>&1" } ; if ( ! ( new File ( "/bin/sh" ) ) . canExecute ( ) ) { ArrayList < String > wincmd = new ArrayList < String > ( ) ; wincmd . add ( "cmd" ) ; wincmd . add ( "/c" ) ; wincmd . add ( "start" ) ; wincmd . add ( "cmd" ) ; wincmd . add ( "/c" ) ; wincmd . add ( sjavac + " >> " + stdouterrfile + " 2>&1" ) ; cmd = wincmd . toArray ( new String [ wincmd . size ( ) ] ) ; } Process pp = null ; try { pp = Runtime . getRuntime ( ) . exec ( cmd ) ; } catch ( Exception e ) { e . printStackTrace ( err ) ; e . printStackTrace ( new PrintWriter ( stdouterrfile ) ) ; } StringBuilder rs = new StringBuilder ( ) ; for ( String s : cmd ) { rs . append ( s + " " ) ; } return rs . toString ( ) ; } Thread t = new Thread ( ) { public void run ( ) { try { JavacServer . startServer ( startserver , err ) ; } catch ( Throwable t ) { t . printStackTrace ( err ) ; } } } ; t . start ( ) ; return "" ; }
Fork a background process . Returns the command line used that can be printed if something failed .
11,579
public static SysInfo connectGetSysInfo ( String serverSettings , PrintStream out , PrintStream err ) { SysInfo sysinfo = new SysInfo ( - 1 , - 1 ) ; String id = Util . extractStringOption ( "id" , serverSettings ) ; String portfile = Util . extractStringOption ( "portfile" , serverSettings ) ; try { PortFile pf = getPortFile ( portfile ) ; useServer ( serverSettings , new String [ 0 ] , new HashSet < URI > ( ) , new HashSet < URI > ( ) , new HashMap < URI , Set < String > > ( ) , new HashMap < String , Set < URI > > ( ) , new HashMap < String , Set < String > > ( ) , new HashMap < String , String > ( ) , sysinfo , out , err ) ; } catch ( Exception e ) { e . printStackTrace ( err ) ; } return sysinfo ; }
Make a request to the server only to get the maximum possible heap size to use for compilations .
11,580
private void run ( PortFile portFile , PrintStream err , int keepalive ) { boolean fileDeleted = false ; long timeSinceLastCompile ; try { serverSocket . setSoTimeout ( CHECK_PORTFILE_INTERVAL * 1000 ) ; for ( ; ; ) { try { Socket s = serverSocket . accept ( ) ; CompilerThread ct = compilerPool . grabCompilerThread ( ) ; ct . setSocket ( s ) ; compilerPool . execute ( ct ) ; flushLog ( ) ; } catch ( java . net . SocketTimeoutException e ) { if ( compilerPool . numActiveRequests ( ) > 0 ) { continue ; } if ( fileDeleted ) { log ( "Quitting because of " + ( keepalive + CHECK_PORTFILE_INTERVAL ) + " seconds of inactivity!" ) ; break ; } if ( ! portFile . exists ( ) ) { log ( "Quitting because portfile was deleted!" ) ; flushLog ( ) ; break ; } if ( portFile . markedForStop ( ) ) { log ( "Quitting because a portfile.stop file was found!" ) ; portFile . delete ( ) ; flushLog ( ) ; break ; } if ( ! portFile . stillMyValues ( ) ) { log ( "Quitting because portfile is now owned by another javac server!" ) ; flushLog ( ) ; break ; } long diff = System . currentTimeMillis ( ) - compilerPool . lastRequestFinished ( ) ; if ( diff < keepalive * 1000 ) { continue ; } portFile . delete ( ) ; fileDeleted = true ; log ( "" + keepalive + " seconds of inactivity quitting in " + CHECK_PORTFILE_INTERVAL + " seconds!" ) ; flushLog ( ) ; } } } catch ( Exception e ) { e . printStackTrace ( err ) ; e . printStackTrace ( theLog ) ; flushLog ( ) ; } finally { compilerPool . shutdown ( ) ; } long realTime = System . currentTimeMillis ( ) - serverStart ; log ( "Shutting down." ) ; log ( "Total wall clock time " + realTime + "ms build time " + totalBuildTime + "ms" ) ; flushLog ( ) ; }
Run the server thread until it exits . Either because of inactivity or because the port file has been deleted by someone else or overtaken by some other javac server .
11,581
public < T extends Object > void writeValue ( T value ) throws IOException { writeValue ( value , ( Class < T > ) value . getClass ( ) ) ; }
Value can not be null
11,582
private void deserializeFromStream ( final InputStream in ) throws IOException { final byte [ ] dateTimeBytes = new byte [ 8 ] ; in . read ( dateTimeBytes , 0 , 8 ) ; eventDateTime = new DateTime ( ByteBuffer . wrap ( dateTimeBytes ) . getLong ( 0 ) ) ; final byte [ ] sizeGranularityInBytes = new byte [ 4 ] ; in . read ( sizeGranularityInBytes , 0 , 4 ) ; final byte [ ] granularityBytes = new byte [ ByteBuffer . wrap ( sizeGranularityInBytes ) . getInt ( 0 ) ] ; in . read ( granularityBytes , 0 , granularityBytes . length ) ; granularity = Granularity . valueOf ( new String ( granularityBytes , Charset . forName ( "UTF-8" ) ) ) ; thriftEnvelope = deserializer . deserialize ( null ) ; }
Given an InputStream extract the eventDateTime granularity and thriftEnvelope to build the ThriftEnvelopeEvent . This method expects the stream to be open and won t close it for you .
11,583
public void add ( Collection < ApplicationInstance > applicationInstances ) { for ( ApplicationInstance applicationInstance : applicationInstances ) this . applicationInstances . put ( applicationInstance . getId ( ) , applicationInstance ) ; }
Adds the application instance list to the application instances for the account .
11,584
public Object get ( ) { synchronized ( this ) { if ( freePool . isEmpty ( ) || usedPool . size ( ) >= capacity ) { try { wait ( 1000 ) ; } catch ( InterruptedException e ) { } if ( freePool . isEmpty ( ) ) add ( new SimpleDateFormat ( ) ) ; } Object o = freePool . get ( 0 ) ; freePool . remove ( o ) ; usedPool . add ( o ) ; return o ; } }
Retrieve a resource from the pool of free resources .
11,585
public SimpleDateFormat getFormat ( String format ) { SimpleDateFormat f = ( SimpleDateFormat ) get ( ) ; f . applyPattern ( format ) ; return f ; }
Retrieve a date format from the pool of free resources .
11,586
public void release ( Object o ) { synchronized ( this ) { usedPool . remove ( o ) ; freePool . add ( o ) ; notify ( ) ; } }
Release a resource and put it back in the pool of free resources .
11,587
public void execute ( ) throws MojoExecutionException { ClassLoader classloader ; try { classloader = createClassLoader ( ) ; } catch ( Exception e ) { throw new MojoExecutionException ( "could not create classloader from dependencies" , e ) ; } AbstractConfiguration [ ] configurations ; try { configurations = ConfigurationGenerator . execute ( generatedSourceDirectory , applicationDefinition , classloader , getSLF4JLogger ( ) ) ; } catch ( Exception e ) { throw new MojoExecutionException ( "could not generate the configurator" , e ) ; } getPluginContext ( ) . put ( GENERATED_CONFIGURATIONS_KEY , configurations ) ; project . addCompileSourceRoot ( generatedSourceDirectory . getPath ( ) ) ; }
Processes all dependencies first and then creates a new JVM to generate the configurator implementation with .
11,588
public String toShortString ( StringBuilder sb ) { sb . setLength ( 0 ) ; sb . append ( '[' ) ; sb . append ( left ) ; sb . append ( ',' ) ; sb . append ( top ) ; sb . append ( "][" ) ; sb . append ( right ) ; sb . append ( ',' ) ; sb . append ( bottom ) ; sb . append ( ']' ) ; return sb . toString ( ) ; }
Return a string representation of the rectangle in a compact form .
11,589
public String flattenToString ( ) { StringBuilder sb = new StringBuilder ( 32 ) ; sb . append ( left ) ; sb . append ( ' ' ) ; sb . append ( top ) ; sb . append ( ' ' ) ; sb . append ( right ) ; sb . append ( ' ' ) ; sb . append ( bottom ) ; return sb . toString ( ) ; }
Return a string representation of the rectangle in a well - defined format .
11,590
public void set ( Rect src ) { this . left = src . left ; this . top = src . top ; this . right = src . right ; this . bottom = src . bottom ; }
Copy the coordinates from src into this rectangle .
11,591
public void offset ( int dx , int dy ) { left += dx ; top += dy ; right += dx ; bottom += dy ; }
Offset the rectangle by adding dx to its left and right coordinates and adding dy to its top and bottom coordinates .
11,592
public boolean contains ( int left , int top , int right , int bottom ) { return this . left < this . right && this . top < this . bottom && this . left <= left && this . top <= top && this . right >= right && this . bottom >= bottom ; }
Returns true iff the 4 specified sides of a rectangle are inside or equal to this rectangle . i . e . is this rectangle a superset of the specified rectangle . An empty rectangle never contains another rectangle .
11,593
public boolean contains ( Rect r ) { return this . left < this . right && this . top < this . bottom && left <= r . left && top <= r . top && right >= r . right && bottom >= r . bottom ; }
Returns true iff the specified rectangle r is inside or equal to this rectangle . An empty rectangle never contains another rectangle .
11,594
public void union ( Rect r ) { union ( r . left , r . top , r . right , r . bottom ) ; }
Update this Rect to enclose itself and the specified rectangle . If the specified rectangle is empty nothing is done . If this rectangle is empty it is set to the specified rectangle .
11,595
public void scale ( float scale ) { if ( scale != 1.0f ) { left = ( int ) ( left * scale + 0.5f ) ; top = ( int ) ( top * scale + 0.5f ) ; right = ( int ) ( right * scale + 0.5f ) ; bottom = ( int ) ( bottom * scale + 0.5f ) ; } }
Scales up the rect by the given scale .
11,596
public void add ( Collection < Plugin > plugins ) { for ( Plugin plugin : plugins ) this . plugins . put ( plugin . getId ( ) , plugin ) ; }
Adds the plugin list to the plugins for the account .
11,597
public PluginComponentCache components ( long pluginId ) { PluginComponentCache cache = components . get ( pluginId ) ; if ( cache == null ) components . put ( pluginId , cache = new PluginComponentCache ( pluginId ) ) ; return cache ; }
Returns the cache of plugin components for the given plugin creating one if it doesn t exist .
11,598
public TypeConverter getTypeConverter ( ) throws RpcException { if ( contract == null ) { throw new IllegalStateException ( "contract cannot be null" ) ; } if ( type == null ) { throw new IllegalStateException ( "field type cannot be null" ) ; } TypeConverter tc = null ; if ( type . equals ( "string" ) ) tc = new StringTypeConverter ( isOptional ) ; else if ( type . equals ( "int" ) ) tc = new IntTypeConverter ( isOptional ) ; else if ( type . equals ( "float" ) ) tc = new FloatTypeConverter ( isOptional ) ; else if ( type . equals ( "bool" ) ) tc = new BoolTypeConverter ( isOptional ) ; else { Struct s = contract . getStructs ( ) . get ( type ) ; if ( s != null ) { tc = new StructTypeConverter ( s , isOptional ) ; } Enum e = contract . getEnums ( ) . get ( type ) ; if ( e != null ) { tc = new EnumTypeConverter ( e , isOptional ) ; } } if ( tc == null ) { throw RpcException . Error . INTERNAL . exc ( "Unknown type: " + type ) ; } else if ( isArray ) { return new ArrayTypeConverter ( tc , isOptional ) ; } else { return tc ; } }
Returns a new TypeConverter appropriate for the Field s type .
11,599
public String getJavaType ( boolean wrapArray ) { String t = "" ; if ( type . equals ( "string" ) ) { t = "String" ; } else if ( type . equals ( "float" ) ) { t = "Double" ; } else if ( type . equals ( "int" ) ) { t = "Long" ; } else if ( type . equals ( "bool" ) ) { t = "Boolean" ; } else { t = type ; } if ( wrapArray && isArray ) { return t + "[]" ; } else { return t ; } }
Returns the Java type this type maps to . Used by Idl2Java code generator .