/**
   * This method will read and load the existing services.xml file and append the provided document
   * in the existing XML
   *
   * @param serviceDoc Document XML generated earlier
   * @param dirName Directory where file exists
   * @param fileName Name of the file to load the previous xml from
   * @return Modified XML document to be written on file
   */
  public Document appendXMLDoc(Document xmlDoc, String dirName, String fileName) {
    Document doc = null;
    try {
      File file = new File(dirName, fileName);
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = dbf.newDocumentBuilder();
      doc = db.parse(file);
      Element existingRoot = doc.getDocumentElement();

      List<Node> importTo = new ArrayList<Node>();
      List<Node> nodeToImport = new ArrayList<Node>();
      if (fileName.equals("ejb-jar.xml")
          || fileName.equals("jboss.xml")
          || fileName.equals("jboss-ejb3.xml")) {
        importTo.add(existingRoot.getElementsByTagName("enterprise-beans").item(0));
        nodeToImport.add(xmlDoc.getDocumentElement().getElementsByTagName("session").item(0));
        if (fileName.equals("ejb-jar.xml")) {
          // Additional security config to append
          importTo.add(existingRoot.getElementsByTagName("assembly-descriptor").item(0));
          nodeToImport.add(
              xmlDoc.getDocumentElement().getElementsByTagName("method-permission").item(0));
        } else if (fileName.equals("jboss-ejb3.xml")) {
          // Additional security config to append
          importTo.add(existingRoot.getElementsByTagName("assembly-descriptor").item(0));
          nodeToImport.add(xmlDoc.getDocumentElement().getElementsByTagName("s:security").item(0));
        }
      } else if (fileName.equals("ibm-ejb-jar-bnd.xml")) {
        importTo.add(existingRoot);
        nodeToImport.add(xmlDoc.getDocumentElement().getElementsByTagName("session").item(0));
      } else if (fileName.equals("weblogic-ejb-jar.xml")) {
        importTo.add(existingRoot);
        nodeToImport.add(
            xmlDoc
                .getDocumentElement()
                .getElementsByTagName("wls:weblogic-enterprise-bean")
                .item(0));
      }
      if (importTo.size() > 0 && nodeToImport.size() > 0) {
        for (int i = 0; i < importTo.size(); i++) {
          importTo.get(i).appendChild(doc.importNode(nodeToImport.get(i), true));
        }
      }
      return doc;
    } catch (ParserConfigurationException pe) {
      System.out.println(
          "Failed to parse existing services XML. ParserConfigException : " + pe.getMessage());
    } catch (SAXException sae) {
      System.out.println(
          "Failed to parse existing services XML. SAXException : " + sae.getMessage());
    } catch (DOMException dome) {
      System.out.println(
          "Failed to parse existing services XML. DOMException : " + dome.getMessage());
    } catch (IOException ioe) {
      System.out.println("Failed to locate services.xml . IOException : " + ioe.getMessage());
    } catch (Exception e) {
      System.out.println("Failed to parse services.xml . Exception : " + e.getMessage());
    }
    // Return the original one back
    return xmlDoc;
  }
