@Override
  protected Transferable createTransferable(JComponent c) {
    JTextPane aTextPane = (JTextPane) c;

    HTMLEditorKit kit = ((HTMLEditorKit) aTextPane.getEditorKit());
    StyledDocument sdoc = aTextPane.getStyledDocument();
    int sel_start = aTextPane.getSelectionStart();
    int sel_end = aTextPane.getSelectionEnd();

    int i = sel_start;
    StringBuilder output = new StringBuilder();
    while (i < sel_end) {
      Element e = sdoc.getCharacterElement(i);
      Object nameAttr = e.getAttributes().getAttribute(StyleConstants.NameAttribute);
      int start = e.getStartOffset(), end = e.getEndOffset();
      if (nameAttr == HTML.Tag.BR) {
        output.append("\n");
      } else if (nameAttr == HTML.Tag.CONTENT) {
        if (start < sel_start) {
          start = sel_start;
        }
        if (end > sel_end) {
          end = sel_end;
        }
        try {
          String str = sdoc.getText(start, end - start);
          output.append(str);
        } catch (BadLocationException ble) {
          Debug.error(me + "Copy-paste problem!\n%s", ble.getMessage());
        }
      }
      i = end;
    }
    return new StringSelection(output.toString());
  }
Example #2
1
  private void updateTemplateFromEditor(PrintfTemplate template) {
    ArrayList params = new ArrayList();
    String format = null;
    int text_length = editorPane.getDocument().getLength();
    try {
      format = editorPane.getDocument().getText(0, text_length);
    } catch (BadLocationException ex1) {
    }
    Element section_el = editorPane.getDocument().getDefaultRootElement();
    // Get number of paragraphs.
    int num_para = section_el.getElementCount();
    for (int p_count = 0; p_count < num_para; p_count++) {
      Element para_el = section_el.getElement(p_count);
      // Enumerate the content elements
      int num_cont = para_el.getElementCount();
      for (int c_count = 0; c_count < num_cont; c_count++) {
        Element content_el = para_el.getElement(c_count);
        AttributeSet attr = content_el.getAttributes();
        // Get the name of the style applied to this content element; may be null
        String sn = (String) attr.getAttribute(StyleConstants.NameAttribute);
        // Check if style name match
        if (sn != null && sn.startsWith("Parameter")) {
          // we extract the label.
          JLabel l = (JLabel) StyleConstants.getComponent(attr);
          if (l != null) {
            params.add(l.getName());
          }
        }
      }
    }

    template.setFormat(format);
    template.setTokens(params);
  }
  /**
   * Writes out an end tag for the element.
   *
   * @param elem an Element
   * @exception IOException on any I/O error
   */
  protected void endTag(Element elem) throws IOException {
    if (synthesizedElement(elem)) {
      return;
    }

    // write out end tags for item on stack
    closeOutUnwantedEmbeddedTags(elem.getAttributes());
    if (inContent) {
      if (!newlineOutputed && !inPre) {
        writeLineSeparator();
      }
      newlineOutputed = false;
      inContent = false;
    }
    if (!inPre) {
      indent();
    }
    if (matchNameAttribute(elem.getAttributes(), HTML.Tag.PRE)) {
      inPre = false;
    }
    write('<');
    write('/');
    write(elem.getName());
    write('>');
    writeLineSeparator();
  }
Example #4
0
  /**
   * This will invoke the <code>startElement</code> callback in the <code>ContentHandler</code>.
   *
   * @param element <code>Element</code> used in callbacks.
   * @param nsAtts <code>List</code> of namespaces to declare with the element or <code>null</code>.
   */
  private void startElement(Element element, Attributes nsAtts) throws JDOMException {
    String namespaceURI = element.getNamespaceURI();
    String localName = element.getName();
    String rawName = element.getQualifiedName();

    // Allocate attribute list.
    AttributesImpl atts = (nsAtts != null) ? new AttributesImpl(nsAtts) : new AttributesImpl();

    List attributes = element.getAttributes();
    Iterator i = attributes.iterator();
    while (i.hasNext()) {
      Attribute a = (Attribute) i.next();
      atts.addAttribute(
          a.getNamespaceURI(),
          a.getName(),
          a.getQualifiedName(),
          getAttributeTypeName(a.getAttributeType()),
          a.getValue());
    }

    try {
      contentHandler.startElement(namespaceURI, localName, rawName, atts);
    } catch (SAXException se) {
      throw new JDOMException("Exception in startElement", se);
    }
  }
