<commit_before>package gov.nih.nci.cananolab.service.particle.impl;

import gov.nih.nci.cananolab.domain.common.Keyword;
import gov.nih.nci.cananolab.domain.common.PointOfContact;
import gov.nih.nci.cananolab.domain.particle.NanoparticleSample;
import gov.nih.nci.cananolab.domain.particle.characterization.Characterization;
import gov.nih.nci.cananolab.domain.particle.samplecomposition.base.NanoparticleEntity;
import gov.nih.nci.cananolab.domain.particle.samplecomposition.chemicalassociation.ChemicalAssociation;
import gov.nih.nci.cananolab.domain.particle.samplecomposition.functionalization.FunctionalizingEntity;
import gov.nih.nci.cananolab.dto.common.UserBean;
import gov.nih.nci.cananolab.dto.particle.ParticleBean;
import gov.nih.nci.cananolab.exception.CaNanoLabSecurityException;
import gov.nih.nci.cananolab.exception.DuplicateEntriesException;
import gov.nih.nci.cananolab.exception.ParticleException;
import gov.nih.nci.cananolab.service.particle.NanoparticleCharacterizationService;
import gov.nih.nci.cananolab.service.particle.NanoparticleCompositionService;
import gov.nih.nci.cananolab.service.particle.NanoparticleSampleService;
import gov.nih.nci.cananolab.service.particle.helper.NanoparticleSampleServiceHelper;
import gov.nih.nci.cananolab.service.security.AuthorizationService;
import gov.nih.nci.cananolab.system.applicationservice.CustomizedApplicationService;
import gov.nih.nci.cananolab.util.CaNanoLabComparators;
import gov.nih.nci.cananolab.util.CaNanoLabConstants;
import gov.nih.nci.cananolab.util.SortableName;
import gov.nih.nci.cananolab.util.StringUtils;
import gov.nih.nci.system.client.ApplicationServiceProvider;
import gov.nih.nci.system.query.hibernate.HQLCriteria;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;

import org.apache.log4j.Logger;
import org.hibernate.FetchMode;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;

/**
 * Service methods involving nanoparticle samples
 * 
 * @author pansu
 * 
 */
