public static List<ComponentDef> getComponentsFromConfig(URL configUrl)
      throws ComponentException {
    if (configUrl == null) {
      throw new ComponentException("Component config file does not exist: " + configUrl);
    }

    List<ComponentDef> componentsFromConfig = null;
    Document document = null;
    try {
      document = UtilXml.readXmlDocument(configUrl, true);
    } catch (SAXException e) {
      throw new ComponentException("Error reading the component config file: " + configUrl, e);
    } catch (ParserConfigurationException e) {
      throw new ComponentException("Error reading the component config file: " + configUrl, e);
    } catch (IOException e) {
      throw new ComponentException("Error reading the component config file: " + configUrl, e);
    }

    Element root = document.getDocumentElement();
    List<? extends Element> toLoad = UtilXml.childElementList(root);
    if (UtilValidate.isNotEmpty(toLoad)) {
      componentsFromConfig = new LinkedList<ComponentDef>();
      for (Element element : toLoad) {
        componentsFromConfig.add(new ComponentDef(element));
      }
    }
    return componentsFromConfig;
  }
Esempio n. 2
0
 /** XML Constructor */
 public ModelKeyMap(Element keyMapElement) {
   this.fieldName = UtilXml.checkEmpty(keyMapElement.getAttribute("field-name")).intern();
   // if no relFieldName is specified, use the fieldName; this is convenient for when they are
   // named the same, which is often the case
   this.relFieldName =
       UtilXml.checkEmpty(keyMapElement.getAttribute("rel-field-name"), this.fieldName).intern();
   this.fullName = this.fieldName.concat(":").concat(this.relFieldName);
 }
 public CombinedCondition(Element element, SimpleMethod simpleMethod) throws MiniLangException {
   super(element, simpleMethod);
   List<? extends Element> childElements = UtilXml.childElementList(element);
   if (MiniLangValidate.validationOn() && childElements.isEmpty()) {
     MiniLangValidate.handleError("No conditional elements.", simpleMethod, element);
   }
   List<Conditional> conditionalList = new ArrayList<Conditional>(childElements.size());
   for (Element conditionalElement : UtilXml.childElementList(element)) {
     conditionalList.add(ConditionalFactory.makeConditional(conditionalElement, simpleMethod));
   }
   this.subConditions = Collections.unmodifiableList(conditionalList);
 }
Esempio n. 4
0
 public EntityCount(Element element, SimpleMethod simpleMethod) throws MiniLangException {
   super(element, simpleMethod);
   if (MiniLangValidate.validationOn()) {
     MiniLangValidate.attributeNames(
         simpleMethod, element, "entity-name", "count-field", "delegator-name");
     MiniLangValidate.requiredAttributes(simpleMethod, element, "entity-name", "count-field");
     MiniLangValidate.expressionAttributes(simpleMethod, element, "count-field", "delegator-name");
     MiniLangValidate.childElements(
         simpleMethod,
         element,
         "condition-expr",
         "condition-list",
         "condition-object",
         "having-condition-list");
     MiniLangValidate.requireAnyChildElement(
         simpleMethod, element, "condition-expr", "condition-list", "condition-object");
   }
   this.entityNameFse = FlexibleStringExpander.getInstance(element.getAttribute("entity-name"));
   this.countFma = FlexibleMapAccessor.getInstance(element.getAttribute("count-field"));
   int conditionElementCount = 0;
   Element conditionExprElement = UtilXml.firstChildElement(element, "condition-expr");
   conditionElementCount =
       conditionExprElement == null ? conditionElementCount : conditionElementCount++;
   Element conditionListElement = UtilXml.firstChildElement(element, "condition-list");
   conditionElementCount =
       conditionListElement == null ? conditionElementCount : conditionElementCount++;
   Element conditionObjectElement = UtilXml.firstChildElement(element, "condition-object");
   conditionElementCount =
       conditionObjectElement == null ? conditionElementCount : conditionElementCount++;
   if (conditionElementCount > 1) {
     MiniLangValidate.handleError(
         "Element must include only one condition child element",
         simpleMethod,
         conditionObjectElement);
   }
   if (conditionExprElement != null) {
     this.whereCondition = new ConditionExpr(conditionExprElement);
   } else if (conditionListElement != null) {
     this.whereCondition = new ConditionList(conditionListElement);
   } else if (conditionObjectElement != null) {
     this.whereCondition = new ConditionObject(conditionObjectElement);
   } else {
     this.whereCondition = null;
   }
   Element havingConditionListElement =
       UtilXml.firstChildElement(element, "having-condition-list");
   if (havingConditionListElement != null) {
     this.havingCondition = new ConditionList(havingConditionListElement);
   } else {
     this.havingCondition = null;
   }
 }
