idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
1,400
public Feature toDto ( InternalFeature feature , int featureIncludes ) throws GeomajasException { if ( feature == null ) { return null ; } Feature dto = new Feature ( feature . getId ( ) ) ; if ( ( featureIncludes & VectorLayerService . FEATURE_INCLUDE_ATTRIBUTES ) != 0 && null != feature . getAttributes ( ) ) { // need to assure lazy attributes are converted to non-lazy attributes Map < String , Attribute > attributes = new HashMap < String , Attribute > ( ) ; for ( Map . Entry < String , Attribute > entry : feature . getAttributes ( ) . entrySet ( ) ) { Attribute value = entry . getValue ( ) ; if ( value instanceof LazyAttribute ) { value = ( ( LazyAttribute ) value ) . instantiate ( ) ; } attributes . put ( entry . getKey ( ) , value ) ; } dto . setAttributes ( attributes ) ; } if ( ( featureIncludes & VectorLayerService . FEATURE_INCLUDE_LABEL ) != 0 ) { dto . setLabel ( feature . getLabel ( ) ) ; } if ( ( featureIncludes & VectorLayerService . FEATURE_INCLUDE_GEOMETRY ) != 0 ) { dto . setGeometry ( toDto ( feature . getGeometry ( ) ) ) ; } if ( ( featureIncludes & VectorLayerService . FEATURE_INCLUDE_STYLE ) != 0 && null != feature . getStyleInfo ( ) ) { dto . setStyleId ( feature . getStyleInfo ( ) . getStyleId ( ) ) ; } InternalFeatureImpl vFeature = ( InternalFeatureImpl ) feature ; dto . setClipped ( vFeature . isClipped ( ) ) ; dto . setUpdatable ( feature . isEditable ( ) ) ; dto . setDeletable ( feature . isDeletable ( ) ) ; return dto ; }
Convert the server side feature to a DTO feature that can be sent to the client .
426
19
1,401
public Class < ? extends com . vividsolutions . jts . geom . Geometry > toInternal ( LayerType layerType ) { switch ( layerType ) { case GEOMETRY : return com . vividsolutions . jts . geom . Geometry . class ; case LINESTRING : return LineString . class ; case MULTILINESTRING : return MultiLineString . class ; case POINT : return Point . class ; case MULTIPOINT : return MultiPoint . class ; case POLYGON : return Polygon . class ; case MULTIPOLYGON : return MultiPolygon . class ; case RASTER : return null ; default : throw new IllegalStateException ( "Don't know how to handle layer type " + layerType ) ; } }
Convert a layer type to a geometry class .
170
10
1,402
public LayerType toDto ( Class < ? extends com . vividsolutions . jts . geom . Geometry > geometryClass ) { if ( geometryClass == LineString . class ) { return LayerType . LINESTRING ; } else if ( geometryClass == MultiLineString . class ) { return LayerType . MULTILINESTRING ; } else if ( geometryClass == Point . class ) { return LayerType . POINT ; } else if ( geometryClass == MultiPoint . class ) { return LayerType . MULTIPOINT ; } else if ( geometryClass == Polygon . class ) { return LayerType . POLYGON ; } else if ( geometryClass == MultiPolygon . class ) { return LayerType . MULTIPOLYGON ; } else { return LayerType . GEOMETRY ; } }
Convert a geometry class to a layer type .
180
10
1,403
public void put ( String key , Object object , Envelope envelope ) { index . put ( key , envelope ) ; cache . put ( key , object ) ; }
Put a spatial object in the cache and index it .
35
11
1,404
public < TYPE > TYPE get ( String key , Class < TYPE > type ) { return cache . get ( key , type ) ; }
Get the spatial object from the cache .
28
8
1,405
public void addFkToThisClass ( String column ) { if ( fksToThisClass == null ) { fksToThisClass = new Vector ( ) ; } fksToThisClass . add ( column ) ; fksToThisClassAry = null ; }
add a FK column pointing to This Class
58
9
1,406
public void addFkToItemClass ( String column ) { if ( fksToItemClass == null ) { fksToItemClass = new Vector ( ) ; } fksToItemClass . add ( column ) ; fksToItemClassAry = null ; }
add a FK column pointing to the item Class
58
10
1,407
protected String sp_createSequenceQuery ( String sequenceName , long maxKey ) { return "insert into " + SEQ_TABLE_NAME + " (" + SEQ_NAME_STRING + "," + SEQ_ID_STRING + ") values ('" + sequenceName + "'," + maxKey + ")" ; }
Insert syntax for our special table
72
6
1,408
protected long getUniqueLong ( FieldDescriptor field ) throws SequenceManagerException { boolean needsCommit = false ; long result = 0 ; /* arminw: use the associated broker instance, check if broker was in tx or we need to commit used connection. */ PersistenceBroker targetBroker = getBrokerForClass ( ) ; if ( ! targetBroker . isInTransaction ( ) ) { targetBroker . beginTransaction ( ) ; needsCommit = true ; } try { // lookup sequence name String sequenceName = calculateSequenceName ( field ) ; try { result = buildNextSequence ( targetBroker , field . getClassDescriptor ( ) , sequenceName ) ; /* if 0 was returned we assume that the stored procedure did not work properly. */ if ( result == 0 ) { throw new SequenceManagerException ( "No incremented value retrieved" ) ; } } catch ( Exception e ) { // maybe the sequence was not created log . info ( "Could not grab next key, message was " + e . getMessage ( ) + " - try to write a new sequence entry to database" ) ; try { // on create, make sure to get the max key for the table first long maxKey = SequenceManagerHelper . getMaxForExtent ( targetBroker , field ) ; createSequence ( targetBroker , field , sequenceName , maxKey ) ; } catch ( Exception e1 ) { String eol = SystemUtils . LINE_SEPARATOR ; throw new SequenceManagerException ( eol + "Could not grab next id, failed with " + eol + e . getMessage ( ) + eol + "Creation of new sequence failed with " + eol + e1 . getMessage ( ) + eol , e1 ) ; } try { result = buildNextSequence ( targetBroker , field . getClassDescriptor ( ) , sequenceName ) ; } catch ( Exception e1 ) { throw new SequenceManagerException ( "Could not grab next id although a sequence seems to exist" , e ) ; } } } finally { if ( targetBroker != null && needsCommit ) { targetBroker . commitTransaction ( ) ; } } return result ; }
Gets the actual key - will create a new row with the max key of table if it does not exist .
466
23
1,409
protected long buildNextSequence ( PersistenceBroker broker , ClassDescriptor cld , String sequenceName ) throws LookupException , SQLException , PlatformException { CallableStatement cs = null ; try { Connection con = broker . serviceConnectionManager ( ) . getConnection ( ) ; cs = getPlatform ( ) . prepareNextValProcedureStatement ( con , PROCEDURE_NAME , sequenceName ) ; cs . executeUpdate ( ) ; return cs . getLong ( 1 ) ; } finally { try { if ( cs != null ) cs . close ( ) ; } catch ( SQLException ignore ) { // ignore it } } }
Calls the stored procedure stored procedure throws an error if it doesn t exist .
138
16
1,410
protected void createSequence ( PersistenceBroker broker , FieldDescriptor field , String sequenceName , long maxKey ) throws Exception { Statement stmt = null ; try { stmt = broker . serviceStatementManager ( ) . getGenericStatement ( field . getClassDescriptor ( ) , Query . NOT_SCROLLABLE ) ; stmt . execute ( sp_createSequenceQuery ( sequenceName , maxKey ) ) ; } catch ( Exception e ) { log . error ( e ) ; throw new SequenceManagerException ( "Could not create new row in " + SEQ_TABLE_NAME + " table - TABLENAME=" + sequenceName + " field=" + field . getColumnName ( ) , e ) ; } finally { try { if ( stmt != null ) stmt . close ( ) ; } catch ( SQLException sqle ) { if ( log . isDebugEnabled ( ) ) log . debug ( "Threw SQLException while in createSequence and closing stmt" , sqle ) ; // ignore it } } }
Creates new row in table
228
6
1,411
static void init ( ) { // NOPMD determineIfNTEventLogIsSupported ( ) ; URL resource = null ; final String configurationOptionStr = OptionConverter . getSystemProperty ( DEFAULT_CONFIGURATION_KEY , null ) ; if ( configurationOptionStr != null ) { try { resource = new URL ( configurationOptionStr ) ; } catch ( MalformedURLException ex ) { // so, resource is not a URL: // attempt to get the resource from the class path resource = Loader . getResource ( configurationOptionStr ) ; } } if ( resource == null ) { resource = Loader . getResource ( DEFAULT_CONFIGURATION_FILE ) ; // NOPMD } if ( resource == null ) { System . err . println ( "[FoundationLogger] Can not find resource: " + DEFAULT_CONFIGURATION_FILE ) ; // NOPMD throw new FoundationIOException ( "Can not find resource: " + DEFAULT_CONFIGURATION_FILE ) ; // NOPMD } // update the log manager to use the Foundation repository. final RepositorySelector foundationRepositorySelector = new FoundationRepositorySelector ( FoundationLogFactory . foundationLogHierarchy ) ; LogManager . setRepositorySelector ( foundationRepositorySelector , null ) ; // set logger to info so we always want to see these logs even if root // is set to ERROR. final Logger logger = getLogger ( FoundationLogger . class ) ; final String logPropFile = resource . getPath ( ) ; log4jConfigProps = getLogProperties ( resource ) ; // select and configure again so the loggers are created with the right // level after the repository selector was updated. OptionConverter . selectAndConfigure ( resource , null , FoundationLogFactory . foundationLogHierarchy ) ; // start watching for property changes setUpPropFileReloading ( logger , logPropFile , log4jConfigProps ) ; // add syslog appender or windows event viewer appender // setupOSSystemLog(logger, log4jConfigProps); // parseMarkerPatterns(log4jConfigProps); // parseMarkerPurePattern(log4jConfigProps); // udpateMarkerStructuredLogOverrideMap(logger); AbstractFoundationLoggingMarker . init ( ) ; updateSniffingLoggersLevel ( logger ) ; setupJULSupport ( resource ) ; }
Initialize that Foundation Logging library .
525
8
1,412
private static void updateSniffingLoggersLevel ( Logger logger ) { InputStream settingIS = FoundationLogger . class . getResourceAsStream ( "/sniffingLogger.xml" ) ; if ( settingIS == null ) { logger . debug ( "file sniffingLogger.xml not found in classpath" ) ; } else { try { SAXBuilder builder = new SAXBuilder ( ) ; Document document = builder . build ( settingIS ) ; settingIS . close ( ) ; Element rootElement = document . getRootElement ( ) ; List < Element > sniffingloggers = rootElement . getChildren ( "sniffingLogger" ) ; for ( Element sniffinglogger : sniffingloggers ) { String loggerName = sniffinglogger . getAttributeValue ( "id" ) ; Logger . getLogger ( loggerName ) . setLevel ( Level . TRACE ) ; } } catch ( Exception e ) { logger . error ( "cannot load the sniffing logger configuration file. error is: " + e , e ) ; throw new IllegalArgumentException ( "Problem parsing sniffingLogger.xml" , e ) ; } } }
The sniffing Loggers are some special Loggers whose level will be set to TRACE forcedly .
251
21
1,413
public void cache ( Identity oid , Object obj ) { try { jcsCache . put ( oid . toString ( ) , obj ) ; } catch ( CacheException e ) { throw new RuntimeCacheException ( e ) ; } }
makes object obj persistent to the Objectcache under the key oid .
50
14
1,414
public void remove ( Identity oid ) { try { jcsCache . remove ( oid . toString ( ) ) ; } catch ( CacheException e ) { throw new RuntimeCacheException ( e . getMessage ( ) ) ; } }
removes an Object from the cache .
50
8
1,415
public List < GetLocationResult > search ( String q , int maxRows , Locale locale ) throws Exception { List < GetLocationResult > searchResult = new ArrayList < GetLocationResult > ( ) ; String url = URLEncoder . encode ( q , "UTF8" ) ; url = "q=select%20*%20from%20geo.placefinder%20where%20text%3D%22" + url + "%22" ; if ( maxRows > 0 ) { url = url + "&count=" + maxRows ; } url = url + "&flags=GX" ; if ( null != locale ) { url = url + "&locale=" + locale ; } if ( appId != null ) { url = url + "&appid=" + appId ; } InputStream inputStream = connect ( url ) ; if ( null != inputStream ) { SAXBuilder parser = new SAXBuilder ( ) ; Document doc = parser . build ( inputStream ) ; Element root = doc . getRootElement ( ) ; // check code for exception String message = root . getChildText ( "Error" ) ; // Integer errorCode = Integer.parseInt(message); if ( message != null && Integer . parseInt ( message ) != 0 ) { throw new Exception ( root . getChildText ( "ErrorMessage" ) ) ; } Element results = root . getChild ( "results" ) ; for ( Object obj : results . getChildren ( "Result" ) ) { Element toponymElement = ( Element ) obj ; GetLocationResult location = getLocationFromElement ( toponymElement ) ; searchResult . add ( location ) ; } } return searchResult ; }
Call the Yahoo! PlaceFinder service for a result .
364
12
1,416
public ClassDescriptor getDescriptorFor ( String strClassName ) throws ClassNotPersistenceCapableException { ClassDescriptor result = discoverDescriptor ( strClassName ) ; if ( result == null ) { throw new ClassNotPersistenceCapableException ( strClassName + " not found in OJB Repository" ) ; } else { return result ; } }
lookup a ClassDescriptor in the internal Hashtable
81
12
1,417
protected String getIsolationLevelAsString ( ) { if ( defaultIsolationLevel == IL_READ_UNCOMMITTED ) { return LITERAL_IL_READ_UNCOMMITTED ; } else if ( defaultIsolationLevel == IL_READ_COMMITTED ) { return LITERAL_IL_READ_COMMITTED ; } else if ( defaultIsolationLevel == IL_REPEATABLE_READ ) { return LITERAL_IL_REPEATABLE_READ ; } else if ( defaultIsolationLevel == IL_SERIALIZABLE ) { return LITERAL_IL_SERIALIZABLE ; } else if ( defaultIsolationLevel == IL_OPTIMISTIC ) { return LITERAL_IL_OPTIMISTIC ; } return LITERAL_IL_READ_UNCOMMITTED ; }
returns IsolationLevel literal as matching to the corresponding id
187
12
1,418
private ClassDescriptor discoverDescriptor ( Class clazz ) { ClassDescriptor result = ( ClassDescriptor ) descriptorTable . get ( clazz . getName ( ) ) ; if ( result == null ) { Class superClass = clazz . getSuperclass ( ) ; // only recurse if the superClass is not java.lang.Object if ( superClass != null ) { result = discoverDescriptor ( superClass ) ; } if ( result == null ) { // we're also checking the interfaces as there could be normal // mappings for them in the repository (using factory-class, // factory-method, and the property field accessor) Class [ ] interfaces = clazz . getInterfaces ( ) ; if ( ( interfaces != null ) && ( interfaces . length > 0 ) ) { for ( int idx = 0 ; ( idx < interfaces . length ) && ( result == null ) ; idx ++ ) { result = discoverDescriptor ( interfaces [ idx ] ) ; } } } if ( result != null ) { /** * Kuali Foundation modification -- 6/19/2009 */ synchronized ( descriptorTable ) { /** * End of Kuali Foundation modification */ descriptorTable . put ( clazz . getName ( ) , result ) ; /** * Kuali Foundation modification -- 6/19/2009 */ } /** * End of Kuali Foundation modification */ } } return result ; }
Internal method for recursivly searching for a class descriptor that avoids class loading when we already have a class object .
301
24
1,419
private void createResultSubClassesMultipleJoinedTables ( List result , ClassDescriptor cld , boolean wholeTree ) { List tmp = ( List ) superClassMultipleJoinedTablesMap . get ( cld . getClassOfObject ( ) ) ; if ( tmp != null ) { result . addAll ( tmp ) ; if ( wholeTree ) { for ( int i = 0 ; i < tmp . size ( ) ; i ++ ) { Class subClass = ( Class ) tmp . get ( i ) ; ClassDescriptor subCld = getDescriptorFor ( subClass ) ; createResultSubClassesMultipleJoinedTables ( result , subCld , wholeTree ) ; } } } }
Add all sub - classes using multiple joined tables feature for specified class .
150
14
1,420
public ProxyAuthentication getProxyAuthentication ( ) { // convert authentication to layerAuthentication so we only use one // TODO Remove when removing deprecated authentication field. if ( layerAuthentication == null && authentication != null ) { layerAuthentication = new LayerAuthentication ( ) ; layerAuthentication . setAuthenticationMethod ( LayerAuthenticationMethod . valueOf ( authentication . getAuthenticationMethod ( ) . name ( ) ) ) ; layerAuthentication . setPassword ( authentication . getPassword ( ) ) ; layerAuthentication . setPasswordKey ( authentication . getPasswordKey ( ) ) ; layerAuthentication . setRealm ( authentication . getRealm ( ) ) ; layerAuthentication . setUser ( authentication . getUser ( ) ) ; layerAuthentication . setUserKey ( authentication . getUserKey ( ) ) ; } // TODO Remove when removing deprecated authentication field. return layerAuthentication ; }
Get the authentication info for this layer .
187
8
1,421
@ Api public void setUseCache ( boolean useCache ) { if ( null == cacheManagerService && useCache ) { log . warn ( "The caching plugin needs to be available to cache WMS requests. Not setting useCache." ) ; } else { this . useCache = useCache ; } }
Set whether the WMS tiles should be cached for later use . This implies that the WMS tiles will be proxied .
64
25
1,422
protected boolean check ( String id , List < String > includes , List < String > excludes ) { return check ( id , includes ) && ! check ( id , excludes ) ; }
Check whether the given id is included in the list of includes and not excluded .
37
16
1,423
protected boolean check ( String id , List < String > includes ) { if ( null != includes ) { for ( String check : includes ) { if ( check ( id , check ) ) { return true ; } } } return false ; }
Check whether the given is is matched by one of the include expressions .
49
14
1,424
protected boolean check ( String value , String regex ) { Pattern pattern = Pattern . compile ( regex ) ; return pattern . matcher ( value ) . matches ( ) ; }
Check whether the value is matched by a regular expression .
35
11
1,425
protected ClassDescriptor getClassDescriptor ( ) { ClassDescriptor cld = ( ClassDescriptor ) m_classDescriptor . get ( ) ; if ( cld == null ) { throw new OJBRuntimeException ( "Requested ClassDescriptor instance was already GC by JVM" ) ; } return cld ; }
Returns the classDescriptor .
75
7
1,426
protected void appendWhereClause ( FieldDescriptor [ ] fields , StringBuffer stmt ) throws PersistenceBrokerException { stmt . append ( " WHERE " ) ; for ( int i = 0 ; i < fields . length ; i ++ ) { FieldDescriptor fmd = fields [ i ] ; stmt . append ( fmd . getColumnName ( ) ) ; stmt . append ( " = ? " ) ; if ( i < fields . length - 1 ) { stmt . append ( " AND " ) ; } } }
Generate a sql where - clause for the array of fields
116
12
1,427
protected void appendWhereClause ( ClassDescriptor cld , boolean useLocking , StringBuffer stmt ) { FieldDescriptor [ ] pkFields = cld . getPkFields ( ) ; FieldDescriptor [ ] fields ; fields = pkFields ; if ( useLocking ) { FieldDescriptor [ ] lockingFields = cld . getLockingFields ( ) ; if ( lockingFields . length > 0 ) { fields = new FieldDescriptor [ pkFields . length + lockingFields . length ] ; System . arraycopy ( pkFields , 0 , fields , 0 , pkFields . length ) ; System . arraycopy ( lockingFields , 0 , fields , pkFields . length , lockingFields . length ) ; } } appendWhereClause ( fields , stmt ) ; }
Generate a where clause for a prepared Statement . Only primary key and locking fields are used in this where clause
188
22
1,428
public Object copy ( final Object obj , PersistenceBroker broker ) throws ObjectCopyException { ObjectOutputStream oos = null ; ObjectInputStream ois = null ; try { final ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; oos = new ObjectOutputStream ( bos ) ; // serialize and pass the object oos . writeObject ( obj ) ; oos . flush ( ) ; final ByteArrayInputStream bin = new ByteArrayInputStream ( bos . toByteArray ( ) ) ; ois = new ObjectInputStream ( bin ) ; // return the new object return ois . readObject ( ) ; } catch ( Exception e ) { throw new ObjectCopyException ( e ) ; } finally { try { if ( oos != null ) { oos . close ( ) ; } if ( ois != null ) { ois . close ( ) ; } } catch ( IOException ioe ) { // ignore } } }
This implementation will probably be slower than the metadata object copy but this was easier to implement .
200
18
1,429
public void bindDelete ( PreparedStatement stmt , Identity oid , ClassDescriptor cld ) throws SQLException { Object [ ] pkValues = oid . getPrimaryKeyValues ( ) ; FieldDescriptor [ ] pkFields = cld . getPkFields ( ) ; int i = 0 ; try { for ( ; i < pkValues . length ; i ++ ) { setObjectForStatement ( stmt , i + 1 , pkValues [ i ] , pkFields [ i ] . getJdbcType ( ) . getType ( ) ) ; } } catch ( SQLException e ) { m_log . error ( "bindDelete failed for: " + oid . toString ( ) + ", while set value '" + pkValues [ i ] + "' for column " + pkFields [ i ] . getColumnName ( ) ) ; throw e ; } }
binds the Identities Primary key values to the statement
202
11
1,430
public void bindDelete ( PreparedStatement stmt , ClassDescriptor cld , Object obj ) throws SQLException { if ( cld . getDeleteProcedure ( ) != null ) { this . bindProcedure ( stmt , cld , obj , cld . getDeleteProcedure ( ) ) ; } else { int index = 1 ; ValueContainer [ ] values , currentLockingValues ; currentLockingValues = cld . getCurrentLockingValues ( obj ) ; // parameters for WHERE-clause pk values = getKeyValues ( m_broker , cld , obj ) ; for ( int i = 0 ; i < values . length ; i ++ ) { setObjectForStatement ( stmt , index , values [ i ] . getValue ( ) , values [ i ] . getJdbcType ( ) . getType ( ) ) ; index ++ ; } // parameters for WHERE-clause locking values = currentLockingValues ; for ( int i = 0 ; i < values . length ; i ++ ) { setObjectForStatement ( stmt , index , values [ i ] . getValue ( ) , values [ i ] . getJdbcType ( ) . getType ( ) ) ; index ++ ; } } }
binds the objects primary key and locking values to the statement BRJ
269
14
1,431
private int bindStatementValue ( PreparedStatement stmt , int index , Object attributeOrQuery , Object value , ClassDescriptor cld ) throws SQLException { FieldDescriptor fld = null ; // if value is a subQuery bind it if ( value instanceof Query ) { Query subQuery = ( Query ) value ; return bindStatement ( stmt , subQuery , cld . getRepository ( ) . getDescriptorFor ( subQuery . getSearchClass ( ) ) , index ) ; } // if attribute is a subQuery bind it if ( attributeOrQuery instanceof Query ) { Query subQuery = ( Query ) attributeOrQuery ; bindStatement ( stmt , subQuery , cld . getRepository ( ) . getDescriptorFor ( subQuery . getSearchClass ( ) ) , index ) ; } else { fld = cld . getFieldDescriptorForPath ( ( String ) attributeOrQuery ) ; } if ( fld != null ) { // BRJ: use field conversions and platform if ( value != null ) { m_platform . setObjectForStatement ( stmt , index , fld . getFieldConversion ( ) . javaToSql ( value ) , fld . getJdbcType ( ) . getType ( ) ) ; } else { m_platform . setNullForStatement ( stmt , index , fld . getJdbcType ( ) . getType ( ) ) ; } } else { if ( value != null ) { stmt . setObject ( index , value ) ; } else { stmt . setNull ( index , Types . NULL ) ; } } return ++ index ; // increment before return }
bind attribute and value
359
4
1,432
public void bindSelect ( PreparedStatement stmt , Identity oid , ClassDescriptor cld , boolean callableStmt ) throws SQLException { ValueContainer [ ] values = null ; int i = 0 ; int j = 0 ; if ( cld == null ) { cld = m_broker . getClassDescriptor ( oid . getObjectsRealClass ( ) ) ; } try { if ( callableStmt ) { // First argument is the result set m_platform . registerOutResultSet ( ( CallableStatement ) stmt , 1 ) ; j ++ ; } values = getKeyValues ( m_broker , cld , oid ) ; for ( /*void*/ ; i < values . length ; i ++ , j ++ ) { setObjectForStatement ( stmt , j + 1 , values [ i ] . getValue ( ) , values [ i ] . getJdbcType ( ) . getType ( ) ) ; } } catch ( SQLException e ) { m_log . error ( "bindSelect failed for: " + oid . toString ( ) + ", PK: " + i + ", value: " + values [ i ] ) ; throw e ; } }
Binds the Identities Primary key values to the statement .
262
12
1,433
public PreparedStatement getDeleteStatement ( ClassDescriptor cld ) throws PersistenceBrokerSQLException , PersistenceBrokerException { try { return cld . getStatementsForClass ( m_conMan ) . getDeleteStmt ( m_conMan . getConnection ( ) ) ; } catch ( SQLException e ) { throw new PersistenceBrokerSQLException ( "Could not build statement ask for" , e ) ; } catch ( LookupException e ) { throw new PersistenceBrokerException ( "Used ConnectionManager instance could not obtain a connection" , e ) ; } }
return a prepared DELETE Statement fitting for the given ClassDescriptor
134
15
1,434
public PreparedStatement getInsertStatement ( ClassDescriptor cds ) throws PersistenceBrokerSQLException , PersistenceBrokerException { try { return cds . getStatementsForClass ( m_conMan ) . getInsertStmt ( m_conMan . getConnection ( ) ) ; } catch ( SQLException e ) { throw new PersistenceBrokerSQLException ( "Could not build statement ask for" , e ) ; } catch ( LookupException e ) { throw new PersistenceBrokerException ( "Used ConnectionManager instance could not obtain a connection" , e ) ; } }
return a prepared Insert Statement fitting for the given ClassDescriptor
134
13
1,435
public PreparedStatement getPreparedStatement ( ClassDescriptor cds , String sql , boolean scrollable , int explicitFetchSizeHint , boolean callableStmt ) throws PersistenceBrokerException { try { return cds . getStatementsForClass ( m_conMan ) . getPreparedStmt ( m_conMan . getConnection ( ) , sql , scrollable , explicitFetchSizeHint , callableStmt ) ; } catch ( LookupException e ) { throw new PersistenceBrokerException ( "Used ConnectionManager instance could not obtain a connection" , e ) ; } }
return a generic Statement for the given ClassDescriptor
130
11
1,436
public PreparedStatement getSelectByPKStatement ( ClassDescriptor cds ) throws PersistenceBrokerSQLException , PersistenceBrokerException { try { return cds . getStatementsForClass ( m_conMan ) . getSelectByPKStmt ( m_conMan . getConnection ( ) ) ; } catch ( SQLException e ) { throw new PersistenceBrokerSQLException ( "Could not build statement ask for" , e ) ; } catch ( LookupException e ) { throw new PersistenceBrokerException ( "Used ConnectionManager instance could not obtain a connection" , e ) ; } }
return a prepared Select Statement for the given ClassDescriptor
138
12
1,437
public PreparedStatement getUpdateStatement ( ClassDescriptor cds ) throws PersistenceBrokerSQLException , PersistenceBrokerException { try { return cds . getStatementsForClass ( m_conMan ) . getUpdateStmt ( m_conMan . getConnection ( ) ) ; } catch ( SQLException e ) { throw new PersistenceBrokerSQLException ( "Could not build statement ask for" , e ) ; } catch ( LookupException e ) { throw new PersistenceBrokerException ( "Used ConnectionManager instance could not obtain a connection" , e ) ; } }
return a prepared Update Statement fitting to the given ClassDescriptor
134
13
1,438
protected ValueContainer [ ] getAllValues ( ClassDescriptor cld , Object obj ) throws PersistenceBrokerException { return m_broker . serviceBrokerHelper ( ) . getAllRwValues ( cld , obj ) ; }
returns an array containing values for all the Objects attribute
52
11
1,439
protected ValueContainer [ ] getKeyValues ( PersistenceBroker broker , ClassDescriptor cld , Object obj ) throws PersistenceBrokerException { return broker . serviceBrokerHelper ( ) . getKeyValues ( cld , obj ) ; }
returns an Array with an Objects PK VALUES
53
10
1,440
protected ValueContainer [ ] getKeyValues ( PersistenceBroker broker , ClassDescriptor cld , Identity oid ) throws PersistenceBrokerException { return broker . serviceBrokerHelper ( ) . getKeyValues ( cld , oid ) ; }
returns an Array with an Identities PK VALUES
55
11
1,441
protected ValueContainer [ ] getNonKeyValues ( PersistenceBroker broker , ClassDescriptor cld , Object obj ) throws PersistenceBrokerException { return broker . serviceBrokerHelper ( ) . getNonKeyRwValues ( cld , obj ) ; }
returns an Array with an Objects NON - PK VALUES
57
12
1,442
private void bindProcedure ( PreparedStatement stmt , ClassDescriptor cld , Object obj , ProcedureDescriptor proc ) throws SQLException { int valueSub = 0 ; // Figure out if we are using a callable statement. If we are, then we // will need to register one or more output parameters. CallableStatement callable = null ; try { callable = ( CallableStatement ) stmt ; } catch ( Exception e ) { m_log . error ( "Error while bind values for class '" + ( cld != null ? cld . getClassNameOfObject ( ) : null ) + "', using stored procedure: " + proc , e ) ; if ( e instanceof SQLException ) { throw ( SQLException ) e ; } else { throw new PersistenceBrokerException ( "Unexpected error while bind values for class '" + ( cld != null ? cld . getClassNameOfObject ( ) : null ) + "', using stored procedure: " + proc ) ; } } // If we have a return value, then register it. if ( ( proc . hasReturnValue ( ) ) && ( callable != null ) ) { int jdbcType = proc . getReturnValueFieldRef ( ) . getJdbcType ( ) . getType ( ) ; m_platform . setNullForStatement ( stmt , valueSub + 1 , jdbcType ) ; callable . registerOutParameter ( valueSub + 1 , jdbcType ) ; valueSub ++ ; } // Process all of the arguments. Iterator iterator = proc . getArguments ( ) . iterator ( ) ; while ( iterator . hasNext ( ) ) { ArgumentDescriptor arg = ( ArgumentDescriptor ) iterator . next ( ) ; Object val = arg . getValue ( obj ) ; int jdbcType = arg . getJdbcType ( ) ; setObjectForStatement ( stmt , valueSub + 1 , val , jdbcType ) ; if ( ( arg . getIsReturnedByProcedure ( ) ) && ( callable != null ) ) { callable . registerOutParameter ( valueSub + 1 , jdbcType ) ; } valueSub ++ ; } }
Bind a prepared statment that represents a call to a procedure or user - defined function .
479
18
1,443
private void setObjectForStatement ( PreparedStatement stmt , int index , Object value , int sqlType ) throws SQLException { if ( value == null ) { m_platform . setNullForStatement ( stmt , index , sqlType ) ; } else { m_platform . setObjectForStatement ( stmt , index , value , sqlType ) ; } }
Sets object for statement at specific index adhering to platform - and null - rules .
79
19
1,444
public void remove ( Identity oid ) { if ( log . isDebugEnabled ( ) ) log . debug ( "Remove object " + oid ) ; sessionCache . remove ( oid ) ; getApplicationCache ( ) . remove ( oid ) ; }
Remove the corresponding object from session AND application cache .
54
10
1,445
private void putToSessionCache ( Identity oid , CacheEntry entry , boolean onlyIfNew ) { if ( onlyIfNew ) { // no synchronization needed, because session cache was used per broker instance if ( ! sessionCache . containsKey ( oid ) ) sessionCache . put ( oid , entry ) ; } else { sessionCache . put ( oid , entry ) ; } }
Put object to session cache .
81
6
1,446
private void processQueue ( ) { CacheEntry sv ; while ( ( sv = ( CacheEntry ) queue . poll ( ) ) != null ) { sessionCache . remove ( sv . oid ) ; } }
Make sure that the Identity objects of garbage collected cached objects are removed too .
43
15
1,447
public void beforeClose ( PBStateEvent event ) { /* arminw: this is a workaround for use in managed environments. When a PB instance is used within a container a PB.close call is done when leave the container method. This close the PB handle (but the real instance is still in use) and the PB listener are notified. But the JTA tx was not committed at this point in time and the session cache should not be cleared, because the updated/new objects will be pushed to the real cache on commit call (if we clear, nothing to push). So we check if the real broker is in a local tx (in this case we are in a JTA tx and the handle is closed), if true we don't reset the session cache. */ if ( ! broker . isInTransaction ( ) ) { if ( log . isDebugEnabled ( ) ) log . debug ( "Clearing the session cache" ) ; resetSessionCache ( ) ; } }
Before closing the PersistenceBroker ensure that the session cache is cleared
200
14
1,448
public boolean isUpToDate ( final DbArtifact artifact ) { final List < String > versions = repoHandler . getArtifactVersions ( artifact ) ; final String currentVersion = artifact . getVersion ( ) ; final String lastDevVersion = getLastVersion ( versions ) ; final String lastReleaseVersion = getLastRelease ( versions ) ; if ( lastDevVersion == null || lastReleaseVersion == null ) { // Plain Text comparison against version "strings" for ( final String version : versions ) { if ( version . compareTo ( currentVersion ) > 0 ) { return false ; } } return true ; } else { return currentVersion . equals ( lastDevVersion ) || currentVersion . equals ( lastReleaseVersion ) ; } }
Check if the current version match the last release or the last snapshot one
152
14
1,449
protected Object buildOrRefreshObject ( Map row , ClassDescriptor targetClassDescriptor , Object targetObject ) { Object result = targetObject ; FieldDescriptor fmd ; FieldDescriptor [ ] fields = targetClassDescriptor . getFieldDescriptor ( true ) ; if ( targetObject == null ) { // 1. create new object instance if needed result = ClassHelper . buildNewObjectInstance ( targetClassDescriptor ) ; } // 2. fill all scalar attributes of the new object for ( int i = 0 ; i < fields . length ; i ++ ) { fmd = fields [ i ] ; fmd . getPersistentField ( ) . set ( result , row . get ( fmd . getColumnName ( ) ) ) ; } if ( targetObject == null ) { // 3. for new build objects, invoke the initialization method for the class if one is provided Method initializationMethod = targetClassDescriptor . getInitializationMethod ( ) ; if ( initializationMethod != null ) { try { initializationMethod . invoke ( result , NO_ARGS ) ; } catch ( Exception ex ) { throw new PersistenceBrokerException ( "Unable to invoke initialization method:" + initializationMethod . getName ( ) + " for class:" + m_cld . getClassOfObject ( ) , ex ) ; } } } return result ; }
Creates an object instance according to clb and fills its fileds width data provided by row .
290
20
1,450
protected ClassDescriptor selectClassDescriptor ( Map row ) throws PersistenceBrokerException { ClassDescriptor result = m_cld ; Class ojbConcreteClass = ( Class ) row . get ( OJB_CONCRETE_CLASS_KEY ) ; if ( ojbConcreteClass != null ) { result = m_cld . getRepository ( ) . getDescriptorFor ( ojbConcreteClass ) ; // if we can't find class-descriptor for concrete class, something wrong with mapping if ( result == null ) { throw new PersistenceBrokerException ( "Can't find class-descriptor for ojbConcreteClass '" + ojbConcreteClass + "', the main class was " + m_cld . getClassNameOfObject ( ) ) ; } } return result ; }
Check if there is an attribute which tells us which concrete class is to be instantiated .
186
18
1,451
protected void load ( ) { properties = new Properties ( ) ; String filename = getFilename ( ) ; try { URL url = ClassHelper . getResource ( filename ) ; if ( url == null ) { url = ( new File ( filename ) ) . toURL ( ) ; } logger . info ( "Loading OJB's properties: " + url ) ; URLConnection conn = url . openConnection ( ) ; conn . setUseCaches ( false ) ; conn . connect ( ) ; InputStream strIn = conn . getInputStream ( ) ; properties . load ( strIn ) ; strIn . close ( ) ; } catch ( FileNotFoundException ex ) { // [tomdz] If the filename is explicitly reset (null or empty string) then we'll // output an info message because the user did this on purpose // Otherwise, we'll output a warning if ( ( filename == null ) || ( filename . length ( ) == 0 ) ) { logger . info ( "Starting OJB without a properties file. OJB is using default settings instead." ) ; } else { logger . warn ( "Could not load properties file '" + filename + "'. Using default settings!" , ex ) ; } // [tomdz] There seems to be no use of this setting ? //properties.put("valid", "false"); } catch ( Exception ex ) { throw new MetadataException ( "An error happend while loading the properties file '" + filename + "'" , ex ) ; } }
Loads the Configuration from the properties file .
313
9
1,452
public static void init ( ) { reports . clear ( ) ; Reflections reflections = new Reflections ( REPORTS_PACKAGE ) ; final Set < Class < ? extends Report > > reportClasses = reflections . getSubTypesOf ( Report . class ) ; for ( Class < ? extends Report > c : reportClasses ) { LOG . info ( "Report class: " + c . getName ( ) ) ; try { reports . add ( c . newInstance ( ) ) ; } catch ( IllegalAccessException | InstantiationException e ) { LOG . error ( "Error while loading report implementation classes" , e ) ; } } if ( LOG . isInfoEnabled ( ) ) { LOG . info ( String . format ( "Detected %s reports" , reports . size ( ) ) ) ; } }
Initializes the set of report implementation .
171
8
1,453
public InternalTile paint ( InternalTile tile ) throws RenderException { if ( tile . getContentType ( ) . equals ( VectorTileContentType . URL_CONTENT ) ) { if ( urlBuilder != null ) { if ( paintGeometries ) { urlBuilder . paintGeometries ( paintGeometries ) ; urlBuilder . paintLabels ( false ) ; tile . setFeatureContent ( urlBuilder . getImageUrl ( ) ) ; } if ( paintLabels ) { urlBuilder . paintGeometries ( false ) ; urlBuilder . paintLabels ( paintLabels ) ; tile . setLabelContent ( urlBuilder . getImageUrl ( ) ) ; } return tile ; } } return tile ; }
Painter the tile by building a URL where the image can be found .
150
15
1,454
public void addPropertyChangeListener ( String propertyName , java . beans . PropertyChangeListener listener ) { this . propertyChangeDelegate . addPropertyChangeListener ( propertyName , listener ) ; }
Add a new PropertyChangeListener to this node for a specific property . This functionality has been borrowed from the java . beans package though this class has nothing to do with a bean
40
35
1,455
public void removePropertyChangeListener ( String propertyName , java . beans . PropertyChangeListener listener ) { this . propertyChangeDelegate . removePropertyChangeListener ( propertyName , listener ) ; }
Remove a PropertyChangeListener for a specific property from this node . This functionality has . Please note that the listener this does not remove a listener that has been added without specifying the property it is interested in .
40
41
1,456
public void setAttribute ( String strKey , Object value ) { this . propertyChangeDelegate . firePropertyChange ( strKey , hmAttributes . put ( strKey , value ) , value ) ; }
Set an attribute of this node as Object . This method is backed by a HashMap so all rules of HashMap apply to this method . Fires a PropertyChangeEvent .
43
34
1,457
private void modifyBeliefCount ( int count ) { introspector . setBeliefValue ( getLocalName ( ) , Definitions . RECEIVED_MESSAGE_COUNT , getBeliefCount ( ) + count , null ) ; }
Modifies the msgCount belief
54
6
1,458
private int getBeliefCount ( ) { Integer count = ( Integer ) introspector . getBeliefBase ( ListenerMockAgent . this ) . get ( Definitions . RECEIVED_MESSAGE_COUNT ) ; if ( count == null ) count = 0 ; // Just in case, not really sure if this is necessary. return count ; }
Returns the msgCount belief
78
5
1,459
@ SuppressWarnings ( "unchecked" ) private void addParameters ( Model model , HttpServletRequest request ) { for ( Object objectEntry : request . getParameterMap ( ) . entrySet ( ) ) { Map . Entry < String , String [ ] > entry = ( Map . Entry < String , String [ ] > ) objectEntry ; String key = entry . getKey ( ) ; String [ ] values = entry . getValue ( ) ; if ( null != values && values . length > 0 ) { String value = values [ 0 ] ; try { model . addAttribute ( key , getParameter ( key , value ) ) ; } catch ( ParseException pe ) { log . error ( "Could not parse parameter value {} for {}, ignoring parameter." , key , value ) ; } catch ( NumberFormatException nfe ) { log . error ( "Could not parse parameter value {} for {}, ignoring parameter." , key , value ) ; } } } }
Add the extra parameters which are passed as report parameters . The type of the parameter is guessed from the first letter of the parameter name .
205
27
1,460
private Object getParameter ( String name , String value ) throws ParseException , NumberFormatException { Object result = null ; if ( name . length ( ) > 0 ) { switch ( name . charAt ( 0 ) ) { case ' ' : if ( null == value || value . length ( ) == 0 ) { value = "0" ; } result = new Integer ( value ) ; break ; case ' ' : if ( name . startsWith ( "form" ) ) { result = value ; } else { if ( null == value || value . length ( ) == 0 ) { value = "0.0" ; } result = new Double ( value ) ; } break ; case ' ' : if ( null == value || value . length ( ) == 0 ) { result = null ; } else { SimpleDateFormat dateParser = new SimpleDateFormat ( "yyyy-MM-dd" ) ; result = dateParser . parse ( value ) ; } break ; case ' ' : if ( null == value || value . length ( ) == 0 ) { result = null ; } else { SimpleDateFormat timeParser = new SimpleDateFormat ( "yyyy-MM-dd HH:mm:ss" ) ; result = timeParser . parse ( value ) ; } break ; case ' ' : result = "true" . equalsIgnoreCase ( value ) ? Boolean . TRUE : Boolean . FALSE ; break ; default : result = value ; } if ( log . isDebugEnabled ( ) ) { if ( result != null ) { log . debug ( "parameter " + name + " value " + result + " class " + result . getClass ( ) . getName ( ) ) ; } else { log . debug ( "parameter" + name + "is null" ) ; } } } return result ; }
Convert a query parameter to the correct object type based on the first letter of the name .
381
19
1,461
public SqlStatement getPreparedDeleteStatement ( ClassDescriptor cld ) { SqlForClass sfc = getSqlForClass ( cld ) ; SqlStatement sql = sfc . getDeleteSql ( ) ; if ( sql == null ) { ProcedureDescriptor pd = cld . getDeleteProcedure ( ) ; if ( pd == null ) { sql = new SqlDeleteByPkStatement ( cld , logger ) ; } else { sql = new SqlProcedureStatement ( pd , logger ) ; } // set the sql string sfc . setDeleteSql ( sql ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "SQL:" + sql . getStatement ( ) ) ; } } return sql ; }
generate a prepared DELETE - Statement for the Class described by cld .
169
17
1,462
public SqlStatement getPreparedInsertStatement ( ClassDescriptor cld ) { SqlStatement sql ; SqlForClass sfc = getSqlForClass ( cld ) ; sql = sfc . getInsertSql ( ) ; if ( sql == null ) { ProcedureDescriptor pd = cld . getInsertProcedure ( ) ; if ( pd == null ) { sql = new SqlInsertStatement ( cld , logger ) ; } else { sql = new SqlProcedureStatement ( pd , logger ) ; } // set the sql string sfc . setInsertSql ( sql ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "SQL:" + sql . getStatement ( ) ) ; } } return sql ; }
generate a prepared INSERT - Statement for the Class described by cld .
168
16
1,463
public SelectStatement getPreparedSelectByPkStatement ( ClassDescriptor cld ) { SelectStatement sql ; SqlForClass sfc = getSqlForClass ( cld ) ; sql = sfc . getSelectByPKSql ( ) ; if ( sql == null ) { sql = new SqlSelectByPkStatement ( m_platform , cld , logger ) ; // set the sql string sfc . setSelectByPKSql ( sql ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "SQL:" + sql . getStatement ( ) ) ; } } return sql ; }
generate a prepared SELECT - Statement for the Class described by cld
134
14
1,464
public SelectStatement getPreparedSelectStatement ( Query query , ClassDescriptor cld ) { SelectStatement sql = new SqlSelectStatement ( m_platform , cld , query , logger ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "SQL:" + sql . getStatement ( ) ) ; } return sql ; }
generate a select - Statement according to query
74
9
1,465
public SqlStatement getPreparedUpdateStatement ( ClassDescriptor cld ) { SqlForClass sfc = getSqlForClass ( cld ) ; SqlStatement result = sfc . getUpdateSql ( ) ; if ( result == null ) { ProcedureDescriptor pd = cld . getUpdateProcedure ( ) ; if ( pd == null ) { result = new SqlUpdateStatement ( cld , logger ) ; } else { result = new SqlProcedureStatement ( pd , logger ) ; } // set the sql string sfc . setUpdateSql ( result ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "SQL:" + result . getStatement ( ) ) ; } } return result ; }
generate a prepared UPDATE - Statement for the Class described by cld
166
14
1,466
private String toSQLClause ( FieldCriteria c , ClassDescriptor cld ) { String colName = toSqlClause ( c . getAttribute ( ) , cld ) ; return colName + c . getClause ( ) + c . getValue ( ) ; }
Answer the SQL - Clause for a FieldCriteria
61
10
1,467
public SqlStatement getPreparedDeleteStatement ( Query query , ClassDescriptor cld ) { return new SqlDeleteByQuery ( m_platform , cld , query , logger ) ; }
generate a prepared DELETE - Statement according to query
42
12
1,468
private boolean hasBidirectionalAssociation ( Class clazz ) { ClassDescriptor cdesc ; Collection refs ; boolean hasBidirAssc ; if ( _withoutBidirAssc . contains ( clazz ) ) { return false ; } if ( _withBidirAssc . contains ( clazz ) ) { return true ; } // first time we meet this class, let's look at metadata cdesc = _pb . getClassDescriptor ( clazz ) ; refs = cdesc . getObjectReferenceDescriptors ( ) ; hasBidirAssc = false ; REFS_CYCLE : for ( Iterator it = refs . iterator ( ) ; it . hasNext ( ) ; ) { ObjectReferenceDescriptor ord ; ClassDescriptor relCDesc ; Collection relRefs ; ord = ( ObjectReferenceDescriptor ) it . next ( ) ; relCDesc = _pb . getClassDescriptor ( ord . getItemClass ( ) ) ; relRefs = relCDesc . getObjectReferenceDescriptors ( ) ; for ( Iterator relIt = relRefs . iterator ( ) ; relIt . hasNext ( ) ; ) { ObjectReferenceDescriptor relOrd ; relOrd = ( ObjectReferenceDescriptor ) relIt . next ( ) ; if ( relOrd . getItemClass ( ) . equals ( clazz ) ) { hasBidirAssc = true ; break REFS_CYCLE ; } } } if ( hasBidirAssc ) { _withBidirAssc . add ( clazz ) ; } else { _withoutBidirAssc . add ( clazz ) ; } return hasBidirAssc ; }
Does the given class has bidirectional assiciation with some other class?
371
16
1,469
private ArrayList handleDependentReferences ( Identity oid , Object userObject , Object [ ] origFields , Object [ ] newFields , Object [ ] newRefs ) throws LockingException { ClassDescriptor mif = _pb . getClassDescriptor ( userObject . getClass ( ) ) ; FieldDescriptor [ ] fieldDescs = mif . getFieldDescriptions ( ) ; Collection refDescs = mif . getObjectReferenceDescriptors ( ) ; int count = 1 + fieldDescs . length ; ArrayList newObjects = new ArrayList ( ) ; int countRefs = 0 ; for ( Iterator it = refDescs . iterator ( ) ; it . hasNext ( ) ; count ++ , countRefs ++ ) { ObjectReferenceDescriptor rds = ( ObjectReferenceDescriptor ) it . next ( ) ; Identity origOid = ( origFields == null ? null : ( Identity ) origFields [ count ] ) ; Identity newOid = ( Identity ) newFields [ count ] ; if ( rds . getOtmDependent ( ) ) { if ( ( origOid == null ) && ( newOid != null ) ) { ContextEntry entry = ( ContextEntry ) _objects . get ( newOid ) ; if ( entry == null ) { Object relObj = newRefs [ countRefs ] ; insertInternal ( newOid , relObj , LockType . WRITE_LOCK , true , oid , new Stack ( ) ) ; newObjects . add ( newOid ) ; } } else if ( ( origOid != null ) && ( ( newOid == null ) || ! newOid . equals ( origOid ) ) ) { markDelete ( origOid , oid , false ) ; } } } return newObjects ; }
Mark for creation all newly introduced dependent references . Mark for deletion all nullified dependent references .
394
18
1,470
private ArrayList handleDependentCollections ( Identity oid , Object obj , Object [ ] origCollections , Object [ ] newCollections , Object [ ] newCollectionsOfObjects ) throws LockingException { ClassDescriptor mif = _pb . getClassDescriptor ( obj . getClass ( ) ) ; Collection colDescs = mif . getCollectionDescriptors ( ) ; ArrayList newObjects = new ArrayList ( ) ; int count = 0 ; for ( Iterator it = colDescs . iterator ( ) ; it . hasNext ( ) ; count ++ ) { CollectionDescriptor cds = ( CollectionDescriptor ) it . next ( ) ; if ( cds . getOtmDependent ( ) ) { ArrayList origList = ( origCollections == null ? null : ( ArrayList ) origCollections [ count ] ) ; ArrayList newList = ( ArrayList ) newCollections [ count ] ; if ( origList != null ) { for ( Iterator it2 = origList . iterator ( ) ; it2 . hasNext ( ) ; ) { Identity origOid = ( Identity ) it2 . next ( ) ; if ( ( newList == null ) || ! newList . contains ( origOid ) ) { markDelete ( origOid , oid , true ) ; } } } if ( newList != null ) { int countElem = 0 ; for ( Iterator it2 = newList . iterator ( ) ; it2 . hasNext ( ) ; countElem ++ ) { Identity newOid = ( Identity ) it2 . next ( ) ; if ( ( origList == null ) || ! origList . contains ( newOid ) ) { ContextEntry entry = ( ContextEntry ) _objects . get ( newOid ) ; if ( entry == null ) { ArrayList relCol = ( ArrayList ) newCollectionsOfObjects [ count ] ; Object relObj = relCol . get ( countElem ) ; insertInternal ( newOid , relObj , LockType . WRITE_LOCK , true , null , new Stack ( ) ) ; newObjects . add ( newOid ) ; } } } } } } return newObjects ; }
Mark for creation all objects that were included into dependent collections . Mark for deletion all objects that were excluded from dependent collections .
473
24
1,471
public void refresh ( String [ ] configLocations ) throws GeomajasException { try { setConfigLocations ( configLocations ) ; refresh ( ) ; } catch ( Exception e ) { throw new GeomajasException ( e , ExceptionCode . REFRESH_CONFIGURATION_FAILED ) ; } }
Refresh this context with the specified configuration locations .
70
10
1,472
public void rollback ( ) throws GeomajasException { try { setConfigLocations ( previousConfigLocations ) ; refresh ( ) ; } catch ( Exception e ) { throw new GeomajasException ( e , ExceptionCode . REFRESH_CONFIGURATION_FAILED ) ; } }
Roll back to the previous configuration .
66
7
1,473
public String getUrl ( ) { final StringBuilder sb = new StringBuilder ( ) ; sb . append ( "http://" ) ; sb . append ( getHttpConfiguration ( ) . getBindHost ( ) . get ( ) ) ; sb . append ( ":" ) ; sb . append ( getHttpConfiguration ( ) . getPort ( ) ) ; return sb . toString ( ) ; }
Returns the complete Grapes root URL
88
8
1,474
public void addRow ( final String ... cells ) { final Row row = new Row ( ( Object [ ] ) cells ) ; if ( ! rows . contains ( row ) ) { rows . add ( row ) ; } }
Add a row to the table if it does not already exist
46
12
1,475
private static String firstFoundTableName ( PersistenceBroker brokerForClass , ClassDescriptor cld ) { String name = null ; if ( ! cld . isInterface ( ) && cld . getFullTableName ( ) != null ) { return cld . getFullTableName ( ) ; } if ( cld . isExtent ( ) ) { Collection extentClasses = cld . getExtentClasses ( ) ; for ( Iterator iterator = extentClasses . iterator ( ) ; iterator . hasNext ( ) ; ) { name = firstFoundTableName ( brokerForClass , brokerForClass . getClassDescriptor ( ( Class ) iterator . next ( ) ) ) ; // System.out.println("## " + cld.getClassNameOfObject()+" - name: "+name); if ( name != null ) break ; } } return name ; }
try to find the first none null table name for the given class - descriptor . If cld has extent classes all of these cld s searched for the first none null table name .
189
37
1,476
public static long getMaxId ( PersistenceBroker brokerForClass , Class topLevel , FieldDescriptor original ) throws PersistenceBrokerException { long max = 0 ; long tmp ; ClassDescriptor cld = brokerForClass . getClassDescriptor ( topLevel ) ; // if class is not an interface / not abstract we have to search its directly mapped table if ( ! cld . isInterface ( ) && ! cld . isAbstract ( ) ) { tmp = getMaxIdForClass ( brokerForClass , cld , original ) ; if ( tmp > max ) { max = tmp ; } } // if class is an extent we have to search through its subclasses if ( cld . isExtent ( ) ) { Vector extentClasses = cld . getExtentClasses ( ) ; for ( int i = 0 ; i < extentClasses . size ( ) ; i ++ ) { Class extentClass = ( Class ) extentClasses . get ( i ) ; if ( cld . getClassOfObject ( ) . equals ( extentClass ) ) { throw new PersistenceBrokerException ( "Circular extent in " + extentClass + ", please check the repository" ) ; } else { // fix by Mark Rowell // Call recursive tmp = getMaxId ( brokerForClass , extentClass , original ) ; } if ( tmp > max ) { max = tmp ; } } } return max ; }
Search down all extent classes and return max of all found PK values .
302
14
1,477
public static long getMaxIdForClass ( PersistenceBroker brokerForClass , ClassDescriptor cldForOriginalOrExtent , FieldDescriptor original ) throws PersistenceBrokerException { FieldDescriptor field = null ; if ( ! original . getClassDescriptor ( ) . equals ( cldForOriginalOrExtent ) ) { // check if extent match not the same table if ( ! original . getClassDescriptor ( ) . getFullTableName ( ) . equals ( cldForOriginalOrExtent . getFullTableName ( ) ) ) { // we have to look for id's in extent class table field = cldForOriginalOrExtent . getFieldDescriptorByName ( original . getAttributeName ( ) ) ; } } else { field = original ; } if ( field == null ) { // if null skip this call return 0 ; } String column = field . getColumnName ( ) ; long result = 0 ; ResultSet rs = null ; Statement stmt = null ; StatementManagerIF sm = brokerForClass . serviceStatementManager ( ) ; String table = cldForOriginalOrExtent . getFullTableName ( ) ; // String column = cld.getFieldDescriptorByName(fieldName).getColumnName(); String sql = SM_SELECT_MAX + column + SM_FROM + table ; try { //lookup max id for the current class stmt = sm . getGenericStatement ( cldForOriginalOrExtent , Query . NOT_SCROLLABLE ) ; rs = stmt . executeQuery ( sql ) ; rs . next ( ) ; result = rs . getLong ( 1 ) ; } catch ( Exception e ) { log . warn ( "Cannot lookup max value from table " + table + " for column " + column + ", PB was " + brokerForClass + ", using jdbc-descriptor " + brokerForClass . serviceConnectionManager ( ) . getConnectionDescriptor ( ) , e ) ; } finally { try { sm . closeResources ( stmt , rs ) ; } catch ( Exception ignore ) { // ignore it } } return result ; }
lookup current maximum value for a single field in table the given class descriptor was associated .
457
18
1,478
public static Identity fromByteArray ( final byte [ ] anArray ) throws PersistenceBrokerException { // reverse of the serialize() algorithm: // read from byte[] with a ByteArrayInputStream, decompress with // a GZIPInputStream and then deserialize by reading from the ObjectInputStream try { final ByteArrayInputStream bais = new ByteArrayInputStream ( anArray ) ; final GZIPInputStream gis = new GZIPInputStream ( bais ) ; final ObjectInputStream ois = new ObjectInputStream ( gis ) ; final Identity result = ( Identity ) ois . readObject ( ) ; ois . close ( ) ; gis . close ( ) ; bais . close ( ) ; return result ; } catch ( Exception ex ) { throw new PersistenceBrokerException ( ex ) ; } }
Factory method that returns an Identity object created from a serializated representation .
179
15
1,479
public byte [ ] serialize ( ) throws PersistenceBrokerException { // Identity is serialized and written to an ObjectOutputStream // This ObjectOutputstream is compressed by a GZIPOutputStream // and finally written to a ByteArrayOutputStream. // the resulting byte[] is returned try { final ByteArrayOutputStream bao = new ByteArrayOutputStream ( ) ; final GZIPOutputStream gos = new GZIPOutputStream ( bao ) ; final ObjectOutputStream oos = new ObjectOutputStream ( gos ) ; oos . writeObject ( this ) ; oos . close ( ) ; gos . close ( ) ; bao . close ( ) ; return bao . toByteArray ( ) ; } catch ( Exception ignored ) { throw new PersistenceBrokerException ( ignored ) ; } }
Return the serialized form of this Identity .
173
9
1,480
protected void checkForPrimaryKeys ( final Object realObject ) throws ClassNotPersistenceCapableException { // if no PKs are specified OJB can't handle this class ! if ( m_pkValues == null || m_pkValues . length == 0 ) { throw createException ( "OJB needs at least one primary key attribute for class: " , realObject , null ) ; } // arminw: should never happen // if(m_pkValues[0] instanceof ValueContainer) // throw new OJBRuntimeException("Can't handle pk values of type "+ValueContainer.class.getName()); }
OJB can handle only classes that declare at least one primary key attribute this method checks this condition .
133
20
1,481
public TileMap getCapabilities ( TmsLayer layer ) throws TmsLayerException { try { // Create a JaxB unmarshaller: JAXBContext context = JAXBContext . newInstance ( TileMap . class ) ; Unmarshaller um = context . createUnmarshaller ( ) ; // Find out where to retrieve the capabilities and unmarshall: if ( layer . getBaseTmsUrl ( ) . startsWith ( CLASSPATH ) ) { String location = layer . getBaseTmsUrl ( ) . substring ( CLASSPATH . length ( ) ) ; if ( location . length ( ) > 0 && location . charAt ( 0 ) == ' ' ) { // classpath resources should not start with a slash, but they often do location = location . substring ( 1 ) ; } ClassLoader cl = Thread . currentThread ( ) . getContextClassLoader ( ) ; if ( null == cl ) { cl = getClass ( ) . getClassLoader ( ) ; // NOSONAR fallback from proper behaviour for some environments } InputStream is = cl . getResourceAsStream ( location ) ; if ( null != is ) { try { return ( TileMap ) um . unmarshal ( is ) ; } finally { try { is . close ( ) ; } catch ( IOException ioe ) { // ignore, just closing the stream } } } throw new TmsLayerException ( TmsLayerException . COULD_NOT_FIND_FILE , layer . getBaseTmsUrl ( ) ) ; } // Normal case, find the URL and unmarshal: return ( TileMap ) um . unmarshal ( httpService . getStream ( layer . getBaseTmsUrl ( ) , layer ) ) ; } catch ( JAXBException e ) { throw new TmsLayerException ( e , TmsLayerException . COULD_NOT_READ_FILE , layer . getBaseTmsUrl ( ) ) ; } catch ( IOException e ) { throw new TmsLayerException ( e , TmsLayerException . COULD_NOT_READ_FILE , layer . getBaseTmsUrl ( ) ) ; } }
Get the configuration for a TMS layer by retrieving and parsing it s XML description file . The parsing is done using JaxB .
464
27
1,482
public RasterLayerInfo asLayerInfo ( TileMap tileMap ) { RasterLayerInfo layerInfo = new RasterLayerInfo ( ) ; layerInfo . setCrs ( tileMap . getSrs ( ) ) ; layerInfo . setDataSourceName ( tileMap . getTitle ( ) ) ; layerInfo . setLayerType ( LayerType . RASTER ) ; layerInfo . setMaxExtent ( asBbox ( tileMap . getBoundingBox ( ) ) ) ; layerInfo . setTileHeight ( tileMap . getTileFormat ( ) . getHeight ( ) ) ; layerInfo . setTileWidth ( tileMap . getTileFormat ( ) . getWidth ( ) ) ; List < ScaleInfo > zoomLevels = new ArrayList < ScaleInfo > ( tileMap . getTileSets ( ) . getTileSets ( ) . size ( ) ) ; for ( TileSet tileSet : tileMap . getTileSets ( ) . getTileSets ( ) ) { zoomLevels . add ( asScaleInfo ( tileSet ) ) ; } layerInfo . setZoomLevels ( zoomLevels ) ; return layerInfo ; }
Transform a TMS layer description object into a raster layer info object .
246
15
1,483
private void init_jdbcTypes ( ) throws SQLException { ReportQuery q = ( ReportQuery ) getQueryObject ( ) . getQuery ( ) ; m_jdbcTypes = new int [ m_attributeCount ] ; // try to get jdbcTypes from Query if ( q . getJdbcTypes ( ) != null ) { m_jdbcTypes = q . getJdbcTypes ( ) ; } else { ResultSetMetaData rsMetaData = getRsAndStmt ( ) . m_rs . getMetaData ( ) ; for ( int i = 0 ; i < m_attributeCount ; i ++ ) { m_jdbcTypes [ i ] = rsMetaData . getColumnType ( i + 1 ) ; } } }
get the jdbcTypes from the Query or the ResultSet if not available from the Query
166
19
1,484
private int getLiteralId ( String literal ) throws PersistenceBrokerException { ////logger.debug("lookup: " + literal); try { return tags . getIdByTag ( literal ) ; } catch ( NullPointerException t ) { throw new MetadataException ( "unknown literal: '" + literal + "'" , t ) ; } }
returns the XmlCapable id associated with the literal . OJB maintains a RepositoryTags table that provides a mapping from xml - tags to XmlCapable ids .
78
37
1,485
public final boolean hasReturnValues ( ) { if ( this . hasReturnValue ( ) ) { return true ; } else { // TODO: We may be able to 'pre-calculate' the results // of this loop by just checking arguments as they are added // The only problem is that the 'isReturnedbyProcedure' property // can be modified once the argument is added to this procedure. // If that occurs, then 'pre-calculated' results will be inacccurate. Iterator iter = this . getArguments ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { ArgumentDescriptor arg = ( ArgumentDescriptor ) iter . next ( ) ; if ( arg . getIsReturnedByProcedure ( ) ) { return true ; } } } return false ; }
Does this procedure return any values to the caller ?
176
10
1,486
protected void addArguments ( FieldDescriptor field [ ] ) { for ( int i = 0 ; i < field . length ; i ++ ) { ArgumentDescriptor arg = new ArgumentDescriptor ( this ) ; arg . setValue ( field [ i ] . getAttributeName ( ) , false ) ; this . addArgument ( arg ) ; } }
Set up arguments for each FieldDescriptor in an array .
77
13
1,487
@ Api public void setNamedRoles ( Map < String , List < NamedRoleInfo > > namedRoles ) { this . namedRoles = namedRoles ; ldapRoleMapping = new HashMap < String , Set < String > > ( ) ; for ( String roleName : namedRoles . keySet ( ) ) { if ( ! ldapRoleMapping . containsKey ( roleName ) ) { ldapRoleMapping . put ( roleName , new HashSet < String > ( ) ) ; } for ( NamedRoleInfo role : namedRoles . get ( roleName ) ) { ldapRoleMapping . get ( roleName ) . add ( role . getName ( ) ) ; } } }
Set the named roles which may be defined .
159
9
1,488
public void setPixelPerUnit ( double pixelPerUnit ) { if ( pixelPerUnit < MINIMUM_PIXEL_PER_UNIT ) { pixelPerUnit = MINIMUM_PIXEL_PER_UNIT ; } if ( pixelPerUnit > MAXIMUM_PIXEL_PER_UNIT ) { pixelPerUnit = MAXIMUM_PIXEL_PER_UNIT ; } this . pixelPerUnit = pixelPerUnit ; setPixelPerUnitBased ( true ) ; postConstruct ( ) ; }
Sets the scale value in pixel per map unit .
114
11
1,489
@ PostConstruct protected void postConstruct ( ) { if ( pixelPerUnitBased ) { // Calculate numerator and denominator if ( pixelPerUnit > PIXEL_PER_METER ) { this . numerator = pixelPerUnit / conversionFactor ; this . denominator = 1 ; } else { this . numerator = 1 ; this . denominator = PIXEL_PER_METER / pixelPerUnit ; } setPixelPerUnitBased ( false ) ; } else { // Calculate PPU this . pixelPerUnit = numerator / denominator * conversionFactor ; setPixelPerUnitBased ( true ) ; } }
Finish configuration .
133
3
1,490
void nextExecuted ( String sql ) throws SQLException { count ++ ; if ( _order . contains ( sql ) ) { return ; } String sqlCmd = sql . substring ( 0 , 7 ) ; String rest = sql . substring ( sqlCmd . equals ( "UPDATE " ) ? 7 // "UPDATE " : 12 ) ; // "INSERT INTO " or "DELETE FROM " String tableName = rest . substring ( 0 , rest . indexOf ( ' ' ) ) ; HashSet fkTables = ( HashSet ) _fkInfo . get ( tableName ) ; // we should not change order of INSERT/DELETE/UPDATE // statements for the same table if ( _touched . contains ( tableName ) ) { executeBatch ( ) ; } if ( sqlCmd . equals ( "INSERT " ) ) { if ( _dontInsert != null && _dontInsert . contains ( tableName ) ) { // one of the previous INSERTs contained a table // that references this table. // Let's execute that previous INSERT right now so that // in the future INSERTs into this table will go first // in the _order array. executeBatch ( ) ; } } else //if (sqlCmd.equals("DELETE ") || sqlCmd.equals("UPDATE ")) { // We process UPDATEs in the same way as DELETEs // because setting FK to NULL in UPDATE is equivalent // to DELETE from the referential integrity point of view. if ( _deleted != null && fkTables != null ) { HashSet intersection = ( HashSet ) _deleted . clone ( ) ; intersection . retainAll ( fkTables ) ; if ( ! intersection . isEmpty ( ) ) { // one of the previous DELETEs contained a table // that is referenced from this table. // Let's execute that previous DELETE right now so that // in the future DELETEs into this table will go first // in the _order array. executeBatch ( ) ; } } } _order . add ( sql ) ; _touched . add ( tableName ) ; if ( sqlCmd . equals ( "INSERT " ) ) { if ( fkTables != null ) { if ( _dontInsert == null ) { _dontInsert = new HashSet ( ) ; } _dontInsert . addAll ( fkTables ) ; } } else if ( sqlCmd . equals ( "DELETE " ) ) { if ( _deleted == null ) { _deleted = new HashSet ( ) ; } _deleted . add ( tableName ) ; } }
Remember the order of execution
572
5
1,491
private PreparedStatement prepareBatchStatement ( String sql ) { String sqlCmd = sql . substring ( 0 , 7 ) ; if ( sqlCmd . equals ( "UPDATE " ) || sqlCmd . equals ( "DELETE " ) || ( _useBatchInserts && sqlCmd . equals ( "INSERT " ) ) ) { PreparedStatement stmt = ( PreparedStatement ) _statements . get ( sql ) ; if ( stmt == null ) { // [olegnitz] for JDK 1.2 we need to list both PreparedStatement and Statement // interfaces, otherwise proxy.jar works incorrectly stmt = ( PreparedStatement ) Proxy . newProxyInstance ( getClass ( ) . getClassLoader ( ) , new Class [ ] { PreparedStatement . class , Statement . class , BatchPreparedStatement . class } , new PreparedStatementInvocationHandler ( this , sql , m_jcd ) ) ; _statements . put ( sql , stmt ) ; } return stmt ; } else { return null ; } }
If UPDATE INSERT or DELETE return BatchPreparedStatement otherwise return null .
225
18
1,492
public static void generateJavaFiles ( String requirementsFolder , String platformName , String src_test_dir , String tests_package , String casemanager_package , String loggingPropFile ) throws Exception { File reqFolder = new File ( requirementsFolder ) ; if ( reqFolder . isDirectory ( ) ) { for ( File f : reqFolder . listFiles ( ) ) { if ( f . getName ( ) . endsWith ( ".story" ) ) { try { SystemReader . generateJavaFilesForOneStory ( f . getCanonicalPath ( ) , platformName , src_test_dir , tests_package , casemanager_package , loggingPropFile ) ; } catch ( IOException e ) { String message = "ERROR: " + e . getMessage ( ) ; logger . severe ( message ) ; throw new BeastException ( message , e ) ; } } } for ( File f : reqFolder . listFiles ( ) ) { if ( f . isDirectory ( ) ) { SystemReader . generateJavaFiles ( requirementsFolder + File . separator + f . getName ( ) , platformName , src_test_dir , tests_package + "." + f . getName ( ) , casemanager_package , loggingPropFile ) ; } } } else if ( reqFolder . getName ( ) . endsWith ( ".story" ) ) { SystemReader . generateJavaFilesForOneStory ( requirementsFolder , platformName , src_test_dir , tests_package , casemanager_package , loggingPropFile ) ; } else { String message = "No story file found in " + requirementsFolder ; logger . severe ( message ) ; throw new BeastException ( message ) ; } }
Main method of the class which handles the process of creating the tests
359
13
1,493
public void setPromoted ( final boolean promoted ) { this . promoted = promoted ; for ( final Artifact artifact : artifacts ) { artifact . setPromoted ( promoted ) ; } for ( final Module suModule : submodules ) { suModule . setPromoted ( promoted ) ; } }
Sets the promotion state .
59
6
1,494
public void addDependency ( final Dependency dependency ) { if ( dependency != null && ! dependencies . contains ( dependency ) ) { this . dependencies . add ( dependency ) ; } }
Add a dependency to the module .
39
7
1,495
public void addSubmodule ( final Module submodule ) { if ( ! submodules . contains ( submodule ) ) { submodule . setSubmodule ( true ) ; if ( promoted ) { submodule . setPromoted ( promoted ) ; } submodules . add ( submodule ) ; } }
Adds a submodule to the module .
62
8
1,496
public void addArtifact ( final Artifact artifact ) { if ( ! artifacts . contains ( artifact ) ) { if ( promoted ) { artifact . setPromoted ( promoted ) ; } artifacts . add ( artifact ) ; } }
Adds an artifact to the module .
46
7
1,497
public static String get ( MessageKey key ) { return data . getProperty ( key . toString ( ) , key . toString ( ) ) ; }
Retrieves the configured message by property key
32
9
1,498
private static void loadFile ( String filePath ) { final Path path = FileSystems . getDefault ( ) . getPath ( filePath ) ; try { data . clear ( ) ; data . load ( Files . newBufferedReader ( path ) ) ; } catch ( IOException e ) { LOG . warn ( "Exception while loading " + path . toString ( ) , e ) ; } }
Loads the file content in the properties collection
84
9
1,499
public void setValue ( String constantValue ) { this . fieldSource = SOURCE_VALUE ; this . fieldRefName = null ; this . returnedByProcedure = false ; this . constantValue = constantValue ; }
Sets up this object to represent an argument that will be set to a constant value .
47
18