Example #5
0
  /**
   * Highlight lines to start or end delimiter.
   *
   * @param content the content to parse
   * @param line the line number
   * @throws BadLocationException if offsets are wrong
   */
  protected void highlightLinesAfter(String content, int line) throws BadLocationException {
    int offset = m_RootElement.getElement(line).getEndOffset();

    // Start/End delimiter not found, nothing to do

    int startDelimiter = -1;
    int endDelimiter = -1;
    if (getMultiLineComment()) {
      startDelimiter = indexOf(content, getMultiLineCommentStart(), offset);
      endDelimiter = indexOf(content, getMultiLineCommentEnd(), offset);
    }

    if (startDelimiter < 0) startDelimiter = content.length();

    if (endDelimiter < 0) endDelimiter = content.length();

    int delimiter = Math.min(startDelimiter, endDelimiter);

    if (delimiter < offset) return;

    // Start/End delimiter found, reapply highlighting

    int endLine = m_RootElement.getElementIndex(delimiter);

    for (int i = line + 1; i < endLine; i++) {
      Element branch = m_RootElement.getElement(i);
      Element leaf = m_Self.getCharacterElement(branch.getStartOffset());
      AttributeSet as = leaf.getAttributes();

      if (as.isEqual(DEFAULT_COMMENT)) applyHighlighting(content, i);
    }
  }
Example #6
0
  private void gatherNamespaces(Element element, List<URI> namespaceSources) throws SAXException {
    NamedNodeMap attributes = element.getAttributes();
    int attributeCount = attributes.getLength();

    for (int i = 0; i < attributeCount; i++) {
      Attr attribute = (Attr) attributes.item(i);
      String namespace = attribute.getNamespaceURI();

      if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(namespace)) {
        try {
          namespaceSources.add(new URI(attribute.getValue()));
        } catch (URISyntaxException e) {
          throw new SAXException(
              "Cannot validate this document with this class.  Namespaces must be valid URIs.  Found Namespace: '"
                  + attribute.getValue()
                  + "'.",
              e);
        }
      }
    }

    NodeList childNodes = element.getChildNodes();
    int childCount = childNodes.getLength();
    for (int i = 0; i < childCount; i++) {
      Node child = childNodes.item(i);

      if (child.getNodeType() == Node.ELEMENT_NODE) {
        gatherNamespaces((Element) child, namespaceSources);
      }
    }
  }
