use of org.datanucleus.Configuration in project datanucleus-rdbms by datanucleus.
the class RDBMSQueryUtils method prepareStatementForExecution.
/**
* Method to apply any restrictions to the created ResultSet.
* @param ps The PreparedStatement
* @param query The query
* @param applyTimeout Whether to apply the query timeout (if any) direct to the PreparedStatement
* @throws SQLException Thrown when an error occurs applying the constraints
*/
public static void prepareStatementForExecution(PreparedStatement ps, Query query, boolean applyTimeout) throws SQLException {
if (applyTimeout) {
Integer timeout = query.getDatastoreReadTimeoutMillis();
if (timeout != null && timeout > 0) {
ps.setQueryTimeout(timeout / 1000);
}
}
// Apply any fetch size
int fetchSize = 0;
if (query.getFetchPlan().getFetchSize() > 0) {
// FetchPlan has a size set so use that
fetchSize = query.getFetchPlan().getFetchSize();
}
if (((RDBMSStoreManager) query.getStoreManager()).getDatastoreAdapter().supportsQueryFetchSize(fetchSize)) {
ps.setFetchSize(fetchSize);
}
// Apply any fetch direction
Configuration conf = query.getExecutionContext().getNucleusContext().getConfiguration();
String fetchDir = conf.getStringProperty(RDBMSPropertyNames.PROPERTY_RDBMS_QUERY_FETCH_DIRECTION);
Object fetchDirExt = query.getExtension(RDBMSPropertyNames.PROPERTY_RDBMS_QUERY_FETCH_DIRECTION);
if (fetchDirExt != null) {
fetchDir = (String) fetchDirExt;
if (!fetchDir.equals("forward") && !fetchDir.equals("reverse") && !fetchDir.equals("unknown")) {
throw new NucleusUserException(Localiser.msg("052512"));
}
}
if (fetchDir.equals("reverse")) {
ps.setFetchDirection(ResultSet.FETCH_REVERSE);
} else if (fetchDir.equals("unknown")) {
ps.setFetchDirection(ResultSet.FETCH_UNKNOWN);
}
// Add a limit on the number of rows to include the maximum we may need
long toExclNo = query.getRangeToExcl();
if (toExclNo != 0 && toExclNo != Long.MAX_VALUE) {
if (toExclNo > Integer.MAX_VALUE) {
// setMaxRows takes an int as input so limit to the correct range
ps.setMaxRows(Integer.MAX_VALUE);
} else {
ps.setMaxRows((int) toExclNo);
}
}
}
use of org.datanucleus.Configuration in project datanucleus-core by datanucleus.
the class SchemaTool method getNucleusContextForMode.
/**
* Method to create a NucleusContext for the specified mode of SchemaTool
* @param mode Mode of operation of SchemaTool
* @param api Persistence API
* @param userProps Map containing user provided properties (usually input via a file)
* @param persistenceUnitName Name of the persistence-unit (if any)
* @param ddlFile Name of a file to output DDL to
* @param verbose Verbose mode
* @param ignoreMetaDataForMissingClasses Whether to ignore metadata for missing classes
* @return The NucleusContext to use
* @throws NucleusException Thrown if an error occurs in creating the required NucleusContext
*/
public static StoreNucleusContext getNucleusContextForMode(Mode mode, String api, Map userProps, String persistenceUnitName, String ddlFile, boolean verbose, boolean ignoreMetaDataForMissingClasses) {
// Extract any properties that affect NucleusContext startup
Map startupProps = null;
if (userProps != null) {
// Possible properties to check for
for (String startupPropName : AbstractNucleusContext.STARTUP_PROPERTIES) {
if (userProps.containsKey(startupPropName)) {
if (startupProps == null) {
startupProps = new HashMap();
}
startupProps.put(startupPropName, userProps.get(startupPropName));
}
}
}
// Initialise the context for this API
PersistenceNucleusContext nucleusCtx = new PersistenceNucleusContextImpl(api, startupProps);
Configuration propConfig = nucleusCtx.getConfiguration();
// Generate list of properties for SchemaTool usage
Map props = new HashMap();
// Get properties from PersistenceUnit first...
PersistenceUnitMetaData pumd = null;
if (persistenceUnitName != null) {
props.put(PropertyNames.PROPERTY_PERSISTENCE_UNIT_NAME.toLowerCase(), persistenceUnitName);
// Extract the persistence-unit metadata
String filename = nucleusCtx.getConfiguration().getStringProperty(PropertyNames.PROPERTY_PERSISTENCE_XML_FILENAME);
boolean validateXML = nucleusCtx.getConfiguration().getBooleanProperty(PropertyNames.PROPERTY_METADATA_XML_VALIDATE);
boolean supportXMLNamespaces = nucleusCtx.getConfiguration().getBooleanProperty(PropertyNames.PROPERTY_METADATA_XML_NAMESPACE_AWARE);
ClassLoaderResolver clr = nucleusCtx.getClassLoaderResolver(null);
pumd = MetaDataUtils.getMetaDataForPersistenceUnit(nucleusCtx.getPluginManager(), filename, persistenceUnitName, validateXML, supportXMLNamespaces, clr);
if (pumd != null) {
// Add the properties for the unit
if (pumd.getProperties() != null) {
props.putAll(pumd.getProperties());
}
} else {
throw new NucleusUserException("SchemaTool has been specified to use persistence-unit with name " + persistenceUnitName + " but none was found with that name");
}
if (api.equalsIgnoreCase("JPA")) {
// Don't use JARs when in JavaSE for JPA
pumd.clearJarFiles();
}
}
// Add/override with user properties
if (userProps != null) {
// Properties specified by the user in a file
for (Object key : userProps.keySet()) {
String propName = (String) key;
props.put(propName.toLowerCase(Locale.ENGLISH), userProps.get(propName));
}
}
// Finally add/override with system properties (only support particular ones, and in correct case)
String[] propNames = { PropertyNames.PROPERTY_CONNECTION_URL, PropertyNames.PROPERTY_CONNECTION_DRIVER_NAME, PropertyNames.PROPERTY_CONNECTION_USER_NAME, PropertyNames.PROPERTY_CONNECTION_PASSWORD, PropertyNames.PROPERTY_MAPPING, "javax.jdo.option.ConnectionURL", "javax.jdo.option.ConnectionDriverName", "javax.jdo.option.ConnectionUserName", "javax.jdo.option.ConnectionPassword", "javax.jdo.option.Mapping", "javax.persistence.jdbc.url", "javax.persistence.jdbc.driver", "javax.persistence.jdbc.user", "javax.persistence.jdbc.password" };
for (int i = 0; i < propNames.length; i++) {
if (System.getProperty(propNames[i]) != null) {
props.put(propNames[i].toLowerCase(Locale.ENGLISH), System.getProperty(propNames[i]));
}
}
// Interferes with usage
props.put(PropertyNames.PROPERTY_AUTOSTART_MECHANISM.toLowerCase(), "None");
// Tag on the mandatory props that we must have for each mode
if (mode == Mode.CREATE) {
if (ddlFile != null) {
// the tables must not be created in the DB, so do not validate (DDL is being output to a file)
props.put(PropertyNames.PROPERTY_SCHEMA_VALIDATE_TABLES.toLowerCase(), "false");
props.put(PropertyNames.PROPERTY_SCHEMA_VALIDATE_COLUMNS.toLowerCase(), "false");
props.put(PropertyNames.PROPERTY_SCHEMA_VALIDATE_CONSTRAINTS.toLowerCase(), "false");
}
// use tables/columns/constraints settings
props.remove(PropertyNames.PROPERTY_SCHEMA_AUTOCREATE_ALL.toLowerCase());
if (!props.containsKey(PropertyNames.PROPERTY_SCHEMA_AUTOCREATE_TABLES.toLowerCase())) {
props.put(PropertyNames.PROPERTY_SCHEMA_AUTOCREATE_TABLES.toLowerCase(), "true");
}
if (!props.containsKey(PropertyNames.PROPERTY_SCHEMA_AUTOCREATE_COLUMNS.toLowerCase())) {
props.put(PropertyNames.PROPERTY_SCHEMA_AUTOCREATE_COLUMNS.toLowerCase(), "true");
}
if (!props.containsKey(PropertyNames.PROPERTY_SCHEMA_AUTOCREATE_CONSTRAINTS.toLowerCase())) {
props.put(PropertyNames.PROPERTY_SCHEMA_AUTOCREATE_CONSTRAINTS.toLowerCase(), "true");
}
props.put(PropertyNames.PROPERTY_DATASTORE_READONLY.toLowerCase(), "false");
props.put("datanucleus.rdbms.checkexisttablesorviews", "true");
} else if (mode == Mode.DELETE) {
props.put(PropertyNames.PROPERTY_DATASTORE_READONLY.toLowerCase(), "false");
} else if (mode == Mode.DELETE_CREATE) {
if (ddlFile != null) {
// the tables must not be created in the DB, so do not validate (DDL is being output to a file)
props.put(PropertyNames.PROPERTY_SCHEMA_VALIDATE_TABLES.toLowerCase(), "false");
props.put(PropertyNames.PROPERTY_SCHEMA_VALIDATE_COLUMNS.toLowerCase(), "false");
props.put(PropertyNames.PROPERTY_SCHEMA_VALIDATE_CONSTRAINTS.toLowerCase(), "false");
}
// use tables/columns/constraints settings
props.remove(PropertyNames.PROPERTY_SCHEMA_AUTOCREATE_ALL.toLowerCase());
if (!props.containsKey(PropertyNames.PROPERTY_SCHEMA_AUTOCREATE_TABLES.toLowerCase())) {
props.put(PropertyNames.PROPERTY_SCHEMA_AUTOCREATE_TABLES.toLowerCase(), "true");
}
if (!props.containsKey(PropertyNames.PROPERTY_SCHEMA_AUTOCREATE_COLUMNS.toLowerCase())) {
props.put(PropertyNames.PROPERTY_SCHEMA_AUTOCREATE_COLUMNS.toLowerCase(), "true");
}
if (!props.containsKey(PropertyNames.PROPERTY_SCHEMA_AUTOCREATE_CONSTRAINTS.toLowerCase())) {
props.put(PropertyNames.PROPERTY_SCHEMA_AUTOCREATE_CONSTRAINTS.toLowerCase(), "true");
}
props.put(PropertyNames.PROPERTY_DATASTORE_READONLY.toLowerCase(), "false");
props.put("datanucleus.rdbms.checkexisttablesorviews", "true");
} else if (mode == Mode.VALIDATE) {
props.put(PropertyNames.PROPERTY_SCHEMA_AUTOCREATE_ALL.toLowerCase(), "false");
props.put(PropertyNames.PROPERTY_SCHEMA_AUTOCREATE_TABLES.toLowerCase(), "false");
props.put(PropertyNames.PROPERTY_SCHEMA_AUTOCREATE_CONSTRAINTS.toLowerCase(), "false");
props.put(PropertyNames.PROPERTY_SCHEMA_AUTOCREATE_COLUMNS.toLowerCase(), "false");
props.put(PropertyNames.PROPERTY_SCHEMA_VALIDATE_TABLES.toLowerCase(), "true");
props.put(PropertyNames.PROPERTY_SCHEMA_VALIDATE_COLUMNS.toLowerCase(), "true");
props.put(PropertyNames.PROPERTY_SCHEMA_VALIDATE_CONSTRAINTS.toLowerCase(), "true");
}
if (ignoreMetaDataForMissingClasses) {
props.put(PropertyNames.PROPERTY_METADATA_IGNORE_METADATA_FOR_MISSING_CLASSES, "true");
}
// Apply remaining persistence properties
propConfig.setPersistenceProperties(props);
if (pumd != null) {
// Initialise the MetaDataManager with all files/classes for this persistence-unit
// This is done now that all persistence properties are set (including the persistence-unit props)
nucleusCtx.getMetaDataManager().loadPersistenceUnit(pumd, null);
}
// Initialise the NucleusContext for use
nucleusCtx.initialise();
if (verbose) {
String msg = Localiser.msg("014020");
LOGGER.info(msg);
System.out.println(msg);
// TODO Some persistence properties will be stored against the StoreManager
Map<String, Object> pmfProps = propConfig.getPersistenceProperties();
Set<String> keys = pmfProps.keySet();
List<String> keyNames = new ArrayList<String>(keys);
Collections.sort(keyNames);
Iterator keyNamesIter = keyNames.iterator();
while (keyNamesIter.hasNext()) {
String key = (String) keyNamesIter.next();
Object value = pmfProps.get(key);
boolean display = true;
if (!key.startsWith("datanucleus")) {
display = false;
} else if (key.equals(PropertyNames.PROPERTY_CONNECTION_PASSWORD.toLowerCase())) {
// Don't show passwords
display = false;
} else if (value == null) {
display = false;
} else if (value instanceof String && StringUtils.isWhitespace((String) value)) {
display = false;
}
if (display) {
// Print the property to sysout
msg = Localiser.msg("014022", key, value);
LOGGER.info(msg);
System.out.println(msg);
}
}
System.out.println();
}
return nucleusCtx;
}
use of org.datanucleus.Configuration in project datanucleus-rdbms by datanucleus.
the class NucleusSequenceImpl method setGenerator.
/**
* Method to set the value generator.
* Uses "sequence" if the datastore supports it, otherwise "increment".
*/
public void setGenerator() {
// Allocate the ValueGenerationManager for this sequence
String valueGeneratorName = null;
if (((RDBMSStoreManager) storeManager).getDatastoreAdapter().supportsOption(DatastoreAdapter.SEQUENCES)) {
valueGeneratorName = ValueGenerationStrategy.SEQUENCE.toString();
} else {
valueGeneratorName = ValueGenerationStrategy.INCREMENT.toString();
}
// Create the controlling properties for this sequence
Properties props = new Properties();
Map<String, String> seqExtensions = seqMetaData.getExtensions();
if (seqExtensions != null && seqExtensions.size() > 0) {
props.putAll(seqExtensions);
}
props.put(ValueGenerator.PROPERTY_SEQUENCE_NAME, seqMetaData.getDatastoreSequence());
if (seqMetaData.getAllocationSize() > 0) {
props.put(ValueGenerator.PROPERTY_KEY_CACHE_SIZE, "" + seqMetaData.getAllocationSize());
}
if (seqMetaData.getInitialValue() > 0) {
props.put(ValueGenerator.PROPERTY_KEY_INITIAL_VALUE, "" + seqMetaData.getInitialValue());
}
// Get a ValueGenerationManager to create the generator
ValueGenerationManager mgr = storeManager.getValueGenerationManager();
ValueGenerationConnectionProvider connProvider = new ValueGenerationConnectionProvider() {
ManagedConnection mconn;
public ManagedConnection retrieveConnection() {
// Obtain a new connection
// Note : it may be worthwhile to use the PM's connection here however where a Sequence doesnt yet
// exist the connection would then be effectively dead until the end of the tx
// The way around this would be to find a way of checking for existence of the sequence
Configuration conf = ec.getNucleusContext().getConfiguration();
int isolationLevel = TransactionUtils.getTransactionIsolationLevelForName(conf.getStringProperty(PropertyNames.PROPERTY_VALUEGEN_TXN_ISOLATION));
this.mconn = ((RDBMSStoreManager) storeManager).getConnectionManager().getConnection(isolationLevel);
return mconn;
}
public void releaseConnection() {
try {
// Release the connection
mconn.release();
} catch (NucleusException e) {
NucleusLogger.PERSISTENCE.error(Localiser.msg("017007", e));
throw e;
}
}
};
generator = mgr.createValueGenerator(valueGeneratorName, seqMetaData.getName(), props, connProvider);
if (NucleusLogger.PERSISTENCE.isDebugEnabled()) {
NucleusLogger.PERSISTENCE.debug(Localiser.msg("017003", seqMetaData.getName(), valueGeneratorName));
}
}
use of org.datanucleus.Configuration in project datanucleus-rdbms by datanucleus.
the class AbstractConnectionPoolFactory method getPropertiesForDriver.
/**
* Convenience method to return the properties to pass to the driver.
* Includes as a minimum "user" and "password", but a user may define a persistence property with name
* "datanucleus.connectionPool.driverProps" then is a comma separated name-value pair that are
* treated as properties
* @param storeMgr StoreManager
* @return The properties for the driver
*/
public static Properties getPropertiesForDriver(StoreManager storeMgr) {
Properties dbProps = new Properties();
String dbUser = storeMgr.getConnectionUserName();
if (dbUser == null) {
// Some RDBMS (e.g Postgresql) don't like null usernames
dbUser = "";
}
dbProps.setProperty("user", dbUser);
String dbPassword = storeMgr.getConnectionPassword();
if (dbPassword == null) {
// Some RDBMS (e.g Postgresql) don't like null passwords
dbPassword = "";
}
dbProps.setProperty("password", dbPassword);
// Optional driver properties
Configuration conf = storeMgr.getNucleusContext().getConfiguration();
String drvPropsString = (String) conf.getProperty(RDBMSPropertyNames.PROPERTY_CONNECTION_POOL_DRIVER_PROPS);
if (drvPropsString != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintWriter pw = new PrintWriter(baos);
StringTokenizer st = new StringTokenizer(drvPropsString, ",");
while (st.hasMoreTokens()) {
String prop = st.nextToken();
pw.println(prop);
}
pw.flush();
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
Properties drvProps = new Properties();
try {
drvProps.load(bais);
} catch (IOException e) {
}
dbProps.putAll(drvProps);
}
return dbProps;
}
use of org.datanucleus.Configuration in project datanucleus-api-jdo by datanucleus.
the class JDOPersistenceManager method getProperties.
/**
* Get the properties and associated values currently in effect for the
* persistence manager. Changing entries in the map will not have affect
* the configuration of the persistence manager.
* @return map of properties in effect
* @since JDO3.1
*/
public Map<String, Object> getProperties() {
assertIsOpen();
Map<String, Object> pmProps = new HashMap<String, Object>();
Map<String, Object> ecProps = ec.getProperties();
Iterator<Map.Entry<String, Object>> propertiesIter = ecProps.entrySet().iterator();
Configuration conf = ec.getNucleusContext().getConfiguration();
while (propertiesIter.hasNext()) {
Map.Entry<String, Object> entry = propertiesIter.next();
String ecPropName = entry.getKey();
// Return with javax.jdo name if this is an internal property name
String pmPropName = conf.getPropertyNameWithInternalPropertyName(ecPropName, "javax.jdo");
pmProps.put(pmPropName != null ? pmPropName : ecPropName, entry.getValue());
}
return pmProps;
}
Aggregations