/** {@inheritDoc} */
  public void start() {
    configuredTemplates_ = new HashMap<String, Set<String>>();
    RepositoryEntry repositoryEntry = null;
    try {
      repositoryEntry = repositoryService.getCurrentRepository().getConfiguration();
    } catch (RepositoryException e) {
      if (LOG.isErrorEnabled()) {
        LOG.error(e.getMessage(), e);
      }
    }

    String repoName = repositoryEntry.getName();
    String workspaceName = repositoryEntry.getSystemWorkspaceName();
    storedWorkspaces.put(repoName, workspaceName);
    basedApplicationTemplatesPath = hierarchyCreator.getJcrPath(BasePath.CMS_VIEWTEMPLATES_PATH);

    SessionProvider sessionProvider = SessionProvider.createSystemProvider();
    for (Iterator<String> repositories = storedWorkspaces.keySet().iterator();
        repositories.hasNext(); ) {
      String repository = repositories.next();
      try {
        Node storedTemplateHome = getBasedApplicationTemplatesHome(sessionProvider);
        importPredefinedTemplateToDB(storedTemplateHome);
      } catch (Exception e) {
        if (LOG.isErrorEnabled()) {
          LOG.error(
              "Exception when import predefine application template into repository: " + repository,
              e);
        }
      }
    }
    sessionProvider.close();
  }
 /**
  * This method will re-observer all nodes that have been ever observed with all repositories.
  *
  * @throws Exception
  */
 private void reInitObserver() throws Exception {
   RepositoryEntry repo = repoService_.getCurrentRepository().getConfiguration();
   ManageableRepository repository = repoService_.getCurrentRepository();
   String[] workspaceNames = repository.getWorkspaceNames();
   for (String workspace : workspaceNames) {
     Session session = repository.getSystemSession(workspace);
     QueryManager queryManager = null;
     try {
       queryManager = session.getWorkspace().getQueryManager();
     } catch (Exception e) {
       if (LOG.isErrorEnabled()) {
         LOG.error("Unexpected error", e);
       }
     }
     if (queryManager == null) {
       session.logout();
       continue;
     }
     try {
       Query query = queryManager.createQuery(WATCHABLE_MIXIN_QUERY, Query.XPATH);
       QueryResult queryResult = query.execute();
       for (NodeIterator iter = queryResult.getNodes(); iter.hasNext(); ) {
         Node observedNode = iter.nextNode();
         EmailNotifyListener emailNotifyListener = new EmailNotifyListener(observedNode);
         ObservationManager manager = session.getWorkspace().getObservationManager();
         List<String> list = getDocumentNodeTypes(observedNode);
         String[] observedNodeTypeNames = list.toArray(new String[list.size()]);
         manager.addEventListener(
             emailNotifyListener,
             Event.PROPERTY_CHANGED,
             observedNode.getPath(),
             true,
             null,
             observedNodeTypeNames,
             false);
       }
       session.logout();
     } catch (Exception e) {
       if (LOG.isWarnEnabled()) {
         LOG.warn(
             "==>>> Cannot init observer for node: "
                 + e.getLocalizedMessage()
                 + " in '"
                 + repo.getName()
                 + "' repository");
       }
       if (LOG.isErrorEnabled()) {
         LOG.error("Unexpected error", e);
       }
     }
   }
 }
 public void updateFolderAllowed(String path) {
   UIFormSelectBox sltWorkspace = getChildById(UIDriveInputSet.FIELD_WORKSPACE);
   String strWorkspace = sltWorkspace.getSelectedValues()[0];
   SessionProvider sessionProvider = WCMCoreUtils.getSystemSessionProvider();
   try {
     Session session =
         sessionProvider.getSession(
             strWorkspace,
             getApplicationComponent(RepositoryService.class).getCurrentRepository());
     Node rootNode = (Node) session.getItem(path);
     List<SelectItemOption<String>> foldertypeOptions = new ArrayList<SelectItemOption<String>>();
     RequestContext context = RequestContext.getCurrentInstance();
     ResourceBundle res = context.getApplicationResourceBundle();
     for (String foldertype : setFoldertypes) {
       if (isChildNodePrimaryTypeAllowed(rootNode, foldertype)) {
         try {
           foldertypeOptions.add(
               new SelectItemOption<String>(
                   res.getString(getId() + ".label." + foldertype.replace(":", "_")), foldertype));
         } catch (MissingResourceException mre) {
           foldertypeOptions.add(new SelectItemOption<String>(foldertype, foldertype));
         }
       }
     }
     Collections.sort(foldertypeOptions, new ItemOptionNameComparator());
     getUIFormSelectBox(FIELD_ALLOW_CREATE_FOLDERS).setOptions(foldertypeOptions);
   } catch (Exception e) {
     if (LOG.isErrorEnabled()) {
       LOG.error("Unexpected problem occurs while updating", e);
     }
   }
 }
 public void activate() {
   try {
     getChild(UIPermissionInfoBase.class).updateGrid(1);
   } catch (Exception e) {
     if (LOG.isErrorEnabled()) {
       LOG.error("Unexpected error!", e.getMessage());
     }
   }
 }
  private List<Node> getLastEditedNode(String noOfItem, String showGadgetWs) throws Exception {
    if (showGadgetWs != null && showGadgetWs.length() > 0) {
      show_gadget = Boolean.parseBoolean(showGadgetWs);
    }
    ArrayList<Node> lstNode = new ArrayList<Node>();
    StringBuffer bf = new StringBuffer(1024);
    List<String> lstNodeType = templateService.getDocumentTemplates();
    if (lstNodeType != null) {
      for (String nodeType : lstNodeType) {
        bf.append("(")
            .append(JCR_PRIMARYTYPE)
            .append("=")
            .append("'")
            .append(nodeType)
            .append("'")
            .append(")")
            .append(" OR ");
      }
    }

    if (bf.length() == 1) return null;
    bf.delete(bf.lastIndexOf("OR") - 1, bf.length());
    if (noOfItem == null || noOfItem.trim().length() == 0) noOfItem = String.valueOf(NO_PER_PAGE);
    String queryStatement = StringUtils.replace(QUERY_STATEMENT, "$0", NT_BASE);
    queryStatement = StringUtils.replace(queryStatement, "$1", bf.toString());
    queryStatement = StringUtils.replace(queryStatement, "$2", DATE_MODIFIED);
    ManageableRepository manageableRepository = repositoryService.getCurrentRepository();
    try {
      String[] workspaces = manageableRepository.getWorkspaceNames();
      List<String> lstWorkspace = new ArrayList<String>();
      // Arrays.asList() return fixed size list;
      lstWorkspace.addAll(Arrays.asList(workspaces));
      if (!show_gadget && lstWorkspace.contains(GADGET)) {
        lstWorkspace.remove(GADGET);
      }
      SessionProvider provider = WCMCoreUtils.createAnonimProvider();
      QueryImpl query = null;
      Session session = null;
      QueryResult queryResult = null;
      QueryManager queryManager = null;
      for (String workspace : lstWorkspace) {
        session = provider.getSession(workspace, manageableRepository);
        queryManager = session.getWorkspace().getQueryManager();
        query = (QueryImpl) queryManager.createQuery(queryStatement, Query.SQL);
        query.setLimit(Integer.parseInt(noOfItem));
        query.setOffset(0);
        queryResult = query.execute();
        puttoList(lstNode, queryResult.getNodes());
        session.logout();
      }
    } catch (RepositoryException e) {
      if (LOG.isErrorEnabled()) {
        LOG.error("Exception when execute SQL " + queryStatement, e);
      }
    }
    return lstNode;
  }