Example #7
0
  // read all defense missile from given defense destructor
  protected void readDefenseDestructorFromGivenDestructor(Element destructor) {
    NamedNodeMap attributes = destructor.getAttributes();
    String id = "";
    String type;

    Attr attr = (Attr) attributes.item(0);

    String name = attr.getNodeName();

    // if it's iron dome
    if (name.equals("id")) {
      id = attr.getNodeValue();

      // update id's in the war
      IdGenerator.updateIronDomeId(id);
      // add to war
      war.addIronDome(id);

      NodeList destructdMissiles = destructor.getElementsByTagName("destructdMissile");
      readDefensDestructoreMissiles(destructdMissiles, id);

      // if it's launcher destructor
    } else {
      if (name.equals("type")) {
        type = attr.getNodeValue();

        // add to war
        id = war.addDefenseLauncherDestructor(type);

        NodeList destructedLanuchers = destructor.getElementsByTagName("destructedLanucher");
        readDefensDestructoreMissiles(destructedLanuchers, id);
      }
    }
  }
 @Override
 public void mouseClicked(MouseEvent me) {
   Element el = doc.getCharacterElement(viewToModel(me.getPoint()));
   if (el == null) return;
   AttributeSet as = el.getAttributes();
   if (as.isDefined("ip")) {
     String ip = (String) as.getAttribute("ip");
     ScriptException se = (ScriptException) as.getAttribute("exception");
     Node node = net.getAtIP(ip);
     if (node == null) {
       Utility.displayError("Error", "Computer does not exist");
       return;
     }
     String errorString =
         "--ERROR--\n"
             + "Error at line number "
             + se.getLineNumber()
             + " and column number "
             + se.getColumnNumber()
             + "\n"
             + se.getMessage();
     new ScriptDialog(
             parentFrame,
             str -> {
               if (str != null) {
                 node.setScript(str);
               }
             },
             node.getScript(),
             errorString)
         .setVisible(true);
   }
 }
 /** @param element */
 private void validatePlugins(Element parent) {
   NodeList list = getChildrenByName(parent, "plugin"); // $NON-NLS-1$
   for (int i = 0; i < list.getLength(); i++) {
     if (fMonitor.isCanceled()) return;
     Element plugin = (Element) list.item(i);
     assertAttributeDefined(plugin, "id", CompilerFlags.ERROR); // $NON-NLS-1$
     assertAttributeDefined(plugin, "version", CompilerFlags.ERROR); // $NON-NLS-1$
     NamedNodeMap attributes = plugin.getAttributes();
     boolean isFragment =
         plugin.getAttribute("fragment").equals("true"); // $NON-NLS-1$ //$NON-NLS-2$
     for (int j = 0; j < attributes.getLength(); j++) {
       Attr attr = (Attr) attributes.item(j);
       String name = attr.getName();
       if (name.equals("id")) { // $NON-NLS-1$
         validatePluginID(plugin, attr, isFragment);
       } else if (name.equals("version")) { // $NON-NLS-1$
         validateVersionAttribute(plugin, attr);
         validateVersion(plugin, attr);
       } else if (name.equals("fragment") || name.equals("unpack")) { // $NON-NLS-1$ //$NON-NLS-2$
         validateBoolean(plugin, attr);
       } else if (!name.equals("os")
           && !name.equals("ws")
           && !name.equals("nl") // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
           && !name.equals("arch")
           && !name.equals("download-size") // $NON-NLS-1$ //$NON-NLS-2$
           && !name.equals("install-size")
           && !name.equals("filter")) { // $NON-NLS-1$ //$NON-NLS-2$
         reportUnknownAttribute(plugin, name, CompilerFlags.ERROR);
       }
     }
     validateUnpack(plugin);
   }
 }
  /*
    Iterates through the element tree and prints
    out each element and its attributes.
  */
  private void dumpTree() {

    Element elem;
    while (true) {
      if ((elem = next()) != null) {
        System.out.println("elem: " + elem.getName());
        AttributeSet attr = elem.getAttributes();
        String s = "";
        Enumeration names = attr.getAttributeNames();
        while (names.hasMoreElements()) {
          Object key = names.nextElement();
          Object value = attr.getAttribute(key);
          if (value instanceof AttributeSet) {
            // don't go recursive
            s = s + key + "=**AttributeSet** ";
          } else {
            s = s + key + "=" + value + " ";
          }
        }
        System.out.println("attributes: " + s);
      } else {
        break;
      }
    }
  }
 /*     */ private int drawText(
     Element paramElement,
     int paramInt1,
     int paramInt2,
     Graphics paramGraphics,
     int paramInt3,
     int paramInt4)
     throws BadLocationException {
   /* 129 */ paramInt2 = Math.min(getDocument().getLength(), paramInt2);
   /* 130 */ AttributeSet localAttributeSet = paramElement.getAttributes();
   /*     */
   /* 132 */ if (Utilities.isComposedTextAttributeDefined(localAttributeSet)) {
     /* 133 */ paramGraphics.setColor(this.unselected);
     /* 134 */ paramInt3 =
         Utilities.drawComposedText(
             this,
             localAttributeSet,
             paramGraphics,
             paramInt3,
             paramInt4,
             paramInt1 - paramElement.getStartOffset(),
             paramInt2 - paramElement.getStartOffset());
     /*     */ }
   /* 138 */ else if ((this.sel0 == this.sel1) || (this.selected == this.unselected))
   /*     */ {
     /* 140 */ paramInt3 =
         drawUnselectedText(paramGraphics, paramInt3, paramInt4, paramInt1, paramInt2);
     /* 141 */ } else if ((paramInt1 >= this.sel0)
       && (paramInt1 <= this.sel1)
       && (paramInt2 >= this.sel0)
       && (paramInt2 <= this.sel1)) {
     /* 142 */ paramInt3 =
         drawSelectedText(paramGraphics, paramInt3, paramInt4, paramInt1, paramInt2);
     /* 143 */ } else if ((this.sel0 >= paramInt1) && (this.sel0 <= paramInt2)) {
     /* 144 */ if ((this.sel1 >= paramInt1) && (this.sel1 <= paramInt2)) {
       /* 145 */ paramInt3 =
           drawUnselectedText(paramGraphics, paramInt3, paramInt4, paramInt1, this.sel0);
       /* 146 */ paramInt3 =
           drawSelectedText(paramGraphics, paramInt3, paramInt4, this.sel0, this.sel1);
       /* 147 */ paramInt3 =
           drawUnselectedText(paramGraphics, paramInt3, paramInt4, this.sel1, paramInt2);
       /*     */ } else {
       /* 149 */ paramInt3 =
           drawUnselectedText(paramGraphics, paramInt3, paramInt4, paramInt1, this.sel0);
       /* 150 */ paramInt3 =
           drawSelectedText(paramGraphics, paramInt3, paramInt4, this.sel0, paramInt2);
       /*     */ }
     /* 152 */ } else if ((this.sel1 >= paramInt1) && (this.sel1 <= paramInt2)) {
     /* 153 */ paramInt3 =
         drawSelectedText(paramGraphics, paramInt3, paramInt4, paramInt1, this.sel1);
     /* 154 */ paramInt3 =
         drawUnselectedText(paramGraphics, paramInt3, paramInt4, this.sel1, paramInt2);
     /*     */ } else {
     /* 156 */ paramInt3 =
         drawUnselectedText(paramGraphics, paramInt3, paramInt4, paramInt1, paramInt2);
     /*     */ }
   /*     */
   /* 160 */ return paramInt3;
   /*     */ }
 private void validateImports(Element parent) {
   NodeList list = getChildrenByName(parent, "import"); // $NON-NLS-1$
   for (int i = 0; i < list.getLength(); i++) {
     if (fMonitor.isCanceled()) return;
     Element element = (Element) list.item(i);
     Attr plugin = element.getAttributeNode("plugin"); // $NON-NLS-1$
     Attr feature = element.getAttributeNode("feature"); // $NON-NLS-1$
     if (plugin == null && feature == null) {
       assertAttributeDefined(element, "plugin", CompilerFlags.ERROR); // $NON-NLS-1$
     } else if (plugin != null && feature != null) {
       reportExclusiveAttributes(
           element, "plugin", "feature", CompilerFlags.ERROR); // $NON-NLS-1$//$NON-NLS-2$
     } else if (plugin != null) {
       validatePluginID(element, plugin, false);
     } else if (feature != null) {
       validateFeatureID(element, feature);
     }
     NamedNodeMap attributes = element.getAttributes();
     for (int j = 0; j < attributes.getLength(); j++) {
       Attr attr = (Attr) attributes.item(j);
       String name = attr.getName();
       if (name.equals("version")) { // $NON-NLS-1$
         validateVersionAttribute(element, attr);
       } else if (name.equals("match")) { // $NON-NLS-1$
         if (element.getAttributeNode("patch") != null) { // $NON-NLS-1$
           report(
               NLS.bind(PDECoreMessages.Builders_Feature_patchedMatch, attr.getValue()),
               getLine(element, attr.getValue()),
               CompilerFlags.ERROR,
               PDEMarkerFactory.CAT_FATAL);
         } else {
           validateMatch(element, attr);
         }
       } else if (name.equals("patch")) { // $NON-NLS-1$
         if ("true".equalsIgnoreCase(attr.getValue()) && feature == null) { // $NON-NLS-1$
           report(
               NLS.bind(PDECoreMessages.Builders_Feature_patchPlugin, attr.getValue()),
               getLine(element, attr.getValue()),
               CompilerFlags.ERROR,
               PDEMarkerFactory.CAT_FATAL);
         } else if ("true".equalsIgnoreCase(attr.getValue())
             && element.getAttributeNode("version") == null) { // $NON-NLS-1$ //$NON-NLS-2$
           report(
               NLS.bind(PDECoreMessages.Builders_Feature_patchedVersion, attr.getValue()),
               getLine(element, attr.getValue()),
               CompilerFlags.ERROR,
               PDEMarkerFactory.CAT_FATAL);
         } else {
           validateBoolean(element, attr);
         }
       } else if (!name.equals("plugin")
           && !name.equals("feature")
           && !name.equals("filter")) { // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
         reportUnknownAttribute(element, name, CompilerFlags.ERROR);
       }
     }
   }
 }