Esempio n. 5
0
  private static List<Map<Object, Object>> getListMapsFromXmlFile(String XmlFilePath) {
    List<Map<Object, Object>> listMaps = FastList.newInstance();
    InputStream ins = null;
    URL xmlFileUrl = null;
    Document xmlDocument = null;
    try {
      if (UtilValidate.isNotEmpty(XmlFilePath)) {
        xmlFileUrl = UtilURL.fromFilename(XmlFilePath);
        if (xmlFileUrl != null) ins = xmlFileUrl.openStream();
        if (ins != null) {
          xmlDocument = UtilXml.readXmlDocument(ins, xmlFileUrl.toString());
          List<? extends Node> nodeList =
              UtilXml.childNodeList(xmlDocument.getDocumentElement().getFirstChild());
          for (Node node : nodeList) {
            if (node.getNodeType() == Node.ELEMENT_NODE) {
              Map<Object, Object> fields = FastMap.newInstance();
              fields.put(node.getNodeName(), UtilXml.elementValue((Element) node));
              Map<Object, Object> attrFields = getAttributeNameValueMap(node);
              Set<Object> keys = attrFields.keySet();
              Iterator<Object> attrFieldsIter = keys.iterator();
              while (attrFieldsIter.hasNext()) {
                Object key = attrFieldsIter.next();
                fields.put(key, attrFields.get(key));
              }

              List<? extends Node> childNodeList = UtilXml.childNodeList(node.getFirstChild());
              for (Node childNode : childNodeList) {
                fields.put(childNode.getNodeName(), UtilXml.elementValue((Element) childNode));
                attrFields = getAttributeNameValueMap(childNode);
                keys = attrFields.keySet();
                attrFieldsIter = keys.iterator();
                while (attrFieldsIter.hasNext()) {
                  Object key = attrFieldsIter.next();
                  fields.put(key, attrFields.get(key));
                }
              }
              listMaps.add(fields);
            }
          }
        }
      }
    } catch (Exception exc) {
      Debug.logError(exc, "Error reading xml file", module);
    } finally {
      try {
        if (ins != null) ins.close();
      } catch (Exception exc) {
        Debug.logError(exc, "Error reading xml file", module);
      }
    }
    return listMaps;
  }
Esempio n. 6
0
 public MapProcessor(Element simpleMapProcessorElement) {
   name = simpleMapProcessorElement.getAttribute("name");
   for (Element makeInStringElement :
       UtilXml.childElementList(simpleMapProcessorElement, "make-in-string")) {
     MakeInString makeInString = new MakeInString(makeInStringElement);
     makeInStrings.add(makeInString);
   }
   for (Element simpleMapProcessElement :
       UtilXml.childElementList(simpleMapProcessorElement, "process")) {
     SimpleMapProcess strProc = new SimpleMapProcess(simpleMapProcessElement);
     simpleMapProcesses.add(strProc);
   }
 }
Esempio n. 7
0
  public static ModelTree getTreeFromLocation(
      String resourceName, String treeName, Delegator delegator, LocalDispatcher dispatcher)
      throws IOException, SAXException, ParserConfigurationException {
    Map<String, ModelTree> modelTreeMap = treeLocationCache.get(resourceName);
    if (modelTreeMap == null) {
      synchronized (TreeFactory.class) {
        modelTreeMap = treeLocationCache.get(resourceName);
        if (modelTreeMap == null) {
          ClassLoader loader = Thread.currentThread().getContextClassLoader();
          if (loader == null) {
            loader = TreeFactory.class.getClassLoader();
          }

          URL treeFileUrl = null;
          treeFileUrl = FlexibleLocation.resolveLocation(resourceName); // , loader);
          Document treeFileDoc = UtilXml.readXmlDocument(treeFileUrl, true);
          modelTreeMap = readTreeDocument(treeFileDoc, delegator, dispatcher, resourceName);
          treeLocationCache.put(resourceName, modelTreeMap);
        }
      }
    }

    ModelTree modelTree = (ModelTree) modelTreeMap.get(treeName);
    if (modelTree == null) {
      throw new IllegalArgumentException(
          "Could not find tree with name ["
              + treeName
              + "] in class resource ["
              + resourceName
              + "]");
    }
    return modelTree;
  }
Esempio n. 8
0
 private void getLabelsFromOfbizComponents()
     throws IOException, SAXException, ParserConfigurationException {
   List<File> componentsFiles =
       FileUtil.findXmlFiles(
           null, null, "ofbiz-component", "http://ofbiz.apache.org/dtds/ofbiz-component.xsd");
   for (File componentFile : componentsFiles) {
     String filePath = componentFile.getPath();
     Document menuDocument = UtilXml.readXmlDocument(componentFile.toURI().toURL());
     Element rootElem = menuDocument.getDocumentElement();
     for (Element elem1 : UtilXml.childElementList(rootElem)) {
       checkOfbizComponentTag(elem1, filePath);
       for (Element elem2 : UtilXml.childElementList(elem1)) {
         checkOfbizComponentTag(elem2, filePath);
       }
     }
   }
 }
Esempio n. 9
0
 public void populateFromAttributes(Element element) {
   author = element.getAttribute("author").intern();
   copyright = element.getAttribute("copyright").intern();
   description = StringUtil.internString(UtilXml.childElementValue(element, "description"));
   title = element.getAttribute("title").intern();
   version = element.getAttribute("version").intern();
   defaultResourceName = StringUtil.internString(element.getAttribute("default-resource-name"));
 }
Esempio n. 10
0
  /** XML Constructor */
  public ModelIndex(ModelEntity mainEntity, Element indexElement) {
    super(mainEntity);

    this.name = UtilXml.checkEmpty(indexElement.getAttribute("name")).intern();
    this.unique = "true".equals(UtilXml.checkEmpty(indexElement.getAttribute("unique")));
    this.description =
        StringUtil.internString(UtilXml.childElementValue(indexElement, "description"));

    NodeList indexFieldList = indexElement.getElementsByTagName("index-field");
    for (int i = 0; i < indexFieldList.getLength(); i++) {
      Element indexFieldElement = (Element) indexFieldList.item(i);

      if (indexFieldElement.getParentNode() == indexElement) {
        String fieldName = indexFieldElement.getAttribute("name").intern();
        this.fieldNames.add(fieldName);
      }
    }
  }
 public static List<ScreenCondition> readSubConditions(
     ModelScreen modelScreen, Element conditionElement) {
   List<ScreenCondition> condList = FastList.newInstance();
   List<? extends Element> subElementList = UtilXml.childElementList(conditionElement);
   for (Element subElement : subElementList) {
     condList.add(readCondition(modelScreen, subElement));
   }
   return condList;
 }