Exemple #6
0
 /**
  * Get the current repository
  *
  * @return the current manageable repository
  */
 public static ManageableRepository getRepository() {
   try {
     RepositoryService repositoryService = getService(RepositoryService.class);
     return repositoryService.getCurrentRepository();
   } catch (Exception e) {
     if (LOG.isErrorEnabled()) {
       LOG.error("getRepository() failed because of ", e);
     }
   }
   return null;
 }
Exemple #7
0
 String displayCategory(Node node, List<Node> taxonomyTrees) {
   try {
     for (Node taxonomyTree : taxonomyTrees) {
       if (node.getPath().contains(taxonomyTree.getPath())) {
         return node.getPath().replace(taxonomyTree.getPath(), taxonomyTree.getName());
       }
     }
   } catch (RepositoryException e) {
     if (LOG.isErrorEnabled()) LOG.error("Unexpected error when getting node taxonomies");
   }
   return "";
 }
 /* (non-Javadoc)
  * @see org.exoplatform.services.wcm.link.LiveLinkManagerService#validateLink(java.lang.String)
  */
 public void updateLinks(String portalName) throws Exception {
   try {
     SessionProvider sessionProvider = WCMCoreUtils.getSystemSessionProvider();
     Node portal = livePortalManagerService.getLivePortal(sessionProvider, portalName);
     String path = portal.getPath();
     Session session = portal.getSession();
     updateLinkStatus(session, "select * from exo:linkable where jcr:path like '" + path + "/%'");
   } catch (Exception e) {
     if (LOG.isErrorEnabled()) {
       LOG.error("Error when perform updateLinks: ", e);
     }
   }
 }
Exemple #9
0
 private void updateSymlinkByQuery(
     String workspace, String statement, SessionProvider sessionProvider) {
   try {
     ManageableRepository manageableRepository = repositoryService.getCurrentRepository();
     Session session = sessionProvider.getSession(workspace, manageableRepository);
     QueryManager manager = session.getWorkspace().getQueryManager();
     NodeIterator iter = manager.createQuery(statement, Query.SQL).execute().getNodes();
     while (iter.hasNext()) {
       try {
         Node currentNode = iter.nextNode();
         linkManager.updateSymlink(currentNode);
       } catch (Exception ex) {
         if (LOG.isErrorEnabled()) {
           LOG.error("Can not update symlink data", ex);
         }
       }
     }
   } catch (RepositoryException e) {
     if (LOG.isErrorEnabled()) {
       LOG.error("Can not update symlinks data", e);
     }
   }
 }
