/**
   * The main entry point of the example application.
   *
   * @param args command line arguments (ignored)
   * @throws Exception if an error occurs
   */
  public static void main(String[] args) throws Exception {
    Repository repository = new TransientRepository();
    Session session = repository.login(new SimpleCredentials("admin", "admin".toCharArray()));
    try {
      Node root = session.getRootNode();

      // Import the XML file unless already imported
      if (!root.hasNode("importxml")) {
        System.out.print("Importing xml... ");

        // Create an unstructured node under which to import the XML
        Node node = root.addNode("importxml", "nt:unstructured");

        // Import the file "test.xml" under the created node
        FileInputStream xml = new FileInputStream("test.xml");
        session.importXML(node.getPath(), xml, ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW);
        xml.close();
        session.save();
        System.out.println("done.");
      }

      // output the repository content
      dump(root);
    } finally {
      session.logout();
    }
  }
Example #2
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;
    }
  }
  public void importRepository(Ticket ticket, String name, InputStream inputStream)
      throws RepositoryAlreadyExistsException, RepositoryException, SecurityException {

    try {

      if (!ticket.getUser().isAdmin()) {
        throw new SecurityException(SecurityException.NOT_ENOUGH_PERMISSIONS);
      }

      javax.jcr.Session systemSession = SessionManager.getInstance().getSystemSession(ticket);
      WorkspaceImpl workspace = checkWorkspaceExists(name, systemSession);
      // Always change to lowercase
      name = name.toLowerCase();
      workspace.createWorkspace(name);

      javax.jcr.Repository repository = SessionManager.getInstance().getRepository();
      SimpleCredentials creds = new SimpleCredentials("username", "password".toCharArray());

      systemSession = repository.login(creds, name);

      // Copy to temp file. We cannot wrap to zip input stream due to incompatibilities
      // between apache implementation and java.util implementation
      File tempFile = File.createTempFile("jlib", "tmp");
      tempFile.deleteOnExit();
      FileOutputStream fos = new FileOutputStream(tempFile);
      IOUtils.copy(inputStream, fos);
      fos.flush();
      fos.close();

      ZipFile archive = null;
      try {
        archive = new ZipFile(tempFile);
      } catch (IOException ioe) {
        logger.warn("[JCRImportService] Trying to import non zipped repository");
        // probably this will be an old repository, so we will return the
        // content to let the process try to import it
        return;
      }

      // do our own buffering; reuse the same buffer.
      byte[] buffer = new byte[16384];
      ZipEntry entry = archive.getEntry("jlibrary");

      // get a stream of the archive entry's bytes
      InputStream zis = archive.getInputStream(entry);

      // ZipInputStream zis = new ZipInputStream(inputStream);
      byte[] smallBuffer = new byte[32];
      int i = 0;
      boolean tagFound = false;
      while (!tagFound) {
        byte next = (byte) zis.read();
        if (next == '*') {
          tagFound = true;
        } else {
          smallBuffer[i] = next;
          i++;
        }
      }

      byte[] header = new byte[i];
      System.arraycopy(smallBuffer, 0, header, 0, i);
      String lengthString = new String(header);
      int contentLength = Integer.parseInt(lengthString.substring(0, lengthString.length()));

      InputStream wrapzis = new ImportInputStream(zis, contentLength);
      systemSession.importXML("/", wrapzis, ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW);

      // Reopen the stream. importXML closes it
      zis = archive.getInputStream(entry);
      zis.skip(i + 1 + contentLength);

      // Now import the remaining info
      systemSession.importXML("/", zis, ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW);

      tempFile.delete();

      checkCustomProperties(systemSession);

      systemSession.save();

      // Finally check versions compatibility
      VersionChecker checker = new VersionChecker();
      checker.checkSession(systemSession);
    } catch (ConfigurationException ce) {
      // TODO: Remove this catch block when Jackrabbit supports workspace deletes
      throw new RecentlyRemovedRepositoryException();
    } catch (RepositoryAlreadyExistsException raee) {
      throw raee;
    } catch (SecurityException se) {
      throw se;
    } catch (AccessDeniedException e) {
      logger.error(e.getMessage(), e);
      throw new SecurityException(e);
    } catch (LoginException e) {
      logger.error(e.getMessage(), e);
      throw new SecurityException(e);
    } catch (RepositoryException re) {
      throw re;
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
      throw new RepositoryException(e);
    }
  }
  public void importRepository(Ticket ticket, byte[] zippedContent, String name)
      throws RepositoryAlreadyExistsException, RepositoryException, SecurityException {

    try {

      if (!ticket.getUser().isAdmin()) {
        throw new SecurityException(SecurityException.NOT_ENOUGH_PERMISSIONS);
      }

      javax.jcr.Session systemSession = SessionManager.getInstance().getSystemSession(ticket);
      WorkspaceImpl workspace = checkWorkspaceExists(name, systemSession);
      // Always change to lowercase
      name = name.toLowerCase();
      workspace.createWorkspace(name);

      javax.jcr.Repository repository = SessionManager.getInstance().getRepository();
      SimpleCredentials creds = new SimpleCredentials("username", "password".toCharArray());

      systemSession = repository.login(creds, name);

      byte[] content = unzipContent(zippedContent);

      // First read the header
      int i = 0;
      while (content[i] != '*') {
        i++;
      }
      i++;
      byte[] header = new byte[i];
      System.arraycopy(content, 0, header, 0, i);
      String lengthString = new String(header);
      int contentLength = Integer.parseInt(lengthString.substring(0, lengthString.length() - 1));

      // Now, load root content

      byte[] rootContent = new byte[contentLength];
      System.arraycopy(content, i, rootContent, 0, contentLength);
      rootContent = filterForCompatibility(rootContent);
      ByteArrayInputStream bais1 = new ByteArrayInputStream(rootContent);

      // Now load system content
      byte[] systemContent = new byte[content.length - contentLength - header.length];
      System.arraycopy(
          content, header.length + contentLength, systemContent, 0, systemContent.length);
      systemContent = filterForCompatibility(systemContent);
      ByteArrayInputStream bais2 = new ByteArrayInputStream(systemContent);

      systemSession.importXML("/", bais1, ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW);

      systemSession.importXML("/", bais2, ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW);

      checkCustomProperties(systemSession);

      bais1.close();
      bais2.close();

      systemSession.save();

      // Finally check versions compatibility
      VersionChecker checker = new VersionChecker();
      checker.checkSession(systemSession);
    } catch (ConfigurationException ce) {
      // TODO: Remove this catch block when Jackrabbit supports workspace deletes
      throw new RecentlyRemovedRepositoryException();
    } catch (RepositoryAlreadyExistsException raee) {
      throw raee;
    } catch (SecurityException se) {
      throw se;
    } catch (AccessDeniedException e) {
      logger.error(e.getMessage(), e);
      throw new SecurityException(e);
    } catch (LoginException e) {
      logger.error(e.getMessage(), e);
      throw new SecurityException(e);
    } catch (RepositoryException re) {
      throw re;
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
      throw new RepositoryException(e);
    }
  }