Esempio n. 1
0
 // This is called client side.
 public List<ClientScreenModule> getClientScreenModules() {
   if (clientScreenModules == null) {
     needsServerData = false;
     clientScreenModules = new ArrayList<ClientScreenModule>();
     for (int i = 0; i < inventoryHelper.getCount(); i++) {
       ItemStack itemStack = inventoryHelper.getStackInSlot(i);
       if (itemStack != null && itemStack.getItem() instanceof ModuleProvider) {
         ModuleProvider moduleProvider = (ModuleProvider) itemStack.getItem();
         ClientScreenModule clientScreenModule;
         try {
           clientScreenModule = moduleProvider.getClientScreenModule().newInstance();
         } catch (InstantiationException e) {
           e.printStackTrace();
           continue;
         } catch (IllegalAccessException e) {
           e.printStackTrace();
           continue;
         }
         clientScreenModule.setupFromNBT(
             itemStack.getTagCompound(), worldObj.provider.dimensionId, xCoord, yCoord, zCoord);
         clientScreenModules.add(clientScreenModule);
         if (clientScreenModule.needsServerData()) {
           needsServerData = true;
         }
       } else {
         clientScreenModules.add(
             null); // To keep the indexing correct so that the modules correspond with there slot
                    // number.
       }
     }
   }
   return clientScreenModules;
 }
Esempio n. 2
0
  /**
   * Method to store the value under the specified key
   *
   * @param key Key to store the value under
   * @param value Object to store
   * @param listType Type of List implementation to use to store multivalues in
   * @param index Index into the list of values to place the new value
   * @return Previous object stored under this key
   */
  public Object put(Object key, Object value, Class listType, int index) {

    // Get the list of values for the key
    List values = (List) super.get(key);

    // If none found, create a new list
    if (values == null) {

      // Create the new instance type of List
      try {
        values = (List) listType.newInstance();
      } catch (IllegalAccessException eae) {
        eae.printStackTrace();
      } catch (InstantiationException inste) {
        inste.printStackTrace();
      }
    }

    // If the value doesn't already exist
    if (!values.contains(value)) {

      // If index is -1, then append to end
      if (index > -1) {
        values.add(index, value);
      } else {
        values.add(value);
      }
    }

    return super.put(key, values);
  }
  public Distribution<T> parse(String distrAsString) {
    DiscreteDistribution<T> dist = new DiscreteDistribution<T>();

    StringTokenizer tok = new StringTokenizer(distrAsString, ",");

    while (tok.hasMoreElements()) {
      String pair = tok.nextToken().trim();
      StringTokenizer sub = new StringTokenizer(pair, "/");

      try {
        T value = (T) domainType.getConstructor(String.class).newInstance(sub.nextToken().trim());
        Degree deg = (Degree) getDegreeStringConstructor().newInstance(sub.nextToken().trim());

        dist.put(value, deg);
      } catch (NoSuchMethodException nsme) {
        nsme.printStackTrace();
      } catch (IllegalAccessException iae) {
        iae.printStackTrace();
      } catch (InstantiationException ie) {
        ie.printStackTrace();
      } catch (InvocationTargetException ite) {
        ite.printStackTrace();
      }
    }
    return dist;
  }
  public void doArtefactConfiguration() {
    if (!pluginBean.isReadableProperty(ARTEFACTS)) {
      return;
    }

    List l = (List) plugin.getProperty(ARTEFACTS);
    for (Object artefact : l) {
      if (artefact instanceof Class) {
        Class artefactClass = (Class) artefact;
        if (ArtefactHandler.class.isAssignableFrom(artefactClass)) {
          try {
            application.registerArtefactHandler((ArtefactHandler) artefactClass.newInstance());
          } catch (InstantiationException e) {
            LOG.error("Cannot instantiate an Artefact Handler:" + e.getMessage(), e);
          } catch (IllegalAccessException e) {
            LOG.error(
                "The constructor of the Artefact Handler is not accessible:" + e.getMessage(), e);
          }
        } else {
          LOG.error("This class is not an ArtefactHandler:" + artefactClass.getName());
        }
      } else {
        if (artefact instanceof ArtefactHandler) {
          application.registerArtefactHandler((ArtefactHandler) artefact);
        } else {
          LOG.error(
              "This object is not an ArtefactHandler:"
                  + artefact
                  + "["
                  + artefact.getClass().getName()
                  + "]");
        }
      }
    }
  }
  /**
   * Creates the brain and launches if it is an agent. The brain class is given as a String. The
   * name argument is used to instantiate the name of the corresponding agent. If the gui flag is
   * true, a bean is created and associated to this agent.
   */
  public void makeBrain(String className, String name, boolean gui, String behaviorFileName) {
    try {
      Class c;
      // c = Class.forName(className);
      c = madkit.kernel.Utils.loadClass(className);
      myBrain = (Brain) c.newInstance();
      myBrain.setBody(this);
      if (myBrain instanceof AbstractAgent) {
        String n = name;
        if (n == null) {
          n = getLabel();
        }
        if (n == null) {
          n = getID();
        }
        if (behaviorFileName != null) setBehaviorFileName(behaviorFileName);
        getStructure().getAgent().doLaunchAgent((AbstractAgent) myBrain, n, gui);
      }

    } catch (ClassNotFoundException ev) {
      System.err.println("Class not found :" + className + " " + ev);
      ev.printStackTrace();
    } catch (InstantiationException e) {
      System.err.println("Can't instanciate ! " + className + " " + e);
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      System.err.println("illegal access! " + className + " " + e);
      e.printStackTrace();
    }
  }
Esempio n. 6
0
  /**
   * forward an execute request to a helper instance associated with the rule
   *
   * @param recipient the recipient of the method from which execution of this rule was triggered or
   *     null if it was a static method
   * @param args the arguments of the method from which execution of this rule was triggered
   */
  private void execute(Object recipient, Object[] args) throws ExecuteException {
    // type check and createHelperAdapter the rule now if it has not already been done

    if (ensureTypeCheckedCompiled()) {

      // create a helper and get it to execute the rule
      // eventually we will create a subclass of helper for each rule and createHelperAdapter
      // an implementation of execute from the rule source. for now we create a generic
      // helper and call the generic execute method which interprets the rule
      HelperAdapter helper;
      try {
        Constructor constructor = helperImplementationClass.getConstructor(Rule.class);
        helper = (HelperAdapter) constructor.newInstance(this);
        // helper = (RuleHelper)helperClass.newInstance();
        // helper.setRule(this);
        helper.execute(recipient, args);
      } catch (NoSuchMethodException e) {
        // should not happen!!!
        System.out.println(
            "cannot find constructor "
                + helperImplementationClass.getCanonicalName()
                + "(Rule) for helper class");
        e.printStackTrace(System.out);
        return;
      } catch (InvocationTargetException e) {
        e
            .printStackTrace(); // To change body of catch statement use File | Settings | File
                                // Templates.
      } catch (InstantiationException e) {
        // should not happen
        System.out.println(
            "cannot create instance of " + helperImplementationClass.getCanonicalName());
        e.printStackTrace(System.out);
        return;
      } catch (IllegalAccessException e) {
        // should not happen
        System.out.println("cannot access " + helperImplementationClass.getCanonicalName());
        e.printStackTrace(System.out);
        return;
      } catch (ClassCastException e) {
        // should not happen
        System.out.println("cast exception " + helperImplementationClass.getCanonicalName());
        e.printStackTrace(System.out);
        return;
      } catch (EarlyReturnException e) {
        throw e;
      } catch (ThrowException e) {
        throw e;
      } catch (ExecuteException e) {
        System.out.println(getName() + " : " + e);
        throw e;
      } catch (Throwable throwable) {
        System.out.println(getName() + " : " + throwable);
        throw new ExecuteException(getName() + "  : caught " + throwable, throwable);
      }
    }
  }
Esempio n. 7
0
 @SuppressWarnings("unchecked")
 public AbstractNetSystem() {
   super();
   try {
     this.marking = (M) Marking.class.newInstance();
     this.marking.setPetriNet(this);
   } catch (InstantiationException e) {
     e.printStackTrace();
   } catch (IllegalAccessException e) {
     e.printStackTrace();
   }
 }
 private Variation createInstance(String className) {
   try {
     return (Variation) Class.forName(className).newInstance();
   } catch (ClassNotFoundException e) {
     e.printStackTrace();
   } catch (InstantiationException e) {
     e.printStackTrace();
   } catch (IllegalAccessException e) {
     e.printStackTrace();
   }
   return null;
 }
