<commit_before>/*
 * Copyright 2011-2015 B2i Healthcare Pte Ltd, http://b2i.sg
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.b2international.snowowl.datastore;

import static com.b2international.commons.CompareUtils.isEmpty;
import static com.b2international.commons.StringUtils.isEmpty;
import static com.b2international.commons.exceptions.Exceptions.extractCause;
import static com.b2international.snowowl.core.ApplicationContext.getServiceForClass;
import static com.b2international.snowowl.datastore.BranchPathUtils.createPath;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Iterables.getOnlyElement;
import static java.text.MessageFormat.format;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.emf.cdo.CDOObject;
import org.eclipse.emf.cdo.common.branch.CDOBranch;
import org.eclipse.emf.cdo.common.commit.CDOCommitInfo;
import org.eclipse.emf.cdo.common.id.CDOIDUtil;
import org.eclipse.emf.cdo.eresource.CDOResource;
import org.eclipse.emf.cdo.transaction.CDOPushTransaction;
import org.eclipse.emf.cdo.transaction.CDOTransaction;
import org.eclipse.emf.cdo.util.CommitException;
import org.eclipse.emf.cdo.view.CDOQuery;
import org.eclipse.emf.cdo.view.CDOView;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.net4j.util.lifecycle.LifecycleUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.b2international.commons.CompareUtils;
import com.b2international.commons.FileUtils;
import com.b2international.commons.StringUtils;
import com.b2international.snowowl.core.ApplicationContext;
import com.b2international.snowowl.core.api.IBranchPath;
import com.b2international.snowowl.core.api.ILookupService;
import com.b2international.snowowl.core.api.SnowowlServiceException;
import com.b2international.snowowl.core.exceptions.ComponentNotFoundException;
import com.b2international.snowowl.datastore.cdo.CDOQueryUtils;
import com.b2international.snowowl.datastore.cdo.CDOUtils;
import com.b2international.snowowl.datastore.cdo.ICDOConnection;
import com.b2international.snowowl.datastore.cdo.ICDOConnectionManager;
import com.b2international.snowowl.datastore.exception.RepositoryLockException;
import com.b2international.snowowl.datastore.tasks.TaskManager;
import com.b2international.snowowl.terminologymetadata.CodeSystemVersionGroup;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;

/**
 * This class is a thin, generic wrapper around the underlying {@link CDOTransaction}. 
 * In order to make it terminology independent, it uses {@link EObject}s as opposed to 
 * specific classes.
 * 
 */
public abstract class CDOEditingContext implements AutoCloseable {

	/**
	 * Number of retires to successfully commit the changes from an editing context.
	 */
	public static final int COMMIT_STRIKES = 5;
	
	/**
	 * Shared logger instance.
	 */
	protected static final Logger LOGGER = LoggerFactory.getLogger(CDOEditingContext.class);
	
	/**
	 * Underlying CDO transaction.
	 */
	protected final CDOTransaction transaction;

	/**
	 * @param ePackage - the primary ePackage of this editing context
	 */
	protected CDOEditingContext(EPackage ePackage) {
		this(ePackage, getActivePath(ePackage));
	}
	
	protected CDOEditingContext(final EPackage ePackage, final IBranchPath branchPath) {
		this(createTransaction(checkNotNull(ePackage, "ePackage"), checkNotNull(branchPath, "Branch path argument cannot be null.")));
	}
	
	protected CDOEditingContext(final CDOTransaction cdoTransaction) {
		this.transaction = CDOUtils.check(cdoTransaction);
	}
	
	public final String getBranch() {
		return BranchPathUtils.createPath(getTransaction()).getPath();
	}
	
