idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
1,000
public Logger getLogger ( String loggerName ) { Logger logger ; logger = ( Logger ) cache . get ( loggerName ) ; if ( logger == null ) { try { logger = createLoggerInstance ( loggerName ) ; if ( getBootLogger ( ) . isDebugEnabled ( ) ) { getBootLogger ( ) . debug ( "Using logger class '" + ( getConfiguration ( ) != null ? getConfiguration ( ) . getLoggerClass ( ) : null ) + "' for " + loggerName ) ; } getBootLogger ( ) . debug ( "Initializing logger instance " + loggerName ) ; logger . configure ( conf ) ; } catch ( Throwable t ) { reassignBootLogger ( true ) ; logger = getBootLogger ( ) ; getBootLogger ( ) . error ( "[" + this . getClass ( ) . getName ( ) + "] Could not initialize logger " + ( conf != null ? conf . getLoggerClass ( ) : null ) , t ) ; } cache . put ( loggerName , logger ) ; reassignBootLogger ( false ) ; } return logger ; }
returns a Logger .
1,001
private Logger createLoggerInstance ( String loggerName ) throws Exception { Class loggerClass = getConfiguration ( ) . getLoggerClass ( ) ; Logger log = ( Logger ) ClassHelper . newInstance ( loggerClass , String . class , loggerName ) ; log . configure ( getConfiguration ( ) ) ; return log ; }
Creates a new Logger instance for the specified name .
1,002
private Field getFieldRecursive ( Class c , String name ) throws NoSuchFieldException { try { return c . getDeclaredField ( name ) ; } catch ( NoSuchFieldException e ) { if ( ( c == Object . class ) || ( c . getSuperclass ( ) == null ) || c . isInterface ( ) ) { throw e ; } else { return getFieldRecursive ( c . getSuperclass ( ) , name ) ; } } }
try to find a field in class c recurse through class hierarchy if necessary
1,003
protected String buildErrorSetMsg ( Object obj , Object value , Field aField ) { String eol = SystemUtils . LINE_SEPARATOR ; StringBuffer buf = new StringBuffer ( ) ; buf . append ( eol + "[try to set 'object value' in 'target object'" ) . append ( eol + "target obj class: " + ( obj != null ? obj . getClass ( ) . getName ( ) : null ) ) . append ( eol + "target field name: " + ( aField != null ? aField . getName ( ) : null ) ) . append ( eol + "target field type: " + ( aField != null ? aField . getType ( ) : null ) ) . append ( eol + "target field declared in: " + ( aField != null ? aField . getDeclaringClass ( ) . getName ( ) : null ) ) . append ( eol + "object value class: " + ( value != null ? value . getClass ( ) . getName ( ) : null ) ) . append ( eol + "object value: " + ( value != null ? value : null ) ) . append ( eol + "]" ) ; return buf . toString ( ) ; }
Build a String representation of given arguments .
1,004
protected PersistenceBrokerInternal createNewBrokerInstance ( PBKey key ) throws PBFactoryException { if ( key == null ) throw new PBFactoryException ( "Could not create new broker with PBkey argument 'null'" ) ; if ( MetadataManager . getInstance ( ) . connectionRepository ( ) . getDescriptor ( key ) == null ) { throw new PBFactoryException ( "Given PBKey " + key + " does not match in metadata configuration" ) ; } if ( log . isEnabledFor ( Logger . INFO ) ) { log . info ( "Create new PB instance for PBKey " + key + ", already created persistence broker instances: " + instanceCount ) ; ++ this . instanceCount ; } PersistenceBrokerInternal instance = null ; Class [ ] types = { PBKey . class , PersistenceBrokerFactoryIF . class } ; Object [ ] args = { key , this } ; try { instance = ( PersistenceBrokerInternal ) ClassHelper . newInstance ( implementationClass , types , args ) ; OjbConfigurator . getInstance ( ) . configure ( instance ) ; instance = ( PersistenceBrokerInternal ) InterceptorFactory . getInstance ( ) . createInterceptorFor ( instance ) ; } catch ( Exception e ) { log . error ( "Creation of a new PB instance failed" , e ) ; throw new PBFactoryException ( "Creation of a new PB instance failed" , e ) ; } return instance ; }
For internal use! This method creates real new PB instances
1,005
public void actionPerformed ( java . awt . event . ActionEvent e ) { System . out . println ( "Action Command: " + e . getActionCommand ( ) ) ; System . out . println ( "Action Params : " + e . paramString ( ) ) ; System . out . println ( "Action Source : " + e . getSource ( ) ) ; System . out . println ( "Action SrcCls : " + e . getSource ( ) . getClass ( ) . getName ( ) ) ; org . apache . ojb . broker . metadata . ClassDescriptor cld = new org . apache . ojb . broker . metadata . ClassDescriptor ( rootNode . getRepository ( ) ) ; cld . setTableName ( "New Table" ) ; rootNode . addClassDescriptor ( cld ) ; }
Invoked when an action occurs .
1,006
public ProxyAuthenticationMethod getMethod ( ) { switch ( authenticationMethod ) { case BASIC : return ProxyAuthenticationMethod . BASIC ; case DIGEST : return ProxyAuthenticationMethod . DIGEST ; case URL : return ProxyAuthenticationMethod . URL ; default : return null ; } }
Get the authentication method to use .
1,007
public static < T > MetaTinyType < T > metaFor ( Class < ? > candidate ) { for ( MetaTinyType meta : metas ) { if ( meta . isMetaOf ( candidate ) ) { return meta ; } } throw new IllegalArgumentException ( String . format ( "not a tinytype: %s" , candidate == null ? "null" : candidate . getCanonicalName ( ) ) ) ; }
Provides a type - specific Meta class for the given TinyType .
1,008
public NamedStyleInfo getNamedStyleInfo ( String name ) { for ( NamedStyleInfo info : namedStyleInfos ) { if ( info . getName ( ) . equals ( name ) ) { return info ; } } return null ; }
Get layer style by name .
1,009
public static void scanClassPathForFormattingAnnotations ( ) { ExecutorService executorService = Executors . newFixedThreadPool ( Runtime . getRuntime ( ) . availableProcessors ( ) * 2 ) ; Reflections reflections = new Reflections ( "com.nds" , "com.cisco" ) ; Set < Class < ? > > annotated = reflections . getTypesAnnotatedWith ( DefaultFormat . class ) ; for ( Class < ? > markerClass : annotated ) { if ( FoundationLoggingMarker . class . isAssignableFrom ( markerClass ) ) { final Class < ? extends FoundationLoggingMarker > clazz = ( Class < ? extends FoundationLoggingMarker > ) markerClass ; executorService . execute ( new Runnable ( ) { public void run ( ) { if ( markersMap . get ( clazz ) == null ) { try { generateAndUpdateFormatterInMap ( clazz ) ; } catch ( Exception e ) { LOGGER . trace ( "problem generating formatter class from static scan method. error is: " + e . toString ( ) ) ; } } } } ) ; } else { if ( LOGGER == null ) { LOGGER = LoggerFactory . getLogger ( AbstractFoundationLoggingMarker . class ) ; } LOGGER . error ( "Formatter annotations should only appear on foundationLoggingMarker implementations" ) ; } } try { TimeUnit . SECONDS . sleep ( 30 ) ; } catch ( InterruptedException e ) { LOGGER . trace ( e . toString ( ) , e ) ; } executorService . shutdown ( ) ; }
Scan all the class path and look for all classes that have the Format Annotations .
1,010
public void addAppenderEvent ( final Category cat , final Appender appender ) { updateDefaultLayout ( appender ) ; if ( appender instanceof FoundationFileRollingAppender ) { final FoundationFileRollingAppender timeSizeRollingAppender = ( FoundationFileRollingAppender ) appender ; updateArchivingSupport ( timeSizeRollingAppender ) ; timeSizeRollingAppender . setFileRollEventListener ( FoundationRollEventListener . class . getName ( ) ) ; boolean rollOnStartup = true ; if ( FoundationLogger . log4jConfigProps != null && FoundationLogger . log4jConfigProps . containsKey ( FoundationLoggerConstants . Foundation_ROLL_ON_STARTUP . toString ( ) ) ) { rollOnStartup = Boolean . valueOf ( FoundationLogger . log4jConfigProps . getProperty ( FoundationLoggerConstants . Foundation_ROLL_ON_STARTUP . toString ( ) ) ) ; } timeSizeRollingAppender . setRollOnStartup ( rollOnStartup ) ; timeSizeRollingAppender . activateOptions ( ) ; } else if ( ! ( appender instanceof FoundationFileRollingAppender ) && ( appender instanceof TimeAndSizeRollingAppender ) ) { final TimeAndSizeRollingAppender timeSizeRollingAppender = ( TimeAndSizeRollingAppender ) appender ; updateDefaultTimeAndSizeRollingAppender ( timeSizeRollingAppender ) ; updateArchivingSupport ( timeSizeRollingAppender ) ; timeSizeRollingAppender . setFileRollEventListener ( FoundationRollEventListener . class . getName ( ) ) ; boolean rollOnStartup = true ; if ( FoundationLogger . log4jConfigProps != null && FoundationLogger . log4jConfigProps . containsKey ( FoundationLoggerConstants . Foundation_ROLL_ON_STARTUP . toString ( ) ) ) { rollOnStartup = Boolean . valueOf ( FoundationLogger . log4jConfigProps . getProperty ( FoundationLoggerConstants . Foundation_ROLL_ON_STARTUP . toString ( ) ) ) ; } timeSizeRollingAppender . setRollOnStartup ( rollOnStartup ) ; timeSizeRollingAppender . activateOptions ( ) ; } if ( ! ( appender instanceof org . apache . log4j . AsyncAppender ) ) initiateAsyncSupport ( appender ) ; }
In this method perform the actual override in runtime .
1,011
private void updateDefaultTimeAndSizeRollingAppender ( final FoundationFileRollingAppender appender ) { if ( appender . getDatePattern ( ) . trim ( ) . length ( ) == 0 ) { appender . setDatePattern ( FoundationLoggerConstants . DEFAULT_DATE_PATTERN . toString ( ) ) ; } String maxFileSizeKey = "log4j.appender." + appender . getName ( ) + ".MaxFileSize" ; appender . setMaxFileSize ( FoundationLogger . log4jConfigProps . getProperty ( maxFileSizeKey , FoundationLoggerConstants . Foundation_MAX_FILE_SIZE . toString ( ) ) ) ; String maxRollCountKey = "log4j.appender." + appender . getName ( ) + ".MaxRollFileCount" ; appender . setMaxRollFileCount ( Integer . parseInt ( FoundationLogger . log4jConfigProps . getProperty ( maxRollCountKey , "100" ) ) ) ; }
Set default values for the TimeAndSizeRollingAppender appender
1,012
final void dispatchToAppender ( final String message ) { final FoundationFileRollingAppender appender = this . getSource ( ) ; if ( appender != null ) { appender . append ( new FileRollEvent ( this , message ) ) ; } }
Convenience method dispatches this object to the source appender which will result in the custom message being appended to the new file .
1,013
final void dispatchToAppender ( final LoggingEvent customLoggingEvent ) { final FoundationFileRollingAppender appender = this . getSource ( ) ; if ( appender != null ) { appender . append ( new FileRollEvent ( customLoggingEvent , this ) ) ; } }
Convenience method dispatches the specified event to the source appender which will result in the custom event data being appended to the new file .
1,014
public String getStatement ( ) { if ( sql == null ) { StringBuffer stmt = new StringBuffer ( 128 ) ; ClassDescriptor cld = getClassDescriptor ( ) ; FieldDescriptor [ ] fieldDescriptors = cld . getPkFields ( ) ; if ( fieldDescriptors == null || fieldDescriptors . length == 0 ) { throw new OJBRuntimeException ( "No PK fields defined in metadata for " + cld . getClassNameOfObject ( ) ) ; } FieldDescriptor field = fieldDescriptors [ 0 ] ; stmt . append ( SELECT ) ; stmt . append ( field . getColumnName ( ) ) ; stmt . append ( FROM ) ; stmt . append ( cld . getFullTableName ( ) ) ; appendWhereClause ( cld , false , stmt ) ; sql = stmt . toString ( ) ; } return sql ; }
Return SELECT clause for object existence call
1,015
public static Comparator getComparator ( ) { return new Comparator ( ) { public int compare ( Object o1 , Object o2 ) { FieldDescriptor fmd1 = ( FieldDescriptor ) o1 ; FieldDescriptor fmd2 = ( FieldDescriptor ) o2 ; if ( fmd1 . getColNo ( ) < fmd2 . getColNo ( ) ) { return - 1 ; } else if ( fmd1 . getColNo ( ) > fmd2 . getColNo ( ) ) { return 1 ; } else { return 0 ; } } } ; }
returns a comparator that allows to sort a Vector of FieldMappingDecriptors according to their m_Order entries .
1,016
public void setFieldConversionClassName ( String fieldConversionClassName ) { try { this . fieldConversion = ( FieldConversion ) ClassHelper . newInstance ( fieldConversionClassName ) ; } catch ( Exception e ) { throw new MetadataException ( "Could not instantiate FieldConversion class using default constructor" , e ) ; } }
Sets the fieldConversion .
1,017
public void setConnection ( JdbcConnectionDescriptor jcd ) throws PlatformException { _jcd = jcd ; String targetDatabase = ( String ) _dbmsToTorqueDb . get ( _jcd . getDbms ( ) . toLowerCase ( ) ) ; if ( targetDatabase == null ) { throw new PlatformException ( "Database " + _jcd . getDbms ( ) + " is not supported by torque" ) ; } if ( ! targetDatabase . equals ( _targetDatabase ) ) { _targetDatabase = targetDatabase ; _creationScript = null ; _initScripts . clear ( ) ; } }
Sets the jdbc connection to use .
1,018
private String writeSchemata ( File dir ) throws IOException { writeCompressedTexts ( dir , _torqueSchemata ) ; StringBuffer includes = new StringBuffer ( ) ; for ( Iterator it = _torqueSchemata . keySet ( ) . iterator ( ) ; it . hasNext ( ) ; ) { includes . append ( ( String ) it . next ( ) ) ; if ( it . hasNext ( ) ) { includes . append ( "," ) ; } } return includes . toString ( ) ; }
Writes the torque schemata to files in the given directory and returns a comma - separated list of the filenames .
1,019
public void createDB ( ) throws PlatformException { if ( _creationScript == null ) { createCreationScript ( ) ; } Project project = new Project ( ) ; TorqueDataModelTask modelTask = new TorqueDataModelTask ( ) ; File tmpDir = null ; File scriptFile = null ; try { tmpDir = new File ( getWorkDir ( ) , "schemas" ) ; tmpDir . mkdir ( ) ; scriptFile = new File ( tmpDir , CREATION_SCRIPT_NAME ) ; writeCompressedText ( scriptFile , _creationScript ) ; project . setBasedir ( tmpDir . getAbsolutePath ( ) ) ; SQLExec sqlTask = new SQLExec ( ) ; SQLExec . OnError onError = new SQLExec . OnError ( ) ; onError . setValue ( "continue" ) ; sqlTask . setProject ( project ) ; sqlTask . setAutocommit ( true ) ; sqlTask . setDriver ( _jcd . getDriver ( ) ) ; sqlTask . setOnerror ( onError ) ; sqlTask . setUserid ( _jcd . getUserName ( ) ) ; sqlTask . setPassword ( _jcd . getPassWord ( ) == null ? "" : _jcd . getPassWord ( ) ) ; sqlTask . setUrl ( getDBCreationUrl ( ) ) ; sqlTask . setSrc ( scriptFile ) ; sqlTask . execute ( ) ; deleteDir ( tmpDir ) ; } catch ( Exception ex ) { if ( ( tmpDir != null ) && tmpDir . exists ( ) ) { try { scriptFile . delete ( ) ; } catch ( NullPointerException e ) { LoggerFactory . getLogger ( this . getClass ( ) ) . error ( "NPE While deleting scriptFile [" + scriptFile . getName ( ) + "]" , e ) ; } } throw new PlatformException ( ex ) ; } }
Creates the database .
1,020
public void initDB ( ) throws PlatformException { if ( _initScripts . isEmpty ( ) ) { createInitScripts ( ) ; } Project project = new Project ( ) ; TorqueSQLTask sqlTask = new TorqueSQLTask ( ) ; File outputDir = null ; try { outputDir = new File ( getWorkDir ( ) , "sql" ) ; outputDir . mkdir ( ) ; writeCompressedTexts ( outputDir , _initScripts ) ; project . setBasedir ( outputDir . getAbsolutePath ( ) ) ; TorqueSQLExec sqlExec = new TorqueSQLExec ( ) ; TorqueSQLExec . OnError onError = new TorqueSQLExec . OnError ( ) ; sqlExec . setProject ( project ) ; onError . setValue ( "continue" ) ; sqlExec . setAutocommit ( true ) ; sqlExec . setDriver ( _jcd . getDriver ( ) ) ; sqlExec . setOnerror ( onError ) ; sqlExec . setUserid ( _jcd . getUserName ( ) ) ; sqlExec . setPassword ( _jcd . getPassWord ( ) == null ? "" : _jcd . getPassWord ( ) ) ; sqlExec . setUrl ( getDBManipulationUrl ( ) ) ; sqlExec . setSrcDir ( outputDir . getAbsolutePath ( ) ) ; sqlExec . setSqlDbMap ( SQL_DB_MAP_NAME ) ; sqlExec . execute ( ) ; deleteDir ( outputDir ) ; } catch ( Exception ex ) { if ( outputDir != null ) { deleteDir ( outputDir ) ; } throw new PlatformException ( ex ) ; } }
Creates the tables according to the schema files .
1,021
protected String getDBManipulationUrl ( ) { JdbcConnectionDescriptor jcd = getConnection ( ) ; return jcd . getProtocol ( ) + ":" + jcd . getSubProtocol ( ) + ":" + jcd . getDbAlias ( ) ; }
Template - and - Hook method for generating the url required by the jdbc driver to allow for modifying an existing database .
1,022
private byte [ ] readStreamCompressed ( InputStream stream ) throws IOException { ByteArrayOutputStream bao = new ByteArrayOutputStream ( ) ; GZIPOutputStream gos = new GZIPOutputStream ( bao ) ; OutputStreamWriter output = new OutputStreamWriter ( gos ) ; BufferedReader input = new BufferedReader ( new InputStreamReader ( stream ) ) ; String line ; while ( ( line = input . readLine ( ) ) != null ) { output . write ( line ) ; output . write ( '\n' ) ; } input . close ( ) ; stream . close ( ) ; output . close ( ) ; gos . close ( ) ; bao . close ( ) ; return bao . toByteArray ( ) ; }
Reads the given text stream and compressed its content .
1,023
private void readTextsCompressed ( File dir , HashMap results ) throws IOException { if ( dir . exists ( ) && dir . isDirectory ( ) ) { File [ ] files = dir . listFiles ( ) ; for ( int idx = 0 ; idx < files . length ; idx ++ ) { if ( files [ idx ] . isDirectory ( ) ) { continue ; } results . put ( files [ idx ] . getName ( ) , readTextCompressed ( files [ idx ] ) ) ; } } }
Reads the text files in the given directory and puts their content in the given map after compressing it . Note that this method does not traverse recursivly into sub - directories .
1,024
private void writeCompressedText ( File file , byte [ ] compressedContent ) throws IOException { ByteArrayInputStream bais = new ByteArrayInputStream ( compressedContent ) ; GZIPInputStream gis = new GZIPInputStream ( bais ) ; BufferedReader input = new BufferedReader ( new InputStreamReader ( gis ) ) ; BufferedWriter output = new BufferedWriter ( new FileWriter ( file ) ) ; String line ; while ( ( line = input . readLine ( ) ) != null ) { output . write ( line ) ; output . write ( '\n' ) ; } input . close ( ) ; gis . close ( ) ; bais . close ( ) ; output . close ( ) ; }
Uncompresses the given textual content and writes it to the given file .
1,025
private void writeCompressedTexts ( File dir , HashMap contents ) throws IOException { String filename ; for ( Iterator nameIt = contents . keySet ( ) . iterator ( ) ; nameIt . hasNext ( ) ; ) { filename = ( String ) nameIt . next ( ) ; writeCompressedText ( new File ( dir , filename ) , ( byte [ ] ) contents . get ( filename ) ) ; } }
Uncompresses the textual contents in the given map and and writes them to the files denoted by the keys of the map .
1,026
public void setWorkDir ( String dir ) throws IOException { File workDir = new File ( dir ) ; if ( ! workDir . exists ( ) || ! workDir . canWrite ( ) || ! workDir . canRead ( ) ) { throw new IOException ( "Cannot access directory " + dir ) ; } _workDir = workDir ; }
Sets the working directory .
1,027
private File getWorkDir ( ) throws IOException { if ( _workDir == null ) { File dummy = File . createTempFile ( "dummy" , ".log" ) ; String workDir = dummy . getPath ( ) . substring ( 0 , dummy . getPath ( ) . lastIndexOf ( File . separatorChar ) ) ; if ( ( workDir == null ) || ( workDir . length ( ) == 0 ) ) { workDir = "." ; } dummy . delete ( ) ; _workDir = new File ( workDir ) ; } return _workDir ; }
Returns the temporary directory used by java .
1,028
private void deleteDir ( File dir ) { if ( dir . exists ( ) && dir . isDirectory ( ) ) { File [ ] files = dir . listFiles ( ) ; for ( int idx = 0 ; idx < files . length ; idx ++ ) { if ( ! files [ idx ] . exists ( ) ) { continue ; } if ( files [ idx ] . isDirectory ( ) ) { deleteDir ( files [ idx ] ) ; } else { files [ idx ] . delete ( ) ; } } dir . delete ( ) ; } }
Little helper function that recursivly deletes a directory .
1,029
@ Produces ( MediaType . APPLICATION_JSON ) @ Path ( "/graph/{name}/{version}" ) public Response getModuleGraph ( @ PathParam ( "name" ) final String moduleName , @ PathParam ( "version" ) final String moduleVersion , final UriInfo uriInfo ) { LOG . info ( "Dependency Checker got a get module graph export request." ) ; if ( moduleName == null || moduleVersion == null ) { return Response . serverError ( ) . status ( HttpStatus . NOT_ACCEPTABLE_406 ) . build ( ) ; } final FiltersHolder filters = new FiltersHolder ( ) ; filters . init ( uriInfo . getQueryParameters ( ) ) ; final String moduleId = DbModule . generateID ( moduleName , moduleVersion ) ; final AbstractGraph moduleGraph = getGraphsHandler ( filters ) . getModuleGraph ( moduleId ) ; return Response . ok ( moduleGraph ) . build ( ) ; }
Perform a module dependency graph of the target and return the graph as a JSON
1,030
void update ( Object feature ) throws LayerException { SimpleFeatureSource source = getFeatureSource ( ) ; if ( source instanceof SimpleFeatureStore ) { SimpleFeatureStore store = ( SimpleFeatureStore ) source ; String featureId = getFeatureModel ( ) . getId ( feature ) ; Filter filter = filterService . createFidFilter ( new String [ ] { featureId } ) ; transactionSynchronization . synchTransaction ( store ) ; List < Name > names = new ArrayList < Name > ( ) ; Map < String , Attribute > attrMap = getFeatureModel ( ) . getAttributes ( feature ) ; List < Object > values = new ArrayList < Object > ( ) ; for ( Map . Entry < String , Attribute > entry : attrMap . entrySet ( ) ) { String name = entry . getKey ( ) ; names . add ( store . getSchema ( ) . getDescriptor ( name ) . getName ( ) ) ; values . add ( entry . getValue ( ) . getValue ( ) ) ; } try { store . modifyFeatures ( names . toArray ( new Name [ names . size ( ) ] ) , values . toArray ( ) , filter ) ; store . modifyFeatures ( store . getSchema ( ) . getGeometryDescriptor ( ) . getName ( ) , getFeatureModel ( ) . getGeometry ( feature ) , filter ) ; log . debug ( "Updated feature {} in {}" , featureId , getFeatureSourceName ( ) ) ; } catch ( IOException ioe ) { featureModelUsable = false ; throw new LayerException ( ioe , ExceptionCode . LAYER_MODEL_IO_EXCEPTION ) ; } } else { log . error ( "Don't know how to create or update " + getFeatureSourceName ( ) + ", class " + source . getClass ( ) . getName ( ) + " does not implement SimpleFeatureStore" ) ; throw new LayerException ( ExceptionCode . CREATE_OR_UPDATE_NOT_IMPLEMENTED , getFeatureSourceName ( ) , source . getClass ( ) . getName ( ) ) ; } }
Update an existing feature . Made package private for testing purposes .
1,031
public void format ( final StringBuffer sbuf , final LoggingEvent event ) { for ( int i = 0 ; i < patternConverters . length ; i ++ ) { final int startField = sbuf . length ( ) ; patternConverters [ i ] . format ( event , sbuf ) ; patternFields [ i ] . format ( startField , sbuf ) ; } }
Format event to string buffer .
1,032
private Database readSingleSchemaFile ( DatabaseIO reader , File schemaFile ) { Database model = null ; if ( ! schemaFile . isFile ( ) ) { log ( "Path " + schemaFile . getAbsolutePath ( ) + " does not denote a schema file" , Project . MSG_ERR ) ; } else if ( ! schemaFile . canRead ( ) ) { log ( "Could not read schema file " + schemaFile . getAbsolutePath ( ) , Project . MSG_ERR ) ; } else { try { model = reader . read ( schemaFile ) ; log ( "Read schema file " + schemaFile . getAbsolutePath ( ) , Project . MSG_INFO ) ; } catch ( Exception ex ) { throw new BuildException ( "Could not read schema file " + schemaFile . getAbsolutePath ( ) + ": " + ex . getLocalizedMessage ( ) , ex ) ; } } return model ; }
Reads a single schema file .
1,033
private MetadataManager initOJB ( ) { try { if ( _ojbPropertiesFile == null ) { _ojbPropertiesFile = new File ( "OJB.properties" ) ; if ( ! _ojbPropertiesFile . exists ( ) ) { throw new BuildException ( "Could not find OJB.properties, please specify it via the ojbpropertiesfile attribute" ) ; } } else { if ( ! _ojbPropertiesFile . exists ( ) ) { throw new BuildException ( "Could not load the specified OJB properties file " + _ojbPropertiesFile ) ; } log ( "Using properties file " + _ojbPropertiesFile . getAbsolutePath ( ) , Project . MSG_INFO ) ; System . setProperty ( "OJB.properties" , _ojbPropertiesFile . getAbsolutePath ( ) ) ; } MetadataManager metadataManager = MetadataManager . getInstance ( ) ; RepositoryPersistor persistor = new RepositoryPersistor ( ) ; if ( _repositoryFile != null ) { if ( ! _repositoryFile . exists ( ) ) { throw new BuildException ( "Could not load the specified repository file " + _repositoryFile ) ; } log ( "Loading repository file " + _repositoryFile . getAbsolutePath ( ) , Project . MSG_INFO ) ; metadataManager . mergeConnectionRepository ( persistor . readConnectionRepository ( _repositoryFile . getAbsolutePath ( ) ) ) ; metadataManager . mergeDescriptorRepository ( persistor . readDescriptorRepository ( _repositoryFile . getAbsolutePath ( ) ) ) ; } else if ( metadataManager . connectionRepository ( ) . getAllDescriptor ( ) . isEmpty ( ) && metadataManager . getGlobalRepository ( ) . getDescriptorTable ( ) . isEmpty ( ) ) { Properties props = new Properties ( ) ; props . load ( new FileInputStream ( _ojbPropertiesFile ) ) ; String repositoryPath = props . getProperty ( "repositoryFile" , "repository.xml" ) ; File repositoryFile = new File ( repositoryPath ) ; if ( ! repositoryFile . exists ( ) ) { repositoryFile = new File ( _ojbPropertiesFile . getParentFile ( ) , repositoryPath ) ; } metadataManager . mergeConnectionRepository ( persistor . readConnectionRepository ( repositoryFile . getAbsolutePath ( ) ) ) ; metadataManager . mergeDescriptorRepository ( persistor . readDescriptorRepository ( repositoryFile . getAbsolutePath ( ) ) ) ; } if ( metadataManager . getDefaultPBKey ( ) == null ) { for ( Iterator it = metadataManager . connectionRepository ( ) . getAllDescriptor ( ) . iterator ( ) ; it . hasNext ( ) ; ) { JdbcConnectionDescriptor descriptor = ( JdbcConnectionDescriptor ) it . next ( ) ; if ( descriptor . isDefaultConnection ( ) ) { metadataManager . setDefaultPBKey ( new PBKey ( descriptor . getJcdAlias ( ) , descriptor . getUserName ( ) , descriptor . getPassWord ( ) ) ) ; break ; } } } return metadataManager ; } catch ( Exception ex ) { if ( ex instanceof BuildException ) { throw ( BuildException ) ex ; } else { throw new BuildException ( ex ) ; } } }
Initializes OJB for the purposes of this task .
1,034
public String putDocument ( Document document ) { String key = UUID . randomUUID ( ) . toString ( ) ; documentMap . put ( key , document ) ; return key ; }
Puts a new document in the service . The generate key is globally unique .
1,035
public Document removeDocument ( String key ) throws PrintingException { if ( documentMap . containsKey ( key ) ) { return documentMap . remove ( key ) ; } else { throw new PrintingException ( PrintingException . DOCUMENT_NOT_FOUND , key ) ; } }
Gets a document from the service .
1,036
private static Query buildQuery ( ClassDescriptor cld ) { FieldDescriptor [ ] pkFields = cld . getPkFields ( ) ; Criteria crit = new Criteria ( ) ; for ( int i = 0 ; i < pkFields . length ; i ++ ) { crit . addEqualTo ( pkFields [ i ] . getAttributeName ( ) , null ) ; } return new QueryByCriteria ( cld . getClassOfObject ( ) , crit ) ; }
Build a Pk - Query base on the ClassDescriptor .
1,037
public String getMessage ( Locale locale ) { if ( getCause ( ) != null ) { String message = getShortMessage ( locale ) + ", " + translate ( "ROOT_CAUSE" , locale ) + " " ; if ( getCause ( ) instanceof GeomajasException ) { return message + ( ( GeomajasException ) getCause ( ) ) . getMessage ( locale ) ; } return message + getCause ( ) . getMessage ( ) ; } else { return getShortMessage ( locale ) ; } }
Get the exception message using the requested locale .
1,038
public String getShortMessage ( Locale locale ) { String message ; message = translate ( Integer . toString ( exceptionCode ) , locale ) ; if ( message != null && msgParameters != null && msgParameters . length > 0 ) { for ( int i = 0 ; i < msgParameters . length ; i ++ ) { boolean isIncluded = false ; String needTranslationParam = "$${" + i + "}" ; if ( message . contains ( needTranslationParam ) ) { String translation = translate ( msgParameters [ i ] , locale ) ; if ( null == translation && null != msgParameters [ i ] ) { translation = msgParameters [ i ] . toString ( ) ; } if ( null == translation ) { translation = "[null]" ; } message = message . replace ( needTranslationParam , translation ) ; isIncluded = true ; } String verbatimParam = "${" + i + "}" ; String rs = null == msgParameters [ i ] ? "[null]" : msgParameters [ i ] . toString ( ) ; if ( message . contains ( verbatimParam ) ) { message = message . replace ( verbatimParam , rs ) ; isIncluded = true ; } if ( ! isIncluded ) { message = message + " (" + rs + ")" ; } } } return message ; }
Get the short exception message using the requested locale . This does not include the cause exception message .
1,039
public PlanarImage toDirectColorModel ( RenderedImage img ) { BufferedImage dest = new BufferedImage ( img . getWidth ( ) , img . getHeight ( ) , BufferedImage . TYPE_4BYTE_ABGR ) ; BufferedImage source = new BufferedImage ( img . getColorModel ( ) , ( WritableRaster ) img . getData ( ) , img . getColorModel ( ) . isAlphaPremultiplied ( ) , null ) ; ColorConvertOp op = new ColorConvertOp ( null ) ; op . filter ( source , dest ) ; return PlanarImage . wrapRenderedImage ( dest ) ; }
Converts an image to a RGBA direct color model using a workaround via buffered image directly calling the ColorConvert operation fails for unknown reasons ?!
1,040
public ManagedConnection createManagedConnection ( Subject subject , ConnectionRequestInfo info ) { Util . log ( "In OTMJCAManagedConnectionFactory.createManagedConnection" ) ; try { Kit kit = getKit ( ) ; PBKey key = ( ( OTMConnectionRequestInfo ) info ) . getPbKey ( ) ; OTMConnection connection = kit . acquireConnection ( key ) ; return new OTMJCAManagedConnection ( this , connection , key ) ; } catch ( ResourceException e ) { throw new OTMConnectionRuntimeException ( e . getMessage ( ) ) ; } }
return a new managed connection . This connection is wrapped around the real connection and delegates to it to get work done .
1,041
public void render ( OutputStream outputStream , Format format , int dpi ) throws PrintingException { try { if ( baos == null ) { prepare ( ) ; } writeDocument ( outputStream , format , dpi ) ; } catch ( Exception e ) { throw new PrintingException ( e , PrintingException . DOCUMENT_RENDER_PROBLEM ) ; } }
Renders the document to the specified output stream .
1,042
private void prepare ( ) throws IOException , DocumentException , PrintingException { if ( baos == null ) { baos = new ByteArrayOutputStream ( ) ; } baos . reset ( ) ; boolean resize = false ; if ( page . getConstraint ( ) . getWidth ( ) == 0 || page . getConstraint ( ) . getHeight ( ) == 0 ) { resize = true ; } Document document = new Document ( page . getBounds ( ) , 0 , 0 , 0 , 0 ) ; PdfWriter writer ; writer = PdfWriter . getInstance ( document , baos ) ; writer . setRgbTransparencyBlending ( true ) ; document . open ( ) ; PdfContext context = new PdfContext ( writer ) ; context . initSize ( page . getBounds ( ) ) ; page . calculateSize ( context ) ; if ( resize ) { int width = ( int ) Math . ceil ( page . getBounds ( ) . getWidth ( ) ) ; int height = ( int ) Math . ceil ( page . getBounds ( ) . getHeight ( ) ) ; page . getConstraint ( ) . setWidth ( width ) ; page . getConstraint ( ) . setHeight ( height ) ; document = new Document ( new Rectangle ( width , height ) , 0 , 0 , 0 , 0 ) ; writer = PdfWriter . getInstance ( document , baos ) ; writer . setRgbTransparencyBlending ( true ) ; document . open ( ) ; baos . reset ( ) ; context = new PdfContext ( writer ) ; context . initSize ( page . getBounds ( ) ) ; } document . addTitle ( "Geomajas" ) ; page . layout ( context ) ; page . render ( context ) ; document . add ( context . getImage ( ) ) ; document . close ( ) ; }
Prepare the document before rendering .
1,043
private static synchronized boolean isLog4JConfigured ( ) { if ( ! log4jConfigured ) { Enumeration en = org . apache . log4j . Logger . getRootLogger ( ) . getAllAppenders ( ) ; if ( ! ( en instanceof org . apache . log4j . helpers . NullEnumeration ) ) { log4jConfigured = true ; } else { Enumeration cats = LogManager . getCurrentLoggers ( ) ; while ( cats . hasMoreElements ( ) ) { org . apache . log4j . Logger c = ( org . apache . log4j . Logger ) cats . nextElement ( ) ; if ( ! ( c . getAllAppenders ( ) instanceof org . apache . log4j . helpers . NullEnumeration ) ) { log4jConfigured = true ; } } } if ( log4jConfigured ) { String msg = "Log4J is already configured, will not search for log4j properties file" ; LoggerFactory . getBootLogger ( ) . info ( msg ) ; } else { LoggerFactory . getBootLogger ( ) . info ( "Log4J is not configured" ) ; } } return log4jConfigured ; }
Helper method to check if log4j is already configured
1,044
private org . apache . log4j . Logger getLogger ( ) { if ( logger == null ) { logger = org . apache . log4j . Logger . getLogger ( name ) ; } return logger ; }
Gets the logger .
1,045
public final void debug ( Object pObject ) { getLogger ( ) . log ( FQCN , Level . DEBUG , pObject , null ) ; }
generate a message for loglevel DEBUG
1,046
public final void info ( Object pObject ) { getLogger ( ) . log ( FQCN , Level . INFO , pObject , null ) ; }
generate a message for loglevel INFO
1,047
public final void warn ( Object pObject ) { getLogger ( ) . log ( FQCN , Level . WARN , pObject , null ) ; }
generate a message for loglevel WARN
1,048
public final void error ( Object pObject ) { getLogger ( ) . log ( FQCN , Level . ERROR , pObject , null ) ; }
generate a message for loglevel ERROR
1,049
public final void fatal ( Object pObject ) { getLogger ( ) . log ( FQCN , Level . FATAL , pObject , null ) ; }
generate a message for loglevel FATAL
1,050
protected Class < ? > getPropertyClass ( ClassMetadata meta , String propertyName ) throws HibernateLayerException { propertyName = propertyName . replace ( XPATH_SEPARATOR , SEPARATOR ) ; if ( propertyName . contains ( SEPARATOR ) ) { String directProperty = propertyName . substring ( 0 , propertyName . indexOf ( SEPARATOR ) ) ; try { Type prop = meta . getPropertyType ( directProperty ) ; if ( prop . isCollectionType ( ) ) { CollectionType coll = ( CollectionType ) prop ; prop = coll . getElementType ( ( SessionFactoryImplementor ) sessionFactory ) ; } ClassMetadata propMeta = sessionFactory . getClassMetadata ( prop . getReturnedClass ( ) ) ; return getPropertyClass ( propMeta , propertyName . substring ( propertyName . indexOf ( SEPARATOR ) + 1 ) ) ; } catch ( HibernateException e ) { throw new HibernateLayerException ( e , ExceptionCode . HIBERNATE_COULD_NOT_RESOLVE , propertyName , meta . getEntityName ( ) ) ; } } else { try { return meta . getPropertyType ( propertyName ) . getReturnedClass ( ) ; } catch ( HibernateException e ) { throw new HibernateLayerException ( e , ExceptionCode . HIBERNATE_COULD_NOT_RESOLVE , propertyName , meta . getEntityName ( ) ) ; } } }
Return the class of one of the properties of another class from which the Hibernate metadata is given .
1,051
public void setSessionFactory ( SessionFactory sessionFactory ) throws HibernateLayerException { try { this . sessionFactory = sessionFactory ; if ( null != layerInfo ) { entityMetadata = sessionFactory . getClassMetadata ( layerInfo . getFeatureInfo ( ) . getDataSourceName ( ) ) ; } } catch ( Exception e ) { throw new HibernateLayerException ( e , ExceptionCode . HIBERNATE_NO_SESSION_FACTORY ) ; } }
Set session factory .
1,052
static JDOClass getJDOClass ( Class c ) { JDOClass rc = null ; try { JavaModelFactory javaModelFactory = RuntimeJavaModelFactory . getInstance ( ) ; JavaModel javaModel = javaModelFactory . getJavaModel ( c . getClassLoader ( ) ) ; JDOModel m = JDOModelFactoryImpl . getInstance ( ) . getJDOModel ( javaModel ) ; rc = m . getJDOClass ( c . getName ( ) ) ; } catch ( RuntimeException ex ) { throw new JDOFatalInternalException ( "Not a JDO class: " + c . getName ( ) ) ; } return rc ; }
this method looks up the appropriate JDOClass for a given persistent Class . It uses the JDOModel to perfom this lookup .
1,053
static Object getLCState ( StateManagerInternal sm ) { try { Field myLC = sm . getClass ( ) . getDeclaredField ( "myLC" ) ; myLC . setAccessible ( true ) ; return myLC . get ( sm ) ; } catch ( NoSuchFieldException e ) { return e ; } catch ( IllegalAccessException e ) { return e ; } }
obtains the internal JDO lifecycle state of the input StatemanagerInternal . This Method is helpful to display persistent objects internal state .
1,054
protected void postConstruct ( ) throws GeomajasException { if ( null == baseTmsUrl ) { throw new GeomajasException ( ExceptionCode . PARAMETER_MISSING , "baseTmsUrl" ) ; } if ( ( baseTmsUrl . startsWith ( "http://" ) || baseTmsUrl . startsWith ( "https://" ) ) && ! baseTmsUrl . endsWith ( "/" ) ) { baseTmsUrl += "/" ; } if ( layerInfo == null || layerInfo == UNUSABLE_LAYER_INFO ) { try { tileMap = configurationService . getCapabilities ( this ) ; version = tileMap . getVersion ( ) ; extension = tileMap . getTileFormat ( ) . getExtension ( ) ; layerInfo = configurationService . asLayerInfo ( tileMap ) ; usable = true ; } catch ( TmsLayerException e ) { layerInfo = UNUSABLE_LAYER_INFO ; usable = false ; log . warn ( "The layer could not be correctly initialized: " + getId ( ) , e ) ; } } else if ( extension == null ) { throw new GeomajasException ( ExceptionCode . PARAMETER_MISSING , "extension" ) ; } if ( layerInfo != null ) { state = new TileServiceState ( geoService , layerInfo ) ; boolean proxying = useCache || useProxy || null != authentication ; if ( tileMap != null && ! proxying ) { urlBuilder = new TileMapUrlBuilder ( tileMap ) ; } else { urlBuilder = new SimpleTmsUrlBuilder ( extension ) ; } } }
Finish initializing the service .
1,055
public Collection getReaders ( Object obj ) { checkTimedOutLocks ( ) ; Identity oid = new Identity ( obj , getBroker ( ) ) ; return getReaders ( oid ) ; }
returns a collection of Reader LockEntries for object obj . If no LockEntries could be found an empty Vector is returned .
1,056
private void removeTimedOutLocks ( long timeout ) { int count = 0 ; long maxAge = System . currentTimeMillis ( ) - timeout ; boolean breakFromLoop = false ; ObjectLocks temp = null ; synchronized ( locktable ) { Iterator it = locktable . values ( ) . iterator ( ) ; while ( it . hasNext ( ) && ! breakFromLoop && ( count <= MAX_LOCKS_TO_CLEAN ) ) { temp = ( ObjectLocks ) it . next ( ) ; if ( temp . getWriter ( ) != null ) { if ( temp . getWriter ( ) . getTimestamp ( ) < maxAge ) { temp . setWriter ( null ) ; } } if ( temp . getYoungestReader ( ) < maxAge ) { temp . getReaders ( ) . clear ( ) ; if ( temp . getWriter ( ) == null ) { it . remove ( ) ; } } else { Iterator readerIt = temp . getReaders ( ) . values ( ) . iterator ( ) ; LockEntry readerLock = null ; while ( readerIt . hasNext ( ) ) { readerLock = ( LockEntry ) readerIt . next ( ) ; if ( readerLock . getTimestamp ( ) < maxAge ) { readerIt . remove ( ) ; } } } count ++ ; } } }
removes all timed out lock entries from the persistent storage . The timeout value can be set in the OJB properties file .
1,057
public void createAgent ( String agent_name , String path ) { IComponentIdentifier agent = cmsService . createComponent ( agent_name , path , null , null ) . get ( new ThreadSuspendable ( ) ) ; createdAgents . put ( agent_name , agent ) ; }
Creates a real agent in the platform
1,058
public IExternalAccess getAgentsExternalAccess ( String agent_name ) { return cmsService . getExternalAccess ( getAgentID ( agent_name ) ) . get ( new ThreadSuspendable ( ) ) ; }
This method searches in the Component Management Service so given an agent name returns its IExternalAccess
1,059
public void create ( final DbProduct dbProduct ) { if ( repositoryHandler . getProduct ( dbProduct . getName ( ) ) != null ) { throw new WebApplicationException ( Response . status ( Response . Status . CONFLICT ) . entity ( "Product already exist!" ) . build ( ) ) ; } repositoryHandler . store ( dbProduct ) ; }
Creates a new Product in Grapes database
1,060
public DbProduct getProduct ( final String name ) { final DbProduct dbProduct = repositoryHandler . getProduct ( name ) ; if ( dbProduct == null ) { throw new WebApplicationException ( Response . status ( Response . Status . NOT_FOUND ) . entity ( "Product " + name + " does not exist." ) . build ( ) ) ; } return dbProduct ; }
Returns a product regarding its name
1,061
public void deleteProduct ( final String name ) { final DbProduct dbProduct = getProduct ( name ) ; repositoryHandler . deleteProduct ( dbProduct . getName ( ) ) ; }
Deletes a product from the database
1,062
public void setProductModules ( final String name , final List < String > moduleNames ) { final DbProduct dbProduct = getProduct ( name ) ; dbProduct . setModules ( moduleNames ) ; repositoryHandler . store ( dbProduct ) ; }
Patches the product module names
1,063
public Object [ ] getAgentPlans ( String agent_name , Connector connector ) { connector . getLogger ( ) . warning ( "Non suported method for Jade Platform. There is no plans in Jade platform." ) ; throw new java . lang . UnsupportedOperationException ( "Non suported method for Jade Platform. There is no extra properties." ) ; }
Non - supported in JadeAgentIntrospector
1,064
protected synchronized int loadSize ( ) throws PersistenceBrokerException { PersistenceBroker broker = getBroker ( ) ; try { return broker . getCount ( getQuery ( ) ) ; } catch ( Exception ex ) { throw new PersistenceBrokerException ( ex ) ; } finally { releaseBroker ( broker ) ; } }
Determines the number of elements that the query would return . Override this method if the size shall be determined in a specific way .
1,065
protected Collection loadData ( ) throws PersistenceBrokerException { PersistenceBroker broker = getBroker ( ) ; try { Collection result ; if ( _data != null ) { result = _data ; } else if ( _size != 0 ) { result = ( Collection ) broker . getCollectionByQuery ( getCollectionClass ( ) , getQuery ( ) ) ; } else { result = ( Collection ) getCollectionClass ( ) . newInstance ( ) ; } return result ; } catch ( Exception ex ) { throw new PersistenceBrokerException ( ex ) ; } finally { releaseBroker ( broker ) ; } }
Loads the data from the database . Override this method if the objects shall be loaded in a specific way .
1,066
protected void beforeLoading ( ) { if ( _listeners != null ) { CollectionProxyListener listener ; if ( _perThreadDescriptorsEnabled ) { loadProfileIfNeeded ( ) ; } for ( int idx = _listeners . size ( ) - 1 ; idx >= 0 ; idx -- ) { listener = ( CollectionProxyListener ) _listeners . get ( idx ) ; listener . beforeLoading ( this ) ; } } }
Notifies all listeners that the data is about to be loaded .
1,067
public void clear ( ) { Class collClass = getCollectionClass ( ) ; if ( IRemovalAwareCollection . class . isAssignableFrom ( collClass ) ) { getData ( ) . clear ( ) ; } else { Collection coll ; try { coll = ( Collection ) collClass . newInstance ( ) ; } catch ( Exception e ) { coll = new ArrayList ( ) ; } setData ( coll ) ; } _size = 0 ; }
Clears the proxy . A cleared proxy is defined as loaded
1,068
protected synchronized void releaseBroker ( PersistenceBroker broker ) { if ( broker != null && _needsClose ) { _needsClose = false ; broker . close ( ) ; } }
Release the broker instance .
1,069
protected synchronized PersistenceBroker getBroker ( ) throws PBFactoryException { if ( _perThreadDescriptorsEnabled ) { loadProfileIfNeeded ( ) ; } PersistenceBroker broker ; if ( getBrokerKey ( ) == null ) { throw new OJBRuntimeException ( "Can't find associated PBKey. Need PBKey to obtain a valid" + "PersistenceBroker instance from intern resources." ) ; } broker = PersistenceBrokerThreadMapping . currentPersistenceBroker ( getBrokerKey ( ) ) ; if ( broker == null || broker . isClosed ( ) ) { broker = PersistenceBrokerFactory . createPersistenceBroker ( getBrokerKey ( ) ) ; _needsClose = true ; } return broker ; }
Acquires a broker instance . If no PBKey is available a runtime exception will be thrown .
1,070
public synchronized void addListener ( CollectionProxyListener listener ) { if ( _listeners == null ) { _listeners = new ArrayList ( ) ; } if ( ! _listeners . contains ( listener ) ) { _listeners . add ( listener ) ; } }
Adds a listener to this collection .
1,071
public String getURN ( ) throws InvalidRegistrationContentException { if ( parsedConfig == null || parsedConfig . urn == null || parsedConfig . urn . trim ( ) . isEmpty ( ) ) { throw new InvalidRegistrationContentException ( "Invalid registration config - failed to read mediator URN" ) ; } return parsedConfig . urn ; }
Reads and returns the mediator URN from the JSON content .
1,072
public boolean deleteExisting ( final File file ) { if ( ! file . exists ( ) ) { return true ; } boolean deleted = false ; if ( file . canWrite ( ) ) { deleted = file . delete ( ) ; } else { LogLog . debug ( file + " is not writeable for delete (retrying)" ) ; } if ( ! deleted ) { if ( ! file . exists ( ) ) { deleted = true ; } else { file . delete ( ) ; deleted = ( ! file . exists ( ) ) ; } } return deleted ; }
Delete with retry .
1,073
public boolean rename ( final File from , final File to ) { boolean renamed = false ; if ( this . isWriteable ( from ) ) { renamed = from . renameTo ( to ) ; } else { LogLog . debug ( from + " is not writeable for rename (retrying)" ) ; } if ( ! renamed ) { from . renameTo ( to ) ; renamed = ( ! from . exists ( ) ) ; } return renamed ; }
Rename with retry .
1,074
protected synchronized void registerOpenDatabase ( DatabaseImpl newDB ) { DatabaseImpl old_db = getCurrentDatabase ( ) ; if ( old_db != null ) { try { if ( old_db . isOpen ( ) ) { log . warn ( "## There is still an opened database, close old one ##" ) ; old_db . close ( ) ; } } catch ( Throwable t ) { } } if ( log . isDebugEnabled ( ) ) log . debug ( "Set current database " + newDB + " PBKey was " + newDB . getPBKey ( ) ) ; setCurrentDatabase ( newDB ) ; }
Register opened database via the PBKey .
1,075
public String [ ] getAttributeNames ( ) { Set keys = ( attributeMap == null ? new HashSet ( ) : attributeMap . keySet ( ) ) ; String [ ] result = new String [ keys . size ( ) ] ; keys . toArray ( result ) ; return result ; }
Returns an array of the names of all atributes of this descriptor .
1,076
public void check ( ModelDef modelDef , String checkLevel ) throws ConstraintException { ensureReferencedKeys ( modelDef , checkLevel ) ; checkReferenceForeignkeys ( modelDef , checkLevel ) ; checkCollectionForeignkeys ( modelDef , checkLevel ) ; checkKeyModifications ( modelDef , checkLevel ) ; }
Checks the given model .
1,077
private void ensureReferencedPKs ( ModelDef modelDef , ReferenceDescriptorDef refDef ) throws ConstraintException { String targetClassName = refDef . getProperty ( PropertyHelper . OJB_PROPERTY_CLASS_REF ) ; ClassDescriptorDef targetClassDef = modelDef . getClass ( targetClassName ) ; ensurePKsFromHierarchy ( targetClassDef ) ; }
Ensures that the primary keys required by the given reference are present in the referenced class .
1,078
private void ensureReferencedPKs ( ModelDef modelDef , CollectionDescriptorDef collDef ) throws ConstraintException { String elementClassName = collDef . getProperty ( PropertyHelper . OJB_PROPERTY_ELEMENT_CLASS_REF ) ; ClassDescriptorDef elementClassDef = modelDef . getClass ( elementClassName ) ; String indirTable = collDef . getProperty ( PropertyHelper . OJB_PROPERTY_INDIRECTION_TABLE ) ; String localKey = collDef . getProperty ( PropertyHelper . OJB_PROPERTY_FOREIGNKEY ) ; String remoteKey = collDef . getProperty ( PropertyHelper . OJB_PROPERTY_REMOTE_FOREIGNKEY ) ; boolean hasRemoteKey = remoteKey != null ; ArrayList fittingCollections = new ArrayList ( ) ; for ( Iterator it = elementClassDef . getAllExtentClasses ( ) ; it . hasNext ( ) ; ) { ClassDescriptorDef subTypeDef = ( ClassDescriptorDef ) it . next ( ) ; for ( Iterator collIt = subTypeDef . getCollections ( ) ; collIt . hasNext ( ) ; ) { CollectionDescriptorDef curCollDef = ( CollectionDescriptorDef ) collIt . next ( ) ; if ( indirTable . equals ( curCollDef . getProperty ( PropertyHelper . OJB_PROPERTY_INDIRECTION_TABLE ) ) && ( collDef != curCollDef ) && ( ! hasRemoteKey || CommaListIterator . sameLists ( remoteKey , curCollDef . getProperty ( PropertyHelper . OJB_PROPERTY_FOREIGNKEY ) ) ) && ( ! curCollDef . hasProperty ( PropertyHelper . OJB_PROPERTY_REMOTE_FOREIGNKEY ) || CommaListIterator . sameLists ( localKey , curCollDef . getProperty ( PropertyHelper . OJB_PROPERTY_REMOTE_FOREIGNKEY ) ) ) ) { fittingCollections . add ( curCollDef ) ; } } } if ( ! fittingCollections . isEmpty ( ) ) { if ( ! hasRemoteKey && ( fittingCollections . size ( ) > 1 ) ) { CollectionDescriptorDef firstCollDef = ( CollectionDescriptorDef ) fittingCollections . get ( 0 ) ; String foreignKey = firstCollDef . getProperty ( PropertyHelper . OJB_PROPERTY_FOREIGNKEY ) ; for ( int idx = 1 ; idx < fittingCollections . size ( ) ; idx ++ ) { CollectionDescriptorDef curCollDef = ( CollectionDescriptorDef ) fittingCollections . get ( idx ) ; if ( ! CommaListIterator . sameLists ( foreignKey , curCollDef . getProperty ( PropertyHelper . OJB_PROPERTY_FOREIGNKEY ) ) ) { throw new ConstraintException ( "Cannot determine the element-side collection that corresponds to the collection " + collDef . getName ( ) + " in type " + collDef . getOwner ( ) . getName ( ) + " because there are at least two different collections that would fit." + " Specifying remote-foreignkey in the original collection " + collDef . getName ( ) + " will perhaps help" ) ; } } collDef . setProperty ( PropertyHelper . OJB_PROPERTY_REMOTE_FOREIGNKEY , foreignKey ) ; for ( int idx = 0 ; idx < fittingCollections . size ( ) ; idx ++ ) { CollectionDescriptorDef curCollDef = ( CollectionDescriptorDef ) fittingCollections . get ( idx ) ; curCollDef . setProperty ( PropertyHelper . OJB_PROPERTY_REMOTE_FOREIGNKEY , localKey ) ; } } } ensurePKsFromHierarchy ( elementClassDef ) ; }
Ensures that the primary keys required by the given collection with indirection table are present in the element class .
1,079
private void ensureReferencedFKs ( ModelDef modelDef , CollectionDescriptorDef collDef ) throws ConstraintException { String elementClassName = collDef . getProperty ( PropertyHelper . OJB_PROPERTY_ELEMENT_CLASS_REF ) ; ClassDescriptorDef elementClassDef = modelDef . getClass ( elementClassName ) ; String fkFieldNames = collDef . getProperty ( PropertyHelper . OJB_PROPERTY_FOREIGNKEY ) ; ArrayList missingFields = new ArrayList ( ) ; SequencedHashMap fkFields = new SequencedHashMap ( ) ; for ( CommaListIterator it = new CommaListIterator ( fkFieldNames ) ; it . hasNext ( ) ; ) { String fieldName = ( String ) it . next ( ) ; FieldDescriptorDef fieldDef = elementClassDef . getField ( fieldName ) ; if ( fieldDef == null ) { missingFields . add ( fieldName ) ; } fkFields . put ( fieldName , fieldDef ) ; } for ( Iterator it = elementClassDef . getAllExtentClasses ( ) ; it . hasNext ( ) && ! missingFields . isEmpty ( ) ; ) { ClassDescriptorDef subTypeDef = ( ClassDescriptorDef ) it . next ( ) ; for ( int idx = 0 ; idx < missingFields . size ( ) ; ) { FieldDescriptorDef fieldDef = subTypeDef . getField ( ( String ) missingFields . get ( idx ) ) ; if ( fieldDef != null ) { fkFields . put ( fieldDef . getName ( ) , fieldDef ) ; missingFields . remove ( idx ) ; } else { idx ++ ; } } } if ( ! missingFields . isEmpty ( ) ) { throw new ConstraintException ( "Cannot find field " + missingFields . get ( 0 ) . toString ( ) + " in the hierarchy with root type " + elementClassDef . getName ( ) + " which is used as foreignkey in collection " + collDef . getName ( ) + " in " + collDef . getOwner ( ) . getName ( ) ) ; } ensureFields ( elementClassDef , fkFields . values ( ) ) ; }
Ensures that the foreign keys required by the given collection are present in the element class .
1,080
private void ensurePKsFromHierarchy ( ClassDescriptorDef classDef ) throws ConstraintException { SequencedHashMap pks = new SequencedHashMap ( ) ; for ( Iterator it = classDef . getAllExtentClasses ( ) ; it . hasNext ( ) ; ) { ClassDescriptorDef subTypeDef = ( ClassDescriptorDef ) it . next ( ) ; ArrayList subPKs = subTypeDef . getPrimaryKeys ( ) ; for ( Iterator pkIt = subPKs . iterator ( ) ; pkIt . hasNext ( ) ; ) { FieldDescriptorDef fieldDef = ( FieldDescriptorDef ) pkIt . next ( ) ; FieldDescriptorDef foundPKDef = ( FieldDescriptorDef ) pks . get ( fieldDef . getName ( ) ) ; if ( foundPKDef != null ) { if ( ! isEqual ( fieldDef , foundPKDef ) ) { throw new ConstraintException ( "Cannot pull up the declaration of the required primary key " + fieldDef . getName ( ) + " because its definitions in " + fieldDef . getOwner ( ) . getName ( ) + " and " + foundPKDef . getOwner ( ) . getName ( ) + " differ" ) ; } } else { pks . put ( fieldDef . getName ( ) , fieldDef ) ; } } } ensureFields ( classDef , pks . values ( ) ) ; }
Gathers the pk fields from the hierarchy of the given class and copies them into the class .
1,081
private void ensureFields ( ClassDescriptorDef classDef , Collection fields ) throws ConstraintException { boolean forceVirtual = ! classDef . getBooleanProperty ( PropertyHelper . OJB_PROPERTY_GENERATE_REPOSITORY_INFO , true ) ; for ( Iterator it = fields . iterator ( ) ; it . hasNext ( ) ; ) { FieldDescriptorDef fieldDef = ( FieldDescriptorDef ) it . next ( ) ; FieldDescriptorDef foundFieldDef = classDef . getField ( fieldDef . getName ( ) ) ; if ( foundFieldDef != null ) { if ( isEqual ( fieldDef , foundFieldDef ) ) { if ( forceVirtual ) { foundFieldDef . setProperty ( PropertyHelper . OJB_PROPERTY_VIRTUAL_FIELD , "true" ) ; } continue ; } else { throw new ConstraintException ( "Cannot pull up the declaration of the required field " + fieldDef . getName ( ) + " from type " + fieldDef . getOwner ( ) . getName ( ) + " to basetype " + classDef . getName ( ) + " because there is already a different field of the same name" ) ; } } if ( classDef . getCollection ( fieldDef . getName ( ) ) != null ) { throw new ConstraintException ( "Cannot pull up the declaration of the required field " + fieldDef . getName ( ) + " from type " + fieldDef . getOwner ( ) . getName ( ) + " to basetype " + classDef . getName ( ) + " because there is already a collection of the same name" ) ; } if ( classDef . getReference ( fieldDef . getName ( ) ) != null ) { throw new ConstraintException ( "Cannot pull up the declaration of the required field " + fieldDef . getName ( ) + " from type " + fieldDef . getOwner ( ) . getName ( ) + " to basetype " + classDef . getName ( ) + " because there is already a reference of the same name" ) ; } classDef . addFieldClone ( fieldDef ) ; classDef . getField ( fieldDef . getName ( ) ) . setProperty ( PropertyHelper . OJB_PROPERTY_VIRTUAL_FIELD , "true" ) ; } }
Ensures that the specified fields are present in the given class .
1,082
private boolean isEqual ( FieldDescriptorDef first , FieldDescriptorDef second ) { return first . getName ( ) . equals ( second . getName ( ) ) && first . getProperty ( PropertyHelper . OJB_PROPERTY_COLUMN ) . equals ( second . getProperty ( PropertyHelper . OJB_PROPERTY_COLUMN ) ) && first . getProperty ( PropertyHelper . OJB_PROPERTY_JDBC_TYPE ) . equals ( second . getProperty ( PropertyHelper . OJB_PROPERTY_JDBC_TYPE ) ) ; }
Tests whether the two field descriptors are equal i . e . have same name same column and same jdbc - type .
1,083
private void checkCollectionForeignkeys ( ModelDef modelDef , String checkLevel ) throws ConstraintException { if ( CHECKLEVEL_NONE . equals ( checkLevel ) ) { return ; } ClassDescriptorDef classDef ; CollectionDescriptorDef collDef ; for ( Iterator it = modelDef . getClasses ( ) ; it . hasNext ( ) ; ) { classDef = ( ClassDescriptorDef ) it . next ( ) ; for ( Iterator collIt = classDef . getCollections ( ) ; collIt . hasNext ( ) ; ) { collDef = ( CollectionDescriptorDef ) collIt . next ( ) ; if ( ! collDef . getBooleanProperty ( PropertyHelper . OJB_PROPERTY_IGNORE , false ) ) { if ( collDef . hasProperty ( PropertyHelper . OJB_PROPERTY_INDIRECTION_TABLE ) ) { checkIndirectionTable ( modelDef , collDef ) ; } else { checkCollectionForeignkeys ( modelDef , collDef ) ; } } } } }
Checks the foreignkeys of all collections in the model .
1,084
private void checkReferenceForeignkeys ( ModelDef modelDef , String checkLevel ) throws ConstraintException { if ( CHECKLEVEL_NONE . equals ( checkLevel ) ) { return ; } ClassDescriptorDef classDef ; ReferenceDescriptorDef refDef ; for ( Iterator it = modelDef . getClasses ( ) ; it . hasNext ( ) ; ) { classDef = ( ClassDescriptorDef ) it . next ( ) ; for ( Iterator refIt = classDef . getReferences ( ) ; refIt . hasNext ( ) ; ) { refDef = ( ReferenceDescriptorDef ) refIt . next ( ) ; if ( ! refDef . getBooleanProperty ( PropertyHelper . OJB_PROPERTY_IGNORE , false ) ) { checkReferenceForeignkeys ( modelDef , refDef ) ; } } } }
Checks the foreignkeys of all references in the model .
1,085
private ReferenceDescriptorDef usedByReference ( ModelDef modelDef , FieldDescriptorDef fieldDef ) { String ownerClassName = ( ( ClassDescriptorDef ) fieldDef . getOwner ( ) ) . getQualifiedName ( ) ; ClassDescriptorDef classDef ; ReferenceDescriptorDef refDef ; String targetClassName ; if ( PropertyHelper . toBoolean ( fieldDef . getProperty ( PropertyHelper . OJB_PROPERTY_PRIMARYKEY ) , false ) ) { for ( Iterator classIt = modelDef . getClasses ( ) ; classIt . hasNext ( ) ; ) { classDef = ( ClassDescriptorDef ) classIt . next ( ) ; for ( Iterator refIt = classDef . getReferences ( ) ; refIt . hasNext ( ) ; ) { refDef = ( ReferenceDescriptorDef ) refIt . next ( ) ; targetClassName = refDef . getProperty ( PropertyHelper . OJB_PROPERTY_CLASS_REF ) . replace ( '$' , '.' ) ; if ( ownerClassName . equals ( targetClassName ) ) { return refDef ; } } } } return null ; }
Checks whether the given field definition is used as the primary key of a class referenced by a reference .
1,086
public Object [ ] getForeignKeyValues ( Object obj , ClassDescriptor mif ) throws PersistenceBrokerException { FieldDescriptor [ ] fks = getForeignKeyFieldDescriptors ( mif ) ; if ( fks . length > 0 ) obj = ProxyHelper . getRealObject ( obj ) ; Object [ ] result = new Object [ fks . length ] ; for ( int i = 0 ; i < result . length ; i ++ ) { FieldDescriptor fmd = fks [ i ] ; PersistentField f = fmd . getPersistentField ( ) ; result [ i ] = f . get ( obj ) ; } return result ; }
Returns an Object array of all FK field values of the specified object . If the specified object is an unmaterialized Proxy it will be materialized to read the FK values .
1,087
public void addForeignKeyField ( int newId ) { if ( m_ForeignKeyFields == null ) { m_ForeignKeyFields = new Vector ( ) ; } m_ForeignKeyFields . add ( new Integer ( newId ) ) ; }
add a foreign key field ID
1,088
public void addForeignKeyField ( String newField ) { if ( m_ForeignKeyFields == null ) { m_ForeignKeyFields = new Vector ( ) ; } m_ForeignKeyFields . add ( newField ) ; }
add a foreign key field
1,089
public OJBLock atomicGetOrCreateLock ( Object resourceId , Object isolationId ) { synchronized ( globalLocks ) { MultiLevelLock lock = getLock ( resourceId ) ; if ( lock == null ) { lock = createLock ( resourceId , isolationId ) ; } return ( OJBLock ) lock ; } }
Either gets an existing lock on the specified resource or creates one if none exists . This methods guarantees to do this atomically .
1,090
public void initSize ( Rectangle rectangle ) { template = writer . getDirectContent ( ) . createTemplate ( rectangle . getWidth ( ) , rectangle . getHeight ( ) ) ; }
Initializes context size .
1,091
public Rectangle getTextSize ( String text , Font font ) { template . saveState ( ) ; DefaultFontMapper mapper = new DefaultFontMapper ( ) ; BaseFont bf = mapper . awtToPdf ( font ) ; template . setFontAndSize ( bf , font . getSize ( ) ) ; float textWidth = template . getEffectiveStringWidth ( text , false ) ; float ascent = bf . getAscentPoint ( text , font . getSize ( ) ) ; float descent = bf . getDescentPoint ( text , font . getSize ( ) ) ; float textHeight = ascent - descent ; template . restoreState ( ) ; return new Rectangle ( 0 , 0 , textWidth , textHeight ) ; }
Return the text box for the specified text and font .
1,092
public void drawText ( String text , Font font , Rectangle box , Color fontColor ) { template . saveState ( ) ; DefaultFontMapper mapper = new DefaultFontMapper ( ) ; BaseFont bf = mapper . awtToPdf ( font ) ; template . setFontAndSize ( bf , font . getSize ( ) ) ; float descent = 0 ; if ( text != null ) { descent = bf . getDescentPoint ( text , font . getSize ( ) ) ; } Rectangle fit = getTextSize ( text , font ) ; template . setColorFill ( fontColor ) ; template . beginText ( ) ; template . showTextAligned ( PdfContentByte . ALIGN_LEFT , text , origX + box . getLeft ( ) + 0.5f * ( box . getWidth ( ) - fit . getWidth ( ) ) , origY + box . getBottom ( ) + 0.5f * ( box . getHeight ( ) - fit . getHeight ( ) ) - descent , 0 ) ; template . endText ( ) ; template . restoreState ( ) ; }
Draw text in the center of the specified box .
1,093
public void strokeRectangle ( Rectangle rect , Color color , float linewidth ) { strokeRectangle ( rect , color , linewidth , null ) ; }
Draw a rectangular boundary with this color and linewidth .
1,094
public void strokeRoundRectangle ( Rectangle rect , Color color , float linewidth , float r ) { template . saveState ( ) ; setStroke ( color , linewidth , null ) ; template . roundRectangle ( origX + rect . getLeft ( ) , origY + rect . getBottom ( ) , rect . getWidth ( ) , rect . getHeight ( ) , r ) ; template . stroke ( ) ; template . restoreState ( ) ; }
Draw a rounded rectangular boundary .
1,095
public void fillRectangle ( Rectangle rect , Color color ) { template . saveState ( ) ; setFill ( color ) ; template . rectangle ( origX + rect . getLeft ( ) , origY + rect . getBottom ( ) , rect . getWidth ( ) , rect . getHeight ( ) ) ; template . fill ( ) ; template . restoreState ( ) ; }
Draw a rectangle s interior with this color .
1,096
public void strokeEllipse ( Rectangle rect , Color color , float linewidth ) { template . saveState ( ) ; setStroke ( color , linewidth , null ) ; template . ellipse ( origX + rect . getLeft ( ) , origY + rect . getBottom ( ) , origX + rect . getRight ( ) , origY + rect . getTop ( ) ) ; template . stroke ( ) ; template . restoreState ( ) ; }
Draw an elliptical exterior with this color .
1,097
public void fillEllipse ( Rectangle rect , Color color ) { template . saveState ( ) ; setFill ( color ) ; template . ellipse ( origX + rect . getLeft ( ) , origY + rect . getBottom ( ) , origX + rect . getRight ( ) , origY + rect . getTop ( ) ) ; template . fill ( ) ; template . restoreState ( ) ; }
Draw an elliptical interior with this color .
1,098
public void moveRectangleTo ( Rectangle rect , float x , float y ) { float width = rect . getWidth ( ) ; float height = rect . getHeight ( ) ; rect . setLeft ( x ) ; rect . setBottom ( y ) ; rect . setRight ( rect . getLeft ( ) + width ) ; rect . setTop ( rect . getBottom ( ) + height ) ; }
Move this rectangle to the specified bottom - left point .
1,099
public void translateRectangle ( Rectangle rect , float dx , float dy ) { float width = rect . getWidth ( ) ; float height = rect . getHeight ( ) ; rect . setLeft ( rect . getLeft ( ) + dx ) ; rect . setBottom ( rect . getBottom ( ) + dy ) ; rect . setRight ( rect . getLeft ( ) + dx + width ) ; rect . setTop ( rect . getBottom ( ) + dy + height ) ; }
Translate this rectangle over the specified following distances .