Define a storage class
@param serviceDbName: dbName
@param viewsManager
328531
function storage( serviceDbName, viewsManager ){
	//Call constructor from super class
	events.EventEmitter.call(this);	
	
	//this db name and handle
	this.serviceDbName = serviceDbName;	
	this.storageDb = null;
	
	this.getDbName = function(){
		return serviceDbName;
	};
	
	//Indicate whether the db didn't exist and was created 
	this.dbCreated = false;
	
	var self = this;	
	this.initCloudant = function( resolve, reject ){
		cloudant.db.get(self.serviceDbName, function(err, body) {
			if ( viewsManager && !_.isArray( viewsManager )){
				viewsManager = [viewsManager];
			}
			if (err ) {
				//Create it
				cloudant.db.create(self.serviceDbName,function(err,body){
					if ( err ){
						reject( "Unable to create db " + self.serviceDbName + ". Error is " + err );
					}else{
						self.dbCreated = true;
						self.storageDb = cloudant.use( serviceDbName );
						if ( viewsManager ){
							var bFound = false;
							_.forEach( viewsManager, function( manager ){
								//Create the design doc
								bFound = true;
								console.log("inserting design doc " + manager.designName );
								self.storageDb.insert( {'views' : manager.getViewsJson() }, manager.designName, function(err,b) {
									if (err) {
										reject( "Failed to create view: "+err);
									}else{
										resolve();
									}
								});
							});
							if ( !bFound ){
								//Nothing to do
								resolve();
							}
						}
					}
				});
			}else{
				self.storageDb = cloudant.use( self.serviceDbName );
				
				//Make sure that the design docs exists, if not create them now
				if ( viewsManager ){
					async.each( viewsManager, function( manager, callback ){
						self.storageDb.get( manager.designName, function( err, body){
							var rev = null;
							var recreateDesignDoc = false;
							if ( err ){
								recreateDesignDoc = true;
							}else{
								//Grab the design doc and check version
								var views = body.views;
								rev = body._rev;
								_.forEach( manager.viewDefs, function( viewDef ){
									if ( views.hasOwnProperty( viewDef.viewName) ){
										var version = views[viewDef.viewName ].version || 0;
										if ( version < viewDef.version ){
											recreateDesignDoc = true;
										}
									}else{
										recreateDesignDoc = true;
									}
								});
							}						
							if ( recreateDesignDoc ){
								var designDoc = {'views' : manager.getViewsJson() };
								if ( rev ){
									designDoc._rev = rev;
								}

								self.storageDb.insert( designDoc , manager.designName, function(err,b) {
									if (err) {
										callback( err );
									}else{
										callback();
									}
								});
							}else{
								callback();
							}
						});
					}, function(err){
						if ( err ){
							reject( "Failed to create view: "+err);
						}else{
							resolve();
						}
					});
				}else{
					resolve();
				}
			}
		});
	};
		
	when.promise( this.initCloudant )
		.then( function() {
			console.log("Cloudant database %s successfully initialized", self.serviceDbName);
			self.emit("cloudant_ready");
		})
		.otherwise( function(err) {
			console.log("Error initializing cloudant database " + err);
			self.emit("cloudant_error");
		});
	
	/**
	 * Return true if db is correctly initialized
	 */
	this.isDbInitialized = function(){
		return !!this.storageDb;
	};
	
	/**
	 * Destroy the current db
	 */
	this.destroy = function( callback ){
		this.run( function( err, db ){
			if ( err ){
				return callback(err);
			}
			cloudant.db.destroy( serviceDbName, function(err){
				if ( err ){
					return callback(err);
				}
				//Set as not initialized
				delete this.storageDb;
				return callback();
			}.bind(this));
		}.bind(this));
	}
	
	/**
	 * Destroy and recreate the database
	 * @param callback(err)
	 */
	this.destroyAndRecreate = function(callback){
		this.run( function( err, db ){
			if ( err ){
				return callback( err );
			}
			cloudant.db.destroy( serviceDbName, function( err ){
				if ( err ){
					return callback(err);
				}
				
				//Reinit
				when.promise( this.initCloudant )
				.then( function() {
					return callback( null );
				})
				.otherwise( function(err) {
					return callback( err );			
				})
			}.bind(this));
		}.bind(this));
	}
	
	this.run = function( callback ){
		if ( !self.storageDb ){
			var err = "Storage has not been correctly initialized";
			console.log( err );
			return callback( err );
		}
		
		return callback( null, self.storageDb );
	};
	
	this.savesInProgress = {};
	
	/**
	 * getDoc: helper function that fetch a document from the database
	 * @param docId: documentId
	 * @param callback(err, doc)
	 */
	this.getDoc = function( docId, callback ){
		this.run( function( err, db ){
			if ( err ){
				return callback(err);
			}
			db.get( docId, { include_docs: true }, callback );
		})
	};
	
	/**
	 * Update doc if exists, insert a new one if not
	 * @param: docId
	 * @param: callback(doc), return updated document
	 * @param: done( err, doc ) status callback
	 */
	this.upsert = function( docId, callback, done ){
		this.run( function( err, db ){
			if ( err ){
				return callback(err);
			}
			
			var insert = function( body ){
				//Let caller modify doc if already exists, caller can replace with entirely new doc, however, doc id will be reestablished if doc already exists
				var id = body && (body._id || body.id);
				var rev = body && (body._rev || body.rev);
				body = callback( body );				
				if ( body ){
					body._id = id || body._id || undefined;
					body._rev = rev || body._rev || undefined;
					
					db.insert( body, body._id, function( err, data ){
						if ( id && this.savesInProgress.hasOwnProperty( id )){
							delete this.savesInProgress[id];
						}
						if ( err ){
							console.log( "Error while saving doc: " + err + ".Doc id: " + body._id + " Doc rev: " + body._rev);
							return done(err);
						}
						//always set the id and rev if available
						body._id = (data && (data.id || data._id)) || body._id;
						body._rev = (data && (data.rev || data._rev)) || body._rev;
						return done( null, body );
					}.bind( this ));
				}else{
					//Caller didn't give us the data, return error
					return done("Error during upsert: Caller didn't return a valid document");
				}
			}.bind( this );
			
			if ( !docId ){
				return insert( null );
			}
			
			if ( this.savesInProgress.hasOwnProperty( docId ) ){
				this.savesInProgress[docId]++;
				//console.log("Deferring save of document: " + docId + " :::: " + this.savesInProgress[docId]);
				//Wait for the other save to finish
				return setTimeout( function(){
					return this.upsert( docId, callback, done );
				}.bind(this), this.savesInProgress[docId] * 500 );
			}

			//Mark this document as being saved
			this.savesInProgress[docId] = 1;
			
			//We have a docId, load it
			db.get( docId, { include_docs: true }, function( err, body ){				
				return insert( body );
			});
		}.bind(this));
	};
	
	/**
	 * Delete all docs in a view
	 */
	this.deleteDocsFromView = function( designName, viewName, callback ){
		//console.log("Deleting all docs in view: " + designName + " / " + viewName );
		this.run( function( err, db ){
			if ( err ){
				return callback( err );
			}
			async.waterfall([
                function( callback ){
                	db.view(designName, viewName, function(err, data) {
						if ( err ){
							return callback( err );
						}
						var docs = _.map( data.rows, function( row ){
							return {id: row.id || row.value._id, rev: row.value.rev||row.value._rev};
						});					
						return callback( null, docs );
                	});
                },
                function( docs, callback ){
                	if ( docs.length == 0 || docs[0].rev ){
                		//We either have no docs to delete, or rev is already retrieved
                		return callback( null, docs );
                	}
                	
                	//Call bulk api to fetch revs
                	db.fetchRevs( { keys: _.map( docs, function(doc){
                			return doc.id;
                		})}, function( err, body ){
                			if ( err ){
                				return callback( err );
                			}
                			return callback( null, _.map(body.rows, function( row ){
                					return {id:row.id, rev: row.value.rev};
                				}) 
                			);
                		}
                	);
                },
                function( docs, callback ){
                	//Delete all docs one by one
                	async.each( docs, function( doc, callback ){
                		db.destroy( doc.id, doc.rev, callback );
                	}, function( err ){
                		return callback( err );
                	});
                }],
                function( err, results ){
					return callback( err, results );
				}
			);
		});
	};
}
453452
public function setServiceLocator(ServiceLocatorInterface $serviceManager)
    {
        if (!$this->dbAdapter instanceof DbAdapter) {
            $this->dbAdapter = $serviceManager->getServiceLocator()->get($this->dbAdapter);
        }
    }
