Esempio n. 1
0
  private AlbumBean addOrUpdateAlbum(
      Map<Integer, AlbumBean> map, SongBean song, boolean albumOnly) {
    // Add an album bean
    if (song != null && song.getAlbum() != null) {
      int hashCode = (song.getAlbum() + (albumOnly ? "" : '\uFFFF' + song.getArtist())).hashCode();

      // Check if the album beam already exists
      AlbumBean album = map.get(hashCode);
      if (album == null) {
        album = new AlbumBean();
        album.setAlbum(song.getAlbum());
        map.put(hashCode, album);
      }

      // Update the album properties
      try {
        // Add the track id to the album bean
        album.addSong(song);
        album.incTracks();
        album.setArtist(song.getArtist());
        album.setGenre(song.getGenre());
        album.setDisc_Count(song.getDisc_Count());
      } catch (LibraryException le) {
        // There was an error adding the song to this album, remove it
        map.remove(hashCode);

        // Add to warning message
        warningList.add(song.getName() + " " + le);
      }

      return album;
    }

    return null;
  }
Esempio n. 2
0
 private void addDefaultValues(Map attributes, Map mappings) {
   if (mappings == null) return;
   Iterator i = mappings.entrySet().iterator();
   while (i.hasNext()) {
     Map.Entry e = (Map.Entry) i.next();
     TagMap.AttributeMapping m = (TagMap.AttributeMapping) e.getValue();
     if (null != m && null != m.getDefaultValue() && null == attributes.get(m.getPropertyName()))
       attributes.put(m.getPropertyName(), m.getDefaultValue());
   }
 }
Esempio n. 3
0
  /**
   * Get a SAXParserFactory to build combinations of validating and XInclude-aware SAXParser.
   *
   * @param parserConfiguration parser configuration
   * @return the SAXParserFactory
   */
  public static synchronized SAXParserFactory getSAXParserFactory(
      XMLUtils.ParserConfiguration parserConfiguration) {

    final String key = parserConfiguration.getKey();

    final SAXParserFactory existingFactory = parserFactories.get(key);
    if (existingFactory != null) return existingFactory;

    final SAXParserFactory newFactory = createSAXParserFactory(parserConfiguration);
    parserFactories.put(key, newFactory);
    return newFactory;
  }
 protected void collectExtensionAttributes(Attributes attributes) {
   for (int i = 0; i < attributes.getLength(); i++) {
     String key = attributes.getURI(i);
     if (key.length() == 0
         || key.startsWith("http://www.osgi.org/xmlns/metatype/v")) // $NON-NLS-1$
     continue;
     Map<String, String> value = extensionAttributes.get(key);
     if (value == null) {
       value = new HashMap<String, String>();
       extensionAttributes.put(key, value);
     }
     value.put(
         getName(attributes.getLocalName(i), attributes.getQName(i)), attributes.getValue(i));
   }
 }
  @Override
  public void endElement(String uri, String localName, String qName) throws SAXException {
    curElem = false;
    curValue = curValue.trim();

    // check for a known tag
    if (qName.equals("name")) {
      curMission.setName(curValue);
    } else if (qName.equals("players")) {
      curMission.setPlayers(curValue);
    } else if (qName.equals("time-limit")) {
      curMission.setTime(curValue, true);
    } else if (qName.equals("time")) {
      curMission.setTime(curValue, false);
    } else if (qName.equals("info")) {
      curMission.setInfo(curValue);
    } else if (qName.equals("mission")) {
      // Log.v(tag, "Adding mission " + curName + " (" + curMission.getName() + ")");
      data.put(curName, curMission);
      curName = "";
      curMission = null;
    } else if (qName.equals("details")) {
      mLoaded = true;
    }

    curValue = "";
  }
