Ejemplo n.º 1
0
  /* Check that all descriptors have been returned */
  private static void checkDescriptors(
      ModelMBeanInfo modelMBeanInfo, Descriptor[] descriptors, String string) {
    int errCount = 0;
    final ArrayList<Descriptor> list = new ArrayList<Descriptor>(descriptors.length);
    list.addAll(Arrays.asList(descriptors));
    System.out.println("Got " + list.size() + " descriptors for " + string);

    // checks that MBean's descriptor is returned.
    //
    final Descriptor mbd = ((MBeanInfo) modelMBeanInfo).getDescriptor();
    if (!mbd.equals(remove(list, mbd))) {
      System.err.println("modelMBeanInfo.getDescriptor(): not found");
      errCount++;
    }

    // checks that MBean's attributes descriptors are returned.
    //
    final MBeanAttributeInfo[] attrs = modelMBeanInfo.getAttributes();
    for (MBeanAttributeInfo att : attrs) {
      final Descriptor ad = att.getDescriptor();
      final String name = att.getName();
      if (!ad.equals(remove(list, ad))) {
        System.err.println("attInfo.getDescriptor(): not found for " + name);
        errCount++;
      }
    }

    // checks that MBean's operations descriptors are returned.
    //
    final MBeanOperationInfo[] ops = modelMBeanInfo.getOperations();
    for (MBeanOperationInfo op : ops) {
      final Descriptor od = op.getDescriptor();
      final String name = op.getName();
      if (!od.equals(remove(list, od))) {
        System.err.println("opInfo.getDescriptor(): not found for " + name);
        errCount++;
      }
    }

    // checks that MBean's notifications descriptors are returned.
    //
    final MBeanNotificationInfo[] ntfs = modelMBeanInfo.getNotifications();
    for (MBeanNotificationInfo ntf : ntfs) {
      final Descriptor nd = ntf.getDescriptor();
      final String name = ntf.getName();
      if (!nd.equals(remove(list, nd))) {
        System.err.println("notifInfo.getDescriptor(): not found for " + name);
        errCount++;
      }
    }
    if (errCount > 0) {
      throw new RuntimeException(string + ": failed with " + errCount + " errors");
    } else if (list.size() != 0) {
      // Check that there are no additional descriptors
      //
      throw new RuntimeException(string + ": Unexpected remaining descriptors: " + list);
    } else System.out.println(string + ": PASSED");
  }
Ejemplo n.º 2
0
 static Method[] getOverridableMethods(Class c) {
   ArrayList<Method> list = new ArrayList<Method>();
   HashSet<String> skip = new HashSet<String>();
   while (c != null) {
     Method[] methods = c.getDeclaredMethods();
     for (int i = 0; i < methods.length; i++) {
       String methodKey =
           methods[i].getName() + getMethodSignature(methods[i], methods[i].getParameterTypes());
       if (skip.contains(methodKey)) continue; // skip this method
       int mods = methods[i].getModifiers();
       if (Modifier.isStatic(mods)) continue;
       if (Modifier.isFinal(mods)) {
         // Make sure we don't add a final method to the list
         // of overridable methods.
         skip.add(methodKey);
         continue;
       }
       if (Modifier.isPublic(mods) || Modifier.isProtected(mods)) {
         list.add(methods[i]);
         skip.add(methodKey);
       }
     }
     c = c.getSuperclass();
   }
   return list.toArray(new Method[list.size()]);
 }
Ejemplo n.º 3
0
  public void removePhaseListener(PhaseListener listener) {
    if (listener == null) throw new NullPointerException();

    synchronized (_phaseList) {
      _phaseList.remove(listener);
      _phaseListeners = new PhaseListener[_phaseList.size()];
      _phaseList.toArray(_phaseListeners);
    }
  }
Ejemplo n.º 4
0
 private static Field[] getAllFields(Class cls) {
   ArrayList<Field> res = new ArrayList<>();
   Class c = cls;
   while (c != View.class) {
     assert Utils.check(c != null);
     res.addAll(Arrays.asList(c.getDeclaredFields()));
     c = c.getSuperclass();
   }
   return res.toArray(new Field[res.size()]);
 }
Ejemplo n.º 5
0
  @Override
  Object decodeArray(Decoder r) throws Exception {
    ArrayList<Object> list = new ArrayList<Object>();
    r.codec.parseArray(list, componentType, r);
    Object array = Array.newInstance(r.codec.getRawClass(componentType), list.size());
    int n = 0;
    for (Object o : list) Array.set(array, n++, o);

    return array;
  }
Ejemplo n.º 6
0
  String constructDN(final T o, final String parentDN, final Map<String, Attribute> attrMap)
      throws LDAPPersistException {
    final String existingDN = getEntryDN(o);
    if (existingDN != null) {
      return existingDN;
    }

    final ArrayList<String> rdnNameList = new ArrayList<String>(1);
    final ArrayList<byte[]> rdnValueList = new ArrayList<byte[]>(1);
    for (final FieldInfo i : rdnFields) {
      final Attribute a = attrMap.get(toLowerCase(i.getAttributeName()));
      if (a == null) {
        throw new LDAPPersistException(
            ERR_OBJECT_HANDLER_RDN_FIELD_MISSING_VALUE.get(type.getName(), i.getField().getName()));
      }

      rdnNameList.add(a.getName());
      rdnValueList.add(a.getValueByteArray());
    }

    for (final GetterInfo i : rdnGetters) {
      final Attribute a = attrMap.get(toLowerCase(i.getAttributeName()));
      if (a == null) {
        throw new LDAPPersistException(
            ERR_OBJECT_HANDLER_RDN_GETTER_MISSING_VALUE.get(
                type.getName(), i.getMethod().getName()));
      }

      rdnNameList.add(a.getName());
      rdnValueList.add(a.getValueByteArray());
    }

    final String[] rdnNames = new String[rdnNameList.size()];
    rdnNameList.toArray(rdnNames);

    final byte[][] rdnValues = new byte[rdnNames.length][];
    rdnValueList.toArray(rdnValues);

    final RDN rdn = new RDN(rdnNames, rdnValues);

    if (parentDN == null) {
      return new DN(rdn, defaultParentDN).toString();
    } else {
      try {
        final DN parsedParentDN = new DN(parentDN);
        return new DN(rdn, parsedParentDN).toString();
      } catch (LDAPException le) {
        debugException(le);
        throw new LDAPPersistException(
            ERR_OBJECT_HANDLER_INVALID_PARENT_DN.get(type.getName(), parentDN, le.getMessage()),
            le);
      }
    }
  }