19586
private static void setServiceEnabled(final XMPPConnection connection,
            final boolean isEnabled) {
        ServiceDiscoveryManager manager = ServiceDiscoveryManager
                .getInstanceFor(connection);

        List<String> namespaces = new ArrayList<>();
        namespaces.addAll(Arrays.asList(NAMESPACE));
        namespaces.add(DataPacketExtension.NAMESPACE);
        if (!IBB_ONLY) {
            namespaces.add(Bytestream.NAMESPACE);
        }

        for (String namespace : namespaces) {
            if (isEnabled) {
                manager.addFeature(namespace);
            } else {
                manager.removeFeature(namespace);
            }
        }
    }
123711
def reflect_db(self):
        
        self.metadata.reflect(views=True, extend_existing=True)
        self.base = automap_base(metadata=self.metadata)
        self.base.prepare()
943667
@Override
	public JdbcDatabaseDescriptor dbByName(final String dbName) {
		Collection<H2DatabaseWorking> select = CollectionUtils.select(dbsw, new Predicate<H2DatabaseWorking>() {

			@Override
			public boolean evaluate(H2DatabaseWorking db) {
				return dbName.equals( db.getName() );
			}

		});
		if(CollectionUtils.size(select)==0){
			throw new IllegalArgumentException("There are no databases called '" + dbName + "'");
		}
		if(CollectionUtils.size(select)>=2){
			throw new IllegalArgumentException("More than one database is called '" + dbName + "'");
		}
		return CollectionUtils.extractSingleton( select );
	}
