/**
   * 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
  @BeforeClass
  public static void beforeClass() {
    TldGenerator tldGen = new TldGenerator();
    BaseTagLibDefinition tldef;
    try {
      tldef = tldGen.getInstanceOfDefinition(MockTagLibDefinition.class);
      document = tldGen.generateDocument(tldef);

    } catch (ClassNotFoundException e) {

      e.printStackTrace();
      fail("ClassNotFoundException Occurs!");
    } catch (DOMException e) {

      e.printStackTrace();
      fail("DOMException Occurs!");
    } catch (ParserConfigurationException e) {

      e.printStackTrace();
      fail("ParserConfigurationException Occurs!");
    } catch (Exception e) {

      e.printStackTrace();
      fail("Exception Occurs!");
    }
  }
예제 #3
0
  public Ending(Paradigm paradigm, Node node) {
    super(node);
    this.paradigm = paradigm;

    if (!node.getNodeName().equalsIgnoreCase("Ending"))
      throw new Error("Node '" + node.getNodeName() + "' but Ending expected.");

    Node n = node.getAttributes().getNamedItem("ID");
    if (n != null) this.setID(Integer.parseInt(n.getTextContent()));

    n = node.getAttributes().getNamedItem("StemChange");
    if (n != null) this.setMija(Integer.parseInt(n.getTextContent()));

    n = node.getAttributes().getNamedItem("Ending");
    if (n != null) this.setEnding(n.getTextContent());

    n = node.getAttributes().getNamedItem("StemID");
    if (n != null) this.stemID = Integer.parseInt(n.getTextContent());

    n = node.getAttributes().getNamedItem("LemmaEnding");
    if (n != null)
      try {
        setLemmaEnding(Integer.parseInt(n.getTextContent()));
        // FIXME - nestrādās, ja pamatformas galotne tiks ielasīta pēc šīs galotnes, nevis pirms..
      } catch (NumberFormatException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (DOMException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (Exception e) {
        throw new Error(e.getMessage());
      }
  }
예제 #4
0
  /**
   * Load or Reload a survey from file, return survey ID or null if unsuccessful
   *
   * @param filename File from which the survey has to be loaded. *
   * @return String The survey Id that has been loaded.
   */
  public String loadSurvey(String filename) {
    String sid = null;
    Survey s;
    try {
      // String file_loc = SurveyorApplication.xmlLoc
      // + System.getProperty("file.separator") + dirName
      // + System.getProperty("file.separator") + filename;
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      factory.setCoalescing(true);
      factory.setExpandEntityReferences(false);
      factory.setIgnoringComments(true);
      factory.setIgnoringElementContentWhitespace(true);

      /*
       * Document xml_doc = factory.newDocumentBuilder().parse(
       * CommonUtils.loadResource(file_loc));
       */

      LOGGER.info("Fetching survey file " + filename + " from database for " + this.studyName);
      InputStream surveyFileInputStream = this.db.getXmlFileFromDatabase(filename);

      if (surveyFileInputStream == null) {
        throw new FileNotFoundException();
      }

      Document xmlDoc = factory.newDocumentBuilder().parse(surveyFileInputStream);

      s = new Survey(xmlDoc, this);
      if (s != null) {
        sid = s.getId();
        this.surveys.put(sid, s);
      }

    } catch (DOMException e) {
      LOGGER.error(
          "WISE - SURVEY parse error: " + e.toString() + "\n" + this.id + "\n" + this.toString(),
          null);

    } catch (FileNotFoundException e) {
      LOGGER.error(
          "Study Space " + this.dirName + " failed to parse survey " + filename + ". Error: " + e,
          e);
    } catch (SAXException e) {
      LOGGER.error(
          "Study Space " + this.dirName + " failed to parse survey " + filename + ". Error: " + e,
          e);
    } catch (ParserConfigurationException e) {
      LOGGER.error(
          "Study Space " + this.dirName + " failed to parse survey " + filename + ". Error: " + e,
          e);
    } catch (IOException e) {
      LOGGER.error(
          "Study Space " + this.dirName + " failed to parse survey " + filename + ". Error: " + e,
          e);
    }
    return sid;
  }