Esempio n. 6
0
 private void checkForRequiredAttributes(String tagName, Map attributes, Map mappings)
     throws ParserException {
   if (mappings == null) return;
   Iterator i = mappings.entrySet().iterator();
   while (i.hasNext()) {
     Map.Entry e = (Map.Entry) i.next();
     TagMap.AttributeMapping m = (TagMap.AttributeMapping) e.getValue();
     if (null != m && m.getRequired())
       if (null == mappings || null == attributes.get(m.getPropertyName()))
         throw new ParserException(
             "An attribute that maps to property name: "
                 + m.getPropertyName()
                 + " is required and was not specified for tag:"
                 + tagName
                 + "!");
   }
 }
Esempio n. 7
0
 private Map attributeMap(String tagName, Attributes atts) throws ParserException {
   if (null == tagName || null == atts) return null;
   Map mapping = null;
   try {
     mapping = (Map) attributeMaps.get(tagName);
   } catch (Exception e) {
     throw new ParserException(
         "Typecast error, unknown element found in attribute list mappings! " + e.getMessage());
   }
   if (null == mapping) return null;
   Map resultMapping = new HashMap();
   for (int i = 0; i < atts.getLength(); i++) {
     String xmlName = atts.getQName(i);
     String value = atts.getValue(i);
     TagMap.AttributeMapping aMap = null;
     try {
       aMap = (TagMap.AttributeMapping) mapping.get(xmlName);
     } catch (Exception e) {
       throw new ParserException(
           "Typecast error, unknown element found in property mapping! " + e.getMessage());
     }
     if (null == aMap)
       throw new ParserException(
           "No attribute mapping specified for attribute: " + xmlName + " in tag: " + tagName);
     String propertyName = aMap.getPropertyName();
     try {
       resultMapping.put(propertyName, aMap.convertValue(value));
     } catch (Exception e) {
       throw new ParserException(
           "Can not convert given value: \""
               + value
               + "\" to specified type: "
               + aMap.getType()
               + " for attribute: "
               + xmlName
               + " in tag: "
               + tagName
               + "! "
               + e.getMessage());
     }
   }
   checkForRequiredAttributes(tagName, resultMapping, mapping);
   addDefaultValues(resultMapping, mapping);
   return resultMapping;
 }
Esempio n. 8
0
 /**
  * Associated one DocumentBuilder per thread. This is so we avoid synchronizing (parse() for
  * example may take a lot of time on a DocumentBuilder) or creating DocumentBuilder instances all
  * the time. Since typically in an app server we work with a thread pool, not too many instances
  * of DocumentBuilder should be created.
  */
 private static DocumentBuilder getThreadDocumentBuilder() {
   Thread thread = Thread.currentThread();
   DocumentBuilder documentBuilder =
       (documentBuilders == null) ? null : documentBuilders.get(thread);
   // Try a first test outside the synchronized block
   if (documentBuilder == null) {
     synchronized (documentBuilderFactory) {
       // Redo the test within the synchronized block
       documentBuilder = (documentBuilders == null) ? null : documentBuilders.get(thread);
       if (documentBuilder == null) {
         if (documentBuilders == null) documentBuilders = new HashMap<Thread, DocumentBuilder>();
         documentBuilder = newDocumentBuilder();
         documentBuilders.put(thread, documentBuilder);
       }
     }
   }
   return documentBuilder;
 }