public class NanoparticleSampleServiceLocalImpl implements
		NanoparticleSampleService {
	private static Logger logger = Logger
			.getLogger(NanoparticleSampleServiceLocalImpl.class);

	private NanoparticleSampleServiceHelper helper = new NanoparticleSampleServiceHelper();

	/**
	 * 
	 * @return all particle sources
	 */
	public SortedSet<PointOfContact> findPointOfContacts() throws ParticleException {
		SortedSet<PointOfContact> pointOfContacts = new TreeSet<PointOfContact>(
				new CaNanoLabComparators.ParticlePointOfContactComparator());
		try {
			CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
					.getApplicationService();
			DetachedCriteria crit = DetachedCriteria.forClass(PointOfContact.class);
			crit.setFetchMode("organization", FetchMode.JOIN);
			List results = appService.query(crit);			
			for (Object obj : results) {
				pointOfContacts.add((PointOfContact) obj);
			}
			return pointOfContacts;
		} catch (Exception e) {
			String err = "Error in retrieving all point of contacts";
			logger.error(err, e);
			throw new ParticleException(err, e);
		}
	}

	/**
	 * 
	 * @return all particle point of contacts visible to user
	 */
	
	public SortedSet<PointOfContact> findPointOfContacts(UserBean user)
		throws ParticleException {
		//TODO: filter out base on POC visibility??
		return findPointOfContacts();
	}
	
//	public SortedSet<PointOfContact> findPointOfContacts(UserBean user)
//			throws ParticleException {
//		SortedSet<Organization> sampleOrganizations = new TreeSet<PointOfContact>(
//				new CaNanoLabComparators.ParticleOrganizationComparator());
//		try {
//			AuthorizationService auth = new AuthorizationService(
//					CaNanoLabConstants.CSM_APP_NAME);
//			CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
//					.getApplicationService();
//			DetachedCriteria crit = DetachedCriteria.forClass(PointOfContact.class);
//			crit.setFetchMode("primaryNanoparticleSampleCollection", FetchMode.JOIN);
//			crit.setFetchMode("nanoparticleSampleCollection", FetchMode.JOIN);
//			List results = appService.query(crit);
//			for (Object obj : results) {
//				PointOfContact poc = (PointOfContact) obj;
//				// if user can access at least one particle from the organization, set
//				// access to true
//				List<String> particleNames = new ArrayList<String>();
//				for (NanoparticleSample sample : 
//					organization.getPrimaryNanoparticleSampleCollection()) {
//					particleNames.add(sample.getName());
//				}
//				for (NanoparticleSample sample : organization
//						.getPrimaryNanoparticleSampleCollection()) {
//					particleNames.add(sample.getName());
//				}				
//				if (auth.isAllowedAtLeastOne(auth, particleNames, user)) {
//					sampleOrganizations.add((Organization) obj);
//				}
//			}
//			return sampleOrganizations;
//		} catch (Exception e) {
//			String err = "Error in retrieving all nanoparticle sample organizations for a user";
//			logger.error(err, e);
//			throw new ParticleException(err, e);
//		}
//	}

	/**
	 * Persist a new nanoparticle sample or update an existing nanoparticle
	 * sample
	 * 
	 * @param particleSample
	 * @throws ParticleException,
	 *             DuplicateEntriesException
	 */
	public void saveNanoparticleSample(NanoparticleSample particleSample)
			throws ParticleException, DuplicateEntriesException {
		try {
			CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
					.getApplicationService();

			NanoparticleSample dbParticle = (NanoparticleSample) appService
					.getObject(NanoparticleSample.class, "name", particleSample
							.getName());
			if (dbParticle != null
					&& !dbParticle.getId().equals(particleSample.getId())) {
				throw new DuplicateEntriesException();
			}
			PointOfContact dbPointOfContact = (PointOfContact) appService.getObject(PointOfContact.class,
					"id", particleSample.getPrimaryPointOfContact().getId());
			
			if (dbPointOfContact != null) {
				dbPointOfContact = (PointOfContact) appService.load(
						PointOfContact.class, dbPointOfContact.getId());
				particleSample.getPrimaryPointOfContact().setId(dbPointOfContact.getId());
				particleSample.setPrimaryPointOfContact(dbPointOfContact);
			}
			for (Keyword keyword : particleSample.getKeywordCollection()) {
				// turned off cascade save-update in order to share the same
				// keyword instance with File keywords.
				Keyword dbKeyword = (Keyword) appService.getObject(
						Keyword.class, "name", keyword.getName());
				if (dbKeyword != null) {
					keyword.setId(dbKeyword.getId());
				}
				appService.saveOrUpdate(keyword);
			}			
			appService.saveOrUpdate(particleSample);
		} catch (DuplicateEntriesException e) {
			throw e;
		} catch (Exception e) {
			String err = "Error in saving the nanoparticle sample.";
			logger.error(err, e);
			throw new ParticleException(err, e);
		}
	}

	/**
	 * 
	 * @param particlePointOfContacts
	 * @param nanoparticleEntityClassNames
	 * @param otherNanoparticleTypes
	 * @param functionalizingEntityClassNames
	 * @param otherFunctionalizingEntityTypes
	 * @param functionClassNames
	 * @param otherFunctionTypes
	 * @param characterizationClassNames
	 * @param wordList
	 * @return
	 * @throws ParticleException
	 */
	public List<ParticleBean> findNanoparticleSamplesBy(String particlePointOfContact,<commit_msg>updated saveNanoparticleSample to save keywords correctly.<commit_after>package gov.nih.nci.cananolab.service.particle.impl;

import gov.nih.nci.cananolab.domain.common.Keyword;
import gov.nih.nci.cananolab.domain.common.PointOfContact;
import gov.nih.nci.cananolab.domain.particle.NanoparticleSample;
import gov.nih.nci.cananolab.domain.particle.characterization.Characterization;
import gov.nih.nci.cananolab.domain.particle.samplecomposition.base.NanoparticleEntity;
import gov.nih.nci.cananolab.domain.particle.samplecomposition.chemicalassociation.ChemicalAssociation;
import gov.nih.nci.cananolab.domain.particle.samplecomposition.functionalization.FunctionalizingEntity;
import gov.nih.nci.cananolab.dto.common.UserBean;
import gov.nih.nci.cananolab.dto.particle.ParticleBean;
import gov.nih.nci.cananolab.exception.CaNanoLabSecurityException;
import gov.nih.nci.cananolab.exception.DuplicateEntriesException;
import gov.nih.nci.cananolab.exception.ParticleException;
import gov.nih.nci.cananolab.service.particle.NanoparticleCharacterizationService;
import gov.nih.nci.cananolab.service.particle.NanoparticleCompositionService;
import gov.nih.nci.cananolab.service.particle.NanoparticleSampleService;
import gov.nih.nci.cananolab.service.particle.helper.NanoparticleSampleServiceHelper;
import gov.nih.nci.cananolab.service.security.AuthorizationService;
import gov.nih.nci.cananolab.system.applicationservice.CustomizedApplicationService;
import gov.nih.nci.cananolab.util.CaNanoLabComparators;
import gov.nih.nci.cananolab.util.CaNanoLabConstants;
import gov.nih.nci.cananolab.util.SortableName;
import gov.nih.nci.cananolab.util.StringUtils;
import gov.nih.nci.system.client.ApplicationServiceProvider;
import gov.nih.nci.system.query.hibernate.HQLCriteria;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;

import org.apache.log4j.Logger;
import org.hibernate.FetchMode;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;

/**
 * Service methods involving nanoparticle samples
 * 
 * @author pansu
 * 
 */
public class NanoparticleSampleServiceLocalImpl implements
		NanoparticleSampleService {
	private static Logger logger = Logger
			.getLogger(NanoparticleSampleServiceLocalImpl.class);

	private NanoparticleSampleServiceHelper helper = new NanoparticleSampleServiceHelper();

	/**
	 * 
	 * @return all particle sources
	 */
	public SortedSet<PointOfContact> findPointOfContacts() throws ParticleException {
		SortedSet<PointOfContact> pointOfContacts = new TreeSet<PointOfContact>(
				new CaNanoLabComparators.ParticlePointOfContactComparator());
		try {
			CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
					.getApplicationService();
			DetachedCriteria crit = DetachedCriteria.forClass(PointOfContact.class);
			crit.setFetchMode("organization", FetchMode.JOIN);
			List results = appService.query(crit);			
			for (Object obj : results) {
				pointOfContacts.add((PointOfContact) obj);
			}
			return pointOfContacts;
		} catch (Exception e) {
			String err = "Error in retrieving all point of contacts";
			logger.error(err, e);
			throw new ParticleException(err, e);
		}
	}

	/**
	 * 
	 * @return all particle point of contacts visible to user
	 */
	
	public SortedSet<PointOfContact> findPointOfContacts(UserBean user)
		throws ParticleException {
		//TODO: filter out base on POC visibility??
		return findPointOfContacts();
	}
	
//	public SortedSet<PointOfContact> findPointOfContacts(UserBean user)
//			throws ParticleException {
//		SortedSet<Organization> sampleOrganizations = new TreeSet<PointOfContact>(
//				new CaNanoLabComparators.ParticleOrganizationComparator());
//		try {
//			AuthorizationService auth = new AuthorizationService(
//					CaNanoLabConstants.CSM_APP_NAME);
//			CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
//					.getApplicationService();
//			DetachedCriteria crit = DetachedCriteria.forClass(PointOfContact.class);
//			crit.setFetchMode("primaryNanoparticleSampleCollection", FetchMode.JOIN);
//			crit.setFetchMode("nanoparticleSampleCollection", FetchMode.JOIN);
//			List results = appService.query(crit);
//			for (Object obj : results) {
//				PointOfContact poc = (PointOfContact) obj;
//				// if user can access at least one particle from the organization, set
//				// access to true
//				List<String> particleNames = new ArrayList<String>();
//				for (NanoparticleSample sample : 
//					organization.getPrimaryNanoparticleSampleCollection()) {
//					particleNames.add(sample.getName());
//				}
//				for (NanoparticleSample sample : organization
//						.getPrimaryNanoparticleSampleCollection()) {
//					particleNames.add(sample.getName());
//				}				
//				if (auth.isAllowedAtLeastOne(auth, particleNames, user)) {
//					sampleOrganizations.add((Organization) obj);
//				}
//			}
//			return sampleOrganizations;
//		} catch (Exception e) {
//			String err = "Error in retrieving all nanoparticle sample organizations for a user";
//			logger.error(err, e);
//			throw new ParticleException(err, e);
//		}
//	}

	/**
	 * Persist a new nanoparticle sample or update an existing nanoparticle
	 * sample
	 * 
	 * @param particleSample
	 * @throws ParticleException,
	 *             DuplicateEntriesException
	 */
	public void saveNanoparticleSample(NanoparticleSample particleSample)
			throws ParticleException, DuplicateEntriesException {
		try {
			CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
					.getApplicationService();

			NanoparticleSample dbParticle = (NanoparticleSample) appService
					.getObject(NanoparticleSample.class, "name", particleSample
							.getName());
			if (dbParticle != null
					&& !dbParticle.getId().equals(particleSample.getId())) {
				throw new DuplicateEntriesException();
			}
			if (particleSample.getPrimaryPointOfContact().getId() != null) {
				PointOfContact dbPointOfContact = (PointOfContact) appService
						.getObject(PointOfContact.class, "id", particleSample
								.getPrimaryPointOfContact().getId());
				if (dbPointOfContact != null) {
					dbPointOfContact = (PointOfContact) appService.load(
							PointOfContact.class, dbPointOfContact.getId());
					particleSample.setPrimaryPointOfContact(dbPointOfContact);
				}
			}
			if (particleSample.getKeywordCollection() != null) {
				Collection<Keyword> keywords = new HashSet<Keyword>(
						particleSample.getKeywordCollection());
				particleSample.getKeywordCollection().clear();
				for (Keyword keyword : keywords) {
					Keyword dbKeyword = (Keyword) appService.getObject(
							Keyword.class, "name", keyword.getName());
					if (dbKeyword != null) {
						keyword.setId(dbKeyword.getId());
					}
					// turned off cascade save-update in order to share the same
					// keyword instance with File keywords.
					appService.saveOrUpdate(keyword);
					particleSample.getKeywordCollection().add(keyword);
				}
			}
			appService.saveOrUpdate(particleSample);
		} catch (DuplicateEntriesException e) {
			throw e;
		} catch (Exception e) {
			String err = "Error in saving the nanoparticle sample.";
			logger.error(err, e);
			throw new ParticleException(err, e);
		}
	}

	/**
	 * 
	 * @param particlePointOfContacts
	 * @param nanoparticleEntityClassNames
	 * @param otherNanoparticleTypes
	 * @param functionalizingEntityClassNames
	 * @param otherFunctionalizingEntityTypes
	 * @param functionClassNames
	 * @param otherFunctionTypes
	 * @param characterizationClassNames
	 * @param wordList
	 * @return
	 * @throws ParticleException
	 */
	public List<ParticleBean> findNanoparticleSamplesBy(String particlePointOfContact,
{'fraction_non_alphanumeric': 0.1023757823476817, 'fraction_numerical': 0.00012773023374632777, 'mean_word_length': 4.810389610389611, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 25, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '6965337', 'n_tokens_mistral': 5294, 'n_tokens_neox': 4578, 'n_words': 854}