org.apache.openjpa.persistence.OpenJPAPersistence Java Examples

The following examples show how to use org.apache.openjpa.persistence.OpenJPAPersistence. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JpaTestCluster.java    From james-project with Apache License 2.0 6 votes vote down vote up
public static JpaTestCluster create(List<Class<?>> clazz) {
    HashMap<String, String> properties = new HashMap<>();
    properties.put("openjpa.ConnectionDriverName", org.apache.derby.jdbc.EmbeddedDriver.class.getName());
    properties.put("openjpa.ConnectionURL", "jdbc:derby:memory:mailboxintegrationtesting;create=true"); // Memory Derby database
    properties.put("openjpa.jdbc.SynchronizeMappings", "buildSchema(ForeignKeys=true)"); // Create Foreign Keys
    properties.put("openjpa.jdbc.SchemaFactory", "native(ForeignKeys=true)");
    properties.put("openjpa.jdbc.MappingDefaults", "ForeignKeyDeleteAction=cascade, JoinForeignKeyDeleteAction=cascade");
    properties.put("openjpa.jdbc.QuerySQLCache", "false");
    properties.put("openjpa.Log", "JDBC=WARN, SQL=WARN, Runtime=WARN");
    properties.put("openjpa.ConnectionFactoryProperties", "PrettyPrint=true, PrettyPrintLineLength=72");
    properties.put("openjpa.MetaDataFactory", "jpa(Types=" +
            clazz.stream()
                .map(Class::getName)
                .collect(Collectors.joining(";"))
        + ")");
    return new JpaTestCluster(OpenJPAPersistence.getEntityManagerFactory(properties));
}
 
Example #2
Source File: RestoreStorage.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
private boolean execute() throws Exception {
	final List<String> storageContainerEntityNames = new ArrayList<>();
	storageContainerEntityNames.addAll((List<String>) Config.resource(Config.RESOURCE_STORAGECONTAINERENTITYNAMES));
	List<String> classNames = new ArrayList<>();
	classNames.addAll(this.catalog.keySet());
	classNames = ListTools.includesExcludesWildcard(classNames, Config.dumpRestoreStorage().getIncludes(),
			Config.dumpRestoreStorage().getExcludes());
	logger.print("restore storage find {} to restore.", classNames.size());
	final File persistence = new File(Config.dir_local_temp_classes(), DateTools.compact(this.start) + "_dump.xml");
	PersistenceXmlHelper.write(persistence.getAbsolutePath(), classNames);
	final StorageMappings storageMappings = Config.storageMappings();
	int count = 0;
	for (int i = 0; i < classNames.size(); i++) {
		final Class<StorageObject> cls = (Class<StorageObject>) Class.forName(classNames.get(i));
		final EntityManagerFactory emf = OpenJPAPersistence.createEntityManagerFactory(cls.getName(),
				persistence.getName(), PersistenceXmlHelper.properties(cls.getName(), Config.slice().getEnable()));
		final EntityManager em = emf.createEntityManager();
		em.setFlushMode(FlushModeType.COMMIT);
		try {
			final DumpRestoreStorageCatalogItem item = this.catalog.get(cls.getName());
			logger.print(
					"restore storage({}/{}): {}, count: {}, normal: {} will be restore, invalidStorage: {} and empty: {} will be ignore, size: {}M.",
					(i + 1), classNames.size(), cls.getName(), item.getCount(), item.getNormal(),
					item.getInvalidStorage(), item.getEmpty(), (item.getSize() / 1024 / 1024));
			count += this.store(cls, em, storageMappings);
		} finally {
			em.close();
			emf.close();
		}
		logger.print("restore storage completed, total count: {}, elapsed: {} minutes.", count,
				(System.currentTimeMillis() - start.getTime()) / 1000 / 60);
	}
	return false;
}
 