Esempio n. 12
0
 public HtmlTemplateDecoratorSection(
     ModelScreen modelScreen, Element htmlTemplateDecoratorSectionElement) {
   super(modelScreen, htmlTemplateDecoratorSectionElement);
   this.name = htmlTemplateDecoratorSectionElement.getAttribute("name");
   // read sub-widgets
   List<? extends Element> subElementList =
       UtilXml.childElementList(htmlTemplateDecoratorSectionElement);
   this.subWidgets = ModelScreenWidget.readSubWidgets(this.modelScreen, subElementList);
 }
Esempio n. 13
0
 public void writeResponse(HttpServletResponse response, Writer writer) throws IOException {
   ByteArrayOutputStream os = new ByteArrayOutputStream();
   try {
     UtilXml.writeXmlDocument(os, this.responseDocument, "UTF-8", true, true);
   } catch (Exception e) {
     throw new IOException(e.getMessage());
   }
   response.setContentLength(os.size());
   writer.write(os.toString("UTF-8"));
 }
 public Document getDocument() throws GenericConfigException {
   try {
     return UtilXml.readXmlDocument(this.getStream(), this.xmlFilename, true);
   } catch (org.xml.sax.SAXException e) {
     throw new GenericConfigException("Error reading " + this.toString(), e);
   } catch (javax.xml.parsers.ParserConfigurationException e) {
     throw new GenericConfigException("Error reading " + this.toString(), e);
   } catch (java.io.IOException e) {
     throw new GenericConfigException("Error reading " + this.toString(), e);
   }
 }
Esempio n. 15
0
 private void getLabelsFromFormWidgets(String inFile, File file)
     throws MalformedURLException, SAXException, ParserConfigurationException, IOException,
         GenericServiceException {
   Set<String> fieldNames = FastSet.newInstance();
   findUiLabelMapInFile(inFile, file.getPath());
   Document formDocument = UtilXml.readXmlDocument(file.toURI().toURL());
   Element rootElem = formDocument.getDocumentElement();
   for (Element formElement : UtilXml.childElementList(rootElem, "form")) {
     for (Element elem : UtilXml.childElementList(formElement, "auto-fields-service")) {
       getAutoFieldsServiceTag(elem, fieldNames);
     }
     for (Element elem : UtilXml.childElementList(formElement, "auto-fields-entity")) {
       getAutoFieldsEntityTag(elem, fieldNames);
     }
     for (String field : fieldNames) {
       String labelKey = formFieldTitle.concat(field);
       if (this.labelSet.contains(labelKey)) {
         setLabelReference(labelKey, file.getPath());
       }
     }
   }
 }
Esempio n. 16
0
 public static Map<String, ModelTree> readTreeDocument(
     Document treeFileDoc, Delegator delegator, LocalDispatcher dispatcher, String treeLocation) {
   Map<String, ModelTree> modelTreeMap = new HashMap<String, ModelTree>();
   if (treeFileDoc != null) {
     // read document and construct ModelTree for each tree element
     Element rootElement = treeFileDoc.getDocumentElement();
     for (Element treeElement : UtilXml.childElementList(rootElement, "tree")) {
       ModelTree modelTree = new ModelTree(treeElement, delegator, dispatcher);
       modelTree.setTreeLocation(treeLocation);
       modelTreeMap.put(modelTree.getName(), modelTree);
     }
   }
   return modelTreeMap;
 }
Esempio n. 17
0
    public HtmlTemplateDecorator(ModelScreen modelScreen, Element htmlTemplateDecoratorElement) {
      super(modelScreen, htmlTemplateDecoratorElement);
      this.locationExdr =
          FlexibleStringExpander.getInstance(htmlTemplateDecoratorElement.getAttribute("location"));

      List<? extends Element> htmlTemplateDecoratorSectionElementList =
          UtilXml.childElementList(htmlTemplateDecoratorElement, "html-template-decorator-section");
      for (Element htmlTemplateDecoratorSectionElement : htmlTemplateDecoratorSectionElementList) {
        String name = htmlTemplateDecoratorSectionElement.getAttribute("name");
        this.sectionMap.put(
            name,
            new HtmlTemplateDecoratorSection(modelScreen, htmlTemplateDecoratorSectionElement));
      }
    }
Esempio n. 18
0
 public void populateFromElements(Element element) {
   author = StringUtil.internString(UtilXml.childElementValue(element, "author"));
   copyright = StringUtil.internString(UtilXml.childElementValue(element, "copyright"));
   description = StringUtil.internString(UtilXml.childElementValue(element, "description"));
   title = StringUtil.internString(UtilXml.childElementValue(element, "title"));
   version = StringUtil.internString(UtilXml.childElementValue(element, "version"));
   defaultResourceName =
       StringUtil.internString(UtilXml.childElementValue(element, "default-resource-name"));
 }
Esempio n. 19
0
 public HtmlWidget(ModelScreen modelScreen, Element htmlElement) {
   super(modelScreen, htmlElement);
   List<? extends Element> childElementList = UtilXml.childElementList(htmlElement);
   for (Element childElement : childElementList) {
     if ("html-template".equals(childElement.getNodeName())) {
       this.subWidgets.add(new HtmlTemplate(modelScreen, childElement));
     } else if ("html-template-decorator".equals(childElement.getNodeName())) {
       this.subWidgets.add(new HtmlTemplateDecorator(modelScreen, childElement));
     } else {
       throw new IllegalArgumentException(
           "Tag not supported under the platform-specific -> html tag with name: "
               + childElement.getNodeName());
     }
   }
 }
