Example #1
1
  /**
   * If the outbound level is BINARY, convert the string field to binary, then pad to the left with
   * the appropriate number of zero bits to reach a number of bits specified by the bitLength
   * attribute of the TDT definition file.
   */
  private void binaryPadding(Map<String, String> extraparams, Field tdtfield) {
    String fieldname = tdtfield.getName();
    int reqbitlength = tdtfield.getBitLength();
    String value;

    String binaryValue = fieldToBinary(tdtfield, extraparams);
    if (binaryValue.length() < reqbitlength) {
      int extraBitLength = reqbitlength - binaryValue.length();

      StringBuilder zeroPaddedBinaryValue = new StringBuilder("");
      for (int i = 0; i < extraBitLength; i++) {
        zeroPaddedBinaryValue.append("0");
      }
      zeroPaddedBinaryValue.append(binaryValue);
      value = zeroPaddedBinaryValue.toString();
    } else {
      if (binaryValue.length() > reqbitlength)
        throw new TDTException(
            "Binary value ["
                + binaryValue
                + "] for field "
                + fieldname
                + " exceeds maximum allowed "
                + reqbitlength
                + " bits.  Decimal value was "
                + extraparams.get(fieldname));

      value = binaryValue;
    }
    extraparams.put(fieldname, value);
  }
 public static final Map parseFrame(Node node) {
   NodeList bones = node.getChildNodes();
   Map bone_infos = new HashMap();
   for (int i = 0; i < bones.getLength(); i++) {
     Node bone = bones.item(i);
     if (bone.getNodeName().equals("transform")) {
       String name = bone.getAttributes().getNamedItem("name").getNodeValue();
       float[] matrix = new float[16];
       matrix[0 * 4 + 0] = getAttrFloat(bone, "m00");
       matrix[0 * 4 + 1] = getAttrFloat(bone, "m01");
       matrix[0 * 4 + 2] = getAttrFloat(bone, "m02");
       matrix[0 * 4 + 3] = getAttrFloat(bone, "m03");
       matrix[1 * 4 + 0] = getAttrFloat(bone, "m10");
       matrix[1 * 4 + 1] = getAttrFloat(bone, "m11");
       matrix[1 * 4 + 2] = getAttrFloat(bone, "m12");
       matrix[1 * 4 + 3] = getAttrFloat(bone, "m13");
       matrix[2 * 4 + 0] = getAttrFloat(bone, "m20");
       matrix[2 * 4 + 1] = getAttrFloat(bone, "m21");
       matrix[2 * 4 + 2] = getAttrFloat(bone, "m22");
       matrix[2 * 4 + 3] = getAttrFloat(bone, "m23");
       matrix[3 * 4 + 0] = getAttrFloat(bone, "m30");
       matrix[3 * 4 + 1] = getAttrFloat(bone, "m31");
       matrix[3 * 4 + 2] = getAttrFloat(bone, "m32");
       matrix[3 * 4 + 3] = getAttrFloat(bone, "m33");
       bone_infos.put(name, matrix);
     }
   }
   return bone_infos;
 }
Example #3
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;
  }
Example #4
0
 private void broadcastRepositoryChange(RepositoryRoot root) {
   if (notificationLevel == 0) {
     broadcastRepositoriesChanged(new ICVSRepositoryLocation[] {root.getRoot()});
   } else {
     changedRepositories.put(root.getRoot().getLocation(false), root.getRoot());
   }
 }
 private void addTagToMethod(
     Map<String, MethodInfo> methods, String tagText, MethodTagType tagType) {
   MethodInfo mi = methods.get(methodName);
   if (mi == null) {
     mi = new MethodInfo();
     methods.put(methodName, mi);
   }
   if (tagType == MethodTagType.OMIT_FROM_UI) {
     mi.omitFromUI = true;
     return;
   }
   String[] tagParts =
       Iterables.toArray(
           Splitter.on(WHITESPACE_PATTERN)
               .trimResults()
               .omitEmptyStrings()
               .limit(2)
               .split(tagText),
           String.class);
   if (tagParts.length == 2) {
     if (tagType == MethodTagType.DESCRIPTION) {
       mi.descriptions.put(tagParts[0], tagParts[1]);
     } else {
       mi.useSchemas.put(tagParts[0], tagParts[1]);
     }
   }
 }