	/*
	 * get the index from the database for an EObject on the given table.
	 * If the object is not in the database, a RTE will be thrown.
	 */
	public int getIndexFromDatabase(final EObject object, final String tableName)  {
			
		// the object must be a cdoObject, otherwise the database cannot contain it
		if (!(object instanceof CDOObject)) {
			throw new RuntimeException("The removable object is not a CDOObject.");
		}
		if (tableName == null) {
			throw new RuntimeException("Argument tableName must not be null.");
		}
		final CDOObject cdoObject = (CDOObject) object;
		 		
		// query the resources table, to get the index directly
		final CDOObject container = object.eContainer()== null ? cdoObject.cdoResource() : (CDOObject) object.eContainer();
		final int version = container.cdoRevision().getVersion();
		final String sqlGetIndexFormatted = DatastoreQueries.SQL_GET_INDEX_AND_BRANCH_FOR_VALUE.getQuery(tableName);
		final CDOQuery query = transaction.createQuery("sql", sqlGetIndexFormatted);
		query.setParameter(CDOQueryUtils.CDO_OBJECT_QUERY, false);
		query.setParameter("cdoId", CDOIDUtil.getLong(cdoObject.cdoID()));
		query.setParameter("versionMaxAdded", version);
		final List<Object[]> result = query.getResult(Object[].class);
		// neither 0 nor more than 1 results are acceptable
		if (result.size() <= 0) {			
			throw new RuntimeException("Object not found in database. CDO ID: " + cdoObject.cdoID());<commit_msg>[core] add getNew/Changed/DetachedObjects methods to edit.context<commit_after>/*
 * Copyright 2011-2015 B2i Healthcare Pte Ltd, http://b2i.sg
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.b2international.snowowl.datastore;

import static com.b2international.commons.CompareUtils.isEmpty;
import static com.b2international.commons.StringUtils.isEmpty;
import static com.b2international.commons.exceptions.Exceptions.extractCause;
import static com.b2international.snowowl.core.ApplicationContext.getServiceForClass;
import static com.b2international.snowowl.datastore.BranchPathUtils.createPath;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Iterables.getOnlyElement;
import static java.text.MessageFormat.format;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.emf.cdo.CDOObject;
import org.eclipse.emf.cdo.common.branch.CDOBranch;
import org.eclipse.emf.cdo.common.commit.CDOCommitInfo;
import org.eclipse.emf.cdo.common.id.CDOIDUtil;
import org.eclipse.emf.cdo.eresource.CDOResource;
import org.eclipse.emf.cdo.transaction.CDOPushTransaction;
import org.eclipse.emf.cdo.transaction.CDOTransaction;
import org.eclipse.emf.cdo.util.CommitException;
import org.eclipse.emf.cdo.view.CDOQuery;
import org.eclipse.emf.cdo.view.CDOView;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.net4j.util.lifecycle.LifecycleUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.b2international.commons.CompareUtils;
import com.b2international.commons.FileUtils;
import com.b2international.commons.StringUtils;
import com.b2international.snowowl.core.ApplicationContext;
import com.b2international.snowowl.core.api.IBranchPath;
import com.b2international.snowowl.core.api.ILookupService;
import com.b2international.snowowl.core.api.SnowowlServiceException;
import com.b2international.snowowl.core.exceptions.ComponentNotFoundException;
import com.b2international.snowowl.datastore.cdo.CDOQueryUtils;
import com.b2international.snowowl.datastore.cdo.CDOUtils;
import com.b2international.snowowl.datastore.cdo.ICDOConnection;
import com.b2international.snowowl.datastore.cdo.ICDOConnectionManager;
import com.b2international.snowowl.datastore.exception.RepositoryLockException;
import com.b2international.snowowl.datastore.tasks.TaskManager;
import com.b2international.snowowl.datastore.utils.ComponentUtils2;
import com.b2international.snowowl.terminologymetadata.CodeSystemVersionGroup;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;

/**
 * This class is a thin, generic wrapper around the underlying {@link CDOTransaction}. 
 * In order to make it terminology independent, it uses {@link EObject}s as opposed to 
 * specific classes.
 * 
 */
public abstract class CDOEditingContext implements AutoCloseable {

	/**
	 * Number of retires to successfully commit the changes from an editing context.
	 */
	public static final int COMMIT_STRIKES = 5;
	
	/**
	 * Shared logger instance.
	 */
	protected static final Logger LOGGER = LoggerFactory.getLogger(CDOEditingContext.class);
	
	/**
	 * Underlying CDO transaction.
	 */
	protected final CDOTransaction transaction;

	/**
	 * @param ePackage - the primary ePackage of this editing context
	 */
	protected CDOEditingContext(EPackage ePackage) {
		this(ePackage, getActivePath(ePackage));
	}
	
	protected CDOEditingContext(final EPackage ePackage, final IBranchPath branchPath) {
		this(createTransaction(checkNotNull(ePackage, "ePackage"), checkNotNull(branchPath, "Branch path argument cannot be null.")));
	}
	
	protected CDOEditingContext(final CDOTransaction cdoTransaction) {
		this.transaction = CDOUtils.check(cdoTransaction);
	}
	
	public final String getBranch() {
		return BranchPathUtils.createPath(getTransaction()).getPath();
	}
	
	public final <T extends CDOObject> Iterable<T> getNewObjects(Class<T> type) {
		return ComponentUtils2.getNewObjects(getTransaction(), type);
	}
	
	public final <T extends CDOObject> Iterable<T> getDetachedObjects(Class<T> type) {
		return ComponentUtils2.getDetachedObjects(getTransaction(), type);
	}
	
	public final <T extends CDOObject> Iterable<T> getChangedObjects(Class<T> type) {
		return ComponentUtils2.getDirtyObjects(getTransaction(), type);
	}
	
	/*
	 * get the index from the database for an EObject on the given table.
	 * If the object is not in the database, a RTE will be thrown.
	 */
	public int getIndexFromDatabase(final EObject object, final String tableName)  {
			
		// the object must be a cdoObject, otherwise the database cannot contain it
		if (!(object instanceof CDOObject)) {
			throw new RuntimeException("The removable object is not a CDOObject.");
		}
		if (tableName == null) {
			throw new RuntimeException("Argument tableName must not be null.");
		}
		final CDOObject cdoObject = (CDOObject) object;
		 		
		// query the resources table, to get the index directly
		final CDOObject container = object.eContainer()== null ? cdoObject.cdoResource() : (CDOObject) object.eContainer();
		final int version = container.cdoRevision().getVersion();
		final String sqlGetIndexFormatted = DatastoreQueries.SQL_GET_INDEX_AND_BRANCH_FOR_VALUE.getQuery(tableName);
		final CDOQuery query = transaction.createQuery("sql", sqlGetIndexFormatted);
		query.setParameter(CDOQueryUtils.CDO_OBJECT_QUERY, false);
		query.setParameter("cdoId", CDOIDUtil.getLong(cdoObject.cdoID()));
		query.setParameter("versionMaxAdded", version);
		final List<Object[]> result = query.getResult(Object[].class);
		// neither 0 nor more than 1 results are acceptable
		if (result.size() <= 0) {			
			throw new RuntimeException("Object not found in database. CDO ID: " + cdoObject.cdoID());
{'fraction_non_alphanumeric': 0.09563442211055276, 'fraction_numerical': 0.006988065326633166, 'mean_word_length': 5.413393756294059, 'pattern_counts': {'":': 0, '<': 16, '<?xml version=': 0, '>': 14, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5665646', 'n_tokens_mistral': 4013, 'n_tokens_neox': 3772, 'n_words': 937}