Esempio n. 20
0
 public CallBsh(Element element, SimpleMethod simpleMethod) throws MiniLangException {
   super(element, simpleMethod);
   if (MiniLangValidate.validationOn()) {
     MiniLangValidate.handleError(
         "<call-bsh> element is deprecated (use <script>)", simpleMethod, element);
     MiniLangValidate.attributeNames(simpleMethod, element, "resource");
     MiniLangValidate.constantAttributes(simpleMethod, element, "resource");
     MiniLangValidate.noChildElements(simpleMethod, element);
   }
   boolean elementModified = autoCorrect(element);
   if (elementModified && MiniLangUtil.autoCorrectOn()) {
     MiniLangUtil.flagDocumentAsCorrected(element);
   }
   this.inline = StringUtil.convertOperatorSubstitutions(UtilXml.elementValue(element));
   this.resource = element.getAttribute("resource");
 }
Esempio n. 21
0
 public CallSimpleMethod(Element element, SimpleMethod simpleMethod) throws MiniLangException {
   super(element, simpleMethod);
   if (MiniLangValidate.validationOn()) {
     MiniLangValidate.attributeNames(
         simpleMethod, element, "method-name", "xml-resource", "scope");
     MiniLangValidate.requiredAttributes(simpleMethod, element, "method-name");
     MiniLangValidate.constantAttributes(
         simpleMethod, element, "method-name", "xml-resource", "scope");
     MiniLangValidate.childElements(simpleMethod, element, "result-to-field");
   }
   this.methodName = element.getAttribute("method-name");
   String xmlResourceAttribute = element.getAttribute("xml-resource");
   if (xmlResourceAttribute.isEmpty()) {
     xmlResourceAttribute = simpleMethod.getFromLocation();
   }
   this.xmlResource = xmlResourceAttribute;
   URL xmlURL = null;
   try {
     xmlURL = FlexibleLocation.resolveLocation(this.xmlResource);
   } catch (MalformedURLException e) {
     MiniLangValidate.handleError(
         "Could not find SimpleMethod XML document in resource: "
             + this.xmlResource
             + "; error was: "
             + e.toString(),
         simpleMethod,
         element);
   }
   this.xmlURL = xmlURL;
   this.scope = element.getAttribute("scope");
   List<? extends Element> resultToFieldElements =
       UtilXml.childElementList(element, "result-to-field");
   if (UtilValidate.isNotEmpty(resultToFieldElements)) {
     if (!"function".equals(this.scope)) {
       MiniLangValidate.handleError(
           "Inline scope cannot include <result-to-field> elements.", simpleMethod, element);
     }
     List<ResultToField> resultToFieldList =
         new ArrayList<ResultToField>(resultToFieldElements.size());
     for (Element resultToFieldElement : resultToFieldElements) {
       resultToFieldList.add(new ResultToField(resultToFieldElement, simpleMethod));
     }
     this.resultToFieldList = resultToFieldList;
   } else {
     this.resultToFieldList = null;
   }
 }
Esempio n. 22
0
  protected static void addEcaDefinitions(
      ResourceHandler handler, Map<String, Map<String, List<EntityEcaRule>>> ecaCache) {
    Element rootElement = null;
    try {
      rootElement = handler.getDocument().getDocumentElement();
    } catch (GenericConfigException e) {
      Debug.logError(e, module);
      return;
    }

    int numDefs = 0;
    for (Element e : UtilXml.childElementList(rootElement, "eca")) {
      String entityName = e.getAttribute("entity");
      String eventName = e.getAttribute("event");
      Map<String, List<EntityEcaRule>> eventMap = ecaCache.get(entityName);
      List<EntityEcaRule> rules = null;
      if (eventMap == null) {
        eventMap = FastMap.newInstance();
        rules = FastList.newInstance();
        ecaCache.put(entityName, eventMap);
        eventMap.put(eventName, rules);
      } else {
        rules = eventMap.get(eventName);
        if (rules == null) {
          rules = FastList.newInstance();
          eventMap.put(eventName, rules);
        }
      }
      rules.add(new EntityEcaRule(e));
      numDefs++;
    }
    try {
      Debug.logImportant(
          "Loaded ["
              + numDefs
              + "] Entity ECA definitions from "
              + handler.getFullLocation()
              + " in loader "
              + handler.getLoaderName(),
          module);
    } catch (GenericConfigException e) {
      Debug.logError(e, module);
      return;
    }
  }
Esempio n. 23
0
  // Load the JMS listeners
  private void loadListeners() {
    try {
      Element rootElement = ServiceConfigUtil.getXmlRootElement();
      NodeList nodeList = rootElement.getElementsByTagName("jms-service");

      if (Debug.verboseOn())
        Debug.logVerbose("[ServiceDispatcher] : Loading JMS Listeners.", module);
      for (int i = 0; i < nodeList.getLength(); i++) {
        Element element = (Element) nodeList.item(i);
        StringBuilder serverKey = new StringBuilder();
        for (Element server : UtilXml.childElementList(element, "server")) {
          try {
            String listenerEnabled = server.getAttribute("listen");

            if (listenerEnabled.equalsIgnoreCase("true")) {
              // create a server key

              serverKey.append(server.getAttribute("jndi-server-name") + ":");
              serverKey.append(server.getAttribute("jndi-name") + ":");
              serverKey.append(server.getAttribute("topic-queue"));
              // store the server element
              servers.put(serverKey.toString(), server);
              // load the listener
              GenericMessageListener listener = loadListener(serverKey.toString(), server);

              // store the listener w/ the key
              if (serverKey.length() > 0 && listener != null)
                listeners.put(serverKey.toString(), listener);
            }
          } catch (GenericServiceException gse) {
            Debug.logInfo(
                "Cannot load message listener " + serverKey + " error: (" + gse.toString() + ").",
                module);
          } catch (Exception e) {
            Debug.logError(e, "Uncaught exception.", module);
          }
        }
      }
    } catch (org.ofbiz.base.config.GenericConfigException gce) {
      Debug.logError(gce, "Cannot get serviceengine.xml root element.", module);
    } catch (Exception e) {
      Debug.logError(e, "Uncaught exception.", module);
    }
  }