Esempio n. 9
0
 /**
  * Class initializer: Populate a table to translate SAX attribute type names into JDOM attribute
  * type value (integer).
  *
  * <p><b>Note that all the mappings defined below are compliant with the SAX 2.0 specification
  * exception for "ENUMERATION" with is specific to Crimson 1.1.X and Xerces 2.0.0-betaX which
  * report attributes of enumerated types with a type "ENUMERATION" instead of the expected
  * "NMTOKEN".
  *
  * <p>Note also that Xerces 1.4.X is not SAX 2.0 compliant either but handling its case requires
  * {@link #getAttributeType specific code}.
  */
 static {
   attrNameToTypeMap.put("CDATA", new Integer(Attribute.CDATA_TYPE));
   attrNameToTypeMap.put("ID", new Integer(Attribute.ID_TYPE));
   attrNameToTypeMap.put("IDREF", new Integer(Attribute.IDREF_TYPE));
   attrNameToTypeMap.put("IDREFS", new Integer(Attribute.IDREFS_TYPE));
   attrNameToTypeMap.put("ENTITY", new Integer(Attribute.ENTITY_TYPE));
   attrNameToTypeMap.put("ENTITIES", new Integer(Attribute.ENTITIES_TYPE));
   attrNameToTypeMap.put("NMTOKEN", new Integer(Attribute.NMTOKEN_TYPE));
   attrNameToTypeMap.put("NMTOKENS", new Integer(Attribute.NMTOKENS_TYPE));
   attrNameToTypeMap.put("NOTATION", new Integer(Attribute.NOTATION_TYPE));
   attrNameToTypeMap.put("ENUMERATION", new Integer(Attribute.ENUMERATED_TYPE));
 }
Esempio n. 10
0
  /**
   * This is called when the parser encounters an external entity declaration.
   *
   * @param name entity name
   * @param publicID public id
   * @param systemID system id
   * @throws SAXException when things go wrong
   */
  public void externalEntityDecl(String name, String publicID, String systemID)
      throws SAXException {
    // Store the public and system ids for the name
    externalEntities.put(name, new String[] {publicID, systemID});

    if (!inInternalSubset) return;

    internalSubset.append("  <!ENTITY ").append(name);
    appendExternalId(publicID, systemID);
    internalSubset.append(">\n");
  }
  private static void addMetadataSet(SolrInputDocument doc, Collection<DcsMetadata> set)
      throws IOException {
    if (set == null || set.size() == 0) {
      return;
    }

    for (DcsMetadata md : set) {
      setadd(doc, MetadataField.SCHEMA, md.getSchemaUri());
      setadd(doc, MetadataField.TEXT, md.getMetadata());

      if (md.getMetadata() == null) {
        continue;
      }

      try {
        Reader in = new StringReader(md.getMetadata());
        addXml(doc, "ext_", MetadataField.SEARCH_TEXT.solrName(), new InputSource(in));
        in.close();

        // Index FGDC
        String metadata = md.getMetadata();

        if (metadata.contains("<metadata>")) // fgdc - change the check
        {
          FgdcMapping mapping = new FgdcMapping();
          Map<Enum, String> fgdcElements = mapping.map(metadata);

          Iterator it = fgdcElements.entrySet().iterator();
          while (it.hasNext()) {
            Map.Entry pair = (Map.Entry) it.next();
            add(doc, (SeadSolrField.FgdcField) pair.getKey(), pair.getValue());
            it.remove(); // avoids a ConcurrentModificationException
          }
        }

        in.close();
      } catch (SAXException e) {
        throw new IOException(e);
      }
    }
  }
  // refactored this out from the three addAction methods above
  private void addAction(Object actionsCollectionOrMap, ActionDescriptor descriptor) {
    if (getAction(descriptor.getId()) != null) {
      throw new IllegalArgumentException(
          "action with id " + descriptor.getId() + " already exists for this step.");
    }

    if (actionsCollectionOrMap instanceof Map) {
      ((Map) actionsCollectionOrMap).put(new Integer(descriptor.getId()), descriptor);
    } else {
      ((Collection) actionsCollectionOrMap).add(descriptor);
    }
  }