Esempio n. 9
0
 void btnChangeServer_actionPerformed(ActionEvent e) {
   setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
   JID temp = null;
   try {
     temp = JID.checkedJIDFromString(txtServer.getText());
   } catch (InstantiationException ex) {
     nu.fw.jeti.util.Popups.errorPopup(ex.getMessage(), I18N.gettext("main.error.invalid_server"));
   }
   if (temp == null) return;
   server = temp;
   backend.getItems(server, this);
 }
Esempio n. 10
0
 public static Object newInstance(Class clazz) throws FacesException {
   try {
     return clazz.newInstance();
   } catch (NoClassDefFoundError e) {
     log.error("Class : " + clazz.getName() + " not found.", e);
     throw new FacesException(e);
   } catch (InstantiationException e) {
     log.error(e.getMessage(), e);
     throw new FacesException(e);
   } catch (IllegalAccessException e) {
     log.error(e.getMessage(), e);
     throw new FacesException(e);
   }
 }
Esempio n. 11
0
  /**
   * Examines a property's type to see which method should be used to parse the property's value.
   *
   * @param desc The description of the property
   * @param element The XML element containing the property value
   * @return The value stored in the element
   * @throws IOException If there is an error reading the document
   */
  public Object getObjectValue(PropertyDescriptor desc, Element element) throws IOException {
    // Find out what kind of property it is
    Class type = desc.getPropertyType();

    // If it's an array, get the base type
    if (type.isArray()) {
      type = type.getComponentType();
    }

    // For native types, object wrappers for natives, and strings, use the
    // basic parse routine
    if (type.equals(Integer.TYPE)
        || type.equals(Long.TYPE)
        || type.equals(Short.TYPE)
        || type.equals(Byte.TYPE)
        || type.equals(Boolean.TYPE)
        || type.equals(Float.TYPE)
        || type.equals(Double.TYPE)
        || Integer.class.isAssignableFrom(type)
        || Long.class.isAssignableFrom(type)
        || Short.class.isAssignableFrom(type)
        || Byte.class.isAssignableFrom(type)
        || Boolean.class.isAssignableFrom(type)
        || Float.class.isAssignableFrom(type)
        || Double.class.isAssignableFrom(type)
        || String.class.isAssignableFrom(type)) {
      return readBasicType(type, element);
    } else if (java.util.Date.class.isAssignableFrom(type)) {
      // If it's a date, use the date parser
      return readDate(element);
    } else {
      try {
        // If it's an object, create a new instance of the object (it should
        // be a bean, or there will be trouble)
        Object newOb = type.newInstance();

        // Copy the XML element into the bean
        readObject(newOb, element);

        return newOb;
      } catch (InstantiationException exc) {
        throw new IOException(
            "Error creating object for " + desc.getName() + ": " + exc.toString());
      } catch (IllegalAccessException exc) {
        throw new IOException(
            "Error creating object for " + desc.getName() + ": " + exc.toString());
      }
    }
  }
Esempio n. 12
0
 public E getE() {
   if (e == null) {
     // 这是使用泛型没有办法之举:ERROR InstantiatingNullHandler Could not create
     // and/or set value back on to object
     // at
     // com.opensymphony.xwork2.spring.SpringObjectFactory.buildBean(SpringObjectFactory.java:169)
     try {
       e = this.getEntityClass().newInstance();
     } catch (InstantiationException e) {
       e.printStackTrace();
     } catch (IllegalAccessException e) {
       e.printStackTrace();
     }
   }
   return e;
 }
Esempio n. 13
0
  @SuppressWarnings("unchecked")
  private <T> T clone(final T o, final Map<Object, Object> clones) throws IllegalAccessException {
    if (o == null) return null;
    if (ignoredInstances.containsKey(o)) return o;

    final Class<T> clz = (Class<T>) o.getClass();
    if (clz.isEnum()) return o;
    // skip cloning ignored classes
    if (ignored.contains(clz)) return o;
    final Object clonedPreviously = clones != null ? clones.get(o) : null;
    if (clonedPreviously != null) return (T) clonedPreviously;

    if (clz.isArray()) {
      final int length = Array.getLength(o);
      final T newInstance = (T) Array.newInstance(clz.getComponentType(), length);
      clones.put(o, newInstance);
      for (int i = 0; i < length; i++) {
        final Object v = Array.get(o, i);
        final Object clone = clones != null ? clone(v, clones) : v;
        Array.set(newInstance, i, clone);
      }
      return newInstance;
    }

    T newInstance = null;
    try {
      newInstance = newInstance(clz);
    } catch (InstantiationException e) {
      e.printStackTrace();
    }
    if (clones != null) {
      clones.put(o, newInstance);
    }
    final List<Field> fields = allFields(clz);
    for (final Field field : fields) {
      if (!Modifier.isStatic(field.getModifiers())) {
        field.setAccessible(true);
        final Object fieldObject = field.get(o);
        final Object fieldObjectClone = clones != null ? clone(fieldObject, clones) : fieldObject;
        field.set(newInstance, fieldObjectClone);
      }
    }
    return newInstance;
  }
Esempio n. 14
0
  public static <T extends PaypalClassicResponseModel> T convertToAPIResponse(
      Map<String, String> mapdata, Class<T> clazz) {
    if (mapdata == null) {
      return null;
    }
    T paypalClassicResponseModel = null;

    try {
      paypalClassicResponseModel = mapToClazz(mapdata, clazz);
    } catch (InstantiationException e) {
      throw new ValidationException(e.getMessage());
    } catch (IllegalAccessException e) {
      throw new ValidationException(e.getMessage());
    } catch (InvocationTargetException e) {
      throw new ValidationException(e.getMessage());
    }

    return paypalClassicResponseModel;
  }
  /**
   * Creates an iterator that returns an {@link Options} containing each possible parameter set
   * defined by these {@link
   * com.biomatters.plugins.barcoding.validator.research.options.BatchOptions}. Note that the {@link
   * Options} object returned is always the same to save on initializing multiple copies. Each time
   * {@link java.util.Iterator#next()} is called the next parameter set is set on the {@link
   * Options}.
   *
   * @return An iterator that will iterate over all possible parameter sets specified by this {@link
   *     com.biomatters.plugins.barcoding.validator.research.options.BatchOptions}
   * @throws DocumentOperationException if there is a problem creating the {@link Options} object
   */
  public Iterator<T> iterator() throws DocumentOperationException {
    List<Set<OptionToSet>> possibleValues = new ArrayList<Set<OptionToSet>>();

    Map<String, MultiValueOption<?>> multiValueOptions = getMultiValueOptions("", options);
    for (Map.Entry<String, MultiValueOption<?>> entry : multiValueOptions.entrySet()) {
      possibleValues.add(getOptionsToSet(entry.getKey(), entry.getValue()));
    }
    Set<List<OptionToSet>> lists = Sets.cartesianProduct(possibleValues);
    final Iterator<List<OptionToSet>> possibilityIterator = lists.iterator();

    final T template;
    try {
      //noinspection unchecked
      template = (T) options.getClass().newInstance(); // getClass() doesn't return Class<T> :(
      template.valuesFromXML(options.valuesToXML(XMLSerializable.ROOT_ELEMENT_NAME));
    } catch (InstantiationException e) {
      throw new DocumentOperationException("Failed to create Options: " + e.getMessage(), e);
    } catch (IllegalAccessException e) {
      throw new DocumentOperationException("Failed to create Options: " + e.getMessage(), e);
    }

    return new Iterator<T>() {
      @Override
      public boolean hasNext() {
        return possibilityIterator.hasNext();
      }

      @Override
      public T next() {
        List<OptionToSet> possibility = possibilityIterator.next();
        for (OptionToSet optionToSet : possibility) {
          template.setValue(optionToSet.name, optionToSet.value);
        }
        return template;
      }

      @Override
      public void remove() {
        new UnsupportedOperationException();
      }
    };
  }
