Esempio n. 1
0
  /**
   * Builds the argument invocation string for calling a constructor
   *
   * @param classVariables The collection of member variables as XMLElements
   * @param constructorArguments The set of names for constructor arguments
   * @param allocatedMemberVariables The set of member variables already allocated
   * @param element The specific 'new' xml element
   */
  private static String buildArguments(
      Vector classVariables,
      Set constructorArguments,
      Set allocatedMemberVariables,
      IXMLElement element)
      throws IOException {
    XMLUtil.checkExpectedNode("new", element);

    boolean comma = false;
    String arguments = "";
    for (Enumeration e = element.enumerateChildren(); e.hasMoreElements(); ) {
      IXMLElement argument = (IXMLElement) e.nextElement();
      String argType = ModelAccessor.getValueType(argument);
      String value = ModelAccessor.getValue(argument);

      /* Exclude cases where we do nothing to the value */
      if (!primitives.contains(argType) && !value.equals("true") && !value.equals("false")) {
        // CASE 0: Translate 'this'
        if (value.equalsIgnoreCase("this")) {
          value = "m_id";
        }

        // CASE 1: It is a singleton member variable which must be mapped to the singleton
        else if (allocatedMemberVariables.contains(value)) {
          String singletonType = getVariableType(classVariables, value);
          if (primitives.contains(singletonType)) {
            value = "(" + singletonType + ") singleton(" + value + ")";
          } else value = "singleton(" + value + ")";
        }

        // CASE 2: It is a constructor argument
        else if (constructorArguments.contains(value)) { // Do nothing, just use the string as is.
        }

        // CASE 3: Test for error - using a member before initializing it
        else if (!allocatedMemberVariables.contains(value) && isMember(classVariables, value)) {
          value = "!ERROR: Cannot use " + value + " without prior initialization.";
        }

        // Otherwise it is a string or enumerataion
        else if (argType.equals("string")
            || // It is an enumeartion of some kind
            ModelAccessor.isEnumeration(argType)
            || argType.equals("symbol")) {
          value = "LabelStr(\"" + XMLUtil.escapeQuotes(value) + "\")";
        }

        // If we fall through to here, there is an error.
        else value = "!ERROR:BAD ASSIGNMENT";
      }

      // CASE 3: It is a true or false value
      if (comma) arguments = arguments + ", ";

      arguments = arguments + value;
      comma = true;
    }

    return arguments;
  }
Esempio n. 2
0
  /**
   * Helper method to generate the signatures for binding the factory. Must account for the
   * inheritance relationships for any arguments that are classes. Ths, each argument can
   * potentially result in a range of values for type, and we have to handle the cross product of
   * all of these.
   */
  private static Vector makeFactoryNames(IXMLElement constructor) {
    String factoryName = XMLUtil.nameOf(constructor.getParent());
    Vector allPermutations = new Vector();
    for (Enumeration e = constructor.enumerateChildren(); e.hasMoreElements(); ) {
      IXMLElement element = (IXMLElement) e.nextElement();

      if (!element.getName().equals("arg")) {
        break;
      }

      String argType = XMLUtil.typeOf(element);
      Vector argTypeAlternates = new Vector();
      argTypeAlternates.add(argType);

      if (ModelAccessor.isClass(argType)) {
        List ancestors = ModelAccessor.getAncestors(argType);
        if (ancestors != null) argTypeAlternates.addAll(ancestors);
      }

      allPermutations.add(argTypeAlternates);
    }

    // Generate all the signatures
    Vector factoryNames = new Vector();
    makeFactoryNames(factoryName, allPermutations, 0, factoryNames);
    return factoryNames;
  }