135894
public static org.opencms.db.generic.CmsSqlManager getInstance(String classname) {

        org.opencms.db.generic.CmsSqlManager sqlManager;

        try {
            Object objectInstance = Class.forName(classname).newInstance();
            sqlManager = (org.opencms.db.generic.CmsSqlManager)objectInstance;
        } catch (Throwable t) {
            LOG.error(Messages.get().getBundle().key(Messages.LOG_SQL_MANAGER_INIT_FAILED_1, classname), t);
            sqlManager = null;
        }

        if (CmsLog.INIT.isInfoEnabled()) {
            CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_DRIVER_SQL_MANAGER_1, classname));
        }

        return sqlManager;

    }
457992
@Override
    public ServiceDelegate createServiceDelegate(URL url, QName qname,
                                                 @SuppressWarnings("rawtypes") Class cls) {
        Bus bus = null;
        JaxWsClientMetaData clientMetaData = JaxWsMetaDataManager.getJaxWsClientMetaData();
        if (clientMetaData != null) {
            bus = clientMetaData.getClientBus();
        }
        if (bus == null) {
            bus = BusFactory.getThreadDefaultBus();
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "No client  bus is found, the thread context default bus " + bus.getId() + " is used");
            }
        }

        WebServiceRefInfo wsrInfo = wsRefInfo.get();

        List<WebServiceFeature> serviceFeatures = wsFeatures.get();
        final List<WebServiceFeature> fServiceFeatures = serviceFeatures;

        AtomicServiceReference<JaxWsSecurityConfigurationService> secConfigSR = securityConfigSR.get();
        JaxWsSecurityConfigurationService securityConfigService = secConfigSR == null ? null : secConfigSR.getService();

        // @TJJ create final vars in order to call a doPriv when creating the LibertyServiceImpl as required by java 2 security
        final JaxWsSecurityConfigurationService scs = securityConfigService;
        final WebServiceRefInfo wi = wsrInfo;
        final Bus b = bus;
        final URL u = url;
        final QName qn = qname;
        final Class c = cls;
        final List<WebServiceFeature> sf = serviceFeatures;

        if (serviceFeatures != null) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Thread context features are configured with " + serviceFeatures);
            }
            LibertyServiceImpl lsl = AccessController.doPrivileged(new PrivilegedAction<LibertyServiceImpl>() {
                @Override
                public LibertyServiceImpl run() {
                    return new LibertyServiceImpl(scs, wi, b, u, qn, c, sf.toArray(new WebServiceFeature[sf.size()]));
                }
            });
            return lsl;

        } else {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Thread context features are not set");
            }

            LibertyServiceImpl lsl = AccessController.doPrivileged(new PrivilegedAction<LibertyServiceImpl>() {
                @Override
                public LibertyServiceImpl run() {
                    return new LibertyServiceImpl(scs, wi, b, u, qn, c);
                }
            });
            return lsl;

        }
    }