예제 #5
0
파일: PlacesFile.java 프로젝트: edask/IMAPI
  public PlacesFile() throws ParserConfigurationException {

    // this.setErrorMessage(ApiConstants.IMAPISuccessCode, "");

    try {
      this.builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();

      this.document =
          builder.parse(ApiConfigClass.class.getResourceAsStream("/PlacesTranslation(TypeB).xml"));
      XPath xpath = XPathFactory.newInstance().newXPath();

      if (this.XpahthPlaces != null) {
        NodeList nodesDuch =
            (NodeList) xpath.evaluate(this.XpahthPlacesDutch, document, XPathConstants.NODESET);
        NodeList nodesEnglish =
            (NodeList) xpath.evaluate(this.XpahthPlacesEnglish, document, XPathConstants.NODESET);
        if (nodesDuch != null && nodesEnglish != null) {

          int howmanyNodes = nodesDuch.getLength();

          for (int i = 0; i < howmanyNodes; i++) {

            String Dutch = "", English = "";

            Node xNodeDuch = nodesDuch.item(i);
            Dutch = xNodeDuch.getNodeValue();

            Node xNodeEnglish = nodesEnglish.item(i);
            try {
              English = xNodeEnglish.getNodeValue();
            } catch (DOMException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }

            this.placesTrans.put(Dutch, English);
          }
        }
      }

    } catch (SAXException e) {
      String tempMsg = "SAXException occured:\r\n" + e.getMessage();
      this.setErrorMessage(ApiConstants.IMAPIFailCode, tempMsg);
      Utilities.handleException(e);
    } catch (IOException e) {
      String tempMsg = "IOException occured:\r\n" + e.getMessage();
      this.setErrorMessage(ApiConstants.IMAPIFailCode, tempMsg);
      Utilities.handleException(e);
    } catch (XPathExpressionException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
예제 #6
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;
  }
  private static PlaceRecord placeDataFromXml(String xmlString) {
    DocumentBuilder builder;
    String countryName = "";
    String countryCode = "";
    String placeName = "";

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    try {
      builder = factory.newDocumentBuilder();
      Document document = builder.parse(new InputSource(new StringReader(xmlString)));
      NodeList list = document.getDocumentElement().getChildNodes();
      for (int i = 0; i < list.getLength(); i++) {
        Node curr = list.item(i);

        NodeList list2 = curr.getChildNodes();

        for (int j = 0; j < list2.getLength(); j++) {

          Node curr2 = list2.item(j);
          if (curr2.getNodeName() != null) {

            if (curr2.getNodeName().equals("countryName")) {
              countryName = curr2.getTextContent();
            } else if (curr2.getNodeName().equals("countryCode")) {
              countryCode = curr2.getTextContent();
            } else if (curr2.getNodeName().equals("name")) {
              placeName = curr2.getTextContent();
            }
          }
        }
      }
    } catch (DOMException e) {
      e.printStackTrace();
    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    } catch (SAXException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    return new PlaceRecord(generateFlagURL(countryCode.toLowerCase()), countryName, placeName);
  }
예제 #8
0
 public void exploreNode(Node node, StringBuffer sVM, VMForm data) {
   try {
     if (node.getNodeType() == Node.ELEMENT_NODE) {
       NamedNodeMap attr = node.getAttributes();
       if (node.getNodeName().equals("valuemeaning")) {
         sVM.delete(0, sVM.length());
         sVM.append(attr.getNamedItem("editvmname").getNodeValue());
         // call teh vm to validate other vm and store new one
         readVMdata(attr, data, true);
       }
       System.out.println(">>>concept vm " + sVM.toString());
       if (node.getNodeName().equals("concept")
           && attr.getNamedItem("vm") != null
           && attr.getNamedItem("vm").getNodeValue().equals(sVM.toString())) {
         System.out.println("get concepts vector " + attr.getNamedItem("vm").getNodeValue());
         // call con method to validate con and store it back in the data
         readConData(attr, data);
       }
       // validate the last VM
       if (node.getNodeName().equals("property")
           && attr.getNamedItem("vmid") != null
           && attr.getNamedItem("vmid").getNodeValue().equals("vmend")) {
         // call teh vm to validate other vm and store new one
         readVMdata(attr, data, false);
       }
       // go to next child
       NodeList children = node.getChildNodes();
       for (int x = 0; x < children.getLength(); x++) {
         System.out.println(
             x + " parent " + node.getNodeName() + " child : " + children.item(x).getNodeName());
         if (children.item(x) != null) {
           System.out.println(" explore node called ");
           exploreNode(children.item(x), sVM, data);
         }
       }
     }
   } catch (DOMException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
 @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));
   }
 }
