Exemple #1
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());
      }
  }
  @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!");
    }
  }
Exemple #3
0
  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();
    }
  }
  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);
  }
Exemple #5
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();
   }
 }
Exemple #6
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;
 }
  /**
   * 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;
  }
  /**
   * 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;
  }
Exemple #9
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();
    }
  }
  /**
   * 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);
      }
    }
  }
  /**
   * 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);
  }
Exemple #12
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;
  }