Example #1
0
  /**
   * Retrieves the NodeRef of the deploymentattempt node with the given id
   *
   * @param attemptId The deployattemptid of the node to be found
   * @return The NodeRef of the deploymentattempt node or null if not found
   */
  public static NodeRef findDeploymentAttempt(String attemptId) {
    FacesContext fc = FacesContext.getCurrentInstance();
    SearchService searchService = Repository.getServiceRegistry(fc).getSearchService();

    // construct the query
    StringBuilder query = new StringBuilder("@");
    query.append(NamespaceService.WCMAPP_MODEL_PREFIX);
    query.append("\\:");
    query.append(WCMAppModel.PROP_DEPLOYATTEMPTID.getLocalName());
    query.append(":\"");
    query.append(attemptId);
    query.append("\"");

    ResultSet results = null;
    NodeRef attempt = null;
    try {
      // execute the query
      results =
          searchService.query(
              Repository.getStoreRef(), SearchService.LANGUAGE_LUCENE, query.toString());

      if (results.length() == 1) {
        attempt = results.getNodeRef(0);
      } else if (results.length() > 1) {
        throw new IllegalStateException(
            "More than one deployment attempt node was found, there should only be one!");
      }
    } finally {
      if (results != null) {
        results.close();
      }
    }

    return attempt;
  }
Example #2
0
    public NodeRef doWork() throws Exception {
      // Get company home / root for the tenant domain
      // Do this as the System user in case the tenant user does not have permission

      // Connect to the repo and ensure that the store exists
      if (!nodeService.exists(storeRef)) {
        throw new AlfrescoRuntimeException(
            "Store not created prior to application startup: " + storeRef);
      }
      NodeRef storeRootNodeRef = nodeService.getRootNode(storeRef);

      // Find the root node for this device
      List<NodeRef> nodeRefs =
          searchService.selectNodes(storeRootNodeRef, rootPath, null, namespaceService, false);

      if (nodeRefs.size() > 1) {
        throw new AlfrescoRuntimeException(
            "Multiple possible roots for device: \n"
                + "   root path: "
                + rootPath
                + "\n"
                + "   results: "
                + nodeRefs);
      } else if (nodeRefs.size() == 0) {
        // nothing found
        throw new AlfrescoRuntimeException(
            "No root found for device: \n" + "   root path: " + rootPath);
      } else {
        // we found a node
        rootNodeRef = nodeRefs.get(0);
      }

      return rootNodeRef;
    }