예제 #11
0
  /**
   * Generates an XML Element representing a single SearchResponse in the format expected by a
   * SearchResponseMessage.
   *
   * @param response The SearchResponse to generate XML for
   * @return The generated XML element
   */
  public static Element serializeSearchResponse(SearchResponse response) {
    Document document = TransformerHelper.newDocument();

    Element searchResult = document.createElement(X_SEARCH_RESULT);
    searchResult.setAttribute(X_TITLE, response.getTitle());
    searchResult.setAttribute(X_RESOURCE_ID, response.getId());
    searchResult.setAttribute(X_FILENAME, response.getFileName());

    // Add article DOM as a child of the searchResult
    try {
      NodeList copyNodes = response.getResourceDOM().getChildNodes();
      for (int k = 0; k < copyNodes.getLength(); k++) {
        Node importedNode = document.importNode(copyNodes.item(k), true);
        searchResult.appendChild(importedNode);
      }

    } catch (DOMException e) {
      e.printStackTrace(); // just output the trace and continue
    }

    return searchResult;
  }
예제 #12
0
 public File saveAsXml(DataLayerInterface dataLayer) {
   File file = null;
   try {
     file = File.createTempFile("unfoldedNet", ".xml");
     file.deleteOnExit();
     DataLayerWriter writer = new DataLayerWriter(dataLayer);
     writer.savePNML(file);
   } catch (NullPointerException e) {
     e.printStackTrace();
   } catch (DOMException e) {
     e.printStackTrace();
   } catch (TransformerConfigurationException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } catch (ParserConfigurationException e) {
     e.printStackTrace();
   } catch (TransformerException e) {
     e.printStackTrace();
   }
   return file;
 }
예제 #13
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();
  }
예제 #14
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;
  }
예제 #15
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);
    }
  }
예제 #16
0
  public void addWindowPair(WindowPairs win, int nwin, Telescope tel) {

    nodelist = this.document.getElementsByTagName("RESOURCE");

    // if telescope is flipped such that east is left, then take account
    double dir = 1.0;
    if (tel.flipped) dir = -1.0;

    // System.out.println("adding window pair " + nwin);

    // now - does this window already exist? If it does there's nothing more to do.
    for (int i = 0; i < nodelist.getLength(); i++) {
      Element elem = (Element) nodelist.item(i);
      String check = "WindowPair" + nwin;
      if (elem.hasAttribute("ID") && elem.getAttribute("ID").equals(check)) {
        // OK, it exists, let's bail
        // System.out.println("Window Pair " + nwin + " already exists.");
        return;
      }
    }

    // OK - it doesn't exist so let's put it in!
    // get a template for a window descriptor by editing the main window resource

    // Get elements containing the whole FoV resource and the full CCD Resource
    Element ccdRes = null;
    Element fovRes = null;
    for (int i = 0; i < nodelist.getLength(); i++) {
      Element elem = (Element) nodelist.item(i);
      if (elem.hasAttribute("ID") && elem.getAttribute("ID").equals("WCCD"))
        // this is the resource element detailing the main window
        ccdRes = (Element) elem;
      if (elem.hasAttribute("ID") && elem.getAttribute("ID").equals("UCAM_FoV"))
        // this is the resource element detailing the whole FOV
        fovRes = (Element) elem;
    }

    // let's try copying the ccd Resource element to a window resource element.
    Element winRes1 = null;
    winRes1 = (Element) ccdRes.cloneNode(true);

    // change resource name
    String id = "WindowPair" + nwin;
    winRes1.setAttribute("ID", id);
    winRes1.setAttribute("name", id);
    // change rest of attributes
    winRes1.normalize();
    nodelist = winRes1.getChildNodes();
    for (int i = 0; i < nodelist.getLength(); i++) {
      if (nodelist.item(i).getNodeType() == 1) {
        Element elem = (Element) nodelist.item(i);
        // description
        if (elem.getTagName().equals("DESCRIPTION")) elem.setTextContent("An ULTRACAM window");
        // Short Description
        if (elem.hasAttribute("ShortDescription"))
          elem.setAttribute("ShortDescription", "Left Window of Pair");
        if (elem.getTagName().equals("TABLE") && elem.hasAttribute("ID")) {
          elem.setAttribute("ID", "LWin");
          elem.setAttribute("name", "Lwin");
        }
      }
    }

    // The right window of the pair is represented by a second <TABLE> node in the
    // resource, so let's copy the one that's already there
    nodelist = winRes1.getElementsByTagName("TABLE");
    Element TableElem = (Element) nodelist.item(0);
    Element rightWin = (Element) TableElem.cloneNode(true);
    rightWin.setAttribute("ID", "RWin");
    rightWin.setAttribute("name", "RWin");

    winRes1.appendChild(rightWin);

    // normally we set the <TD> datatags here to the 4 corners of the window
    double x1, x2, x3, x4, y1, y2;
    double PlateScale = tel.plateScale;
    double xoff = tel.delta_x;
    double yoff = tel.delta_y;
    try {
      x1 = xoff + dir * (512 - win.getXleft(nwin)) * PlateScale;
      x3 = (x1 - dir * win.getNx(nwin) * PlateScale);
      y1 = yoff + (win.getYstart(nwin) - 512) * PlateScale;
      y2 = y1 + win.getNy(nwin) * PlateScale;
      x2 = xoff + dir * (512 - win.getXright(nwin)) * PlateScale;
      x4 = (x2 - dir * win.getNx(nwin) * PlateScale);
      nodelist = winRes1.getElementsByTagName("TD");
      nodelist.item(0).setTextContent("" + x1);
      nodelist.item(1).setTextContent("" + y1);
      nodelist.item(2).setTextContent("" + x3);
      nodelist.item(3).setTextContent("" + y1);
      nodelist.item(4).setTextContent("" + x3);
      nodelist.item(5).setTextContent("" + y2);
      nodelist.item(6).setTextContent("" + x1);
      nodelist.item(7).setTextContent("" + y2);
      nodelist.item(8).setTextContent("" + x2);
      nodelist.item(9).setTextContent("" + y1);
      nodelist.item(10).setTextContent("" + x4);
      nodelist.item(11).setTextContent("" + y1);
      nodelist.item(12).setTextContent("" + x4);
      nodelist.item(13).setTextContent("" + y2);
      nodelist.item(14).setTextContent("" + x2);
      nodelist.item(15).setTextContent("" + y2);
    } catch (Exception e) {
      e.printStackTrace();
    }

    // set colour to blue
    nodelist = winRes1.getElementsByTagName("PARAM");
    for (int i = 0; i < nodelist.getLength(); i++) {
      Element elem = (Element) nodelist.item(i);
      if (elem.hasAttribute("name") && (elem.getAttribute("name").equals("color")))
        elem.setAttribute("value", "blue");
    }

    // append window to file
    try {
      fovRes.appendChild(winRes1);
    } catch (DOMException e) {
      e.printStackTrace();
    }
  }
