/**
   * @see
   *     org.alfresco.service.cmr.coci.CheckOutCheckInService#getWorkingCopy(org.alfresco.service.cmr.repository.NodeRef)
   */
  public NodeRef getWorkingCopy(NodeRef nodeRef) {
    NodeRef workingCopy = null;

    // Do a search to find the working copy document
    ResultSet resultSet = null;

    try {
      resultSet =
          this.searchService.query(
              nodeRef.getStoreRef(),
              SearchService.LANGUAGE_LUCENE,
              "+ASPECT:\""
                  + ContentModel.ASPECT_WORKING_COPY.toString()
                  + "\" +@\\{http\\://www.alfresco.org/model/content/1.0\\}"
                  + ContentModel.PROP_COPY_REFERENCE.getLocalName()
                  + ":\""
                  + nodeRef.toString()
                  + "\"");
      if (resultSet.getNodeRefs().size() != 0) {
        workingCopy = resultSet.getNodeRef(0);
      }
    } finally {
      if (resultSet != null) {
        resultSet.close();
      }
    }

    return workingCopy;
  }
  /**
   * Returns all deployment attempts for the given store
   *
   * @param store The store to get the deployment attempts for
   * @param fromDate If present only attempts after the given date are returned
   * @param toDate If present only attempts before the given date are returned, if null toDate
   *     defaults to today's date
   * @return List of NodeRef's representing the deployment attempts
   */
  public static List<NodeRef> findDeploymentAttempts(String store, Date fromDate, Date toDate) {
    FacesContext fc = FacesContext.getCurrentInstance();
    SearchService searchService = Repository.getServiceRegistry(fc).getSearchService();

    // query for all deploymentattempt nodes with the deploymentattemptstore
    // set to the given store id
    StringBuilder query = new StringBuilder("@");
    query.append(NamespaceService.WCMAPP_MODEL_PREFIX);
    query.append("\\:");
    query.append(WCMAppModel.PROP_DEPLOYATTEMPTSTORE.getLocalName());
    query.append(":\"");
    query.append(store);
    query.append("\"");

    // constrain the search by date if a fromDate is applied
    if (fromDate != null) {
      if (toDate == null) {
        toDate = new Date();
      }

      // see if the dates are the same (ignoring the time)
      boolean sameDate = false;
      Calendar fromCal = new GregorianCalendar();
      fromCal.setTime(fromDate);
      Calendar toCal = new GregorianCalendar();
      toCal.setTime(toDate);
      if ((fromCal.get(Calendar.YEAR) == toCal.get(Calendar.YEAR))
          && (fromCal.get(Calendar.MONTH) == toCal.get(Calendar.MONTH))
          && (fromCal.get(Calendar.DAY_OF_MONTH) == toCal.get(Calendar.DAY_OF_MONTH))) {
        sameDate = true;
      }

      // add date to query
      query.append(" AND @");
      query.append(NamespaceService.WCMAPP_MODEL_PREFIX);
      query.append("\\:");
      query.append(WCMAppModel.PROP_DEPLOYATTEMPTTIME.getLocalName());
      query.append(":");

      if (sameDate) {
        // convert date into format needed for range query
        String queryDate = formatLuceneQueryDate(fromDate, false);

        // query for exact date
        query.append("\"");
        query.append(queryDate);
        query.append("\"");
      } else {
        // convert to date into format needed for range query
        String queryFromDate = formatLuceneQueryDate(fromDate, true);
        String queryToDate = formatLuceneQueryDate(toDate, true);

        // create a date range query
        query.append("[");
        query.append(queryFromDate);
        query.append(" TO ");
        query.append(queryToDate);
        query.append("]");
      }
    }

    if (logger.isDebugEnabled())
      logger.debug("Finding deploymentattempt nodes using query: " + query.toString());

    ResultSet results = null;
    List<NodeRef> attempts = new ArrayList<NodeRef>();
    try {
      // sort the results by deploymentattempttime
      SearchParameters sp = new SearchParameters();
      sp.addStore(Repository.getStoreRef());
      sp.setLanguage(SearchService.LANGUAGE_LUCENE);
      sp.setQuery(query.toString());
      sp.addSort("@" + WCMAppModel.PROP_DEPLOYATTEMPTTIME, false);

      // execute the query
      results = searchService.query(sp);

      if (logger.isDebugEnabled())
        logger.debug("Found " + results.length() + " deployment attempts");

      for (NodeRef attempt : results.getNodeRefs()) {
        attempts.add(attempt);
      }
    } finally {
      if (results != null) {
        results.close();
      }
    }

    return attempts;
  }
  /**
   * Returns a list of NodeRefs representing the deployment servers configured for the given web
   * project.
   *
   * @param webProject Web project to get test servers for
   * @param live
   * @param availableOnly if true only returns those servers still available for deployment
   * @return List of test servers
   */
  private static List<NodeRef> findServers(
      NodeRef webProject, boolean live, boolean availableOnly) {
    FacesContext context = FacesContext.getCurrentInstance();
    NodeService nodeService = Repository.getServiceRegistry(context).getNodeService();
    SearchService searchService = Repository.getServiceRegistry(context).getSearchService();

    NamespacePrefixResolver namespacePrefixResolver =
        Repository.getServiceRegistry(context).getNamespaceService();

    Path projectPath = nodeService.getPath(webProject);

    String stringPath = projectPath.toPrefixString(namespacePrefixResolver);

    StringBuilder query = new StringBuilder("PATH:\"");

    query.append(stringPath);
    query.append("/*\" ");
    query.append(" AND @");
    query.append(NamespaceService.WCMAPP_MODEL_PREFIX);
    query.append("\\:");
    query.append(WCMAppModel.PROP_DEPLOYSERVERTYPE.getLocalName());
    query.append(":\"");
    if (live) {
      query.append(WCMAppModel.CONSTRAINT_LIVESERVER);
    } else {
      query.append(WCMAppModel.CONSTRAINT_TESTSERVER);
    }
    query.append("\"");

    // if required filter the test servers
    if (live == false && availableOnly) {
      query.append(" AND ISNULL:\"");
      query.append(WCMAppModel.PROP_DEPLOYSERVERALLOCATEDTO.toString());
      query.append("\"");
    }

    if (logger.isDebugEnabled())
      logger.debug("Finding deployment servers using query: " + query.toString());

    // execute the query
    ResultSet results = null;
    List<NodeRef> servers = new ArrayList<NodeRef>();
    try {
      results =
          searchService.query(
              Repository.getStoreRef(), SearchService.LANGUAGE_LUCENE, query.toString());

      if (logger.isDebugEnabled())
        logger.debug("Found " + results.length() + " deployment servers");

      for (NodeRef server : results.getNodeRefs()) {
        servers.add(server);
      }
    } finally {
      if (results != null) {
        results.close();
      }
    }

    return servers;
  }