Ejemplo n.º 7
0
  // Expand grid search related argument sets
  @Override
  protected NanoHTTPD.Response serveGrid(NanoHTTPD server, Properties parms, RequestType type) {
    String[][] values = new String[_arguments.size()][];
    boolean gridSearch = false;
    for (int i = 0; i < _arguments.size(); i++) {
      Argument arg = _arguments.get(i);
      if (arg._gridable) {
        String value = _parms.getProperty(arg._name);
        if (value != null) {
          // Skips grid if argument is an array, except if imbricated expression
          // Little hackish, waiting for real language
          boolean imbricated = value.contains("(");
          if (!arg._field.getType().isArray() || imbricated) {
            values[i] = split(value);
            if (values[i] != null && values[i].length > 1) gridSearch = true;
          } else if (arg._field.getType().isArray()
              && !imbricated) { // Copy values which are arrays
            values[i] = new String[] {value};
          }
        }
      }
    }
    if (!gridSearch) return superServeGrid(server, parms, type);

    // Ignore destination key so that each job gets its own
    _parms.remove("destination_key");
    for (int i = 0; i < _arguments.size(); i++)
      if (_arguments.get(i)._name.equals("destination_key")) values[i] = null;

    // Iterate over all argument combinations
    int[] counters = new int[values.length];
    ArrayList<Job> jobs = new ArrayList<Job>();
    for (; ; ) {
      Job job = (Job) create(_parms);
      Properties combination = new Properties();
      for (int i = 0; i < values.length; i++) {
        if (values[i] != null) {
          String value = values[i][counters[i]];
          value = value.trim();
          combination.setProperty(_arguments.get(i)._name, value);
          _arguments.get(i).reset();
          _arguments.get(i).check(job, value);
        }
      }
      job._parms = combination;
      jobs.add(job);
      if (!increment(counters, values)) break;
    }
    GridSearch grid = new GridSearch();
    grid.jobs = jobs.toArray(new Job[jobs.size()]);
    return grid.superServeGrid(server, parms, type);
  }
Ejemplo n.º 8
0
 static Method[] getOverridableMethods(Class c) {
   ArrayList list = new ArrayList();
   while (c != null) {
     Method[] methods = c.getDeclaredMethods();
     for (int i = 0; i < methods.length; i++) {
       int mods = methods[i].getModifiers();
       if (Modifier.isStatic(mods) || Modifier.isFinal(mods)) continue;
       if (Modifier.isPublic(mods) || Modifier.isProtected(mods)) list.add(methods[i]);
     }
     c = c.getSuperclass();
   }
   return (Method[]) list.toArray(new Method[list.size()]);
 }
Ejemplo n.º 9
0
  public Document serialize(Object object, Document doc) {
    Class c = object.getClass();
    Integer id = getID(object);
    map.put(object, id);
    String mapSize = Integer.toString(map.size());

    // creating serialization objects
    Element objectElement = new Element("object");
    objectElement.setAttribute(new Attribute("class", c.getName()));
    objectElement.setAttribute(new Attribute("id", mapSize));
    doc.getRootElement().addContent(objectElement);

    if (!c.isArray()) // class is not an array
    {
      Field[] fields = c.getDeclaredFields();
      ArrayList<Element> fieldXML = serializeFields(fields, object, doc);
      for (int i = 0; i < fieldXML.size(); i++) {
        objectElement.addContent(fieldXML.get(i));
      }
    } else // class is an array
    {
      Object array = object;
      objectElement.setAttribute(new Attribute("length", Integer.toString(Array.getLength(array))));
      if (c.getComponentType().isPrimitive()) // class is array of primitives
      {
        for (int i = 0; i < Array.getLength(array); i++) {
          Element value = new Element("value");
          value.setText(Array.get(c, i).toString());
          objectElement.addContent(value);
        }
      } else // class is array of references
      {
        for (int j = 0; j < Array.getLength(array); j++) {
          Element ref = new Element("reference");
          id = getID(Array.get(c, j));
          if (id != -1) {
            ref.setText(Integer.toString(id));
          }
        }
        for (int k = 0; k < Array.getLength(array); k++) {
          serialize(Array.get(array, k), doc);
        }
      }
    }
    if (currentElement == 0) {
      referenceID = 0;
    }

    return doc;
  }
Ejemplo n.º 10
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;
  }
Ejemplo n.º 11
0
 static Method[] getOverridableMethods(Class<?> clazz) {
   ArrayList<Method> list = new ArrayList<Method>();
   HashSet<String> skip = new HashSet<String>();
   // Check superclasses before interfaces so we always choose
   // implemented methods over abstract ones, even if a subclass
   // re-implements an interface already implemented in a superclass
   // (e.g. java.util.ArrayList)
   for (Class<?> c = clazz; c != null; c = c.getSuperclass()) {
     appendOverridableMethods(c, list, skip);
   }
   for (Class<?> c = clazz; c != null; c = c.getSuperclass()) {
     for (Class<?> intf : c.getInterfaces()) appendOverridableMethods(intf, list, skip);
   }
   return list.toArray(new Method[list.size()]);
 }
Ejemplo n.º 12
0
  /** Splits into */
  public static String[] split(String input, String delimiters) {
    if (input == null || input.equals("")) {
      return new String[] {""};
    }

    if (delimiters == null || delimiters.equals("")) {
      return new String[] {input};
    }

    StringTokenizer tokenizer = new StringTokenizer(input, delimiters);
    ArrayList<String> values = new ArrayList<String>();

    while (tokenizer.hasMoreTokens()) values.add(tokenizer.nextToken());

    String[] array = new String[values.size()];

    return values.toArray(array);
  }
Ejemplo n.º 13
0
  /**
   * 描画用オブジェクト情報を作成する
   *
   * @param mqoMats MQOファイルから読み込んだマテリアル情報配列
   * @param mqoObjs MQOファイルのオブジェクト情報
   * @return 描画用オブジェクト情報
   */
  private GLObject makeObjs(GL10 gl, material mqoMats[], objects mqoObjs) {
    GLObject ret = null;
    ArrayList<GLMaterial> mats = new ArrayList<GLMaterial>();
    GLMaterial mr;
    KGLPoint[] vn = null;
    vn = vNormal(mqoObjs);
    for (int m = 0; m < mqoMats.length; m++) {
      mr = makeMats(gl, mqoMats[m], m, mqoObjs, vn);
      if (mr != null) {
        mats.add(mr);
      }
    }
    if (mats.size() == 0) return null;
    ret = new GLObject();
    ret.name = mqoObjs.name;
    ret.mat = mats.toArray(new GLMaterial[0]);
    ret.isVisible = (mqoObjs.data.visible != 0);

    return ret;
  }