Example #3
Source File: RestoreData.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public boolean execute() throws Exception {
	List<String> containerEntityNames = new ArrayList<>();
	containerEntityNames.addAll((List<String>) Config.resource(Config.RESOURCE_CONTAINERENTITYNAMES));
	List<String> classNames = new ArrayList<>();
	classNames.addAll(this.catalog.keySet());
	classNames = ListTools.includesExcludesWildcard(classNames, Config.dumpRestoreData().getIncludes(),
			Config.dumpRestoreData().getExcludes());
	classNames = ListTools.includesExcludesWildcard(containerEntityNames, classNames, null);

	logger.print("find: {} data to restore, path: {}.", classNames.size(), this.dir.getAbsolutePath());
	File persistence = new File(Config.dir_local_temp_classes(), DateTools.compact(this.start) + "_dump.xml");
	PersistenceXmlHelper.write(persistence.getAbsolutePath(), classNames);
	long count = 0;
	for (int i = 0; i < classNames.size(); i++) {
		Class<JpaObject> cls = (Class<JpaObject>) Class.forName(classNames.get(i));
		EntityManagerFactory emf = OpenJPAPersistence.createEntityManagerFactory(cls.getName(),
				persistence.getName(), PersistenceXmlHelper.properties(cls.getName(), Config.slice().getEnable()));
		if (emf != null) {
			EntityManager em = emf.createEntityManager();
			em.setFlushMode(FlushModeType.COMMIT);
			try {
				logger.print("restore data({}/{}): {}, count: {}.", (i + 1), classNames.size(), cls.getName(),
						catalog.get(cls.getName()));
				count = count + this.store(cls, em);
			} finally {
				em.close();
				emf.close();
			}
		} else {
			logger.warn("can not create 'EntityManagerFactory' for Entity:[" + cls.getName() + "]");
		}
	}
	logger.print("restore data completed, total count: {}, elapsed: {} minutes.", count,
			(System.currentTimeMillis() - start.getTime()) / 1000 / 60);
	return true;
}
 
Example #4
Source File: EraseContentProcessPlatform.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
protected void run() throws Exception {
	logger.print("clean {} content data, start at {}.", name, DateTools.format(start));
	this.classNames = ListUtils.intersection(this.classNames,
			(List<String>) Config.resource(Config.RESOURCE_CONTAINERENTITYNAMES));
	StorageMappings storageMappings = Config.storageMappings();
	File persistence = new File(Config.dir_local_temp_classes(),
			DateTools.compact(this.start) + "_eraseContent.xml");
	PersistenceXmlHelper.write(persistence.getAbsolutePath(), classNames);
	for (int i = 0; i < classNames.size(); i++) {
		Class<? extends JpaObject> cls = (Class<? extends JpaObject>) Class.forName(classNames.get(i));
		EntityManagerFactory emf = OpenJPAPersistence.createEntityManagerFactory(cls.getName(),
				persistence.getName(), PersistenceXmlHelper.properties(cls.getName(), Config.slice().getEnable()));
		EntityManager em = emf.createEntityManager();
		try {
			if (DataItem.class.isAssignableFrom(cls)) {
				logger.print("erase {} content data:{}, total:{}.", name, cls.getName(),
						this.estimateItemCount(em, cls));
				this.eraseItem(cls, em);
			} else {
				logger.print("erase {} content data:{}, total:{}.", name, cls.getName(),
						this.estimateCount(em, cls));
				this.erase(cls, em, storageMappings);
			}
		} finally {
			System.gc();
		}
	}
	Date end = new Date();
	logger.print("erase {} completed at {}, elapsed: {} ms.", name, DateTools.format(end),
			(end.getTime() - start.getTime()));
}
 
Example #5
Source File: ConfigurationDao.java    From openmeetings with Apache License 2.0 5 votes vote down vote up
public void updateClusterAddresses(String addresses) throws UnknownHostException {
	OpenJPAConfiguration cfg = ((OpenJPAEntityManagerSPI)OpenJPAPersistence.cast(em)).getConfiguration();
	RemoteCommitProvider prov = cfg.getRemoteCommitEventManager().getRemoteCommitProvider();
	if (prov instanceof TCPRemoteCommitProvider) {
		((TCPRemoteCommitProvider)prov).setAddresses(addresses);
	}
}
 
Example #6
Source File: DaoHelper.java    From openmeetings with Apache License 2.0 5 votes vote down vote up
public static <T> List<T> fillLazy(EntityManager em, Function<OpenJPAEntityManager, TypedQuery<T>> func, String...groups) {
	OpenJPAEntityManager oem = OpenJPAPersistence.cast(em);
	boolean qrce = oem.getFetchPlan().getQueryResultCacheEnabled();
	try {
		oem.getFetchPlan().setQueryResultCacheEnabled(false); //update in cache during update
		TypedQuery<T> q = func.apply(oem);
		@SuppressWarnings("unchecked")
		OpenJPAQuery<T> kq = OpenJPAPersistence.cast(q);
		kq.getFetchPlan().addFetchGroups(groups);
		return kq.getResultList();
	} finally {
		oem.getFetchPlan().setQueryResultCacheEnabled(qrce);
	}
}
 