Example #13
0
 /** Convert the attributes in the given XML Element into a Map of name/value pairs. */
 protected static Map createAttributeMap(Element el) {
   Log.debug("Creating attribute map for " + el);
   Map attributes = new HashMap();
   Iterator iter = el.getAttributes().iterator();
   while (iter.hasNext()) {
     Attribute att = (Attribute) iter.next();
     attributes.put(att.getName(), att.getValue());
   }
   return attributes;
 }
 @Override
 public void mouseMoved(MouseEvent me) {
   Element el = doc.getCharacterElement(viewToModel(me.getPoint()));
   if (el == null) return;
   AttributeSet as = el.getAttributes();
   if (as.isDefined("ip")) {
     setCursor(handCursor);
   } else {
     setCursor(defaultCursor);
   }
 }
 /**
  * Writes out comments.
  *
  * @param elem an Element
  * @exception IOException on any I/O error
  * @exception BadLocationException if pos represents an invalid location within the document.
  */
 protected void comment(Element elem) throws BadLocationException, IOException {
   AttributeSet as = elem.getAttributes();
   if (matchNameAttribute(as, HTML.Tag.COMMENT)) {
     Object comment = as.getAttribute(HTML.Attribute.COMMENT);
     if (comment instanceof String) {
       writeComment((String) comment);
     } else {
       writeComment(null);
     }
   }
 }
 protected Element copyElementToName(Element element, String tagName) {
   Element newElement = element.getOwnerDocument().createElement(tagName);
   NamedNodeMap attrs = element.getAttributes();
   for (int i = 0; i < attrs.getLength(); i++) {
     Node attribute = attrs.item(i);
     newElement.setAttribute(attribute.getNodeName(), attribute.getNodeValue());
   }
   for (int i = 0; i < element.getChildNodes().getLength(); i++) {
     newElement.appendChild(element.getChildNodes().item(i).cloneNode(true));
   }
   return newElement;
 }