Example #6
0
 public static void testConfigurableForNonPrimitives() {
   Map<String, String> p = new HashMap<String, String>();
   C config = Configurable.createConfigurable(C.class, p);
   assertNull(config.port());
   p.put("port", "10");
   config = Configurable.createConfigurable(C.class, p);
   assertEquals(Integer.valueOf(10), config.port()); // property port is
   // not set
 }
Example #7
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());
   }
 }
Example #8
0
 private static final Skeleton parseSkeleton(Node skel_node) {
   Map name_to_bone_map = new HashMap();
   Map initial_pose =
       AnimationLoader.parseFrame(ConvertToBinary.getNodeByName("init_pose", skel_node));
   NodeList bone_list = ConvertToBinary.getNodeByName("bones", skel_node).getChildNodes();
   Map bone_parent_map = new HashMap();
   for (int i = 0; i < bone_list.getLength(); i++) {
     Node bone_node = bone_list.item(i);
     if (bone_node.getNodeName().equals("bone")) {
       String bone_name = bone_node.getAttributes().getNamedItem("name").getNodeValue();
       String bone_parent_name = bone_node.getAttributes().getNamedItem("parent").getNodeValue();
       // System.out.println("bone name = " + bone_name + " parent name = " + bone_parent_name);
       bone_parent_map.put(bone_name, bone_parent_name);
     }
   }
   Map bone_children_map = new HashMap();
   Iterator it = bone_parent_map.keySet().iterator();
   String root = null;
   while (it.hasNext()) {
     String name = (String) it.next();
     String parent = (String) bone_parent_map.get(name);
     if (bone_parent_map.get(parent) == null) {
       if (root != null) {
         System.out.println(
             "WARNING: Multiple roots in skeleton, root = "
                 + root
                 + ", additional root = "
                 + name);
         parent = root;
         bone_parent_map.put(name, parent);
       } else root = name;
     }
     List parent_children = (List) bone_children_map.get(parent);
     if (parent_children == null) {
       parent_children = new ArrayList();
       bone_children_map.put(parent, parent_children);
     }
     parent_children.add(name);
   }
   Bone bone_root = buildBone((byte) 0, bone_children_map, root, name_to_bone_map);
   return new Skeleton(bone_root, initial_pose, name_to_bone_map);
 }
Example #9
0
 /*
  * XXX I hope this methos is not needed in this form
  */
 public Map getKnownProjectsAndVersions(ICVSRepositoryLocation location) {
   Map knownTags = new HashMap();
   RepositoryRoot root = getRepositoryRootFor(location);
   String[] paths = root.getKnownRemotePaths();
   for (int i = 0; i < paths.length; i++) {
     String path = paths[i];
     Set result = new HashSet();
     result.addAll(Arrays.asList(root.getAllKnownTags(path)));
     knownTags.put(path, result);
   }
   return knownTags;
 }
Example #10
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;
  }
Example #11
0
 private static final Bone buildBone(
     byte index, Map bone_children_map, String bone_name, Map name_to_bone_map) {
   List children_list = (List) bone_children_map.get(bone_name);
   Bone[] children_array;
   if (children_list != null) {
     children_array = new Bone[children_list.size()];
     for (int i = 0; i < children_array.length; i++) {
       String child_name = (String) children_list.get(i);
       Bone child_bone = buildBone(index, bone_children_map, child_name, name_to_bone_map);
       children_array[i] = child_bone;
       index = (byte) (child_bone.getIndex() + 1);
     }
   } else children_array = new Bone[0];
   Bone bone = new Bone(bone_name, index, children_array);
   name_to_bone_map.put(bone_name, bone);
   return bone;
 }
Example #12
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;
 }
Example #13
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;
 }
Example #14
0
  /** pad a value according the field definition. */
  private void padField(Map<String, String> extraparams, Field field) {
    String name = field.getName();
    String value = extraparams.get(name);
    PadDirectionList padDir = field.getPadDir();
    int requiredLength = field.getLength();

    // assert value != null;
    if (value == null) return;

    String padCharString = field.getPadChar();
    // if no pad char specified, don't attempt padding
    if (padCharString == null) return;
    assert padCharString.length() > 0;
    char padChar = padCharString.charAt(0);

    StringBuilder buf = new StringBuilder(requiredLength);
    if (padDir == PadDirectionList.LEFT) {
      for (int i = 0; i < requiredLength - value.length(); i++) buf.append(padChar);
      buf.append(value);
    } else if (padDir == PadDirectionList.RIGHT) {
      buf.append(value);
      for (int i = 0; i < requiredLength - value.length(); i++) buf.append(padChar);
    }
    assert buf.length() == requiredLength;
    if (requiredLength != value.length()) {
      // System.out.println("    updated " + name + " to '" + buf + "'");
      extraparams.put(name, buf.toString());
    }
    /*
    else {
        StringBuilder mybuf = new StringBuilder();
        for (int i = 0; i < value.length(); i++) {
    	if (i > 0)
    	    mybuf.append(',');
    	mybuf.append('\'');
    	mybuf.append(value.charAt(i));
    	mybuf.append('\'');
        }


        System.out.println("    field " + name + " not padded as " + mybuf.toString() + " is already " + requiredLength + " characters long");
    }
    */
  }