Ejemplo n.º 14
0
 protected synchronized Message receiveMessage() throws IOException {
   if (messageBuffer.size() > 0) {
     Message m = (Message) messageBuffer.get(0);
     messageBuffer.remove(0);
     return m;
   }
   try {
     InetSocketAddress remoteAddress = (InetSocketAddress) channel.receive(receiveBuffer);
     if (remoteAddress != null) {
       int len = receiveBuffer.position();
       receiveBuffer.rewind();
       receiveBuffer.get(buf, 0, len);
       try {
         IP address = IP.fromInetAddress(remoteAddress.getAddress());
         int port = remoteAddress.getPort();
         extractor.appendData(buf, 0, len, new SocketDescriptor(address, port));
         receiveBuffer.clear();
         extractor.updateAvailableMessages();
         return extractor.nextMessage();
       } catch (EOFException exc) {
         exc.printStackTrace();
         System.err.println(buf.length + ", " + len);
       } catch (InvocationTargetException exc) {
         exc.printStackTrace();
       } catch (IllegalAccessException exc) {
         exc.printStackTrace();
       } catch (InstantiationException exc) {
         exc.printStackTrace();
       } catch (IllegalArgumentException e) {
         e.printStackTrace();
       } catch (InvalidCompressionMethodException e) {
         e.printStackTrace();
       }
     }
   } catch (ClosedChannelException exc) {
     if (isKeepAlive()) {
       throw exc;
     }
   }
   return null;
 }
  /** Create a cached information about shallow size and reference fields for a given class. */
  private static ClassCache createCacheEntry(final Class<?> clazz) {
    ClassCache cachedInfo;
    long shallowInstanceSize = NUM_BYTES_OBJECT_HEADER;
    final ArrayList<Field> referenceFields = new ArrayList<Field>(32);
    for (Class<?> c = clazz; c != null; c = c.getSuperclass()) {
      final Field[] fields = c.getDeclaredFields();
      for (final Field f : fields) {
        if (!Modifier.isStatic(f.getModifiers())) {
          shallowInstanceSize = adjustForField(shallowInstanceSize, f);

          if (!f.getType().isPrimitive()) {
            f.setAccessible(true);
            referenceFields.add(f);
          }
        }
      }
    }

    cachedInfo =
        new ClassCache(
            alignObjectSize(shallowInstanceSize),
            referenceFields.toArray(new Field[referenceFields.size()]));
    return cachedInfo;
  }
  /*
   * Non-recursive version of object descend. This consumes more memory than recursive in-depth
   * traversal but prevents stack overflows on long chains of objects
   * or complex graphs (a max. recursion depth on my machine was ~5000 objects linked in a chain
   * so not too much).
   */
  private static long measureObjectSize(Object root) {
    // Objects seen so far.
    final IdentityHashSet<Object> seen = new IdentityHashSet<Object>();
    // Class cache with reference Field and precalculated shallow size.
    final IdentityHashMap<Class<?>, ClassCache> classCache =
        new IdentityHashMap<Class<?>, ClassCache>();
    // Stack of objects pending traversal. Recursion caused stack overflows.
    final ArrayList<Object> stack = new ArrayList<Object>();
    stack.add(root);

    long totalSize = 0;
    while (!stack.isEmpty()) {
      final Object ob = stack.remove(stack.size() - 1);

      if (ob == null || seen.contains(ob)) {
        continue;
      }
      seen.add(ob);

      final Class<?> obClazz = ob.getClass();
      if (obClazz.isArray()) {
        /*
         * Consider an array, possibly of primitive types. Push any of its references to
         * the processing stack and accumulate this array's shallow size.
         */
        long size = NUM_BYTES_ARRAY_HEADER;
        final int len = Array.getLength(ob);
        if (len > 0) {
          Class<?> componentClazz = obClazz.getComponentType();
          if (componentClazz.isPrimitive()) {
            size += (long) len * primitiveSizes.get(componentClazz);
          } else {
            size += (long) NUM_BYTES_OBJECT_REF * len;

            // Push refs for traversal later.
            for (int i = len; --i >= 0; ) {
              final Object o = Array.get(ob, i);
              if (o != null && !seen.contains(o)) {
                stack.add(o);
              }
            }
          }
        }
        totalSize += alignObjectSize(size);
      } else {
        /*
         * Consider an object. Push any references it has to the processing stack
         * and accumulate this object's shallow size.
         */
        try {
          ClassCache cachedInfo = classCache.get(obClazz);
          if (cachedInfo == null) {
            classCache.put(obClazz, cachedInfo = createCacheEntry(obClazz));
          }

          for (Field f : cachedInfo.referenceFields) {
            // Fast path to eliminate redundancies.
            final Object o = f.get(ob);
            if (o != null && !seen.contains(o)) {
              stack.add(o);
            }
          }

          totalSize += cachedInfo.alignedShallowInstanceSize;
        } catch (IllegalAccessException e) {
          // this should never happen as we enabled setAccessible().
          throw new RuntimeException("Reflective field access failed?", e);
        }
      }
    }

    // Help the GC (?).
    seen.clear();
    stack.clear();
    classCache.clear();

    return totalSize;
  }
Ejemplo n.º 17
0
 /** Returns the number of properties discovered */
 public int numProperties() {
   if (auxillary != null) return auxillary.numProperties();
   return getMethods.size();
 }