Esempio n. 16
0
 public List<Object> readExcel(Workbook wb, Class clz, int readLine, int tailLine) {
   Sheet sheet = wb.getSheetAt(0); // 取第一张表
   List<Object> objs = null;
   try {
     Row row = sheet.getRow(readLine); // 开始行,主题栏
     objs = new ArrayList<Object>();
     Map<Integer, String> maps = getHeaderMap(row, clz); // 设定对应的字段顺序与方法名
     if (maps == null || maps.size() <= 0)
       throw new RuntimeException("要读取的Excel的格式不正确,检查是否设定了合适的行"); // 与order顺序不符
     for (int i = readLine + 1; i <= sheet.getLastRowNum() - tailLine; i++) { // 取数据
       row = sheet.getRow(i);
       Object obj = clz.newInstance(); //   调用无参结构
       for (Cell c : row) {
         int ci = c.getColumnIndex();
         String mn = maps.get(ci).substring(3); // 消除get
         mn = mn.substring(0, 1).toLowerCase() + mn.substring(1);
         Map<String, Object> params = new HashMap<String, Object>();
         if (!"enterDate".equals(mn)) c.setCellType(Cell.CELL_TYPE_STRING); // 设置单元格格式
         else c.setCellType(Cell.CELL_TYPE_NUMERIC);
         if (this.getCellValue(c).trim().equals("是")) {
           BeanUtils.copyProperty(obj, mn, 1);
         } else if (this.getCellValue(c).trim().equals("否")) {
           BeanUtils.copyProperty(obj, mn, 0);
         } else BeanUtils.copyProperty(obj, mn, this.getCellValue(c));
       }
       objs.add(obj);
     }
   } catch (InstantiationException e) {
     e.printStackTrace();
     logger.error(e);
   } catch (IllegalAccessException e) {
     e.printStackTrace();
     logger.error(e);
   } catch (InvocationTargetException e) {
     e.printStackTrace();
     logger.error(e);
   } catch (NumberFormatException e) {
     e.printStackTrace();
     logger.error(e);
   }
   return objs;
 }
 // convenience method for invoking a constructor;
 // used as a central point for exception handling for Java reflection
 // constructor calls
 private <T> T invokeConstructor(
     Class<T> clazz, Class<?>[] argumentClasses, Object[] argumentObjects) {
   try {
     Constructor<T> constructor = clazz.getConstructor(argumentClasses);
     return constructor.newInstance(argumentObjects);
   } catch (IllegalArgumentException e) {
     e.printStackTrace();
   } catch (InstantiationException e) {
     e.printStackTrace();
   } catch (IllegalAccessException e) {
     e.printStackTrace();
   } catch (InvocationTargetException e) {
     e.printStackTrace();
   } catch (SecurityException e) {
     e.printStackTrace();
   } catch (NoSuchMethodException e) {
     e.printStackTrace();
   }
   return null;
 }
Esempio n. 18
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;
 }
Esempio n. 19
0
  // This is called server side.
  public List<ScreenModule> getScreenModules() {
    if (screenModules == null) {
      totalRfPerTick = 0;
      screenModules = new ArrayList<ScreenModule>();
      for (int i = 0; i < inventoryHelper.getCount(); i++) {
        ItemStack itemStack = inventoryHelper.getStackInSlot(i);
        if (itemStack != null && itemStack.getItem() instanceof ModuleProvider) {
          ModuleProvider moduleProvider = (ModuleProvider) itemStack.getItem();
          ScreenModule screenModule;
          try {
            screenModule = moduleProvider.getServerScreenModule().newInstance();
          } catch (InstantiationException e) {
            e.printStackTrace();
            continue;
          } catch (IllegalAccessException e) {
            e.printStackTrace();
            continue;
          }
          screenModule.setupFromNBT(
              itemStack.getTagCompound(), worldObj.provider.dimensionId, xCoord, yCoord, zCoord);
          screenModules.add(screenModule);
          totalRfPerTick += screenModule.getRfPerTick();

          if (screenModule instanceof ComputerScreenModule) {
            ComputerScreenModule computerScreenModule = (ComputerScreenModule) screenModule;
            String tag = computerScreenModule.getTag();
            if (!computerModules.containsKey(tag)) {
              computerModules.put(tag, new ArrayList<ComputerScreenModule>());
            }
            computerModules.get(tag).add(computerScreenModule);
          }
        } else {
          screenModules.add(
              null); // To keep the indexing correct so that the modules correspond with there slot
                     // number.
        }
      }
    }
    return screenModules;
  }
Esempio n. 20
0
 static Mod newModInstance(Class<? extends Mod> modClass) {
   Mod mod = null;
   try {
     mod =
         modClass
             .getConstructor(MinecraftVersion.class)
             .newInstance(MCPatcher.minecraft.getVersion());
   } catch (InstantiationException e) {
     e.printStackTrace();
   } catch (IllegalAccessException e) {
     e.printStackTrace();
   } catch (InvocationTargetException e) {
     e.printStackTrace();
   } catch (NoSuchMethodException e) {
     try {
       mod = modClass.newInstance();
     } catch (Exception e1) {
       e1.printStackTrace();
     }
   }
   return mod;
 }
Esempio n. 21
0
  /**
   * Return a new strategy (Design Pattern Abstract Factory)
   *
   * @return a new strategy
   */
  public static Strategy newStrategy() {
    Strategy strategy = null;
    Class stratClass;

    // FIXME: When you do a new Solution() it get an error because the strategies weren't
    // initialized before to do a newStrategy().
    if (allStrategies == null) {
      Hocli.initStrategies();
      setStrategy("FR");
    }
    stratClass = allStrategies.get(Hocli.strategyTag.toUpperCase());
    if (stratClass == null) {
      stopError("Hocli.newStrategy(Solution) : Unknown strategy class '" + Hocli.strategyTag + "'");
    }
    try {
      strategy = (Strategy) stratClass.newInstance();
    } catch (IllegalAccessException ex) {
      stopError(ex.getMessage());
    } catch (InstantiationException ex) {
      stopError(ex.getMessage());
    }
    return strategy;
  }
Esempio n. 22
0
  public RPGItem(ConfigurationSection s) {

    name = s.getString("name");
    id = s.getInt("id");
    setDisplay(s.getString("display"), false);
    setType(
        s.getString("type", Plugin.plugin.getConfig().getString("defaults.sword", "Sword")), false);
    setHand(
        s.getString("hand", Plugin.plugin.getConfig().getString("defaults.hand", "One handed")),
        false);
    setLore(s.getString("lore"), false);
    description = (List<String>) s.getList("description", new ArrayList<String>());
    for (int i = 0; i < description.size(); i++) {
      description.set(i, ChatColor.translateAlternateColorCodes('&', description.get(i)));
    }
    quality = Quality.valueOf(s.getString("quality"));
    damageMin = s.getInt("damageMin");
    damageMax = s.getInt("damageMax");
    armour = s.getInt("armour", 0);
    item = new ItemStack(Material.valueOf(s.getString("item")));
    ItemMeta meta = item.getItemMeta();
    if (meta instanceof LeatherArmorMeta) {
      ((LeatherArmorMeta) meta).setColor(Color.fromRGB(s.getInt("item_colour", 0)));
    } else {
      item.setDurability((short) s.getInt("item_data", 0));
    }
    for (String locale : Locale.getLocales()) {
      localeMeta.put(locale, meta.clone());
    }
    ignoreWorldGuard = s.getBoolean("ignoreWorldGuard", false);

    // Powers
    ConfigurationSection powerList = s.getConfigurationSection("powers");
    if (powerList != null) {
      for (String sectionKey : powerList.getKeys(false)) {
        ConfigurationSection section = powerList.getConfigurationSection(sectionKey);
        try {
          if (!Power.powers.containsKey(section.getString("powerName"))) {
            // Invalid power
            continue;
          }
          Power pow = Power.powers.get(section.getString("powerName")).newInstance();
          pow.init(section);
          pow.item = this;
          addPower(pow, false);
        } catch (InstantiationException e) {
          e.printStackTrace();
        } catch (IllegalAccessException e) {
          e.printStackTrace();
        }
      }
    }
    encodedID = getMCEncodedID(id);

    // Recipes
    hasRecipe = s.getBoolean("hasRecipe", false);
    if (hasRecipe) {
      recipe = (List<ItemStack>) s.getList("recipe");
    }

    ConfigurationSection drops = s.getConfigurationSection("dropChances");
    if (drops != null) {
      for (String key : drops.getKeys(false)) {
        double chance = drops.getDouble(key, 0.0);
        chance = Math.min(chance, 100.0);
        if (chance > 0) {
          dropChances.put(key, chance);
          if (!Events.drops.containsKey(key)) {
            Events.drops.put(key, new HashSet<Integer>());
          }
          Set<Integer> set = Events.drops.get(key);
          set.add(getID());
        } else {
          dropChances.remove(key);
          if (Events.drops.containsKey(key)) {
            Set<Integer> set = Events.drops.get(key);
            set.remove(getID());
          }
        }
        dropChances.put(key, chance);
      }
    }
    if (item.getType().getMaxDurability() != 0) {
      hasBar = true;
    }
    maxDurability = s.getInt("maxDurability", item.getType().getMaxDurability());
    forceBar = s.getBoolean("forceBar", false);

    if (maxDurability == 0) {
      maxDurability = -1;
    }

    rebuild();
  }