Example #17
0
 // dump and element
 public void dump(Element e) throws Exception {
   System.out.println("Element " + e.getNodeName());
   NamedNodeMap attrs = e.getAttributes();
   for (int i = 0; i < attrs.getLength(); i++) {
     Attr attr = (Attr) attrs.item(i);
     System.out.println("  " + attr.getName() + "=" + attr.getValue());
   }
   NodeList nodes = e.getChildNodes();
   for (int i = 0; i < nodes.getLength(); i++) {
     Node node = nodes.item(i);
     if (node instanceof Element) dump((Element) node);
   }
 }
 /**
  * Creates a {@link View} for the specified <code>Element</code>.
  *
  * @param element the <code>Element</code> to create a <code>View</code> for
  * @return the <code>View</code> for the specified <code>Element</code> or <code>null</code> if
  *     the type of <code>element</code> is not supported
  */
 public View create(Element element) {
   View view = null;
   Object attr = element.getAttributes().getAttribute(StyleConstants.NameAttribute);
   if (attr instanceof HTML.Tag) {
     HTML.Tag tag = (HTML.Tag) attr;
     if (tag.equals(HTML.Tag.IMPLIED) || tag.equals(HTML.Tag.P)) {
       view = new MinParagraphView(element);
     } else if (tag.equals(HTML.Tag.OBJECT)) {
       view = new ConstObjectView(element, map);
     }
   }
   return (view != null ? view : super.create(element));
 }
 private void validateInstallHandler(Element element) {
   NodeList elements = getChildrenByName(element, "install-handler"); // $NON-NLS-1$
   if (elements.getLength() > 0) {
     if (fMonitor.isCanceled()) return;
     Element handler = (Element) elements.item(0);
     NamedNodeMap attributes = handler.getAttributes();
     for (int i = 0; i < attributes.getLength(); i++) {
       String name = attributes.item(i).getNodeName();
       if (!name.equals("library") && !name.equals("handler")) // $NON-NLS-1$ //$NON-NLS-2$
       reportUnknownAttribute(handler, name, CompilerFlags.ERROR);
     }
     reportExtraneousElements(elements, 1);
   }
 }