Ejemplo n.º 18
0
  void generateProperties(
      boolean includeSuperclasses, boolean includeGetClass, boolean includeExtensions) {
    if (object != null && auxillary == null) {
      // generate the properties
      Class c = object.getClass();

      try {
        // handle integers
        if (object instanceof Long
            || object instanceof Integer
            || object instanceof Short
            || object instanceof Byte) {
          Method meth = c.getMethod("longValue", new Class[0]);
          getMethods.add(meth);
          setMethods.add(null);
          domMethods.add(null);
          hideMethods.add(null);
          desMethods.add(null);
          nameMethods.add(null);
        }

        // handle other kinds of numbers
        else if (object instanceof Number) {
          Method meth = c.getMethod("doubleValue", new Class[0]);
          getMethods.add(meth);
          setMethods.add(null);
          domMethods.add(null);
          hideMethods.add(null);
          desMethods.add(null);
          nameMethods.add(null);
        }

        // handle Booleans
        if (object instanceof Boolean) {
          Method meth = c.getMethod("booleanValue", new Class[0]);
          getMethods.add(meth);
          setMethods.add(null);
          domMethods.add(null);
          hideMethods.add(null);
          desMethods.add(null);
          nameMethods.add(null);
        }

        // handle Strings
        if (object instanceof CharSequence) {
          Method meth = c.getMethod("toString", new Class[0]);
          getMethods.add(meth);
          setMethods.add(null);
          domMethods.add(null);
          hideMethods.add(null);
          desMethods.add(null);
          nameMethods.add(null);
        }
      } catch (Exception e) // just in case of RuntimeExceptions
      {
        e.printStackTrace();
      }

      // handle general properties
      Method[] m = (includeSuperclasses ? c.getMethods() : c.getDeclaredMethods());
      for (int x = 0; x < m.length; x++) {
        try // we handle exceptions here by going to the next method and trying that one.
        {
          if (!("get".equals(m[x].getName()))
              && !("is".equals(m[x].getName()))
              && // "get()" and "is()" aren't properties
              (m[x].getName().startsWith("get")
                  || m[x].getName().startsWith("is"))) // corrrect syntax?
          {
            int modifier = m[x].getModifiers();
            if ((includeGetClass || !m[x].getName().equals("getClass"))
                && m[x].getParameterTypes().length == 0
                && Modifier.isPublic(modifier)) // no arguments, and public, non-abstract?
            {
              //// Add all properties...
              Class returnType = m[x].getReturnType();
              if (returnType != Void.TYPE) {
                getMethods.add(m[x]);
                setMethods.add(getWriteProperty(m[x], c));
                domMethods.add(getDomain(m[x], c, includeExtensions));
                hideMethods.add(getHidden(m[x], c, includeExtensions));
                desMethods.add(getDescription(m[x], c, includeExtensions));
                nameMethods.add(getName(m[x], c, includeExtensions));

                // simple check for invalid Interval domains
                int lastIndex = domMethods.size() - 1;
                Object domain = getDomain(lastIndex);
                if (returnType == Float.TYPE || returnType == Double.TYPE) {
                  if (domain != null && domain instanceof Interval) {
                    Interval interval = (Interval) domain;
                    if (!interval.isDouble()) {
                      System.err.println(
                          "WARNING: Property is double or float valued, but the Interval provided for the property's domain is byte/short/integer/long valued: "
                              + getName(lastIndex)
                              + " on Object "
                              + object);
                      // get rid of the domain
                      domMethods.set(lastIndex, null);
                    }
                  }
                } else if (returnType == Byte.TYPE
                    || returnType == Short.TYPE
                    || returnType == Integer.TYPE
                    || returnType == Long.TYPE) {
                  if (domain != null && domain instanceof Interval) {
                    Interval interval = (Interval) domain;
                    if (interval.isDouble()) {
                      System.err.println(
                          "WARNING: Property is byte/short/integer/long valued, but the Interval provided for the property's domain is double or float valued: "
                              + getName(lastIndex)
                              + " on Object "
                              + object);
                      // get rid of the domain
                      domMethods.set(lastIndex, null);
                    }
                  }
                } else if (domain != null && domain instanceof Interval) {
                  System.err.println(
                      "WARNING: Property is not a basic number type, but an Interval was provided for the property's domain: "
                          + getName(lastIndex)
                          + " on Object "
                          + object);
                  // get rid of the domain
                  domMethods.set(lastIndex, null);
                }
              }
            }
          }
        } catch (Exception e1) {
          e1.printStackTrace(); // try again though
        }
      }
    }
  }
Ejemplo n.º 19
0
  /**
   * Returns whether the following token exists (using wildcards).
   *
   * @return result of check
   */
  private boolean moreWC() {
    final StringBuilder word = new StringBuilder();
    final int size = tokenList.size();
    boolean period = false, bs = false, more = false;

    for (; cpos < size; cpos++) {
      String cSrfc = tokenList.get(cpos).getSurface();
      final boolean cMark = tokenList.get(cpos).isMark();
      String nSrfc = null;
      boolean nMark = false;
      if (cpos < size - 1) {
        nSrfc = tokenList.get(cpos + 1).getSurface();
        nMark = tokenList.get(cpos + 1).isMark();
      }

      if (nSrfc != null) {
        if ("\\".equals(cSrfc)) bs = true;

        // delimiter
        if (cMark && !isFtChar(cSrfc) || "\\".equals(cSrfc) && nMark) {
          period = false;
          bs = false;
          if (word.length() != 0) {
            more = true;
            break;
          }
          if ("\\".equals(cSrfc) && nMark) cpos++;
          continue;
        }

        word.append(cSrfc);

        if (bs || "\\".equals(nSrfc)) {
          more = true;
          continue;
        }

        if (".".equals(cSrfc) || ".".equals(nSrfc)) {
          period = true;
          continue;
        }
        if (period) {
          if ("{".equals(cSrfc)) {
            cpos++;
            for (; cpos < size; cpos++) {
              cSrfc = tokenList.get(cpos).getSurface();
              word.append(cSrfc);
              if ("}".equals(cSrfc)) {
                more = true;
                break;
              }
            }
            cpos++;
            break;
          }
          continue;
        }
      } else {
        // last token.
        if (cMark) {
          if ("\\".equals(cSrfc)) continue;
          if (word.length() != 0) {
            word.append(cSrfc);
          }
          more = true;
          continue;
        }
      }

      if (period) {
        word.append(cSrfc);
      } else {
        if (bs)
          if (!isFtChar(cSrfc)) word.append(cSrfc);
          else word.setLength(0);
      }
      more = true;
      cpos++;
      break;
    }
    if (more) {
      currToken =
          word.length() == 0
              ? tokenList.get(cpos - 1)
              : new Morpheme(word.toString(), MEISHI_FEATURE);
    }
    return more;
  }