Esempio n. 24
0
  /** XML Constructor */
  public ModelScreen(
      Element screenElement, Map<String, ModelScreen> modelScreenMap, String sourceLocation) {
    super(screenElement);
    this.sourceLocation = sourceLocation;
    this.transactionTimeoutExdr =
        FlexibleStringExpander.getInstance(screenElement.getAttribute("transaction-timeout"));
    this.modelScreenMap = modelScreenMap;
    this.useTransaction = "true".equals(screenElement.getAttribute("use-transaction"));
    this.useCache = "true".equals(screenElement.getAttribute("use-cache"));

    // read in the section, which will read all sub-widgets too
    Element sectionElement = UtilXml.firstChildElement(screenElement, "section");
    if (sectionElement == null) {
      throw new IllegalArgumentException(
          "No section found for the screen definition with name: " + this.name);
    }
    this.section = new ModelScreenWidget.Section(this, sectionElement);
    this.section.isMainSection = true;
  }
Esempio n. 25
0
  public static ModelTree getTreeFromWebappContext(
      String resourceName, String treeName, HttpServletRequest request)
      throws IOException, SAXException, ParserConfigurationException {
    String webappName = UtilHttp.getApplicationName(request);
    String cacheKey = webappName + "::" + resourceName;

    Map<String, ModelTree> modelTreeMap = treeWebappCache.get(cacheKey);
    if (modelTreeMap == null) {
      synchronized (TreeFactory.class) {
        modelTreeMap = treeWebappCache.get(cacheKey);
        if (modelTreeMap == null) {
          ServletContext servletContext = (ServletContext) request.getAttribute("servletContext");
          Delegator delegator = (Delegator) request.getAttribute("delegator");
          LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");

          URL treeFileUrl = servletContext.getResource(resourceName);
          Document treeFileDoc = UtilXml.readXmlDocument(treeFileUrl, true);
          modelTreeMap = readTreeDocument(treeFileDoc, delegator, dispatcher, cacheKey);
          treeWebappCache.put(cacheKey, modelTreeMap);
        }
      }
    }

    ModelTree modelTree = (ModelTree) modelTreeMap.get(treeName);
    if (modelTree == null) {
      throw new IllegalArgumentException(
          "Could not find tree with name ["
              + treeName
              + "] in webapp resource ["
              + resourceName
              + "] in the webapp ["
              + webappName
              + "]");
    }
    return modelTree;
  }
  public IterateSectionWidget(ModelScreen modelScreen, Element iterateSectionElement) {
    super(modelScreen, iterateSectionElement);
    listNameExdr = FlexibleMapAccessor.getInstance(iterateSectionElement.getAttribute("list"));
    if (listNameExdr.isEmpty())
      listNameExdr =
          FlexibleMapAccessor.getInstance(iterateSectionElement.getAttribute("list-name"));
    entryNameExdr = FlexibleStringExpander.getInstance(iterateSectionElement.getAttribute("entry"));
    if (entryNameExdr.isEmpty())
      entryNameExdr =
          FlexibleStringExpander.getInstance(iterateSectionElement.getAttribute("entry-name"));
    keyNameExdr = FlexibleStringExpander.getInstance(iterateSectionElement.getAttribute("key"));
    if (keyNameExdr.isEmpty())
      keyNameExdr =
          FlexibleStringExpander.getInstance(iterateSectionElement.getAttribute("key-name"));

    if (this.paginateTarget == null || iterateSectionElement.hasAttribute("paginate-target")) {
      this.paginateTarget =
          FlexibleStringExpander.getInstance(iterateSectionElement.getAttribute("paginate-target"));
    }

    if (this.paginate == null || iterateSectionElement.hasAttribute("paginate")) {
      this.paginate =
          FlexibleStringExpander.getInstance(iterateSectionElement.getAttribute("paginate"));
    }

    if (iterateSectionElement.hasAttribute("view-size")) {
      setViewSize(iterateSectionElement.getAttribute("view-size"));
    }
    sectionList = new ArrayList<ModelScreenWidget.Section>();
    List<? extends Element> childElementList = UtilXml.childElementList(iterateSectionElement);
    for (Element sectionElement : childElementList) {
      ModelScreenWidget.Section section =
          new ModelScreenWidget.Section(modelScreen, sectionElement);
      sectionList.add(section);
    }
  }