Exemple #10
0
 public static List<String> getListAllowedFileType(
     Node currentNode, TemplateService templateService) throws Exception {
   List<String> nodeTypes = new ArrayList<String>();
   NodeTypeManager ntManager = currentNode.getSession().getWorkspace().getNodeTypeManager();
   NodeType currentNodeType = currentNode.getPrimaryNodeType();
   NodeDefinition[] childDefs = currentNodeType.getChildNodeDefinitions();
   List<String> templates = templateService.getDocumentTemplates();
   try {
     for (int i = 0; i < templates.size(); i++) {
       String nodeTypeName = templates.get(i).toString();
       NodeType nodeType = ntManager.getNodeType(nodeTypeName);
       NodeType[] superTypes = nodeType.getSupertypes();
       boolean isCanCreateDocument = false;
       for (NodeDefinition childDef : childDefs) {
         NodeType[] requiredChilds = childDef.getRequiredPrimaryTypes();
         for (NodeType requiredChild : requiredChilds) {
           if (nodeTypeName.equals(requiredChild.getName())) {
             isCanCreateDocument = true;
             break;
           }
         }
         if (nodeTypeName.equals(childDef.getName()) || isCanCreateDocument) {
           if (!nodeTypes.contains(nodeTypeName)) nodeTypes.add(nodeTypeName);
           isCanCreateDocument = true;
         }
       }
       if (!isCanCreateDocument) {
         for (NodeType superType : superTypes) {
           for (NodeDefinition childDef : childDefs) {
             for (NodeType requiredType : childDef.getRequiredPrimaryTypes()) {
               if (superType.getName().equals(requiredType.getName())) {
                 if (!nodeTypes.contains(nodeTypeName)) nodeTypes.add(nodeTypeName);
                 isCanCreateDocument = true;
                 break;
               }
             }
             if (isCanCreateDocument) break;
           }
           if (isCanCreateDocument) break;
         }
       }
     }
   } catch (Exception e) {
     if (LOG.isErrorEnabled()) {
       LOG.error("Unexpected error", e);
     }
   }
   return nodeTypes;
 }
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    SettingService settingService =
        PortalContainer.getInstance().getComponentInstanceOfType(SettingService.class);
    SoftwareRegistrationService softwareRegistrationService =
        PortalContainer.getInstance().getComponentInstanceOfType(SoftwareRegistrationService.class);

    if (softwareRegistrationService.isSoftwareRegistered()) {
      response.sendRedirect("/");
      return;
    }
    String code = request.getParameter("code");
    if (StringUtils.isEmpty(code)) {
      try {
        getServletContext().getRequestDispatcher(SR_JSP_RESOURCE).forward(request, response);
      } catch (Exception se) {
        if (LOG.isErrorEnabled()) {
          LOG.error(se);
        }
        response.sendRedirect("/");
      }
      return;
    }

    SoftwareRegistration softwareRegistration =
        softwareRegistrationService.registrationPLF(code, getRegistrationURL(request));
    if (softwareRegistration.isPushInfo()) {
      settingService.set(
          Context.GLOBAL,
          Scope.GLOBAL,
          SoftwareRegistrationService.SOFTWARE_REGISTRATION_NODE,
          SettingValue.create("Software registered:" + "true"));
      softwareRegistrationService.checkSoftwareRegistration();
      getServletContext().setAttribute("status", "success");
    } else if (softwareRegistration.isNotReachable()) {
      request.getSession().setAttribute("notReachable", "true");
      getServletContext().getRequestDispatcher(SR_JSP_RESOURCE).forward(request, response);
      return;
    } else {
      getServletContext().setAttribute("status", "failed");
      request.getSession().setAttribute("notReachable", "true");
      response.sendRedirect("/");
      return;
    }
    getServletContext().getRequestDispatcher(SR_JSP_RESOURCE_SUCCESS).forward(request, response);
    return;
  }
Exemple #12
0
 /**
  * Get folders and files.
  *
  * @param currentFolder The current folder.
  * @param lang The language.
  * @param host The server address on which the gadget is deployed.
  * @return The folders and files.
  * @throws Exception The exception
  * @anchor GadgetConnector.getFoldersAndFiles
  */
 @GET
 @Path("/getFoldersAndFiles/")
 public Response getFoldersAndFiles(
     @QueryParam("currentFolder") String currentFolder,
     @QueryParam("lang") String lang,
     @QueryParam("host") String host)
     throws Exception {
   try {
     Response response = buildXMLResponse(currentFolder, lang, host);
     if (response != null) return response;
   } catch (Exception e) {
     if (LOG.isErrorEnabled()) {
       LOG.error("Error when perform getFoldersAndFiles: ", e);
     }
   }
   DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT);
   return Response.ok().header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())).build();
 }