Example #3
0
  /**
   * Helper to convert a path into an indexed path which uniquely identifies a node
   *
   * @param nodeRef
   * @param path
   * @return
   */
  private Path createIndexedPath(NodeRef nodeRef, Path path) {
    // Add indexes for same name siblings
    // TODO: Look at more efficient approach
    for (int i = path.size() - 1; i >= 0; i--) {
      Path.Element pathElement = path.get(i);
      if (i > 0 && pathElement instanceof Path.ChildAssocElement) {
        int index = 1; // for xpath index compatibility
        String searchPath = path.subPath(i).toPrefixString(namespaceService);
        List<NodeRef> siblings =
            searchService.selectNodes(nodeRef, searchPath, null, namespaceService, false);
        if (siblings.size() > 1) {
          ChildAssociationRef childAssoc = ((Path.ChildAssocElement) pathElement).getRef();
          NodeRef childRef = childAssoc.getChildRef();
          for (NodeRef sibling : siblings) {
            if (sibling.equals(childRef)) {
              childAssoc.setNthSibling(index);
              break;
            }
            index++;
          }
        }
      }
    }

    return path;
  }
  /**
   * @param storeValue
   * @param rootPath
   * @param context
   * @param nodeService
   * @param searchService
   * @param namespaceService
   * @param tenantService
   * @param m_transactionService
   */
  private void initializeRootNode(
      String storeValue,
      String rootPath,
      WebApplicationContext context,
      NodeService nodeService,
      SearchService searchService,
      NamespaceService namespaceService,
      TenantService tenantService,
      TransactionService m_transactionService) {

    // Use the system user as the authenticated context for the filesystem initialization

    AuthenticationContext authComponent =
        (AuthenticationContext) context.getBean("authenticationContext");
    authComponent.setSystemUserAsCurrentUser();

    // Wrap the initialization in a transaction

    UserTransaction tx = m_transactionService.getUserTransaction(true);

    try {
      // Start the transaction

      if (tx != null) tx.begin();

      StoreRef storeRef = new StoreRef(storeValue);

      if (nodeService.exists(storeRef) == false) {
        throw new RuntimeException("No store for path: " + storeRef);
      }

      NodeRef storeRootNodeRef = nodeService.getRootNode(storeRef);

      List<NodeRef> nodeRefs =
          searchService.selectNodes(storeRootNodeRef, rootPath, null, namespaceService, false);

      if (nodeRefs.size() > 1) {
        throw new RuntimeException(
            "Multiple possible children for : \n"
                + "   path: "
                + rootPath
                + "\n"
                + "   results: "
                + nodeRefs);
      } else if (nodeRefs.size() == 0) {
        throw new RuntimeException("Node is not found for : \n" + "   root path: " + rootPath);
      }

      defaultRootNode = nodeRefs.get(0);

      // Commit the transaction
      if (tx != null) tx.commit();
    } catch (Exception ex) {
      logger.error(ex);
    } finally {
      // Clear the current system user

      authComponent.clearCurrentSecurityContext();
    }
  }
  @Override
  public NodeRef createNode(
      Resource resource,
      RepositoryLocation targetLocation,
      String encoding,
      String mimetype,
      QName nodeType)
      throws IOException {
    NodeRef rootNode = nodeService.getRootNode(targetLocation.getStoreRef());
    final List<NodeRef> parentNodes =
        searchService.selectNodes(
            rootNode, targetLocation.getPath(), null, namespaceService, false);
    Assert.isTrue(parentNodes.size() == 1, "Target location leads to not 1 unique Node reference");

    final String fileName = resource.getFilename();
    final FileInfo fileInfo = fileFolderService.create(parentNodes.get(0), fileName, nodeType);
    final NodeRef nodeRef = fileInfo.getNodeRef();

    final ContentWriter writer = contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
    writer.putContent(resource.getInputStream());

    if (mimetype == null) {
      mimetype = guessMimetype(resource);
    }

    if (encoding == null) {
      encoding = guessEncoding(resource.getInputStream(), mimetype);
    }

    writer.setMimetype(mimetype);
    writer.setEncoding(encoding);

    return nodeRef;
  }
Example #6
0
  /**
   * Returns the test servers allocated to the given store.
   *
   * @param store The store to get the test server for
   * @return The allocated server(s), an empty list if there isn't one
   */
  public static List<NodeRef> findAllocatedTestServers(String store) {
    List<NodeRef> serverList = new ArrayList<NodeRef>();

    FacesContext fc = FacesContext.getCurrentInstance();
    SearchService searchService = Repository.getServiceRegistry(fc).getSearchService();

    // construct the query
    StringBuilder query = new StringBuilder("@");
    query.append(NamespaceService.WCMAPP_MODEL_PREFIX);
    query.append("\\:");
    query.append(WCMAppModel.PROP_DEPLOYSERVERALLOCATEDTO.getLocalName());
    query.append(":\"");
    query.append(store);
    query.append("\"");

    ResultSet results = null;
    NodeRef testServer = null;
    try {
      // execute the query
      results =
          searchService.query(
              Repository.getStoreRef(), SearchService.LANGUAGE_LUCENE, query.toString());

      if (results.length() > 0) {
        for (int i = 0; i < results.length(); i++) {
          serverList.add(results.getNodeRef(i));
        }
      }
    } finally {
      if (results != null) {
        results.close();
      }
    }

    return serverList;
  }
