protected Attribute getAttribute(Element e, String attributeName) {
   Attribute attribute = e.getAttribute(attributeName);
   if (attribute == null) {
     attribute = e.getAttribute(attributeName, _namespace);
   }
   return attribute;
 }
 /**
  * 测试单元格样式
  *
  * @author David
  * @param wb
  * @param cell
  * @param td
  */
 private static void setType(HSSFWorkbook wb, HSSFCell cell, Element td) {
   Attribute typeAttr = td.getAttribute("type");
   String type = typeAttr.getValue();
   HSSFDataFormat format = wb.createDataFormat();
   HSSFCellStyle cellStyle = wb.createCellStyle();
   if ("NUMERIC".equalsIgnoreCase(type)) {
     cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
     Attribute formatAttr = td.getAttribute("format");
     String formatValue = formatAttr.getValue();
     formatValue = StringUtils.isNotBlank(formatValue) ? formatValue : "#,##0.00";
     cellStyle.setDataFormat(format.getFormat(formatValue));
   } else if ("STRING".equalsIgnoreCase(type)) {
     cell.setCellValue("");
     cell.setCellType(HSSFCell.CELL_TYPE_STRING);
     cellStyle.setDataFormat(format.getFormat("@"));
   } else if ("DATE".equalsIgnoreCase(type)) {
     cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
     cellStyle.setDataFormat(format.getFormat("yyyy-m-d"));
   } else if ("ENUM".equalsIgnoreCase(type)) {
     CellRangeAddressList regions =
         new CellRangeAddressList(
             cell.getRowIndex(), cell.getRowIndex(), cell.getColumnIndex(), cell.getColumnIndex());
     Attribute enumAttr = td.getAttribute("format");
     String enumValue = enumAttr.getValue();
     // 加载下拉列表内容
     DVConstraint constraint = DVConstraint.createExplicitListConstraint(enumValue.split(","));
     // 数据有效性对象
     HSSFDataValidation dataValidation = new HSSFDataValidation(regions, constraint);
     wb.getSheetAt(0).addValidationData(dataValidation);
   }
   cell.setCellStyle(cellStyle);
 }
  /**
   * Update page information.
   *
   * @param node Element for the page.
   * @param page Page.
   * @throws JDOMException
   */
  public void updatePageInformation(Element node, Page page) throws JDOMException {

    // Retrieve basic page information
    Attribute attrPageId = node.getAttribute("pageid");
    if (attrPageId != null) {
      page.setPageId(attrPageId.getValue());
    }
    Attribute attrTitle = node.getAttribute("title");
    if (attrTitle != null) {
      page.setTitle(attrTitle.getValue());
    }
    page.setStartTimestamp(node.getAttributeValue("starttimestamp"));
    Attribute attrRedirect = node.getAttribute("redirect");
    if (attrRedirect != null) {
      page.isRedirect(true);
    }
    Attribute attrMissing = node.getAttribute("missing");
    if (attrMissing != null) {
      page.setExisting(Boolean.FALSE);
    }

    // Retrieve protection information
    XPath xpaProtection = XPath.newInstance("protection/pr[@type=\"edit\"]");
    Element protectionNode = (Element) xpaProtection.selectSingleNode(node);
    if (protectionNode != null) {
      XPath xpaLevel = XPath.newInstance("./@level");
      page.setEditProtectionLevel(xpaLevel.valueOf(protectionNode));
    }
  }
  /*
   * Recursively walk the XHTML DOM tree and manipulate specific elements to
   * make them better for WYSIWYG editing.
   */
  private void processChildren(Element baseElement) {
    for (Iterator itr = baseElement.getChildren().iterator(); itr.hasNext(); ) {
      Object childElement = itr.next();
      if (childElement instanceof Element) {
        Element element = (Element) childElement;
        String elementName = element.getName().toLowerCase();
        Attribute classAttr = element.getAttribute(CLASS_ATTRIBUTE);

        if (elementName.equals(A_ELEMENT)) {
          if (classAttr != null) {
            String classValue = classAttr.getValue();
            Attribute hrefAttr = element.getAttribute(HREF_ATTRIBUTE);

            XHtmlToWikiConfig wikiConfig = new XHtmlToWikiConfig(m_context);

            // Get the url for wiki page link - it's typically "Wiki.jsp?page=MyPage"
            // or when using the ShortURLConstructor option, it's "wiki/MyPage" .
            String wikiPageLinkUrl = wikiConfig.getWikiJspPage();
            String editPageLinkUrl = wikiConfig.getEditJspPage();

            if (classValue.equals(WIKIPAGE)
                || (hrefAttr != null && hrefAttr.getValue().startsWith(wikiPageLinkUrl))) {
              // Remove the leading url string so that users will only see the
              // wikipage's name when editing an existing wiki link.
              // For example, change "Wiki.jsp?page=MyPage" to just "MyPage".
              String newHref = hrefAttr.getValue().substring(wikiPageLinkUrl.length());

              // Convert "This%20Pagename%20Has%20Spaces" to "This Pagename Has Spaces"
              newHref = m_context.getEngine().decodeName(newHref);

              // Handle links with section anchors.
              // For example, we need to translate the html string
              // "TargetPage#section-TargetPage-Heading2"
              // to this wiki string: "TargetPage#Heading2".
              hrefAttr.setValue(newHref.replaceFirst(LINKS_SOURCE, LINKS_TRANSLATION));
            } else if (hrefAttr != null
                && (classValue.equals(EDITPAGE)
                    || hrefAttr.getValue().startsWith(editPageLinkUrl))) {
              Attribute titleAttr = element.getAttribute(TITLE_ATTRIBUTE);
              if (titleAttr != null) {
                // remove the title since we don't want to eventually save the default undefined
                // page title.
                titleAttr.detach();
              }

              String newHref = hrefAttr.getValue().substring(editPageLinkUrl.length());
              newHref = m_context.getEngine().decodeName(newHref);

              hrefAttr.setValue(newHref);
            }
          }
        } // end of check for "a" element

        processChildren(element);
      }
    }
  }
 /**
  * 生成服务器端文件,每个消息一个文件
  *
  * @param messages
  * @throws Exception
  */
 private void createServerFiles(List<Element> messages, String module) throws Exception {
   for (Iterator i = messages.iterator(); i.hasNext(); ) {
     Element msgElement = (Element) i.next();
     MessageObject msgObj = new MessageObject();
     String msgType = msgElement.getAttributeValue("type");
     msgObj.setType(msgType);
     msgObj.setClassName(GeneratorHelper.generateServerClassName(msgType));
     msgObj.setModule(module);
     msgObj.setComment(msgElement.getAttributeValue("comment"));
     msgObj.setHandleMethodName(GeneratorHelper.generateHandleMethodName(msgType));
     if (msgElement.getAttributeValue("playerQueue") != null) {
       msgObj.setPlayerQueue(
           msgElement.getAttributeValue("playerQueue").equals("true") ? true : false);
     }
     if (msgElement.getAttributeValue("friendQueue") != null) {
       msgObj.setFriendQueue(msgElement.getAttribute("friendQueue").getValue().equals("true"));
     }
     if (msgElement.getAttributeValue("guildQueue") != null) {
       msgObj.setGuildQueue(msgElement.getAttribute("guildQueue").getValue().equals("true"));
     }
     List fElements = msgElement.getChildren("field", NAME_SPACE);
     setMsgObjFields(msgObj, fElements, false, false);
     VelocityContext context = new VelocityContext();
     context.put("message", msgObj);
     context.put("list", msgObj.getFields());
     String templateFileName = "";
     String outputFile = "";
     for (int j = 0; j < serverMsgTemplates.length; j++) {
       String templateName = serverMsgTemplates[j];
       if (templateName.substring(0, 2).equalsIgnoreCase(msgType.substring(0, 2))) {
         templateFileName = templateName;
         char lastCharOfTempate = templateName.charAt(templateName.length() - 4);
         switch (lastCharOfTempate) {
           case 'g': // 放在GameServer
             outputFile =
                 gameRootPath
                     + msgObj.getModule()
                     + File.separator
                     + "msg"
                     + File.separator
                     + msgObj.getClassName()
                     + ".java";
             break;
           default:
             throw new RuntimeException("模板名称非法," + templateName);
         }
         GeneratorHelper.generate(context, templateFileName, outputFile);
         //					JavaGeneratorHelper.generateJavaFile(msgObj, outputFile + "0");
       }
     }
     msgs.put(msgObj.getClassName(), msgObj);
   }
 }
  public List getUserList() {
    List<Map> list = new ArrayList<Map>();

    try {

      /*
      String apiUrl=rallyApiHost+"/user?query="+
      	"((TeamMemberships%20%3D%20https%3A%2F%2Frally1.rallydev.com%2Fslm%2Fwebservice%2F1.34%2Fproject%2F6169133135)%20or%20"+
      	"(TeamMemberships%20%3D%20https%3A%2F%2Frally1.rallydev.com%2Fslm%2Fwebservice%2F1.34%2Fproject%2F6083311244))"+
      	"&fetch=true&order=Name&start=1&pagesize=100";
      */

      String apiUrl =
          rallyApiHost
              + "/user?query=(Disabled%20=%20false)"
              + "&fetch=true&order=Name&start=1&pagesize=100";

      log.info("apiUrl=" + apiUrl);

      String responseXML = getRallyXML(apiUrl);

      org.jdom.input.SAXBuilder bSAX = new org.jdom.input.SAXBuilder();
      org.jdom.Document doc = bSAX.build(new StringReader(responseXML));
      Element root = doc.getRootElement();

      XPath xpath = XPath.newInstance("//Object");
      List xlist = xpath.selectNodes(root);

      Iterator iter = xlist.iterator();
      while (iter.hasNext()) {

        Map map = new HashMap();

        Element item = (Element) iter.next();

        String userRef = item.getAttribute("ref").getValue();
        String userName = item.getAttribute("refObjectName").getValue();
        String userObjectId = item.getChildText("ObjectID");

        map.put("userRef", userRef);
        map.put("userObjectId", userObjectId);
        map.put("userName", userName);

        list.add(map);
      }

    } catch (Exception ex) {
      log.error("", ex);
    }

    return list;
  }