Example #15
0
 protected Object exec(Object[] args, Context context) {
   int nargs = args.length;
   Object schema = null;
   Map properties = null;
   Object errorHandler;
   Object input;
   switch (nargs) {
     case 4:
       schema = args[3];
     case 3:
       properties = (Map) args[2];
     case 2:
       errorHandler = args[1];
       break;
     case 1:
       errorHandler = Util.getDefaultErrorHandler(context);
       break;
     default:
       undefined(args, context);
       return null;
   }
   input = args[0];
   if (properties == null) {
     properties = new LinkedHashMap();
   }
   if (schema != null) {
     properties.put(Util.KEY_SCHEMA, schema);
   }
   DocumentBuilder builder = Util.getDocumentBuilder(properties, context);
   if (errorHandler != null) {
     builder.setErrorHandler((ErrorHandler) Util.contentHandler(errorHandler, context));
   }
   try {
     return builder.parse(Util.inputSource(input, context));
   } catch (IOException e1) {
     throw new PnutsException(e1, context);
   } catch (SAXException e2) {
     throw new PnutsException(e2, context);
   }
 }
Example #16
0
 private static final Map[] parseAnimation(Node node) {
   NodeList frames = node.getChildNodes();
   Map anim_infos_map = new HashMap();
   for (int i = 0; i < frames.getLength(); i++) {
     Node frame = frames.item(i);
     if (frame.getNodeName().equals("frame")) {
       int frame_index = getAttrInt(frame, "index");
       assert frame_index >= 0;
       anim_infos_map.put(new Integer(frame_index), parseFrame(frame));
     }
   }
   Map[] anim_infos = new Map[anim_infos_map.size()];
   Iterator it = anim_infos_map.keySet().iterator();
   while (it.hasNext()) {
     Integer frame_index_obj = (Integer) it.next();
     Map frame = (Map) anim_infos_map.get(frame_index_obj);
     int index = frame_index_obj.intValue();
     assert anim_infos[index] == null;
     anim_infos[index] = frame;
   }
   return anim_infos;
 }
 static {
   for (MethodTagType type : MethodTagType.values()) {
     TAG_TEXT_MAPPING.put(type.tag, type);
   }
 }
Example #18
0
 /**
  * Add the given repository root to the receiver. The provided instance of RepositoryRoot is used
  * to provide extra information about the repository location
  *
  * @param currentRepositoryRoot
  */
 public void add(RepositoryRoot root) {
   repositoryRoots.put(root.getRoot().getLocation(false), root);
   broadcastRepositoryChange(root);
 }