Example #7
0
  private NodeRef getEmailTemplateNodeRef() {
    List<NodeRef> nodeRefs =
        searchService.selectNodes(
            repository.getRootHome(),
            "app:company_home/app:dictionary/app:email_templates/cm:invite/cm:invite-email.html.ftl",
            null,
            this.namespaceService,
            false);

    if (nodeRefs.size() == 1) {
      // Now localise this
      NodeRef base = nodeRefs.get(0);
      NodeRef local = fileFolderService.getLocalizedSibling(base);
      return local;
    } else {
      throw new InvitationException("Cannot find the email template!");
    }
  }
  protected NodeRef getTemplateNode(RenderingContext context) {
    NodeRef node = context.getCheckedParam(PARAM_TEMPLATE_NODE, NodeRef.class);
    if (node == null) {
      String path = context.getCheckedParam(PARAM_TEMPLATE_PATH, String.class);
      if (path != null && path.length() > 0) {
        StoreRef storeRef = context.getDestinationNode().getStoreRef();
        ResultSet result = null;

        try {
          result = searchService.query(storeRef, SearchService.LANGUAGE_XPATH, path);
          if (result.length() != 1) {
            throw new RenditionServiceException("Could not find template node for path: " + path);
          }
          node = result.getNodeRef(0);
        } finally {
          if (result != null) {
            result.close();
          }
        }
      }
    }
    return node;
  }
  /**
   * Test attachment extraction with a TNEF message
   *
   * @throws Exception
   */
  public void testAttachmentExtraction() throws Exception {
    AuthenticationUtil.setRunAsUserSystem();
    /** Load a TNEF message */
    ClassPathResource fileResource = new ClassPathResource("imap/test-tnef-message.eml");
    assertNotNull("unable to find test resource test-tnef-message.eml", fileResource);
    InputStream is = new FileInputStream(fileResource.getFile());
    MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()), is);

    /** Create a test node containing the message */
    String storePath = "workspace://SpacesStore";
    String companyHomePathInStore = "/app:company_home";
    StoreRef storeRef = new StoreRef(storePath);
    NodeRef storeRootNodeRef = nodeService.getRootNode(storeRef);

    List<NodeRef> nodeRefs =
        searchService.selectNodes(
            storeRootNodeRef, companyHomePathInStore, null, namespaceService, false);
    NodeRef companyHomeNodeRef = nodeRefs.get(0);

    FileInfo f1 =
        fileFolderService.create(
            companyHomeNodeRef, "ImapServiceImplTest", ContentModel.TYPE_FOLDER);
    FileInfo d2 =
        fileFolderService.create(f1.getNodeRef(), "ImapServiceImplTest", ContentModel.TYPE_FOLDER);
    FileInfo f2 =
        fileFolderService.create(
            f1.getNodeRef(), "test-tnef-message.eml", ContentModel.TYPE_CONTENT);

    ContentWriter writer = fileFolderService.getWriter(f2.getNodeRef());
    writer.putContent(new FileInputStream(fileResource.getFile()));

    NodeRef folder = imapService.extractAttachments(f1.getNodeRef(), f2.getNodeRef(), message);
    assertNotNull(folder);

    List<FileInfo> files = fileFolderService.listFiles(folder);
    assertTrue("three files not found", files.size() == 3);
  }
  /**
   * Get the value of the counter.
   *
   * @param parameters
   * @return
   * @throws Exception
   */
  private String getCounter(Map<String, Object> parameters) throws Exception {

    String counter = "0";

    switch ((String) parameters.get(PARAMETER_COUNTER)) {
      case PARAMETER_COUNTER_AUDIT_TRAIL:
      case PARAMETER_COUNTER_WORKFLOW_INSTANCES:
      case PARAMETER_COUNTER_WORKFLOW_TASKS:

        /*
         * TODO: The query should be defined using hibernate.
         */

        Class.forName(properties.getProperty(DB_DRIVER));

        java.sql.Connection dbConnection =
            DriverManager.getConnection(
                properties.getProperty(DB_URL),
                properties.getProperty(DB_USERNAME),
                properties.getProperty(DB_PASSWORD));
        Statement dbStatement = dbConnection.createStatement();
        String dbQuery = getDatabaseQuery(parameters);
        java.sql.ResultSet dbResultSet = dbStatement.executeQuery(dbQuery);

        if (dbResultSet.next()) {
          counter = String.valueOf(dbResultSet.getDouble(VALUE_FIELD));
        }

        if (dbResultSet.next()) {
          throw new Exception(
              "Database query '" + dbQuery + "' with multiple results when only one is expected.");
        }

        if (dbStatement != null) dbStatement.close();
        if (dbConnection != null) dbConnection.close();

        break;

      case PARAMETER_COUNTER_ASPECTS:
      case PARAMETER_COUNTER_TYPES:
        SearchParameters searchParameters = new SearchParameters();

        searchParameters.addStore(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);
        searchParameters.setLanguage(SearchService.LANGUAGE_FTS_ALFRESCO);
        searchParameters.setPermissionEvaluation(PermissionEvaluationMode.NONE);
        searchParameters.setUseInMemorySort(false);
        searchParameters.setLimitBy(LimitBy.FINAL_SIZE);

        List<String> alfrescoQueries = getAlfrescoQueries(parameters);
        int sum = 0;
        for (int i = 0; i < alfrescoQueries.size(); ++i) {

          searchParameters.setQuery(alfrescoQueries.get(i));

          org.alfresco.service.cmr.search.ResultSet resultSet =
              searchService.query(searchParameters);
          sum += resultSet.getNumberFound();
          resultSet.close();
        }

        counter = String.valueOf(sum);

        break;

      default:
        throw new Exception(
            "Parameter '"
                + PARAMETER_COUNTER
                + "' with value '"
                + ((String) parameters.get(PARAMETER_COUNTER))
                + "' not admitted.");
    }

    return counter;
  }
