public void TryFinderClass(String str, String matchKey) {
   // String jsonText = "{\"first\": 123, \"second\": [{\"k1\":{\"id\":\"id1\"}}, 4, 5, 6, {\"id\":
   // 123}], \"third\": 789, \"id\": null}";
   String jsonText = str;
   JSONParser parser = new JSONParser();
   KeyFinder finder = new KeyFinder();
   // finder.setMatchKey("id");
   finder.setMatchKey(matchKey);
   try {
     while (!finder.isEnd()) {
       parser.parse(jsonText, finder, true);
       if (finder.isFound()) {
         finder.setFound(false);
         System.out.println(matchKey + " found:");
         System.out.println(finder.getValue());
       }
     }
   } catch (ParseException pe) {
     System.out.println(pe.getMessage());
   }
 }
Example #2
0
 public List<String> getList(T event) {
   return finder.get(event);
 }
  /**
   * runs key and bpm detector on
   *
   * @filename, optionally writes tags
   * @param filename
   * @return
   */
  public boolean analyzeTrack(String filename, boolean writeTags) {
    String wavfilename = "";
    AudioData data = new AudioData();
    File temp = null;
    File temp2 = null;
    try {
      temp = File.createTempFile("keyfinder", ".wav");
      temp2 = File.createTempFile("keyfinder2", ".wav");
      wavfilename = temp.getAbsolutePath();
      // Delete temp file when program exits.
      temp.deleteOnExit();
      temp2.deleteOnExit();
      decodeAudioFile(new File(filename), temp, 44100);
      decodeAudioFile(temp, temp2);
    } catch (Exception ex) {
      Logger.getLogger(TrackAnalyzer.class.getName())
          .log(Level.WARNING, "error while decoding" + filename + ".");
      if (temp.length() == 0) {
        logDetectionResult(filename, "-", "-", false);
        temp.delete();
        temp2.delete();
        return false;
      }
    }

    KeyDetectionResult r;
    try {
      data.loadFromAudioFile(temp2.getAbsolutePath());
      r = k.findKey(data, p);
      if (r.globalKeyEstimate == Parameters.key_t.SILENCE) {
        System.out.println("SILENCE");
      }
    } catch (Exception ex) {
      Logger.getLogger(TrackAnalyzer.class.getName()).log(Level.SEVERE, null, ex);
      logDetectionResult(filename, "-", "-", false);
      deleteTempFiles(temp, temp2);
      return false;
    }

    String formattedBpm = "0";
    if (!c.noBpm) {
      // get bpm
      if (c.hiQuality) {
        try {
          // decodeAudioFile(new File(filename), temp, 44100);
          // @todo hiquality stuff
        } catch (Exception ex) {
          Logger.getLogger(TrackAnalyzer.class.getName())
              .log(
                  Level.WARNING,
                  "couldn't decode " + filename + " for hiquality bpm detection.",
                  ex);
        }
      }
      double bpm = BeatRoot.getBPM(wavfilename);
      if (Double.isNaN(bpm) && !c.hiQuality) {
        try {
          // bpm couldn't be detected. try again with a higher quality wav.
          Logger.getLogger(TrackAnalyzer.class.getName())
              .log(Level.WARNING, "bpm couldn't be detected for " + filename + ". Trying again.");
          decodeAudioFile(new File(filename), temp, 44100);
          bpm = BeatRoot.getBPM(wavfilename);
          if (Double.isNaN(bpm)) {
            Logger.getLogger(TrackAnalyzer.class.getName())
                .log(Level.WARNING, "bpm still couldn't be detected for " + filename + ".");
          } else {
            Logger.getLogger(TrackAnalyzer.class.getName())
                .log(Level.INFO, "bpm now detected correctly for " + filename);
          }
        } catch (Exception ex) {
          logDetectionResult(filename, "-", "-", false);
        }
      } else if (Double.isNaN(bpm) && c.hiQuality) {
        Logger.getLogger(TrackAnalyzer.class.getName())
            .log(Level.WARNING, "bpm couldn't be detected for " + filename + ".");
      }
      if (!Double.isNaN(bpm)) {
        formattedBpm = new DecimalFormat("#.#").format(bpm).replaceAll(",", ".");
      }
    }
    System.out.printf(
        "%s key: %s BPM: %s\n", filename, Parameters.camelotKey(r.globalKeyEstimate), formattedBpm);

    boolean wroteTags = false;
    if (c.writeTags) {
      wroteTags = updateTags(filename, formattedBpm, Parameters.camelotKey(r.globalKeyEstimate));
    }
    logDetectionResult(
        filename, Parameters.camelotKey(r.globalKeyEstimate), formattedBpm, wroteTags);
    deleteTempFiles(temp, temp2);
    return true;
  }