Example #20
0
  /**
   * Get the default namespace associated with the supplied element.
   *
   * @param element The element to be checked.
   * @return The default namespace, or null if none was found.
   */
  public static String getDefaultNamespace(Element element) {
    NamedNodeMap attributes = element.getAttributes();
    int attributeCount = attributes.getLength();

    for (int i = 0; i < attributeCount; i++) {
      Attr attribute = (Attr) attributes.item(i);

      if (XMLConstants.XMLNS_ATTRIBUTE.equals(attribute.getName())
          && XMLConstants.XMLNS_ATTRIBUTE.equals(attribute.getLocalName())) {
        return attribute.getValue();
      }
    }

    return null;
  }
  public void validateContent(IProgressMonitor monitor) {
    Element element = getDocumentRoot();
    if (element == null) return;
    String elementName = element.getNodeName();
    if (!"plugin".equals(elementName)
        && !"fragment".equals(elementName)) { // $NON-NLS-1$ //$NON-NLS-2$
      reportIllegalElement(element, CompilerFlags.ERROR);
    } else {
      int severity = CompilerFlags.getFlag(fProject, CompilerFlags.P_DEPRECATED);
      if (severity != CompilerFlags.IGNORE) {
        NamedNodeMap attrs = element.getAttributes();
        for (int i = 0; i < attrs.getLength(); i++) {
          reportUnusedAttribute(element, attrs.item(i).getNodeName(), severity);
        }
      }

      NodeList children = element.getChildNodes();
      for (int i = 0; i < children.getLength(); i++) {
        if (monitor.isCanceled()) break;
        Element child = (Element) children.item(i);
        String name = child.getNodeName();
        if (name.equals("extension")) { // $NON-NLS-1$
          validateExtension(child);
        } else if (name.equals("extension-point")) { // $NON-NLS-1$
          validateExtensionPoint(child);
        } else {
          if (!name.equals("runtime") && !name.equals("requires")) { // $NON-NLS-1$ //$NON-NLS-2$
            severity = CompilerFlags.getFlag(fProject, CompilerFlags.P_UNKNOWN_ELEMENT);
            if (severity != CompilerFlags.IGNORE) reportIllegalElement(child, severity);
          } else {
            severity = CompilerFlags.getFlag(fProject, CompilerFlags.P_DEPRECATED);
            if (severity != CompilerFlags.IGNORE) reportUnusedElement(child, severity);
          }
        }
      }

      IExtensions extensions = fModel.getExtensions();
      if (extensions != null
          && extensions.getExtensions().length == 0
          && extensions.getExtensionPoints().length == 0)
        report(
            MDECoreMessages.Builders_Manifest_useless_file,
            -1,
            IMarker.SEVERITY_WARNING,
            MDEMarkerFactory.P_USELESS_FILE,
            MDEMarkerFactory.CAT_OTHER);
    }
  }
Example #22
0
 void editorPane_keyPressed(KeyEvent e) {
   StyledDocument doc = editorPane.getStyledDocument();
   int pos = editorPane.getCaretPosition();
   int code = e.getKeyCode();
   Element el;
   switch (code) {
     case KeyEvent.VK_BACK_SPACE:
     case KeyEvent.VK_DELETE:
     case KeyEvent.VK_LEFT:
     case KeyEvent.VK_KP_LEFT:
       if (pos == 0) return;
       // we want to get the element to the left of position.
       el = doc.getCharacterElement(pos - 1);
       break;
     case KeyEvent.VK_RIGHT:
     case KeyEvent.VK_KP_RIGHT:
       // we want to get the element to the right of position.
       el = doc.getCharacterElement(pos + 1);
       break;
     default:
       return; // bail we don't handle it.
   }
   AttributeSet attr = el.getAttributes();
   String el_name = (String) attr.getAttribute(StyleConstants.NameAttribute);
   int el_range = el.getEndOffset() - el.getStartOffset() - 1;
   if (el_name.startsWith("Parameter") && StyleConstants.getComponent(attr) != null) {
     try {
       switch (code) {
         case KeyEvent.VK_BACK_SPACE:
         case KeyEvent.VK_DELETE:
           doc.remove(el.getStartOffset(), el_range);
           break;
         case KeyEvent.VK_LEFT:
         case KeyEvent.VK_KP_LEFT:
           editorPane.setCaretPosition(pos - el_range);
           break;
         case KeyEvent.VK_RIGHT:
         case KeyEvent.VK_KP_RIGHT:
           editorPane.setCaretPosition(pos + (el_range));
           break;
       }
     } catch (BadLocationException ex) {
     }
   }
 }