Beispiel #7
0
  public void readDOMElement(Element element) {
    String label = element.getAttribute("name").getValue();
    m_name = label;
    Attribute idelement = element.getAttribute("id");
    if (idelement != null) {
      setId(idelement.getValue());
    }
    Element datasetselements = (Element) element.getChild(IDataSets.class.getName());
    readDOMDataElement(datasetselements, getDataSets());

    Element exportselements = (Element) element.getChild(IExportItem.class.getName());
    if (exportselements != null) {}
  }
  public SimpleResult process(RouteContext context, RouteHelper helper) throws Exception {

    LOG.debug("processing FYIByUniversityId node");
    Element rootElement =
        getRootElement(new StandardDocumentContent(context.getDocument().getDocContent()));
    Collection<Element> fieldElements = XmlHelper.findElements(rootElement, "field");
    Iterator<Element> elementIter = fieldElements.iterator();
    while (elementIter.hasNext()) {
      Element field = (Element) elementIter.next();
      Element version = field.getParentElement();
      if (version.getAttribute("current").getValue().equals("true")) {
        LOG.debug("Looking for studentUid field:  " + field.getAttributeValue("name"));
        if (field.getAttribute("name") != null
            && field.getAttributeValue("name").equals("studentUid")) {
          String employeeId = field.getChildText("value");
          LOG.debug("Should send an FYI to employee ID:  " + employeeId);
          if (!StringUtils.isBlank(employeeId)) {
            Person person = KimApiServiceLocator.getPersonService().getPerson(employeeId);

            if (person == null) {
              throw new WorkflowRuntimeException(
                  "Failed to locate a Person with the given employee ID: " + employeeId);
            }
            if (!context.isSimulation()) {
              KEWServiceLocator.getWorkflowDocumentService()
                  .adHocRouteDocumentToPrincipal(
                      person.getPrincipalId(),
                      context.getDocument(),
                      KewApiConstants.ACTION_REQUEST_FYI_REQ,
                      null,
                      null,
                      "Notification Request",
                      person.getPrincipalId(),
                      "Notification Request",
                      true,
                      null);
            }
            // wfDoc.adHocRouteDocumentToPrincipal(KewApiConstants.ACTION_REQUEST_FYI_REQ,
            // "Notification Request", new EmplIdVO(field.getChildText("value")), "Notification
            // Request", true);
            LOG.debug(
                "Sent FYI using the adHocRouteDocumentToPrincipal function to UniversityID:  "
                    + person.getEmployeeId());
            break;
          }
        }
      }
    }
    return super.process(context, helper);
  }
  @Override
  protected void setUp() throws Exception {
    final Document document = new SAXBuilder().build(new File(getTestDataRoot(), "/RETest.xml"));
    final List<Element> list = XPath.selectNodes(document.getRootElement(), "//test");
    new File(getTestDataPath()).mkdirs();

    int i = 0;
    for (Element element : list) {
      final String name;
      final Element parent = (Element) element.getParent();
      final String s = parent.getName();
      final String t =
          parent.getAttribute("id") == null ? "" : parent.getAttribute("id").getValue() + "-";
      if (!"tests".equals(s)) {
        name = s + "/test-" + t + ++i + ".regexp";
      } else {
        name = "test-" + t + ++i + ".regexp";
      }
      final Result result =
          Result.valueOf((String) XPath.selectSingleNode(element, "string(expected)"));
      final boolean warn = !"false".equals(element.getAttributeValue("warning"));
      final boolean info = "true".equals(element.getAttributeValue("info"));
      myMap.put(name, new Test(result, warn, info));

      final File file = new File(getTestDataPath(), name);
      file.getParentFile().mkdirs();

      final FileWriter stream = new FileWriter(file);
      final String pattern = (String) XPath.selectSingleNode(element, "string(pattern)");
      if (!"false".equals(element.getAttributeValue("verify")))
        try {
          Pattern.compile(pattern);
          if (result == Result.ERR) {
            System.out.println("Incorrect FAIL value for " + pattern);
          }
        } catch (PatternSyntaxException e) {
          if (result == Result.OK) {
            System.out.println("Incorrect OK value for " + pattern);
          }
        }
      stream.write(pattern);
      stream.close();
    }

    super.setUp();

    myOut = new ByteArrayOutputStream();
    System.setErr(new PrintStream(myOut));
  }
  /**
   * "Draws" the Elements on the Pane. Currently supported types are:
   * <li>
   *
   *     <ul>
   *       Normal data Elements
   * </ul>
   *
   * <ul>
   *   Outbound data Elements (are only shown not clickable
   * </ul>
   *
   * <ul>
   *   Inbound Data is shown
   * </ul>
   *
   * <ul>
   *   Pictures are shown
   * </ul>
   *
   * @param coll the collectible that should be drawn
   */
  public void drawElements(Collectible coll) {

    // clear prior content
    try {
      this.remove(0, this.getLength());
    } catch (BadLocationException ex) {
      // shoudl always work
    }

    // get dataElements
    Element data = coll.getContent();

    // foreach : get name, type, content
    List<Element> fields = data.getChildren("field");
    for (Element element : fields) {
      String name = element.getAttribute("name").getValue();

      // might be a picture
      Attribute typeAttribute = element.getAttribute("type");

      // might be a Inbound
      List<Element> childElements = element.getChildren("li");

      // is it a picture? If so draw it.
      if (typeAttribute != null) {
        drawPicture(element);
      }

      // is it a multifield, then draw it
      else if (childElements != null && childElements.size() > 0) {
        drawString(name + ":\n", this.getStyle("bold"));
        for (Element childElement : childElements) {
          drawChildElement(childElement);
        }
      }

      // is it a single field. Draw it.
      else {
        String content = element.getTextNormalize();
        drawString(name + ":\n", this.getStyle("bold"));
        drawString(content + "\n", this.getStyle("regular"));
      }
    }

    // informListeners
    fireChangedUpdate(
        new DefaultDocumentEvent(0, this.getLength(), DocumentEvent.EventType.CHANGE));
  }