Esempio n. 13
0
  // returns list of statements
  protected static void replaceMultSPO(
      Statement st, NodeFactory f, Map o2n, Collection result, RDFNode toReplace, int position)
      throws ModelException {

    Collection replacements;

    if (toReplace instanceof Statement) {

      List l = new ArrayList();
      replaceMult((Statement) toReplace, f, o2n, l);

      if (l.size() == 1 && toReplace == l.get(0)) {
        result.add(st);
        return; // keep the same
      } else replacements = l;

    } else {

      Object ro = o2n.get(toReplace);

      if (ro instanceof Collection) replacements = (Collection) ro;
      else if (ro != null) {

        replacements = new ArrayList();
        replacements.add(ro);

      } else { // no replacement needed

        result.add(st); // keep the same statement
        return;
      }
    }

    for (Iterator it = replacements.iterator(); it.hasNext(); ) {

      Statement rs = null;
      Object rr = it.next();

      switch (position) {
        case 0:
          rs = f.createStatement((Resource) rr, st.predicate(), st.object());
          break;
        case 1:
          rs = f.createStatement(st.subject(), (Resource) rr, st.object());
          break;
        case 2:
          rs = f.createStatement(st.subject(), st.predicate(), (RDFNode) rr);
          break;
      }
      result.add(rs);
    }
  }
Esempio n. 14
0
  public static Statement replaceNamespace(
      Statement st, String o, String n, NodeFactory f, Map o2n, Set resourcesToIgnore)
      throws ModelException {

    boolean replaced = false;
    Resource subj = st.subject();
    Resource pred = st.predicate();
    RDFNode obj = st.object();

    if (obj instanceof Resource
        && !(obj instanceof Statement)
        && o.equals(((Resource) obj).getNamespace())
        && (resourcesToIgnore == null || !resourcesToIgnore.contains(obj))) {

      replaced = true;
      Resource r = f.createResource(n, ((Resource) obj).getLocalName());
      if (o2n != null) o2n.put(obj, r);
      obj = r;
    }

    if (o.equals(subj.getNamespace())
        && (resourcesToIgnore == null || !resourcesToIgnore.contains(subj))) {

      replaced = true;
      Resource r = f.createResource(n, subj.getLocalName());
      if (o2n != null) o2n.put(subj, r);
      subj = r;
    }

    if (o.equals(pred.getNamespace())
        && (resourcesToIgnore == null || !resourcesToIgnore.contains(pred))) {

      replaced = true;
      Resource r = f.createResource(n, pred.getLocalName());
      if (o2n != null) o2n.put(pred, r);
      pred = r;
    }
    return replaced ? f.createStatement(subj, pred, obj) : st;
  }
Esempio n. 15
0
  public static Statement replaceResources(Statement st, NodeFactory f, Map o2n)
      throws ModelException {

    boolean replaced = false;
    Resource subj = st.subject();
    Resource pred = st.predicate();
    RDFNode obj = st.object();

    Object n = null;

    if (obj instanceof Statement) {

      n = obj;
      obj = replaceResources((Statement) obj, f, o2n);
      replaced = n != obj;

    } else if ((n = o2n.get(obj)) != null) {
      replaced = true;
      obj = (RDFNode) n;
    }

    if (subj instanceof Statement) {

      n = subj;
      subj = replaceResources((Statement) subj, f, o2n);
      replaced = n != subj;
    }
    if ((n = o2n.get(subj)) != null) {
      replaced = true;
      subj = (Resource) n;
    }

    if ((n = o2n.get(pred)) != null) {
      replaced = true;
      pred = (Resource) n;
    }
    return replaced ? f.createStatement(subj, pred, obj) : st;
  }
Esempio n. 16
0
 /**
  * Returns the the JDOM Attribute type value from the SAX 2.0 attribute type string provided by
  * the parser.
  *
  * @param typeName <code>String</code> the SAX 2.0 attribute type string.
  * @return <code>int</code> the JDOM attribute type.
  * @see Attribute#setAttributeType
  * @see Attributes#getType
  */
 private static int getAttributeType(String typeName) {
   Integer type = (Integer) (attrNameToTypeMap.get(typeName));
   if (type == null) {
     if (typeName != null && typeName.length() > 0 && typeName.charAt(0) == '(') {
       // Xerces 1.4.X reports attributes of enumerated type with
       // a type string equals to the enumeration definition, i.e.
       // starting with a parenthesis.
       return Attribute.ENUMERATED_TYPE;
     } else {
       return Attribute.UNDECLARED_TYPE;
     }
   } else {
     return type.intValue();
   }
 }