Example #23
0
  protected static XmlConfigurator parse(Element root_element) throws java.io.IOException {
    XmlConfigurator configurator = null;
    final LinkedList<ProtocolConfiguration> prot_data = new LinkedList<ProtocolConfiguration>();

    /**
     * CAUTION: crappy code ahead ! I (bela) am not an XML expert, so the code below is pretty
     * amateurish... But it seems to work, and it is executed only on startup, so no perf loss on
     * the critical path. If somebody wants to improve this, please be my guest.
     */
    try {
      String root_name = root_element.getNodeName();
      if (!"config".equals(root_name.trim().toLowerCase()))
        throw new IOException("the configuration does not start with a <config> element");

      NodeList prots = root_element.getChildNodes();
      for (int i = 0; i < prots.getLength(); i++) {
        Node node = prots.item(i);
        if (node.getNodeType() != Node.ELEMENT_NODE) continue;

        Element tag = (Element) node;
        String protocol = tag.getTagName();
        Map<String, String> params = new HashMap<String, String>();

        NamedNodeMap attrs = tag.getAttributes();
        int attrLength = attrs.getLength();
        for (int a = 0; a < attrLength; a++) {
          Attr attr = (Attr) attrs.item(a);
          String name = attr.getName();
          String value = attr.getValue();
          params.put(name, value);
        }
        ProtocolConfiguration cfg = new ProtocolConfiguration(protocol, params);
        prot_data.add(cfg);
      }
      configurator = new XmlConfigurator(prot_data);
    } catch (Exception x) {
      if (x instanceof java.io.IOException) throw (java.io.IOException) x;
      else {
        IOException tmp = new IOException();
        tmp.initCause(x);
        throw tmp;
      }
    }
    return configurator;
  }
  // DOM input
  public void declareNamespace(Element element) {
    NamedNodeMap attrs = element.getAttributes();
    int size = attrs.getLength();

    for (int i = 0; i < size; i++) {
      Attr attr = (Attr) attrs.item(i);
      String qName = attr.getName();

      if (qName.startsWith("xmlns:")) {
        String uri = attr.getValue();
        String prefix = qName.substring("xmlns:".length());
        declareNamespace(prefix, uri);
      } else if (qName.startsWith("xmlns")) {
        String uri = attr.getValue();
        declareNamespace("", uri);
      }
    }
  }
 private void validateUpdateURL(Element parent) {
   NodeList list = getChildrenByName(parent, "update"); // $NON-NLS-1$
   if (list.getLength() > 0) {
     if (fMonitor.isCanceled()) return;
     Element update = (Element) list.item(0);
     assertAttributeDefined(update, "url", CompilerFlags.ERROR); // $NON-NLS-1$
     NamedNodeMap attributes = update.getAttributes();
     for (int i = 0; i < attributes.getLength(); i++) {
       String name = attributes.item(i).getNodeName();
       if (name.equals("url")) { // $NON-NLS-1$
         validateURL(update, "url"); // $NON-NLS-1$
       } else if (!name.equals("label")) { // $NON-NLS-1$
         reportUnknownAttribute(update, name, CompilerFlags.ERROR);
       }
     }
     reportExtraneousElements(list, 1);
   }
 }
Example #26
0
  /*
   *  Determine the Y offset for the current row
   */
  private int getOffsetY(int rowStartOffset, FontMetrics fontMetrics) throws BadLocationException {
    //  Get the bounding rectangle of the row

    Rectangle r = component.modelToView(rowStartOffset);
    int lineHeight = fontMetrics.getHeight();
    int y = r.y + r.height;
    int descent = 0;

    //  The text needs to be positioned above the bottom of the bounding
    //  rectangle based on the descent of the font(s) contained on the row.
    if (r.height == lineHeight) {
      // default font is being used
      descent = fontMetrics.getDescent();
    } else {
      // We need to check all the attributes for font changes
      if (fonts == null) {
        fonts = new HashMap<String, FontMetrics>();
      }

      Element root = component.getDocument().getDefaultRootElement();
      int index = root.getElementIndex(rowStartOffset);
      Element line = root.getElement(index);

      for (int i = 0; i < line.getElementCount(); i++) {
        Element child = line.getElement(i);
        AttributeSet as = child.getAttributes();
        String fontFamily = (String) as.getAttribute(StyleConstants.FontFamily);
        Integer fontSize = (Integer) as.getAttribute(StyleConstants.FontSize);
        String key = fontFamily + fontSize;

        FontMetrics fm = fonts.get(key);

        if (fm == null) {
          Font font = new Font(fontFamily, Font.PLAIN, fontSize);
          fm = component.getFontMetrics(font);
          fonts.put(key, fm);
        }

        descent = Math.max(descent, fm.getDescent());
      }
    }

    return y - descent;
  }