Beispiel #11
0
  private String loadRule(Element rule, String id) throws DataConversionException {
    Rule dataRule = new Rule(allVars, id, id, rule.getAttribute("weight").getIntValue());
    java.util.List<?> elements = rule.getChildren();

    for (final Object element : elements) {
      Element child = (Element) element;
      String elementName = child.getName();

      if (elementName.equals("GETLIST")) {
        String listId = child.getAttributeValue("idref");
        dataRule.add(listId);
      } else if (elementName.equals("SPACE")) {
        SpaceRule sp = new SpaceRule();
        allVars.addDataElement(sp);
        dataRule.add(sp.getId());
      } else if (elementName.equals("HYPHEN")) {
        HyphenRule hy = new HyphenRule();
        allVars.addDataElement(hy);
        dataRule.add(hy.getId());
      } else if (elementName.equals("CR")) {
        CRRule cr = new CRRule();
        allVars.addDataElement(cr);
        dataRule.add(cr.getId());
      } else if (elementName.equals("GETRULE")) {
        String ruleId = child.getAttributeValue("idref");
        dataRule.add(ruleId);
      }
    }

    allVars.addDataElement(dataRule);

    return dataRule.getId();
  }
Beispiel #12
0
  private String loadList(Element list) throws DataConversionException {
    pcgen.core.doomsdaybook.DDList dataList =
        new pcgen.core.doomsdaybook.DDList(
            allVars, list.getAttributeValue("title"), list.getAttributeValue("id"));
    java.util.List<?> elements = list.getChildren();

    for (final Object element : elements) {
      Element child = (Element) element;
      String elementName = child.getName();

      if (elementName.equals("VALUE")) {
        WeightedDataValue dv =
            new WeightedDataValue(child.getText(), child.getAttribute("weight").getIntValue());
        List<?> subElements = child.getChildren("SUBVALUE");

        for (final Object subElement1 : subElements) {
          Element subElement = (Element) subElement1;
          dv.addSubValue(subElement.getAttributeValue("type"), subElement.getText());
        }

        dataList.add(dv);
      }
    }

    allVars.addDataElement(dataList);

    return dataList.getId();
  }
 void getAttributes(Object node, String localName, String namespaceUri, List result) {
   if (node instanceof Element) {
     Element e = (Element) node;
     if (localName == null) {
       result.addAll(e.getAttributes());
     } else {
       Attribute attr = e.getAttribute(localName, Namespace.getNamespace("", namespaceUri));
       if (attr != null) {
         result.add(attr);
       }
     }
   } else if (node instanceof ProcessingInstruction) {
     ProcessingInstruction pi = (ProcessingInstruction) node;
     if ("target".equals(localName)) {
       result.add(new Attribute("target", pi.getTarget()));
     } else if ("data".equals(localName)) {
       result.add(new Attribute("data", pi.getData()));
     } else {
       result.add(new Attribute(localName, pi.getValue(localName)));
     }
   } else if (node instanceof DocType) {
     DocType doctype = (DocType) node;
     if ("publicId".equals(localName)) {
       result.add(new Attribute("publicId", doctype.getPublicID()));
     } else if ("systemId".equals(localName)) {
       result.add(new Attribute("systemId", doctype.getSystemID()));
     } else if ("elementName".equals(localName)) {
       result.add(new Attribute("elementName", doctype.getElementName()));
     }
   }
 }