예제 #2
0
파일: Page.java 프로젝트: tolleiv/structr
  /**
   * Creates a default simple page for the Structr backend "add page" button.
   *
   * @param securityContext
   * @param name
   * @return
   * @throws FrameworkException
   */
  public static Page createSimplePage(final SecurityContext securityContext, final String name)
      throws FrameworkException {

    final Page page = Page.createNewPage(securityContext, name);
    if (page != null) {

      Element html = page.createElement("html");
      Element head = page.createElement("head");
      Element body = page.createElement("body");
      Element title = page.createElement("title");
      Element h1 = page.createElement("h1");
      Element div = page.createElement("div");

      try {
        // add HTML element to page
        page.appendChild(html);

        // add HEAD and BODY elements to HTML
        html.appendChild(head);
        html.appendChild(body);

        // add TITLE element to HEAD
        head.appendChild(title);

        // add H1 element to BODY
        body.appendChild(h1);

        // add DIV element to BODY
        body.appendChild(div);

        // add text nodes
        title.appendChild(page.createTextNode("${capitalize(page.name)}"));
        h1.appendChild(page.createTextNode("${capitalize(page.name)}"));
        div.appendChild(page.createTextNode("Initial body text"));

      } catch (DOMException dex) {

        logger.log(Level.WARNING, "", dex);

        throw new FrameworkException(422, dex.getMessage());
      }
    }

    return page;
  }
 @FXML
 private void HandleValidateButtonAction(ActionEvent event) {
   String s = StringEscapeUtils.unescapeHtml(markdownToHtml(SourceText.getText()));
   if (corrector == null) {
     corrector = new Corrector();
   }
   try {
     String result = corrector.checkHtmlContent(s);
     WebEngine webEngine = renderView.getEngine();
     webEngine.loadContent(
         "<!doctype html><html lang='fr'><head><meta charset='utf-8'><base href='file://"
             + MainApp.class.getResource(".").getPath()
             + "' /></head><body>"
             + result
             + "</body></html>");
     webEngine.setUserStyleSheetLocation(
         MainApp.class.getResource("css/content.css").toExternalForm());
   } catch (DOMException e) {
     logger.error(e.getMessage(), e);
   }
 }
 protected void buildParentElement(cfStructData s, Node parent) throws cfmRunTimeException {
   try {
     Object[] keys = s.keys();
     for (int i = 0; i < keys.length; i++) {
       String k = (String) keys[i];
       cfData d = s.getData(k);
       if (d instanceof cfXmlData) {
         // Add as a child node
         parent.appendChild(((cfXmlData) d).getXMLNode());
       } else if (d instanceof cfStructData) {
         // Create a child node and continue recursion
         Element e = parent.getOwnerDocument().createElement(k);
         parent.appendChild(e);
         buildParentElement((cfStructData) d, e);
       }
     }
   } catch (DOMException ex) {
     throw new cfmRunTimeException(
         catchDataFactory.javaMethodException(
             "errorCode.javaException", ex.getClass().getName(), ex.getMessage(), ex));
   }
 }