Ejemplo n.º 20
0
  /**
   * 描画用マテリアル情報をMQOデータから作成
   *
   * @param mqomat MQOファイルから読み込んだマテリアル情報
   * @param i_mqomat MQOファイルのマテリアル番号
   * @param mqoObjs MQOファイルのオブジェクト情報
   * @param vn 頂点法線配列
   * @return 描画用マテリアル情報
   */
  private GLMaterial makeMats(
      GL10 gl, material mqomat, int i_mqomat, objects mqoObjs, KGLPoint[] vn) {
    GLMaterial ret = new GLMaterial();
    ArrayList<KGLPoint> apv = new ArrayList<KGLPoint>();
    ArrayList<KGLPoint> apn = new ArrayList<KGLPoint>();
    ArrayList<KGLPoint> apuv = new ArrayList<KGLPoint>();
    ArrayList<KGLPoint> apc = new ArrayList<KGLPoint>();
    KGLPoint wpoint = null;
    boolean uvValid = false;
    boolean colValid = false;
    KGLPoint fn;
    float s;
    for (int f = 0; f < mqoObjs.face.length; f++) {
      if (mqoObjs.face[f].M == null) {
        continue;
      }
      if (mqoObjs.face[f].M != i_mqomat) continue;

      fn =
          calcNormal(
              mqoObjs.vertex, mqoObjs.face[f].V[0], mqoObjs.face[f].V[1], mqoObjs.face[f].V[2]);
      for (int v = 0; v < 3; v++) {
        apv.add(mqoObjs.vertex[mqoObjs.face[f].V[v]]);
        // apv.add(new KGLPoint(mqoObjs.vertex[mqoObjs.face[f].V[v]])) ;
        s =
            (float)
                Math.acos(
                    fn.X() * vn[mqoObjs.face[f].V[v]].X()
                        + fn.Y() * vn[mqoObjs.face[f].V[v]].Y()
                        + fn.Z() * vn[mqoObjs.face[f].V[v]].Z());
        if (mqoObjs.data.facet < s) {
          apn.add(fn);
        } else {
          apn.add(vn[mqoObjs.face[f].V[v]]);
        }
        wpoint = new KGLPoint(2);
        if (mqoObjs.face[f].UV == null) {
          wpoint.set_UV(0, 0);
        } else {
          wpoint.set_UV(mqoObjs.face[f].UV[v * 2 + 0], mqoObjs.face[f].UV[v * 2 + 1]);
          uvValid = true;
        }
        apuv.add(wpoint);
        wpoint = new KGLPoint(4);
        if (mqoObjs.face[f].COL == null) {
          if (mqomat.data.col == null) {
            wpoint.set_COLOR(1.0f, 1.0f, 1.0f, 1.0f);
          } else {
            wpoint.set_COLOR(
                mqomat.data.col[0], mqomat.data.col[1], mqomat.data.col[2], mqomat.data.col[3]);
          }
        } else {
          wpoint.set_COLOR(
              mqoObjs.face[f].COL[v * 4 + 0],
              mqoObjs.face[f].COL[v * 4 + 1],
              mqoObjs.face[f].COL[v * 4 + 2],
              mqoObjs.face[f].COL[v * 4 + 3]);
          colValid = true;
        }
        apc.add(wpoint);
      }
    }
    ret.texID = texPool.getGLTexture(gl, mqomat.data.tex, mqomat.data.aplane, false);
    // @@@ reload 用
    if (ret.texID != 0) {
      ret.texName = mqomat.data.tex;
      ret.alphaTexName = mqomat.data.aplane;
    } else {
      ret.texName = null;
      ret.alphaTexName = null;
    }

    if (apv.size() == 0) return null;
    uvValid &= (ret.texID != 0);
    ret.name = mqomat.name;
    // uvValid = false ;
    KGLPoint[] wfv = null;
    KGLPoint[] wfn = null;
    KGLPoint[] wft = null;
    KGLPoint[] wfc = null;
    wfv = apv.toArray(new KGLPoint[0]);
    wfn = apn.toArray(new KGLPoint[0]);
    wft = apuv.toArray(new KGLPoint[0]);
    wfc = apc.toArray(new KGLPoint[0]);
    ret.vertex_num = wfv.length;

    // @@@ interleaveFormat は無いので分ける
    ret.uvValid = uvValid;
    ret.colValid = colValid;

    ret.vertexBuffer = ByteBuffer.allocateDirect(ret.vertex_num * 3 * 4);
    ret.vertexBuffer.order(ByteOrder.nativeOrder());
    ret.vertexBuffer.position(0);

    ret.normalBuffer = ByteBuffer.allocateDirect(ret.vertex_num * 3 * 4);
    ret.normalBuffer.order(ByteOrder.nativeOrder());
    ret.normalBuffer.position(0);

    if (uvValid) {
      ret.uvBuffer = ByteBuffer.allocateDirect(ret.vertex_num * 2 * 4);
      ret.uvBuffer.order(ByteOrder.nativeOrder());
      ret.uvBuffer.position(0);
    }
    if (colValid) {
      ret.colBuffer = ByteBuffer.allocateDirect(ret.vertex_num * 4 * 4);
      ret.colBuffer.order(ByteOrder.nativeOrder());
      ret.colBuffer.position(0);
    }

    // Log.i("KGLMetaseq", "vertex_num: "+ ret.vertex_num);

    for (int v = 0; v < ret.vertex_num; v++) {
      ret.vertexBuffer.putFloat(wfv[v].X());
      ret.vertexBuffer.putFloat(wfv[v].Y());
      ret.vertexBuffer.putFloat(wfv[v].Z());

      ret.normalBuffer.putFloat(wfn[v].X());
      ret.normalBuffer.putFloat(wfn[v].Y());
      ret.normalBuffer.putFloat(wfn[v].Z());

      if (uvValid) {
        ret.uvBuffer.putFloat(wft[v].U());
        ret.uvBuffer.putFloat(wft[v].V());
      }
      if (colValid) {
        ret.colBuffer.putFloat(wfc[v].R());
        ret.colBuffer.putFloat(wfc[v].G());
        ret.colBuffer.putFloat(wfc[v].B());
        ret.colBuffer.putFloat(wfc[v].A());
      }
    }
    if (mqomat.data.col != null) {
      ret.color = new float[mqomat.data.col.length];
      for (int c = 0; c < mqomat.data.col.length; c++) {
        ret.color[c] = mqomat.data.col[c];
      }
      if (mqomat.data.dif != null) {
        ret.dif = new float[mqomat.data.col.length];
        for (int c = 0; c < mqomat.data.col.length; c++) {
          ret.dif[c] = mqomat.data.dif * mqomat.data.col[c];
        }
        // KEICHECK difでアルファ値を1未満にすると透明度が変化する?
        ret.dif[3] = mqomat.data.col[3];
      }
      if (mqomat.data.amb != null) {
        ret.amb = new float[mqomat.data.col.length];
        for (int c = 0; c < mqomat.data.col.length; c++) {
          ret.amb[c] = mqomat.data.amb * mqomat.data.col[c];
        }
      }
      if (mqomat.data.emi != null) {
        ret.emi = new float[mqomat.data.col.length];
        for (int c = 0; c < mqomat.data.col.length; c++) {
          ret.emi[c] = mqomat.data.emi * mqomat.data.col[c];
        }
      }
      if (mqomat.data.spc != null) {
        ret.spc = new float[mqomat.data.col.length];
        for (int c = 0; c < mqomat.data.col.length; c++) {
          ret.spc[c] = mqomat.data.spc * mqomat.data.col[c];
        }
      }
    }
    if (mqomat.data.pow != null) {
      ret.power = new float[1];
      ret.power[0] = mqomat.data.pow;
    }
    ret.shadeMode_IsSmooth = true; // defaultはtrue
    if (mqoObjs.data.shading == 0) ret.shadeMode_IsSmooth = false;

    return ret;
  }