Beispiel #14
0
 public static Attribute getMandatoryAttribute(final Element element, final String name) {
   final Attribute attribute = element.getAttribute(name);
   if (attribute == null) {
     throw new RuntimeException("Attribute '" + name + "' expected");
   }
   return attribute;
 }
Beispiel #15
0
  private static void handleExportAttributesFromJAR(Element e, File config, File toDir) {
    for (Element c : ((List<Element>) e.getChildren()).toArray(new Element[0])) {
      Attribute a = c.getAttribute("EXPORT");
      if (a != null && a.getValue().equals("copy")) {
        /* Copy file from JAR */
        File file = GUI.restoreConfigRelativePath(config, new File(c.getText()));
        InputStream inputStream = GUI.class.getResourceAsStream("/" + file.getName());
        if (inputStream == null) {
          throw new RuntimeException("Could not unpack file: " + file);
        }
        byte[] fileData = ArrayUtils.readFromStream(inputStream);
        if (fileData == null) {
          logger.info("Failed unpacking file");
          throw new RuntimeException("Could not unpack file: " + file);
        }
        if (OVERWRITE || !file.exists()) {
          boolean ok = ArrayUtils.writeToFile(file, fileData);
          if (!ok) {
            throw new RuntimeException("Failed unpacking file: " + file);
          }
          logger.info("Unpacked file from JAR: " + file.getName());
        } else if (OVERWRITE) {
          logger.info("Skip: unpack file from JAR: " + file.getName());
        }
      }

      /* Recursive search */
      handleExportAttributesFromJAR(c, config, toDir);
    }
  }
  /**
   * Test for overwrite existing file with action = create.
   *
   * @throws CruiseControlException
   * @throws IOException
   */
  public final void testMsgActionCreate() throws CruiseControlException, IOException {
    final File outFile = filesToDelete.add(this);
    final WriterBuilder writerObj = new WriterBuilder();

    // Create file with inner text
    IO.write(outFile, "InnerText");

    // Set append true.
    writerObj.setFile(outFile.getAbsolutePath());
    writerObj.setAction("create");
    newMssg(writerObj).append("first text");

    // Validation step
    // Setting overwrite false set append also false
    assertFalse(writerObj.getAppend());

    try {
      writerObj.validate();
      fail();
    } catch (Exception e) {
      assertTrue(e.getMessage().equals("Trying to overwrite file without permition."));
    }

    // Build step. The file was not existing during the validation, but has been created
    // later on ...
    IO.delete(outFile);
    writerObj.validate();
    // Create file with inner text - again
    IO.write(outFile, "InnerText");

    // Trigger the build as well
    final Element out = writerObj.build(buildMap, buildProgress);
    assertNotNull(out.getAttribute("error"));
  }
