예제 #1
0
  /**
   * Retrieves the specified value. Throws an error if value cannot be read.
   *
   * @param key key
   * @param c expected type
   * @return result
   */
  private Object get(final Object[] key, final Class<?> c) {
    final Object entry = props.get(key[0].toString());
    if (entry == null) Util.notexpected("Property " + key[0] + " not defined.");

    final Class<?> cc = entry.getClass();
    if (c != cc) Util.notexpected("Property '" + key[0] + "' is a " + Util.name(cc));
    return entry;
  }
예제 #2
0
  @Override
  public JapaneseTokenizer init(final byte[] txt) {
    String source = string(txt);
    if (wc) { // convert wide-space to space
      source = source.replace('\u3000', '\u0020');
    }
    final ArrayList<?> morpheme = (ArrayList<?>) Reflect.invoke(parse, tagger, source);
    final ArrayList<Morpheme> list = new ArrayList<>();
    try {
      int prev = 0;
      final int ms = morpheme.size();
      for (int i = 0; i < ms; i++) {
        final Object m = morpheme.get(i);
        final String srfc = surface.get(m).toString();
        final String ftr = feature.get(m).toString();
        final int strt = start.getInt(m);
        if (i != 0) {
          final int l = strt - prev;
          if (l != 0) {
            list.add(new Morpheme(source.substring(strt - 1, strt + l - 1), KIGOU_FEATURE));
          }
        }
        prev = srfc.length() + strt;

        // separates continuous mark (ASCII)
        boolean cont = true;
        final ArrayList<Morpheme> marks = new ArrayList<>();
        final int sl = srfc.length();
        for (int s = 0; s < sl; s++) {
          final String c = String.valueOf(srfc.charAt(s));
          final byte[] t = token(c);
          if (t.length == 1) {
            if (letter(t[0]) || digit(t[0])) cont = false;
            else marks.add(new Morpheme(c, KIGOU_FEATURE));
          } else {
            cont = false;
          }
        }

        if (cont) list.addAll(marks);
        else list.add(new Morpheme(srfc, ftr));
      }
    } catch (final Exception ex) {
      Util.errln(Util.className(this) + ": " + ex);
    }
    tokenList = list;
    tokens = list.iterator();

    return this;
  }
예제 #3
0
 public Object computeReadValue() {
   Object readValue;
   try {
     readValue = MethodInvocationManager.invokeMethod(readMethod, parentObject, readMethodParams);
     return Util.deepCopy(readValue);
   } catch (Exception e) {
     return null;
   }
 }
예제 #4
0
 /**
  * Returns a string representation of all found arguments.
  *
  * @param args array with arguments
  * @return string representation
  */
 static String foundArgs(final Value[] args) {
   // compose found arguments
   final StringBuilder sb = new StringBuilder();
   for (final Value v : args) {
     if (sb.length() != 0) sb.append(", ");
     sb.append(v instanceof Jav ? Util.className(((Jav) v).toJava()) : v.seqType());
   }
   return sb.toString();
 }
예제 #5
0
  /**
   * Sets the specified value after casting it to the correct type.
   *
   * @param key key
   * @param val value
   * @return final value, or {@code null} if the key has not been found
   */
  public final synchronized String set(final String key, final String val) {
    final Object type = get(key);
    if (type == null) return null;

    String v = val;
    if (type instanceof Boolean) {
      final boolean b = val == null || val.isEmpty() ? !((Boolean) type) : Util.yes(val);
      setObject(key, b);
      v = Util.flag(b);
    } else if (type instanceof Integer) {
      setObject(key, Integer.parseInt(val));
      v = String.valueOf(get(key));
    } else if (type instanceof String) {
      setObject(key, val);
    } else {
      Util.notexpected("Unknown property type: " + type.getClass().getSimpleName());
    }
    return v;
  }