Ejemplo n.º 21
0
 /**
  * faceチャンクの読み込み
  *
  * @param br 読み込みストリーム
  * @return 面配列
  * @throws Exception
  */
 private Face[] readFace(multiInput br) throws Exception {
   ArrayList<Face> qf;
   String line = null;
   String[] s;
   Integer Mn;
   Face[] wface = null;
   int p;
   int pe;
   qf = new ArrayList<Face>();
   try {
     while ((line = br.readLine()) != null) {
       if (line.length() <= 0) continue;
       line = line.trim();
       if (line.equals("}")) break;
       wface = null;
       Mn = null;
       p = line.indexOf("M(");
       if (p != -1) {
         pe = line.indexOf(")", p);
         Mn = Integer.parseInt(line.substring(p + 2, pe));
       }
       p = line.indexOf("V(");
       if (p == -1) continue;
       pe = line.indexOf(")", p);
       s = line.substring(p + 2, pe).split(" ");
       if (s.length == 3) {
         wface = new Face[1];
         wface[0] = new Face();
         wface[0].V = new Integer[3];
         wface[0].V[0] = Integer.parseInt(s[0]);
         wface[0].V[1] = Integer.parseInt(s[1]);
         wface[0].V[2] = Integer.parseInt(s[2]);
         wface[0].M = Mn;
         p = line.indexOf("UV(");
         if (p != -1) {
           pe = line.indexOf(")", p);
           s = line.substring(p + 3, pe).split(" ");
           if (s.length != 2 * 3) throw new Exception("UVの数が不正");
           wface[0].UV = new Float[2 * 3];
           for (int i = 0; i < s.length; i++) {
             wface[0].UV[i] = Float.parseFloat(s[i]);
           }
         }
         p = line.indexOf("COL(");
         if (p != -1) {
           pe = line.indexOf(")", p);
           s = line.substring(p + 4, pe).split(" ");
           if (s.length != 3) throw new Exception("COLの数が不正");
           wface[0].COL = new Float[4 * 3];
           long wl;
           float wf;
           for (int i = 0; i < s.length; i++) {
             wl = Long.parseLong(s[i]);
             wf = (wl >>> 0) & 0x000000ff;
             wface[0].COL[i * 4 + 0] = wf / 255f;
             wf = (wl >>> 8) & 0x000000ff;
             wface[0].COL[i * 4 + 1] = wf / 255f;
             wf = (wl >>> 16) & 0x000000ff;
             wface[0].COL[i * 4 + 2] = wf / 255f;
             wf = (wl >>> 24) & 0x000000ff;
             wface[0].COL[i * 4 + 3] = wf / 255f;
           }
         }
       }
       // 頂点配列はすべて三角にするので、四角は三角x2に分割
       // 0 3 0 0 3
       // □ → △ ▽
       // 1 2 1 2 2
       if (s.length == 4) {
         wface = new Face[2];
         wface[0] = new Face();
         wface[1] = new Face();
         wface[0].V = new Integer[3];
         wface[0].V[0] = Integer.parseInt(s[0]);
         wface[0].V[1] = Integer.parseInt(s[1]);
         wface[0].V[2] = Integer.parseInt(s[2]);
         wface[0].M = Mn;
         wface[1].V = new Integer[3];
         wface[1].V[0] = Integer.parseInt(s[0]);
         wface[1].V[1] = Integer.parseInt(s[2]);
         wface[1].V[2] = Integer.parseInt(s[3]);
         wface[1].M = Mn;
         p = line.indexOf("UV(");
         if (p != -1) {
           int uv_p;
           pe = line.indexOf(")", p);
           s = line.substring(p + 3, pe).split(" ");
           if (s.length != 2 * 4) throw new Exception("UVの数が不正");
           wface[0].UV = new Float[2 * 3];
           wface[1].UV = new Float[2 * 3];
           for (int i = 0; i < 2; i++) {
             uv_p = 0;
             for (int j = 0; j < 4; j++) {
               if (i == 0 && j == 3) continue;
               if (i == 1 && j == 1) continue;
               wface[i].UV[uv_p++] = Float.parseFloat(s[j * 2 + 0]);
               wface[i].UV[uv_p++] = Float.parseFloat(s[j * 2 + 1]);
             }
           }
         }
         p = line.indexOf("COL(");
         if (p != -1) {
           pe = line.indexOf(")", p);
           s = line.substring(p + 4, pe).split(" ");
           if (s.length != 4) throw new Exception("COLの数が不正");
           wface[0].COL = new Float[4 * 3];
           wface[1].COL = new Float[4 * 3];
           long wl;
           float wf;
           int col_p;
           for (int i = 0; i < 2; i++) {
             col_p = 0;
             for (int j = 0; j < s.length; j++) {
               if (i == 0 && j == 3) continue;
               if (i == 1 && j == 1) continue;
               wl = Long.parseLong(s[j]);
               wf = (wl >>> 0) & 0x000000ff;
               wface[i].COL[col_p * 4 + 0] = wf / 255f;
               wf = (wl >>> 8) & 0x000000ff;
               wface[i].COL[col_p * 4 + 1] = wf / 255f;
               wf = (wl >>> 16) & 0x000000ff;
               wface[i].COL[col_p * 4 + 2] = wf / 255f;
               wf = (wl >>> 24) & 0x000000ff;
               wface[i].COL[col_p * 4 + 3] = wf / 255f;
               col_p++;
             }
           }
         }
       }
       if (wface != null) {
         for (int i = 0; i < wface.length; i++) {
           qf.add(wface[i]);
         }
       }
     }
   } catch (Exception e) {
     Log.e("KGLMetaseq", "MQOファイル フォーマットエラー(Object>face)" + e.getMessage() + "[" + line + "]");
     throw e;
   }
   if (qf.size() == 0) return null;
   return qf.toArray(new Face[0]);
 }
Ejemplo n.º 22
0
  public Annotation[] getAnnotations() {
    Annotation[] annotations = new Annotation[_annotationList.size()];
    _annotationList.toArray(annotations);

    return annotations;
  }