269361
public static final synchronized BPMTaskService getTaskService(QName serviceDomainName, QName serviceName) {
        KnowledgeRuntimeManager runtimeManager = KnowledgeRuntimeManagerRegistry.getRuntimeManager(serviceDomainName, serviceName);
        if (runtimeManager != null) {
            RuntimeEngine runtimeEngine = runtimeManager.getRuntimeEngine();
            if (runtimeEngine != null) {
                final TaskService taskService = runtimeEngine.getTaskService();
                if (taskService != null) {
                    InvocationHandler ih = new InvocationHandler() {
                        @Override
                        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                            return method.invoke(taskService, args);
                        }
                    };
                    return (BPMTaskService)Proxy.newProxyInstance(BPMTaskService.class.getClassLoader(), new Class[] {BPMTaskService.class}, ih);
                }
            }
        }
        return null;
    }
376595
@Override
	public void createDb(String dbName) {
		String dbPath = getDbPath(dbName);
		if (map.containsKey(dbPath)) {
			throw DBLogger.newUser("Database already exists: " + dbPath);
		}
		map.put(dbPath, new ArrayList<ByteBuffer>());
		
		//create files

		//DB file
		FreeSpaceManager fsm = new FreeSpaceManager();
		StorageRootInMemory root = 
				new StorageRootInMemory(dbPath, "rw", ZooConfig.getFilePageSize(), fsm);
		IOResourceProvider file = root.createChannel();
		StorageChannelOutput out = file.createWriter(false);
		fsm.initBackingIndexNew(file);

		int headerPage = out.allocateAndSeek(PAGE_TYPE.DB_HEADER, 0);
		if (headerPage != 0) {
			throw DBLogger.newFatalInternal("Header page = " + headerPage);
		}
		int rootPage1 = out.allocateAndSeek(PAGE_TYPE.ROOT_PAGE, 0);
		int rootPage2 = out.allocateAndSeek(PAGE_TYPE.ROOT_PAGE, 0);

		//header: this is written further down

		//write User data
		int userData = out.allocateAndSeek(PAGE_TYPE.USERS, 0);

		//dir for schemata
		int schemaData = out.allocateAndSeekAP(PAGE_TYPE.SCHEMA_INDEX, 0, -1);
		//ID of next page
		out.writeInt(0);
		//Schema ID / schema data (page or actual data?)
		//0 for no more schemata
		out.writeInt(0);


		//dir for indices
		int indexDirPage = out.allocateAndSeek(PAGE_TYPE.INDEX_CATALOG, 0);
		//ID of next page
		out.writeInt(0);
		//Schema ID / attribute ID / index type / Page ID
		//0 for nor more indices
		out.writeInt(0);

		//OID index
		PagedOidIndex oidIndex = new PagedOidIndex(file);
		int oidPage = file.writeIndex(oidIndex::write);

		//Free space index
		int freeSpacePg = file.writeIndex(fsm::write);
		
		//write header
		out.seekPageForWrite(PAGE_TYPE.DB_HEADER, headerPage);
		out.writeInt(DiskIO.DB_FILE_TYPE_ID);
		out.writeInt(DiskIO.DB_FILE_VERSION_MAJ);
		out.writeInt(DiskIO.DB_FILE_VERSION_MIN);
		out.writeInt(ZooConfig.getFilePageSize());
		out.writeInt(rootPage1);
		out.writeInt(rootPage2);

		writeRoot(out, rootPage1, 1, userData, oidPage, schemaData, indexDirPage, freeSpacePg, 
				fsm.getPageCount());
		writeRoot(out, rootPage2, 0, userData, oidPage, schemaData, indexDirPage, freeSpacePg, 
				fsm.getPageCount());

		file.close();
		file = null;
		root.close();
		root = null;
		out = null;


		//initial schemata
		Properties props = new ZooJdoProperties(dbName);
		PersistenceManagerFactory pmf = 
			JDOHelper.getPersistenceManagerFactory(props);
		PersistenceManager pm = pmf.getPersistenceManager();
		pm.currentTransaction().begin();

		ZooSchema schema = ZooJdoHelper.schema(pm);
		schema.addClass(PersistenceCapableImpl.class);
		schema.addClass(DBHashMap.class);
		schema.addClass(DBArrayList.class);

		pm.currentTransaction().commit();
		pm.close();
		pmf.close();
	}