예제 #6
0
 /** Constructor, initializing the default options. */
 protected AProp() {
   try {
     for (final Field f : getClass().getFields()) {
       final Object obj = f.get(null);
       if (!(obj instanceof Object[])) continue;
       final Object[] arr = (Object[]) obj;
       props.put(arr[0].toString(), arr[1]);
     }
   } catch (final Exception ex) {
     Util.notexpected(ex);
   }
 }
예제 #7
0
  static {
    IOFile dic = null;
    if (Reflect.available(PATTERN)) {
      dic = new IOFile(LANG);
      if (!dic.exists()) {
        dic = new IOFile(Prop.HOME, "etc/" + LANG);
        if (!dic.exists()) {
          available = false;
        }
      }
    } else {
      available = false;
    }

    if (available) {
      Class<?> clz = Reflect.find(PATTERN);
      if (clz == null) {
        Util.debug("Could not initialize Igo Japanese lexer.");
      } else {
        /* Igo constructor. */
        final Constructor<?> tgr = Reflect.find(clz, String.class);
        tagger = Reflect.get(tgr, dic.path());
        if (tagger == null) {
          available = false;
          Util.debug("Could not initialize Igo Japanese lexer.");
        } else {
          parse = Reflect.method(clz, "parse", CharSequence.class);
          if (parse == null) {
            Util.debug("Could not initialize Igo lexer method.");
          }
          clz = Reflect.find("net.reduls.igo.Morpheme");
          surface = Reflect.field(clz, "surface");
          feature = Reflect.field(clz, "feature");
          start = Reflect.field(clz, "start");
        }
      }
    }
  }
예제 #8
0
  public void init(
      CommandListener theListener,
      MethodProxy theWriteMethod,
      Object theParentObject,
      Object[] theParams,
      MethodProxy theReadMethod // ,
      // Object[] theReadMethodParams
      ) {
    // frame = theFrame;
    writeMethod = theWriteMethod;
    // undoWriteMethod = uiBean.getUndo(theParentObject, writeMethod);
    // if (undoWriteMethod == null)
    undoWriteMethod = writeMethod;
    parentObject = theParentObject;
    params = theParams;
    readMethod = theReadMethod;
    // readMethodParams = theReadMethodParams;
    listener = theListener;
    undoWriteMethodParams = Util.copy(theParams);
    readMethodParams = createReadMethodParams(theParams);

    isVoid = theWriteMethod.getReturnType() == theWriteMethod.getDeclaringClass().voidType();
  }