Example #4
0
  @SuppressWarnings("unchecked")
  public void testDecode() throws Exception {
    System.out.println("=======decode=======");

    String s = "[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
    Object obj = JSONValue.parse(s);
    JSONArray array = (JSONArray) obj;
    System.out.println("======the 2nd element of array======");
    System.out.println(array.get(1));
    System.out.println();
    assertEquals("{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}", array.get(1).toString());

    JSONObject obj2 = (JSONObject) array.get(1);
    System.out.println("======field \"1\"==========");
    System.out.println(obj2.get("1"));
    assertEquals("{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}", obj2.get("1").toString());

    s = "{}";
    obj = JSONValue.parse(s);
    assertEquals("{}", obj.toString());

    s = "[5,]";
    obj = JSONValue.parse(s);
    assertEquals("[5]", obj.toString());

    s = "[5,,2]";
    obj = JSONValue.parse(s);
    assertEquals("[5,2]", obj.toString());

    s = "[\"hello\\bworld\\\"abc\\tdef\\\\ghi\\rjkl\\n123\\u4e2d\"]";
    obj = JSONValue.parse(s);
    assertEquals("hello\bworld\"abc\tdef\\ghi\rjkl\n123δΈ­", ((List<Object>) obj).get(0).toString());

    JSONParser parser = new JSONParser();
    s = "{\"name\":";
    try {
      obj = parser.parse(s);
    } catch (ParseException pe) {
      assertEquals(ParseException.ERROR_UNEXPECTED_TOKEN, pe.getErrorType());
      assertEquals(8, pe.getPosition());
    }

    s = "{\"name\":}";
    try {
      obj = parser.parse(s);
    } catch (ParseException pe) {
      assertEquals(ParseException.ERROR_UNEXPECTED_TOKEN, pe.getErrorType());
      assertEquals(8, pe.getPosition());
    }

    s = "{\"name";
    try {
      obj = parser.parse(s);
    } catch (ParseException pe) {
      assertEquals(ParseException.ERROR_UNEXPECTED_TOKEN, pe.getErrorType());
      assertEquals(6, pe.getPosition());
    }

    s = "[[null, 123.45, \"a\\\tb c\"}, true]";
    try {
      parser.parse(s);
    } catch (ParseException pe) {
      assertEquals(24, pe.getPosition());
      System.out.println("Error at character position: " + pe.getPosition());
      switch (pe.getErrorType()) {
        case ParseException.ERROR_UNEXPECTED_TOKEN:
          System.out.println("Unexpected token: " + pe.getUnexpectedObject());
          break;
        case ParseException.ERROR_UNEXPECTED_CHAR:
          System.out.println("Unexpected character: " + pe.getUnexpectedObject());
          break;
        case ParseException.ERROR_UNEXPECTED_EXCEPTION:
          ((Exception) pe.getUnexpectedObject()).printStackTrace();
          break;
      }
    }

    s = "{\"first\": 123, \"second\": [4, 5, 6], \"third\": 789}";
    ContainerFactory containerFactory =
        new ContainerFactory() {
          public List<Object> creatArrayContainer() {
            return new LinkedList<Object>();
          }

          public Map<Object, Object> createObjectContainer() {
            return new LinkedHashMap<Object, Object>();
          }
        };

    try {
      Map<Object, Object> json = (Map<Object, Object>) parser.parse(s, containerFactory);
      Iterator<Map.Entry<Object, Object>> iter = json.entrySet().iterator();
      System.out.println("==iterate result==");
      while (iter.hasNext()) {
        Map.Entry<Object, Object> entry = (Map.Entry<Object, Object>) iter.next();
        System.out.println(entry.getKey() + "=>" + entry.getValue());
      }

      System.out.println("==toJSONString()==");
      System.out.println(JSONValue.toJSONString(json));
      assertEquals(
          "{\"first\":123,\"second\":[4,5,6],\"third\":789}", JSONValue.toJSONString(json));
    } catch (ParseException pe) {
      pe.printStackTrace();
    }

    s = "{\"first\": 123, \"second\": [{\"s1\":{\"s11\":\"v11\"}}, 4, 5, 6], \"third\": 789}";
    ContentHandler myHandler =
        new ContentHandler() {

          public boolean endArray() throws ParseException {
            System.out.println("endArray()");
            return true;
          }

          public void endJSON() throws ParseException {
            System.out.println("endJSON()");
          }

          public boolean endObject() throws ParseException {
            System.out.println("endObject()");
            return true;
          }

          public boolean endObjectEntry() throws ParseException {
            System.out.println("endObjectEntry()");
            return true;
          }

          public boolean primitive(Object value) throws ParseException {
            System.out.println("primitive(): " + value);
            return true;
          }

          public boolean startArray() throws ParseException {
            System.out.println("startArray()");
            return true;
          }

          public void startJSON() throws ParseException {
            System.out.println("startJSON()");
          }

          public boolean startObject() throws ParseException {
            System.out.println("startObject()");
            return true;
          }

          public boolean startObjectEntry(String key) throws ParseException {
            System.out.println("startObjectEntry(), key:" + key);
            return true;
          }
        };
    try {
      parser.parse(s, myHandler);
    } catch (ParseException pe) {
      pe.printStackTrace();
    }

    class KeyFinder implements ContentHandler {
      private Object value;
      private boolean found = false;
      private boolean end = false;
      private String key;
      private String matchKey;

      public void setMatchKey(String matchKey) {
        this.matchKey = matchKey;
      }

      public Object getValue() {
        return value;
      }

      public boolean isEnd() {
        return end;
      }

      public void setFound(boolean found) {
        this.found = found;
      }

      public boolean isFound() {
        return found;
      }

      public void startJSON() throws ParseException, IOException {
        found = false;
        end = false;
      }

      public void endJSON() throws ParseException, IOException {
        end = true;
      }

      public boolean primitive(Object value) throws ParseException, IOException {
        if (key != null) {
          if (key.equals(matchKey)) {
            found = true;
            this.value = value;
            key = null;
            return false;
          }
        }
        return true;
      }

      public boolean startArray() throws ParseException, IOException {
        return true;
      }

      public boolean startObject() throws ParseException, IOException {
        return true;
      }

      public boolean startObjectEntry(String key) throws ParseException, IOException {
        this.key = key;
        return true;
      }

      public boolean endArray() throws ParseException, IOException {
        return false;
      }

      public boolean endObject() throws ParseException, IOException {
        return true;
      }

      public boolean endObjectEntry() throws ParseException, IOException {
        return true;
      }
    };

    s =
        "{\"first\": 123, \"second\": [{\"k1\":{\"id\":\"id1\"}}, 4, 5, 6, {\"id\": 123}], \"third\": 789, \"id\": null}";
    parser.reset();
    KeyFinder keyFinder = new KeyFinder();
    keyFinder.setMatchKey("id");
    int i = 0;
    try {
      while (!keyFinder.isEnd()) {
        parser.parse(s, keyFinder, true);
        if (keyFinder.isFound()) {
          i++;
          keyFinder.setFound(false);
          System.out.println("found id:");
          System.out.println(keyFinder.getValue());
          if (i == 1) assertEquals("id1", keyFinder.getValue());
          if (i == 2) {
            assertTrue(keyFinder.getValue() instanceof Number);
            assertEquals("123", String.valueOf(keyFinder.getValue()));
          }
          if (i == 3) assertTrue(null == keyFinder.getValue());
        }
      }
    } catch (ParseException pe) {
      pe.printStackTrace();
    }
  }