Exemple #13
0
 /**
  * Update all document nodetypes and write a query statement
  *
  * @return a part of the query allow search all document node and taxonomy link also. Return null
  *     if there is any exception.
  */
 public String updateTemplatesSQLFilter() {
   try {
     List<String> documentTypes = templateService.getDocumentTemplates();
     StringBuffer documentTypeClause = new StringBuffer("(");
     for (int i = 0; i < documentTypes.size(); i++) {
       String documentType = documentTypes.get(i);
       documentTypeClause.append("jcr:primaryType = '" + documentType + "'");
       if (i != (documentTypes.size() - 1)) documentTypeClause.append(" OR ");
     }
     templatesFilter = documentTypeClause.toString();
     templatesFilter +=
         " OR jcr:primaryType = 'exo:taxonomyLink' OR jcr:primaryType = 'exo:symlink')";
     return templatesFilter;
   } catch (Exception e) {
     if (LOG.isErrorEnabled()) {
       LOG.error("Error when perform getTemlatesSQLFilter: ", e);
     }
     return null;
   }
 }
 /* (non-Javadoc)
  * @see org.exoplatform.services.wcm.link.LiveLinkManagerService#validateLink()
  */
 public void updateLinks() throws Exception {
   try {
     Collection<NodeLocation> nodeLocationCollection =
         configurationService.getAllLivePortalsLocation();
     SessionProvider sessionProvider = WCMCoreUtils.getSystemSessionProvider();
     Session session = null;
     for (NodeLocation nodeLocation : nodeLocationCollection) {
       String workspace = nodeLocation.getWorkspace();
       String path = nodeLocation.getPath();
       ManageableRepository manageableRepository = repositoryService.getCurrentRepository();
       session = sessionProvider.getSession(workspace, manageableRepository);
       updateLinkStatus(
           session, "select * from exo:linkable where jcr:path like '" + path + "/%'");
     }
   } catch (Exception e) {
     if (LOG.isErrorEnabled()) {
       LOG.error("Error when perform updateLinks: ", e);
     }
   }
 }
  public void start() {
    if (ProductVersions.getCurrentVersionAsInt() == ProductVersions.WCM_2_1_2_NUM) {
      SessionProvider sessionProvider = SessionProvider.createSystemProvider();
      try {
        ManageableRepository repository = repositoryService.getCurrentRepository();
        Session session = sessionProvider.getSession("dms-system", repository);
        Node rootNode = session.getRootNode();

        /** CHECK IF WE USE THE OLD STRUCTURE (PRE 2.1.2) OR IF IT'S A POST 2.1.2 WEBSITE */
        if (rootNode.hasNode("exo:ecm/views/templates/Content List Viewer")) {
          /** CREATE NEW STRUCTURE IF IT DOESN'T EXIST */
          if (!rootNode.hasNode("exo:ecm/views/templates/content-list-viewer")) {
            rootNode.addNode("exo:ecm/views/templates/content-list-viewer", "nt:unstructured");
            if (LOG.isInfoEnabled()) LOG.info("CREATE :: content-list-viewer");
            rootNode.save();
          }
          if (!rootNode.hasNode("exo:ecm/views/templates/content-list-viewer/paginators")) {
            rootNode.addNode(
                "exo:ecm/views/templates/content-list-viewer/paginators", "nt:unstructured");
            if (LOG.isInfoEnabled()) LOG.info("CREATE :: paginators");
            rootNode.save();
          }
          if (!rootNode.hasNode("exo:ecm/views/templates/content-list-viewer/list")) {
            rootNode.addNode("exo:ecm/views/templates/content-list-viewer/list", "nt:unstructured");
            if (LOG.isInfoEnabled()) LOG.info("CREATE :: list");
            rootNode.save();
          }
          if (!rootNode.hasNode("exo:ecm/views/templates/content-list-viewer/navigation")) {
            rootNode.addNode(
                "exo:ecm/views/templates/content-list-viewer/navigation", "nt:unstructured");
            if (LOG.isInfoEnabled()) LOG.info("CREATE :: navigation");
            rootNode.save();
          }

          /** CHECK IF PAGINATORS ARE IN THE NEW PLACE */
          Node oldPaginatorsNode =
              rootNode.getNode("exo:ecm/views/templates/Content List Viewer/paginators");
          Node newPaginatorsNode =
              rootNode.getNode("exo:ecm/views/templates/content-list-viewer/paginators");
          NodeIterator oldPaginatorsNodes = oldPaginatorsNode.getNodes();
          while (oldPaginatorsNodes.hasNext()) {
            Node paginatorNode = oldPaginatorsNodes.nextNode();
            if (!newPaginatorsNode.hasNode(paginatorNode.getName())) {
              /** NODE NOT MIGRATED, WE DO IT */
              session
                  .getWorkspace()
                  .copy(
                      "/exo:ecm/views/templates/Content List Viewer/paginators/"
                          + paginatorNode.getName(),
                      "/exo:ecm/views/templates/content-list-viewer/paginators/"
                          + paginatorNode.getName());
              if (LOG.isInfoEnabled()) LOG.info("CLONE :: " + paginatorNode.getName());
            }
          }
          session.save();
          /** CHECK IF VIEWS ARE IN THE NEW PLACE */
          Node oldViewNode =
              rootNode.getNode("exo:ecm/views/templates/Content List Viewer/list-by-folder");
          Node newViewListNode =
              rootNode.getNode("exo:ecm/views/templates/content-list-viewer/list");
          Node newViewNavNode =
              rootNode.getNode("exo:ecm/views/templates/content-list-viewer/navigation");
          NodeIterator oldViewNodes = oldViewNode.getNodes();
          while (oldViewNodes.hasNext()) {
            Node viewNode = oldViewNodes.nextNode();
            if (!newViewListNode.hasNode(viewNode.getName())
                && !newViewNavNode.hasNode(viewNode.getName())) {
              Node content = viewNode.getNode("jcr:content");
              InputStream data = content.getProperty("jcr:data").getStream();
              String sdata = inputStreamAsString(data);
              String targetFolder = "list";
              if (sdata.contains("public void renderCategories")) {
                targetFolder = "navigation";
              }

              /** NODE NOT MIGRATED, WE DO IT */
              session
                  .getWorkspace()
                  .copy(
                      "/exo:ecm/views/templates/Content List Viewer/list-by-folder/"
                          + viewNode.getName(),
                      "/exo:ecm/views/templates/content-list-viewer/"
                          + targetFolder
                          + "/"
                          + viewNode.getName());
              if (LOG.isInfoEnabled())
                LOG.info("CLONE :: " + targetFolder + " :: " + viewNode.getName());
            }
          }
          session.save();

          session.logout();

          /** UPDATE OLD PORTLET PREFERENCES */
          session = sessionProvider.getSession("portal-system", repository);
          QueryManager manager = session.getWorkspace().getQueryManager();
          String statement =
              "SELECT * from mop:portletpreference where mop:value LIKE '/exo:ecm/views/templates/Content List Viewer/%'";
          Query query = manager.createQuery(statement.toString(), Query.SQL);
          NodeIterator nodes = query.execute().getNodes();

          while (nodes.hasNext()) {
            Node node = (Node) nodes.next();
            String value = node.getProperty("mop:value").getValues()[0].getString();
            String newValue = MigrationUtil.checkAndUpdateViewerTemplate(value);
            if (!value.equals(newValue)) {
              if (LOG.isInfoEnabled())
                LOG.info(
                    "CONVERT :: mop:portletpreference :: "
                        + value
                        + " :: "
                        + newValue
                        + " :: "
                        + node.getPath());
              node.setProperty("mop:value", new String[] {newValue});
              node.save();
            }
          }

          if (LOG.isWarnEnabled()) {
            LOG.warn(
                "IMPORTANT NOTE ABOUT WCM 2.1.2 :\n"
                    + "All CLV templates have been copied to a new storage place. "
                    + "We keep your old templates in the old structure but they won't be used anymore.\n"
                    + "Storage place goes from dms-system:/exo:ecm/views/templates/Content List Viewer to "
                    + "dms-system:/exo:ecm/views/templates/content-list-viewer\n"
                    + "Please, read the WCM 2.1.2 Upgrade Notice or contact the eXo Support for more info.");
          }
        }

      } catch (Exception e) {
        if (LOG.isErrorEnabled())
          LOG.error("An unexpected problem occurs when migrating templates to new structure", e);
      } finally {
        sessionProvider.close();
      }
    }
  }