Example #11
0
  @Override
  public void setUp() throws Exception {
    ServiceRegistry serviceRegistry = (ServiceRegistry) ctx.getBean("ServiceRegistry");
    authenticationService = serviceRegistry.getAuthenticationService();
    imapService = serviceRegistry.getImapService();
    importerService = serviceRegistry.getImporterService();
    NodeService nodeService = serviceRegistry.getNodeService();
    SearchService searchService = serviceRegistry.getSearchService();
    NamespaceService namespaceService = serviceRegistry.getNamespaceService();
    PersonService personService = serviceRegistry.getPersonService();
    FileFolderService fileFolderService = serviceRegistry.getFileFolderService();
    TransactionService transactionService = serviceRegistry.getTransactionService();
    PermissionService permissionService = serviceRegistry.getPermissionService();

    // start the transaction
    UserTransaction txn = transactionService.getUserTransaction();
    txn.begin();

    authenticationService.authenticate(USER_NAME, USER_PASSWORD.toCharArray());

    anotherUserName = "******";

    NodeRef person = personService.getPerson(anotherUserName);

    if (person != null) {
      personService.deletePerson(anotherUserName);
      PropertyMap testUser = new PropertyMap();
      testUser.put(ContentModel.PROP_USERNAME, anotherUserName);
      testUser.put(ContentModel.PROP_FIRSTNAME, anotherUserName);
      testUser.put(ContentModel.PROP_LASTNAME, anotherUserName);
      testUser.put(ContentModel.PROP_EMAIL, anotherUserName + "@alfresco.com");
      testUser.put(ContentModel.PROP_JOBTITLE, "jobTitle");
      personService.createPerson(testUser);
    }
    if (authenticationService.authenticationExists(anotherUserName)) {
      authenticationService.deleteAuthentication(anotherUserName);
    }
    authenticationService.createAuthentication(anotherUserName, anotherUserName.toCharArray());

    user =
        new AlfrescoImapUser(anotherUserName + "@alfresco.com", anotherUserName, anotherUserName);

    String storePath = "workspace://SpacesStore";
    String companyHomePathInStore = "/app:company_home";

    StoreRef storeRef = new StoreRef(storePath);
    NodeRef storeRootNodeRef = nodeService.getRootNode(storeRef);

    List<NodeRef> nodeRefs =
        searchService.selectNodes(
            storeRootNodeRef, companyHomePathInStore, null, namespaceService, false);
    NodeRef companyHomeNodeRef = nodeRefs.get(0);

    ChildApplicationContextFactory imap = (ChildApplicationContextFactory) ctx.getBean("imap");
    ApplicationContext imapCtx = imap.getApplicationContext();
    ImapServiceImpl imapServiceImpl = (ImapServiceImpl) imapCtx.getBean("imapService");

    // Delete test folder
    nodeRefs =
        searchService.selectNodes(
            storeRootNodeRef,
            companyHomePathInStore
                + "/"
                + NamespaceService.CONTENT_MODEL_PREFIX
                + ":"
                + TEST_IMAP_ROOT_FOLDER_NAME,
            null,
            namespaceService,
            false);
    if (nodeRefs.size() == 1) {
      NodeRef ch = nodeRefs.get(0);
      nodeService.deleteNode(ch);
    }

    // Creating IMAP test folder for IMAP root
    LinkedList<String> folders = new LinkedList<String>();
    folders.add(TEST_IMAP_ROOT_FOLDER_NAME);
    FileFolderServiceImpl.makeFolders(
        fileFolderService, companyHomeNodeRef, folders, ContentModel.TYPE_FOLDER);

    // Setting IMAP root
    RepositoryFolderConfigBean imapHome = new RepositoryFolderConfigBean();
    imapHome.setStore(storePath);
    imapHome.setRootPath(companyHomePathInStore);
    imapHome.setFolderPath(TEST_IMAP_ROOT_FOLDER_NAME);
    imapServiceImpl.setImapHome(imapHome);

    // Starting IMAP
    imapServiceImpl.startupInTxn(true);

    nodeRefs =
        searchService.selectNodes(
            storeRootNodeRef,
            companyHomePathInStore
                + "/"
                + NamespaceService.CONTENT_MODEL_PREFIX
                + ":"
                + TEST_IMAP_ROOT_FOLDER_NAME,
            null,
            namespaceService,
            false);

    // Used to create User's folder
    NodeRef userFolderRef = imapService.getUserImapHomeRef(anotherUserName);
    permissionService.setPermission(
        userFolderRef, anotherUserName, PermissionService.ALL_PERMISSIONS, true);

    importTestData("imap/load_test_data.acp", userFolderRef);

    reauthenticate(anotherUserName, anotherUserName);

    AlfrescoImapFolder testDataFolder =
        imapService.getOrCreateMailbox(user, TEST_DATA_FOLDER_NAME, true, false);

    SimpleStoredMessage m = testDataFolder.getMessages().get(0);
    m = testDataFolder.getMessage(m.getUid());

    AlfrescoImapFolder folder = imapService.getOrCreateMailbox(user, TEST_FOLDER_NAME, false, true);

    logger.info("Creating folders...");
    long t = System.currentTimeMillis();

    try {
      for (int i = 0; i < MESSAGE_QUANTITY; i++) {
        System.out.println("i = " + i);
        folder.appendMessage(m.getMimeMessage(), new Flags(), new Date());
      }
    } catch (Exception e) {
      logger.error(e, e);
    }

    t = System.currentTimeMillis() - t;
    logger.info("Create time: " + t + " ms (" + t / 1000 + " s (" + t / 60000 + " min))");

    txn.commit();
  }
  @Override
  public void setUp() throws Exception {
    ServiceRegistry serviceRegistry = (ServiceRegistry) ctx.getBean("ServiceRegistry");
    transactionService = serviceRegistry.getTransactionService();
    nodeService = serviceRegistry.getNodeService();
    importerService = serviceRegistry.getImporterService();
    personService = serviceRegistry.getPersonService();
    authenticationService = serviceRegistry.getAuthenticationService();
    permissionService = serviceRegistry.getPermissionService();
    imapService = serviceRegistry.getImapService();
    searchService = serviceRegistry.getSearchService();
    namespaceService = serviceRegistry.getNamespaceService();
    fileFolderService = serviceRegistry.getFileFolderService();

    flags = new Flags();
    flags.add(Flags.Flag.SEEN);
    flags.add(Flags.Flag.FLAGGED);
    flags.add(Flags.Flag.ANSWERED);
    flags.add(Flags.Flag.DELETED);

    // start the transaction
    txn = transactionService.getUserTransaction();
    txn.begin();
    authenticationService.authenticate(USER_NAME, USER_PASSWORD.toCharArray());

    // downgrade integrity
    IntegrityChecker.setWarnInTransaction();

    anotherUserName = "******" + System.currentTimeMillis();

    PropertyMap testUser = new PropertyMap();
    testUser.put(ContentModel.PROP_USERNAME, anotherUserName);
    testUser.put(ContentModel.PROP_FIRSTNAME, anotherUserName);
    testUser.put(ContentModel.PROP_LASTNAME, anotherUserName);
    testUser.put(ContentModel.PROP_EMAIL, anotherUserName + "@alfresco.com");
    testUser.put(ContentModel.PROP_JOBTITLE, "jobTitle");

    personService.createPerson(testUser);

    // create the ACEGI Authentication instance for the new user
    authenticationService.createAuthentication(anotherUserName, anotherUserName.toCharArray());

    user =
        new AlfrescoImapUser(anotherUserName + "@alfresco.com", anotherUserName, anotherUserName);

    String storePath = "workspace://SpacesStore";
    String companyHomePathInStore = "/app:company_home";

    StoreRef storeRef = new StoreRef(storePath);

    NodeRef storeRootNodeRef = nodeService.getRootNode(storeRef);

    List<NodeRef> nodeRefs =
        searchService.selectNodes(
            storeRootNodeRef, companyHomePathInStore, null, namespaceService, false);
    NodeRef companyHomeNodeRef = nodeRefs.get(0);

    ChildApplicationContextFactory imap = (ChildApplicationContextFactory) ctx.getBean("imap");
    ApplicationContext imapCtx = imap.getApplicationContext();
    ImapServiceImpl imapServiceImpl = (ImapServiceImpl) imapCtx.getBean("imapService");

    // Creating IMAP test folder for IMAP root
    LinkedList<String> folders = new LinkedList<String>();
    folders.add(TEST_IMAP_FOLDER_NAME);
    FileFolderServiceImpl.makeFolders(
        fileFolderService, companyHomeNodeRef, folders, ContentModel.TYPE_FOLDER);

    // Setting IMAP root
    RepositoryFolderConfigBean imapHome = new RepositoryFolderConfigBean();
    imapHome.setStore(storePath);
    imapHome.setRootPath(companyHomePathInStore);
    imapHome.setFolderPath(TEST_IMAP_FOLDER_NAME);
    imapServiceImpl.setImapHome(imapHome);

    // Starting IMAP
    imapServiceImpl.startup();

    nodeRefs =
        searchService.selectNodes(
            storeRootNodeRef,
            companyHomePathInStore
                + "/"
                + NamespaceService.CONTENT_MODEL_PREFIX
                + ":"
                + TEST_IMAP_FOLDER_NAME,
            null,
            namespaceService,
            false);
    testImapFolderNodeRef = nodeRefs.get(0);

    /*
     * Importing test folders:
     *
     * Test folder contains: "___-___folder_a"
     *
     * "___-___folder_a" contains: "___-___folder_a_a",
     *                             "___-___file_a",
     *                             "Message_485.eml" (this is IMAP Message)
     *
     * "___-___folder_a_a" contains: "____-____file_a_a"
     *
     */
    importInternal("imap/imapservice_test_folder_a.acp", testImapFolderNodeRef);

    reauthenticate(anotherUserName, anotherUserName);
  }