Beispiel #17
0
 @Override
 public void read(Element element, Project project) throws CantLoadSomethingException {
   super.read(element, project);
   Element filterXML = element.getChild(FILTER);
   String filterName = filterXML.getAttribute(CLASS_NAME).getValue();
   try {
     Class filterClass = null;
     for (Language l : project.getProjectModules(Language.class)) {
       filterClass = ClassLoaderManager.getInstance().getClass(l, filterName);
       if (filterClass != null) break;
     }
     if (filterClass == null) {
       try {
         filterClass = Class.forName(filterName);
       } catch (ClassNotFoundException e) {
         filterClass = null;
       }
     }
     if (filterClass != null) {
       myFilter = (BaseFilter) filterClass.newInstance();
     } else {
       throw new CantLoadSomethingException("Can't find filter class " + filterName);
     }
   } catch (Throwable t) {
     throw new CantLoadSomethingException("Can't instantiate or read filter " + filterName, t);
   }
 }
  /* (non-Javadoc)
   * @see uk.ac.jorum.packager.detector.BasePackageDetector#isValidPackage()
   */
  @Override
  public boolean isValidPackage() {
    boolean result = false;
    boolean isUrl = false;

    try {
      // Download the feed
      // url is the bitstream contents

      // Check that the bitstream belongs in the FEED_BUNDLE - if it isn't then we may be looking at
      // raw content ie not a link to a feed!
      Bundle[] bundles = this.getBitstream().getBundles();
      for (Bundle b : bundles) {
        if (b.getName().equals(Constants.FEED_BUNDLE)) {
          isUrl = true;
          break;
        }
      }

      if (isUrl) {
        Document xmlDoc = getRssDocument(this.getBitstream());
        Element root = xmlDoc.getRootElement();

        Attribute version = root.getAttribute("version");
        if (root.getName().equals("rss") && version != null && version.getValue().equals("2.0")) {
          result = true;
        }
      }

    } catch (Exception e) {
      ExceptionLogger.logException(log, e);
    }

    return result;
  }