166515
function (connectionName, collectionName, obj, cb) {
        if (_.isObject(obj)) {
            try {
                var modelInstance = new this._model(obj);
                return cb(null, modelInstance);
            }
            catch (err) {
                return cb(err, null);
            }
        }
    }
831921
@Override
    protected ModelService getModelService(String serviceName){
        ModelService service = getCache().get(serviceName);
        if (service == null) {
            getCache().putIfAbsent(serviceName,super.getModelService(serviceName));
            service = getCache().get(serviceName);
        }
        return service;
    }
465142
def access_storage_view(name, **kwargs):
    
    ctx = Context(**kwargs)
    ctx.execute_action('access:storage:view', **{
        'storage': ctx.repo.create_secure_service('storage'),
        'name': name,
    })
165908
@Override
	@Deprecated
	public DataSource dataSourceByName(String dbName) {
		return new com.danidemi.jlubricant.embeddable.BasicDataSource(
				dbByName(dbName));
	}
820482
public static void main(String[] args) {
		String dbName;
		if (args.length == 0) {
			dbName = DB_NAME;
		} else {
			dbName = args[0];
		}
		
		if (!ZooHelper.getDataStoreManager().dbExists(dbName)) {
			err.println("ERROR Database not found: " + dbName);
			return;
		}
		
		out.println("Checking database: " + dbName);

		ZooJdoProperties props = new ZooJdoProperties(dbName);
		PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory(props);
		PersistenceManager pm = pmf.getPersistenceManager();
		Session s = (Session) pm.getDataStoreConnection().getNativeConnection();
		String report = s.getPrimaryNode().checkDb();
		out.println();
		out.println("Report");
		out.println("======");

		out.println(report);

		out.println("======");
		pm.close();
		pmf.close();
		out.println("Checking database done.");
	}
577459
protected <T> ManagedObjectFactory<T> getEJBManagedObjectFactory(BeanMetaData bmd, Class<T> klass) throws EJBConfigurationException {
        ManagedObjectFactory<T> factory = null;
        ManagedObjectService managedObjectService = getManagedObjectService();
        if (managedObjectService != null) {
            try {
                factory = managedObjectService.createEJBManagedObjectFactory(bmd._moduleMetaData, klass, bmd.j2eeName.getComponent());
                //TODO the isManaged method could be moved to the ManagedObjectService and then wouldn't need to create the factory
                if (!factory.isManaged()) {
                    factory = null;
                }
            } catch (ManagedObjectException e) {
                throw new EJBConfigurationException(e);
            }
        }

        return factory;
    }
402933
function SessionManager(config, encrypter) {
    /**
     * The configuration object
     *
     * @var Object
     * @protected
     */
    this.__config = config;

    /**
     * The registered custom driver creators.
     *
     * @var Object
     * @protected
     */
    this.__customCreators = {};

    /**
     * The encrypter instance.
     * An encrypter implements encrypt and decrypt methods.
     *
     * @var Object
     * @protected
     */
    this.__encrypter = encrypter;

    /**
     * The session database model instance
     *
     * @var Object
     * @protected
     */
    this.__sessionModel;

    /**
     * The memory session handler storage
     * @type {null}
     * @protected
     */
    this.__memorySession = Object.create(null);
}
1183827
public final void setName(String newName)
                    throws ObjectManagerException {
        final String methodName = "setName";
        if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
            trace.entry(this, cclass, methodName, new Object[] { newName, storeName });

        objectManagerState.renameObjectStore(this, newName);

        if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
            trace.exit(this, cclass, methodName);
    }