예제 #9
0
  /**
   * Converts an HTML document to XML.
   *
   * @param io io reference
   * @param opts html options
   * @return parser
   * @throws IOException I/O exception
   */
  private static IO toXML(final IO io, final HtmlOptions opts) throws IOException {
    // reader could not be initialized; fall back to XML
    if (READER == null) return io;

    try {
      // tries to extract the encoding from the input
      final TextInput ti = new TextInput(io);
      String enc = ti.encoding();
      final byte[] content = ti.content();

      // looks for a charset definition
      final byte[] encoding = token("charset=");
      int cs = indexOf(content, encoding);
      if (cs > 0) {
        // extracts the encoding string
        cs += encoding.length;
        int ce = cs;
        final int cl = content.length;
        while (++ce < cl && content[ce] > 0x28) ;
        enc = string(substring(content, cs, ce));
      }

      // define input
      final InputSource is = new InputSource(new ArrayInput(content));
      is.setEncoding(supported(enc) ? normEncoding(enc) : UTF8);
      // define output
      final StringWriter sw = new StringWriter();
      final XMLReader reader = (XMLReader) Reflect.get(READER);
      final Object writer = Reflect.get(WRITER, sw);

      // set TagSoup options
      if (opts.get(HtmlOptions.HTML)) {
        reader.setFeature("http://xml.org/sax/features/namespaces", false);
        opt("method", "html");
        opt("omit-xml-declaration", "yes");
      }
      if (opts.get(HtmlOptions.NONS))
        reader.setFeature("http://xml.org/sax/features/namespaces", false);
      if (opts.get(HtmlOptions.OMITXML)) opt("omit-xml-declaration", "yes");
      if (opts.get(HtmlOptions.NOBOGONS)) reader.setFeature(FEATURES + "ignore-bogons", true);
      if (opts.get(HtmlOptions.NODEFAULTS))
        reader.setFeature(FEATURES + "default-attributes", false);
      if (opts.get(HtmlOptions.NOCOLONS)) reader.setFeature(FEATURES + "translate-colons", true);
      if (opts.get(HtmlOptions.NORESTART)) reader.setFeature(FEATURES + "restart-elements", false);
      if (opts.get(HtmlOptions.IGNORABLE))
        reader.setFeature(FEATURES + "ignorable-whitespace", true);
      if (opts.get(HtmlOptions.EMPTYBOGONS)) reader.setFeature(FEATURES + "bogons-empty", true);
      if (opts.get(HtmlOptions.ANY)) reader.setFeature(FEATURES + "bogons-empty", false);
      if (opts.get(HtmlOptions.NOROOTBOGONS)) reader.setFeature(FEATURES + "root-bogons", false);
      if (opts.get(HtmlOptions.NOCDATA)) reader.setFeature(FEATURES + "cdata-elements", false);
      if (opts.get(HtmlOptions.LEXICAL))
        reader.setProperty("http://xml.org/sax/properties/lexical-handler", writer);
      if (opts.contains(HtmlOptions.METHOD)) opt("method", opts.get(HtmlOptions.METHOD));
      if (opts.contains(HtmlOptions.DOCTYPESYS))
        opt("doctype-system", opts.get(HtmlOptions.DOCTYPESYS));
      if (opts.contains(HtmlOptions.DOCTYPEPUB))
        opt("doctype-public", opts.get(HtmlOptions.DOCTYPEPUB));
      if (opts.contains(HtmlOptions.ENCODING)) is.setEncoding(opts.get(HtmlOptions.ENCODING));
      // end TagSoup options

      reader.setContentHandler((ContentHandler) writer);
      reader.parse(is);
      return new IOContent(token(sw.toString()), io.name());

    } catch (final SAXException ex) {
      Util.errln(ex);
      return io;
    }
  }
    public void runTest() throws Throwable {
      boolean pass = true;

      out.println("### framework test bundle :STARTLVL100A start");

      try {
        buA = Util.installBundle(bc, "bundleSLA_test-1.0.0.jar");
        sl.setBundleStartLevel(buA, baseLevel + 10);
      } catch (Exception e) {
        out.println("Unexpected exception: " + e);
        e.printStackTrace();
        fail("framework test bundle " + e + " :STARTLVL100A:FAIL");
      }

      buB = null;
      try {
        buB = Util.installBundle(bc, "bundleSLB_test-1.0.0.jar");
        sl.setBundleStartLevel(buB, baseLevel + 30);
      } catch (Exception e) {
        out.println("Unexpected exception: " + e);
        e.printStackTrace();
        fail("framework test bundle " + e + " :STARTLVL100A:FAIL");
      }

      buC = null;
      try {
        buC = Util.installBundle(bc, "bundleSLC_test_api-1.0.0.jar");
        sl.setBundleStartLevel(buC, baseLevel + 20);
      } catch (Exception e) {
        out.println("Unexpected exception: " + e);
        e.printStackTrace();
        fail("framework test bundle " + e + " :STARTLVL100A:FAIL");
      }

      try {
        buA.start();
        assertTrue("BundleA should not be ACTIVE", buA.getState() != Bundle.ACTIVE);
      } catch (Exception e) {
        out.println("Unexpected exception: " + e);
        e.printStackTrace();
        fail("framework test bundle " + e + " :STARTLVL100A:FAIL");
      }

      try {
        buB.start();
        assertTrue("BundleB should not be ACTIVE", buB.getState() != Bundle.ACTIVE);
      } catch (Exception e) {
        out.println("Unexpected exception: " + e);
        e.printStackTrace();
        fail("framework test bundle " + e + " :STARTLVL100A:FAIL");
      }

      try {
        buC.start();
        assertTrue("BundleC should not be ACTIVE", buC.getState() != Bundle.ACTIVE);
      } catch (Exception e) {
        out.println("Unexpected exception: " + e);
        e.printStackTrace();
        fail("framework test bundle " + e + " :STARTLVL100A:FAIL");
      }

      syncBListen.clearEvents();

      sl.setStartLevel(baseLevel + 30);

      pass =
          syncBListen.checkEvents(
              new BundleEvent[] {
                new BundleEvent(BundleEvent.STARTED, buA),
                new BundleEvent(BundleEvent.STARTED, buC),
                new BundleEvent(BundleEvent.STARTED, buB)
              });
      assertTrue("Bundle A, C, B should start", pass);

      buD = null;
      try {
        buD = Util.installBundle(bc, "bundleSLD_test-1.0.0.jar");
        sl.setBundleStartLevel(buD, baseLevel + 15);
        buD.start();
        assertTrue("BundleD should be ACTIVE", buD.getState() == Bundle.ACTIVE);
      } catch (Exception e) {
        out.println("Unexpected exception: " + e);
        e.printStackTrace();
        fail("start level test bundle " + e + " :STARTLVL100A:FAIL");
      }

      syncBListen.clearEvents();

      Util.updateBundle(bc, buC, "bundleSLC_test_api-1.0.0.jar");

      // Check BundleEvent stop/start C
      pass =
          syncBListen.checkEvents(
              new BundleEvent[] {
                new BundleEvent(BundleEvent.STOPPED, buC),
                new BundleEvent(BundleEvent.STARTED, buC),
              });
      assertTrue("Bundle C should stop and start", pass);

      syncBListen.clearEvents();

      pa.refreshPackages(new Bundle[] {buA, buB, buC, buD});

      // Check BundleEvent stop order B, C, D, A
      // Check BundleEvent start order A, D, C, B
      pass =
          syncBListen.checkEvents(
              new BundleEvent[] {
                new BundleEvent(BundleEvent.STOPPED, buB),
                new BundleEvent(BundleEvent.STOPPED, buC),
                new BundleEvent(BundleEvent.STOPPED, buD),
                new BundleEvent(BundleEvent.STOPPED, buA),
                new BundleEvent(BundleEvent.STARTED, buA),
                new BundleEvent(BundleEvent.STARTED, buD),
                new BundleEvent(BundleEvent.STARTED, buC),
                new BundleEvent(BundleEvent.STARTED, buB)
              });
      assertTrue("Bundle B, C, D, A should stop and start in reverse", pass);

      buA.uninstall();
      buA = null;
      buB.uninstall();
      buB = null;
      buC.uninstall();
      buC = null;
      buD.uninstall();
      buD = null;

      out.println("### start level test bundle :STARTLVL100A:PASS");
    }