Beispiel #19
0
  ModuleJdkOrderEntryImpl(
      Element element,
      RootModelImpl rootModel,
      ProjectRootManagerImpl projectRootManager,
      VirtualFilePointerManager filePointerManager)
      throws InvalidDataException {
    super(rootModel, projectRootManager, filePointerManager);
    if (!element.getName().equals(OrderEntryFactory.ORDER_ENTRY_ELEMENT_NAME)) {
      throw new InvalidDataException();
    }
    final Attribute jdkNameAttribute = element.getAttribute(JDK_NAME_ATTR);
    if (jdkNameAttribute == null) {
      throw new InvalidDataException();
    }

    final String jdkName = jdkNameAttribute.getValue();
    final String jdkType = element.getAttributeValue(JDK_TYPE_ATTR);
    final ProjectJdkTable projectJdkTable = ProjectJdkTable.getInstance();
    final Sdk jdkByName = projectJdkTable.findJdk(jdkName, jdkType);
    if (jdkByName == null) {
      init(null, jdkName, jdkType);
    } else {
      init(jdkByName, null, null);
    }
  }
Beispiel #20
0
 @Override
 public void readExternal(Element element) {
   super.readExternal(element);
   Attribute configurationNameAttr = element.getAttribute("run_configuration_name");
   Attribute configurationTypeAttr = element.getAttribute("run_configuration_type");
   myConfigurationName = configurationNameAttr != null ? configurationNameAttr.getValue() : null;
   myConfigurationType = configurationTypeAttr != null ? configurationTypeAttr.getValue() : null;
 }
  /**
   * Returns the prefix for the request: http://wms.jpl.nasa.gov/wms.cgi?
   *
   * @return
   */
  public String getBaseUrl() {
    Element onlineResource = tiledPatterns.getChild("OnlineResource"); // $NON-NLS-1$
    Namespace xlink = onlineResource.getNamespace("xlink"); // $NON-NLS-1$
    Attribute href = onlineResource.getAttribute("href", xlink); // $NON-NLS-1$
    String baseUrl = href.getValue();

    return baseUrl;
  }
 private String getProjectName(final Element childElement) throws CruiseControlException {
   if (!isProject(childElement.getName())) {
     throw new IllegalStateException(
         "Invalid Node <" + childElement.getName() + "> (not a project)");
   }
   final String rawName = childElement.getAttribute("name").getValue();
   return Util.parsePropertiesInString(rootProperties, rawName, false);
 }
  public void compile(Element element) {
    if (!element.getChildren().isEmpty()) {
      throw new CompilationError("<script> elements can't have children", element);
    }
    String pathname = null;
    String script = element.getText();
    if (element.getAttribute(SRC_ATTR_NAME) != null) {
      pathname = element.getAttributeValue(SRC_ATTR_NAME);
      File file = mEnv.resolveReference(element, SRC_ATTR_NAME);
      try {
        script =
            "#file "
                + element.getAttributeValue(SRC_ATTR_NAME)
                + "\n"
                + "#line 1\n"
                + FileUtils.readFileString(file);
      } catch (IOException e) {
        throw new CompilationError(e);
      }
    }
    try {
      // If it is when=immediate, emit code inline
      if ("immediate".equals(element.getAttributeValue("when"))) {
        mEnv.compileScript(
            CompilerUtils.sourceLocationDirective(element, true)
                + script
                + CompilerUtils.endSourceLocationDirective,
            element);
      } else {
        // Compile scripts to run at construction time in the view
        // instantiation queue.

        mEnv.compileScript(
            // Provide file info for anonymous function name
            CompilerUtils.sourceLocationDirective(element, true)
                + VIEW_INSTANTIATION_FNAME
                + "({'class': lz.script, attrs: "
                + "{script: function () {\n"
                + "#beginContent\n"
                + "#pragma 'scriptElement'\n"
                + CompilerUtils.sourceLocationDirective(element, true)
                + script
                + CompilerUtils.endSourceLocationDirective
                + "\n#endContent\n"
                +
                // Scripts have no children
                "}}}, 1)",
            element);
      }
    } catch (CompilationError e) {
      // TODO: [2003-01-16] Instead of this, put the filename in ParseException,
      // and modify CompilationError.initElement to copy it from there.
      if (pathname != null) {
        e.setPathname(pathname);
      }
      throw e;
    }
  }
  private RuleTemplateBo parseRuleTemplate(Element element, List<RuleTemplateBo> ruleTemplates)
      throws XmlException {
    String name = element.getChildText(NAME, RULE_TEMPLATE_NAMESPACE);
    String description = element.getChildText(DESCRIPTION, RULE_TEMPLATE_NAMESPACE);
    Attribute allowOverwriteAttrib = element.getAttribute("allowOverwrite");

    boolean allowOverwrite = false;
    if (allowOverwriteAttrib != null) {
      allowOverwrite = Boolean.valueOf(allowOverwriteAttrib.getValue()).booleanValue();
    }
    if (org.apache.commons.lang.StringUtils.isEmpty(name)) {
      throw new XmlException("RuleTemplate must have a name");
    }
    if (org.apache.commons.lang.StringUtils.isEmpty(description)) {
      throw new XmlException("RuleTemplate must have a description");
    }

    // look up the rule template by name first
    RuleTemplateBo ruleTemplate =
        KEWServiceLocator.getRuleTemplateService().findByRuleTemplateName(name);

    if (ruleTemplate == null) {
      // if it does not exist create a new one
      ruleTemplate = new RuleTemplateBo();
    } else {
      // if it does exist, update it, only if allowOverwrite is set
      if (!allowOverwrite) {
        throw new RuntimeException(
            "Attempting to overwrite template " + name + " without allowOverwrite set");
      }

      // the name should be equal if one was actually found
      assert (name.equals(ruleTemplate.getName()))
          : "Existing template definition name does not match incoming definition name";
    }

    // overwrite simple properties
    ruleTemplate.setName(name);
    ruleTemplate.setDescription(description);

    // update the delegation template
    updateDelegationTemplate(element, ruleTemplate, ruleTemplates);

    // update the attribute relationships
    updateRuleTemplateAttributes(element, ruleTemplate);

    // save the rule template first so that the default/template rule that is generated
    // in the process of setting defaults is associated properly with this rule template
    ruleTemplate = KEWServiceLocator.getRuleTemplateService().save(ruleTemplate);

    // update the default options
    updateRuleTemplateDefaultOptions(element, ruleTemplate);

    ruleTemplate = KEWServiceLocator.getRuleTemplateService().save(ruleTemplate);

    return ruleTemplate;
  }
  public void replaceBinaryKeyPlaceholders(List<BinaryDataKey> binaryDatas) {
    if (binaryDatas == null || binaryDatas.size() == 0) {
      return;
    }

    final Element binaryDataEl = contentDataEl.getChild("binarydata");
    Attribute attr = binaryDataEl.getAttribute("key");
    replaceBinaryKeyPlaceHolder(attr, binaryDatas);
  }
  public void writeExternal(@NotNull final Element parentNode) {
    // restore old breakpoints
    for (Element group : myOriginalBreakpointsNodes) {
      if (group.getAttribute(CONVERTED_PARAM) == null) {
        group.setAttribute(CONVERTED_PARAM, "true");
      }
      group.detach();
    }

    parentNode.addContent(myOriginalBreakpointsNodes);
    // ApplicationManager.getApplication().runReadAction(new Runnable() {
    //  @Override
    //  public void run() {
    //    removeInvalidBreakpoints();
    //    final Map<Key<? extends Breakpoint>, Element> categoryToElementMap = new THashMap<Key<?
    // extends Breakpoint>, Element>();
    //    for (Key<? extends Breakpoint> category : myBreakpointDefaults.keySet()) {
    //      final Element group = getCategoryGroupElement(categoryToElementMap, category,
    // parentNode);
    //      final BreakpointDefaults defaults = getBreakpointDefaults(category);
    //      group.setAttribute(DEFAULT_SUSPEND_POLICY_ATTRIBUTE_NAME,
    // String.valueOf(defaults.getSuspendPolicy()));
    //      group.setAttribute(DEFAULT_CONDITION_STATE_ATTRIBUTE_NAME,
    // String.valueOf(defaults.isConditionEnabled()));
    //    }
    //    // don't store invisible breakpoints
    //    for (Breakpoint breakpoint : getBreakpoints()) {
    //      if (breakpoint.isValid() &&
    //          (!(breakpoint instanceof BreakpointWithHighlighter) ||
    // ((BreakpointWithHighlighter)breakpoint).isVisible())) {
    //        writeBreakpoint(getCategoryGroupElement(categoryToElementMap,
    // breakpoint.getCategory(), parentNode), breakpoint);
    //      }
    //    }
    //    final AnyExceptionBreakpoint anyExceptionBreakpoint = getAnyExceptionBreakpoint();
    //    final Element group = getCategoryGroupElement(categoryToElementMap,
    // anyExceptionBreakpoint.getCategory(), parentNode);
    //    writeBreakpoint(group, anyExceptionBreakpoint);
    //
    //    final Element rules = new Element(RULES_GROUP_NAME);
    //    parentNode.addContent(rules);
    //    //for (EnableBreakpointRule myBreakpointRule : myBreakpointRules) {
    //    //  writeRule(myBreakpointRule, rules);
    //    //}
    //  }
    // });
    //
    // final Element uiProperties = new Element("ui_properties");
    // parentNode.addContent(uiProperties);
    // for (final String name : myUIProperties.keySet()) {
    //  Element property = new Element("property");
    //  uiProperties.addContent(property);
    //  property.setAttribute("name", name);
    //  property.setAttribute("value", myUIProperties.get(name));
    // }
  }
  protected <T> void getAttribute(
      Element root, String name, Action<T> setFunc, Func1<String, T> convertFunc) {
    if (root == null) {
      return;
    }

    Attribute attribute = root.getAttribute(name);
    if (attribute != null) {
      setFunc.invoke(convertFunc.invoke(attribute.getValue()));
    }
  }