Example #7
Source File: DumpStorage.java    From o2oa with GNU Affero General Public License v3.0 4 votes vote down vote up
public boolean execute(String path) throws Exception {
	if (StringUtils.isEmpty(path)) {
		this.dir = new File(Config.base(), "local/dump/dumpStorage_" + DateTools.compact(this.start));
	} else {
		this.dir = new File(path);
		if (dir.getAbsolutePath().startsWith(Config.base())) {
			logger.print("path can not in base directory.");
			return false;
		}
	}
	FileUtils.forceMkdir(this.dir);
	FileUtils.cleanDirectory(this.dir);
	this.catalog = new DumpRestoreStorageCatalog();

	List<String> storageContainerEntityNames = new ArrayList<>();
	storageContainerEntityNames.addAll((List<String>) Config.resource(Config.RESOURCE_STORAGECONTAINERENTITYNAMES));
	List<String> classNames = ListTools.includesExcludesWildcard(storageContainerEntityNames,
			Config.dumpRestoreStorage().getIncludes(), Config.dumpRestoreStorage().getExcludes());
	logger.print("dump storage find {} data to dump, start at {}.", classNames.size(), DateTools.format(start));
	StorageMappings storageMappings = Config.storageMappings();
	File persistence = new File(Config.dir_local_temp_classes(), DateTools.compact(this.start) + "_dump.xml");
	PersistenceXmlHelper.write(persistence.getAbsolutePath(), classNames);
	for (int i = 0; i < classNames.size(); i++) {
		Class<StorageObject> cls = (Class<StorageObject>) Class.forName(classNames.get(i));
		EntityManagerFactory emf = OpenJPAPersistence.createEntityManagerFactory(cls.getName(),
				persistence.getName(), PersistenceXmlHelper.properties(cls.getName(), Config.slice().getEnable()));
		EntityManager em = emf.createEntityManager();
		try {
			logger.print("dump storage({}/{}): {}, estimate count: {}, estimate size: {}M.", (i + 1),
					classNames.size(), cls.getName(), this.estimateCount(em, cls),
					(this.estimateSize(em, cls) / 1024 / 1024));
			this.dump(cls, em, storageMappings);
		} finally {
			em.close();
			emf.close();
		}
	}
	FileUtils.write(new File(dir, "catalog.json"), XGsonBuilder.instance().toJson(this.catalog),
			DefaultCharset.charset);
	logger.print(
			"dump storage completed, directory: {}, count: {}, normal: {}, empty: {}, invalidStorage: {}, size: {}M, elapsed: {} minutes.",
			dir.getAbsolutePath(), this.count(), this.normal(), this.empty(), this.invalidStorage(),
			(this.size() / 1024 / 1024), (System.currentTimeMillis() - start.getTime()) / 1000 / 60);
	return true;
}
 
Example #8
Source File: DumpData.java    From o2oa with GNU Affero General Public License v3.0 4 votes vote down vote up
public boolean execute(String path) throws Exception {
	if (StringUtils.isEmpty(path)) {
		this.dir = new File(Config.base(), "local/dump/dumpData_" + DateTools.compact(this.start));
	} else {
		this.dir = new File(path);
		if (dir.getAbsolutePath().startsWith(Config.base())) {
			logger.print("path can not in base directory.");
			return false;
		}
	}
	FileUtils.forceMkdir(this.dir);
	FileUtils.cleanDirectory(this.dir);
	this.catalog = new DumpRestoreDataCatalog();

	/* 初始化完成 */

	List<String> containerEntityNames = new ArrayList<>();
	containerEntityNames.addAll((List<String>) Config.resource(Config.RESOURCE_CONTAINERENTITYNAMES));
	List<String> classNames = ListTools.includesExcludesWildcard(containerEntityNames,
			Config.dumpRestoreData().getIncludes(), Config.dumpRestoreData().getExcludes());
	logger.print("dump data find {} data to dump, start at {}.", classNames.size(), DateTools.format(start));
	File persistence = new File(Config.dir_local_temp_classes(), DateTools.compact(this.start) + "_dump.xml");
	PersistenceXmlHelper.write(persistence.getAbsolutePath(), classNames);
	for (int i = 0; i < classNames.size(); i++) {
		Class<JpaObject> cls = (Class<JpaObject>) Class.forName(classNames.get(i));
			EntityManagerFactory emf = OpenJPAPersistence.createEntityManagerFactory(cls.getName(),
					persistence.getName(),
					PersistenceXmlHelper.properties(cls.getName(), Config.slice().getEnable()));
			EntityManager em = emf.createEntityManager();
			try {
				logger.print("dump data({}/{}): {}, count: {}.", (i + 1), classNames.size(), cls.getName(),
						this.estimateCount(em, cls));
				this.dump(cls, em);
			} finally {
				em.close();
				emf.close();
			}
	}
	FileUtils.write(new File(dir, "catalog.json"), pureGsonDateFormated.toJson(this.catalog),
			DefaultCharset.charset);
	logger.print("dump data completed, directory: {}, count: {}, elapsed: {} minutes.", dir.getAbsolutePath(),
			this.count(), (System.currentTimeMillis() - start.getTime()) / 1000 / 60);
	return true;
}
 