Example #19
0
  /** convert from a particular scheme / level */
  private String convertLevel(
      Scheme tdtscheme,
      Level tdtlevel,
      String input,
      Map<String, String> inputParameters,
      LevelTypeList outboundlevel) {

    String outboundstring;
    Map<String, String> extraparams =
        //	    new NoisyMap
        (new HashMap<String, String>(inputParameters));

    // get the scheme's option key, which is the name of a
    // parameter whose value is matched to the option key of the
    // level.

    String optionkey = tdtscheme.getOptionKey();
    String optionValue = extraparams.get(optionkey);
    // the name of a parameter which allows the appropriate option
    // to be selected

    // now consider the various options within the scheme and
    // level for each option element inside the level, check
    // whether the pattern attribute matches as a regular
    // expression

    String matchingOptionKey = null;
    Option matchingOption = null;
    Matcher prefixMatcher = null;
    for (Enumeration e = tdtlevel.enumerateOption(); e.hasMoreElements(); ) {
      Option opt = (Option) e.nextElement();
      if (optionValue == null || optionValue.equals(opt.getOptionKey())) {
        // possible match

        Matcher matcher = Pattern.compile(opt.getPattern()).matcher(input);
        if (matcher.matches()) {
          if (prefixMatcher != null) throw new TDTException("Multiple patterns matched");
          prefixMatcher = matcher;
          matchingOptionKey = opt.getOptionKey();
          matchingOption = opt;
        }
      }
    }
    if (prefixMatcher == null) throw new TDTException("No patterns matched");

    optionValue = matchingOptionKey;

    for (Enumeration e = matchingOption.enumerateField(); e.hasMoreElements(); ) {
      Field field = (Field) e.nextElement();
      int seq = field.getSeq();

      String strfieldname = field.getName();
      int fieldlength = field.getLength();
      String strfieldvalue = prefixMatcher.group(seq);
      // System.out.println("   processing field " + strfieldname + " = '" + strfieldvalue + "'");

      if (field.getCompaction() == null) {
        // if compaction is null, treat field as an integer

        if (field.getCharacterSet() != null) { // if the character set is specified
          Matcher charsetmatcher =
              Pattern.compile("^" + field.getCharacterSet() + "$").matcher(strfieldvalue);
          if (!charsetmatcher.matches()) {
            throw new TDTException(
                "field "
                    + strfieldname
                    + " ("
                    + strfieldvalue
                    + ") does not conform to the allowed character set ("
                    + field.getCharacterSet()
                    + ") ");
          }
        }

        BigInteger bigvalue = null;

        if (tdtlevel.getType() == LevelTypeList.BINARY) { // if the input was BINARY
          bigvalue = new BigInteger(strfieldvalue, 2);
          extraparams.put(strfieldname, bigvalue.toString());
        } else {
          if (field.getDecimalMinimum() != null || field.getDecimalMaximum() != null)
            bigvalue = new BigInteger(strfieldvalue);
          extraparams.put(strfieldname, strfieldvalue);
        }

        if (field.getDecimalMinimum() != null) { // if the decimal minimum is specified
          BigInteger bigmin = new BigInteger(field.getDecimalMinimum());

          if (bigvalue.compareTo(bigmin)
              == -1) { // throw an exception if the field value is less than the decimal minimum
            throw new TDTException(
                "field "
                    + strfieldname
                    + " ("
                    + bigvalue
                    + ") is less than DecimalMinimum ("
                    + field.getDecimalMinimum()
                    + ") allowed");
          }
        }

        if (field.getDecimalMaximum() != null) { // if the decimal maximum is specified
          BigInteger bigmax = new BigInteger(field.getDecimalMaximum());

          if (bigvalue.compareTo(bigmax)
              == 1) { // throw an excpetion if the field value is greater than the decimal maximum
            throw new TDTException(
                "field "
                    + strfieldname
                    + " ("
                    + bigvalue
                    + ") is greater than DecimalMaximum ("
                    + field.getDecimalMaximum()
                    + ") allowed");
          }
        }

        // after extracting the field, it may be necessary to pad it.

        padField(extraparams, field);

      } else {
        // compaction is specified - interpret binary as a string value using a truncated byte per
        // character

        CompactionMethodList compaction = field.getCompaction();
        PadDirectionList padDir = field.getPadDir();
        String padchar = field.getPadChar();
        String s;
        if (compaction == CompactionMethodList.VALUE_5)
          // "5-bit"
          s = bin2uppercasefive(strfieldvalue);
        else if (compaction == CompactionMethodList.VALUE_4)
          // 6-bit
          s = bin2alphanumsix(strfieldvalue);
        else if (compaction == CompactionMethodList.VALUE_3)
          // 7-bit
          s = bin2asciiseven(strfieldvalue);
        else if (compaction == CompactionMethodList.VALUE_2)
          // 8-bit
          s = bin2bytestring(strfieldvalue);
        else throw new Error("unsupported compaction method " + compaction);
        extraparams.put(strfieldname, stripPadChar(s, padDir, padchar));
      }
    } // for each field;

    /**
     * the EXTRACT rules are performed after parsing the input, in order to determine additional
     * fields that are to be derived from the fields obtained by the pattern match process
     */
    int seq = 0;
    for (Enumeration e = tdtlevel.enumerateRule(); e.hasMoreElements(); ) {
      Rule tdtrule = (Rule) e.nextElement();
      if (tdtrule.getType() == ModeList.EXTRACT) {
        assert seq < tdtrule.getSeq() : "Rule out of sequence order";
        seq = tdtrule.getSeq();
        processRules(extraparams, tdtrule);
      }
    }

    /**
     * Now we need to consider the corresponding output level and output option. The scheme must
     * remain the same, as must the value of optionkey (to select the corresponding option element
     * nested within the required outbound level)
     */
    Level tdtoutlevel = findLevel(tdtscheme, outboundlevel);
    Option tdtoutoption = findOption(tdtoutlevel, optionValue);

    /**
     * the FORMAT rules are performed before formatting the output, in order to determine additional
     * fields that are required for preparation of the outbound format
     */
    seq = 0;
    for (Enumeration e = tdtoutlevel.enumerateRule(); e.hasMoreElements(); ) {
      Rule tdtrule = (Rule) e.nextElement();
      if (tdtrule.getType() == ModeList.FORMAT) {
        assert seq < tdtrule.getSeq() : "Rule out of sequence order";
        seq = tdtrule.getSeq();
        processRules(extraparams, tdtrule);
      }
    }

    /**
     * Now we need to ensure that all fields required for the outbound grammar are suitably padded
     * etc. processPadding takes care of firstly padding the non-binary fields if padChar and
     * padDir, length are specified then (if necessary) converting to binary and padding the binary
     * representation to the left with zeros if the bit string is has fewer bits than the bitLength
     * attribute specifies. N.B. TDTv1.1 will be more specific about bit-level padding rather than
     * assuming that it is always to the left with the zero bit.
     */

    // System.out.println(" prior to processPadding, " + extraparams);
    for (Enumeration e = tdtoutoption.enumerateField(); e.hasMoreElements(); ) {
      Field field = (Field) e.nextElement();
      // processPadding(extraparams, field, outboundlevel, tdtoutoption);

      padField(extraparams, field);
      if (outboundlevel == LevelTypeList.BINARY) binaryPadding(extraparams, field);
    }

    /**
     * Construct the output from the specified grammar (in ABNF format) together with the field
     * values stored in inputparams
     */
    outboundstring = buildGrammar(tdtoutoption.getGrammar(), extraparams);

    // System.out.println("final extraparams = " + extraparams);
    // System.out.println("returned " + outboundstring);
    return outboundstring;
  }