Beispiel #28
0
 /**
  * Utility method to parse a taxonomy from an element.
  *
  * <p>
  *
  * @param desc the taxonomy description element.
  * @return the string contained in the resource of the element.
  */
 protected final String getTaxonomy(Element desc) {
   String d = null;
   Element taxo = desc.getChild("topic", getTaxonomyNamespace());
   if (taxo != null) {
     Attribute a = taxo.getAttribute("resource", getRDFNamespace());
     if (a != null) {
       d = a.getValue();
     }
   }
   return d;
 }
  @Override
  public String parse(Element t) throws ParseException {
    try {

      XPath p = constructPath(this.getPath(), t);
      Element elem = (Element) p.selectSingleNode(t);
      return elem.getAttribute(attribute).getValue();
    } catch (JDOMException e) {
      throw new ParseException(e.getMessage(), 0);
    }
  }
  public HtmlAreaDataEntry parse(
      final Element containerElement, final DataEntryConfig inputConfig) {
    final Attribute hasValueAtr = containerElement.getAttribute("has-value");
    if (hasValueAtr != null && hasValueAtr.getValue().equalsIgnoreCase("false")) {
      return new HtmlAreaDataEntry(inputConfig, null);
    }

    final String value = elementContentToString(containerElement);

    return new HtmlAreaDataEntry(inputConfig, value);
  }