Esempio n. 27
0
  public Map<String, ModelEntity> getEntityCache() throws GenericEntityException {
    if (entityCache == null) { // don't want to block here
      synchronized (ModelReader.class) {
        // must check if null again as one of the blocked threads can still enter
        if (entityCache == null) { // now it's safe
          numEntities = 0;
          numViewEntities = 0;
          numFields = 0;
          numRelations = 0;
          numAutoRelations = 0;

          entityCache = new HashMap<String, ModelEntity>();
          List<ModelViewEntity> tempViewEntityList = FastList.newInstance();
          List<Element> tempExtendEntityElementList = FastList.newInstance();

          UtilTimer utilTimer = new UtilTimer();

          for (ResourceHandler entityResourceHandler : entityResourceHandlers) {

            // utilTimer.timerString("Before getDocument in file " + entityFileName);
            Document document = null;

            try {
              document = entityResourceHandler.getDocument();
            } catch (GenericConfigException e) {
              throw new GenericEntityConfException(
                  "Error getting document from resource handler", e);
            }
            if (document == null) {
              throw new GenericEntityConfException(
                  "Could not get document for " + entityResourceHandler.toString());
            }

            // utilTimer.timerString("Before getDocumentElement in " +
            // entityResourceHandler.toString());
            Element docElement = document.getDocumentElement();

            if (docElement == null) {
              return null;
            }
            docElement.normalize();
            Node curChild = docElement.getFirstChild();

            ModelInfo def = new ModelInfo();
            def.populateFromElements(docElement);
            int i = 0;

            if (curChild != null) {
              utilTimer.timerString(
                  "Before start of entity loop in " + entityResourceHandler.toString());
              do {
                boolean isEntity = "entity".equals(curChild.getNodeName());
                boolean isViewEntity = "view-entity".equals(curChild.getNodeName());
                boolean isExtendEntity = "extend-entity".equals(curChild.getNodeName());

                if ((isEntity || isViewEntity) && curChild.getNodeType() == Node.ELEMENT_NODE) {
                  i++;
                  ModelEntity modelEntity =
                      buildEntity(entityResourceHandler, (Element) curChild, i, def);
                  // put the view entity in a list to get ready for the second pass to populate
                  // fields...
                  if (isViewEntity) {
                    tempViewEntityList.add((ModelViewEntity) modelEntity);
                  } else {
                    entityCache.put(modelEntity.getEntityName(), modelEntity);
                  }
                } else if (isExtendEntity && curChild.getNodeType() == Node.ELEMENT_NODE) {
                  tempExtendEntityElementList.add((Element) curChild);
                }
              } while ((curChild = curChild.getNextSibling()) != null);
            } else {
              Debug.logWarning("No child nodes found.", module);
            }
            utilTimer.timerString(
                "Finished "
                    + entityResourceHandler.toString()
                    + " - Total Entities: "
                    + i
                    + " FINISHED");
          }

          // all entity elements in, now go through extend-entity elements and add their stuff
          for (Element extendEntityElement : tempExtendEntityElementList) {
            String entityName = UtilXml.checkEmpty(extendEntityElement.getAttribute("entity-name"));
            ModelEntity modelEntity = entityCache.get(entityName);
            if (modelEntity == null)
              throw new GenericEntityConfException(
                  "Entity to extend does not exist: " + entityName);
            modelEntity.addExtendEntity(this, extendEntityElement);
          }

          // do a pass on all of the view entities now that all of the entities have
          // loaded and populate the fields
          while (!tempViewEntityList.isEmpty()) {
            int startSize = tempViewEntityList.size();
            Iterator<ModelViewEntity> mveIt = tempViewEntityList.iterator();
            TEMP_VIEW_LOOP:
            while (mveIt.hasNext()) {
              ModelViewEntity curViewEntity = mveIt.next();
              for (ModelViewEntity.ModelMemberEntity mve :
                  curViewEntity.getAllModelMemberEntities()) {
                if (!entityCache.containsKey(mve.getEntityName())) {
                  continue TEMP_VIEW_LOOP;
                }
              }
              mveIt.remove();
              curViewEntity.populateFields(this);
              for (ModelViewEntity.ModelMemberEntity mve :
                  curViewEntity.getAllModelMemberEntities()) {
                ModelEntity me = (ModelEntity) entityCache.get(mve.getEntityName());
                me.addViewEntity(curViewEntity);
              }
              entityCache.put(curViewEntity.getEntityName(), curViewEntity);
            }
            if (tempViewEntityList.size() == startSize) {
              // Oops, the remaining views reference other entities
              // that can't be found, or they reference other views
              // that have some reference problem.
              break;
            }
          }
          if (!tempViewEntityList.isEmpty()) {
            StringBuilder sb = new StringBuilder("View entities reference non-existant members:\n");
            Set<String> allViews = FastSet.newInstance();
            for (ModelViewEntity curViewEntity : tempViewEntityList) {
              allViews.add(curViewEntity.getEntityName());
            }
            for (ModelViewEntity curViewEntity : tempViewEntityList) {
              Set<String> perViewMissingEntities = FastSet.newInstance();
              Iterator<ModelViewEntity.ModelMemberEntity> mmeIt =
                  curViewEntity.getAllModelMemberEntities().iterator();
              while (mmeIt.hasNext()) {
                ModelViewEntity.ModelMemberEntity mme = mmeIt.next();
                String memberEntityName = mme.getEntityName();
                if (!entityCache.containsKey(memberEntityName)) {
                  // this member is not a real entity
                  // check to see if it is a view
                  if (!allViews.contains(memberEntityName)) {
                    // not a view, it's a real missing entity
                    perViewMissingEntities.add(memberEntityName);
                  }
                }
              }
              for (String perViewMissingEntity : perViewMissingEntities) {
                sb.append("\t[")
                    .append(curViewEntity.getEntityName())
                    .append("] missing member entity [")
                    .append(perViewMissingEntity)
                    .append("]\n");
              }
            }
            throw new GenericEntityConfException(sb.toString());
          }

          // auto-create relationships
          TreeSet<String> orderedMessages = new TreeSet<String>();
          for (String curEntityName : new TreeSet<String>(this.getEntityNames())) {
            ModelEntity curModelEntity = this.getModelEntity(curEntityName);
            if (curModelEntity instanceof ModelViewEntity) {
              // for view-entities auto-create relationships for all member-entity relationships
              // that have all corresponding fields in the view-entity

            } else {
              // for entities auto-create many relationships for all type one relationships

              // just in case we add a new relation to the same entity, keep in a separate list and
              // add them at the end
              List<ModelRelation> newSameEntityRelations = FastList.newInstance();

              Iterator<ModelRelation> relationsIter = curModelEntity.getRelationsIterator();
              while (relationsIter.hasNext()) {
                ModelRelation modelRelation = relationsIter.next();
                if (("one".equals(modelRelation.getType())
                        || "one-nofk".equals(modelRelation.getType()))
                    && !modelRelation.isAutoRelation()) {
                  ModelEntity relatedEnt = null;
                  try {
                    relatedEnt = this.getModelEntity(modelRelation.getRelEntityName());
                  } catch (GenericModelException e) {
                    throw new GenericModelException(
                        "Error getting related entity ["
                            + modelRelation.getRelEntityName()
                            + "] definition from entity ["
                            + curEntityName
                            + "]",
                        e);
                  }
                  if (relatedEnt != null) {
                    // don't do relationship to the same entity, unless title is "Parent", then do a
                    // "Child" automatically
                    String targetTitle = modelRelation.getTitle();
                    if (curModelEntity.getEntityName().equals(relatedEnt.getEntityName())
                        && "Parent".equals(targetTitle)) {
                      targetTitle = "Child";
                    }

                    // create the new relationship even if one exists so we can show what we are
                    // looking for in the info message
                    ModelRelation newRel = new ModelRelation();
                    newRel.setModelEntity(relatedEnt);
                    newRel.setRelEntityName(curModelEntity.getEntityName());
                    newRel.setTitle(targetTitle);
                    newRel.setAutoRelation(true);
                    Set<String> curEntityKeyFields = FastSet.newInstance();
                    for (int kmn = 0; kmn < modelRelation.getKeyMapsSize(); kmn++) {
                      ModelKeyMap curkm = modelRelation.getKeyMap(kmn);
                      ModelKeyMap newkm = new ModelKeyMap();
                      newRel.addKeyMap(newkm);
                      newkm.setFieldName(curkm.getRelFieldName());
                      newkm.setRelFieldName(curkm.getFieldName());
                      curEntityKeyFields.add(curkm.getFieldName());
                    }
                    // decide whether it should be one or many by seeing if the key map represents
                    // the complete pk of the relEntity
                    if (curModelEntity.containsAllPkFieldNames(curEntityKeyFields)) {
                      // always use one-nofk, we don't want auto-fks getting in for these automatic
                      // ones
                      newRel.setType("one-nofk");

                      // to keep it clean, remove any additional keys that aren't part of the PK
                      List<String> curPkFieldNames = curModelEntity.getPkFieldNames();
                      Iterator<ModelKeyMap> nrkmIter = newRel.getKeyMapsIterator();
                      while (nrkmIter.hasNext()) {
                        ModelKeyMap nrkm = nrkmIter.next();
                        String checkField = nrkm.getRelFieldName();
                        if (!curPkFieldNames.contains(checkField)) {
                          nrkmIter.remove();
                        }
                      }
                    } else {
                      newRel.setType("many");
                    }

                    ModelRelation existingRelation =
                        relatedEnt.getRelation(targetTitle + curModelEntity.getEntityName());
                    if (existingRelation == null) {
                      numAutoRelations++;
                      if (curModelEntity.getEntityName().equals(relatedEnt.getEntityName())) {
                        newSameEntityRelations.add(newRel);
                      } else {
                        relatedEnt.addRelation(newRel);
                      }
                    } else {
                      if (newRel.equals(existingRelation)) {
                        // don't warn if the target title+entity = current title+entity
                        if (!(targetTitle + curModelEntity.getEntityName())
                            .equals(modelRelation.getTitle() + modelRelation.getRelEntityName())) {
                          // String errorMsg = "Relation already exists to entity [] with title [" +
                          // targetTitle + "],from entity []";
                          String message =
                              "Entity ["
                                  + relatedEnt.getPackageName()
                                  + ":"
                                  + relatedEnt.getEntityName()
                                  + "] already has identical relationship to entity ["
                                  + curModelEntity.getEntityName()
                                  + "] title ["
                                  + targetTitle
                                  + "]; would auto-create: type ["
                                  + newRel.getType()
                                  + "] and fields ["
                                  + newRel.keyMapString(",", "")
                                  + "]";
                          orderedMessages.add(message);
                        }
                      } else {
                        String message =
                            "Existing relationship with the same name, but different specs found from what would be auto-created for Entity ["
                                + relatedEnt.getEntityName()
                                + "] and relationship to entity ["
                                + curModelEntity.getEntityName()
                                + "] title ["
                                + targetTitle
                                + "]; would auto-create: type ["
                                + newRel.getType()
                                + "] and fields ["
                                + newRel.keyMapString(",", "")
                                + "]";
                        Debug.logVerbose(message, module);
                      }
                    }
                  } else {
                    String errorMsg =
                        "Could not find related entity ["
                            + modelRelation.getRelEntityName()
                            + "], no reverse relation added.";
                    Debug.logWarning(errorMsg, module);
                  }
                }
              }

              if (newSameEntityRelations.size() > 0) {
                for (ModelRelation newRel : newSameEntityRelations) {
                  curModelEntity.addRelation(newRel);
                }
              }
            }
          }

          for (String message : orderedMessages) {
            Debug.logInfo(message, module);
          }

          Debug.log(
              "FINISHED LOADING ENTITIES - ALL FILES; #Entities="
                  + numEntities
                  + " #ViewEntities="
                  + numViewEntities
                  + " #Fields="
                  + numFields
                  + " #Relationships="
                  + numRelations
                  + " #AutoRelationships="
                  + numAutoRelations,
              module);
        }
      }
    }
    return entityCache;
  }