Example #20
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);
    }
  }
Example #21
0
  /**
   * Adds additional entries to the extraparams hashmap by processing various rules defined in the
   * TDT definition files. Typically used for string processing functions, lookup in tables,
   * calculation of check digits etc.
   */
  private void processRules(Map<String, String> extraparams, Rule tdtrule) {
    String tdtfunction = tdtrule.getFunction();
    int openbracket = tdtfunction.indexOf("(");
    assert openbracket != -1;
    String params = tdtfunction.substring(openbracket + 1, tdtfunction.length() - 1);
    String rulename = tdtfunction.substring(0, openbracket);
    String[] parameter = params.split(",");
    String newfieldname = tdtrule.getNewFieldName();
    // System.out.println(tdtfunction + " " + parameter[0] + " " + extraparams.get(parameter[0]));
    /**
     * Stores in the hashmap extraparams the value obtained from a lookup in a specified XML table.
     *
     * <p>The first parameter is the given value already known. This is denoted as $1 in the
     * corresponding XPath expression
     *
     * <p>The second parameter is the string filename of the table which must be present in the
     * auxiliary subdirectory
     *
     * <p>The third parameter is the column in which the supplied input value should be sought
     *
     * <p>The fourth parameter is the column whose value should be read for the corresponding row,
     * in order to obtain the result of the lookup.
     *
     * <p>The rule in the definition file may contain an XPath expression and a URL where the table
     * may be obtained.
     */
    if (rulename.equals("TABLELOOKUP")) {
      // parameter[0] is given value
      // parameter[1] is table
      // parameter[2] is input column supplied
      // parameter[3] is output column required
      assert parameter.length == 4 : "incorrect number of parameters to tablelookup " + params;
      if (parameter[1].equals("tdt64bitcpi")) {
        String s = extraparams.get(parameter[0]);
        assert s != null : tdtfunction + " when " + parameter[0] + " is null";
        String t = gs1cpi.get(s);
        assert t != null : "gs1cpi[" + s + "] is null";
        assert newfieldname != null;
        extraparams.put(newfieldname, t);
        // extraparams.put(newfieldname, gs1cpi.get(extraparams.get(parameter[0])));
      } else { // JPB! the following is untested
        String tdtxpath = tdtrule.getTableXPath();
        String tdttableurl = tdtrule.getTableURL();
        String tdtxpathsub = tdtxpath.replaceAll("\\$1", extraparams.get(parameter[0]));
        extraparams.put(newfieldname, xpathlookup("ManagerTranslation.xml", tdtxpathsub));
      }
    }

    /**
     * Stores the length of the specified string under the new fieldname specified by the
     * corresponding rule of the definition file.
     */
    if (rulename.equals("LENGTH")) {
      assert extraparams.get(parameter[0]) != null
          : tdtfunction + " when " + parameter[0] + " is null";
      if (extraparams.get(parameter[0]) != null) {
        extraparams.put(newfieldname, Integer.toString(extraparams.get(parameter[0]).length()));
      }
    }

    /**
     * Stores a GS1 check digit in the extraparams hashmap, keyed under the new fieldname specified
     * by the corresponding rule of the definition file.
     */
    if (rulename.equals("GS1CHECKSUM")) {
      assert extraparams.get(parameter[0]) != null
          : tdtfunction + " when " + parameter[0] + " is null";
      if (extraparams.get(parameter[0]) != null) {
        extraparams.put(newfieldname, gs1checksum(extraparams.get(parameter[0])));
      }
    }

    /**
     * Obtains a substring of the string provided as the first parameter. If only a single second
     * parameter is specified, then this is considered as the start index and all characters from
     * the start index onwards are stored in the extraparams hashmap under the key named
     * 'newfieldname' in the corresponding rule of the definition file. If a second and third
     * parameter are specified, then the second parameter is the start index and the third is the
     * length of characters required. A substring consisting characters from the start index up to
     * the required length of characters is stored in the extraparams hashmap, keyed under the new
     * fieldname specified by the corresponding rule of the defintion file.
     */
    if (rulename.equals("SUBSTR")) {
      assert extraparams.get(parameter[0]) != null
          : tdtfunction + " when " + parameter[0] + " is null";
      if (parameter.length == 2) {
        if (extraparams.get(parameter[0]) != null) {
          int start = getIntValue(parameter[1], extraparams);
          if (start >= 0) {
            extraparams.put(newfieldname, extraparams.get(parameter[0]).substring(start));
          }
        }
      }
      if (parameter.length
          == 3) { // need to check that this variation is correct - c.f. Perl substr
        assert extraparams.get(parameter[0]) != null
            : tdtfunction + " when " + parameter[0] + " is null";
        if (extraparams.get(parameter[0]) != null) {
          int start = getIntValue(parameter[1], extraparams);
          int end = getIntValue(parameter[2], extraparams);
          if ((start >= 0) && (end >= 0)) {
            extraparams.put(
                newfieldname, extraparams.get(parameter[0]).substring(start, start + end));
          }
        }
      }
    }

    /**
     * Concatenates specified string parameters together. Literal values must be enclosed within
     * single or double quotes or consist of unquoted digits. Other unquoted strings are considered
     * as fieldnames and the corresponding value from the extraparams hashmap are inserted. The
     * result of the concatenation (and substitution) of the strings is stored as a new entry in the
     * extraparams hashmap, keyed under the new fieldname specified by the rule.
     */
    if (rulename.equals("CONCAT")) {
      StringBuilder buffer = new StringBuilder();
      for (int p1 = 0; p1 < parameter.length; p1++) {
        Matcher matcher = Pattern.compile("\"(.*?)\"|'(.*?)'|[0-9]").matcher(parameter[p1]);
        if (matcher.matches()) {
          buffer.append(parameter[p1]);
        } else {
          assert extraparams.get(parameter[p1]) != null
              : tdtfunction + " when " + parameter[p1] + " is null";
          if (extraparams.get(parameter[p1]) != null) {
            buffer.append(extraparams.get(parameter[p1]));
          }
        }
      }
      extraparams.put(newfieldname, buffer.toString());
    }
  }
  public void buildTypeGraph() {
    Map<String, JarFile> openJarFiles = new HashMap<String, JarFile>();
    Map<String, File> openClassFiles = new HashMap<String, File>();
    // use global cache to load resource in/out of the same jar as the classes
    Set<String> resourceCacheSet = new HashSet<>();
    try {
      for (String path : pathsToScan) {
        File f = null;
        try {
          f = new File(path);
          if (!f.exists()
              || f.isDirectory()
              || (!f.getName().endsWith("jar") && !f.getName().endsWith("class"))) {
            continue;
          }
          if (GENERATED_CLASSES_JAR.equals(f.getName())) {
            continue;
          }
          if (f.getName().endsWith("class")) {
            typeGraph.addNode(f);
            openClassFiles.put(path, f);
          } else {
            JarFile jar = new JarFile(path);
            openJarFiles.put(path, jar);
            java.util.Enumeration<JarEntry> entriesEnum = jar.entries();
            while (entriesEnum.hasMoreElements()) {
              final java.util.jar.JarEntry jarEntry = entriesEnum.nextElement();
              String entryName = jarEntry.getName();
              if (jarEntry.isDirectory()) {
                continue;
              }
              if (entryName.endsWith("-javadoc.xml")) {
                try {
                  processJavadocXml(jar.getInputStream(jarEntry));
                  // break;
                } catch (Exception ex) {
                  LOG.warn("Cannot process javadoc {} : ", entryName, ex);
                }
              } else if (entryName.endsWith(".class")) {
                TypeGraph.TypeGraphVertex newNode = typeGraph.addNode(jarEntry, jar);
                // check if any visited resources belong to this type
                for (Iterator<String> iter = resourceCacheSet.iterator(); iter.hasNext(); ) {
                  String entry = iter.next();
                  if (entry.startsWith(entryName.substring(0, entryName.length() - 6))) {
                    newNode.setHasResource(true);
                    iter.remove();
                  }
                }
              } else {
                String className = entryName;
                boolean foundClass = false;
                // check if this resource belongs to any visited type
                while (className.contains("/")) {
                  className = className.substring(0, className.lastIndexOf('/'));
                  TypeGraph.TypeGraphVertex tgv = typeGraph.getNode(className.replace('/', '.'));
                  if (tgv != null) {
                    tgv.setHasResource(true);
                    foundClass = true;
                    break;
                  }
                }
                if (!foundClass) {
                  resourceCacheSet.add(entryName);
                }
              }
            }
          }
        } catch (IOException ex) {
          LOG.warn("Cannot process file {}", f, ex);
        }
      }

      typeGraph.trim();

      typeGraph.updatePortTypeInfoInTypeGraph(openJarFiles, openClassFiles);
    } finally {
      for (Entry<String, JarFile> entry : openJarFiles.entrySet()) {
        try {
          entry.getValue().close();
        } catch (IOException e) {
          DTThrowable.wrapIfChecked(e);
        }
      }
    }
  }