Esempio n. 23
0
  public ReverseFlashCard() {
    // basic init
    setTitle("WayMemo -Reverse Flash Card Mode");
    this.setSize(800, 600);
    paneCenter = new JPanel(new GridLayout(7, 1));

    add(ln, "North");
    add(paneCenter, "Center");
    add(b2, "West");
    add(bReset, "South");
    add(b1, "East");
    paneCenter.add(l1);
    paneCenter.add(l2);
    paneCenter.add(l3);
    paneCenter.add(l4);
    paneCenter.add(l5);
    paneCenter.add(b3);
    paneCenter.add(pMark);
    pMark.add(bMark);
    pMark.add(bUnMark);
    pMark.add(lt);

    // text area init

    Utility.initTextAreaView(l1);
    Utility.initTextAreaView(l2);
    Utility.initTextAreaView(l3);
    Utility.initTextAreaView(l4);
    Utility.initTextAreaView(l5);

    // action

    //
    Action actionNext =
        new AbstractAction() {
          public void actionPerformed(ActionEvent e) {
            num++;
            wordDisplay();
          }
        };
    b1.getInputMap().put(KeyStroke.getKeyStroke("C"), "pressed");
    b1.getActionMap().put("released", actionNext);
    //
    Action actionBack =
        new AbstractAction() {
          public void actionPerformed(ActionEvent e) {
            num--;
            wordDisplay();
          }
        };
    b2.getInputMap().put(KeyStroke.getKeyStroke("Z"), "pressed");
    b2.getActionMap().put("released", actionBack);
    //
    Action actionShow =
        new AbstractAction() {
          public void actionPerformed(ActionEvent e) {
            l1.setText(dtr[num]);
            l3.setText(d2[num]);
            l4.setText(d3[num]);
            l5.setText(d4[num]);
          }
        };
    b3.getInputMap().put(KeyStroke.getKeyStroke("X"), "pressed");
    b3.getActionMap().put("released", actionShow);
    //
    //
    Action actionMark =
        new AbstractAction() {
          public void actionPerformed(ActionEvent e) {
            d1[num] = "[MARKED*]" + d1[num];
            l2.setText(d1[num]);
          }
        };
    bMark.getInputMap().put(KeyStroke.getKeyStroke("S"), "pressed");
    bMark.getActionMap().put("released", actionMark);
    //
    //
    //
    Action actionUnmark =
        new AbstractAction() {
          public void actionPerformed(ActionEvent e) {
            d1[num] = od1[num];
            l2.setText(d1[num]);
          }
        };
    bUnMark.getInputMap().put(KeyStroke.getKeyStroke("F2"), "pressed");
    bUnMark.getActionMap().put("released", actionUnmark);
    //
    //
    Action actionReset =
        new AbstractAction() {
          public void actionPerformed(ActionEvent e) {
            num = 0;
            wordDisplay();
          }
        };
    bReset.getInputMap().put(KeyStroke.getKeyStroke("r"), "pressed");
    bReset.getActionMap().put("released", actionReset);
    //
    //
    b1.setMnemonic(KeyEvent.VK_C);
    b2.setMnemonic(KeyEvent.VK_Z);
    b3.setMnemonic(KeyEvent.VK_X);
    bMark.setMnemonic(KeyEvent.VK_S);
    bUnMark.setMnemonic(KeyEvent.VK_D);
    bReset.setMnemonic(KeyEvent.VK_R);

    b1.addActionListener(actionNext);
    b2.addActionListener(actionBack);
    b3.addActionListener(actionShow);
    bReset.addActionListener(actionReset);
    bMark.addActionListener(actionMark);
    bUnMark.addActionListener(actionUnmark);
    //
    //
    try {
      this.fileScan(new OpenFileDTR().getPathDTR());
    } catch (IOException e) {
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InstantiationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (UnsupportedLookAndFeelException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Esempio n. 24
0
  /**
   * An HTTP WebEvent handler that logs in a userLogin. This should run before the security check.
   *
   * @param request The HTTP request object for the current JSP or Servlet request.
   * @param response The HTTP response object for the current JSP or Servlet request.
   * @return Return a boolean which specifies whether or not the calling Servlet or JSP should
   *     generate its own content. This allows an event to override the default content.
   */
  public static String login(HttpServletRequest request, HttpServletResponse response) {

    Element rootElement = getRootElement(request);
    String result = "error";
    if (rootElement != null) {
      String className =
          UtilXml.childElementValue(
              rootElement,
              "AuthenticationHandler",
              "org.ofbiz.ldap.openldap.OFBizLdapAuthenticationHandler");
      try {
        Class<?> handlerClass = Class.forName(className);
        InterfaceOFBizAuthenticationHandler authenticationHandler =
            (InterfaceOFBizAuthenticationHandler) handlerClass.newInstance();
        result = authenticationHandler.login(request, response, rootElement);
      } catch (ClassNotFoundException e) {
        Debug.logError(e, "Error calling userLogin service", module);
        Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage());
        String errMsg =
            UtilProperties.getMessage(
                resourceWebapp,
                "loginevents.following_error_occurred_during_login",
                messageMap,
                UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
      } catch (InstantiationException e) {
        Debug.logError(e, "Error calling userLogin service", module);
        Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage());
        String errMsg =
            UtilProperties.getMessage(
                resourceWebapp,
                "loginevents.following_error_occurred_during_login",
                messageMap,
                UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
      } catch (IllegalAccessException e) {
        Debug.logError(e, "Error calling userLogin service", module);
        Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage());
        String errMsg =
            UtilProperties.getMessage(
                resourceWebapp,
                "loginevents.following_error_occurred_during_login",
                messageMap,
                UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
      } catch (NamingException e) {
        Debug.logError(e, "Error calling userLogin service", module);
        Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage());
        String errMsg =
            UtilProperties.getMessage(
                resourceWebapp,
                "loginevents.following_error_occurred_during_login",
                messageMap,
                UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
      } catch (Exception e) {
        Debug.logError(e, "Error calling userLogin service", module);
        Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage());
        String errMsg =
            UtilProperties.getMessage(
                resourceWebapp,
                "loginevents.following_error_occurred_during_login",
                messageMap,
                UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
      }
    }

    if (result.equals("error")) {
      boolean useOFBizLoginWhenFail =
          Boolean.getBoolean(
              UtilXml.childElementValue(rootElement, "UseOFBizLoginWhenLDAPFail", "false"));
      if (useOFBizLoginWhenFail) {
        return LoginWorker.login(request, response);
      }
    }
    return result;
  }
Esempio n. 25
0
  /**
   * An HTTP WebEvent handler that logs out a userLogin by clearing the session.
   *
   * @param request The HTTP request object for the current request.
   * @param response The HTTP response object for the current request.
   * @return Return a boolean which specifies whether or not the calling request should generate its
   *     own content. This allows an event to override the default content.
   */
  public static String logout(HttpServletRequest request, HttpServletResponse response) {
    // run the before-logout events
    RequestHandler rh = RequestHandler.getRequestHandler(request.getSession().getServletContext());
    rh.runBeforeLogoutEvents(request, response);

    // invalidate the security group list cache
    GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");

    doBasicLogout(userLogin, request, response);

    Element rootElement = getRootElement(request);

    String result = "error";
    if (rootElement != null) {
      String className =
          UtilXml.childElementValue(
              rootElement,
              "AuthenticationHandler",
              "org.ofbiz.ldap.openldap.OFBizLdapAuthenticationHandler");
      try {
        Class<?> handlerClass = Class.forName(className);
        InterfaceOFBizAuthenticationHandler authenticationHandler =
            (InterfaceOFBizAuthenticationHandler) handlerClass.newInstance();
        result = authenticationHandler.logout(request, response, rootElement);
      } catch (ClassNotFoundException e) {
        Debug.logError(e, "Error calling userLogin service", module);
        Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage());
        String errMsg =
            UtilProperties.getMessage(
                resourceWebapp,
                "loginevents.following_error_occurred_during_login",
                messageMap,
                UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
      } catch (InstantiationException e) {
        Debug.logError(e, "Error calling userLogin service", module);
        Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage());
        String errMsg =
            UtilProperties.getMessage(
                resourceWebapp,
                "loginevents.following_error_occurred_during_login",
                messageMap,
                UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
      } catch (IllegalAccessException e) {
        Debug.logError(e, "Error calling userLogin service", module);
        Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage());
        String errMsg =
            UtilProperties.getMessage(
                resourceWebapp,
                "loginevents.following_error_occurred_during_login",
                messageMap,
                UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
      } catch (Exception e) {
        Debug.logError(e, "Error calling userLogin service", module);
        Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage());
        String errMsg =
            UtilProperties.getMessage(
                resourceWebapp,
                "loginevents.following_error_occurred_during_login",
                messageMap,
                UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
      }
    }

    if (request.getAttribute("_AUTO_LOGIN_LOGOUT_") == null) {
      return autoLoginCheck(request, response);
    }
    return result;
  }
Esempio n. 26
0
  /**
   * An HTTP WebEvent handler that checks to see is a userLogin is logged in. If not, the user is
   * forwarded to the login page.
   *
   * @param request The HTTP request object for the current JSP or Servlet request.
   * @param response The HTTP response object for the current JSP or Servlet request.
   * @return String
   */
  public static String checkLogin(HttpServletRequest request, HttpServletResponse response) {
    GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
    // anonymous shoppers are not logged in
    if (userLogin != null && "anonymous".equals(userLogin.getString("userLoginId"))) {
      userLogin = null;
    }

    // user is logged in; check to see if they have globally logged out if not
    // check if they have permission for this login attempt; if not log them out
    if (userLogin != null) {
      Element rootElement = getRootElement(request);
      boolean hasLdapLoggedOut = false;
      if (rootElement != null) {
        String className =
            UtilXml.childElementValue(
                rootElement,
                "AuthenticationHandler",
                "org.ofbiz.ldap.openldap.OFBizLdapAuthenticationHandler");
        try {
          Class<?> handlerClass = Class.forName(className);
          InterfaceOFBizAuthenticationHandler authenticationHandler =
              (InterfaceOFBizAuthenticationHandler) handlerClass.newInstance();
          hasLdapLoggedOut = authenticationHandler.hasLdapLoggedOut(request, response, rootElement);
        } catch (ClassNotFoundException e) {
          Debug.logError(e, "Error calling checkLogin service", module);
          Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage());
          String errMsg =
              UtilProperties.getMessage(
                  resourceWebapp,
                  "loginevents.following_error_occurred_during_login",
                  messageMap,
                  UtilHttp.getLocale(request));
          request.setAttribute("_ERROR_MESSAGE_", errMsg);
        } catch (InstantiationException e) {
          Debug.logError(e, "Error calling checkLogin service", module);
          Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage());
          String errMsg =
              UtilProperties.getMessage(
                  resourceWebapp,
                  "loginevents.following_error_occurred_during_login",
                  messageMap,
                  UtilHttp.getLocale(request));
          request.setAttribute("_ERROR_MESSAGE_", errMsg);
        } catch (IllegalAccessException e) {
          Debug.logError(e, "Error calling checkLogin service", module);
          Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage());
          String errMsg =
              UtilProperties.getMessage(
                  resourceWebapp,
                  "loginevents.following_error_occurred_during_login",
                  messageMap,
                  UtilHttp.getLocale(request));
          request.setAttribute("_ERROR_MESSAGE_", errMsg);
        } catch (Exception e) {
          Debug.logError(e, "Error calling checkLogin service", module);
          Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage());
          String errMsg =
              UtilProperties.getMessage(
                  resourceWebapp,
                  "loginevents.following_error_occurred_during_login",
                  messageMap,
                  UtilHttp.getLocale(request));
          request.setAttribute("_ERROR_MESSAGE_", errMsg);
        }
      }

      if (!hasBasePermission(userLogin, request)
          || isFlaggedLoggedOut(userLogin)
          || hasLdapLoggedOut) {
        Debug.logInfo("User does not have permission or is flagged as logged out", module);
        doBasicLogout(userLogin, request, response);
        userLogin = null;
      }
    }

    if (userLogin == null) {
      return login(request, response);
    }

    return "success";
  }