Esempio n. 17
0
  public void startEntity(String name) throws SAXException {
    entityDepth++;

    if (expand || entityDepth > 1) {
      // Short cut out if we're expanding or if we're nested
      return;
    }

    // A "[dtd]" entity indicates the beginning of the external subset
    if (name.equals("[dtd]")) {
      inInternalSubset = false;
      return;
    }

    // Ignore DTD references, and translate the standard 5
    if ((!inDTD)
        && (!name.equals("amp"))
        && (!name.equals("lt"))
        && (!name.equals("gt"))
        && (!name.equals("apos"))
        && (!name.equals("quot"))) {

      if (!expand) {
        String pub = null;
        String sys = null;
        String[] ids = (String[]) externalEntities.get(name);
        if (ids != null) {
          pub = ids[0]; // may be null, that's OK
          sys = ids[1]; // may be null, that's OK
        }
        /**
         * if no current element, this entity belongs to an attribute in these cases, it is an error
         * on the part of the parser to call startEntity but this will help in some cases. See
         * org/xml/sax/ext/LexicalHandler.html#startEntity(java.lang.String) for more information
         */
        if (!atRoot) {
          flushCharacters();
          EntityRef entity = factory.entityRef(name, pub, sys);

          // no way to tell if the entity was from an attribute or element so just assume element
          factory.addContent(getCurrentElement(), entity);
        }
        suppress = true;
      }
    }
  }
