idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
600
public IGoal [ ] getAgentGoals ( final String agent_name , Connector connector ) { ( ( IExternalAccess ) connector . getAgentsExternalAccess ( agent_name ) ) . scheduleStep ( new IComponentStep < Plan > ( ) { public IFuture < Plan > execute ( IInternalAccess ia ) { IBDIInternalAccess bia = ( IBDIInternalAccess ) ia ; goals = bia . getGoalbase ( ) . getGoals ( ) ; return null ; } } ) . get ( new ThreadSuspendable ( ) ) ; return goals ; }
This method prints goal information of an agent through its external access . It can be used to check the correct behaviour of the agent .
127
26
601
public void localBegin ( ) { if ( this . isInLocalTransaction ) { throw new TransactionInProgressException ( "Connection is already in transaction" ) ; } Connection connection = null ; try { connection = this . getConnection ( ) ; } catch ( LookupException e ) { /** * must throw to notify user that we couldn't start a connection */ throw new PersistenceBrokerException ( "Can't lookup a connection" , e ) ; } if ( log . isDebugEnabled ( ) ) log . debug ( "localBegin was called for con " + connection ) ; // change autoCommit state only if we are not in a managed environment // and it is enabled by user if ( ! broker . isManaged ( ) ) { if ( jcd . getUseAutoCommit ( ) == JdbcConnectionDescriptor . AUTO_COMMIT_SET_TRUE_AND_TEMPORARY_FALSE ) { if ( log . isDebugEnabled ( ) ) log . debug ( "Try to change autoCommit state to 'false'" ) ; platform . changeAutoCommitState ( jcd , connection , false ) ; } } else { if ( log . isDebugEnabled ( ) ) log . debug ( "Found managed environment setting in PB, will skip Platform.changeAutoCommitState(...) call" ) ; } this . isInLocalTransaction = true ; }
Start transaction on the underlying connection .
293
7
602
public void localCommit ( ) { if ( log . isDebugEnabled ( ) ) log . debug ( "commit was called" ) ; if ( ! this . isInLocalTransaction ) { throw new TransactionNotInProgressException ( "Not in transaction, call begin() before commit()" ) ; } try { if ( ! broker . isManaged ( ) ) { if ( batchCon != null ) { batchCon . commit ( ) ; } else if ( con != null ) { con . commit ( ) ; } } else { if ( log . isDebugEnabled ( ) ) log . debug ( "Found managed environment setting in PB, will skip Connection.commit() call" ) ; } } catch ( SQLException e ) { log . error ( "Commit on underlying connection failed, try to rollback connection" , e ) ; this . localRollback ( ) ; throw new TransactionAbortedException ( "Commit on connection failed" , e ) ; } finally { this . isInLocalTransaction = false ; restoreAutoCommitState ( ) ; this . releaseConnection ( ) ; } }
Call commit on the underlying connection .
231
7
603
public void localRollback ( ) { log . info ( "Rollback was called, do rollback on current connection " + con ) ; if ( ! this . isInLocalTransaction ) { throw new PersistenceBrokerException ( "Not in transaction, cannot abort" ) ; } try { //truncate the local transaction this . isInLocalTransaction = false ; if ( ! broker . isManaged ( ) ) { if ( batchCon != null ) { batchCon . rollback ( ) ; } else if ( con != null && ! con . isClosed ( ) ) { con . rollback ( ) ; } } else { if ( log . isEnabledFor ( Logger . INFO ) ) log . info ( "Found managed environment setting in PB, will ignore rollback call on connection, this should be done by JTA" ) ; } } catch ( SQLException e ) { log . error ( "Rollback on the underlying connection failed" , e ) ; } finally { try { restoreAutoCommitState ( ) ; } catch ( OJBRuntimeException ignore ) { // Ignore or log exception } releaseConnection ( ) ; } }
Call rollback on the underlying connection .
241
8
604
protected void restoreAutoCommitState ( ) { try { if ( ! broker . isManaged ( ) ) { if ( jcd . getUseAutoCommit ( ) == JdbcConnectionDescriptor . AUTO_COMMIT_SET_TRUE_AND_TEMPORARY_FALSE && originalAutoCommitState == true && con != null && ! con . isClosed ( ) ) { platform . changeAutoCommitState ( jcd , con , true ) ; } } else { if ( log . isDebugEnabled ( ) ) log . debug ( "Found managed environment setting in PB, will skip Platform.changeAutoCommitState(...) call" ) ; } } catch ( SQLException e ) { // should never be reached throw new OJBRuntimeException ( "Restore of connection autocommit state failed" , e ) ; } }
Reset autoCommit state .
186
7
605
public boolean isAlive ( Connection conn ) { try { return con != null ? ! con . isClosed ( ) : false ; } catch ( SQLException e ) { log . error ( "IsAlive check failed, running connection was invalid!!" , e ) ; return false ; } }
Check if underlying connection was alive .
63
7
606
public static void registerAgent ( Agent agent , String serviceName , String serviceType ) throws FIPAException { DFAgentDescription dfd = new DFAgentDescription ( ) ; ServiceDescription sd = new ServiceDescription ( ) ; sd . setType ( serviceType ) ; sd . setName ( serviceName ) ; //NOTE El serviceType es un string que define el tipo de servicio publicado en el DF por el Agente X. // He escogido crear nombres en clave en jade.common.Definitions para este campo. //NOTE El serviceName es el nombre efectivo del servicio. // Esto es lo que el usuario va a definir en MockConfiguration.DFNameService y no el tipo como estaba puesto. // sd.setType(agentType); // sd.setName(agent.getLocalName()); //Add services?? // Sets the agent description dfd . setName ( agent . getAID ( ) ) ; dfd . addServices ( sd ) ; // Register the agent DFService . register ( agent , dfd ) ; }
Register the agent in the platform
242
6
607
public static InterceptorFactory getInstance ( ) { if ( instance == null ) { instance = new InterceptorFactory ( ) ; OjbConfigurator . getInstance ( ) . configure ( instance ) ; } return instance ; }
Returns the instance .
48
4
608
public void registerDropPasteWorker ( DropPasteWorkerInterface worker ) { this . dropPasteWorkerSet . add ( worker ) ; defaultDropTarget . setDefaultActions ( defaultDropTarget . getDefaultActions ( ) | worker . getAcceptableActions ( defaultDropTarget . getComponent ( ) ) ) ; }
Register a new DropPasteWorkerInterface .
72
10
609
public void removeDropPasteWorker ( DropPasteWorkerInterface worker ) { this . dropPasteWorkerSet . remove ( worker ) ; java . util . Iterator it = this . dropPasteWorkerSet . iterator ( ) ; int newDefaultActions = 0 ; while ( it . hasNext ( ) ) newDefaultActions |= ( ( DropPasteWorkerInterface ) it . next ( ) ) . getAcceptableActions ( defaultDropTarget . getComponent ( ) ) ; defaultDropTarget . setDefaultActions ( newDefaultActions ) ; }
Remove a DropPasteWorker from the helper .
124
11
610
public static String serialize ( final Object obj ) throws IOException { final ObjectMapper mapper = new ObjectMapper ( ) ; mapper . disable ( MapperFeature . USE_GETTERS_AS_SETTERS ) ; return mapper . writeValueAsString ( obj ) ; }
Serialize an object with Json
63
7
611
public static Organization unserializeOrganization ( final String organization ) throws IOException { final ObjectMapper mapper = new ObjectMapper ( ) ; mapper . disable ( MapperFeature . USE_GETTERS_AS_SETTERS ) ; return mapper . readValue ( organization , Organization . class ) ; }
Un - serialize a Json into Organization
68
9
612
public static Module unserializeModule ( final String module ) throws IOException { final ObjectMapper mapper = new ObjectMapper ( ) ; mapper . disable ( MapperFeature . USE_GETTERS_AS_SETTERS ) ; return mapper . readValue ( module , Module . class ) ; }
Un - serialize a Json into Module
67
9
613
public static Map < String , String > unserializeBuildInfo ( final String buildInfo ) throws IOException { final ObjectMapper mapper = new ObjectMapper ( ) ; mapper . disable ( MapperFeature . USE_GETTERS_AS_SETTERS ) ; return mapper . readValue ( buildInfo , new TypeReference < Map < String , Object > > ( ) { } ) ; }
Un - serialize a Json into BuildInfo
87
10
614
public Object get ( String name , ObjectFactory < ? > factory ) { ThreadScopeContext context = ThreadScopeContextHolder . getContext ( ) ; Object result = context . getBean ( name ) ; if ( null == result ) { result = factory . getObject ( ) ; context . setBean ( name , result ) ; } return result ; }
Get bean for given name in the thread scope .
75
10
615
public Object remove ( String name ) { ThreadScopeContext context = ThreadScopeContextHolder . getContext ( ) ; return context . remove ( name ) ; }
Removes bean from scope .
33
6
616
public static void addItemsHandled ( String handledItemsType , int handledItemsNumber ) { JobLogger jobLogger = ( JobLogger ) getInstance ( ) ; if ( jobLogger == null ) { return ; } jobLogger . addItemsHandledInstance ( handledItemsType , handledItemsNumber ) ; }
Number of failed actions in scheduler
68
7
617
protected DataSource getDataSource ( JdbcConnectionDescriptor jcd ) throws LookupException { final PBKey key = jcd . getPBKey ( ) ; DataSource ds = ( DataSource ) dsMap . get ( key ) ; if ( ds == null ) { // Found no pool for PBKey try { synchronized ( poolSynch ) { // Setup new object pool ObjectPool pool = setupPool ( jcd ) ; poolMap . put ( key , pool ) ; // Wrap the underlying object pool as DataSource ds = wrapAsDataSource ( jcd , pool ) ; dsMap . put ( key , ds ) ; } } catch ( Exception e ) { log . error ( "Could not setup DBCP DataSource for " + jcd , e ) ; throw new LookupException ( e ) ; } } return ds ; }
Returns the DBCP DataSource for the specified connection descriptor after creating a new DataSource if needed .
185
21
618
protected ObjectPool setupPool ( JdbcConnectionDescriptor jcd ) { log . info ( "Create new ObjectPool for DBCP connections:" + jcd ) ; try { ClassHelper . newInstance ( jcd . getDriver ( ) ) ; } catch ( InstantiationException e ) { log . fatal ( "Unable to instantiate the driver class: " + jcd . getDriver ( ) + " in ConnectionFactoryDBCImpl!" , e ) ; } catch ( IllegalAccessException e ) { log . fatal ( "IllegalAccessException while instantiating the driver class: " + jcd . getDriver ( ) + " in ConnectionFactoryDBCImpl!" , e ) ; } catch ( ClassNotFoundException e ) { log . fatal ( "Could not find the driver class : " + jcd . getDriver ( ) + " in ConnectionFactoryDBCImpl!" , e ) ; } // Get the configuration for the connection pool GenericObjectPool . Config conf = jcd . getConnectionPoolDescriptor ( ) . getObjectPoolConfig ( ) ; // Get the additional abandoned configuration AbandonedConfig ac = jcd . getConnectionPoolDescriptor ( ) . getAbandonedConfig ( ) ; // Create the ObjectPool that serves as the actual pool of connections. final ObjectPool connectionPool = createConnectionPool ( conf , ac ) ; // Create a DriverManager-based ConnectionFactory that // the connectionPool will use to create Connection instances final org . apache . commons . dbcp . ConnectionFactory connectionFactory ; connectionFactory = createConnectionFactory ( jcd ) ; // Create PreparedStatement object pool (if any) KeyedObjectPoolFactory statementPoolFactory = createStatementPoolFactory ( jcd ) ; // Set validation query and auto-commit mode final String validationQuery ; final boolean defaultAutoCommit ; final boolean defaultReadOnly = false ; validationQuery = jcd . getConnectionPoolDescriptor ( ) . getValidationQuery ( ) ; defaultAutoCommit = ( jcd . getUseAutoCommit ( ) != JdbcConnectionDescriptor . AUTO_COMMIT_SET_FALSE ) ; // // Now we'll create the PoolableConnectionFactory, which wraps // the "real" Connections created by the ConnectionFactory with // the classes that implement the pooling functionality. // final PoolableConnectionFactory poolableConnectionFactory ; poolableConnectionFactory = new PoolableConnectionFactory ( connectionFactory , connectionPool , statementPoolFactory , validationQuery , defaultReadOnly , defaultAutoCommit , ac ) ; return poolableConnectionFactory . getPool ( ) ; }
Returns a new ObjectPool for the specified connection descriptor . Override this method to setup your own pool .
545
21
619
protected DataSource wrapAsDataSource ( JdbcConnectionDescriptor jcd , ObjectPool connectionPool ) { final boolean allowConnectionUnwrap ; if ( jcd == null ) { allowConnectionUnwrap = false ; } else { final Properties properties = jcd . getConnectionPoolDescriptor ( ) . getDbcpProperties ( ) ; final String allowConnectionUnwrapParam ; allowConnectionUnwrapParam = properties . getProperty ( PARAM_NAME_UNWRAP_ALLOWED ) ; allowConnectionUnwrap = allowConnectionUnwrapParam != null && Boolean . valueOf ( allowConnectionUnwrapParam ) . booleanValue ( ) ; } final PoolingDataSource dataSource ; dataSource = new PoolingDataSource ( connectionPool ) ; dataSource . setAccessToUnderlyingConnectionAllowed ( allowConnectionUnwrap ) ; if ( jcd != null ) { final AbandonedConfig ac = jcd . getConnectionPoolDescriptor ( ) . getAbandonedConfig ( ) ; if ( ac . getRemoveAbandoned ( ) && ac . getLogAbandoned ( ) ) { final LoggerWrapperPrintWriter loggerPiggyBack ; loggerPiggyBack = new LoggerWrapperPrintWriter ( log , Logger . ERROR ) ; dataSource . setLogWriter ( loggerPiggyBack ) ; } } return dataSource ; }
Wraps the specified object pool for connections as a DataSource .
289
13
620
public void setAlias ( String alias ) { m_alias = alias ; String attributePath = ( String ) getAttribute ( ) ; boolean allPathsAliased = true ; m_userAlias = new UserAlias ( alias , attributePath , allPathsAliased ) ; }
Sets the alias . By default the entire attribute path participates in the alias
58
15
621
final void begin ( ) { if ( this . properties . isDateRollEnforced ( ) ) { final Thread thread = new Thread ( this , "Log4J Time-based File-roll Enforcer" ) ; thread . setDaemon ( true ) ; thread . start ( ) ; this . threadRef = thread ; } }
Starts the enforcer .
69
6
622
public Map < String , ClientWidgetInfo > securityClone ( Map < String , ClientWidgetInfo > widgetInfo ) { Map < String , ClientWidgetInfo > res = new HashMap < String , ClientWidgetInfo > ( ) ; for ( Map . Entry < String , ClientWidgetInfo > entry : widgetInfo . entrySet ( ) ) { ClientWidgetInfo value = entry . getValue ( ) ; if ( ! ( value instanceof ServerSideOnlyInfo ) ) { res . put ( entry . getKey ( ) , value ) ; } } return res ; }
Clone a widget info map considering what may be copied to the client .
117
15
623
public ClientLayerInfo securityClone ( ClientLayerInfo original ) { // the data is explicitly copied as this assures the security is considered when copying. if ( null == original ) { return null ; } ClientLayerInfo client = null ; String layerId = original . getServerLayerId ( ) ; if ( securityContext . isLayerVisible ( layerId ) ) { client = ( ClientLayerInfo ) SerializationUtils . clone ( original ) ; client . setWidgetInfo ( securityClone ( original . getWidgetInfo ( ) ) ) ; client . getLayerInfo ( ) . setExtraInfo ( securityCloneLayerExtraInfo ( original . getLayerInfo ( ) . getExtraInfo ( ) ) ) ; if ( client instanceof ClientVectorLayerInfo ) { ClientVectorLayerInfo vectorLayer = ( ClientVectorLayerInfo ) client ; // set statuses vectorLayer . setCreatable ( securityContext . isLayerCreateAuthorized ( layerId ) ) ; vectorLayer . setUpdatable ( securityContext . isLayerUpdateAuthorized ( layerId ) ) ; vectorLayer . setDeletable ( securityContext . isLayerDeleteAuthorized ( layerId ) ) ; // filter feature info FeatureInfo featureInfo = vectorLayer . getFeatureInfo ( ) ; List < AttributeInfo > originalAttr = featureInfo . getAttributes ( ) ; List < AttributeInfo > filteredAttr = new ArrayList < AttributeInfo > ( ) ; featureInfo . setAttributes ( filteredAttr ) ; for ( AttributeInfo ai : originalAttr ) { if ( securityContext . isAttributeReadable ( layerId , null , ai . getName ( ) ) ) { filteredAttr . add ( ai ) ; } } } } return client ; }
Clone layer information considering what may be copied to the client .
367
13
624
public String getKeyValue ( String key ) { String keyName = keysMap . get ( key ) ; if ( keyName != null ) { return keyName ; } return "" ; //key wasn't defined in keys properties file }
get the key name to use in log from the logging keys map
48
13
625
public static void serialize ( final File folder , final String content , final String fileName ) throws IOException { if ( ! folder . exists ( ) ) { folder . mkdirs ( ) ; } final File output = new File ( folder , fileName ) ; try ( final FileWriter writer = new FileWriter ( output ) ; ) { writer . write ( content ) ; writer . flush ( ) ; } catch ( Exception e ) { throw new IOException ( "Failed to serialize the notification in folder " + folder . getPath ( ) , e ) ; } }
Serialize a content into a targeted file checking that the parent directory exists .
120
15
626
public static String read ( final File file ) throws IOException { final StringBuilder sb = new StringBuilder ( ) ; try ( final FileReader fr = new FileReader ( file ) ; final BufferedReader br = new BufferedReader ( fr ) ; ) { String sCurrentLine ; while ( ( sCurrentLine = br . readLine ( ) ) != null ) { sb . append ( sCurrentLine ) ; } } return sb . toString ( ) ; }
Reads a file and returns the result in a String
100
11
627
public static Long getSize ( final File file ) { if ( file != null && file . exists ( ) ) { return file . length ( ) ; } return null ; }
Get file size
36
3
628
public static void touch ( final File folder , final String fileName ) throws IOException { if ( ! folder . exists ( ) ) { folder . mkdirs ( ) ; } final File touchedFile = new File ( folder , fileName ) ; // The JVM will only 'touch' the file if you instantiate a // FileOutputStream instance for the file in question. // You don't actually write any data to the file through // the FileOutputStream. Just instantiate it and close it. try ( FileOutputStream doneFOS = new FileOutputStream ( touchedFile ) ; ) { // Touching the file } catch ( FileNotFoundException e ) { throw new FileNotFoundException ( "Failed to the find file." + e ) ; } }
Creates a file
160
4
629
private void init ( final List < DbLicense > licenses ) { licensesRegexp . clear ( ) ; for ( final DbLicense license : licenses ) { if ( license . getRegexp ( ) == null || license . getRegexp ( ) . isEmpty ( ) ) { licensesRegexp . put ( license . getName ( ) , license ) ; } else { licensesRegexp . put ( license . getRegexp ( ) , license ) ; } } }
Init the licenses cache
104
4
630
public DbLicense getLicense ( final String name ) { final DbLicense license = repoHandler . getLicense ( name ) ; if ( license == null ) { throw new WebApplicationException ( Response . status ( Response . Status . NOT_FOUND ) . entity ( "License " + name + " does not exist." ) . build ( ) ) ; } return license ; }
Return a html view that contains the targeted license
79
9
631
public void deleteLicense ( final String licName ) { final DbLicense dbLicense = getLicense ( licName ) ; repoHandler . deleteLicense ( dbLicense . getName ( ) ) ; final FiltersHolder filters = new FiltersHolder ( ) ; final LicenseIdFilter licenseIdFilter = new LicenseIdFilter ( licName ) ; filters . addFilter ( licenseIdFilter ) ; for ( final DbArtifact artifact : repoHandler . getArtifacts ( filters ) ) { repoHandler . removeLicenseFromArtifact ( artifact , licName , this ) ; } }
Delete a license from the repository
121
6
632
public DbLicense resolve ( final String licenseId ) { for ( final Entry < String , DbLicense > regexp : licensesRegexp . entrySet ( ) ) { try { if ( licenseId . matches ( regexp . getKey ( ) ) ) { return regexp . getValue ( ) ; } } catch ( PatternSyntaxException e ) { LOG . error ( "Wrong pattern for the following license " + regexp . getValue ( ) . getName ( ) , e ) ; continue ; } } if ( LOG . isWarnEnabled ( ) ) { LOG . warn ( String . format ( "No matching pattern for license %s" , licenseId ) ) ; } return null ; }
Resolve the targeted license thanks to the license ID Return null if no license is matching the licenseId
150
20
633
public Set < DbLicense > resolveLicenses ( List < String > licStrings ) { Set < DbLicense > result = new HashSet <> ( ) ; licStrings . stream ( ) . map ( this :: getMatchingLicenses ) . forEach ( result :: addAll ) ; return result ; }
Turns a series of strings into their corresponding license entities by using regular expressions
68
15
634
private void verityLicenseIsConflictFree ( final DbLicense newComer ) { if ( newComer . getRegexp ( ) == null || newComer . getRegexp ( ) . isEmpty ( ) ) { return ; } final DbLicense existing = repoHandler . getLicense ( newComer . getName ( ) ) ; final List < DbLicense > licenses = repoHandler . getAllLicenses ( ) ; if ( null == existing ) { licenses . add ( newComer ) ; } else { existing . setRegexp ( newComer . getRegexp ( ) ) ; } final Optional < Report > reportOp = ReportsRegistry . findById ( MULTIPLE_LICENSE_MATCHING_STRINGS ) ; if ( reportOp . isPresent ( ) ) { final Report reportDef = reportOp . get ( ) ; ReportRequest reportRequest = new ReportRequest ( ) ; reportRequest . setReportId ( reportDef . getId ( ) ) ; Map < String , String > params = new HashMap <> ( ) ; // // TODO: Make the organization come as an external parameter from the client side. // This may have impact on the UI, as when the user will update a license he will // have to specify which organization he's editing the license for (in case there // are more organizations defined in the collection). // params . put ( "organization" , "Axway" ) ; reportRequest . setParamValues ( params ) ; final RepositoryHandler wrapped = wrapperBuilder . start ( repoHandler ) . replaceGetMethod ( "getAllLicenses" , licenses ) . build ( ) ; final ReportExecution execution = reportDef . execute ( wrapped , reportRequest ) ; List < String [ ] > data = execution . getData ( ) ; final Optional < String [ ] > first = data . stream ( ) . filter ( strings -> strings [ 2 ] . contains ( newComer . getName ( ) ) ) . findFirst ( ) ; if ( first . isPresent ( ) ) { final String [ ] strings = first . get ( ) ; final String message = String . format ( "Pattern conflict for string entry %s matching multiple licenses: %s" , strings [ 1 ] , strings [ 2 ] ) ; LOG . info ( message ) ; throw new WebApplicationException ( Response . status ( Response . Status . BAD_REQUEST ) . entity ( message ) . build ( ) ) ; } else { if ( ! data . isEmpty ( ) && ! data . get ( 0 ) [ 2 ] . isEmpty ( ) ) { LOG . info ( "There are remote conflicts between existing licenses and artifact strings" ) ; } } } else { if ( LOG . isWarnEnabled ( ) ) { LOG . warn ( String . format ( "Cannot find report by id %s" , MULTIPLE_LICENSE_MATCHING_STRINGS ) ) ; } } }
Check if new license pattern is valid and doesn t match any existing one
626
14
635
public List < Dependency > getModuleDependencies ( final String moduleId , final FiltersHolder filters ) { final DbModule module = moduleHandler . getModule ( moduleId ) ; final DbOrganization organization = moduleHandler . getOrganization ( module ) ; filters . setCorporateFilter ( new CorporateFilter ( organization ) ) ; return getModuleDependencies ( module , filters , 1 , new ArrayList < String > ( ) ) ; }
Returns the list of module dependencies regarding the provided filters
97
10
636
public DependencyReport getDependencyReport ( final String moduleId , final FiltersHolder filters ) { final DbModule module = moduleHandler . getModule ( moduleId ) ; final DbOrganization organization = moduleHandler . getOrganization ( module ) ; filters . setCorporateFilter ( new CorporateFilter ( organization ) ) ; final DependencyReport report = new DependencyReport ( moduleId ) ; final List < String > done = new ArrayList < String > ( ) ; for ( final DbModule submodule : DataUtils . getAllSubmodules ( module ) ) { done . add ( submodule . getId ( ) ) ; } addModuleToReport ( report , module , filters , done , 1 ) ; return report ; }
Generate a report about the targeted module dependencies
158
9
637
public final boolean roll ( final LoggingEvent loggingEvent ) { for ( int i = 0 ; i < this . fileRollables . length ; i ++ ) { if ( this . fileRollables [ i ] . roll ( loggingEvent ) ) { return true ; } } return false ; }
Delegates file rolling to composed objects .
61
8
638
public boolean isPartOf ( GetVectorTileRequest request ) { if ( Math . abs ( request . scale - scale ) > EQUALS_DELTA ) { return false ; } if ( code != null ? ! code . equals ( request . code ) : request . code != null ) { return false ; } if ( crs != null ? ! crs . equals ( request . crs ) : request . crs != null ) { return false ; } if ( filter != null ? ! filter . equals ( request . filter ) : request . filter != null ) { return false ; } if ( panOrigin != null ? ! panOrigin . equals ( request . panOrigin ) : request . panOrigin != null ) { return false ; } if ( renderer != null ? ! renderer . equals ( request . renderer ) : request . renderer != null ) { return false ; } if ( styleInfo != null ? ! styleInfo . equals ( request . styleInfo ) : request . styleInfo != null ) { return false ; } if ( paintGeometries && ! request . paintGeometries ) { return false ; } if ( paintLabels && ! request . paintLabels ) { return false ; } return true ; }
Check if this request is part of the specified request . This is the case if both requests have equal properties and the specified request is asking for the same or more paint operations than this one .
258
38
639
@ PostConstruct protected void checkPluginDependencies ( ) throws GeomajasException { if ( "true" . equals ( System . getProperty ( "skipPluginDependencyCheck" ) ) ) { return ; } if ( null == declaredPlugins ) { return ; } // start by going through all plug-ins to build a map of versions for plug-in keys // includes verification that each key is only used once Map < String , String > versions = new HashMap < String , String > ( ) ; for ( PluginInfo plugin : declaredPlugins . values ( ) ) { String name = plugin . getVersion ( ) . getName ( ) ; String version = plugin . getVersion ( ) . getVersion ( ) ; // check for multiple plugin with same name but different versions (duplicates allowed for jar+source dep) if ( null != version ) { String otherVersion = versions . get ( name ) ; if ( null != otherVersion ) { if ( ! version . startsWith ( EXPR_START ) ) { if ( ! otherVersion . startsWith ( EXPR_START ) && ! otherVersion . equals ( version ) ) { throw new GeomajasException ( ExceptionCode . DEPENDENCY_CHECK_INVALID_DUPLICATE , name , version , versions . get ( name ) ) ; } versions . put ( name , version ) ; } } else { versions . put ( name , version ) ; } } } // Check dependencies StringBuilder message = new StringBuilder ( ) ; String backendVersion = versions . get ( "Geomajas" ) ; for ( PluginInfo plugin : declaredPlugins . values ( ) ) { String name = plugin . getVersion ( ) . getName ( ) ; message . append ( checkVersion ( name , "Geomajas back-end" , plugin . getBackendVersion ( ) , backendVersion ) ) ; List < PluginVersionInfo > dependencies = plugin . getDependencies ( ) ; if ( null != dependencies ) { for ( PluginVersionInfo dependency : plugin . getDependencies ( ) ) { String depName = dependency . getName ( ) ; message . append ( checkVersion ( name , depName , dependency . getVersion ( ) , versions . get ( depName ) ) ) ; } } dependencies = plugin . getOptionalDependencies ( ) ; if ( null != dependencies ) { for ( PluginVersionInfo dependency : dependencies ) { String depName = dependency . getName ( ) ; String availableVersion = versions . get ( depName ) ; if ( null != availableVersion ) { message . append ( checkVersion ( name , depName , dependency . getVersion ( ) , versions . get ( depName ) ) ) ; } } } } if ( message . length ( ) > 0 ) { throw new GeomajasException ( ExceptionCode . DEPENDENCY_CHECK_FAILED , message . toString ( ) ) ; } recorder . record ( GROUP , VALUE ) ; }
Finish initializing .
629
4
640
String checkVersion ( String pluginName , String dependency , String requestedVersion , String availableVersion ) { if ( null == availableVersion ) { return "Dependency " + dependency + " not found for " + pluginName + ", version " + requestedVersion + " or higher needed.\n" ; } if ( requestedVersion . startsWith ( EXPR_START ) || availableVersion . startsWith ( EXPR_START ) ) { return "" ; } Version requested = new Version ( requestedVersion ) ; Version available = new Version ( availableVersion ) ; if ( requested . getMajor ( ) != available . getMajor ( ) ) { return "Dependency " + dependency + " is provided in a incompatible API version for plug-in " + pluginName + ", which requests version " + requestedVersion + ", but version " + availableVersion + " supplied.\n" ; } if ( requested . after ( available ) ) { return "Dependency " + dependency + " too old for " + pluginName + ", version " + requestedVersion + " or higher needed, but version " + availableVersion + " supplied.\n" ; } return "" ; }
Check the version to assure it is allowed .
243
9
641
public void check ( ClassDescriptorDef classDef , String checkLevel ) throws ConstraintException { ensureNoTableInfoIfNoRepositoryInfo ( classDef , checkLevel ) ; checkModifications ( classDef , checkLevel ) ; checkExtents ( classDef , checkLevel ) ; ensureTableIfNecessary ( classDef , checkLevel ) ; checkFactoryClassAndMethod ( classDef , checkLevel ) ; checkInitializationMethod ( classDef , checkLevel ) ; checkPrimaryKey ( classDef , checkLevel ) ; checkProxyPrefetchingLimit ( classDef , checkLevel ) ; checkRowReader ( classDef , checkLevel ) ; checkObjectCache ( classDef , checkLevel ) ; checkProcedures ( classDef , checkLevel ) ; }
Checks the given class descriptor .
161
7
642
private void ensureNoTableInfoIfNoRepositoryInfo ( ClassDescriptorDef classDef , String checkLevel ) { if ( ! classDef . getBooleanProperty ( PropertyHelper . OJB_PROPERTY_GENERATE_REPOSITORY_INFO , true ) ) { classDef . setProperty ( PropertyHelper . OJB_PROPERTY_GENERATE_TABLE_INFO , "false" ) ; } }
Ensures that generate - table - info is set to false if generate - repository - info is set to false .
92
24
643
private void checkModifications ( ClassDescriptorDef classDef , String checkLevel ) throws ConstraintException { if ( CHECKLEVEL_NONE . equals ( checkLevel ) ) { return ; } HashMap features = new HashMap ( ) ; FeatureDescriptorDef def ; for ( Iterator it = classDef . getFields ( ) ; it . hasNext ( ) ; ) { def = ( FeatureDescriptorDef ) it . next ( ) ; features . put ( def . getName ( ) , def ) ; } for ( Iterator it = classDef . getReferences ( ) ; it . hasNext ( ) ; ) { def = ( FeatureDescriptorDef ) it . next ( ) ; features . put ( def . getName ( ) , def ) ; } for ( Iterator it = classDef . getCollections ( ) ; it . hasNext ( ) ; ) { def = ( FeatureDescriptorDef ) it . next ( ) ; features . put ( def . getName ( ) , def ) ; } // now checking the modifications Properties mods ; String modName ; String propName ; for ( Iterator it = classDef . getModificationNames ( ) ; it . hasNext ( ) ; ) { modName = ( String ) it . next ( ) ; if ( ! features . containsKey ( modName ) ) { throw new ConstraintException ( "Class " + classDef . getName ( ) + " contains a modification for an unknown feature " + modName ) ; } def = ( FeatureDescriptorDef ) features . get ( modName ) ; if ( def . getOriginal ( ) == null ) { throw new ConstraintException ( "Class " + classDef . getName ( ) + " contains a modification for a feature " + modName + " that is not inherited but defined in the same class" ) ; } // checking modification mods = classDef . getModification ( modName ) ; for ( Iterator propIt = mods . keySet ( ) . iterator ( ) ; propIt . hasNext ( ) ; ) { propName = ( String ) propIt . next ( ) ; if ( ! PropertyHelper . isPropertyAllowed ( def . getClass ( ) , propName ) ) { throw new ConstraintException ( "The modification of attribute " + propName + " in class " + classDef . getName ( ) + " is not applicable to the feature " + modName ) ; } } } }
Checks that the modified features exist .
524
8
644
private void checkExtents ( ClassDescriptorDef classDef , String checkLevel ) throws ConstraintException { if ( CHECKLEVEL_NONE . equals ( checkLevel ) ) { return ; } HashMap processedClasses = new HashMap ( ) ; InheritanceHelper helper = new InheritanceHelper ( ) ; ClassDescriptorDef curExtent ; boolean canBeRemoved ; for ( Iterator it = classDef . getExtentClasses ( ) ; it . hasNext ( ) ; ) { curExtent = ( ClassDescriptorDef ) it . next ( ) ; canBeRemoved = false ; if ( classDef . getName ( ) . equals ( curExtent . getName ( ) ) ) { throw new ConstraintException ( "The class " + classDef . getName ( ) + " specifies itself as an extent-class" ) ; } else if ( processedClasses . containsKey ( curExtent ) ) { canBeRemoved = true ; } else { try { if ( ! helper . isSameOrSubTypeOf ( curExtent , classDef . getName ( ) , false ) ) { throw new ConstraintException ( "The class " + classDef . getName ( ) + " specifies an extent-class " + curExtent . getName ( ) + " that is not a sub-type of it" ) ; } // now we check whether we already have an extent for a base-class of this extent-class for ( Iterator processedIt = processedClasses . keySet ( ) . iterator ( ) ; processedIt . hasNext ( ) ; ) { if ( helper . isSameOrSubTypeOf ( curExtent , ( ( ClassDescriptorDef ) processedIt . next ( ) ) . getName ( ) , false ) ) { canBeRemoved = true ; break ; } } } catch ( ClassNotFoundException ex ) { // won't happen because we don't use lookup of the actual classes } } if ( canBeRemoved ) { it . remove ( ) ; } processedClasses . put ( curExtent , null ) ; } }
Checks the extents specifications and removes unnecessary entries .
447
11
645
private void checkInitializationMethod ( ClassDescriptorDef classDef , String checkLevel ) throws ConstraintException { if ( ! CHECKLEVEL_STRICT . equals ( checkLevel ) ) { return ; } String initMethodName = classDef . getProperty ( PropertyHelper . OJB_PROPERTY_INITIALIZATION_METHOD ) ; if ( initMethodName == null ) { return ; } Class initClass ; Method initMethod ; try { initClass = InheritanceHelper . getClass ( classDef . getName ( ) ) ; } catch ( ClassNotFoundException ex ) { throw new ConstraintException ( "The class " + classDef . getName ( ) + " was not found on the classpath" ) ; } try { initMethod = initClass . getDeclaredMethod ( initMethodName , new Class [ 0 ] ) ; } catch ( NoSuchMethodException ex ) { initMethod = null ; } catch ( Exception ex ) { throw new ConstraintException ( "Exception while checking the class " + classDef . getName ( ) + ": " + ex . getMessage ( ) ) ; } if ( initMethod == null ) { try { initMethod = initClass . getMethod ( initMethodName , new Class [ 0 ] ) ; } catch ( NoSuchMethodException ex ) { throw new ConstraintException ( "No suitable initialization-method " + initMethodName + " found in class " + classDef . getName ( ) ) ; } catch ( Exception ex ) { throw new ConstraintException ( "Exception while checking the class " + classDef . getName ( ) + ": " + ex . getMessage ( ) ) ; } } // checking modifiers int mods = initMethod . getModifiers ( ) ; if ( Modifier . isStatic ( mods ) || Modifier . isAbstract ( mods ) ) { throw new ConstraintException ( "The initialization-method " + initMethodName + " in class " + classDef . getName ( ) + " must be a concrete instance method" ) ; } }
Checks the initialization - method of given class descriptor .
438
11
646
private void checkPrimaryKey ( ClassDescriptorDef classDef , String checkLevel ) throws ConstraintException { if ( CHECKLEVEL_NONE . equals ( checkLevel ) ) { return ; } if ( classDef . getBooleanProperty ( PropertyHelper . OJB_PROPERTY_GENERATE_TABLE_INFO , true ) && classDef . getPrimaryKeys ( ) . isEmpty ( ) ) { LogHelper . warn ( true , getClass ( ) , "checkPrimaryKey" , "The class " + classDef . getName ( ) + " has no primary key" ) ; } }
Checks whether given class descriptor has a primary key .
131
11
647
private void checkRowReader ( ClassDescriptorDef classDef , String checkLevel ) throws ConstraintException { if ( ! CHECKLEVEL_STRICT . equals ( checkLevel ) ) { return ; } String rowReaderName = classDef . getProperty ( PropertyHelper . OJB_PROPERTY_ROW_READER ) ; if ( rowReaderName == null ) { return ; } try { InheritanceHelper helper = new InheritanceHelper ( ) ; if ( ! helper . isSameOrSubTypeOf ( rowReaderName , ROW_READER_INTERFACE ) ) { throw new ConstraintException ( "The class " + rowReaderName + " specified as row-reader of class " + classDef . getName ( ) + " does not implement the interface " + ROW_READER_INTERFACE ) ; } } catch ( ClassNotFoundException ex ) { throw new ConstraintException ( "Could not find the class " + ex . getMessage ( ) + " on the classpath while checking the row-reader class " + rowReaderName + " of class " + classDef . getName ( ) ) ; } }
Checks the given class descriptor for correct row - reader setting .
245
13
648
private void checkObjectCache ( ClassDescriptorDef classDef , String checkLevel ) throws ConstraintException { if ( ! CHECKLEVEL_STRICT . equals ( checkLevel ) ) { return ; } ObjectCacheDef objCacheDef = classDef . getObjectCache ( ) ; if ( objCacheDef == null ) { return ; } String objectCacheName = objCacheDef . getName ( ) ; if ( ( objectCacheName == null ) || ( objectCacheName . length ( ) == 0 ) ) { throw new ConstraintException ( "No class specified for the object-cache of class " + classDef . getName ( ) ) ; } try { InheritanceHelper helper = new InheritanceHelper ( ) ; if ( ! helper . isSameOrSubTypeOf ( objectCacheName , OBJECT_CACHE_INTERFACE ) ) { throw new ConstraintException ( "The class " + objectCacheName + " specified as object-cache of class " + classDef . getName ( ) + " does not implement the interface " + OBJECT_CACHE_INTERFACE ) ; } } catch ( ClassNotFoundException ex ) { throw new ConstraintException ( "Could not find the class " + ex . getMessage ( ) + " on the classpath while checking the object-cache class " + objectCacheName + " of class " + classDef . getName ( ) ) ; } }
Checks the given class descriptor for correct object cache setting .
302
12
649
private void checkProcedures ( ClassDescriptorDef classDef , String checkLevel ) throws ConstraintException { if ( CHECKLEVEL_NONE . equals ( checkLevel ) ) { return ; } ProcedureDef procDef ; String type ; String name ; String fieldName ; String argName ; for ( Iterator it = classDef . getProcedures ( ) ; it . hasNext ( ) ; ) { procDef = ( ProcedureDef ) it . next ( ) ; type = procDef . getName ( ) ; name = procDef . getProperty ( PropertyHelper . OJB_PROPERTY_NAME ) ; if ( ( name == null ) || ( name . length ( ) == 0 ) ) { throw new ConstraintException ( "The " + type + "-procedure in class " + classDef . getName ( ) + " doesn't have a name" ) ; } fieldName = procDef . getProperty ( PropertyHelper . OJB_PROPERTY_RETURN_FIELD_REF ) ; if ( ( fieldName != null ) && ( fieldName . length ( ) > 0 ) ) { if ( classDef . getField ( fieldName ) == null ) { throw new ConstraintException ( "The " + type + "-procedure " + name + " in class " + classDef . getName ( ) + " references an unknown or non-persistent return field " + fieldName ) ; } } for ( CommaListIterator argIt = new CommaListIterator ( procDef . getProperty ( PropertyHelper . OJB_PROPERTY_ARGUMENTS ) ) ; argIt . hasNext ( ) ; ) { argName = argIt . getNext ( ) ; if ( classDef . getProcedureArgument ( argName ) == null ) { throw new ConstraintException ( "The " + type + "-procedure " + name + " in class " + classDef . getName ( ) + " references an unknown argument " + argName ) ; } } } ProcedureArgumentDef argDef ; for ( Iterator it = classDef . getProcedureArguments ( ) ; it . hasNext ( ) ; ) { argDef = ( ProcedureArgumentDef ) it . next ( ) ; type = argDef . getProperty ( PropertyHelper . OJB_PROPERTY_TYPE ) ; if ( "runtime" . equals ( type ) ) { fieldName = argDef . getProperty ( PropertyHelper . OJB_PROPERTY_FIELD_REF ) ; if ( ( fieldName != null ) && ( fieldName . length ( ) > 0 ) ) { if ( classDef . getField ( fieldName ) == null ) { throw new ConstraintException ( "The " + type + "-argument " + argDef . getName ( ) + " in class " + classDef . getName ( ) + " references an unknown or non-persistent return field " + fieldName ) ; } } } } }
Checks the given class descriptor for correct procedure settings .
635
11
650
OTMConnection getConnection ( ) { if ( m_connection == null ) { OTMConnectionRuntimeException ex = new OTMConnectionRuntimeException ( "Connection is null." ) ; sendEvents ( ConnectionEvent . CONNECTION_ERROR_OCCURRED , ex , null ) ; } return m_connection ; }
get the underlying wrapped connection
67
5
651
private Integer getReleaseId ( ) { final String [ ] versionParts = stringVersion . split ( "-" ) ; if ( isBranch ( ) && versionParts . length >= 3 ) { return Integer . valueOf ( versionParts [ 2 ] ) ; } else if ( versionParts . length >= 2 ) { return Integer . valueOf ( versionParts [ 1 ] ) ; } return 0 ; }
Return the releaseId
83
4
652
public int compare ( final Version other ) throws IncomparableException { // Cannot compare branch versions and others if ( ! isBranch ( ) . equals ( other . isBranch ( ) ) ) { throw new IncomparableException ( ) ; } // Compare digits final int minDigitSize = getDigitsSize ( ) < other . getDigitsSize ( ) ? getDigitsSize ( ) : other . getDigitsSize ( ) ; for ( int i = 0 ; i < minDigitSize ; i ++ ) { if ( ! getDigit ( i ) . equals ( other . getDigit ( i ) ) ) { return getDigit ( i ) . compareTo ( other . getDigit ( i ) ) ; } } // If not the same number of digits and the first digits are equals, the longest is the newer if ( ! getDigitsSize ( ) . equals ( other . getDigitsSize ( ) ) ) { return getDigitsSize ( ) > other . getDigitsSize ( ) ? 1 : - 1 ; } if ( isBranch ( ) && ! getBranchId ( ) . equals ( other . getBranchId ( ) ) ) { return getBranchId ( ) . compareTo ( other . getBranchId ( ) ) ; } // if the digits are the same, a snapshot is newer than a release if ( isSnapshot ( ) && other . isRelease ( ) ) { return 1 ; } if ( isRelease ( ) && other . isSnapshot ( ) ) { return - 1 ; } // if both versions are releases, compare the releaseID if ( isRelease ( ) && other . isRelease ( ) ) { return getReleaseId ( ) . compareTo ( other . getReleaseId ( ) ) ; } return 0 ; }
Compare two versions
381
3
653
public void calculateSize ( PdfContext context ) { float width = 0 ; float height = 0 ; for ( PrintComponent < ? > child : children ) { child . calculateSize ( context ) ; float cw = child . getBounds ( ) . getWidth ( ) + 2 * child . getConstraint ( ) . getMarginX ( ) ; float ch = child . getBounds ( ) . getHeight ( ) + 2 * child . getConstraint ( ) . getMarginY ( ) ; switch ( getConstraint ( ) . getFlowDirection ( ) ) { case LayoutConstraint . FLOW_NONE : width = Math . max ( width , cw ) ; height = Math . max ( height , ch ) ; break ; case LayoutConstraint . FLOW_X : width += cw ; height = Math . max ( height , ch ) ; break ; case LayoutConstraint . FLOW_Y : width = Math . max ( width , cw ) ; height += ch ; break ; default : throw new IllegalStateException ( "Unknown flow direction " + getConstraint ( ) . getFlowDirection ( ) ) ; } } if ( getConstraint ( ) . getWidth ( ) != 0 ) { width = getConstraint ( ) . getWidth ( ) ; } if ( getConstraint ( ) . getHeight ( ) != 0 ) { height = getConstraint ( ) . getHeight ( ) ; } setBounds ( new Rectangle ( 0 , 0 , width , height ) ) ; }
Calculates the size based constraint width and height if present otherwise from children sizes .
336
17
654
public void setChildren ( List < PrintComponent < ? > > children ) { this . children = children ; // needed for Json unmarshall !!!! for ( PrintComponent < ? > child : children ) { child . setParent ( this ) ; } }
Set child components .
54
4
655
public void remove ( Identity oid ) { //processQueue(); if ( oid != null ) { removeTracedIdentity ( oid ) ; objectTable . remove ( buildKey ( oid ) ) ; if ( log . isDebugEnabled ( ) ) log . debug ( "Remove object " + oid ) ; } }
Removes an Object from the cache .
69
8
656
public List < DbComment > getComments ( String entityId , String entityType ) { return repositoryHandler . getComments ( entityId , entityType ) ; }
Get a list of comments made for a particular entity
34
10
657
public void store ( String gavc , String action , String commentText , DbCredential credential , String entityType ) { DbComment comment = new DbComment ( ) ; comment . setEntityId ( gavc ) ; comment . setEntityType ( entityType ) ; comment . setDbCommentedBy ( credential . getUser ( ) ) ; comment . setAction ( action ) ; if ( ! commentText . isEmpty ( ) ) { comment . setDbCommentText ( commentText ) ; } comment . setDbCreatedDateTime ( new Date ( ) ) ; repositoryHandler . store ( comment ) ; }
Store a comment based on comment text gavc and user information
132
13
658
private boolean relevant ( File currentLogFile , GregorianCalendar lastRelevantDate ) { String fileName = currentLogFile . getName ( ) ; Pattern p = Pattern . compile ( APPENER_DATE_DEFAULT_PATTERN ) ; Matcher m = p . matcher ( fileName ) ; if ( m . find ( ) ) { int year = Integer . parseInt ( m . group ( 1 ) ) ; int month = Integer . parseInt ( m . group ( 2 ) ) ; int dayOfMonth = Integer . parseInt ( m . group ( 3 ) ) ; GregorianCalendar fileDate = new GregorianCalendar ( year , month , dayOfMonth ) ; fileDate . add ( Calendar . MONTH , - 1 ) ; //Because of Calendar save the month such that January is 0 return fileDate . compareTo ( lastRelevantDate ) > 0 ; } else { return false ; } }
Get a log file and last relevant date and check if the log file is relevant
197
16
659
private GregorianCalendar getLastReleventDate ( GregorianCalendar currentDate ) { int age = this . getProperties ( ) . getMaxFileAge ( ) ; GregorianCalendar result = new GregorianCalendar ( currentDate . get ( Calendar . YEAR ) , currentDate . get ( Calendar . MONTH ) , currentDate . get ( Calendar . DAY_OF_MONTH ) ) ; result . add ( Calendar . DAY_OF_MONTH , - age ) ; return result ; }
Get the last date to keep logs from by a given current date .
108
14
660
private ColumnDef addColumnFor ( FieldDescriptorDef fieldDef , TableDef tableDef ) { String name = fieldDef . getProperty ( PropertyHelper . OJB_PROPERTY_COLUMN ) ; ColumnDef columnDef = tableDef . getColumn ( name ) ; if ( columnDef == null ) { columnDef = new ColumnDef ( name ) ; tableDef . addColumn ( columnDef ) ; } if ( ! fieldDef . isNested ( ) ) { columnDef . setProperty ( PropertyHelper . TORQUE_PROPERTY_JAVANAME , fieldDef . getName ( ) ) ; } columnDef . setProperty ( PropertyHelper . TORQUE_PROPERTY_TYPE , fieldDef . getProperty ( PropertyHelper . OJB_PROPERTY_JDBC_TYPE ) ) ; columnDef . setProperty ( PropertyHelper . TORQUE_PROPERTY_ID , fieldDef . getProperty ( PropertyHelper . OJB_PROPERTY_ID ) ) ; if ( fieldDef . getBooleanProperty ( PropertyHelper . OJB_PROPERTY_PRIMARYKEY , false ) ) { columnDef . setProperty ( PropertyHelper . TORQUE_PROPERTY_PRIMARYKEY , "true" ) ; columnDef . setProperty ( PropertyHelper . TORQUE_PROPERTY_REQUIRED , "true" ) ; } else if ( ! fieldDef . getBooleanProperty ( PropertyHelper . OJB_PROPERTY_NULLABLE , true ) ) { columnDef . setProperty ( PropertyHelper . TORQUE_PROPERTY_REQUIRED , "true" ) ; } if ( "database" . equals ( fieldDef . getProperty ( PropertyHelper . OJB_PROPERTY_AUTOINCREMENT ) ) ) { columnDef . setProperty ( PropertyHelper . TORQUE_PROPERTY_AUTOINCREMENT , "true" ) ; } columnDef . setProperty ( PropertyHelper . TORQUE_PROPERTY_SIZE , fieldDef . getSizeConstraint ( ) ) ; if ( fieldDef . hasProperty ( PropertyHelper . OJB_PROPERTY_DOCUMENTATION ) ) { columnDef . setProperty ( PropertyHelper . OJB_PROPERTY_DOCUMENTATION , fieldDef . getProperty ( PropertyHelper . OJB_PROPERTY_DOCUMENTATION ) ) ; } if ( fieldDef . hasProperty ( PropertyHelper . OJB_PROPERTY_COLUMN_DOCUMENTATION ) ) { columnDef . setProperty ( PropertyHelper . OJB_PROPERTY_COLUMN_DOCUMENTATION , fieldDef . getProperty ( PropertyHelper . OJB_PROPERTY_COLUMN_DOCUMENTATION ) ) ; } return columnDef ; }
Generates a column for the given field and adds it to the table .
603
15
661
private List getColumns ( List fields ) { ArrayList columns = new ArrayList ( ) ; for ( Iterator it = fields . iterator ( ) ; it . hasNext ( ) ; ) { FieldDescriptorDef fieldDef = ( FieldDescriptorDef ) it . next ( ) ; columns . add ( fieldDef . getProperty ( PropertyHelper . OJB_PROPERTY_COLUMN ) ) ; } return columns ; }
Extracts the list of columns from the given field list .
93
13
662
private boolean containsCollectionAndMapsToDifferentTable ( CollectionDescriptorDef origCollDef , TableDef origTableDef , ClassDescriptorDef classDef ) { if ( classDef . getBooleanProperty ( PropertyHelper . OJB_PROPERTY_GENERATE_TABLE_INFO , true ) && ! origTableDef . getName ( ) . equals ( classDef . getProperty ( PropertyHelper . OJB_PROPERTY_TABLE ) ) ) { CollectionDescriptorDef curCollDef = classDef . getCollection ( origCollDef . getName ( ) ) ; if ( ( curCollDef != null ) && ! curCollDef . getBooleanProperty ( PropertyHelper . OJB_PROPERTY_IGNORE , false ) ) { return true ; } } return false ; }
Checks whether the given class maps to a different table but also has the given collection .
169
18
663
private String getHierarchyTable ( ClassDescriptorDef classDef ) { ArrayList queue = new ArrayList ( ) ; String tableName = null ; queue . add ( classDef ) ; while ( ! queue . isEmpty ( ) ) { ClassDescriptorDef curClassDef = ( ClassDescriptorDef ) queue . get ( 0 ) ; queue . remove ( 0 ) ; if ( curClassDef . getBooleanProperty ( PropertyHelper . OJB_PROPERTY_GENERATE_TABLE_INFO , true ) ) { if ( tableName != null ) { if ( ! tableName . equals ( curClassDef . getProperty ( PropertyHelper . OJB_PROPERTY_TABLE ) ) ) { return null ; } } else { tableName = curClassDef . getProperty ( PropertyHelper . OJB_PROPERTY_TABLE ) ; } } for ( Iterator it = curClassDef . getExtentClasses ( ) ; it . hasNext ( ) ; ) { curClassDef = ( ClassDescriptorDef ) it . next ( ) ; if ( curClassDef . getReference ( "super" ) == null ) { queue . add ( curClassDef ) ; } } } return tableName ; }
Tries to return the single table to which all classes in the hierarchy with the given class as the root map .
263
23
664
private void addIndex ( IndexDescriptorDef indexDescDef , TableDef tableDef ) { IndexDef indexDef = tableDef . getIndex ( indexDescDef . getName ( ) ) ; if ( indexDef == null ) { indexDef = new IndexDef ( indexDescDef . getName ( ) , indexDescDef . getBooleanProperty ( PropertyHelper . OJB_PROPERTY_UNIQUE , false ) ) ; tableDef . addIndex ( indexDef ) ; } try { String fieldNames = indexDescDef . getProperty ( PropertyHelper . OJB_PROPERTY_FIELDS ) ; ArrayList fields = ( ( ClassDescriptorDef ) indexDescDef . getOwner ( ) ) . getFields ( fieldNames ) ; FieldDescriptorDef fieldDef ; for ( Iterator it = fields . iterator ( ) ; it . hasNext ( ) ; ) { fieldDef = ( FieldDescriptorDef ) it . next ( ) ; indexDef . addColumn ( fieldDef . getProperty ( PropertyHelper . OJB_PROPERTY_COLUMN ) ) ; } } catch ( NoSuchFieldException ex ) { // won't happen if we already checked the constraints } }
Adds an index to the table for the given index descriptor .
257
12
665
private void addTable ( TableDef table ) { table . setOwner ( this ) ; _tableDefs . put ( table . getName ( ) , table ) ; }
Adds a table to this model .
36
7
666
public static Class getClass ( String name ) throws ClassNotFoundException { try { return Class . forName ( name ) ; } catch ( ClassNotFoundException ex ) { throw new ClassNotFoundException ( name ) ; } }
Retrieves the class object for the class with the given name .
48
14
667
public void cache ( Identity oid , Object obj ) { if ( oid != null && obj != null ) { ObjectCache cache = getCache ( oid , obj , METHOD_CACHE ) ; if ( cache != null ) { cache . cache ( oid , obj ) ; } } }
Caches the given object using the given Identity as key
64
11
668
public Object lookup ( Identity oid ) { Object ret = null ; if ( oid != null ) { ObjectCache cache = getCache ( oid , null , METHOD_LOOKUP ) ; if ( cache != null ) { ret = cache . lookup ( oid ) ; } } return ret ; }
Looks up the object from the cache
65
7
669
public void remove ( Identity oid ) { if ( oid == null ) return ; ObjectCache cache = getCache ( oid , null , METHOD_REMOVE ) ; if ( cache != null ) { cache . remove ( oid ) ; } }
Removes the given object from the cache
55
8
670
public static ResourceBundle getCurrentResourceBundle ( String locale ) { try { if ( null != locale && ! locale . isEmpty ( ) ) { return getCurrentResourceBundle ( LocaleUtils . toLocale ( locale ) ) ; } } catch ( IllegalArgumentException ex ) { // do nothing } return getCurrentResourceBundle ( ( Locale ) null ) ; }
Returns the resource bundle for current Locale i . e . locale set in the PageComponent . Always create a new instance this avoids getting the incorrect locale information .
82
32
671
private String getPropertyName ( Expression expression ) { if ( ! ( expression instanceof PropertyName ) ) { throw new IllegalArgumentException ( "Expression " + expression + " is not a PropertyName." ) ; } String name = ( ( PropertyName ) expression ) . getPropertyName ( ) ; if ( name . endsWith ( FilterService . ATTRIBUTE_ID ) ) { // replace by Hibernate id property, always refers to the id, even if named differently name = name . substring ( 0 , name . length ( ) - FilterService . ATTRIBUTE_ID . length ( ) ) + HIBERNATE_ID ; } return name ; }
Get the property name from the expression .
144
8
672
private Object getLiteralValue ( Expression expression ) { if ( ! ( expression instanceof Literal ) ) { throw new IllegalArgumentException ( "Expression " + expression + " is not a Literal." ) ; } return ( ( Literal ) expression ) . getValue ( ) ; }
Get the literal value for an expression .
63
8
673
private String parsePropertyName ( String orgPropertyName , Object userData ) { // try to assure the correct separator is used String propertyName = orgPropertyName . replace ( HibernateLayerUtil . XPATH_SEPARATOR , HibernateLayerUtil . SEPARATOR ) ; // split the path (separator is defined in the HibernateLayerUtil) String [ ] props = propertyName . split ( HibernateLayerUtil . SEPARATOR_REGEXP ) ; String finalName ; if ( props . length > 1 && userData instanceof Criteria ) { // the criteria API requires an alias for each join table !!! String prevAlias = null ; for ( int i = 0 ; i < props . length - 1 ; i ++ ) { String alias = props [ i ] + "_alias" ; if ( ! aliases . contains ( alias ) ) { Criteria criteria = ( Criteria ) userData ; if ( i == 0 ) { criteria . createAlias ( props [ 0 ] , alias ) ; } else { criteria . createAlias ( prevAlias + "." + props [ i ] , alias ) ; } aliases . add ( alias ) ; } prevAlias = alias ; } finalName = prevAlias + "." + props [ props . length - 1 ] ; } else { finalName = propertyName ; } return finalName ; }
Go through the property name to see if it is a complex one . If it is aliases must be declared .
291
22
674
public void afterCompletion ( int status ) { if ( afterCompletionCall ) return ; log . info ( "Method afterCompletion was called" ) ; try { switch ( status ) { case Status . STATUS_COMMITTED : if ( log . isDebugEnabled ( ) ) { log . debug ( "Method afterCompletion: Do commit internal odmg-tx, status of JTA-tx is " + TxUtil . getStatusString ( status ) ) ; } commit ( ) ; break ; default : log . error ( "Method afterCompletion: Do abort call on internal odmg-tx, status of JTA-tx is " + TxUtil . getStatusString ( status ) ) ; abort ( ) ; } } finally { afterCompletionCall = true ; log . info ( "Method afterCompletion finished" ) ; } }
FOR internal use . This method was called after the external transaction was completed .
183
15
675
public void beforeCompletion ( ) { // avoid redundant calls if ( beforeCompletionCall ) return ; log . info ( "Method beforeCompletion was called" ) ; int status = Status . STATUS_UNKNOWN ; try { JTATxManager mgr = ( JTATxManager ) getImplementation ( ) . getTxManager ( ) ; status = mgr . getJTATransaction ( ) . getStatus ( ) ; // ensure proper work, check all possible status // normally only check for 'STATUS_MARKED_ROLLBACK' is necessary if ( status == Status . STATUS_MARKED_ROLLBACK || status == Status . STATUS_ROLLEDBACK || status == Status . STATUS_ROLLING_BACK || status == Status . STATUS_UNKNOWN || status == Status . STATUS_NO_TRANSACTION ) { log . error ( "Synchronization#beforeCompletion: Can't prepare for commit, because tx status was " + TxUtil . getStatusString ( status ) + ". Do internal cleanup only." ) ; } else { if ( log . isDebugEnabled ( ) ) { log . debug ( "Synchronization#beforeCompletion: Prepare for commit" ) ; } // write objects to database prepareCommit ( ) ; } } catch ( Exception e ) { log . error ( "Synchronization#beforeCompletion: Error while prepare for commit" , e ) ; if ( e instanceof LockNotGrantedException ) { throw ( LockNotGrantedException ) e ; } else if ( e instanceof TransactionAbortedException ) { throw ( TransactionAbortedException ) e ; } else if ( e instanceof ODMGRuntimeException ) { throw ( ODMGRuntimeException ) e ; } else { throw new ODMGRuntimeException ( "Method beforeCompletion() fails, status of JTA-tx was " + TxUtil . getStatusString ( status ) + ", message: " + e . getMessage ( ) ) ; } } finally { beforeCompletionCall = true ; setInExternTransaction ( false ) ; internalCleanup ( ) ; } }
FOR internal use . This method was called before the external transaction was completed .
461
15
676
private void internalCleanup ( ) { if ( hasBroker ( ) ) { PersistenceBroker broker = getBroker ( ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Do internal cleanup and close the internal used connection without" + " closing the used broker" ) ; } ConnectionManagerIF cm = broker . serviceConnectionManager ( ) ; if ( cm . isInLocalTransaction ( ) ) { /* arminw: in managed environment this call will be ignored because, the JTA transaction manager control the connection status. But to make connectionManager happy we have to complete the "local tx" of the connectionManager before release the connection */ cm . localCommit ( ) ; } cm . releaseConnection ( ) ; } }
In managed environment do internal close the used connection
158
9
677
public void checkpoint ( ObjectEnvelope mod ) throws org . apache . ojb . broker . PersistenceBrokerException { mod . doUpdate ( ) ; }
checkpoint the transaction
36
4
678
@ Api public void setUrl ( String url ) throws LayerException { try { this . url = url ; Map < String , Object > params = new HashMap < String , Object > ( ) ; params . put ( "url" , url ) ; DataStore store = DataStoreFactory . create ( params ) ; setDataStore ( store ) ; } catch ( IOException ioe ) { throw new LayerException ( ioe , ExceptionCode . INVALID_SHAPE_FILE_URL , url ) ; } }
Set the url for the shape file .
109
8
679
private void beginInternTransaction ( ) { if ( log . isDebugEnabled ( ) ) log . debug ( "beginInternTransaction was called" ) ; J2EETransactionImpl tx = ( J2EETransactionImpl ) super . currentTransaction ( ) ; if ( tx == null ) tx = newInternTransaction ( ) ; if ( ! tx . isOpen ( ) ) { // start the transaction tx . begin ( ) ; tx . setInExternTransaction ( true ) ; } }
Here we start a intern odmg - Transaction to hide transaction demarcation This method could be invoked several times within a transaction but only the first call begin a intern odmg transaction
104
36
680
private J2EETransactionImpl newInternTransaction ( ) { if ( log . isDebugEnabled ( ) ) log . debug ( "obtain new intern odmg-transaction" ) ; J2EETransactionImpl tx = new J2EETransactionImpl ( this ) ; try { getConfigurator ( ) . configure ( tx ) ; } catch ( ConfigurationException e ) { throw new OJBRuntimeException ( "Cannot create new intern odmg transaction" , e ) ; } return tx ; }
Returns a new intern odmg - transaction for the current database .
110
13
681
protected void associateBatched ( Collection owners , Collection children ) { ObjectReferenceDescriptor ord = getObjectReferenceDescriptor ( ) ; ClassDescriptor cld = getOwnerClassDescriptor ( ) ; Object owner ; Object relatedObject ; Object fkValues [ ] ; Identity id ; PersistenceBroker pb = getBroker ( ) ; PersistentField field = ord . getPersistentField ( ) ; Class topLevelClass = pb . getTopLevelClass ( ord . getItemClass ( ) ) ; HashMap childrenMap = new HashMap ( children . size ( ) ) ; for ( Iterator it = children . iterator ( ) ; it . hasNext ( ) ; ) { relatedObject = it . next ( ) ; childrenMap . put ( pb . serviceIdentity ( ) . buildIdentity ( relatedObject ) , relatedObject ) ; } for ( Iterator it = owners . iterator ( ) ; it . hasNext ( ) ; ) { owner = it . next ( ) ; fkValues = ord . getForeignKeyValues ( owner , cld ) ; if ( isNull ( fkValues ) ) { field . set ( owner , null ) ; continue ; } id = pb . serviceIdentity ( ) . buildIdentity ( null , topLevelClass , fkValues ) ; relatedObject = childrenMap . get ( id ) ; field . set ( owner , relatedObject ) ; } }
Associate the batched Children with their owner object . Loop over owners
302
14
682
public boolean existsElement ( String predicate ) throws org . odmg . QueryInvalidException { DList results = ( DList ) this . query ( predicate ) ; if ( results == null || results . size ( ) == 0 ) return false ; else return true ; }
Determines whether there is an element of the collection that evaluates to true for the predicate .
55
19
683
public Iterator select ( String predicate ) throws org . odmg . QueryInvalidException { return this . query ( predicate ) . iterator ( ) ; }
Access all of the elements of the collection that evaluate to true for the provided query predicate .
31
18
684
public Object selectElement ( String predicate ) throws org . odmg . QueryInvalidException { return ( ( DList ) this . query ( predicate ) ) . get ( 0 ) ; }
Selects the single element of the collection for which the provided OQL query predicate is true .
38
19
685
public static boolean sameLists ( String list1 , String list2 ) { return new CommaListIterator ( list1 ) . equals ( new CommaListIterator ( list2 ) ) ; }
Compares the two comma - separated lists .
41
9
686
public static void startTimer ( final String type ) { TransactionLogger instance = getInstance ( ) ; if ( instance == null ) { return ; } instance . components . putIfAbsent ( type , new Component ( type ) ) ; instance . components . get ( type ) . startTimer ( ) ; }
Start component timer for current instance
64
6
687
public static void pauseTimer ( final String type ) { TransactionLogger instance = getInstance ( ) ; if ( instance == null ) { return ; } instance . components . get ( type ) . pauseTimer ( ) ; }
Pause component timer for current instance
46
6
688
public static ComponentsMultiThread getComponentsMultiThread ( ) { TransactionLogger instance = getInstance ( ) ; if ( instance == null ) { return null ; } return instance . componentsMultiThread ; }
Get ComponentsMultiThread of current instance
42
7
689
public static Collection < Component > getComponentsList ( ) { TransactionLogger instance = getInstance ( ) ; if ( instance == null ) { return null ; } return instance . components . values ( ) ; }
Get components list for current instance
44
6
690
public static String getFlowContext ( ) { TransactionLogger instance = getInstance ( ) ; if ( instance == null ) { return null ; } return instance . flowContext ; }
Get string value of flow context for current instance
37
9
691
protected static boolean createLoggingAction ( final Logger logger , final Logger auditor , final TransactionLogger instance ) { TransactionLogger oldInstance = getInstance ( ) ; if ( oldInstance == null || oldInstance . finished ) { if ( loggingKeys == null ) { synchronized ( TransactionLogger . class ) { if ( loggingKeys == null ) { logger . info ( "Initializing 'LoggingKeysHandler' class" ) ; loggingKeys = new LoggingKeysHandler ( keysPropStream ) ; } } } initInstance ( instance , logger , auditor ) ; setInstance ( instance ) ; return true ; } return false ; // Really not sure it can happen - since we arrive here in a new thread of transaction I think it's ThreadLocal should be empty. But leaving this code just in case... }
Create new logging action This method check if there is an old instance for this thread - local If not - Initialize new instance and set it as this thread - local s instance
168
35
692
protected void addPropertiesStart ( String type ) { putProperty ( PropertyKey . Host . name ( ) , IpUtils . getHostName ( ) ) ; putProperty ( PropertyKey . Type . name ( ) , type ) ; putProperty ( PropertyKey . Status . name ( ) , Status . Start . name ( ) ) ; }
Add properties to properties map on transaction start
72
8
693
protected void writePropertiesToLog ( Logger logger , Level level ) { writeToLog ( logger , level , getMapAsString ( this . properties , separator ) , null ) ; if ( this . exception != null ) { writeToLog ( this . logger , Level . ERROR , "Error:" , this . exception ) ; } }
Write properties map to given log in given level - with pipe separator between each entry Write exception stack trace to logger in error level if not empty
72
29
694
private static void initInstance ( final TransactionLogger instance , final Logger logger , final Logger auditor ) { instance . logger = logger ; instance . auditor = auditor ; instance . components = new LinkedHashMap <> ( ) ; instance . properties = new LinkedHashMap <> ( ) ; instance . total = new Component ( TOTAL_COMPONENT ) ; instance . total . startTimer ( ) ; instance . componentsMultiThread = new ComponentsMultiThread ( ) ; instance . flowContext = FlowContextFactory . serializeNativeFlowContext ( ) ; }
Initialize new instance
118
4
695
private static void writeToLog ( Logger logger , Level level , String pattern , Exception exception ) { if ( level == Level . ERROR ) { logger . error ( pattern , exception ) ; } else if ( level == Level . INFO ) { logger . info ( pattern ) ; } else if ( level == Level . DEBUG ) { logger . debug ( pattern ) ; } }
Write the given pattern to given log in given logging level
77
11
696
private static void addTimePerComponent ( HashMap < String , Long > mapComponentTimes , Component component ) { Long currentTimeOfComponent = 0L ; String key = component . getComponentType ( ) ; if ( mapComponentTimes . containsKey ( key ) ) { currentTimeOfComponent = mapComponentTimes . get ( key ) ; } //when transactions are run in parallel, we should log the longest transaction only to avoid that //for ex 'Total time' would be 100ms and transactions in parallel to hornetQ will be 2000ms Long maxTime = Math . max ( component . getTime ( ) , currentTimeOfComponent ) ; mapComponentTimes . put ( key , maxTime ) ; }
Add component processing time to given map
146
7
697
public static String convertToSQL92 ( char escape , char multi , char single , String pattern ) throws IllegalArgumentException { if ( ( escape == ' ' ) || ( multi == ' ' ) || ( single == ' ' ) ) { throw new IllegalArgumentException ( "do not use single quote (') as special char!" ) ; } StringBuilder result = new StringBuilder ( pattern . length ( ) + 5 ) ; int i = 0 ; while ( i < pattern . length ( ) ) { char chr = pattern . charAt ( i ) ; if ( chr == escape ) { // emit the next char and skip it if ( i != ( pattern . length ( ) - 1 ) ) { result . append ( pattern . charAt ( i + 1 ) ) ; } i ++ ; // skip next char } else if ( chr == single ) { result . append ( ' ' ) ; } else if ( chr == multi ) { result . append ( ' ' ) ; } else if ( chr == ' ' ) { result . append ( ' ' ) ; result . append ( ' ' ) ; } else { result . append ( chr ) ; } i ++ ; } return result . toString ( ) ; }
Given OGC PropertyIsLike Filter information construct an SQL - compatible like pattern .
259
16
698
public String getSQL92LikePattern ( ) throws IllegalArgumentException { if ( escape . length ( ) != 1 ) { throw new IllegalArgumentException ( "Like Pattern --> escape char should be of length exactly 1" ) ; } if ( wildcardSingle . length ( ) != 1 ) { throw new IllegalArgumentException ( "Like Pattern --> wildcardSingle char should be of length exactly 1" ) ; } if ( wildcardMulti . length ( ) != 1 ) { throw new IllegalArgumentException ( "Like Pattern --> wildcardMulti char should be of length exactly 1" ) ; } return LikeFilterImpl . convertToSQL92 ( escape . charAt ( 0 ) , wildcardMulti . charAt ( 0 ) , wildcardSingle . charAt ( 0 ) , isMatchingCase ( ) , pattern ) ; }
See convertToSQL92 .
174
6
699
public boolean evaluate ( Object feature ) { // Checks to ensure that the attribute has been set if ( attribute == null ) { return false ; } // Note that this converts the attribute to a string // for comparison. Unlike the math or geometry filters, which // require specific types to function correctly, this filter // using the mandatory string representation in Java // Of course, this does not guarantee a meaningful result, but it // does guarantee a valid result. // LOGGER.finest("pattern: " + pattern); // LOGGER.finest("string: " + attribute.getValue(feature)); // return attribute.getValue(feature).toString().matches(pattern); Object value = attribute . evaluate ( feature ) ; if ( null == value ) { return false ; } Matcher matcher = getMatcher ( ) ; matcher . reset ( value . toString ( ) ) ; return matcher . matches ( ) ; }
Determines whether or not a given feature matches this pattern .
192
13