Esempio n. 27
0
  /**
   * Load a license.
   *
   * @param path The license file path.
   * @return The license info.
   */
  public static LicenseInfo loadLicense(Log log, String path) {
    String keyString = null;
    try {
      keyString =
          ((AkteraKeyProvider) Class.forName("de.iritgo.aktera.license.AkteraKey").newInstance())
              .getKey();
    } catch (InstantiationException x1) {
      x1.printStackTrace();
    } catch (IllegalAccessException x1) {
      x1.printStackTrace();
    } catch (ClassNotFoundException x1) {
      x1.printStackTrace();
    }

    Properties props = new Properties();

    try {
      BufferedReader in = new BufferedReader(new FileReader(path));
      StringBuffer sb = new StringBuffer();
      String line = null;

      while ((line = in.readLine()) != null) {
        if ("# SHA1 Signature".equals(line)) {
          break;
        } else {
          sb.append(line + "\n");
        }
      }

      StringBuffer sbSig = new StringBuffer();

      while ((line = in.readLine()) != null) {
        sbSig.append(line + "\n");
      }

      X509EncodedKeySpec spec = new X509EncodedKeySpec(Base64.decodeBase64(keyString.getBytes()));
      KeyFactory keyFactory = KeyFactory.getInstance("DSA", "SUN");
      PublicKey key = keyFactory.generatePublic(spec);

      Signature sig = Signature.getInstance("SHA1withDSA", "SUN");

      sig.initVerify(key);
      sig.update(sb.toString().getBytes(), 0, sb.toString().getBytes().length);

      boolean valid = sig.verify(Base64.decodeBase64(sbSig.toString().getBytes()));

      if (!valid) {
        return null;
      }

      try {
        props.load(new StringReader(sb.toString()));
      } catch (Exception x) {
        System.out.println("LicenseTools.loadLicense: " + x.getMessage());
        x.printStackTrace();
        return null;
      }
    } catch (Exception x) {
      System.out.println("LicenseTools.loadLicense: " + x.getMessage());
      x.printStackTrace();
      return null;
    }

    return new LicenseInfo(log, props);
  }