Esempio n. 18
0
  protected Document parse(InputStream inputStream) throws LibraryException {
    Map<Integer, SongBean> songMap = new HashMap<Integer, SongBean>();
    Map<Integer, AlbumBean> albumMap = new HashMap<Integer, AlbumBean>();
    Map<Integer, AlbumBean> secondaryAlbumMap = new HashMap<Integer, AlbumBean>();
    warningList.clear();

    try {
      // Create a builder factory
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      factory.setValidating(false);
      factory.setNamespaceAware(true);
      factory.setIgnoringElementContentWhitespace(true);
      factory.setIgnoringComments(true);

      // Create the builder and parse the file
      DocumentBuilder builder = factory.newDocumentBuilder();

      // Set an error listener and parse the document
      builder.setErrorHandler(new iTradeTunesLibraryErrorHandler());
      builder.setEntityResolver(new iTradeTunesLibraryResolver());
      Document document = builder.parse(inputStream);

      synchronized (libraryList) {
        // Query the library document and build the library list
        XPath xPath = XPathFactory.newInstance().newXPath();
        XPathExpression xPathExpression = xPath.compile(XPATH_LIBRARY_LIST);
        NodeList nodelist = (NodeList) xPathExpression.evaluate(document, XPathConstants.NODESET);

        // Process the elements in the nodelist
        SongBean song = null;

        for (int i = 0; i < nodelist.getLength(); i++) {
          boolean isTrackID = false;

          // Get element and child nodes
          Element elem = (Element) nodelist.item(i);
          NodeList list = elem.getChildNodes();

          // Get node value
          Node childKey = list.item(0);
          String key = childKey.getNodeValue();

          // Check if we have to create a new bean
          if (SongBean.NAME_TRACK_ID.equals(key)) {
            isTrackID = true;
            SongBean previousSong = song;
            song = new SongBean();
            if (previousSong != null
                && !("AAC audio file".equals(previousSong.getKind())
                    || "MPEG audio file".equals(previousSong.getKind()))) {
              songMap.remove(previousSong.getTrack_ID());
            } else {
              // Add an album bean
              addOrUpdateAlbum(albumMap, previousSong, false);
            }
          }

          // The first parameter is the key
          String prop = childKey.getNodeValue().replace(' ', '_');

          // The second parameter is the value
          i++;

          // Get element and child nodes
          elem = (Element) nodelist.item(i);

          // Check for boolean properties
          Object value = null;
          // Get node value
          list = elem.getChildNodes();
          childKey = list.item(0);
          value = (childKey == null) ? elem.getNodeName() : childKey.getNodeValue();

          if (isTrackID) {
            isTrackID = false;
          }

          // Set the property of the song bean
          Statement stmt = new Statement(song, "set" + prop, new Object[] {value});
          try {
            stmt.execute();

          } catch (Exception e) {
            // Ignore that field, we do not have it in our bean
          }

          // If the property is the track ID, add the song to the hash
          // map
          if (SongBean.NAME_TRACK_ID.equals(key)) {
            int trackID = Integer.valueOf((String) value);
            songMap.put(trackID, song);
          }
        }

        // Update album for last song
        addOrUpdateAlbum(albumMap, song, false);

        // Check the album map for inconsistencies
        Iterator<AlbumBean> albums = albumMap.values().iterator();
        while (albums.hasNext()) {
          AlbumBean album = albums.next();
          if (album.checkConsistency()) {
            libraryList.add(album);
            album.setHashCode();
          } else {
            // Add an inconsistent album only using the album title
            SongBean[] songs = album.getSongs();
            for (int i = 0; i < songs.length; i++) {
              addOrUpdateAlbum(secondaryAlbumMap, songs[i], true);
            }
          }
        }

        // Check secondary album map for consistency
        albums = secondaryAlbumMap.values().iterator();
        while (albums.hasNext()) {
          AlbumBean album = albums.next();
          if (album.checkConsistency()) {
            libraryList.add(album);
            album.setHashCode();
          } else {
            // This album cannot be matched
            // TODO: Add to warning message
          }
        }

        setChanged();
      }

      return document;
    } catch (IOException ioe) {
      // Log an expected connect exception
      throw new LibraryException(ioe);
    } catch (SAXException se) {
      // Catch all other exceptions
      throw new LibraryException(se);
    } catch (ParserConfigurationException pce) {
      // Catch all other exceptions
      Utils.logSevere(pce);
      throw new LibraryException(pce);
    } catch (XPathExpressionException xpe) {
      // Catch all other exceptions
      Utils.logSevere(xpe);
      throw new LibraryException(xpe);
    } catch (NumberFormatException nfe) {
      // Catch all other exceptions
      throw new LibraryException(nfe);
    }
  }