예제 #17
0
  /** put our keywords into the XML description */
  protected static String swapKeywords(
      final DetectionEvent detection,
      final Status currentLocation,
      final String weapon,
      final TargetType theTarget) {
    // amend string template to include available parameters
    final Float brg_degs = detection.getBearing();
    final WorldDistance rng = detection.getRange();

    // take a copy of the string
    String working = new String(weapon);

    // swap the bearing
    if (brg_degs != null) {
      final String brg_val = "" + brg_degs.floatValue();
      working = replaceAll(working, "$BRG$", brg_val);
    }

    // swap the range
    if (rng != null) {
      final String rng_val = "" + rng.getValueIn(WorldDistance.YARDS);
      working = replaceAll(working, "$RNG$", rng_val);
    }

    // insert the location of the target
    if (brg_degs != null) {
      final float brg_val = brg_degs.floatValue();

      // do we know range?
      if (rng != null) {
        // yes, compute target location
        final WorldVector newVector =
            new WorldVector(
                MWC.Algorithms.Conversions.Degs2Rads(brg_val),
                rng.getValueIn(WorldDistance.DEGS),
                0);
        final WorldLocation newLoc = currentLocation.getLocation().add(newVector);

        // produce strings from this location
        final String theDepth = "" + newLoc.getDepth();
        final String theLat = "" + newLoc.getLat();
        final String theLong = "" + newLoc.getLong();

        // put these strings into the new behaviour
        working = replaceAll(working, "$TGT_DEPTH$", theDepth);
        working = replaceAll(working, "$TGT_LAT$", theLat);
        working = replaceAll(working, "$TGT_LONG$", theLong);

      } else {
        // no, send the weapon down a bearing for XXXX yds
        // compute target location
        final double TGT_RANGE = 5000;
        final WorldVector newVector =
            new WorldVector(
                MWC.Algorithms.Conversions.Degs2Rads(brg_val),
                MWC.Algorithms.Conversions.Yds2Degs(TGT_RANGE),
                0);
        final WorldLocation newLoc = currentLocation.getLocation().add(newVector);

        // produce strings from this location
        final String theDepth = "" + newLoc.getDepth();
        final String theLat = "" + newLoc.getLat();
        final String theLong = "" + newLoc.getLong();

        // put these strings into the new behaviour
        working = replaceAll(working, "$TGT_DEPTH$", theDepth);
        working = replaceAll(working, "$TGT_LAT$", theLat);
        working = replaceAll(working, "$TGT_LONG$", theLong);
      }
    }

    if (theTarget != null) {
      // output the XML header stuff
      // output the plot
      final java.io.StringWriter newString = new StringWriter();
      //      final com.sun.xml.tree.XmlDocument doc = new com.sun.xml.tree.XmlDocument();
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      Document doc = null;
      try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        doc = builder.newDocument();
        final org.w3c.dom.Element type =
            ASSET.Util.XML.Decisions.Util.TargetTypeHandler.getElement(theTarget, doc);
        doc.appendChild(type);
        doc.setNodeValue(type.getTagName());
        //    doc.changeNodeOwner(type);
        //   doc.setSystemId("ASSET XML Version 1.0");

        // Use a Transformer for output
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer();

        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(newString);
        transformer.transform(source, result);
      } catch (ParserConfigurationException e) {
        e.printStackTrace(); // To change body of catch statement use Options | File Templates.
      } catch (DOMException e) {
        e.printStackTrace(); // To change body of catch statement use Options | File Templates.
      } catch (TransformerFactoryConfigurationError transformerFactoryConfigurationError) {
        transformerFactoryConfigurationError
            .printStackTrace(); // To change body of catch statement use Options | File Templates.
      } catch (TransformerException e) {
        e.printStackTrace(); // To change body of catch statement use Options | File Templates.
      }

      //      // ok, we should be done now
      //      try
      //      {
      //        doc.write(newString);
      //      }
      //      catch(java.io.IOException e)
      //      {
      //        e.printStackTrace();
      //      }

      // try to extract the <target type portion
      if (newString != null) {
        final String val = newString.toString();
        final String startIdentifier = "<TargetType";
        final String endIdentifier = "</TargetType";
        final int start = val.indexOf(startIdentifier);
        final int end = val.lastIndexOf(endIdentifier);
        final String detail = val.substring(start, end + endIdentifier.length() + 1);

        // lastly, replace the string
        working = replaceAll(working, "<TargetType/>", detail);
      }
    }

    return working;
  }
