Пример #1
0
  @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 = "";
  }
Пример #2
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;
  }
Пример #3
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));
 }
Пример #4
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());
   }
 }
Пример #5
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");
  }
  // 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);
    }
  }
Пример #7
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;
  }
Пример #8
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;
  }
 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));
   }
 }
Пример #10
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;
 }
Пример #11
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;
 }
 /**
  * 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);
 }
Пример #13
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);
    }
  }
Пример #14
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);
  }
Пример #15
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;
  }