Esempio n. 3
0
  /** @brief Generates the signature for the class constructors */
  private static void generateSignature(IndentWriter writer, IXMLElement constructor)
      throws IOException {
    assert (DebugMsg.debugMsg("ClassWriter", "Begin ClassWriter::generateSignature"));
    writer.write("constructor(");
    boolean comma = false;
    for (Enumeration e = constructor.enumerateChildren(); e.hasMoreElements(); ) {
      IXMLElement element = (IXMLElement) e.nextElement();
      if (!element.getName().equals("arg")) {
        break;
      }
      String argType = XMLUtil.typeOf(element);
      String argName = XMLUtil.getAttribute(element, "name");
      if (comma) {
        writer.write(", ");
      }

      // Argument are structured as: <arg name="argName" type="argType"/>
      if (argType.equals(NddlXmlStrings.x_int)) writer.write("int " + argName);
      else if (argType.equals(NddlXmlStrings.x_float)) writer.write("double " + argName);
      else if (argType.equals(NddlXmlStrings.x_boolean)) writer.write("bool " + argName);
      else if (argType.equals(NddlXmlStrings.x_string)
          || argType.equals(NddlXmlStrings.x_symbol)
          || ModelAccessor.isEnumeration(argType)) writer.write("const LabelStr& " + argName);
      else writer.write("const " + argType + "Id& " + argName);

      comma = true;
    }
    writer.write(")");
    assert (DebugMsg.debugMsg("ClassWriter", "End ClassWriter::generateSignature"));
  }
Esempio n. 4
0
  public static void generateImplementation(IndentWriter writer, IXMLElement klass)
      throws IOException {
    String superClass = ModelAccessor.getSuperClass(klass);
    String name = XMLUtil.getAttribute(klass, "name");

    if (ModelAccessor.isPredefinedClass(name)) {
      writer.write("// SKIPPING IMPLEMENTATION FOR BUILT-IN CLASS " + name + "\n\n");
      return;
    }

    ModelAccessor.setCurrentObjectType(name);

    String longname = XMLUtil.qualifiedName(klass);

    boolean extendsBuiltIn = ModelAccessor.isPredefinedClass(superClass);

    String superCppClass = ModelAccessor.getCppClass(superClass);

    writer.write("\n");
    SharedWriter.generateFileLocation(writer, klass);
    writer.write(
        longname + "::" + name + "(const PlanDatabaseId& planDatabase, const LabelStr& name)\n");
    if (extendsBuiltIn)
      writer.write(" : " + superCppClass + "(planDatabase, \"" + name + "\", name, true)");
    else writer.write(" : " + superCppClass + "(planDatabase, \"" + name + "\", name)");
    writer.write(" {\n");
    writer.write("}\n");

    writer.write(
        longname
            + "::"
            + name
            + "(const PlanDatabaseId& planDatabase, const LabelStr& type, const LabelStr& name)\n");
    if (extendsBuiltIn) writer.write(" : " + superCppClass + "(planDatabase, type, name, true)");
    else writer.write(" : " + superCppClass + "(planDatabase, type, name)");
    writer.write(" {\n");
    writer.write("}\n");

    writer.write(longname + "::" + name + "(const ObjectId& parent, const LabelStr& name)\n");
    if (extendsBuiltIn)
      writer.write(" : " + superCppClass + "(parent, \"" + name + "\", name, true)");
    else writer.write(" : " + superCppClass + "(parent, \"" + name + "\", name)");
    writer.write(" {}\n");

    writer.write(
        longname
            + "::"
            + name
            + "(const ObjectId& parent, const LabelStr& type, const LabelStr& name)\n");
    if (extendsBuiltIn) writer.write(" : " + superCppClass + "(parent, type, name, true)");
    else writer.write(" : " + superCppClass + "(parent, type, name)");
    writer.write(" {}\n");

    Vector classVariables = klass.getChildrenNamed("var");
    SharedWriter.defineHandleDefaults(writer, klass, classVariables);

    generateChildren(writer, klass);
    ModelAccessor.resetCurrentObjectType();
  }