Exemple #16
0
  private static void processCut(
      String nodePath,
      Event<CutManageComponent> event,
      UIJCRExplorer uiExplorer,
      boolean isMultiSelect)
      throws Exception {
    UIWorkingArea uiWorkingArea = uiExplorer.getChild(UIWorkingArea.class);
    UIApplication uiApp = event.getSource().getAncestorOfType(UIApplication.class);
    Matcher matcher = UIWorkingArea.FILE_EXPLORER_URL_SYNTAX.matcher(nodePath);
    String wsName = null;
    if (matcher.find()) {
      wsName = matcher.group(1);
      nodePath = matcher.group(2);
    } else {
      throw new IllegalArgumentException("The ObjectId is invalid '" + nodePath + "'");
    }
    Session session = uiExplorer.getSessionByWorkspace(wsName);
    Node selectedNode;
    try {
      // Use the method getNodeByPath because it is link aware
      selectedNode = uiExplorer.getNodeByPath(nodePath, session, false);
      // Reset the path to manage the links that potentially create virtual path
      nodePath = selectedNode.getPath();
      // Reset the session to manage the links that potentially change of workspace
      session = selectedNode.getSession();
      // Reset the workspace name to manage the links that potentially change of workspace
      wsName = session.getWorkspace().getName();
    } catch (ConstraintViolationException cons) {
      uiExplorer.getSession().refresh(false);
      uiExplorer.refreshExplorer();
      uiApp.addMessage(
          new ApplicationMessage(
              "UIPopupMenu.msg.constraintviolation-exception", null, ApplicationMessage.WARNING));

      uiExplorer.updateAjax(event);
      return;
    } catch (PathNotFoundException path) {
      uiApp.addMessage(
          new ApplicationMessage(
              "UIPopupMenu.msg.path-not-found-exception", null, ApplicationMessage.WARNING));

      return;
    } catch (Exception e) {
      if (LOG.isErrorEnabled()) {
        LOG.error("an unexpected error occurs while cuting the node", e);
      }
      JCRExceptionManager.process(uiApp, e);
      return;
    }
    try {
      List<ClipboardCommand> clipboards = uiExplorer.getAllClipBoard();
      for (ClipboardCommand command : clipboards) {
        if (command.getSrcPath().equals(nodePath)) {
          clipboards.remove(command);
          break;
        }
      }
      ClipboardCommand clipboard = new ClipboardCommand();
      clipboard.setType(ClipboardCommand.CUT);
      clipboard.setSrcPath(nodePath);
      clipboard.setWorkspace(wsName);
      uiExplorer.getAllClipBoard().add(clipboard);
      if (isMultiSelect) {
        uiWorkingArea.getVirtualClipboards().add(clipboard);
      } else {
        session.save();
        uiExplorer.updateAjax(event);
      }
    } catch (Exception e) {
      JCRExceptionManager.process(uiApp, e);
    }
  }