Example #9
Source File: Ddl.java    From o2oa with GNU Affero General Public License v3.0 4 votes vote down vote up
public boolean execute(String type) throws Exception {

		// List<String> containerEntityNames = new ArrayList<>();
		// containerEntityNames.addAll((List<String>)
		// Config.resource(Config.RESOURCE_CONTAINERENTITYNAMES));
		// List<String> classNames =
		// ListTools.includesExcludesWildcard(containerEntityNames,
		// Config.dumpRestoreData().getIncludes(),
		// Config.dumpRestoreData().getExcludes());
		// File persistence = new File(Config.dir_local_temp_classes(),
		// "META-INF/persistence.xml");
		// PersistenceXmlHelper.writeForDdl(persistence.getAbsolutePath());
		// String[] arguments = new String[4];
		// arguments[0] = "-schemaAction";
		// arguments[1] = StringUtils.equals(type ,"create")? "build":"add";
		// arguments[2] = "-sql";
		// arguments[3] = Config.dir_local_temp_sql(true) + "/" + type + ".sql";
		// MappingTool.main(arguments);
		// return true;
		String flag = "build";
		if (StringUtils.equalsIgnoreCase(type, "createDB")) {
			flag = "createDB";
		} else if (StringUtils.equalsIgnoreCase(type, "dropDB")) {
			flag = "dropDB";
		} else if (StringUtils.equalsIgnoreCase(type, "drop")) {
			flag = "drop";
			// } else if (StringUtils.equalsIgnoreCase(type, "deleteTableContents")) {
			// flag = "deleteTableContents";
		}
		List<String> containerEntityNames = new ArrayList<>();
		containerEntityNames.addAll((List<String>) Config.resource(Config.RESOURCE_CONTAINERENTITYNAMES));
		List<String> classNames = ListTools.includesExcludesWildcard(containerEntityNames,
				Config.dumpRestoreData().getIncludes(), Config.dumpRestoreData().getExcludes());
		File persistence = new File(Config.dir_local_temp_classes(), "persistence_sql.xml");
		PersistenceXmlHelper.writeForDdl(persistence.getAbsolutePath());
		OpenJPAEntityManagerFactory emf = OpenJPAPersistence.createEntityManagerFactory("enhance",
				persistence.getName());
		EntityManagerImpl em = (EntityManagerImpl) emf.createEntityManager();
		String[] arguments = null;
		String[] args = null;
		Options opts = new Options();
		if (StringUtils.equals(flag, "build") || StringUtils.equals(flag, "drop")
				|| StringUtils.equals(flag, "createDB") || StringUtils.equals(flag, "dropDB")) {
			arguments = new String[4];
			File file = new File(Config.dir_local_temp_sql(true), flag + ".sql");
			arguments[0] = "-schemaAction";
			arguments[1] = flag;
			arguments[2] = "-sql";
			arguments[3] = file.getAbsolutePath();
			args = opts.setFromCmdLine(arguments);
			MappingTool.run((JDBCConfiguration) em.getConfiguration(), args, opts, null);
			logger.print("file : {}.", file.getAbsolutePath());
		} else if (StringUtils.equals(flag, "deleteTableContents")) {
			// arguments = new String[2];
			// arguments[0] = "-schemaAction";
			// arguments[1] = flag;
			// args = opts.setFromCmdLine(arguments);
			// MappingTool.run((JDBCConfiguration) em.getConfiguration(), args, opts, null);
			// logger.print("delete all table contents.");
		}
		em.close();
		emf.close();
		return true;
	}
 
Example #10
Source File: OpenJpaDialect.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Return the OpenJPA-specific variant of {@code EntityManager}.
 * @param em the generic {@code EntityManager} instance
 * @return the OpenJPA-specific variant of {@code EntityManager}
 */
protected OpenJPAEntityManager getOpenJPAEntityManager(EntityManager em) {
	return OpenJPAPersistence.cast(em);
}
 
Example #11
Source File: OpenJpaDialect.java    From spring4-understanding with Apache License 2.0 2 votes vote down vote up
/**
 * Return the OpenJPA-specific variant of {@code EntityManager}.
 * @param em the generic {@code EntityManager} instance
 * @return the OpenJPA-specific variant of {@code EntityManager}
 */
protected OpenJPAEntityManager getOpenJPAEntityManager(EntityManager em) {
	return OpenJPAPersistence.cast(em);
}
 
Example #12
Source File: OpenJpaDialect.java    From syncope with Apache License 2.0 2 votes vote down vote up
/**
 * Return the OpenJPA-specific variant of {@code EntityManager}.
 *
 * @param em the generic {@code EntityManager} instance
 * @return the OpenJPA-specific variant of {@code EntityManager}
 */
protected static OpenJPAEntityManager getOpenJPAEntityManager(final EntityManager em) {
    return OpenJPAPersistence.cast(em);
}