Esempio n. 5
0
 private static String getVariableType(Vector classVariables, String name) {
   String type = "!ERROR";
   for (int i = 0; i < classVariables.size(); i++) {
     IXMLElement variable = (IXMLElement) classVariables.elementAt(i);
     if (XMLUtil.nameOf(variable).equals(name)) {
       type = XMLUtil.getAttribute(variable, "type");
       String _class = XMLUtil.getAttribute(variable.getParent(), "name");
       if (ModelAccessor.isEnumeration(_class + "::" + type)) type = _class + "::" + type;
       break;
     }
   }
   return type;
 }
  public void readFileAndGenerate(boolean onlyUniquePeptides, ISpectrumDataFilter... filters) {
    @SuppressWarnings("UnusedDeclaration")
    int numberProcessed = 0;
    @SuppressWarnings("UnusedDeclaration")
    double lastRetentionTime = 0;

    @SuppressWarnings("UnusedDeclaration")
    int numberUnProcessed = 0;
    try {
      LineNumberReader rdr = new LineNumberReader(new FileReader(m_File));
      String line = rdr.readLine();
      while (line != null) {
        if (line.contains("<spectrum_query")) {
          String retention_time_sec = XMLUtil.extractAttribute(line, "retention_time_sec");
          scan_id = XMLUtil.extractAttribute(line, "start_scan");
          if (retention_time_sec == null) {
            lastRetentionTime = 0;
          } else {
            try {
              lastRetentionTime = Double.parseDouble(retention_time_sec.trim());
            } catch (NumberFormatException e) {
              lastRetentionTime = 0;
            }
          }
        }

        //noinspection StatementWithEmptyBody,StatementWithEmptyBody
        if (line.contains("<search_result")) {
          String[] searchHitLines = readSearchHitLines(line, rdr);
          //              System.out.println(line);
          boolean processed =
              handleSearchHit(searchHitLines, lastRetentionTime, onlyUniquePeptides, filters);
          if (processed) {
            for (int i = 0; i < searchHitLines.length; i++) {
              @SuppressWarnings("UnusedDeclaration")
              String searchHitLine = searchHitLines[i];
            }
            numberProcessed++;
          } else numberUnProcessed++;
        }
        line = rdr.readLine();
      }

      //noinspection UnnecessaryReturnStatement
      return;
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
Esempio n. 7
0
 /** Test if the given variable name is listed in the vector of variable xml elements */
 private static boolean isMember(Vector classVariables, String name) {
   for (int i = 0; i < classVariables.size(); i++) {
     IXMLElement variable = (IXMLElement) classVariables.elementAt(i);
     if (XMLUtil.nameOf(variable).equals(name)) return true;
   }
   return false;
 }
Esempio n. 8
0
  public static void generateDefaultFactory(IndentWriter writer, IXMLElement klass)
      throws IOException {
    SharedWriter.generateFileLocation(writer, klass);

    if (klass == null) {
      throw new RuntimeException("missing class for factory");
    }

    String longname = XMLUtil.nameOf(klass) + "Factory" + s_factoryCounter++;
    String klassName = XMLUtil.nameOf(klass);

    writer.write("DECLARE_DEFAULT_OBJECT_FACTORY(" + longname + ", " + klassName + ");\n");

    // Generate all appropriate registration information
    SchemaWriter.addFactory("REGISTER_OBJECT_FACTORY(id," + longname + ", " + klassName + ");\n");
  }
 /**
  * This method returns a Document from the contents of the XML file as contained in the String
  * xmlFile, with no restriction as to the root element.
  */
 public Document loadXMLFile(String xmlFile) {
   if (!StringUtil.blank(xmlFile)) {
     Document CipresDoc = XMLUtil.getDocumentFromString(xmlFile);
     return CipresDoc;
   }
   return null;
 }
 public static IdentifiedPSM processPeptide(final String line, double retentionTime, String id) {
   String peptide = XMLUtil.extractAttribute(line, "peptide");
   if (peptide == null) throw new IllegalArgumentException("bad line " + line);
   Polypeptide polypeptide = Polypeptide.fromString(peptide);
   polypeptide.setRetentionTime(retentionTime);
   return new IdentifiedPSM(id, polypeptide);
 }
Esempio n. 11
0
 /**
  * Sets the {@linkplain #rootTag} property.
  *
  * @param rootTag to be used as XML root tag
  * @throws IllegalArgumentException if tag is null or empty
  * @throws IllegalStateException if write isn't in initial state
  */
 public void setRootTag(String rootTag) {
   if (!XMLUtil.isLegalXMLTag(rootTag)) {
     throw new IllegalArgumentException("rootTag: illegal: " + rootTag);
   }
   if (!this.isInitialState()) {
     throw new IllegalStateException("writer write in progress");
   }
   this.checkNotSharedConfiguration();
   this.rootTag = rootTag;
 }
Esempio n. 12
0
 public static void declareConstructor(IndentWriter writer, IXMLElement constructor)
     throws IOException {
   IXMLElement klass = constructor.getParent();
   SharedWriter.generateFileLocation(writer, klass);
   if (klass == null) {
     throw new RuntimeException("constructor not contained in a class");
   }
   String name = XMLUtil.getAttribute(klass, "name");
   writer.write("virtual void ");
   generateSignature(writer, constructor);
   writer.write(";\n");
 }
Esempio n. 13
0
 private static void generateChildren(IndentWriter writer, IXMLElement parent) throws IOException {
   for (Enumeration e = parent.enumerateChildren(); e.hasMoreElements(); ) {
     IXMLElement element = (IXMLElement) e.nextElement();
     if (element.getName().equals("enum")) {
       EnumerationWriter.generateImplementation(writer, element);
     } else if (element.getName().equals("predicate")) {
       PredicateWriter.generateImplementation(writer, element);
     } else if (element.getName().equals("var")) {
     } else if (element.getName().equals("constructor")) {
       defineConstructor(writer, element);
       generateFactory(writer, element);
     } else {
       System.err.println("generateImplementation:");
       XMLUtil.dump(element);
     }
   }
 }
  protected void init(Element root) {
    NodeList children = root.getChildNodes();

    for (int i = 0; i < children.getLength(); i++) {
      Node child = children.item(i);

      if (child.getNodeName().equals("meta")) {
        Element meta = (Element) child;
        String value = XMLUtil.getText(meta);
        this.metaAttributes.put(meta.getAttribute("name"), value);
      }
    }

    // handle registers - OPTIONAL
    Element r = XMLUtil.getChildElement(root, "registers");

    if (r != null) {
      List registers = XMLUtil.getChildElements(r, "register");

      for (int i = 0; i < registers.size(); i++) {
        Element register = (Element) registers.get(i);
        RegisterDescriptor registerDescriptor =
            DescriptorFactory.getFactory().createRegisterDescriptor(register);
        registerDescriptor.setParent(this);
        this.registers.add(registerDescriptor);
      }
    }

    // handle global-conditions - OPTIONAL
    Element globalConditionsElement = XMLUtil.getChildElement(root, "global-conditions");

    if (globalConditionsElement != null) {
      Element globalConditions = XMLUtil.getChildElement(globalConditionsElement, "conditions");

      ConditionsDescriptor conditionsDescriptor =
          DescriptorFactory.getFactory().createConditionsDescriptor(globalConditions);
      conditionsDescriptor.setParent(this);
      this.globalConditions = conditionsDescriptor;
    }

    // handle initial-steps - REQUIRED
    Element intialActionsElement = XMLUtil.getChildElement(root, "initial-actions");
    List initialActions = XMLUtil.getChildElements(intialActionsElement, "action");

    for (int i = 0; i < initialActions.size(); i++) {
      Element initialAction = (Element) initialActions.get(i);
      ActionDescriptor actionDescriptor =
          DescriptorFactory.getFactory().createActionDescriptor(initialAction);
      actionDescriptor.setParent(this);
      this.initialActions.add(actionDescriptor);
    }

    // handle global-actions - OPTIONAL
    Element globalActionsElement = XMLUtil.getChildElement(root, "global-actions");

    if (globalActionsElement != null) {
      List globalActions = XMLUtil.getChildElements(globalActionsElement, "action");

      for (int i = 0; i < globalActions.size(); i++) {
        Element globalAction = (Element) globalActions.get(i);
        ActionDescriptor actionDescriptor =
            DescriptorFactory.getFactory().createActionDescriptor(globalAction);
        actionDescriptor.setParent(this);
        this.globalActions.add(actionDescriptor);
      }
    }

    // handle common-actions - OPTIONAL
    //   - Store actions in HashMap for now. When parsing Steps, we'll resolve
    //      any common actions into local references.
    Element commonActionsElement = XMLUtil.getChildElement(root, "common-actions");

    if (commonActionsElement != null) {
      List commonActions = XMLUtil.getChildElements(commonActionsElement, "action");

      for (int i = 0; i < commonActions.size(); i++) {
        Element commonAction = (Element) commonActions.get(i);
        ActionDescriptor actionDescriptor =
            DescriptorFactory.getFactory().createActionDescriptor(commonAction);
        actionDescriptor.setParent(this);
        addCommonAction(actionDescriptor);
      }
    }

    // handle timer-functions - OPTIONAL
    Element timerFunctionsElement = XMLUtil.getChildElement(root, "trigger-functions");

    if (timerFunctionsElement != null) {
      List timerFunctions = XMLUtil.getChildElements(timerFunctionsElement, "trigger-function");

      for (int i = 0; i < timerFunctions.size(); i++) {
        Element timerFunction = (Element) timerFunctions.get(i);
        Integer id = new Integer(timerFunction.getAttribute("id"));
        FunctionDescriptor function =
            DescriptorFactory.getFactory()
                .createFunctionDescriptor(XMLUtil.getChildElement(timerFunction, "function"));
        function.setParent(this);
        this.timerFunctions.put(id, function);
      }
    }

    // handle steps - REQUIRED
    Element stepsElement = XMLUtil.getChildElement(root, "steps");
    List steps = XMLUtil.getChildElements(stepsElement, "step");

    for (int i = 0; i < steps.size(); i++) {
      Element step = (Element) steps.get(i);
      StepDescriptor stepDescriptor =
          DescriptorFactory.getFactory().createStepDescriptor(step, this);
      this.steps.add(stepDescriptor);
    }

    // handle splits - OPTIONAL
    Element splitsElement = XMLUtil.getChildElement(root, "splits");

    if (splitsElement != null) {
      List split = XMLUtil.getChildElements(splitsElement, "split");

      for (int i = 0; i < split.size(); i++) {
        Element s = (Element) split.get(i);
        SplitDescriptor splitDescriptor = DescriptorFactory.getFactory().createSplitDescriptor(s);
        splitDescriptor.setParent(this);
        this.splits.add(splitDescriptor);
      }
    }

    // handle joins - OPTIONAL:
    Element joinsElement = XMLUtil.getChildElement(root, "joins");

    if (joinsElement != null) {
      List join = XMLUtil.getChildElements(joinsElement, "join");

      for (int i = 0; i < join.size(); i++) {
        Element s = (Element) join.get(i);
        JoinDescriptor joinDescriptor = DescriptorFactory.getFactory().createJoinDescriptor(s);
        joinDescriptor.setParent(this);
        this.joins.add(joinDescriptor);
      }
    }
  }
  public void writeXML(PrintWriter out, int indent) {
    XMLUtil.printIndent(out, indent++);
    out.println("<workflow>");

    Iterator iter = metaAttributes.entrySet().iterator();

    while (iter.hasNext()) {
      Map.Entry entry = (Map.Entry) iter.next();
      XMLUtil.printIndent(out, indent);
      out.print("<meta name=\"");
      out.print(XMLUtil.encode(entry.getKey()));
      out.print("\">");
      out.print(XMLUtil.encode(entry.getValue()));
      out.println("</meta>");
    }

    if (registers.size() > 0) {
      XMLUtil.printIndent(out, indent++);
      out.println("<registers>");

      for (int i = 0; i < registers.size(); i++) {
        RegisterDescriptor register = (RegisterDescriptor) registers.get(i);
        register.writeXML(out, indent);
      }

      XMLUtil.printIndent(out, --indent);
      out.println("</registers>");
    }

    if (timerFunctions.size() > 0) {
      XMLUtil.printIndent(out, indent++);
      out.println("<trigger-functions>");

      Iterator iterator = timerFunctions.entrySet().iterator();

      while (iterator.hasNext()) {
        Map.Entry entry = (Map.Entry) iterator.next();
        XMLUtil.printIndent(out, indent++);
        out.println("<trigger-function id=\"" + entry.getKey() + "\">");

        FunctionDescriptor trigger = (FunctionDescriptor) entry.getValue();
        trigger.writeXML(out, indent);
        XMLUtil.printIndent(out, --indent);
        out.println("</trigger-function>");
      }

      while (iterator.hasNext()) {}

      XMLUtil.printIndent(out, --indent);
      out.println("</trigger-functions>");
    }

    if (getGlobalConditions() != null) {
      XMLUtil.printIndent(out, indent++);
      out.println("<global-conditions>");

      getGlobalConditions().writeXML(out, indent);

      out.println("</global-conditions>");
    }

    XMLUtil.printIndent(out, indent++);
    out.println("<initial-actions>");

    for (int i = 0; i < initialActions.size(); i++) {
      ActionDescriptor action = (ActionDescriptor) initialActions.get(i);
      action.writeXML(out, indent);
    }

    XMLUtil.printIndent(out, --indent);
    out.println("</initial-actions>");

    if (globalActions.size() > 0) {
      XMLUtil.printIndent(out, indent++);
      out.println("<global-actions>");

      for (int i = 0; i < globalActions.size(); i++) {
        ActionDescriptor action = (ActionDescriptor) globalActions.get(i);
        action.writeXML(out, indent);
      }

      XMLUtil.printIndent(out, --indent);
      out.println("</global-actions>");
    }

    if (commonActions.size() > 0) {
      XMLUtil.printIndent(out, indent++);
      out.println("<common-actions>");

      Iterator iterator = getCommonActions().values().iterator();

      while (iterator.hasNext()) {
        ActionDescriptor action = (ActionDescriptor) iterator.next();
        action.writeXML(out, indent);
      }

      XMLUtil.printIndent(out, --indent);
      out.println("</common-actions>");
    }

    XMLUtil.printIndent(out, indent++);
    out.println("<steps>");

    for (int i = 0; i < steps.size(); i++) {
      StepDescriptor step = (StepDescriptor) steps.get(i);
      step.writeXML(out, indent);
    }

    XMLUtil.printIndent(out, --indent);
    out.println("</steps>");

    if (splits.size() > 0) {
      XMLUtil.printIndent(out, indent++);
      out.println("<splits>");

      for (int i = 0; i < splits.size(); i++) {
        SplitDescriptor split = (SplitDescriptor) splits.get(i);
        split.writeXML(out, indent);
      }

      XMLUtil.printIndent(out, --indent);
      out.println("</splits>");
    }

    if (joins.size() > 0) {
      XMLUtil.printIndent(out, indent++);
      out.println("<joins>");

      for (int i = 0; i < joins.size(); i++) {
        JoinDescriptor join = (JoinDescriptor) joins.get(i);
        join.writeXML(out, indent);
      }

      XMLUtil.printIndent(out, --indent);
      out.println("</joins>");
    }

    XMLUtil.printIndent(out, --indent);
    out.println("</workflow>");
  }
Esempio n. 16
0
 /**
  * Aliases the given field's name with the given <code>alias</code>. The given alias must not be
  * non-null, not-empty and must not contain illegal characters w.r.t. the XML format.
  *
  * @param f to alias
  * @param alias the alias to set
  * @return the previous alias, if any, or null
  * @throws IllegalArgumentException if alias contains invalid XML chars
  * @throws IllegalStateException if shared configuration
  */
 public String alias(Field f, String alias) {
   XMLUtil.validateAlias(alias);
   this.checkNotSharedConfiguration();
   return this.aliasing.put(f, alias);
 }
Esempio n. 17
0
  public static void defineConstructor(IndentWriter writer, IXMLElement constructor)
      throws IOException {
    assert (DebugMsg.debugMsg("ClassWriter", "Begin ClassWriter::defineConstructor"));
    IXMLElement klass = constructor.getParent();
    SharedWriter.generateFileLocation(writer, klass);

    if (klass == null) {
      throw new RuntimeException("missing class for constructor");
    }

    String longname = XMLUtil.nameOf(klass);
    writer.write("void " + longname + "::");
    generateSignature(writer, constructor);
    writer.write(" {\n");
    writer.indent();

    // If the constructor has a call to the super class, invoke it.
    assert (DebugMsg.debugMsg(
        "ClassWriter", "ClassWriter::defineConstructor -  getting children named 'super'"));
    Vector superCalls = constructor.getChildrenNamed("super");
    assert (DebugMsg.debugMsg(
        "ClassWriter",
        "ClassWriter::defineConstructor -  " + superCalls.size() + " children named retrieved"));
    if (!superCalls.isEmpty()) {
      assert (DebugMsg.debugMsg("ClassWriter", "ClassWriter::defineConstructor -  calling super"));

      if (superCalls.size() > 1) writer.write("!ERROR: AT MOST ONE CALL TO SUPER ALLOWED\n");

      IXMLElement superCall = (IXMLElement) superCalls.elementAt(0);
      String superClass = ModelAccessor.getParentClassName(klass);
      String superCppClass = ModelAccessor.getCppClass(superClass);
      writer.write(superCppClass + "::constructor(");
      String comma = "";
      Enumeration arguments = superCall.enumerateChildren();
      while (arguments.hasMoreElements()) {
        IXMLElement argument = (IXMLElement) arguments.nextElement();
        String value = ModelAccessor.getValue(argument);
        if (argument.getName().equals("value")
            && XMLUtil.getAttribute(argument, "type").equals("string"))
          writer.write(comma + "\"" + value + "\"");
        else writer.write(comma + value);
        comma = ", ";
      }
      writer.write(");\n");
    }

    Set allocatedMemberVariables = new HashSet(); // Store names as we go for reference

    /* Now capture names of constructor arguments */
    Set constructorArguments = new HashSet(); // Store for names of constructor arguments
    {
      Vector args = constructor.getChildrenNamed("arg");
      assert (DebugMsg.debugMsg(
          "ClassWriter",
          "ClassWriter::defineConstructor -  getting " + args.size() + " arguments"));
      for (int i = 0; i < args.size(); i++) {
        IXMLElement arg = (IXMLElement) args.elementAt(i);
        String argName = XMLUtil.getAttribute(arg, "name");
        constructorArguments.add(argName);
      }
    }

    Vector constructorAssignments = constructor.getChildrenNamed("assign");
    Vector classVariables = klass.getChildrenNamed("var");

    // Use the set below  to track when an assignment is being made more than once for same variable
    Set assignmentsMade = new HashSet();

    for (int i = 0; i < constructorAssignments.size(); i++) {
      IXMLElement element = (IXMLElement) constructorAssignments.elementAt(i);
      String target = XMLUtil.getAttribute(element, "name");

      if (assignmentsMade.contains(target)) {
        writer.write("!ERROR: Duplicate assignment for " + target + "\n");
      } else {
        assignmentsMade.add(target);
        // String type = getVariableType(classVariables, target);
        // trust in the parser, for it will assign the correct types
        String type = XMLUtil.getAttribute(element, "type");
        IXMLElement sourceElement = element.getChildAtIndex(0);

        if (sourceElement.getName().equals("new")) { // Handle object allocation
          assert (DebugMsg.debugMsg(
              "ClassWriter", "ClassWriter::defineConstructor -  allocating object for " + target));
          String sourceType = XMLUtil.typeOf(sourceElement);
          writer.write(target + " = addVariable(");
          writer.write(
              sourceType
                  + "Domain((new "
                  + sourceType
                  + "(m_id, \""
                  + target
                  + "\"))->getId(), \""
                  + sourceType
                  + "\")");
          writer.write(", " + makeObjectVariableNameString(target) + ");\n");
          writer.write(
              "Id<"
                  + type
                  + ">(singleton("
                  + target
                  + "))->constructor("
                  + buildArguments(
                      classVariables, constructorArguments, allocatedMemberVariables, sourceElement)
                  + ");\n"); // Invoke initialization
          writer.write(
              "Id<"
                  + type
                  + ">(singleton("
                  + target
                  + "))->handleDefaults();\n"); // Default variable setup
        } else { // Handle variable allocation
          String value = ModelAccessor.getValue(sourceElement);

          if (sourceElement.getName().equals("id") && type.equals(NddlXmlStrings.x_string))
            value = XMLUtil.escapeQuotes(value);
          else if (sourceElement.getName().equals(NddlXmlStrings.x_symbol)
              || XMLUtil.getAttribute(sourceElement, "type").equals(NddlXmlStrings.x_string))
            value = "LabelStr(\"" + XMLUtil.escapeQuotes(value) + "\")";
          else if (ModelAccessor.isNumericPrimitive(type)
              && !type.equals(NddlXmlStrings.x_boolean)) {
            // Set both bounds to singleton value
            value = value + ", " + value;
          }

          writer.write(target + " = addVariable(");

          if (allocatedMemberVariables.contains(
              value)) // If we are assigning one member to another, we obtain the base domain for it
          writer.write(value + "->baseDomain()");
          else writer.write(ModelAccessor.getDomain(type) + "(" + value + ", \"" + type + "\")");

          writer.write(", " + makeObjectVariableNameString(target) + ");\n");
        }
        // Add member to the set
        allocatedMemberVariables.add(target);
      }
    }

    writer.unindent();
    writer.write("}\n");
    assert (DebugMsg.debugMsg("ClassWriter", "End ClassWriter::defineConstructor"));
  }
 public static IProtein processProtein(final String line) {
   String peptide = XMLUtil.extractAttribute(line, "protein_descr");
   if (peptide == null) throw new IllegalArgumentException("bad line " + line);
   return Protein.getProtein(peptide, "", "", null);
 }
 public CIPResCommunicator(MesquiteModule mb, String xmlPrefsString, String[] outputFilePaths) {
   if (xmlPrefsString != null) XMLUtil.readXMLPreferences(mb, this, xmlPrefsString);
   this.outputFilePaths = outputFilePaths;
   ownerModule = mb;
 }
Esempio n. 20
0
  public static void generateFactory(IndentWriter writer, IXMLElement constructor)
      throws IOException {
    IXMLElement klass = constructor.getParent();
    SharedWriter.generateFileLocation(writer, klass);

    if (klass == null) throw new RuntimeException("missing class for factory");

    String longname = XMLUtil.nameOf(klass) + "Factory" + s_factoryCounter++;

    writer.write("class " + longname + ": public ObjectFactory {\n");
    writer.write("public:\n");
    writer.indent();
    writer.write(longname + "(const LabelStr& name): ObjectFactory(name){}\n");
    writer.unindent();
    writer.write("private:\n");
    writer.indent();
    writer.write("ObjectId createInstance(const PlanDatabaseId& planDb,\n");
    writer.write("                        const LabelStr& objectType, \n");
    writer.write("                        const LabelStr& objectName,\n");
    writer.write(
        "                        const std::vector<const AbstractDomain*>& arguments) const {\n");
    writer.indent();

    Vector constructorAssignments = constructor.getChildrenNamed("arg");
    String klassName = XMLUtil.nameOf(klass);
    String constructorArguments = "";
    String comma = "";

    // Do some type checking - at least the size must match!
    writer.write("check_error(arguments.size() == " + constructorAssignments.size() + ");\n");

    // Process arguments, defining local variables and giving them initial values
    for (int i = 0; i < constructorAssignments.size(); i++) {
      IXMLElement element = (IXMLElement) constructorAssignments.elementAt(i);
      String target = XMLUtil.getAttribute(element, "name");
      String type = XMLUtil.getAttribute(element, "type");
      writer.write("check_error(AbstractDomain::canBeCompared(*arguments[" + i + "], \n");
      writer.write(
          "                                          planDb->getConstraintEngine()->getCESchema()->baseDomain(\""
              + type
              + "\")), \n");
      writer.write(
          "            \"Cannot convert \" + arguments["
              + i
              + "]->getTypeName().toString() + \" to "
              + type
              + "\");\n");
      writer.write("check_error(arguments[" + i + "]->isSingleton());\n");

      String localVarType =
          makeArgumentType(
              type); // Some conversion may be required for Id's or strings or enumerations

      // Declare local variable for current argument
      writer.write(
          localVarType
              + " "
              + target
              + "(("
              + localVarType
              + ")arguments["
              + i
              + "]->getSingletonValue());\n\n");
      constructorArguments = constructorArguments + comma + target;
      comma = ", ";
    }

    // Now do the declaration and allocation of the instance
    writer.write(
        klassName
            + "Id instance = (new "
            + klassName
            + "(planDb, objectType, objectName))->getId();\n");
    writer.write("instance->constructor(" + constructorArguments + ");\n");
    writer.write("instance->handleDefaults();\n");
    writer.write("return instance;\n");
    writer.unindent();
    writer.write("}\n");
    writer.unindent();
    writer.write("};\n");

    // Generate all appropriate registration informationLabelStr
    Vector factoryNames = makeFactoryNames(constructor);
    for (int i = 0; i < factoryNames.size(); i++) {
      String factoryName = (String) factoryNames.elementAt(i);
      SchemaWriter.addFactory(
          "REGISTER_OBJECT_FACTORY(id," + longname + ", " + factoryName + ");\n");
    }
  }