Exemple #17
0
  public void execute(JobExecutionContext context) throws JobExecutionException {
    Session session = null;
    try {
      if (LOG.isInfoEnabled()) {
        LOG.info("Start Execute ImportXMLJob");
      }
      if (stagingStorage == null) {

        JobDataMap jdatamap = context.getJobDetail().getJobDataMap();
        stagingStorage = jdatamap.getString("stagingStorage");
        temporaryStorge = jdatamap.getString("temporaryStorge");
        if (LOG.isDebugEnabled()) {
          LOG.debug("Init parameters first time :");
        }
      }
      SessionProvider sessionProvider = SessionProvider.createSystemProvider();
      String containerName = WCMCoreUtils.getContainerNameFromJobContext(context);
      RepositoryService repositoryService_ =
          WCMCoreUtils.getService(RepositoryService.class, containerName);
      ManageableRepository manageableRepository = repositoryService_.getCurrentRepository();
      PublicationService publicationService =
          WCMCoreUtils.getService(PublicationService.class, containerName);
      PublicationPlugin publicationPlugin =
          publicationService
              .getPublicationPlugins()
              .get(AuthoringPublicationConstant.LIFECYCLE_NAME);
      XMLInputFactory factory = XMLInputFactory.newInstance();

      File stagingFolder = new File(stagingStorage);
      File tempfolder = new File(temporaryStorge);

      File[] files = null;
      File xmlFile = null;
      XMLStreamReader reader = null;
      InputStream xmlInputStream = null;
      int eventType;
      List<LinkObject> listLink = new ArrayList<LinkObject>();
      LinkObject linkObj = new LinkObject();
      boolean hasNewContent = false;
      if (stagingFolder.exists()) {
        files = stagingFolder.listFiles();
        if (files != null) {
          hasNewContent = true;
          for (int i = 0; i < files.length; i++) {
            xmlFile = files[i];
            if (xmlFile.isFile()) {
              MimeTypeResolver resolver = new MimeTypeResolver();
              String fileName = xmlFile.getName();
              String hashCode = fileName.split("-")[0];
              String mimeType = resolver.getMimeType(xmlFile.getName());
              if ("text/xml".equals(mimeType)) {
                xmlInputStream = new FileInputStream(xmlFile);
                reader = factory.createXMLStreamReader(xmlInputStream);
                while (reader.hasNext()) {
                  eventType = reader.next();
                  if (eventType == XMLEvent.START_ELEMENT && "data".equals(reader.getLocalName())) {
                    String data = reader.getElementText();

                    if (!tempfolder.exists()) tempfolder.mkdirs();
                    long time = System.currentTimeMillis();
                    File file =
                        new File(
                            temporaryStorge
                                + File.separator
                                + "-"
                                + hashCode
                                + "-"
                                + time
                                + ".xml.tmp");
                    InputStream inputStream = new ByteArrayInputStream(data.getBytes());
                    OutputStream out = new FileOutputStream(file);
                    byte[] buf = new byte[1024];
                    int len;
                    while ((len = inputStream.read(buf)) > 0) out.write(buf, 0, len);
                    out.close();
                    inputStream.close();
                  }
                  try {
                    if (eventType == XMLEvent.START_ELEMENT
                        && "published-content".equals(reader.getLocalName())) {
                      linkObj.setSourcePath(reader.getAttributeValue(0)); // --Attribute
                      // number
                      // 0 =
                      // targetPath
                    }
                    if (eventType == XMLEvent.START_ELEMENT
                        && "type".equals(reader.getLocalName())) {
                      linkObj.setLinkType(reader.getElementText());
                    }
                    if (eventType == XMLEvent.START_ELEMENT
                        && "title".equals(reader.getLocalName())) {
                      linkObj.setLinkTitle(reader.getElementText());
                    }
                    if (eventType == XMLEvent.START_ELEMENT
                        && "targetPath".equals(reader.getLocalName())) {
                      linkObj.setLinkTargetPath(reader.getElementText());
                      listLink.add(linkObj);
                    }

                    if (eventType == XMLEvent.START_ELEMENT
                        && "unpublished-content".equals(reader.getLocalName())) {

                      String contentTargetPath = reader.getAttributeValue(0);
                      String[] strContentPath = contentTargetPath.split(":");
                      StringBuffer sbContPath = new StringBuffer();
                      boolean flag = true;
                      for (int index = 2; index < strContentPath.length; index++) {
                        if (flag) {
                          sbContPath.append(strContentPath[index]);
                          flag = false;
                        } else {
                          sbContPath.append(":").append(strContentPath[index]);
                        }
                      }
                      sessionProvider = SessionProvider.createSystemProvider();

                      manageableRepository = repositoryService_.getCurrentRepository();
                      String workspace = strContentPath[1];
                      session = sessionProvider.getSession(workspace, manageableRepository);
                      String contentPath = sbContPath.toString();
                      if (session.itemExists(contentPath)) {
                        Node currentContent = (Node) session.getItem(contentPath);
                        HashMap<String, String> variables = new HashMap<String, String>();
                        variables.put("nodePath", contentTargetPath);
                        variables.put("workspaceName", workspace);
                        if (currentContent.hasProperty(
                                StageAndVersionPublicationConstant.PUBLICATION_LIFECYCLE_NAME)
                            && AuthoringPublicationConstant.LIFECYCLE_NAME.equals(
                                currentContent
                                    .getProperty(
                                        StageAndVersionPublicationConstant
                                            .PUBLICATION_LIFECYCLE_NAME)
                                    .getString())
                            && PublicationDefaultStates.PUBLISHED.equals(
                                currentContent
                                    .getProperty(StageAndVersionPublicationConstant.CURRENT_STATE)
                                    .getString())) {

                          publicationPlugin.changeState(
                              currentContent, PublicationDefaultStates.UNPUBLISHED, variables);
                          if (LOG.isInfoEnabled()) {
                            LOG.info(
                                "Change the status of the node "
                                    + currentContent.getPath()
                                    + " from "
                                    + PublicationDefaultStates.PUBLISHED
                                    + " to "
                                    + PublicationDefaultStates.UNPUBLISHED);
                          }
                        }
                      } else {
                        if (LOG.isWarnEnabled()) {
                          LOG.warn("The node " + contentPath + " does not exist");
                        }
                      }
                    }

                  } catch (Exception ie) {
                    if (LOG.isWarnEnabled()) {
                      LOG.warn("Error in ImportContentsJob: " + ie.getMessage());
                    }
                  }
                }
                reader.close();
                xmlInputStream.close();
                xmlFile.delete();
              }
            }
          }
        }
      }
      files = tempfolder.listFiles();
      if (files != null) {
        for (int i = 0; i < files.length; i++) {
          xmlFile = files[i];
          InputStream inputStream = new FileInputStream(xmlFile);
          reader = factory.createXMLStreamReader(inputStream);
          String workspace = null;
          String nodePath = new String();

          while (reader.hasNext()) {
            eventType = reader.next();
            if (eventType == XMLEvent.START_ELEMENT) {
              if (reader.getLocalName().equals("property")) {
                String value = reader.getAttributeValue(0);
                if (MIX_TARGET_PATH.equals(value)) {
                  eventType = reader.next();
                  if (eventType == XMLEvent.START_ELEMENT) {
                    reader.next();
                    nodePath = reader.getText();
                  }
                } else if (MIX_TARGET_WORKSPACE.equals(value)) {
                  eventType = reader.next();
                  if (eventType == XMLEvent.START_ELEMENT) {
                    reader.next();
                    workspace = reader.getText();
                  }
                }
              }
            }
          }
          reader.close();
          inputStream.close();
          session = sessionProvider.getSession(workspace, manageableRepository);
          if (session.itemExists(nodePath)) session.getItem(nodePath).remove();
          session.save();

          String path = nodePath.substring(0, nodePath.lastIndexOf(JCR_File_SEPARATOR));
          if (!session.itemExists(path)) {
            String[] pathTab = path.split(JCR_File_SEPARATOR);
            Node node_ = session.getRootNode();
            StringBuffer path_ = new StringBuffer(JCR_File_SEPARATOR);
            for (int j = 1; j < pathTab.length; j++) {
              path_ = path_.append(pathTab[j] + JCR_File_SEPARATOR);
              if (!session.itemExists(path_.toString())) {
                node_.addNode(pathTab[j], "nt:unstructured");
              }
              node_ = (Node) session.getItem(path_.toString());
            }
          }

          session.importXML(path, new FileInputStream(xmlFile), 0);
          session.save();
          xmlFile.delete();

          if (hasNewContent) {
            for (LinkObject obj : listLink) {
              String[] linkTarget = obj.getLinkTargetPath().split(":");
              StringBuffer itemPath = new StringBuffer();
              boolean flag = true;
              for (int index = 2; index < linkTarget.length; index++) {
                if (flag) {
                  itemPath.append(linkTarget[index]);
                  flag = false;
                } else {
                  itemPath.append(":");
                  itemPath.append(linkTarget[index]);
                }
              }
              String[] linkSource = obj.getSourcePath().split(":");
              session = sessionProvider.getSession(linkTarget[1], manageableRepository);
              Node parentNode = (Node) session.getItem(itemPath.toString());

              StringBuffer sourcePath = new StringBuffer();
              boolean flagSource = true;
              for (int index = 2; index < linkSource.length; index++) {
                if (flagSource) {
                  sourcePath.append(linkSource[index]);
                  flagSource = false;
                } else {
                  sourcePath.append(":");
                  sourcePath.append(linkSource[index]);
                }
              }

              if (parentNode.hasNode(obj.getLinkTitle())) {
                Node existedNode = (Node) session.getItem(itemPath + "/" + obj.getLinkTitle());
                existedNode.remove();
              }
              session = sessionProvider.getSession(linkSource[1], manageableRepository);
              Node targetNode = (Node) session.getItem(sourcePath.toString());
              LinkManager linkManager = WCMCoreUtils.getService(LinkManager.class, containerName);
              linkManager.createLink(parentNode, obj.getLinkType(), targetNode, obj.getLinkTitle());
            }
          }
        }
      }
      if (LOG.isInfoEnabled()) {
        LOG.info("End Execute ImportXMLJob");
      }
    } catch (RepositoryException ex) {
      if (LOG.isDebugEnabled()) {
        LOG.debug("Repository 'repository ' not found.");
      }
    } catch (Exception ex) {
      if (LOG.isErrorEnabled()) {
        LOG.error("Error when importing Contents : " + ex.getMessage(), ex);
      }
    } finally {
      if (session != null) session.logout();
    }
  }
  /*
   * (non-Javadoc)
   * @see
   * org.exoplatform.services.wcm.portal.artifacts.BasePortalArtifactsPlugin
   * #deployToPortal(java.lang.String,
   * org.exoplatform.services.jcr.ext.common.SessionProvider)
   */
  public void deployToPortal(SessionProvider sessionProvider, String portalName) throws Exception {
    Iterator iterator = initParams.getObjectParamIterator();
    DeploymentDescriptor deploymentDescriptor = null;
    try {
      while (iterator.hasNext()) {
        ObjectParameter objectParameter = (ObjectParameter) iterator.next();
        deploymentDescriptor = (DeploymentDescriptor) objectParameter.getObject();
        Boolean cleanupPublication = deploymentDescriptor.getCleanupPublication();
        String sourcePath = deploymentDescriptor.getSourcePath();
        String versionHistoryPath = deploymentDescriptor.getVersionHistoryPath();
        // sourcePath should start with: war:/, jar:/, classpath:/, file:/
        String xmlData = (String) artifactsCache.get(sourcePath);
        if (xmlData == null) {
          InputStream stream = configurationManager.getInputStream(sourcePath);
          xmlData = IOUtil.getStreamContentAsString(stream);
          artifactsCache.put(sourcePath, xmlData);
        }
        ManageableRepository repository = repositoryService.getCurrentRepository();
        Session session =
            sessionProvider.getSession(deploymentDescriptor.getTarget().getWorkspace(), repository);
        String targetPath = deploymentDescriptor.getTarget().getNodePath();
        String realTargetFolder = StringUtils.replace(targetPath, "{portalName}", portalName);
        InputStream inputStream = configurationManager.getInputStream(sourcePath);
        session.importXML(realTargetFolder, inputStream, ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW);
        if (cleanupPublication) {
          /**
           * This code allows to cleanup the publication lifecycle in the target folder after
           * importing the data. By using this, the publication live revision property will be
           * re-initialized and the content will be set as published directly. Thus, the content
           * will be visible in front side.
           */
          QueryManager manager = session.getWorkspace().getQueryManager();
          String statement =
              "select * from nt:base where jcr:path LIKE '" + realTargetFolder + "/%'";
          Query query = manager.createQuery(statement.toString(), Query.SQL);
          NodeIterator iter = query.execute().getNodes();
          while (iter.hasNext()) {
            Node node = iter.nextNode();
            if (node.hasProperty("publication:liveRevision")
                && node.hasProperty("publication:currentState")) {
              if (LOG.isInfoEnabled()) {
                LOG.info("\"" + node.getName() + "\" publication lifecycle has been cleaned up");
              }
              node.setProperty("publication:liveRevision", "");
              node.setProperty("publication:currentState", "published");
            }
          }
        }

        if (versionHistoryPath != null && versionHistoryPath.length() > 0) {
          // process import version history
          Node currentNode = (Node) session.getItem(deploymentDescriptor.getTarget().getNodePath());

          Map<String, String> mapHistoryValue =
              Utils.getMapImportHistory(configurationManager.getInputStream(versionHistoryPath));
          Utils.processImportHistory(
              currentNode,
              configurationManager.getInputStream(versionHistoryPath),
              mapHistoryValue);
        }
        session.save();
      }
      Node portalNode = livePortalManagerService.getLivePortal(sessionProvider, portalName);
      configure(portalNode, portalName);
      portalNode.getSession().save();
    } catch (Exception ex) {
      if (LOG.isErrorEnabled()) {
        LOG.error(
            "deploy the portal "
                + portalName
                + " from "
                + deploymentDescriptor.getSourcePath()
                + " into "
                + StringUtils.replace(
                    deploymentDescriptor.getTarget().getNodePath(), "{portalName}", portalName)
                + " is FAILURE at "
                + new Date().toString()
                + "\n",
            ex);
      }
      throw ex;
    }
  }