예제 #18
0
  /**
   * marshall xml for keywords into theme and place keyword objects
   *
   * @return
   */
  void handleKeywords() {
    String tagName = FgdcTag.KeywordsHeader.getTagName();
    String tagValue = "";
    List<ThemeKeywords> themeKeywordList = new ArrayList<ThemeKeywords>();
    List<PlaceKeywords> placeKeywordList = new ArrayList<PlaceKeywords>();

    NodeList nodes = document.getElementsByTagName(tagName);
    if (nodes.getLength() == 0) {
      logger.info("no nodes under keyword");
      tagValue = null; // no keywords
    } else {
      Node keywordHeader = nodes.item(0);
      logger.info(keywordHeader.getNodeName());

      if (keywordHeader.hasChildNodes()) {
        NodeList keywordNodeList = keywordHeader.getChildNodes();
        for (int j = 0; j < keywordNodeList.getLength(); j++) {
          Node currentKeywordNode = keywordNodeList.item(j);
          if (currentKeywordNode
              .getNodeName()
              .equalsIgnoreCase(FgdcTag.PlaceKeywordsHeader.getTagName())) {
            logger.info("attempting to add place keyword node...");
            // add the contents of this node to place keywords
            PlaceKeywords placeKeywords = new PlaceKeywords();
            NodeList currentKeywordChildren = currentKeywordNode.getChildNodes();
            for (int i = 0; i < currentKeywordChildren.getLength(); i++) {
              Node currentKeywordChild = currentKeywordChildren.item(i);
              if (currentKeywordChild.getNodeType() == 1) {
                logger.info("node name: " + currentKeywordChild.getNodeName());
                if (currentKeywordChild
                    .getNodeName()
                    .equalsIgnoreCase(FgdcTag.PlaceKeywordsThesaurus.getTagName())) {
                  logger.info("thesaurus: " + currentKeywordChild.getTextContent());
                  try {
                    String rawThesaurus = getValidValue(currentKeywordChild.getTextContent());
                    PlaceKeywordThesaurus keywordThesaurus =
                        placeKeywordThesaurusResolver.getPlaceKeywordThesaurus(rawThesaurus);
                    placeKeywords.setKeywordThesaurus(keywordThesaurus);

                  } catch (DOMException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                  } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                  }
                } else if (currentKeywordChild
                    .getNodeName()
                    .equalsIgnoreCase(FgdcTag.PlaceKeywords.getTagName())) {
                  logger.info("keyword: " + currentKeywordChild.getTextContent());
                  try {
                    placeKeywords.addKeyword(getValidValue(currentKeywordChild.getTextContent()));
                  } catch (DOMException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                  } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                  }
                }
              }
            }
            placeKeywordList.add(placeKeywords);
          } else if (currentKeywordNode
              .getNodeName()
              .equalsIgnoreCase(FgdcTag.ThemeKeywordsHeader.getTagName())) {
            logger.info("attempting to add theme keyword node...");
            // add the contents of this node to theme keywords
            ThemeKeywords themeKeywords = new ThemeKeywords();
            NodeList currentKeywordChildren = currentKeywordNode.getChildNodes();
            for (int i = 0; i < currentKeywordChildren.getLength(); i++) {
              Node currentKeywordChild = currentKeywordChildren.item(i);

              if (currentKeywordChild.getNodeType() == 1) {
                // logger.info("node value: " + currentKeywordChild.getNodeValue());
                logger.info("node name: " + currentKeywordChild.getNodeName());
                // logger.info("node type: " + currentKeywordChild.getNodeType());
                if (currentKeywordChild
                    .getNodeName()
                    .equalsIgnoreCase(FgdcTag.ThemeKeywordsThesaurus.getTagName())) {
                  logger.info("thesaurus: " + currentKeywordChild.getTextContent());
                  try {
                    String rawThesaurus = getValidValue(currentKeywordChild.getTextContent());
                    ThemeKeywordThesaurus keywordThesaurus =
                        themeKeywordThesaurusResolver.getThemeKeywordThesaurus(rawThesaurus);
                    themeKeywords.setKeywordThesaurus(keywordThesaurus);
                  } catch (DOMException e) {

                  } catch (Exception e) {
                  }
                } else if (currentKeywordChild
                    .getNodeName()
                    .equalsIgnoreCase(FgdcTag.ThemeKeywords.getTagName())) {
                  logger.info("keyword: " + currentKeywordChild.getTextContent());
                  try {
                    themeKeywords.addKeyword(getValidValue(currentKeywordChild.getTextContent()));
                  } catch (DOMException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                  } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                  }
                }
              }
            }
            themeKeywordList.add(themeKeywords);
          }
        }
      }
    }
    this.metadataParseResponse.metadata.setThemeKeywords(themeKeywordList);
    this.metadataParseResponse.metadata.setPlaceKeywords(placeKeywordList);
  }