Example #23
0
  private void processTxt(Node operation) {
    List<Node> targets = getChildNodes(operation, "target");
    List<Node> optionNodes = getChildNodes(operation, "opt");
    List<Node> separatorNode = getChildNodes(operation, "separator");
    if (targets.isEmpty() || optionNodes.isEmpty()) {
      return;
    }
    String defaultSeparator = "=";
    String globalSeparator = defaultSeparator;
    if (!separatorNode.isEmpty()) {
      globalSeparator = separatorNode.get(0).getTextContent();
      if (globalSeparator.length() != 1) {
        globalSeparator = defaultSeparator;
      }
    }
    Map<String, String> options = new HashMap<String, String>();
    Map<String, String> processedOptions = new HashMap<String, String>();
    for (int i = 0; i < optionNodes.size(); i++) {
      Node option = optionNodes.get(i);
      String name = option.getAttributes().getNamedItem("name").getNodeValue();
      String value = option.getTextContent();
      if (options.containsKey(name)) {
        options.remove(name);
      }
      options.put(name, value);
    }
    for (int t = 0; t < targets.size(); t++) {
      File target = new File(absolutePath(targets.get(t).getTextContent()));
      File tmpFile = new File(Utils.timestamp());
      BufferedWriter bw = null;
      BufferedReader br = null;
      try {
        Node separatorAttr = targets.get(t).getAttributes().getNamedItem("separator");
        String separator = (separatorAttr == null) ? globalSeparator : separatorAttr.getNodeValue();
        if (separator.length() != 1) {
          separator = globalSeparator;
        }
        bw = new BufferedWriter(new FileWriter(tmpFile));
        if (target.exists()) {
          br = new BufferedReader(new FileReader(target));
          for (String line; (line = br.readLine()) != null; ) {
            String[] parts = line.split(separator);
            if (parts.length < 2) {
              bw.write(line);
              bw.newLine();
              continue;
            }

            String optName = parts[0].trim();
            if (options.containsKey(optName)) {
              String optValue = options.get(optName);
              bw.write(optName + " " + separator + " " + optValue);
              bw.newLine();
              processedOptions.put(optName, optValue);
              options.remove(optName);
            } else if (processedOptions.containsKey(optName)) {
              bw.write(optName + " " + separator + " " + processedOptions.get(optName));
              bw.newLine();
            } else {
              bw.write(line);
              bw.newLine();
            }
          }
          br.close();
        }
        for (Map.Entry<String, String> entry : options.entrySet()) {
          bw.write(entry.getKey() + " " + separator + " " + entry.getValue());
          bw.newLine();
        }
        bw.close();
        FileUtils.copyFile(tmpFile, target);
        FileUtils.forceDelete(tmpFile);
      } catch (IOException ex) {
        Utils.onError(new Error.WriteTxtConfig(target.getPath()));
      }
    }
  }