Esempio n. 28
0
  private ModelEntity buildEntity(
      ResourceHandler entityResourceHandler, Element curEntityElement, int i, ModelInfo def)
      throws GenericEntityException {
    boolean isEntity = "entity".equals(curEntityElement.getNodeName());
    String entityName = UtilXml.checkEmpty(curEntityElement.getAttribute("entity-name")).intern();

    // add entityName to appropriate resourceHandlerEntities collection
    Collection<String> resourceHandlerEntityNames =
        resourceHandlerEntities.get(entityResourceHandler);

    if (resourceHandlerEntityNames == null) {
      resourceHandlerEntityNames = FastList.newInstance();
      resourceHandlerEntities.put(entityResourceHandler, resourceHandlerEntityNames);
    }
    resourceHandlerEntityNames.add(entityName);

    // check to see if entity with same name has already been read
    if (entityCache.containsKey(entityName)) {
      Debug.logWarning(
          "WARNING: Entity "
              + entityName
              + " is defined more than once, most recent will over-write "
              + "previous definition(s)",
          module);
      Debug.logWarning(
          "WARNING: Entity "
              + entityName
              + " was found in "
              + entityResourceHandler
              + ", but was already defined in "
              + entityResourceHandlerMap.get(entityName).toString(),
          module);
    }

    // add entityName, entityFileName pair to entityResourceHandlerMap map
    entityResourceHandlerMap.put(entityName, entityResourceHandler);

    // utilTimer.timerString("  After entityEntityName -- " + i + " --");
    // ModelEntity entity = createModelEntity(curEntity, utilTimer);

    ModelEntity modelEntity = null;
    if (isEntity) {
      modelEntity = createModelEntity(curEntityElement, null, def);
    } else {
      modelEntity = createModelViewEntity(curEntityElement, null, def);
    }

    String resourceLocation = entityResourceHandler.getLocation();
    try {
      resourceLocation = entityResourceHandler.getURL().toExternalForm();
    } catch (GenericConfigException e) {
      Debug.logError(e, "Could not get resource URL", module);
    }

    // utilTimer.timerString("  After createModelEntity -- " + i + " --");
    if (modelEntity != null) {
      modelEntity.setLocation(resourceLocation);
      // utilTimer.timerString("  After entityCache.put -- " + i + " --");
      if (isEntity) {
        if (Debug.verboseOn()) Debug.logVerbose("-- [Entity]: #" + i + ": " + entityName, module);
      } else {
        if (Debug.verboseOn())
          Debug.logVerbose("-- [ViewEntity]: #" + i + ": " + entityName, module);
      }
    } else {
      Debug.logWarning(
          "-- -- ENTITYGEN ERROR:getModelEntity: Could not create "
              + "entity for entityName: "
              + entityName,
          module);
    }
    return modelEntity;
  }
  @Override
  public SearchResult getLdapSearchResult(
      String username, String password, Element rootElement, boolean bindRequired)
      throws NamingException {
    DirContext ctx = null;
    SearchResult result = null;
    String ldapURL = UtilXml.childElementValue(rootElement, "URL", "ldap://localhost:389");
    String authenType = UtilXml.childElementValue(rootElement, "AuthenType", "simple");
    String searchType = UtilXml.childElementValue(rootElement, "SearchType", "");
    String baseDN = UtilXml.childElementValue(rootElement, "BaseDN");
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapURL);
    if (searchType == null || searchType.trim().equals("")) {
      env.put(Context.SECURITY_AUTHENTICATION, "none");
    } else if (searchType.trim().equals("login")) {
      env.put(Context.SECURITY_AUTHENTICATION, authenType);
      // specify the username for search
      String userDNForSearch = UtilXml.childElementValue(rootElement, "UserDNForSearch");
      env.put(Context.SECURITY_PRINCIPAL, userDNForSearch);
      // specify the password for search
      String passwordForSearch = UtilXml.childElementValue(rootElement, "PasswordForSearch");
      env.put(Context.SECURITY_CREDENTIALS, passwordForSearch);
    }
    try {
      ctx = new InitialDirContext(env);
      SearchControls controls = new SearchControls();
      // ldap search timeout
      controls.setTimeLimit(1000);
      // ldap search count
      controls.setCountLimit(2);
      // ldap search scope
      String sub = UtilXml.childElementValue(rootElement, "Scope", "sub").toLowerCase().trim();
      if (sub.equals("sub")) {
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
      } else if (sub.equals("one")) {
        controls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
      } else {
        controls.setSearchScope(SearchControls.OBJECT_SCOPE);
      }
      String filter = UtilXml.childElementValue(rootElement, "Filter", "(objectclass=*)");
      String attribute = UtilXml.childElementValue(rootElement, "Attribute", "uid=%u");
      attribute = LdapUtils.getFilterWithValues(attribute, username);
      NamingEnumeration<SearchResult> answer =
          ctx.search(
              baseDN,
              // Filter expression
              "(&(" + filter + ") (" + attribute + "))",
              controls);
      if (answer.hasMoreElements()) {
        result = answer.next();
        if (bindRequired) {
          env.put(Context.SECURITY_AUTHENTICATION, authenType);
          // specify the username
          String userDN = result.getName() + "," + baseDN;
          env.put(Context.SECURITY_PRINCIPAL, userDN);
          // specify the password
          env.put(Context.SECURITY_CREDENTIALS, password);
          ctx = new InitialDirContext(env);
        }
      }
    } catch (NamingException e) {
      // No ldap service found, or cannot login.
      throw new NamingException(e.getLocalizedMessage());
    }

    return result;
  }
 public ModelScreenCondition(ModelScreen modelScreen, Element conditionElement) {
   this.modelScreen = modelScreen;
   Element firstChildElement = UtilXml.firstChildElement(conditionElement);
   this.rootCondition = readCondition(modelScreen, firstChildElement);
 }