/*
Found a unique persistence unit from the application, starting from the module and if not
found, look for one in the ear scope. Returns null if no unqiue PU is found.
351976
private JPAPUnitInfo getUniquePU(String modName) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.entry(tc, "getUniquePU", modName);
        JPAPUnitInfo rtnVal = null;

        JPAScopeInfo scopeInfo = null;
        synchronized (puScopes) {
            scopeInfo = puScopes.get(modName);
        }
        int totalPus = (scopeInfo != null) ? scopeInfo.getAllPuCount() : 0;

        switch (totalPus) {
            case 1: // found a unique PU in the module.
                rtnVal = scopeInfo.getUniquePuInfo();
                break;

            case 0: // no PU in module scope, look for unique PU in ear scope
                synchronized (puScopes) {
                    scopeInfo = puScopes.get(EAR_SCOPE_MODULE_NAME);
                }
                totalPus = (scopeInfo != null) ? scopeInfo.getAllPuCount() : 0;
                if (totalPus == 1) {
                    // found only one, use it.
                    rtnVal = scopeInfo.getUniquePuInfo();
                    break;
                }
                // fall through to indicate no unique PU is found.
            default:
                // otherwise, can not determine what to use.
                Tr.error(tc, "PU_NOT_SPECIFIED_AND_NO_UNIQUE_PU_FOUND_CWWJP0012E", applName, modName);
        }
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.exit(tc, "getUniquePU", rtnVal);
        return rtnVal;
    }
917009
@GET
  @PermitAll
  @Path("uniquetag/{uniqueTag}")
  public Response findByUniqueTag(@PathParam("uniqueTag") String uniqueTag) {
    checkNotNull(uniqueTag);

    DContact contact = dao.findByUniqueTag(null, uniqueTag);

    return null != contact ? Response.ok(contact).build() : Response.status(Response.Status.NOT_FOUND).build();
  }
681975
def find(id)
      begin
        if repository?
          super(id)
        else
          serialize!(PersistenceAdapter.find(self, id))
        end
      rescue Exception => e
        message = "Couldn't find #{self} with ID=#{id}"
        message = "Couldn't find all #{self} objects with IDs (#{id.join(', ')})" if id.is_a?(Array)

        raise ActiveHash::RecordNotFound.new(message)
      end
    end
663387
@Override
    public <T> T find(Class<T> entityClass, Object primaryKey)
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            Tr.debug(tc, "em.find(" + entityClass + ',' + primaryKey + ");\n" + toString());

        return getEMInvocationInfo(false).find(entityClass, primaryKey);
    }
209920
public String find(RemoteBaseSession obj)
    {
        for (String strKey : this.keySet())
        {
            BaseHolder value = this.get(strKey);
            if (value.getRemoteObject() == obj)
                return strKey;            
        }
        return null;    // Not found.
    }
632657
@Override
    public LogRepositoryBrowser find(RepositoryPointerImpl location, boolean ignoreTimestamp) {
        String[] instanceIds = location.getInstanceIds();
        if (instanceIds.length == 0) {
            logger.logp(Level.SEVERE, className, "find", "HPEL_NotRepositoryLocation");
            return null;
        }

        String locProcId = ignoreTimestamp ? parsePIDandLabel(instanceIds[0]) : instanceIds[0];
        LogRepositoryBrowser result = null;
        File[] files = listFiles(instanceFilter);
        if (files == null) {
            return null;
        }
        for (File file : files) {
            String curProcId = ignoreTimestamp ? parsePIDandLabel(file.getName()) : file.getName();
            if (locProcId.equalsIgnoreCase(curProcId)) {
                result = new LogRepositoryBrowserImpl(file, new String[] { file.getName() });
                for (int i = 1; i < instanceIds.length && result != null; i++) {
                    Map<String, LogRepositoryBrowser> map = result.getSubProcesses();
                    result = map.get(instanceIds[i]);
                }
            }
        }

        return result;
    }
289133
private void readObject(ObjectInputStream ois)
      throws ClassNotFoundException, IOException
   {
      ObjectInputStream.GetField fields = ois.readFields();
      String name = serialPersistentFields[STATUS_IDX].getName();
      this.status = (DeploymentStatus) fields.get(name, null);
      name = serialPersistentFields[MODULE_ID_IDX].getName();
      this.moduleID = (TargetModuleID) fields.get(name, null);
   }
555436
protected String lookupEeApplicationName() {

    try {
      InitialContext initialContext = new InitialContext();

      String appName = (String) initialContext.lookup(JAVA_APP_APP_NAME_PATH);
      String moduleName = (String) initialContext.lookup(MODULE_NAME_PATH);

      // make sure that if an EAR carries multiple PAs, they are correctly
      // identified by appName + moduleName
      if (moduleName != null && !moduleName.equals(appName)) {
        return appName + "/" + moduleName;
      } else {
        return appName;
      }
    }
    catch (NamingException e) {
      throw LOG.ejbPaCannotAutodetectName(e);
    }
  }
354197
@Override
    public EntityManager getEntityManager
                    (JPAPuId puId,
                     J2EEName j2eeName, // d510184
                     String refName, // d510184
                     boolean isExtendedContextType,
                     boolean isUnsynchronized,
                     Map<?, ?> properties)
    {
        final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
        if (isTraceOn && tc.isEntryEnabled())
            Tr.entry(tc, "getEntityManager : " + puId + ", " + j2eeName);

        EntityManager em = null;
        JPAPUnitInfo puInfo = findPersistenceUnitInfo(puId);
        if (puInfo != null)
        {
            em = isExtendedContextType ?
                            getJPARuntime().createJPAExEntityManager(puId, puInfo, j2eeName, refName, properties, isUnsynchronized, this) :
                            getJPARuntime().createJPATxEntityManager(puId, puInfo, j2eeName, refName, properties, isUnsynchronized, this);
        }
        if (isTraceOn && tc.isEntryEnabled())
            Tr.exit(tc, "getEntityManager : " + em);
        return em;

    }
1006738
public void addPersistenceUnits(JPAPXml pxml) {
        final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
        if (isTraceOn && tc.isDebugEnabled())
            Tr.debug(tc, "addPersistenceUnits", pxml);

        JPAPuScope puScope = pxml.getPuScope();
        String scopeKey = (puScope == JPAPuScope.EAR_Scope) ? EAR_SCOPE_MODULE_NAME : pxml.getArchiveName();

        JPAScopeInfo scopeInfo = null;
        synchronized (puScopes) {
            scopeInfo = puScopes.get(scopeKey);
            if (scopeInfo == null) {
                scopeInfo = new JPAScopeInfo(scopeKey, puScope);
                puScopes.put(scopeKey, scopeInfo);
            }
        }

        // delegate to scopeInfo to read in the persistence-unit data
        JPAIntrospection.beginPUScopeVisit(scopeInfo);
        try {
            scopeInfo.processPersistenceUnit(pxml, this);
        } finally {
            JPAIntrospection.endPUScopeVisit();
        }
    }
706630
public boolean startDiscovery() {
        if (mScanning) {
            Log.e(TAG, "Already discovering");
            return true;
        }

        if (mListener == null) {
            throw new NullPointerException("Listener cannot be null");
        }

        return scan();
    }
1116162
@Transactional
    public E findUniqueOrNone(E entity, SearchParameters sp) {
        // this code is an optimization to prevent using a count
        sp.setFirst(0);
        sp.setMaxResults(2);
        List<E> results = find(entity, sp);

        if (results == null || results.isEmpty()) {
            return null;
        } else if (results.size() > 1) {
            throw new NonUniqueResultException("Developper: You expected 1 result but we found more ! sample: " + entity);
        } else {
            return results.iterator().next();
        }
    }
988641
@Override
    public final long getUniqueTickCount() throws PersistenceException
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(this, tc, "getUniqueTickCount");

        if (_tickCountGenerator != null)
        {
            long key = AbstractItem.NO_ID;

            key = _tickCountGenerator.getUniqueValue();

            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
                SibTr.exit(this, tc, "getUniqueTickCount", Long.valueOf(key));
            return key;
        }
        else
        {
            MessageStoreUnavailableException msue;
            if (!_startupExceptions.isEmpty())
            {
                if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled())
                    SibTr.event(this, tc, "Operation not possible as MessageStore failed to start!");
                msue = new MessageStoreUnavailableException("Operation not possible as MessageStore failed to start!", _startupExceptions.get(0));
            }
            else
            {
                if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled())
                    SibTr.event(this, tc, "Operation not possible as MessageStore is unavailable!");
                msue = new MessageStoreUnavailableException("Operation not possible as MessageStore is unavailable!");
            }

            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
                SibTr.exit(this, tc, "getUniqueTickCount");
            throw msue;
        }
    }
900342
@Override
    public Object find(Class entityClass, Object key)
    {
        Object result = null;
        Object connection = getConnection();
        try
        {
            result = fetch(entityClass, key, connection, null);
        }
        catch (InstantiationException e)
        {
            logger.error("Error during find by key:", e);
            throw new PersistenceException(e);
        }
        catch (IllegalAccessException e)
        {
            logger.error("Error during find by key:", e);
            throw new PersistenceException(e);
        }
        finally
        {
            onCleanup(connection);
        }

        return result;
    }
863787
public Object find(Class clazz, Object identifier) {
        try {
            return persistenceManager.findById(clazz, identifier);
        } catch (InitializationException ignore){}
        catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
27272
private Map<String, PersistenceUnitMetadata> findPersistenceMetadatas() throws InvalidConfigurationException
    {
        String puLocation = (String) (externalPropertyMap != null
                && externalPropertyMap.get(Constants.PERSISTENCE_UNIT_LOCATIION) != null ? externalPropertyMap
                .get(Constants.PERSISTENCE_UNIT_LOCATIION) : Constants.DEFAULT_PERSISTENCE_UNIT_LOCATIION);

        Enumeration<URL> xmls = null;
        try
        {
            xmls = this.getClass().getClassLoader().getResources(puLocation);
        }
        catch (IOException ioex)
        {
            log.warn("Error while loading persistence.xml, Caused by: {}.", ioex);
        }

        if (xmls == null || !xmls.hasMoreElements())
        {
            log.error("Could not find any META-INF/persistence.xml file in the classpath");
            throw new InvalidConfigurationException("Could not find any META-INF/persistence.xml file in the classpath");
        }

        Set<String> persistenceUnitNames = new HashSet<String>();
        Map<String, PersistenceUnitMetadata> persistenceUnitMap = new HashMap<String, PersistenceUnitMetadata>();
        while (xmls.hasMoreElements())
        {
            URL url = xmls.nextElement();

            log.trace("Analysing persistence.xml: " + url);
            List<PersistenceUnitMetadata> metadataFiles = PersistenceXMLLoader.findPersistenceUnits(url, persistenceUnits, 
                    PersistenceUnitTransactionType.RESOURCE_LOCAL);

            // Pick only those that have Kundera Provider
            for (PersistenceUnitMetadata metadata : metadataFiles)
            {
                // check for unique names
                if (persistenceUnitNames.contains(metadata.getPersistenceUnitName()))
                {
                    if (log.isWarnEnabled())
                    {
                        log.warn("Duplicate persistence-units for name: " + metadata.getPersistenceUnitName()
                                + ". verify your persistence.xml file");
                    }
                }

                // check for provider
                if (metadata.getPersistenceProviderClassName() == null
                        || PROVIDER_IMPLEMENTATION_NAME.equalsIgnoreCase(metadata.getPersistenceProviderClassName()))
                {
                    persistenceUnitMap.put(metadata.getPersistenceUnitName(), metadata);
                }

                // add to check for duplicate persistence unit.
                persistenceUnitNames.add(metadata.getPersistenceUnitName());
            }
        }
        return persistenceUnitMap;
    }
440078
@Override
    public LogRepositoryBrowser findNext(RepositoryPointerImpl location,
                                         long timelimit) {
        String[] instanceIds = location.getInstanceIds();
        if (instanceIds.length == 0) {
            logger.logp(Level.SEVERE, className, "findNext", "HPEL_NotRepositoryLocation");
            return null;
        }

        return findNext(parseTimeStamp(instanceIds[0]), timelimit);
    }