Example #24
0
  public static void testNaming() throws Exception {
    Map<String, Object> map = Create.map();

    map.put("_secret", "_secret");
    map.put("_secret", "_secret");
    map.put(".secret", ".secret");
    map.put("$new", "$new");
    map.put("new", "new");
    map.put("secret", "secret");
    map.put("a_b_c", "a_b_c");
    map.put("a.b.c", "a.b.c");
    map.put(".a_b", ".a_b");
    map.put("$$$$a_b", "$$$$a_b");
    map.put("$$$$a.b", "$$$$a.b");
    map.put("a", "a");
    map.put("a$", "a$");
    map.put("a$$", "a$$");
    map.put("a$.$", "a$.$");
    map.put("a$_$", "a$_$");
    map.put("a..", "a..");
    map.put("noid", "noid");
    map.put("nullid", "nullid");

    Naming trt = Configurable.createConfigurable(Naming.class, map);

    // By name
    assertEquals("secret", trt.secret());
    assertEquals("_secret", trt.__secret());
    assertEquals(".secret", trt._secret());
    assertEquals("new", trt.$new());
    assertEquals("$new", trt.$$new());
    assertEquals("a.b.c", trt.a_b_c());
    assertEquals("a_b_c", trt.a__b__c());
    assertEquals(".a_b", trt._a__b());
    assertEquals("$$$$a.b", trt.$$$$$$$$a_b());
    assertEquals("$$$$a_b", trt.$$$$$$$$a__b());
    assertEquals("a", trt.a$());
    assertEquals("a$", trt.a$$());
    assertEquals("a$", trt.a$$$());
    assertEquals("a$.$", trt.a$$_$$());
    assertEquals("a$_$", trt.a$$__$$());
    assertEquals("a..", trt.a_$_());
    assertEquals("noid", trt.noid());
    assertEquals("nullid", trt.nullid());

    // By AD
    assertEquals("secret", trt.xsecret());
    assertEquals("_secret", trt.x__secret());
    assertEquals(".secret", trt.x_secret());
    assertEquals("new", trt.x$new());
    assertEquals("$new", trt.x$$new());
    assertEquals("a.b.c", trt.xa_b_c());
    assertEquals("a_b_c", trt.xa__b__c());
    assertEquals(".a_b", trt.x_a__b());
    assertEquals("$$$$a.b", trt.x$$$$$$$$a_b());
    assertEquals("$$$$a_b", trt.x$$$$$$$$a__b());
    assertEquals("a", trt.xa$());
    assertEquals("a$", trt.xa$$());
    assertEquals("a$", trt.xa$$$());
    assertEquals("a$.$", trt.xa$$_$$());

    Builder b = new Builder();
    b.addClasspath(new File("bin"));
    b.setProperty("Export-Package", "test.metatype");
    b.setProperty("-metatype", "*");
    b.build();
    assertEquals(0, b.getErrors().size());
    assertEquals(0, b.getWarnings().size());

    Resource r = b.getJar().getResource("OSGI-INF/metatype/test.metatype.MetatypeTest$Naming.xml");
    IO.copy(r.openInputStream(), System.err);
    Document d = db.parse(r.openInputStream(), "UTF-8");
    assertEquals(
        "http://www.osgi.org/xmlns/metatype/v1.1.0", d.getDocumentElement().getNamespaceURI());
  }