Ejemplo n.º 1
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);
    }
  }
Ejemplo n.º 2
0
  /**
   * Set the preconfigured event properties resolved by XPath expression.
   *
   * @param explicitXPathProperties are preconfigured event properties
   * @param additionalSchemaProperties the explicit properties
   */
  protected void initialize(
      Collection<ConfigurationEventTypeXMLDOM.XPathPropertyDesc> explicitXPathProperties,
      List<ExplicitPropertyDescriptor> additionalSchemaProperties) {
    // make sure we override those explicitly provided with those derived from a metadataz
    Map<String, ExplicitPropertyDescriptor> namedProperties =
        new LinkedHashMap<String, ExplicitPropertyDescriptor>();
    for (ExplicitPropertyDescriptor desc : additionalSchemaProperties) {
      namedProperties.put(desc.getDescriptor().getPropertyName(), desc);
    }

    String xpathExpression = null;
    try {

      for (ConfigurationEventTypeXMLDOM.XPathPropertyDesc property : explicitXPathProperties) {
        XPath xPath = xPathFactory.newXPath();
        if (namespaceContext != null) {
          xPath.setNamespaceContext(namespaceContext);
        }

        xpathExpression = property.getXpath();
        if (log.isInfoEnabled()) {
          log.info(
              "Compiling XPath expression for property '"
                  + property.getName()
                  + "' as '"
                  + xpathExpression
                  + "'");
        }
        XPathExpression expression = xPath.compile(xpathExpression);

        FragmentFactoryXPathPredefinedGetter fragmentFactory = null;
        boolean isFragment = false;
        if (property.getOptionaleventTypeName() != null) {
          fragmentFactory =
              new FragmentFactoryXPathPredefinedGetter(
                  this.getEventAdapterService(),
                  property.getOptionaleventTypeName(),
                  property.getName());
          isFragment = true;
        }
        boolean isArray = false;
        if (property.getType().equals(XPathConstants.NODESET)) {
          isArray = true;
        }

        EventPropertyGetter getter =
            new XPathPropertyGetter(
                property.getName(),
                xpathExpression,
                expression,
                property.getType(),
                property.getOptionalCastToType(),
                fragmentFactory);
        Class returnType =
            SchemaUtil.toReturnType(property.getType(), property.getOptionalCastToType());

        EventPropertyDescriptor desc =
            new EventPropertyDescriptor(
                property.getName(), returnType, null, false, false, isArray, false, isFragment);
        ExplicitPropertyDescriptor explicit =
            new ExplicitPropertyDescriptor(
                desc, getter, isArray, property.getOptionaleventTypeName());
        namedProperties.put(desc.getPropertyName(), explicit);
      }
    } catch (XPathExpressionException ex) {
      throw new EPException(
          "XPath expression could not be compiled for expression '" + xpathExpression + '\'', ex);
    }

    super.initialize(new ArrayList<ExplicitPropertyDescriptor>(namedProperties.values()));

    // evaluate start and end timestamp properties if any
    startTimestampPropertyName = configurationEventTypeXMLDOM.getStartTimestampPropertyName();
    endTimestampPropertyName = configurationEventTypeXMLDOM.getEndTimestampPropertyName();
    EventTypeUtility.validateTimestampProperties(
        this, startTimestampPropertyName, endTimestampPropertyName);
  }