Example #27
0
  @Test
  public void testgetAttributesWithNamedNodeMap() throws Exception {
    //		builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setNamespaceAware(true);

    File f = new File(System.getProperty("user.dir"), "src/test/resources/sample-springbeans.xml");
    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    Document doc = builder.parse(f);
    Element root = doc.getDocumentElement();
    //		System.out.println("* current impl:  " + doc.getClass().getName());

    // id, class
    Map<String, String> actualMap = new HashMap<String, String>();

    NodeList list = root.getChildNodes();
    for (int i = 0; i < list.getLength(); i++) {
      Node node = list.item(i);
      if (node instanceof Element) {
        Element elem = (Element) node;
        if (elem.getTagName().equals("beans:bean")) {
          //					System.out.println("bean[" + elem.getAttribute("id") + "]");
          NamedNodeMap map = elem.getAttributes();
          String valueId = null;
          String valueClass = null;
          for (int x = 0; x < map.getLength(); x++) {
            Node attr = map.item(x);
            if (attr.getNodeName().equals("id")) valueId = attr.getNodeValue();
            if (attr.getNodeName().equals("class")) valueClass = attr.getNodeValue();
          }
          if (valueId != null && valueClass != null) actualMap.put(valueId, valueClass);
        }
      }
    }

    Map<String, String> expected = new HashMap<String, String>();
    expected.put("authenticationManager", "org.springframework.security.providers.ProviderManager");
    expected.put(
        "daoAuthenticationProvider",
        "org.springframework.security.providers.dao.DaoAuthenticationProvider");
    expected.put(
        "loggerListener", "org.springframework.security.event.authentication.LoggerListener");
    Assert.assertEquals("Attributes with NamedNodeMap", expected, actualMap);
  }
 private void validateDescription(Element parent) {
   NodeList list = getChildrenByName(parent, "description"); // $NON-NLS-1$
   if (list.getLength() > 0) {
     if (fMonitor.isCanceled()) return;
     Element element = (Element) list.item(0);
     validateElementWithContent((Element) list.item(0), true);
     NamedNodeMap attributes = element.getAttributes();
     for (int i = 0; i < attributes.getLength(); i++) {
       Attr attr = (Attr) attributes.item(i);
       String name = attr.getName();
       if (name.equals("url")) { // $NON-NLS-1$
         validateURL(element, name);
       } else {
         reportUnknownAttribute(element, name, CompilerFlags.ERROR);
       }
     }
     reportExtraneousElements(list, 1);
   }
 }
Example #29
0
 private void addNamespaces(Namespaces rv, Element element) {
   if (element == null) throw new RuntimeException("element must not be null");
   String myDefaultNamespace = toUri(element.lookupNamespaceURI(null));
   String parentDefaultNamespace = "";
   if (element.getParentNode() != null) {
     parentDefaultNamespace = toUri(element.getParentNode().lookupNamespaceURI(null));
   }
   if (!myDefaultNamespace.equals(parentDefaultNamespace)
       || !(element.getParentNode() instanceof Element)) {
     rv.declare(Namespace.create("", myDefaultNamespace));
   }
   NamedNodeMap attributes = element.getAttributes();
   for (int i = 0; i < attributes.getLength(); i++) {
     Attr attr = (Attr) attributes.item(i);
     if (attr.getPrefix() != null && attr.getPrefix().equals("xmlns")) {
       rv.declare(Namespace.create(attr.getLocalName(), attr.getValue()));
     }
   }
 }
 @Override
 protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
   BeanDefinitionBuilder builder =
       BeanDefinitionBuilder.genericBeanDefinition(SpringJolokiaConfigHolder.class);
   Map<String, String> config = new HashMap<String, String>();
   NamedNodeMap attrs = element.getAttributes();
   for (int i = 0; i < attrs.getLength(); i++) {
     Attr attr = (Attr) attrs.item(i);
     String name = attr.getName();
     if (skipMap.contains(name)) {
       continue;
     }
     config.put(name, attr.getValue());
   }
   builder.addPropertyValue("config", config);
   String order = element.getAttribute("order");
   if (StringUtils.hasText(order)) {
     builder.addPropertyValue("order", Integer.parseInt(order));
   }
   return builder.getBeanDefinition();
 }