예제 #19
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);
    }
  }
예제 #20
0
  /**
   * creates a new image
   *
   * @param svgHandle a svg handle
   * @param resourceId the id of the resource from which the image will be created
   */
  protected void createNewImage(SVGHandle svgHandle, String resourceId) {

    if (svgHandle != null && resourceId != null && !resourceId.equals("")) {

      Element resourceElement = null;

      resourceElement =
          svgHandle.getScrollPane().getSVGCanvas().getDocument().getElementById(resourceId);

      final String fresourceId = resourceId;

      if (resourceElement != null) {

        final SVGHandle fhandle = svgHandle;

        // creating the canvas and setting its properties
        final JSVGCanvas canvas =
            new JSVGCanvas() {

              @Override
              public void dispose() {

                removeKeyListener(listener);
                removeMouseMotionListener(listener);
                removeMouseListener(listener);
                disableInteractions = true;
                selectableText = false;
                userAgent = null;

                bridgeContext.dispose();
                super.dispose();
              }
            };

        // the element to be added
        Element elementToAdd = null;

        canvas.setDocumentState(JSVGComponent.ALWAYS_STATIC);
        canvas.setDisableInteractions(true);

        // creating the new document
        final String svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI;
        final SVGDocument doc = (SVGDocument) resourceElement.getOwnerDocument().cloneNode(false);

        // creating the root element
        final Element root =
            (Element)
                doc.importNode(resourceElement.getOwnerDocument().getDocumentElement(), false);
        doc.appendChild(root);

        // removing all the attributes of the root element
        NamedNodeMap attributes = doc.getDocumentElement().getAttributes();

        for (int i = 0; i < attributes.getLength(); i++) {

          if (attributes.item(i) != null) {

            doc.getDocumentElement().removeAttribute(attributes.item(i).getNodeName());
          }
        }

        // adding the new attributes for the root
        root.setAttributeNS(null, "width", imageSize.width + "");
        root.setAttributeNS(null, "height", imageSize.height + "");
        root.setAttributeNS(null, "viewBox", "0 0 " + imageSize.width + " " + imageSize.height);

        // the defs element that will contain the cloned resource node
        final Element defs = (Element) doc.importNode(resourceElement.getParentNode(), true);
        root.appendChild(defs);

        if (resourceElement.getNodeName().equals("linearGradient")
            || resourceElement.getNodeName().equals("radialGradient")
            || resourceElement.getNodeName().equals("pattern")) {

          // the rectangle that will be drawn
          final Element rect = doc.createElementNS(svgNS, "rect");
          rect.setAttributeNS(null, "x", "0");
          rect.setAttributeNS(null, "y", "0");
          rect.setAttributeNS(null, "width", imageSize.width + "");
          rect.setAttributeNS(null, "height", imageSize.height + "");

          elementToAdd = rect;

          // setting that the rectangle uses the resource
          String id = resourceElement.getAttribute("id");

          if (id == null) {

            id = "";
          }

          rect.setAttributeNS(null, "style", "fill:url(#" + id + ");");

          // getting the cloned resource node
          Node cur = null;
          Element clonedResourceElement = null;
          String id2 = "";

          for (cur = defs.getFirstChild(); cur != null; cur = cur.getNextSibling()) {

            if (cur instanceof Element) {

              id2 = ((Element) cur).getAttribute("id");

              if (id2 != null && id.equals(id2)) {

                clonedResourceElement = (Element) cur;
              }
            }
          }

          if (clonedResourceElement != null) {

            // getting the root element of the initial resource
            // element
            Element initialRoot = resourceElement.getOwnerDocument().getDocumentElement();

            // getting the width and height of the initial root
            // element
            double initialWidth = 0, initialHeight = 0;

            try {
              initialWidth =
                  EditorToolkit.getPixelledNumber(initialRoot.getAttributeNS(null, "width"));
              initialHeight =
                  EditorToolkit.getPixelledNumber(initialRoot.getAttributeNS(null, "height"));
            } catch (DOMException ex) {
              ex.printStackTrace();
            }

            if (resourceElement.getNodeName().equals("linearGradient")) {

              if (resourceElement.getAttributeNS(null, "gradientUnits").equals("userSpaceOnUse")) {

                double x1 = 0, y1 = 0, x2 = 0, y2 = 0;

                // normalizing the values for the vector to fit
                // the rectangle
                try {
                  x1 = Double.parseDouble(resourceElement.getAttributeNS(null, "x1"));
                  y1 = Double.parseDouble(resourceElement.getAttributeNS(null, "y1"));
                  x2 = Double.parseDouble(resourceElement.getAttributeNS(null, "x2"));
                  y2 = Double.parseDouble(resourceElement.getAttributeNS(null, "y2"));

                  x1 = x1 / initialWidth * imageSize.width;
                  y1 = y1 / initialHeight * imageSize.height;
                  x2 = x2 / initialWidth * imageSize.width;
                  y2 = y2 / initialHeight * imageSize.height;
                } catch (NumberFormatException | DOMException ex) {
                  ex.printStackTrace();
                }

                clonedResourceElement.setAttributeNS(null, "x1", format.format(x1));
                clonedResourceElement.setAttributeNS(null, "y1", format.format(y1));
                clonedResourceElement.setAttributeNS(null, "x2", format.format(x2));
                clonedResourceElement.setAttributeNS(null, "y2", format.format(y2));
              }

            } else if (resourceElement.getNodeName().equals("radialGradient")) {

              if (resourceElement.getAttributeNS(null, "gradientUnits").equals("userSpaceOnUse")) {

                double cx = 0, cy = 0, r = 0, fx = 0, fy = 0;

                // normalizing the values for the circle to fit
                // the rectangle
                try {
                  cx = Double.parseDouble(resourceElement.getAttributeNS(null, "cx"));
                  cy = Double.parseDouble(resourceElement.getAttributeNS(null, "cy"));
                  r = Double.parseDouble(resourceElement.getAttributeNS(null, "r"));
                  fx = Double.parseDouble(resourceElement.getAttributeNS(null, "fx"));
                  fy = Double.parseDouble(resourceElement.getAttributeNS(null, "fy"));

                  cx = cx / initialWidth * imageSize.width;
                  cy = cy / initialHeight * imageSize.height;

                  r =
                      r
                          / (Math.abs(
                              Math.sqrt(Math.pow(initialWidth, 2) + Math.pow(initialHeight, 2))))
                          * Math.abs(
                              Math.sqrt(
                                  Math.pow(imageSize.width, 2) + Math.pow(imageSize.width, 2)));

                  fx = fx / initialWidth * imageSize.width;
                  fy = fy / initialHeight * imageSize.height;
                } catch (NumberFormatException | DOMException ex) {
                  ex.printStackTrace();
                }

                clonedResourceElement.setAttributeNS(null, "cx", format.format(cx));
                clonedResourceElement.setAttributeNS(null, "cy", format.format(cy));
                clonedResourceElement.setAttributeNS(null, "r", format.format(r));
                clonedResourceElement.setAttributeNS(null, "fx", format.format(fx));
                clonedResourceElement.setAttributeNS(null, "fy", format.format(fy));
              }

            } else if (resourceElement.getNodeName().equals("pattern")) {

              if (resourceElement.getAttributeNS(null, "patternUnits").equals("userSpaceOnUse")) {

                double x = 0, y = 0, w = 0, h = 0;

                // normalizing the values for the vector to fit
                // the rectangle
                try {
                  String xString = resourceElement.getAttributeNS(null, "x");
                  if (!xString.equals("")) {
                    x = Double.parseDouble(xString);
                  }
                  String yString = resourceElement.getAttributeNS(null, "y");
                  if (!yString.equals("")) {
                    y = Double.parseDouble(yString);
                  }
                  String wString = resourceElement.getAttributeNS(null, "w");
                  if (!wString.equals("")) {
                    w = Double.parseDouble(wString);
                  }
                  String hString = resourceElement.getAttributeNS(null, "h");
                  if (!hString.equals("")) {
                    h = Double.parseDouble(hString);
                  }

                  x = x / initialWidth * imageSize.width;
                  y = y / initialHeight * imageSize.height;
                  w = w / initialWidth * imageSize.width;
                  h = h / initialHeight * imageSize.height;
                } catch (NumberFormatException | DOMException ex) {
                  ex.printStackTrace();
                }

                clonedResourceElement.setAttributeNS(null, "x", format.format(x));
                clonedResourceElement.setAttributeNS(null, "y", format.format(y));
                clonedResourceElement.setAttributeNS(null, "width", format.format(w));
                clonedResourceElement.setAttributeNS(null, "height", format.format(h));
              }
            }
          }

        } else if (resourceElement.getNodeName().equals("marker")) {

          // the line that will be drawn
          final Element line = doc.createElementNS(svgNS, "line");
          line.setAttributeNS(null, "x1", (((double) imageSize.width) / 2) + "");
          line.setAttributeNS(null, "y1", (((double) imageSize.height) / 2) + "");
          line.setAttributeNS(null, "x2", ((double) imageSize.width / 2) + "");
          line.setAttributeNS(null, "y2", imageSize.height + "");

          elementToAdd = line;

          // setting that the line uses the resource
          String id = resourceElement.getAttribute("id");
          if (id == null) id = "";
          line.setAttributeNS(
              null, "style", "stroke:none;fill:none;marker-start:url(#" + id + ");");
        }

        root.appendChild(elementToAdd);

        // adding a rendering listener to the canvas
        GVTTreeRendererAdapter gVTTreeRendererAdapter =
            new GVTTreeRendererAdapter() {

              @Override
              public void gvtRenderingCompleted(GVTTreeRendererEvent evt) {

                Image bufferedImage = canvas.getOffScreen();

                if (bufferedImage != null) {

                  Graphics g = bufferedImage.getGraphics();
                  Color borderColor = MetalLookAndFeel.getSeparatorForeground();

                  g.setColor(borderColor);
                  g.drawRect(0, 0, imageSize.width - 1, imageSize.height - 1);
                }

                setImage(fhandle, fresourceId, bufferedImage);

                // refreshing the panels that have been created when no
                // image was available for them
                Image image = null;

                for (ResourceRepresentation resourceRepresentation :
                    new LinkedList<ResourceRepresentation>(resourceRepresentationList)) {

                  if (resourceRepresentation != null) {

                    resourceRepresentation.refreshRepresentation();
                    image = resourceRepresentation.getImage();

                    if (image != null) {

                      resourceRepresentationList.remove(resourceRepresentation);
                    }
                  }
                }

                canvas.removeGVTTreeRendererListener(this);
                canvas.stopProcessing();
                canvas.dispose();
              }
            };

        canvas.addGVTTreeRendererListener(gVTTreeRendererAdapter);

        // setting the document for the canvas
        canvas.setSVGDocument(doc);

        canvas.setBackground(Color.white);
        canvas.setBounds(1, 1, imageSize.width, imageSize.height);
      }
    }
  }
  @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);
    }
  }
예제 #22
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();
  }