예제 #11
0
  /**
   * Reads the configuration file and initializes the project properties. The file is located in the
   * project home directory.
   *
   * @param prop property file extension
   */
  protected synchronized void read(final String prop) {
    file = new IOFile(HOME + IO.BASEXSUFFIX + prop);

    final StringList read = new StringList();
    final TokenBuilder err = new TokenBuilder();
    if (!file.exists()) {
      err.addExt("Saving properties in \"%\"..." + NL, file);
    } else {
      BufferedReader br = null;
      try {
        br = new BufferedReader(new FileReader(file.file()));
        for (String line; (line = br.readLine()) != null; ) {
          line = line.trim();
          if (line.isEmpty() || line.charAt(0) == '#') continue;
          final int d = line.indexOf('=');
          if (d < 0) {
            err.addExt("%: \"%\" ignored. " + NL, file, line);
            continue;
          }

          final String val = line.substring(d + 1).trim();
          String key = line.substring(0, d).trim();

          // extract numeric value in key
          int num = 0;
          final int ss = key.length();
          for (int s = 0; s < ss; ++s) {
            if (Character.isDigit(key.charAt(s))) {
              num = Integer.parseInt(key.substring(s));
              key = key.substring(0, s);
              break;
            }
          }
          read.add(key);

          final Object entry = props.get(key);
          if (entry == null) {
            err.addExt("%: \"%\" not found. " + NL, file, key);
          } else if (entry instanceof String) {
            props.put(key, val);
          } else if (entry instanceof Integer) {
            props.put(key, Integer.parseInt(val));
          } else if (entry instanceof Boolean) {
            props.put(key, Boolean.parseBoolean(val));
          } else if (entry instanceof String[]) {
            if (num == 0) {
              props.put(key, new String[Integer.parseInt(val)]);
            } else {
              ((String[]) entry)[num - 1] = val;
            }
          } else if (entry instanceof int[]) {
            ((int[]) entry)[num] = Integer.parseInt(val);
          }
        }
      } catch (final Exception ex) {
        err.addExt("% could not be parsed." + NL, file);
        Util.debug(ex);
      } finally {
        if (br != null)
          try {
            br.close();
          } catch (final IOException ex) {
          }
      }
    }

    // check if all mandatory files have been read
    try {
      if (err.isEmpty()) {
        boolean ok = true;
        for (final Field f : getClass().getFields()) {
          final Object obj = f.get(null);
          if (!(obj instanceof Object[])) continue;
          final String key = ((Object[]) obj)[0].toString();
          ok &= read.contains(key);
        }
        if (!ok) err.addExt("Saving properties in \"%\"..." + NL, file);
      }
    } catch (final IllegalAccessException ex) {
      Util.notexpected(ex);
    }

    if (!err.isEmpty()) {
      Util.err(err.toString());
      write();
    }
  }