Example #13
0
  /**
   * 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;
  }
Example #14
0
  /**
   * 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;
  }
  /** This is where the action is. */
  @Override
  protected void executeImpl(Action action, NodeRef someRef) {

    if (logger.isDebugEnabled()) logger.debug("enter executeImpl");

    // ReportingRoot reportingRoot = new ReportingRoot(someRef);
    // reportingHelper.initializeReportingRoot(reportingRoot);

    // get the frequency value (hourly, daily, weekly, monthly)
    String executionFrequency = (String) action.getParameterValue(EXECUTION_FREQUENCY);

    if (executionFrequency == null) executionFrequency = "hourly";

    // build a query to find all reportingContainer folders
    // having the executionFrequency, AND executionEnabled
    String query =
        "+@reporting\\:executionFrequency:\""
            + executionFrequency
            + "\" "
            + "+@reporting\\:executionEnabled:true";
    if (logger.isDebugEnabled()) logger.debug("executeImpl query=" + query);

    // build the query and execute. Find all relevant reportingContainers

    ResultSet results =
        searchService.query(
            StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, Constants.QUERYLANGUAGE, query);

    // cycle the resultset
    for (ResultSetRow resultRow : results) {
      NodeRef containerRef = resultRow.getChildAssocRef().getChildRef();

      ReportingContainer reportingContainer = new ReportingContainer(containerRef);
      reportingHelper.initializeReportingContainer(reportingContainer);

      logger.debug("Found container: " + reportingContainer.getName());

      // get its related ReportingRoot
      ReportingRoot reportingRoot =
          new ReportingRoot(reportingHelper.getReportingRoot(containerRef));
      reportingHelper.initializeReportingRoot(reportingRoot);

      // determine if execution of this container is allowed considering
      // the parent ReportingRoot
      if (reportingRoot.isGlobalExecutionEnabled()) {

        // Start a reportingContainerExecuter for the given noderef.
        // Pass the NodeRef of the ReportingRoot since we know who that is.
        Action customAction = actionService.createAction(ReportContainerExecutor.NAME);
        // action.setParameterValue(
        //		ReportContainerExecutor.REPORTING_CONTAINER_NODEREF, containerRef);

        actionService.executeAction(customAction, containerRef);
      } // end if reportingExecturinEnabled()
      {
        logger.warn(
            "Container execution of "
                + reportingContainer.getName()
                + " veto'd by ReportingRoot "
                + reportingRoot.getName());
      }
    } // end for ResultSetRow

    if (logger.isDebugEnabled()) logger.debug("exit executeImpl");
  }