Ejemplo n.º 23
0
  private Filter createFilter(final T o, final AtomicBoolean addedRequiredOrAllowed)
      throws LDAPPersistException {
    final ArrayList<Attribute> attrs = new ArrayList<Attribute>(5);
    attrs.add(objectClassAttribute);

    for (final FieldInfo i : requiredFilterFields) {
      final Attribute a = i.encode(o, true);
      if (a == null) {
        throw new LDAPPersistException(
            ERR_OBJECT_HANDLER_FILTER_MISSING_REQUIRED_FIELD.get(i.getField().getName()));
      } else {
        attrs.add(a);
        addedRequiredOrAllowed.set(true);
      }
    }

    for (final GetterInfo i : requiredFilterGetters) {
      final Attribute a = i.encode(o);
      if (a == null) {
        throw new LDAPPersistException(
            ERR_OBJECT_HANDLER_FILTER_MISSING_REQUIRED_GETTER.get(i.getMethod().getName()));
      } else {
        attrs.add(a);
        addedRequiredOrAllowed.set(true);
      }
    }

    for (final FieldInfo i : alwaysAllowedFilterFields) {
      final Attribute a = i.encode(o, true);
      if (a != null) {
        attrs.add(a);
        addedRequiredOrAllowed.set(true);
      }
    }

    for (final GetterInfo i : alwaysAllowedFilterGetters) {
      final Attribute a = i.encode(o);
      if (a != null) {
        attrs.add(a);
        addedRequiredOrAllowed.set(true);
      }
    }

    for (final FieldInfo i : conditionallyAllowedFilterFields) {
      final Attribute a = i.encode(o, true);
      if (a != null) {
        attrs.add(a);
      }
    }

    for (final GetterInfo i : conditionallyAllowedFilterGetters) {
      final Attribute a = i.encode(o);
      if (a != null) {
        attrs.add(a);
      }
    }

    final ArrayList<Filter> comps = new ArrayList<Filter>(attrs.size());
    for (final Attribute a : attrs) {
      for (final ASN1OctetString v : a.getRawValues()) {
        comps.add(Filter.createEqualityFilter(a.getName(), v.getValue()));
      }
    }

    if (superclassHandler != null) {
      final Filter f = superclassHandler.createFilter(o, addedRequiredOrAllowed);
      if (f.getFilterType() == Filter.FILTER_TYPE_AND) {
        comps.addAll(Arrays.asList(f.getComponents()));
      } else {
        comps.add(f);
      }
    }

    return Filter.createANDFilter(comps);
  }
Ejemplo n.º 24
0
  String[] getPluginDirectories() {

    ArrayList<String> directories = new ArrayList<String>();
    PackageManager pm = this.mAppContext.getPackageManager();
    List<ResolveInfo> plugins =
        pm.queryIntentServices(
            new Intent(PLUGIN_ACTION), PackageManager.GET_SERVICES | PackageManager.GET_META_DATA);

    synchronized (mPackageInfoCache) {

      // clear the list of existing packageInfo objects
      mPackageInfoCache.clear();

      for (ResolveInfo info : plugins) {

        // retrieve the plugin's service information
        ServiceInfo serviceInfo = info.serviceInfo;
        if (serviceInfo == null) {
          Log.w(LOGTAG, "Ignore bad plugin");
          continue;
        }

        Log.w(LOGTAG, "Loading plugin: " + serviceInfo.packageName);

        // retrieve information from the plugin's manifest
        PackageInfo pkgInfo;
        try {
          pkgInfo =
              pm.getPackageInfo(
                  serviceInfo.packageName,
                  PackageManager.GET_PERMISSIONS | PackageManager.GET_SIGNATURES);
        } catch (Exception e) {
          Log.w(LOGTAG, "Can't find plugin: " + serviceInfo.packageName);
          continue;
        }
        if (pkgInfo == null) {
          Log.w(
              LOGTAG,
              "Loading plugin: "
                  + serviceInfo.packageName
                  + ". Could not load package information.");
          continue;
        }

        /*
         * find the location of the plugin's shared library. The default
         * is to assume the app is either a user installed app or an
         * updated system app. In both of these cases the library is
         * stored in the app's data directory.
         */
        String directory = pkgInfo.applicationInfo.dataDir + "/lib";
        final int appFlags = pkgInfo.applicationInfo.flags;
        final int updatedSystemFlags =
            ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
        // preloaded system app with no user updates
        if ((appFlags & updatedSystemFlags) == ApplicationInfo.FLAG_SYSTEM) {
          directory = PLUGIN_SYSTEM_LIB + pkgInfo.packageName;
        }

        // check if the plugin has the required permissions
        String permissions[] = pkgInfo.requestedPermissions;
        if (permissions == null) {
          Log.w(
              LOGTAG,
              "Loading plugin: "
                  + serviceInfo.packageName
                  + ". Does not have required permission.");
          continue;
        }
        boolean permissionOk = false;
        for (String permit : permissions) {
          if (PLUGIN_PERMISSION.equals(permit)) {
            permissionOk = true;
            break;
          }
        }
        if (!permissionOk) {
          Log.w(
              LOGTAG,
              "Loading plugin: "
                  + serviceInfo.packageName
                  + ". Does not have required permission (2).");
          continue;
        }

        // check to ensure the plugin is properly signed
        Signature signatures[] = pkgInfo.signatures;
        if (signatures == null) {
          Log.w(LOGTAG, "Loading plugin: " + serviceInfo.packageName + ". Not signed.");
          continue;
        }

        // determine the type of plugin from the manifest
        if (serviceInfo.metaData == null) {
          Log.e(LOGTAG, "The plugin '" + serviceInfo.name + "' has no type defined");
          continue;
        }

        String pluginType = serviceInfo.metaData.getString(PLUGIN_TYPE);
        if (!TYPE_NATIVE.equals(pluginType)) {
          Log.e(LOGTAG, "Unrecognized plugin type: " + pluginType);
          continue;
        }

        try {
          Class<?> cls = getPluginClass(serviceInfo.packageName, serviceInfo.name);

          // TODO implement any requirements of the plugin class here!
          boolean classFound = true;

          if (!classFound) {
            Log.e(
                LOGTAG,
                "The plugin's class' "
                    + serviceInfo.name
                    + "' does not extend the appropriate class.");
            continue;
          }

        } catch (NameNotFoundException e) {
          Log.e(LOGTAG, "Can't find plugin: " + serviceInfo.packageName);
          continue;
        } catch (ClassNotFoundException e) {
          Log.e(LOGTAG, "Can't find plugin's class: " + serviceInfo.name);
          continue;
        }

        // if all checks have passed then make the plugin available
        mPackageInfoCache.add(pkgInfo);
        directories.add(directory);
      }
    }

    return directories.toArray(new String[directories.size()]);
  }