예제 #5
0
  /**
   * Parse the direct payment transaction response received from the server Response template:
   *
   * <pre>
   * &lt;ns1:EnviarInstrucaoUnicaResponse xmlns:ns1="http://www.moip.com.br/ws/alpha/"&gt;
   *   &lt;Resposta&gt;
   * &lt;ID&gt;000000000000000000&lt;/ID&gt;
   * &lt;Status&gt;Falha&lt;/Status&gt;
   * &lt;Erro Codigo="XXX"&gt;Message;/Erro&gt;
   * &lt;Erro Codigo="XXX"&gt;Message&lt;/Erro&gt;
   *  &lt;/Resposta&gt;
   * &lt;/ns1:EnviarInstrucaoUnicaResponse&gt;
   *
   *
   * &lt;ns1:EnviarInstrucaoUnicaResponse xmlns:ns1="https://desenvolvedor.moip.com.br/sandbox/"&gt;
   * &lt;Resposta&gt;
   *   &lt;ID&gt;200807272314444710000000000022&lt;/ID&gt;
   *   &lt;Status&gt;Sucesso&lt;/Status&gt;
   *   &lt;Token&gt;T2N0L0X8E0S71217U2H3W1T4F4S4G4K731D010V0S0V0S080M010E0Q082X2&lt;/Token&gt;
   *    &lt;RespostaPagamentoDireto&gt;
   *      &lt;TotalPago&gt;213.25&lt;/TotalPago&gt;
   *      &lt;TaxaMoIP&gt;15.19&lt;/TaxaMoIP&gt;
   *      &lt;Status&gt;EmAnalise&lt;/Status&gt;
   *      &lt;CodigoMoIP&gt;0000.0006.9922&lt;/CodigoMoIP&gt;
   *      &lt;Mensagem&gt;Transação com Sucesso&lt;/Mensagem&gt;
   *      &lt;CodigoAutorizacao&gt;396822&lt;/CodigoAutorizacao&gt;
   *      &lt;CodigoRetorno0&lt;/CodigoRetorno&gt;
   *   &lt;/RespostaPagamentoDireto&gt;
   * &lt;/Resposta&gt;
   * &lt;/ns1:EnviarInstrucaoUnicaResponse&gt;
   * </pre>
   *
   * @param msg the InputStream received from the server
   * @return true or false
   * @throws ParserConfigurationException
   * @throws IOException
   * @throws SAXException
   * @throws DOMException
   */
  public boolean parseDirectPaymentResponse(InputStream msg) {
    String responseToken = "ERROR";

    try {
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = dbf.newDocumentBuilder();
      Document doc = db.parse(msg);
      NodeList nodeList = doc.getElementsByTagName("Status");
      if (nodeList.item(0) != null) {
        responseToken = nodeList.item(0).getChildNodes().item(0).getNodeValue();
        if (responseToken.equalsIgnoreCase("Sucesso")) {
          responseObj.setResponseStatus("Sucesso");
          nodeList = doc.getElementsByTagName("ID");
          if (nodeList.item(0) != null)
            responseObj.setId(nodeList.item(0).getChildNodes().item(0).getNodeValue());
          nodeList = doc.getElementsByTagName("Token");
          if (nodeList.item(0) != null)
            responseObj.setToken(nodeList.item(0).getChildNodes().item(0).getNodeValue());
          nodeList = doc.getElementsByTagName("TotalPago");
          if (nodeList.item(0) != null)
            responseObj.setAmount(nodeList.item(0).getChildNodes().item(0).getNodeValue());
          nodeList = doc.getElementsByTagName("TaxaMoIP");
          if (nodeList.item(0) != null)
            responseObj.setMoIPTax(nodeList.item(0).getChildNodes().item(0).getNodeValue());
          nodeList = doc.getElementsByTagName("Status");
          // assuming second ocurrence of "Status"
          if (nodeList.item(1) != null)
            responseObj.setTransactionStatus(
                nodeList.item(1).getChildNodes().item(0).getNodeValue());
          nodeList = doc.getElementsByTagName("CodigoMoIP");
          if (nodeList.item(0) != null)
            responseObj.setMoIPCode(nodeList.item(0).getChildNodes().item(0).getNodeValue());
          nodeList = doc.getElementsByTagName("CodigoRetorno");
          if (nodeList.item(0) != null)
            responseObj.setReturnCode(nodeList.item(0).getChildNodes().item(0).getNodeValue());
          nodeList = doc.getElementsByTagName("Mensagem");
          if (nodeList.item(0) != null)
            responseObj.setMessage(nodeList.item(0).getChildNodes().item(0).getNodeValue());

        } else {
          responseObj.setResponseStatus("Falha");
          nodeList = doc.getElementsByTagName("Erro");
          if (nodeList.item(0) != null) {
            for (int i = 0; i < nodeList.getLength(); i++)
              responseObj.setMessage(nodeList.item(i).getChildNodes().item(0).getNodeValue());
          }
        }
      } else return false;

      //			//Reading as String
      //			BufferedReader rd = new BufferedReader(new InputStreamReader(msg));
      //			String line;
      //			StringBuilder sb =  new StringBuilder( );
      //			while ((line = rd.readLine()) != null)
      //			{	sb.append(line); }
      //			rd.close();
      //			if(sb.length( ) > 0)
      //				responseToken = sb.toString( );

    } catch (ParserConfigurationException pce) {
      Log.e("MENKI [parseDirectPaymentResponse] ", pce.getMessage());
      pce.printStackTrace();
    } catch (SAXException se) {
      Log.e("MENKI [parseDirectPaymentResponse] ", se.getMessage());
      se.printStackTrace();
    } catch (IOException ioe) {
      Log.e("MENKI [parseDirectPaymentResponse] ", ioe.getMessage());
      ioe.printStackTrace();
    } catch (DOMException de) {
      Log.e("MENKI [parseDirectPaymentResponse] ", de.getMessage());
      de.printStackTrace();
    }

    return true;
  }
예제 #6
0
  @Override
  public void processMessage(WebSocketMessage webSocketData) {

    final Map<String, Object> nodeData = webSocketData.getNodeData();
    final String parentId = (String) nodeData.get("parentId");
    final String pageId = webSocketData.getPageId();

    nodeData.remove("parentId");

    if (pageId != null) {

      // check for parent ID before creating any nodes
      if (parentId == null) {

        getWebSocket()
            .send(
                MessageBuilder.status()
                    .code(422)
                    .message("Cannot add node without parentId")
                    .build(),
                true);
        return;
      }

      // check if content node with given ID exists
      final DOMNode contentNode = getDOMNode(parentId);
      if (contentNode == null) {

        getWebSocket()
            .send(MessageBuilder.status().code(404).message("Parent node not found").build(), true);
        return;
      }

      final Document document = getPage(pageId);
      if (document != null) {

        final String tagName = (String) nodeData.get("tagName");
        nodeData.remove("tagName");

        final DOMNode parentNode = (DOMNode) contentNode.getParentNode();

        try {

          DOMNode elementNode = null;
          if (tagName != null && !tagName.isEmpty()) {

            elementNode = (DOMNode) document.createElement(tagName);
          }

          // append new node to parent parent node
          if (elementNode != null) {

            parentNode.appendChild(elementNode);
          }

          // append new node to parent parent node
          if (elementNode != null) {

            // append content node to new node
            elementNode.appendChild(contentNode);
          }

        } catch (DOMException dex) {

          // send DOM exception
          getWebSocket()
              .send(MessageBuilder.status().code(422).message(dex.getMessage()).build(), true);
        }

      } else {

        getWebSocket()
            .send(MessageBuilder.status().code(404).message("Page not found").build(), true);
      }

    } else {

      getWebSocket()
          .send(
              MessageBuilder.status()
                  .code(422)
                  .message("Cannot create node without pageId")
                  .build(),
              true);
    }
  }