예제 #12
0
 /**
  * Returns an error string for an unknown key.
  *
  * @param key key
  * @return error string
  */
 public final synchronized String unknown(final String key) {
   final String sim = similar(key);
   return Util.info(sim != null ? Text.UNKNOWN_OPT_SIMILAR_X_X : Text.UNKNOWN_OPTION_X, key, sim);
 }
예제 #13
0
  /** Writes the properties to disk. */
  public final synchronized void write() {
    final StringBuilder user = new StringBuilder();
    BufferedReader br = null;
    try {
      // caches options specified by the user
      if (file.exists()) {
        br = new BufferedReader(new FileReader(file.file()));
        for (String line; (line = br.readLine()) != null; ) {
          if (line.equals(PROPUSER)) break;
        }
        for (String line; (line = br.readLine()) != null; ) {
          user.append(line).append(NL);
        }
      }
    } catch (final Exception ex) {
      Util.debug(ex);
    } finally {
      if (br != null)
        try {
          br.close();
        } catch (final IOException e) {
        }
    }

    BufferedWriter bw = null;
    try {
      bw = new BufferedWriter(new FileWriter(file.file()));
      bw.write(PROPHEADER + NL);

      for (final Field f : getClass().getFields()) {
        final Object obj = f.get(null);
        if (!(obj instanceof Object[])) continue;
        final String key = ((Object[]) obj)[0].toString();

        final Object val = props.get(key);
        if (val instanceof String[]) {
          final String[] str = (String[]) val;
          bw.write(key + " = " + str.length + NL);
          final int is = str.length;
          for (int i = 0; i < is; ++i) {
            if (str[i] != null) bw.write(key + (i + 1) + " = " + str[i] + NL);
          }
        } else if (val instanceof int[]) {
          final int[] num = (int[]) val;
          final int ns = num.length;
          for (int i = 0; i < ns; ++i) {
            bw.write(key + i + " = " + num[i] + NL);
          }
        } else {
          bw.write(key + " = " + val + NL);
        }
      }
      bw.write(NL + PROPUSER + NL);
      bw.write(user.toString());
    } catch (final Exception ex) {
      Util.errln("% could not be written.", file);
      Util.debug(ex);
    } finally {
      if (bw != null)
        try {
          bw.close();
        } catch (final IOException e) {
        }
    }
  }