Esempio n. 28
0
  public static void main(String[] args) {
    Options op = new Options(new EnglishTreebankParserParams());
    // op.tlpParams may be changed to something else later, so don't use it till
    // after options are parsed.

    System.out.println("Currently " + new Date());
    System.out.print("Invoked with arguments:");
    for (String arg : args) {
      System.out.print(" " + arg);
    }
    System.out.println();

    String path = "/u/nlp/stuff/corpora/Treebank3/parsed/mrg/wsj";
    int trainLow = 200, trainHigh = 2199, testLow = 2200, testHigh = 2219;
    String serializeFile = null;

    int i = 0;
    while (i < args.length && args[i].startsWith("-")) {
      if (args[i].equalsIgnoreCase("-path") && (i + 1 < args.length)) {
        path = args[i + 1];
        i += 2;
      } else if (args[i].equalsIgnoreCase("-train") && (i + 2 < args.length)) {
        trainLow = Integer.parseInt(args[i + 1]);
        trainHigh = Integer.parseInt(args[i + 2]);
        i += 3;
      } else if (args[i].equalsIgnoreCase("-test") && (i + 2 < args.length)) {
        testLow = Integer.parseInt(args[i + 1]);
        testHigh = Integer.parseInt(args[i + 2]);
        i += 3;
      } else if (args[i].equalsIgnoreCase("-serialize") && (i + 1 < args.length)) {
        serializeFile = args[i + 1];
        i += 2;
      } else if (args[i].equalsIgnoreCase("-tLPP") && (i + 1 < args.length)) {
        try {
          op.tlpParams = (TreebankLangParserParams) Class.forName(args[i + 1]).newInstance();
        } catch (ClassNotFoundException e) {
          System.err.println("Class not found: " + args[i + 1]);
        } catch (InstantiationException e) {
          System.err.println("Couldn't instantiate: " + args[i + 1] + ": " + e.toString());
        } catch (IllegalAccessException e) {
          System.err.println("illegal access" + e);
        }
        i += 2;
      } else if (args[i].equals("-encoding")) {
        // sets encoding for TreebankLangParserParams
        op.tlpParams.setInputEncoding(args[i + 1]);
        op.tlpParams.setOutputEncoding(args[i + 1]);
        i += 2;
      } else {
        i = op.setOptionOrWarn(args, i);
      }
    }
    // System.out.println(tlpParams.getClass());
    TreebankLanguagePack tlp = op.tlpParams.treebankLanguagePack();

    Train.sisterSplitters = new HashSet(Arrays.asList(op.tlpParams.sisterSplitters()));
    //    BinarizerFactory.TreeAnnotator.setTreebankLang(tlpParams);
    PrintWriter pw = op.tlpParams.pw();

    Test.display();
    Train.display();
    op.display();
    op.tlpParams.display();

    // setup tree transforms
    Treebank trainTreebank = op.tlpParams.memoryTreebank();
    MemoryTreebank testTreebank = op.tlpParams.testMemoryTreebank();
    // Treebank blippTreebank = ((EnglishTreebankParserParams) tlpParams).diskTreebank();
    // String blippPath = "/afs/ir.stanford.edu/data/linguistic-data/BLLIP-WSJ/";
    // blippTreebank.loadPath(blippPath, "", true);

    Timing.startTime();
    System.err.print("Reading trees...");
    testTreebank.loadPath(path, new NumberRangeFileFilter(testLow, testHigh, true));
    if (Test.increasingLength) {
      Collections.sort(testTreebank, new TreeLengthComparator());
    }

    trainTreebank.loadPath(path, new NumberRangeFileFilter(trainLow, trainHigh, true));
    Timing.tick("done.");
    System.err.print("Binarizing trees...");
    TreeAnnotatorAndBinarizer binarizer = null;
    if (!Train.leftToRight) {
      binarizer =
          new TreeAnnotatorAndBinarizer(op.tlpParams, op.forceCNF, !Train.outsideFactor(), true);
    } else {
      binarizer =
          new TreeAnnotatorAndBinarizer(
              op.tlpParams.headFinder(),
              new LeftHeadFinder(),
              op.tlpParams,
              op.forceCNF,
              !Train.outsideFactor(),
              true);
    }
    CollinsPuncTransformer collinsPuncTransformer = null;
    if (Train.collinsPunc) {
      collinsPuncTransformer = new CollinsPuncTransformer(tlp);
    }
    TreeTransformer debinarizer = new Debinarizer(op.forceCNF);
    List<Tree> binaryTrainTrees = new ArrayList<Tree>();

    if (Train.selectiveSplit) {
      Train.splitters =
          ParentAnnotationStats.getSplitCategories(
              trainTreebank,
              Train.tagSelectiveSplit,
              0,
              Train.selectiveSplitCutOff,
              Train.tagSelectiveSplitCutOff,
              op.tlpParams.treebankLanguagePack());
      if (Train.deleteSplitters != null) {
        List<String> deleted = new ArrayList<String>();
        for (String del : Train.deleteSplitters) {
          String baseDel = tlp.basicCategory(del);
          boolean checkBasic = del.equals(baseDel);
          for (Iterator<String> it = Train.splitters.iterator(); it.hasNext(); ) {
            String elem = it.next();
            String baseElem = tlp.basicCategory(elem);
            boolean delStr = checkBasic && baseElem.equals(baseDel) || elem.equals(del);
            if (delStr) {
              it.remove();
              deleted.add(elem);
            }
          }
        }
        System.err.println("Removed from vertical splitters: " + deleted);
      }
    }
    if (Train.selectivePostSplit) {
      TreeTransformer myTransformer = new TreeAnnotator(op.tlpParams.headFinder(), op.tlpParams);
      Treebank annotatedTB = trainTreebank.transform(myTransformer);
      Train.postSplitters =
          ParentAnnotationStats.getSplitCategories(
              annotatedTB,
              true,
              0,
              Train.selectivePostSplitCutOff,
              Train.tagSelectivePostSplitCutOff,
              op.tlpParams.treebankLanguagePack());
    }

    if (Train.hSelSplit) {
      binarizer.setDoSelectiveSplit(false);
      for (Tree tree : trainTreebank) {
        if (Train.collinsPunc) {
          tree = collinsPuncTransformer.transformTree(tree);
        }
        // tree.pennPrint(tlpParams.pw());
        tree = binarizer.transformTree(tree);
        // binaryTrainTrees.add(tree);
      }
      binarizer.setDoSelectiveSplit(true);
    }
    for (Tree tree : trainTreebank) {
      if (Train.collinsPunc) {
        tree = collinsPuncTransformer.transformTree(tree);
      }
      tree = binarizer.transformTree(tree);
      binaryTrainTrees.add(tree);
    }
    if (Test.verbose) {
      binarizer.dumpStats();
    }

    List<Tree> binaryTestTrees = new ArrayList<Tree>();
    for (Tree tree : testTreebank) {
      if (Train.collinsPunc) {
        tree = collinsPuncTransformer.transformTree(tree);
      }
      tree = binarizer.transformTree(tree);
      binaryTestTrees.add(tree);
    }
    Timing.tick("done."); // binarization
    BinaryGrammar bg = null;
    UnaryGrammar ug = null;
    DependencyGrammar dg = null;
    // DependencyGrammar dgBLIPP = null;
    Lexicon lex = null;
    // extract grammars
    Extractor bgExtractor = new BinaryGrammarExtractor();
    // Extractor bgExtractor = new SmoothedBinaryGrammarExtractor();//new BinaryGrammarExtractor();
    // Extractor lexExtractor = new LexiconExtractor();

    // Extractor dgExtractor = new DependencyMemGrammarExtractor();

    Extractor dgExtractor = new MLEDependencyGrammarExtractor(op);
    if (op.doPCFG) {
      System.err.print("Extracting PCFG...");
      Pair bgug = null;
      if (Train.cheatPCFG) {
        List allTrees = new ArrayList(binaryTrainTrees);
        allTrees.addAll(binaryTestTrees);
        bgug = (Pair) bgExtractor.extract(allTrees);
      } else {
        bgug = (Pair) bgExtractor.extract(binaryTrainTrees);
      }
      bg = (BinaryGrammar) bgug.second;
      bg.splitRules();
      ug = (UnaryGrammar) bgug.first;
      ug.purgeRules();
      Timing.tick("done.");
    }
    System.err.print("Extracting Lexicon...");
    lex = op.tlpParams.lex(op.lexOptions);
    lex.train(binaryTrainTrees);
    Timing.tick("done.");

    if (op.doDep) {
      System.err.print("Extracting Dependencies...");
      binaryTrainTrees.clear();
      // dgBLIPP = (DependencyGrammar) dgExtractor.extract(new
      // ConcatenationIterator(trainTreebank.iterator(),blippTreebank.iterator()),new
      // TransformTreeDependency(tlpParams,true));

      DependencyGrammar dg1 =
          (DependencyGrammar)
              dgExtractor.extract(
                  trainTreebank.iterator(), new TransformTreeDependency(op.tlpParams, true));
      // dgBLIPP=(DependencyGrammar)dgExtractor.extract(blippTreebank.iterator(),new
      // TransformTreeDependency(tlpParams));

      // dg = (DependencyGrammar) dgExtractor.extract(new
      // ConcatenationIterator(trainTreebank.iterator(),blippTreebank.iterator()),new
      // TransformTreeDependency(tlpParams));
      // dg=new DependencyGrammarCombination(dg1,dgBLIPP,2);
      // dg = (DependencyGrammar) dgExtractor.extract(binaryTrainTrees); //uses information whether
      // the words are known or not, discards unknown words
      Timing.tick("done.");
      // System.out.print("Extracting Unknown Word Model...");
      // UnknownWordModel uwm = (UnknownWordModel)uwmExtractor.extract(binaryTrainTrees);
      // Timing.tick("done.");
      System.out.print("Tuning Dependency Model...");
      dg.tune(binaryTestTrees);
      // System.out.println("TUNE DEPS: "+tuneDeps);
      Timing.tick("done.");
    }

    BinaryGrammar boundBG = bg;
    UnaryGrammar boundUG = ug;

    GrammarProjection gp = new NullGrammarProjection(bg, ug);

    // serialization
    if (serializeFile != null) {
      System.err.print("Serializing parser...");
      LexicalizedParser.saveParserDataToSerialized(
          new ParserData(lex, bg, ug, dg, Numberer.getNumberers(), op), serializeFile);
      Timing.tick("done.");
    }

    // test: pcfg-parse and output

    ExhaustivePCFGParser parser = null;
    if (op.doPCFG) {
      parser = new ExhaustivePCFGParser(boundBG, boundUG, lex, op);
    }

    ExhaustiveDependencyParser dparser =
        ((op.doDep && !Test.useFastFactored) ? new ExhaustiveDependencyParser(dg, lex, op) : null);

    Scorer scorer = (op.doPCFG ? new TwinScorer(new ProjectionScorer(parser, gp), dparser) : null);
    // Scorer scorer = parser;
    BiLexPCFGParser bparser = null;
    if (op.doPCFG && op.doDep) {
      bparser =
          (Test.useN5)
              ? new BiLexPCFGParser.N5BiLexPCFGParser(
                  scorer, parser, dparser, bg, ug, dg, lex, op, gp)
              : new BiLexPCFGParser(scorer, parser, dparser, bg, ug, dg, lex, op, gp);
    }

    LabeledConstituentEval pcfgPE = new LabeledConstituentEval("pcfg  PE", true, tlp);
    LabeledConstituentEval comboPE = new LabeledConstituentEval("combo PE", true, tlp);
    AbstractEval pcfgCB = new LabeledConstituentEval.CBEval("pcfg  CB", true, tlp);

    AbstractEval pcfgTE = new AbstractEval.TaggingEval("pcfg  TE");
    AbstractEval comboTE = new AbstractEval.TaggingEval("combo TE");
    AbstractEval pcfgTEnoPunct = new AbstractEval.TaggingEval("pcfg nopunct TE");
    AbstractEval comboTEnoPunct = new AbstractEval.TaggingEval("combo nopunct TE");
    AbstractEval depTE = new AbstractEval.TaggingEval("depnd TE");

    AbstractEval depDE =
        new AbstractEval.DependencyEval("depnd DE", true, tlp.punctuationWordAcceptFilter());
    AbstractEval comboDE =
        new AbstractEval.DependencyEval("combo DE", true, tlp.punctuationWordAcceptFilter());

    if (Test.evalb) {
      EvalB.initEVALBfiles(op.tlpParams);
    }

    // int[] countByLength = new int[Test.maxLength+1];

    // use a reflection ruse, so one can run this without needing the tagger
    // edu.stanford.nlp.process.SentenceTagger tagger = (Test.preTag ? new
    // edu.stanford.nlp.process.SentenceTagger("/u/nlp/data/tagger.params/wsj0-21.holder") : null);
    SentenceProcessor tagger = null;
    if (Test.preTag) {
      try {
        Class[] argsClass = new Class[] {String.class};
        Object[] arguments =
            new Object[] {"/u/nlp/data/pos-tagger/wsj3t0-18-bidirectional/train-wsj-0-18.holder"};
        tagger =
            (SentenceProcessor)
                Class.forName("edu.stanford.nlp.tagger.maxent.MaxentTagger")
                    .getConstructor(argsClass)
                    .newInstance(arguments);
      } catch (Exception e) {
        System.err.println(e);
        System.err.println("Warning: No pretagging of sentences will be done.");
      }
    }

    for (int tNum = 0, ttSize = testTreebank.size(); tNum < ttSize; tNum++) {
      Tree tree = testTreebank.get(tNum);
      int testTreeLen = tree.yield().size();
      if (testTreeLen > Test.maxLength) {
        continue;
      }
      Tree binaryTree = binaryTestTrees.get(tNum);
      // countByLength[testTreeLen]++;
      System.out.println("-------------------------------------");
      System.out.println("Number: " + (tNum + 1));
      System.out.println("Length: " + testTreeLen);

      // tree.pennPrint(pw);
      // System.out.println("XXXX The binary tree is");
      // binaryTree.pennPrint(pw);
      // System.out.println("Here are the tags in the lexicon:");
      // System.out.println(lex.showTags());
      // System.out.println("Here's the tagnumberer:");
      // System.out.println(Numberer.getGlobalNumberer("tags").toString());

      long timeMil1 = System.currentTimeMillis();
      Timing.tick("Starting parse.");
      if (op.doPCFG) {
        // System.err.println(Test.forceTags);
        if (Test.forceTags) {
          if (tagger != null) {
            // System.out.println("Using a tagger to set tags");
            // System.out.println("Tagged sentence as: " +
            // tagger.processSentence(cutLast(wordify(binaryTree.yield()))).toString(false));
            parser.parse(addLast(tagger.processSentence(cutLast(wordify(binaryTree.yield())))));
          } else {
            // System.out.println("Forcing tags to match input.");
            parser.parse(cleanTags(binaryTree.taggedYield(), tlp));
          }
        } else {
          // System.out.println("XXXX Parsing " + binaryTree.yield());
          parser.parse(binaryTree.yield());
        }
        // Timing.tick("Done with pcfg phase.");
      }
      if (op.doDep) {
        dparser.parse(binaryTree.yield());
        // Timing.tick("Done with dependency phase.");
      }
      boolean bothPassed = false;
      if (op.doPCFG && op.doDep) {
        bothPassed = bparser.parse(binaryTree.yield());
        // Timing.tick("Done with combination phase.");
      }
      long timeMil2 = System.currentTimeMillis();
      long elapsed = timeMil2 - timeMil1;
      System.err.println("Time: " + ((int) (elapsed / 100)) / 10.00 + " sec.");
      // System.out.println("PCFG Best Parse:");
      Tree tree2b = null;
      Tree tree2 = null;
      // System.out.println("Got full best parse...");
      if (op.doPCFG) {
        tree2b = parser.getBestParse();
        tree2 = debinarizer.transformTree(tree2b);
      }
      // System.out.println("Debinarized parse...");
      // tree2.pennPrint();
      // System.out.println("DepG Best Parse:");
      Tree tree3 = null;
      Tree tree3db = null;
      if (op.doDep) {
        tree3 = dparser.getBestParse();
        // was: but wrong Tree tree3db = debinarizer.transformTree(tree2);
        tree3db = debinarizer.transformTree(tree3);
        tree3.pennPrint(pw);
      }
      // tree.pennPrint();
      // ((Tree)binaryTrainTrees.get(tNum)).pennPrint();
      // System.out.println("Combo Best Parse:");
      Tree tree4 = null;
      if (op.doPCFG && op.doDep) {
        try {
          tree4 = bparser.getBestParse();
          if (tree4 == null) {
            tree4 = tree2b;
          }
        } catch (NullPointerException e) {
          System.err.println("Blocked, using PCFG parse!");
          tree4 = tree2b;
        }
      }
      if (op.doPCFG && !bothPassed) {
        tree4 = tree2b;
      }
      // tree4.pennPrint();
      if (op.doDep) {
        depDE.evaluate(tree3, binaryTree, pw);
        depTE.evaluate(tree3db, tree, pw);
      }
      TreeTransformer tc = op.tlpParams.collinizer();
      TreeTransformer tcEvalb = op.tlpParams.collinizerEvalb();
      Tree tree4b = null;
      if (op.doPCFG) {
        // System.out.println("XXXX Best PCFG was: ");
        // tree2.pennPrint();
        // System.out.println("XXXX Transformed best PCFG is: ");
        // tc.transformTree(tree2).pennPrint();
        // System.out.println("True Best Parse:");
        // tree.pennPrint();
        // tc.transformTree(tree).pennPrint();
        pcfgPE.evaluate(tc.transformTree(tree2), tc.transformTree(tree), pw);
        pcfgCB.evaluate(tc.transformTree(tree2), tc.transformTree(tree), pw);
        if (op.doDep) {
          comboDE.evaluate((bothPassed ? tree4 : tree3), binaryTree, pw);
          tree4b = tree4;
          tree4 = debinarizer.transformTree(tree4);
          if (op.nodePrune) {
            NodePruner np = new NodePruner(parser, debinarizer);
            tree4 = np.prune(tree4);
          }
          // tree4.pennPrint();
          comboPE.evaluate(tc.transformTree(tree4), tc.transformTree(tree), pw);
        }
        // pcfgTE.evaluate(tree2, tree);
        pcfgTE.evaluate(tcEvalb.transformTree(tree2), tcEvalb.transformTree(tree), pw);
        pcfgTEnoPunct.evaluate(tc.transformTree(tree2), tc.transformTree(tree), pw);

        if (op.doDep) {
          comboTE.evaluate(tcEvalb.transformTree(tree4), tcEvalb.transformTree(tree), pw);
          comboTEnoPunct.evaluate(tc.transformTree(tree4), tc.transformTree(tree), pw);
        }
        System.out.println("PCFG only: " + parser.scoreBinarizedTree(tree2b, 0));

        // tc.transformTree(tree2).pennPrint();
        tree2.pennPrint(pw);

        if (op.doDep) {
          System.out.println("Combo: " + parser.scoreBinarizedTree(tree4b, 0));
          // tc.transformTree(tree4).pennPrint(pw);
          tree4.pennPrint(pw);
        }
        System.out.println("Correct:" + parser.scoreBinarizedTree(binaryTree, 0));
        /*
        if (parser.scoreBinarizedTree(tree2b,true) < parser.scoreBinarizedTree(binaryTree,true)) {
          System.out.println("SCORE INVERSION");
          parser.validateBinarizedTree(binaryTree,0);
        }
        */
        tree.pennPrint(pw);
      } // end if doPCFG

      if (Test.evalb) {
        if (op.doPCFG && op.doDep) {
          EvalB.writeEVALBline(tcEvalb.transformTree(tree), tcEvalb.transformTree(tree4));
        } else if (op.doPCFG) {
          EvalB.writeEVALBline(tcEvalb.transformTree(tree), tcEvalb.transformTree(tree2));
        } else if (op.doDep) {
          EvalB.writeEVALBline(tcEvalb.transformTree(tree), tcEvalb.transformTree(tree3db));
        }
      }
    } // end for each tree in test treebank

    if (Test.evalb) {
      EvalB.closeEVALBfiles();
    }

    // Test.display();
    if (op.doPCFG) {
      pcfgPE.display(false, pw);
      System.out.println("Grammar size: " + Numberer.getGlobalNumberer("states").total());
      pcfgCB.display(false, pw);
      if (op.doDep) {
        comboPE.display(false, pw);
      }
      pcfgTE.display(false, pw);
      pcfgTEnoPunct.display(false, pw);
      if (op.doDep) {
        comboTE.display(false, pw);
        comboTEnoPunct.display(false, pw);
      }
    }
    if (op.doDep) {
      depTE.display(false, pw);
      depDE.display(false, pw);
    }
    if (op.doPCFG && op.doDep) {
      comboDE.display(false, pw);
    }
    // pcfgPE.printGoodBad();
  }
  public Properties parseURL(String url, Properties defaults) throws java.sql.SQLException {
    Properties urlProps = (defaults != null) ? new Properties(defaults) : new Properties();

    if (url == null) {
      return null;
    }

    if (!StringUtils.startsWithIgnoreCase(url, URL_PREFIX)
        && !StringUtils.startsWithIgnoreCase(url, MXJ_URL_PREFIX)
        && !StringUtils.startsWithIgnoreCase(url, LOADBALANCE_URL_PREFIX)
        && !StringUtils.startsWithIgnoreCase(url, REPLICATION_URL_PREFIX)) { // $NON-NLS-1$

      return null;
    }

    int beginningOfSlashes = url.indexOf("//");

    if (StringUtils.startsWithIgnoreCase(url, MXJ_URL_PREFIX)) {
      urlProps.setProperty(
          "socketFactory", "com.mysql.management.driverlaunched.ServerLauncherSocketFactory");
    }

    /*
     * Parse parameters after the ? in the URL and remove them from the
     * original URL.
     */
    int index = url.indexOf("?"); // $NON-NLS-1$

    if (index != -1) {
      String paramString = url.substring(index + 1, url.length());
      url = url.substring(0, index);

      StringTokenizer queryParams = new StringTokenizer(paramString, "&"); // $NON-NLS-1$

      while (queryParams.hasMoreTokens()) {
        String parameterValuePair = queryParams.nextToken();

        int indexOfEquals = StringUtils.indexOfIgnoreCase(0, parameterValuePair, "=");

        String parameter = null;
        String value = null;

        if (indexOfEquals != -1) {
          parameter = parameterValuePair.substring(0, indexOfEquals);

          if (indexOfEquals + 1 < parameterValuePair.length()) {
            value = parameterValuePair.substring(indexOfEquals + 1);
          }
        }

        if ((value != null && value.length() > 0)
            && (parameter != null && parameter.length() > 0)) {
          try {
            urlProps.put(parameter, URLDecoder.decode(value, "UTF-8"));
          } catch (UnsupportedEncodingException badEncoding) {
            // punt
            urlProps.put(parameter, URLDecoder.decode(value));
          } catch (NoSuchMethodError nsme) {
            // punt again
            urlProps.put(parameter, URLDecoder.decode(value));
          }
        }
      }
    }

    url = url.substring(beginningOfSlashes + 2);

    String hostStuff = null;

    int slashIndex = url.indexOf("/"); // $NON-NLS-1$

    if (slashIndex != -1) {
      hostStuff = url.substring(0, slashIndex);

      if ((slashIndex + 1) < url.length()) {
        urlProps.put(
            DBNAME_PROPERTY_KEY, //$NON-NLS-1$
            url.substring((slashIndex + 1), url.length()));
      }
    } else {
      hostStuff = url;
    }

    if ((hostStuff != null) && (hostStuff.length() > 0)) {
      urlProps.put(HOST_PROPERTY_KEY, hostStuff); // $NON-NLS-1$
    }

    String propertiesTransformClassName = urlProps.getProperty(PROPERTIES_TRANSFORM_KEY);

    if (propertiesTransformClassName != null) {
      try {
        ConnectionPropertiesTransform propTransformer =
            (ConnectionPropertiesTransform)
                Class.forName(propertiesTransformClassName).newInstance();

        urlProps = propTransformer.transformProperties(urlProps);
      } catch (InstantiationException e) {
        throw SQLError.createSQLException(
            "Unable to create properties transform instance '"
                + propertiesTransformClassName
                + "' due to underlying exception: "
                + e.toString(),
            SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE);
      } catch (IllegalAccessException e) {
        throw SQLError.createSQLException(
            "Unable to create properties transform instance '"
                + propertiesTransformClassName
                + "' due to underlying exception: "
                + e.toString(),
            SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE);
      } catch (ClassNotFoundException e) {
        throw SQLError.createSQLException(
            "Unable to create properties transform instance '"
                + propertiesTransformClassName
                + "' due to underlying exception: "
                + e.toString(),
            SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE);
      }
    }

    if (Util.isColdFusion()
        && urlProps.getProperty("autoConfigureForColdFusion", "true").equalsIgnoreCase("true")) {
      String configs = urlProps.getProperty(USE_CONFIG_PROPERTY_KEY);

      StringBuffer newConfigs = new StringBuffer();

      if (configs != null) {
        newConfigs.append(configs);
        newConfigs.append(",");
      }

      newConfigs.append("coldFusion");

      urlProps.setProperty(USE_CONFIG_PROPERTY_KEY, newConfigs.toString());
    }

    // If we use a config, it actually should get overridden by anything in
    // the URL or passed-in properties

    String configNames = null;

    if (defaults != null) {
      configNames = defaults.getProperty(USE_CONFIG_PROPERTY_KEY);
    }

    if (configNames == null) {
      configNames = urlProps.getProperty(USE_CONFIG_PROPERTY_KEY);
    }

    if (configNames != null) {
      List splitNames = StringUtils.split(configNames, ",", true);

      Properties configProps = new Properties();

      Iterator namesIter = splitNames.iterator();

      while (namesIter.hasNext()) {
        String configName = (String) namesIter.next();

        try {
          InputStream configAsStream =
              getClass().getResourceAsStream("configs/" + configName + ".properties");

          if (configAsStream == null) {
            throw SQLError.createSQLException(
                "Can't find configuration template named '" + configName + "'",
                SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE);
          }
          configProps.load(configAsStream);
        } catch (IOException ioEx) {
          throw SQLError.createSQLException(
              "Unable to load configuration template '"
                  + configName
                  + "' due to underlying IOException: "
                  + ioEx,
              SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE);
        }
      }

      Iterator propsIter = urlProps.keySet().iterator();

      while (propsIter.hasNext()) {
        String key = propsIter.next().toString();
        String property = urlProps.getProperty(key);
        configProps.setProperty(key, property);
      }

      urlProps = configProps;
    }

    // Properties passed in should override ones in URL

    if (defaults != null) {
      Iterator propsIter = defaults.keySet().iterator();

      while (propsIter.hasNext()) {
        String key = propsIter.next().toString();
        String property = defaults.getProperty(key);
        urlProps.setProperty(key, property);
      }
    }

    return urlProps;
  }