예제 #7
0
  /*
   * (non-Javadoc)
   *
   * @see org.sakaiproject.service.legacy.entity.ResourceService#merge(java.lang.String,
   *      org.w3c.dom.Element, java.lang.String, java.lang.String, java.util.Map, java.util.HashMap,
   *      java.util.Set)
   */
  public String merge(
      String siteId,
      Element root,
      String archivePath,
      String fromSiteId,
      Map attachmentNames,
      Map userIdTrans,
      Set userListAllowImport) {
    // buffer for the results log
    StringBuilder results = new StringBuilder();
    // populate SyllabusItem
    int syDataCount = 0;
    SyllabusItem syItem = null;
    if (siteId != null && siteId.trim().length() > 0) {
      try {
        NodeList allChildrenNodes = root.getChildNodes();
        int length = allChildrenNodes.getLength();
        for (int i = 0; i < length; i++) {
          Node siteNode = allChildrenNodes.item(i);
          if (siteNode.getNodeType() == Node.ELEMENT_NODE) {
            Element siteElement = (Element) siteNode;
            if (siteElement.getTagName().equals(SITE_ARCHIVE)) {
              // sakai2              NodeList pageNodes = siteElement.getChildNodes();
              //              int lengthPageNodes = pageNodes.getLength();
              //              for (int p = 0; p < lengthPageNodes; p++)
              //              {
              //                Node pageNode = pageNodes.item(p);
              //                if (pageNode.getNodeType() == Node.ELEMENT_NODE)
              //                {
              //                  Element pageElement = (Element) pageNode;
              //                  if (pageElement.getTagName().equals(PAGE_ARCHIVE))
              //                  {
              //                    NodeList syllabusNodes = pageElement.getChildNodes();
              NodeList syllabusNodes = siteElement.getChildNodes();
              int lengthSyllabusNodes = syllabusNodes.getLength();
              for (int sn = 0; sn < lengthSyllabusNodes; sn++) {
                Node syNode = syllabusNodes.item(sn);
                if (syNode.getNodeType() == Node.ELEMENT_NODE) {
                  Element syElement = (Element) syNode;
                  if (syElement.getTagName().equals(SYLLABUS)) {
                    // create a page and all syllabus tool to the page
                    // sakai2                          String page =
                    // addSyllabusToolToPage(siteId,pageElement
                    //                              .getAttribute(PAGE_NAME));
                    //                          SyllabusItem syllabusItem = syllabusManager
                    //                          .createSyllabusItem(UserDirectoryService
                    //                              .getCurrentUser().getId(), page, syElement
                    //                              .getAttribute(SYLLABUS_REDIRECT_URL));
                    String page =
                        addSyllabusToolToPage(siteId, siteElement.getAttribute(SITE_NAME));
                    // sakai2                          SyllabusItem syllabusItem = syllabusManager
                    //                          .createSyllabusItem(UserDirectoryService
                    //                              .getCurrentUser().getId(), page, syElement
                    //                              .getAttribute(SYLLABUS_REDIRECT_URL));
                    // sakai2 add--
                    SyllabusItem syllabusItem = syllabusManager.getSyllabusItemByContextId(page);
                    if (syllabusItem == null) {
                      syllabusItem =
                          syllabusManager.createSyllabusItem(
                              UserDirectoryService.getCurrentUser().getId(),
                              page,
                              syElement.getAttribute(SYLLABUS_REDIRECT_URL));
                    }
                    // added htripath: get imported redirecturl, even if syllabus item is existing.
                    else {
                      if (syElement.getAttribute(SYLLABUS_REDIRECT_URL) != null) {
                        syllabusItem.setRedirectURL(syElement.getAttribute(SYLLABUS_REDIRECT_URL));
                        syllabusManager.saveSyllabusItem(syllabusItem);
                      }
                    }
                    //
                    NodeList allSyllabiNodes = syElement.getChildNodes();
                    int lengthSyllabi = allSyllabiNodes.getLength();
                    for (int j = 0; j < lengthSyllabi; j++) {
                      Node child2 = allSyllabiNodes.item(j);
                      if (child2.getNodeType() == Node.ELEMENT_NODE) {

                        Element syDataElement = (Element) child2;
                        if (syDataElement.getTagName().equals(SYLLABUS_DATA)) {
                          List attachStringList = new ArrayList();

                          syDataCount = syDataCount + 1;
                          SyllabusData syData = new SyllabusDataImpl();
                          syData.setView(syDataElement.getAttribute(SYLLABUS_DATA_VIEW));
                          syData.setTitle(syDataElement.getAttribute(SYLLABUS_DATA_TITLE));
                          syData.setStatus(syDataElement.getAttribute(SYLLABUS_DATA_STATUS));
                          syData.setEmailNotification(
                              syDataElement.getAttribute(SYLLABUS_DATA_EMAIL_NOTIFICATION));

                          NodeList allAssetNodes = syDataElement.getChildNodes();
                          int lengthSyData = allAssetNodes.getLength();
                          for (int k = 0; k < lengthSyData; k++) {
                            Node child3 = allAssetNodes.item(k);
                            if (child3.getNodeType() == Node.ELEMENT_NODE) {
                              Element assetEle = (Element) child3;
                              if (assetEle.getTagName().equals(SYLLABUS_DATA_ASSET)) {
                                String charset = trimToNull(assetEle.getAttribute("charset"));
                                if (charset == null) charset = "UTF-8";

                                String body =
                                    trimToNull(assetEle.getAttribute("syllabus_body-html"));
                                if (body != null) {
                                  try {
                                    byte[] decoded = Base64.decodeBase64(body.getBytes("UTF-8"));
                                    body = new String(decoded, charset);
                                  } catch (Exception e) {
                                    logger.warn("Decode Syllabus: " + e);
                                  }
                                }

                                if (body == null) body = "";

                                String ret;
                                ret = trimToNull(body);

                                syData.setAsset(ret);
                                /*decode
                                NodeList assetStringNodes = assetEle
                                    .getChildNodes();
                                int lengthAssetNodes = assetStringNodes
                                    .getLength();
                                for (int l = 0; l < lengthAssetNodes; l++)
                                {
                                  Node child4 = assetStringNodes.item(l);
                                  if (child4.getNodeType() == Node.TEXT_NODE)
                                  {
                                    Text textNode = (Text) child4;
                                    syData.setAsset(textNode.getData());
                                  }
                                }*/
                              }
                              if (assetEle.getTagName().equals(SYLLABUS_ATTACHMENT)) {
                                Element attachElement = (Element) child3;
                                String oldUrl = attachElement.getAttribute("relative-url");
                                if (oldUrl.startsWith("/content/attachment/")) {
                                  String newUrl = (String) attachmentNames.get(oldUrl);
                                  if (newUrl != null) {
                                    //// if (newUrl.startsWith("/attachment/"))
                                    //// newUrl = "/content".concat(newUrl);

                                    attachElement.setAttribute(
                                        "relative-url", Validator.escapeQuestionMark(newUrl));

                                    attachStringList.add(Validator.escapeQuestionMark(newUrl));
                                  }
                                } else if (oldUrl.startsWith(
                                    "/content/group/" + fromSiteId + "/")) {
                                  String newUrl =
                                      "/content/group/"
                                          + siteId
                                          + oldUrl.substring(15 + fromSiteId.length());
                                  attachElement.setAttribute(
                                      "relative-url", Validator.escapeQuestionMark(newUrl));

                                  attachStringList.add(Validator.escapeQuestionMark(newUrl));
                                }
                              }
                            }
                          }

                          int initPosition =
                              syllabusManager.findLargestSyllabusPosition(syllabusItem).intValue()
                                  + 1;
                          syData =
                              syllabusManager.createSyllabusDataObject(
                                  syData.getTitle(),
                                  (new Integer(initPosition)),
                                  syData.getAsset(),
                                  syData.getView(),
                                  syData.getStatus(),
                                  syData.getEmailNotification());
                          Set attachSet = new TreeSet();
                          for (int m = 0; m < attachStringList.size(); m++) {
                            ContentResource cr =
                                contentHostingService.getResource((String) attachStringList.get(m));
                            ResourceProperties rp = cr.getProperties();
                            //                            			SyllabusAttachment tempAttach =
                            // syllabusManager.createSyllabusAttachmentObject(
                            //
                            //	(String)attachStringList.get(m),rp.getProperty(ResourceProperties.PROP_DISPLAY_NAME));
                            SyllabusAttachment tempAttach =
                                syllabusManager.createSyllabusAttachmentObject(
                                    cr.getId(),
                                    rp.getProperty(ResourceProperties.PROP_DISPLAY_NAME));
                            tempAttach.setName(
                                rp.getProperty(ResourceProperties.PROP_DISPLAY_NAME));
                            tempAttach.setSize(
                                rp.getProperty(ResourceProperties.PROP_CONTENT_LENGTH));
                            tempAttach.setType(
                                rp.getProperty(ResourceProperties.PROP_CONTENT_TYPE));
                            tempAttach.setUrl(cr.getUrl());
                            tempAttach.setAttachmentId(cr.getId());

                            attachSet.add(tempAttach);
                          }
                          syData.setAttachments(attachSet);

                          syllabusManager.addSyllabusToSyllabusItem(syllabusItem, syData);
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
        results.append("merging syllabus " + siteId + " (" + syDataCount + ") syllabus items.\n");

      } catch (DOMException e) {
        logger.error(e.getMessage(), e);
        results.append("merging " + getLabel() + " failed during xml parsing.\n");

      } catch (Exception e) {
        logger.error(e.getMessage(), e);
        results.append("merging " + getLabel() + " failed.\n");
      }
    }

    return results.toString();
  }
예제 #8
0
  /*
   * (non-Javadoc)
   *
   * @see org.sakaiproject.service.legacy.entity.ResourceService#archive(java.lang.String,
   *      org.w3c.dom.Document, java.util.Stack, java.lang.String,
   *      org.sakaiproject.service.legacy.entity.ReferenceVector)
   */
  public String archive(String siteId, Document doc, Stack stack, String arg3, List attachments) {

    StringBuilder results = new StringBuilder();

    try {
      int syDataCount = 0;
      results.append(
          "archiving "
              + getLabel()
              + " context "
              + Entity.SEPARATOR
              + siteId
              + Entity.SEPARATOR
              + SiteService.MAIN_CONTAINER
              + ".\n");
      // start with an element with our very own (service) name
      Element element = doc.createElement(SyllabusService.class.getName());
      ((Element) stack.peek()).appendChild(element);
      stack.push(element);
      if (siteId != null && siteId.trim().length() > 0) {
        Element siteElement = doc.createElement(SITE_ARCHIVE);
        siteElement.setAttribute(SITE_NAME, SiteService.getSite(siteId).getId());
        siteElement.setAttribute(SITE_ID, SiteService.getSite(siteId).getTitle());
        // sakai2        Iterator pageIter = getSyllabusPages(siteId);
        //        if (pageIter != null)
        //        {
        //          while (pageIter.hasNext())
        //          {
        //            String page = (String) pageIter.next();
        //            if (page != null)
        //            {
        //              Element pageElement = doc.createElement(PAGE_ARCHIVE);
        //              pageElement.setAttribute(PAGE_ID, page);
        // sakai2              pageElement.setAttribute(PAGE_NAME, SiteService.getSite(siteId)
        // sakai2                  .getPage(page).getTitle());
        // sakai2              SyllabusItem syllabusItem = syllabusManager
        //                  .getSyllabusItemByContextId(page);
        SyllabusItem syllabusItem = syllabusManager.getSyllabusItemByContextId(siteId);
        if (syllabusItem != null) {
          Element syllabus = doc.createElement(SYLLABUS);
          syllabus.setAttribute(SYLLABUS_ID, syllabusItem.getSurrogateKey().toString());
          syllabus.setAttribute(SYLLABUS_USER_ID, syllabusItem.getUserId());
          syllabus.setAttribute(SYLLABUS_CONTEXT_ID, syllabusItem.getContextId());
          syllabus.setAttribute(SYLLABUS_REDIRECT_URL, syllabusItem.getRedirectURL());

          Set syllabi = syllabusManager.getSyllabiForSyllabusItem(syllabusItem);

          if (syllabi != null && !syllabi.isEmpty()) {
            Iterator syllabiIter = syllabi.iterator();
            while (syllabiIter.hasNext()) {
              SyllabusData syllabusData = (SyllabusData) syllabiIter.next();
              if (syllabusData != null) {
                syDataCount++;
                Element syllabus_data = doc.createElement(SYLLABUS_DATA);
                syllabus_data.setAttribute(
                    SYLLABUS_DATA_ID, syllabusData.getSyllabusId().toString());
                syllabus_data.setAttribute(
                    SYLLABUS_DATA_POSITION, syllabusData.getPosition().toString());
                syllabus_data.setAttribute(SYLLABUS_DATA_TITLE, syllabusData.getTitle());
                syllabus_data.setAttribute(SYLLABUS_DATA_VIEW, syllabusData.getView());
                syllabus_data.setAttribute(SYLLABUS_DATA_STATUS, syllabusData.getStatus());
                syllabus_data.setAttribute(
                    SYLLABUS_DATA_EMAIL_NOTIFICATION, syllabusData.getEmailNotification());
                Element asset = doc.createElement(SYLLABUS_DATA_ASSET);

                try {
                  String encoded =
                      new String(Base64.encodeBase64(syllabusData.getAsset().getBytes()), "UTF-8");
                  asset.setAttribute("syllabus_body-html", encoded);
                } catch (Exception e) {
                  logger.warn("Encode Syllabus - " + e);
                }

                syllabus_data.appendChild(asset);
                syllabus.appendChild(syllabus_data);
              }
            }
            // sakai2                }
            //                pageElement.appendChild(syllabus);
            //              }
            //              siteElement.appendChild(pageElement);
            //            }

            // sakai2
            siteElement.appendChild(syllabus);
          }
          results.append(
              "archiving "
                  + getLabel()
                  + ": ("
                  + syDataCount
                  + ") syllabys items archived successfully.\n");
        } else {
          results.append("archiving " + getLabel() + ": empty syllabus archived.\n");
        }
        ((Element) stack.peek()).appendChild(siteElement);
        stack.push(siteElement);
      }
      stack.pop();

    } catch (DOMException e) {
      logger.error(e.getMessage(), e);
    } catch (IdUnusedException e) {
      logger.error(e.getMessage(), e);
    }
    return results.toString();
  }
예제 #9
0
  public void initialize(InputStream configFileStream) throws InitializationException {

    try {
      XPathFactory factory = XPathFactory.newInstance();
      XPath xPath = factory.newXPath();
      DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      Document document = parser.parse(new InputSource(configFileStream));
      Node node;
      NodeList nodes =
          (NodeList) xPath.evaluate("/htmlextractors/extractor", document, XPathConstants.NODESET);
      if (nodes != null) {
        TransformerFactory transFac = TransformerFactory.newInstance();
        transFac.setURIResolver(new BundleURIResolver());
        for (int j = 0, iCnt = nodes.getLength(); j < iCnt; j++) {
          Node nd = nodes.item(j);
          node = (Node) xPath.evaluate("@id", nd, XPathConstants.NODE);
          String id = node.getNodeValue();
          Node srcNode = (Node) xPath.evaluate("source", nd, XPathConstants.NODE);
          if (srcNode != null) {
            node = (Node) xPath.evaluate("@type", srcNode, XPathConstants.NODE);
            String srcType = node.getNodeValue();
            if (srcType.equals("xslt")) {
              String rdfFormat = "rdfxml";
              Syntax rdfSyntax = Syntax.RdfXml;
              node = (Node) xPath.evaluate("@syntax", srcNode, XPathConstants.NODE);
              if (node != null) {
                rdfFormat = node.getNodeValue();
                if (rdfFormat.equalsIgnoreCase("turtle")) {
                  rdfSyntax = Syntax.Turtle;
                } else if (rdfFormat.equalsIgnoreCase("ntriple")) {
                  rdfSyntax = Syntax.Ntriples;
                } else if (rdfFormat.equalsIgnoreCase("n3")) {
                  rdfSyntax = XsltExtractor.N3;
                } else if (!rdfFormat.equalsIgnoreCase("rdfxml")) {
                  throw new InitializationException(
                      "Unknown RDF Syntax: " + rdfFormat + " for " + id + " extractor");
                }
              }
              // TODO: do something about disjunctions of
              // Extractors? Assume, only RDFa or Microformats are
              // used?
              String fileName = DOMUtils.getText(srcNode);
              XsltExtractor xsltExtractor = new XsltExtractor(id, fileName, transFac);
              xsltExtractor.setSyntax(rdfSyntax);
              // name of URI/URL parameter of the script (default
              // "uri")
              node = (Node) xPath.evaluate("@uri", srcNode, XPathConstants.NODE);
              if (node != null) {
                xsltExtractor.setUriParameter(node.getNodeValue());
              }
              registry.put(id, xsltExtractor);
              activeExtractors.add(id);
            } else if (srcType.equals("java")) {
              String clsName = srcNode.getNodeValue();
              Object extractor = Class.forName(clsName).newInstance();
              if (extractor instanceof HtmlExtractionComponent) {
                registry.put(id, (HtmlExtractionComponent) extractor);
                activeExtractors.add(id);
              } else {
                throw new InitializationException("clsName is not an HtmlExtractionComponent");
              }
            } else {
              LOG.warn("No valid type for extractor found: " + id);
            }
            LOG.info("Extractor for: " + id);
          }
        }
      }
    } catch (FileNotFoundException e) {
      throw new InitializationException(e.getMessage(), e);
    } catch (XPathExpressionException e) {
      throw new InitializationException(e.getMessage(), e);
    } catch (DOMException e) {
      throw new InitializationException(e.getMessage(), e);
    } catch (ParserConfigurationException e) {
      throw new InitializationException(e.getMessage(), e);
    } catch (SAXException e) {
      throw new InitializationException(e.getMessage(), e);
    } catch (IOException e) {
      throw new InitializationException(e.getMessage(), e);
    } catch (ClassNotFoundException e) {
      throw new InitializationException(e.getMessage(), e);
    } catch (InstantiationException e) {
      throw new InitializationException(e.getMessage(), e);
    } catch (IllegalAccessException e) {
      throw new InitializationException(e.getMessage(), e);
    }
  }
  @Override
  public void processMessage(WebSocketMessage webSocketData) {

    final Map<String, Object> nodeData = webSocketData.getNodeData();
    final String parentId = (String) nodeData.get("parentId");
    final String childContent = (String) nodeData.get("childContent");
    final String pageId = webSocketData.getPageId();

    nodeData.remove("parentId");

    if (pageId != null) {

      // check for parent ID before creating any nodes
      if (parentId == null) {

        getWebSocket()
            .send(
                MessageBuilder.status()
                    .code(422)
                    .message("Cannot add node without parentId")
                    .build(),
                true);
        return;
      }

      // check if parent node with given ID exists
      final DOMNode parentNode = getDOMNode(parentId);
      if (parentNode == null) {

        getWebSocket()
            .send(MessageBuilder.status().code(404).message("Parent node not found").build(), true);
        return;
      }

      final Document document = getPage(pageId);
      if (document != null) {

        final String tagName = (String) nodeData.get("tagName");
        final App app = StructrApp.getInstance();

        nodeData.remove("tagName");

        try {
          app.beginTx();

          DOMNode newNode;

          if (tagName != null && !tagName.isEmpty()) {

            newNode = (DOMNode) document.createElement(tagName);

          } else {

            newNode = (DOMNode) document.createTextNode("#text");
          }

          // append new node to parent
          if (newNode != null) {

            parentNode.appendChild(newNode);

            for (Entry entry : nodeData.entrySet()) {

              String key = (String) entry.getKey();
              Object val = entry.getValue();

              PropertyKey propertyKey =
                  StructrApp.getConfiguration()
                      .getPropertyKeyForDatabaseName(newNode.getClass(), key);
              if (propertyKey != null) {

                try {
                  Object convertedValue = val;

                  PropertyConverter inputConverter =
                      propertyKey.inputConverter(SecurityContext.getSuperUserInstance());
                  if (inputConverter != null) {

                    convertedValue = inputConverter.convert(val);
                  }

                  // newNode.unlockReadOnlyPropertiesOnce();
                  newNode.setProperty(propertyKey, convertedValue);

                } catch (FrameworkException fex) {

                  logger.log(
                      Level.WARNING,
                      "Unable to set node property {0} of node {1} to {2}: {3}",
                      new Object[] {propertyKey, newNode.getUuid(), val, fex.getMessage()});
                }
              }
            }

            // create a child text node if content is given
            if (StringUtils.isNotBlank(childContent)) {

              DOMNode childNode = (DOMNode) document.createTextNode(childContent);

              if (newNode != null) {

                newNode.appendChild(childNode);
              }
            }
          }
          app.commitTx();

        } catch (DOMException dex) {

          // send DOM exception
          getWebSocket()
              .send(MessageBuilder.status().code(422).message(dex.getMessage()).build(), true);

        } catch (FrameworkException ex) {

          Logger.getLogger(CreateAndAppendDOMNodeCommand.class.getName())
              .log(Level.SEVERE, null, ex);

        } finally {

          app.finishTx();
        }

      } else {

        getWebSocket()
            .send(MessageBuilder.status().code(404).message("Page not found").build(), true);
      }

    } else {

      getWebSocket()
          .send(
              MessageBuilder.status()
                  .code(422)
                  .message("Cannot create node without pageId")
                  .build(),
              true);
    }
  }