Esempio n. 19
0
  /**
   * @return a new model in which all occurrences of the old resources are replaced by the new ones.
   *     Returns number replacements done.
   */
  public static int replaceResource(Model m, Resource oldR, Resource newR) throws ModelException {

    Map map = new HashMap();
    map.put(oldR, newR);
    return replaceResources(m, map);
  }
 public MissionInfo getMission(String name) {
   return data.get(name);
 }
  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>");
  }
  public void validate() throws InvalidWorkflowDescriptorException {
    ValidationHelper.validate(this.getRegisters());
    ValidationHelper.validate(this.getTriggerFunctions().values());
    ValidationHelper.validate(this.getGlobalActions());
    ValidationHelper.validate(this.getInitialActions());
    ValidationHelper.validate(this.getCommonActions().values());
    ValidationHelper.validate(this.getSteps());
    ValidationHelper.validate(this.getSplits());
    ValidationHelper.validate(this.getJoins());

    Set actions = new HashSet();
    Iterator i = globalActions.iterator();

    while (i.hasNext()) {
      ActionDescriptor action = (ActionDescriptor) i.next();
      actions.add(new Integer(action.getId()));
    }

    i = getSteps().iterator();

    while (i.hasNext()) {
      StepDescriptor step = (StepDescriptor) i.next();
      Iterator j = step.getActions().iterator();

      while (j.hasNext()) {
        ActionDescriptor action = (ActionDescriptor) j.next();

        // check to see if it's a common action (dups are ok, since that's the point of common
        // actions!)
        if (!action.isCommon()) {
          if (!actions.add(new Integer(action.getId()))) {
            throw new InvalidWorkflowDescriptorException(
                "Duplicate occurance of action ID "
                    + action.getId()
                    + " found in step "
                    + step.getId());
          }
        }
      }
    }

    // now we have all our unique actions, let's check that no common action id's exist in them
    i = commonActions.keySet().iterator();

    while (i.hasNext()) {
      Integer action = (Integer) i.next();

      if (actions.contains(action)) {
        throw new InvalidWorkflowDescriptorException(
            "common-action ID " + action + " is duplicated in a step action");
      }
    }

    i = initialActions.iterator();

    while (i.hasNext()) {
      ActionDescriptor action = (ActionDescriptor) i.next();

      if (actions.contains(new Integer(action.getId()))) {
        throw new InvalidWorkflowDescriptorException(
            "initial-action ID " + action + " is duplicated in a step action");
      }
    }

    validateDTD();
  }
 /**
  * Update a trigger function
  *
  * @param id The id for the trigger function
  * @param descriptor The descriptor for the trigger function
  * @return The old trigger function with the specified ID, if any existed
  */
 public FunctionDescriptor setTriggerFunction(int id, FunctionDescriptor descriptor) {
   return (FunctionDescriptor) timerFunctions.put(new Integer(id), descriptor);
 }
Esempio n. 24
0
  /** Receive notification of the end of an element. */
  @Override
  public void endElement(String uri, String l, String q) {
    /*
     * 1. If current element is a String, update its value from the string buffer.
     * 2. Add the element to parent.
     */
    ElementInfo element = _stack.remove(_stack.size() - 1);
    _logger.fine("endElement " + element);
    if (element.type == null) {
      _logger.warning("Element " + element.name + " not created ");
      return;
    } else if (_chars.length() > 0) {
      try {
        injectProperty(element.data, String.class, _chars.toString(), null, null);
      } catch (Exception x) {
        if (!_lenient) {
          throw new BeanAssemblyException(
              "Failed to set characters to object " + element.type.getName(), x);
        } else {
          _logger.warning("Failed to set characters to parent " + element.data);
        }
      }
    }
    _chars.setLength(0);
    _logger.fine(
        "<<ElementInfo: "
            + element.type.getName()
            + " in "
            + element
            + "\n    @as is "
            + element.inst.get("@as")
            + "\n    @id is "
            + element.inst.get("@id"));

    if (List.class.isAssignableFrom(element.data.getClass()) && element.name.endsWith("...")) {
      List<?> list = (List<?>) element.data;
      Object array = Array.newInstance(element.type, list.size());
      for (int i = 0; i < list.size(); ++i) {
        Array.set(array, i, list.get(i));
      }
      element.data = array;
    }

    String id = element.inst.get("@id");
    if (id != null) {
      // locally stored object - not added to the parent
      _local.put(id, element);
    } else if (!_stack.isEmpty()) {
      // inject into the parent as a property
      ElementInfo parent = _stack.get(_stack.size() - 1);
      _logger.fine("Parent is " + parent.data.getClass().getName());
      try {
        String as = element.inst.get("@as");
        if (as != null) {
          injectProperty(
              parent.data,
              element.type,
              element.data,
              Strings.toCamelCase(as, '-', false),
              element.args.complete());
        } else {
          injectProperty(parent.data, element.type, element.data, null, element.args.complete());
        }
      } catch (Exception x) {
        if (!_lenient) {
          throw new BeanAssemblyException(
              "Failed to set value " + element.data + " to parent " + parent.data, x);
        } else {
          _logger.log(
              Level.WARNING,
              "Failed to set value " + element.data + " to parent " + parent.data,
              x);
        }
      }
    }
    _top = element.data;
  }