Ejemplo n.º 25
0
  public void deinit(Appendable out, boolean force) throws Exception {
    Settings settings = new Settings(platform.getConfigFile());

    if (!force) {
      Justif justify = new Justif(80, 40);
      StringBuilder sb = new StringBuilder();
      Formatter f = new Formatter(sb);

      try {
        String list = listFiles(platform.getGlobal());
        if (list != null) {
          f.format("In global default environment:%n");
          f.format(list);
        }

        list = listFiles(platform.getLocal());
        if (list != null) {
          f.format("In local default environment:%n");
          f.format(list);
        }

        if (settings.containsKey(JPM_CACHE_GLOBAL)) {
          list = listFiles(IO.getFile(settings.get(JPM_CACHE_GLOBAL)));
          if (list != null) {
            f.format("In global configured environment:%n");
            f.format(list);
          }
        }

        if (settings.containsKey(JPM_CACHE_LOCAL)) {
          list = listFiles(IO.getFile(settings.get(JPM_CACHE_LOCAL)));
          if (list != null) {
            f.format("In local configured environment:%n");
            f.format(list);
          }
        }

        list = listSupportFiles();
        if (list != null) {
          f.format("jpm support files:%n");
          f.format(list);
        }

        f.format("%n%n");

        f.format(
            "All files listed above will be deleted if deinit is run with the force flag set"
                + " (\"jpm deinit -f\" or \"jpm deinit --force\"%n%n");
        f.flush();

        justify.wrap(sb);
        out.append(sb.toString());
      } finally {
        f.close();
      }
    } else { // i.e. if(force)
      int count = 0;
      File[] caches = {platform.getGlobal(), platform.getLocal(), null, null};
      if (settings.containsKey(JPM_CACHE_LOCAL)) {
        caches[2] = IO.getFile(settings.get(JPM_CACHE_LOCAL));
      }
      if (settings.containsKey(JPM_CACHE_GLOBAL)) {
        caches[3] = IO.getFile(settings.get(JPM_CACHE_GLOBAL));
      }
      ArrayList<File> toDelete = new ArrayList<File>();

      for (File cache : caches) {
        if (cache == null || !cache.exists()) {
          continue;
        }
        listFiles(cache, toDelete);
        if (toDelete.size() > count) {
          count = toDelete.size();
          if (!cache.canWrite()) {
            reporter.error(PERMISSION_ERROR + " (" + cache + ")");
            return;
          }
          toDelete.add(cache);
        }
      }
      listSupportFiles(toDelete);

      for (File f : toDelete) {
        if (f.exists() && !f.canWrite()) {
          reporter.error(PERMISSION_ERROR + " (" + f + ")");
        }
      }
      if (reporter.getErrors().size() > 0) {
        return;
      }

      for (File f : toDelete) {
        if (f.exists()) {
          IO.deleteWithException(f);
        }
      }
    }
  }
  public String getPublicPropertiesForClasses(String classNames[]) {
    StringBuilder result = new StringBuilder();
    String className = null;
    ArrayList publicFields = new ArrayList();
    result.append("<classDefinitions>");
    if (classNames != null && classNames.length > 0) {
      for (int i = 0; i < classNames.length; i++) {
        className = classNames[i];
        if (className != null) {
          result.append("<classDefinition>");
          try {
            Class c = Class.forName(className);
            Field fields[] = c.getFields();
            Field field = null;
            if (fields != null) {
              for (int k = 0; k < fields.length; k++) {
                field = fields[k];
                if (field != null)
                  publicFields.add(
                      (new StringBuilder(String.valueOf(field.getName())))
                          .append(",")
                          .append(field.getType().getName())
                          .toString());
              }
            }
            try {
              BeanInfo b = Introspector.getBeanInfo(c);
              result.append(
                  (new StringBuilder("<classSimpleName>"))
                      .append(c.getSimpleName())
                      .append("</classSimpleName>")
                      .toString());
              result.append(
                  (new StringBuilder("<classFullName>"))
                      .append(c.getName())
                      .append("</classFullName>")
                      .toString());
              Package pack = c.getPackage();
              String packStr = "";
              if (pack != null) packStr = pack.getName();
              result.append(
                  (new StringBuilder("<packageName>"))
                      .append(packStr)
                      .append("</packageName>")
                      .toString());
              PropertyDescriptor pds[] = b.getPropertyDescriptors();
              if (pds != null) {
                for (int propCount = 0; propCount < pds.length; propCount++) {
                  PropertyDescriptor pd = pds[propCount];
                  String propertyName = pd.getName();
                  Method readMethod = pd.getReadMethod();
                  Method writeMethod = pd.getWriteMethod();
                  if (readMethod != null
                      && isPublicAccessor(readMethod.getModifiers())
                      && writeMethod != null
                      && isPublicAccessor(writeMethod.getModifiers()))
                    publicFields.add(
                        (new StringBuilder(String.valueOf(propertyName)))
                            .append(",")
                            .append(pd.getPropertyType().getName())
                            .toString());
                }
              }
            } catch (Exception e) {
              e.printStackTrace();
            }
            if (publicFields != null && publicFields.size() > 0) {
              String temp = null;
              result.append("<publicFields>");
              for (int counter = 0; counter < publicFields.size(); counter++) {
                temp = (String) publicFields.get(counter);
                if (temp != null) {
                  String pubTemp[] = temp.split(",");
                  if (pubTemp.length == 2) {
                    result.append("<publicField>");
                    result.append(
                        (new StringBuilder("<publicFieldName>"))
                            .append(pubTemp[0])
                            .append("</publicFieldName>")
                            .toString());
                    result.append(
                        (new StringBuilder("<publicFieldType>"))
                            .append(pubTemp[1])
                            .append("</publicFieldType>")
                            .toString());
                    result.append("</publicField>");
                  }
                }
              }

              result.append("</publicFields>");
            }
          } catch (ClassNotFoundException e) {
            result.append(
                (new StringBuilder("<classFullName>"))
                    .append(className)
                    .append("</classFullName>")
                    .toString());
            result.append(
                (new StringBuilder("<error>Problem retrieving "))
                    .append(className)
                    .append(" information</error>")
                    .toString());
            System.out.println(e.getMessage());
          }
          result.append("</classDefinition>");
        }
      }
    }
    result.append("</classDefinitions>");
    return result.toString();
  }
Ejemplo n.º 27
0
 // A helper method to check if a given position is dirty or not.
 private boolean isDirty(ArrayList<Integer> dirty, int position) {
   for (int k = 0; k < dirty.size(); k += 2)
     if (position > dirty.get(k) && position < dirty.get(k + 1)) return true;
   return false;
 }