コード例 #1
0
ファイル: NetworkManager.java プロジェクト: McSwede/XIV
 public void sendPacket(
     Packet packetIn, GenericFutureListener listener, GenericFutureListener... listeners) {
   if (this.channel != null && this.channel.isOpen()) {
     this.flushOutboundQueue();
     this.dispatchPacket(
         packetIn, (GenericFutureListener[]) ArrayUtils.add(listeners, 0, listener));
   } else {
     this.outboundPacketsQueue.add(
         new NetworkManager.InboundHandlerTuplePacketListener(
             packetIn, (GenericFutureListener[]) ArrayUtils.add(listeners, 0, listener)));
   }
 }
コード例 #2
0
  public void a(Packet var1, GenericFutureListener var2, GenericFutureListener... var3) {
    if (g()) {
      m();
      this.a(var1, ArrayUtils.add(var3, 0, var2));
    } else {
      j.writeLock().lock();

      try {
        i.add(new class_ek.class_a_in_class_ek(var1, ArrayUtils.add(var3, 0, var2)));
      } finally {
        j.writeLock().unlock();
      }
    }
  }
コード例 #3
0
ファイル: GenericDaoImpl.java プロジェクト: zishinan/xuhuamao
  @Override
  public List<T> listQuery(String condition, Object[] params, Integer start, Integer max) {
    StringBuilder sql = new StringBuilder("select * from ").append(getTable());
    if (StringUtils.isNotBlank(condition)) {
      sql.append(" where ").append(condition);
    }

    if (start != null && max != null && start >= 0 && max > 0) {
      sql.append(" limit ?,?");
      params = ArrayUtils.add(params, start);
      params = ArrayUtils.add(params, max);
    }
    return query(sql.toString(), new MyBeanListHandler<T>(this.clazz), params);
  }
コード例 #4
0
  /**
   * Method dropAttackable.
   *
   * @param attackable NpcInstance
   * @param killer Player
   */
  public void dropAttackable(NpcInstance attackable, Player killer) {
    if (killer.isInOlympiadMode()
        || killer.isCursedWeaponEquipped()
        || (_cursedWeapons.length == 0)
        || (killer.getReflection() != ReflectionManager.DEFAULT)) {
      return;
    }

    synchronized (_cursedWeapons) {
      CursedWeapon[] cursedWeapons = new CursedWeapon[0];

      for (CursedWeapon cw : _cursedWeapons) {
        if (cw.isActive()) {
          continue;
        }

        cursedWeapons = ArrayUtils.add(cursedWeapons, cw);
      }

      if (cursedWeapons.length > 0) {
        CursedWeapon cw = cursedWeapons[Rnd.get(cursedWeapons.length)];

        if (Rnd.get(100000000) <= cw.getDropRate()) {
          cw.create(attackable, killer);
        }
      }
    }
  }
コード例 #5
0
  /**
   * Opens an input stream to this location.
   *
   * <p>Please note that it will try to obtain a stream from every storage until a storage returns
   * one.
   *
   * @return The input-stream to this location.
   */
  @Override
  public InputStream getInputStream() throws IOException {
    // Sine we are going to suppress all unhandles IOExceptions and only throw them
    // if we were unable to get a stream, we will access the location.
    List<IOException> exceptionList = new ArrayList<IOException>();

    // Try all locations but try the write-storage first.
    for (ConfigurationStorage cs :
        ArrayUtils.add(this.storage.getChildStorage(), 0, this.storage.getWriteStorage())) {
      // Try to access the storage location.
      InputStream is = null;
      try {
        is = cs.getInputStream(this.module, this.configuration);
      } catch (IOException e) {
        // Just suppress IOExceptions.
        exceptionList.add(e);
      }

      // If we were able to access the location, return the stream.
      if (is != null) return is;
    }

    if (exceptionList.size() == 0) return null;
    else if (exceptionList.size() == 1) {
      // Just rethrow the only one that occured.
      throw exceptionList.get(0);
    } else {
      // Throw all suppressed exceptions.
      IOException exception =
          new IOException(
              "Failed to obtain the stream. The following exceptions have been suppressed.");
      for (IOException e : exceptionList) exception.addSuppressed(e);
      throw exception;
    }
  }
  public List<SimpleObject> getPatients(
      @RequestParam(value = "searchValue", required = true) String searchValue,
      @RequestParam(value = "excludePatientsOf", required = false) Person excludePatientsOf,
      @RequestParam(value = "existingRelationshipTypeToExclude", required = false)
          RelationshipType existingRelationshipTypeToExclude,
      @RequestParam(value = "resultFields[]", required = true) String[] resultFields,
      UiUtils ui)
      throws PersonIsNotProviderException, InvalidRelationshipTypeException {

    if (resultFields == null || resultFields.length == 0) {
      resultFields = new String[] {"personName"};
    }

    // always want to return the id of the result objects
    resultFields = ArrayUtils.add(resultFields, "id");

    // now fetch the results
    List<Patient> patients = Context.getPatientService().getPatients(searchValue);

    // exclude any patients if specified
    if (excludePatientsOf != null && existingRelationshipTypeToExclude != null) {
      List<Patient> patientsToExclude =
          Context.getService(ProviderManagementService.class)
              .getPatientsOfProvider(
                  excludePatientsOf, existingRelationshipTypeToExclude, new Date());
      patients.removeAll(patientsToExclude);
    }

    return SimpleObject.fromCollection(patients, ui, resultFields);
  }
コード例 #7
0
ファイル: QuickCheck.java プロジェクト: sbukharov/quickCheck
    /** Main method that responds to mouseClick events. */
    public void mouseClicked(MouseEvent arg0) {
      if (errListModel.getSize() > 0
          && !errorsList.isSelectionEmpty()
          && !correctionsList.isSelectionEmpty()) {

        String correction = correctionsList.getSelectedValue();
        String error = errorsList.getSelectedValue();

        char[] inputAsChars = text.getText().toCharArray();
        int errIndex = getErrorIndex(error, inputAsChars);

        for (int i = 0; i < error.length(); i++) {
          inputAsChars = ArrayUtils.remove(inputAsChars, errIndex);
        }

        for (int i = 0; i < correction.length(); i++) {
          inputAsChars =
              ArrayUtils.add(
                  inputAsChars, errIndex, correction.charAt(correction.length() - i - 1));
        }

        correctionsListModel.clear();
        errListModel.clear();

        text.setText(new String(inputAsChars));
      }
    }
コード例 #8
0
ファイル: AbstractUser.java プロジェクト: jsklepek/structr
  @Override
  public void addSessionId(final String sessionId) {

    try {

      final String[] ids = getProperty(Principal.sessionIds);
      if (ids != null) {

        if (!ArrayUtils.contains(ids, sessionId)) {

          setProperty(
              Principal.sessionIds,
              (String[]) ArrayUtils.add(getProperty(Principal.sessionIds), sessionId));
        }

      } else {

        setProperty(Principal.sessionIds, new String[] {sessionId});
      }

    } catch (FrameworkException ex) {
      logger.log(
          Level.SEVERE, "Could not add sessionId " + sessionId + " to array of sessionIds", ex);
    }
  }
コード例 #9
0
ファイル: CareDaoImpl.java プロジェクト: xclq24/crm
 @Override
 public void update(Care care) throws Exception {
   // TODO Auto-generated method stub
   Object[] params = care.toArray();
   params = ArrayUtils.remove(params, 2);
   params = ArrayUtils.add(params, care.getId());
   update(
       "update care set theme=?, object=?, next=?, way=?, people=?, note=? where id = ?", params);
 }
コード例 #10
0
  @Override
  @SideOnly(Side.CLIENT)
  public double getDurabilityForDisplay(ItemStack itemstack) {
    if (!showDurabilityBar(itemstack)) return 0;

    ConsomationManager manager = TeleplatesSavedData.getClient().getConsomationManager();

    double[] ds = new double[] {};
    if (manager.isManagerActive(EnergyConsomationManager.class)
        && EnergyConsomationManager.rfUsageType != 0) {
      EnergyConsomationManager emanager =
          manager.getActiveConsomationManager(EnergyConsomationManager.class);
      ds =
          ArrayUtils.add(
              ds,
              EnergyConsomationManager.rfUsageType == 1
                  ? (double)
                          emanager
                              .getEnergyStorage(Minecraft.getMinecraft().thePlayer)
                              .getEnergyStored()
                      / (double)
                          emanager
                              .getEnergyStorage(Minecraft.getMinecraft().thePlayer)
                              .getMaxEnergyStored()
                  : getEnergyStored_(itemstack) / (double) getMaxEnergyStored_(itemstack));
    }
    if (manager.isManagerActive(FluidConsomationManager.class)
        && FluidConsomationManager.fluidConsomationType != 0) {
      FluidConsomationManager fmanager =
          manager.getActiveConsomationManager(FluidConsomationManager.class);
      ds =
          ArrayUtils.add(
              ds,
              FluidConsomationManager.fluidConsomationType == 1
                  ? (double)
                          fmanager
                              .getFluidStorage(Minecraft.getMinecraft().thePlayer)
                              .getFluidAmount()
                      / (double)
                          fmanager.getFluidStorage(Minecraft.getMinecraft().thePlayer).getCapacity()
                  : getFluid_(itemstack).amount);
    }
    return 1 - AdvancedMathUtils.average(ds);
  }
コード例 #11
0
  public static Question[] getQuestions(File xmlFile) {
    SAXBuilder builder = new SAXBuilder();
    Question[] res = {};

    try {

      Document document = (Document) builder.build(xmlFile);

      Element rootNode = document.getRootElement();

      List topics = rootNode.getChildren("t");

      String id, group, text, text_en, answer, q_type, q_ans, support, number; // , snippet;

      for (int i = 0; i < topics.size(); i++) {

        Element t = (Element) topics.get(i);
        List questions = t.getChildren("q");
        for (int j = 0; j < questions.size(); j++) {

          Element q = (Element) questions.get(j);
          id = q.getAttributeValue("q_id").toString();
          q_type = q.getAttributeValue("q_type").toString();
          q_ans = q.getAttributeValue("q_exp_ans_type").toString();
          support = q.getChild("answer").getAttributeValue("a_support");
          // snippet = q.getChild("answer").getAttributeValue("a_support");
          group = t.getAttributeValue("t_string").toString();
          text = q.getChild("question").getText();
          number = q.getChild("question").getAttributeValue("question_id");
          answer = q.getChild("answer").getChildText("a_string");
          text_en = q.getChild("q_translation").getText();
          res =
              ArrayUtils.add(
                  res,
                  new Question(
                      id,
                      group,
                      text,
                      answer,
                      text_en,
                      new String[0],
                      q_type,
                      q_ans,
                      support,
                      number));
        }
      }

    } catch (IOException io) {
      System.out.println(io.getMessage());
    } catch (JDOMException jdomex) {
      System.out.println(jdomex.getMessage());
    }

    return res;
  }
コード例 #12
0
 @Override
 public AxisAlignedBB[] getActiveBoxes() {
   AxisAlignedBB[] Result = {};
   if (collisionBoxes != null)
     for (int i = 0; i < collisionBoxes.length; i++) {
       if (collisionBoxes[i] != null) Result = ArrayUtils.add(Result, collisionBoxes[i]);
     }
   else updateConnections();
   return Result;
 }
コード例 #13
0
  /**
   * combogrid
   *
   * @return
   * @throws Exception
   */
  @RequestMapping(value = {"combogrid"})
  @ResponseBody
  public Datagrid<User> combogrid(
      @RequestParam(value = "ids", required = false) List<Long> ids,
      String loginNameOrName,
      Integer rows)
      throws Exception {
    Criterion statusCriterion = Restrictions.eq("status", StatusState.normal.getValue());
    Criterion[] criterions = new Criterion[0];
    criterions = (Criterion[]) ArrayUtils.add(criterions, 0, statusCriterion);
    Criterion criterion = null;
    if (Collections3.isNotEmpty(ids)) {
      // in条件
      Criterion inCriterion = Restrictions.in("id", ids);

      if (StringUtils.isNotBlank(loginNameOrName)) {
        Criterion loginNameCriterion =
            Restrictions.like("loginName", loginNameOrName, MatchMode.ANYWHERE);
        Criterion nameCriterion = Restrictions.like("name", loginNameOrName, MatchMode.ANYWHERE);
        Criterion criterion1 = Restrictions.or(loginNameCriterion, nameCriterion);
        criterion = Restrictions.or(inCriterion, criterion1);
      } else {
        criterion = inCriterion;
      }
      // 合并查询条件
      criterions = (Criterion[]) ArrayUtils.add(criterions, 0, criterion);
    } else {
      if (StringUtils.isNotBlank(loginNameOrName)) {
        Criterion loginNameCriterion =
            Restrictions.like("loginName", loginNameOrName, MatchMode.ANYWHERE);
        Criterion nameCriterion = Restrictions.like("name", loginNameOrName, MatchMode.ANYWHERE);
        criterion = Restrictions.or(loginNameCriterion, nameCriterion);
        // 合并查询条件
        criterions = (Criterion[]) ArrayUtils.add(criterions, 0, criterion);
      }
    }

    // 分页查询
    Page<User> p = new Page<User>(rows); // 分页对象
    p = userManager.findByCriteria(p, criterions);
    Datagrid<User> dg = new Datagrid<User>(p.getTotalCount(), p.getResult());
    return dg;
  }
コード例 #14
0
 private List<ParentFolder> getParentFolders(String relativeParentPaths) {
   ArrayList<ParentFolder> list = new ArrayList<GenerateWebCatalogCommand.ParentFolder>();
   String[] parentFolderPaths = StringUtils.split(relativeParentPaths, File.separator);
   parentFolderPaths = ArrayUtils.add(parentFolderPaths, 0, "Home");
   for (int i = 0; i < parentFolderPaths.length - 1; i++) {
     list.add(
         new ParentFolder(
             parentFolderPaths[i], StringUtils.repeat("../", parentFolderPaths.length - i - 1)));
   }
   list.add(new ParentFolder(parentFolderPaths[parentFolderPaths.length - 1], "."));
   return list;
 }
コード例 #15
0
 /**
  * returns a BCD byte array that specifies the length of the supplied value for a variable-width
  * field to the output stream
  *
  * @param vsize size of the variable width specifier (1, 2 or 3)
  * @param value the value to be stored in the field
  * @return field size as a byte array
  */
 private byte[] getVarLengthSpecifier(final int vsize, final String value) {
   int length = value.length();
   if (length % 2 != 0) { // is odd
     length++;
   }
   byte[] vspecifier = BCD.valueOf(length);
   if (vsize > 2
       && vspecifier.length < 2) { // LLLVAR: needs filler to make 2-byte length specifier
     vspecifier = ArrayUtils.add(vspecifier, 0, (byte) 0);
   }
   return vspecifier;
 }
コード例 #16
0
  public static Question[] filterSupport(Question[] qs, boolean wiki, boolean nil, boolean payed) {
    int cnil = 0, cpayed = 0, cwiki = 0;
    BaseComparator comp = new ContainsComparator();
    Question[] res = {};
    for (int i = 0; i < qs.length; i++) {

      if (qs[i].getSupport().compareTo("NIL") == 0 || qs[i].getSupport().length() == 0) {
        cnil++;
        if (nil) res = ArrayUtils.add(res, qs[i]);
        // Utils.println("NIL:"+qs[i].getSupport());

      } else if (comp.compare(qs[i].getSupport(), "html")) {
        cwiki++;
        if (wiki) res = ArrayUtils.add(res, qs[i]);
      } else {
        cpayed++;
        if (payed) res = ArrayUtils.add(res, qs[i]);
      }
    }
    // System.out.format("{wiki: %d, payed: %d, nil: %d}", cwiki, cpayed, cnil);
    return res;
  }
コード例 #17
0
  public static Question[] filterQType(
      Question[] qs, boolean factoid, boolean definition, boolean list) {
    int cfactoid = 0, cdefinition = 0, clist = 0;
    BaseComparator comp = new ContainsComparator();
    Question[] res = {};
    for (int i = 0; i < qs.length; i++) {
      if (qs[i].getQType().compareTo("FACTOID") == 0) {
        cfactoid++;
        if (factoid) res = ArrayUtils.add(res, qs[i]);
        // Utils.println("NIL:"+qs[i].getSupport());

      } else if (qs[i].getQType().compareTo("LIST") == 0) {
        clist++;
        if (list) res = ArrayUtils.add(res, qs[i]);
      } else {
        cdefinition++;
        if (definition) res = ArrayUtils.add(res, qs[i]);
      }
    }
    // System.out.format("{list: %d, def: %d, fact: %d}", clist, cdefinition, cfactoid);
    return res;
  }
コード例 #18
0
ファイル: QueryParams.java プロジェクト: avasquez614/search
  public QueryParams addParam(String name, String value) {
    String[] oldValues = params.get(name);
    String[] values;

    if (ArrayUtils.isNotEmpty(oldValues)) {
      values = ArrayUtils.add(oldValues, value);
    } else {
      values = new String[1];
      values[0] = value;
    }

    params.put(name, values);

    return this;
  }
コード例 #19
0
ファイル: TestCommonsLang.java プロジェクト: cassc/javaNotes
  public static void main(String[] args) {
    // StringUtils
    print(StringUtils.abbreviate("javajava", 10));
    print(StringUtils.repeat("java", 20));
    print(StringUtils.leftPad("java", 10));
    print(StringUtils.left("long-long-long-java-string", 10));

    // ArrayUtils
    // Add element to an array
    int[] ids = new int[] {1, 3, 5, 7};
    print(Arrays.toString(ArrayUtils.add(ids, 9)));

    // StringUtils
    // Get a string by joining all elements
    print(StringUtils.join("a", "b", "c"));
  }
コード例 #20
0
ファイル: Utils.java プロジェクト: gyurix/ProtectionCore
 public static void loadConfig() {
   dir = KFA.fileCopy(MyPlugin.pl, "config.yml", false);
   kf = new ConfigFile(dir + File.separator + "config.yml");
   long oldver = kf.getLong("version", 0L);
   if (oldver < 7L) {
     dir = KFA.fileCopy(MyPlugin.pl, "config.yml", true);
     kf = new ConfigFile(dir + File.separator + "config.yml");
     verchange = true;
   }
   else if (oldver == 7L) {
     kf.set("forcelangcopy", "+");
     kf.set("version", "8");
     verchange = false;
   }
   if (kf.getBoolean("forcelangcopy")) {
     KFA.lf.insert(new LangFile(KFA.getFileStream(MyPlugin.pl, "lang.lng")));
     kf.set("forcelangcopy", "-");
   }
   kf.repair_missing = true;
   opperms = kf.getBoolean("permissions.op", true);
   dfcheck = kf.getBoolean("permissions.disableflagcheck", true);
   silktouch = kf.getBoolean("creatorblock.silktouch", true);
   ProtectionCore.movecheckrate = (int)kf.getLong("movecheckrate", 10L);
   try {
     String[] tool = (kf.get("tools.wand", "271") + ":0").split("\\:");
     wandtool = KFA.srv.createItemStack(Integer.valueOf(tool[0]).intValue(), 1, Integer.valueOf(tool[1]).intValue());
     tool = (kf.get("tools.info", "268") + ":0").split("\\:");
     infotool = KFA.srv.createItemStack(Integer.valueOf(tool[0]).intValue(), 1, Integer.valueOf(tool[1]).intValue());
   }
   catch (Throwable e) {
     System.out.println("[ProtectionCore] Error in configuration, the tools aren't defined properly");
     e.printStackTrace();
   }
   limits = new int[0];
   for (String s : kf.get("regionlimits").split("\\ ")) {
     try {
       limits = ArrayUtils.add(limits, Integer.valueOf(s).intValue());
     }
     catch (Throwable e) {
       System.out.println("[ProtectionCore] Error the limit \"" + s + "\" is not number!");
     }
   }
   kf.save();
 }
コード例 #21
0
  @Transactional
  public void deleteInBatch(Iterable<M> entities) {
    Iterator iter = entities.iterator();
    if ((entities == null) || (!iter.hasNext())) {
      return;
    }
    Serializable[] ids = null;
    while (iter.hasNext()) {
      try {
        ids =
            (Serializable[])
                (Serializable[])
                    ArrayUtils.add(ids, BeanUtils.getProperty(iter.next(), this.idName));
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

    delete(ids);
  }
コード例 #22
0
ファイル: QuickCheck.java プロジェクト: sbukharov/quickCheck
    @Override
    public void mouseClicked(MouseEvent arg0) {
      int loops = errListModel.getSize();
      int skipped = 0;
      for (int j = 0; j <= loops; j++) {
        errorsList.setSelectedIndex(0 + skipped);
        if (correctionsListModel.getSize() > 0) {
          correctionsList.setSelectedIndex(0);

          // String correction = correctionsList.getSelectedValue();
          String correction = correctionsListModel.getElementAt(0);
          // String error = errorsList.getSelectedValue();
          String error = errListModel.getElementAt(0);

          char[] inputAsChars = text.getText().toCharArray();
          int errIndex = getErrorIndex(error, inputAsChars);

          for (int i = 0; i < error.length(); i++) {
            inputAsChars = ArrayUtils.remove(inputAsChars, errIndex);
          }

          for (int i = 0; i < correction.length(); i++) {
            inputAsChars =
                ArrayUtils.add(
                    inputAsChars, errIndex, correction.charAt(correction.length() - i - 1));
          }

          // correctionsListModel.clear();
          errListModel.clear();
          correctionsListModel.clear();

          text.setText(new String(inputAsChars));
          correctionsList.setSelectedIndex(0);
        } else {
          skipped++;
        }
        errorsList.setSelectedIndex(0);
      }
    }
コード例 #23
0
  @Test
  public void testHas1Pin() {
    InputStream is = this.getClass().getResourceAsStream("/json_test/user_profile_json.txt");

    Profile profile = JsonParser.parseProfile(is);
    DashBoard dash = profile.dashBoards[0];
    dash.isActive = true;

    Button button = dash.getWidgetByType(Button.class);
    assertEquals(1, button.pin);
    assertEquals(PinType.DIGITAL, button.pinType);
    assertEquals("1", button.value);

    dash.update("dw 1 0".replaceAll(" ", StringUtils.BODY_SEPARATOR_STRING));
    assertEquals("0", button.value);

    dash.update("aw 1 1".replaceAll(" ", StringUtils.BODY_SEPARATOR_STRING));
    assertEquals("0", button.value);

    dash.update("dw 1 1".replaceAll(" ", StringUtils.BODY_SEPARATOR_STRING));
    assertEquals("1", button.value);

    RGB rgb = new RGB();
    rgb.pins = new Pin[3];
    rgb.pins[0] = new Pin();
    rgb.pins[0].pin = 0;
    rgb.pins[0].pinType = PinType.VIRTUAL;
    rgb.pins[1] = new Pin();
    rgb.pins[1].pin = 1;
    rgb.pins[1].pinType = PinType.VIRTUAL;
    rgb.pins[2] = new Pin();
    rgb.pins[2].pin = 2;
    rgb.pins[2].pinType = PinType.VIRTUAL;

    dash.widgets = ArrayUtils.add(dash.widgets, rgb);

    dash.update("vw 0 100".replaceAll(" ", StringUtils.BODY_SEPARATOR_STRING));
    dash.update("vw 1 101".replaceAll(" ", StringUtils.BODY_SEPARATOR_STRING));
    dash.update("vw 2 102".replaceAll(" ", StringUtils.BODY_SEPARATOR_STRING));

    for (int i = 0; i < rgb.pins.length; i++) {
      assertEquals("10" + i, rgb.pins[i].value);
    }

    rgb = new RGB();
    rgb.pins = new Pin[3];
    rgb.pins[0] = new Pin();
    rgb.pins[0].pin = 4;
    rgb.pins[0].pinType = PinType.VIRTUAL;
    rgb.pins[1] = new Pin();
    rgb.pins[1].pin = 4;
    rgb.pins[1].pinType = PinType.VIRTUAL;
    rgb.pins[2] = new Pin();
    rgb.pins[2].pin = 4;
    rgb.pins[2].pinType = PinType.VIRTUAL;

    dash.widgets = ArrayUtils.add(dash.widgets, rgb);

    dash.update("vw 4 100 101 102".replaceAll(" ", StringUtils.BODY_SEPARATOR_STRING));

    assertEquals(
        "100 101 102".replaceAll(" ", StringUtils.BODY_SEPARATOR_STRING), rgb.pins[0].value);
  }
コード例 #24
0
 public static void registerKeyBinding(KeyBinding key) {
   Minecraft.getMinecraft().gameSettings.keyBindings =
       ArrayUtils.add(Minecraft.getMinecraft().gameSettings.keyBindings, key);
 }
コード例 #25
0
  /**
   * 處理確定加選學生選課內容之方法
   *
   * @param mapping org.apache.struts.action.ActionMapping object
   * @param form org.apache.struts.action.ActionForm object
   * @param request javax.servlet.http.HttpServletRequest object
   * @param response javax.servlet.http.HttpServletResponse object
   * @return org.apache.struts.action.ActionForward object
   * @exception java.lang.Exception
   */
  public ActionForward add(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    CourseManager cm = (CourseManager) getBean(COURSE_MANAGER_BEAN_NAME);
    HttpSession session = request.getSession(false);
    DynaActionForm aForm = (DynaActionForm) form;
    Seld seld = processSeldByForm(aForm);
    session.setAttribute("seldInfoForOnline", seld);
    Dtime dtime = cm.findDtimeBy(seld.getDtimeOid());

    ActionMessages messages = validateInputForUpdate(aForm, Toolket.getBundle(request));
    if (!messages.isEmpty()) {
      saveErrors(request, messages);
      return mapping.findForward(IConstants.ACTION_MAIN_NAME);
    } else {
      try {
        // 會以紙本作業完成加選,無需考慮衝堂問題
        // 選課人數上線於前端JavaScript判斷
        // 跨選設定不允許須阻擋並顯示訊息
        // 會顯示衝堂訊息
        MemberManager mm = (MemberManager) getBean(MEMBER_MANAGER_BEAN_NAME);
        ScoreManager sm = (ScoreManager) getBean(IConstants.SCORE_MANAGER_BEAN_NAME);
        Student student = mm.findStudentByNo(seld.getStudentNo());
        ScoreHist scoreHist = new ScoreHist(student.getStudentNo());
        List<ScoreHist> scoreHistList = sm.findScoreHistBy(scoreHist);
        String[] cscodeHist = new String[0];
        Float[] scoreList = new Float[0];
        float passScore = Toolket.getPassScoreByDepartClass(student.getDepartClass());
        for (ScoreHist hist : scoreHistList) {
          cscodeHist = (String[]) ArrayUtils.add(cscodeHist, hist.getCscode().toUpperCase());
          // 抵免要給分數,不然就會被當做無修課記錄而被加選成功
          if ("6".equals(hist.getEvgrType()))
            scoreList =
                (Float[])
                    ArrayUtils.add(
                        scoreList, hist.getScore() != null ? hist.getScore() : passScore);
          else scoreList = (Float[]) ArrayUtils.add(scoreList, hist.getScore());
        }

        int ind = 0, startIndex = 0;
        boolean isHist = false;
        do {
          ind = ArrayUtils.indexOf(cscodeHist, seld.getCscode().toUpperCase(), startIndex);
          startIndex = ind + 1;
          // 判斷是否選過且及格
          isHist =
              ind != StringUtils.INDEX_NOT_FOUND
                  && scoreList[ind] != null
                  && scoreList[ind] >= passScore;
        } while (!isHist && ind != StringUtils.INDEX_NOT_FOUND);

        // 特殊班級(跨校生等)無條件加選
        String[] specialDepartClass = {"1152A", "1220", "122A", "122B", "2220"};
        String[] addGrade = {"42", "52"}; // 2技學生年級要+2
        int stuGrade =
            ArrayUtils.contains(specialDepartClass, student.getDepartClass())
                ? 9
                : Integer.parseInt(StringUtils.substring(student.getDepartClass(), 4, 5));
        stuGrade =
            ArrayUtils.contains(addGrade, StringUtils.substring(student.getDepartClass(), 1, 3))
                ? stuGrade + 2
                : stuGrade;
        int dtimeGrade = Integer.parseInt(StringUtils.substring(dtime.getDepartClass(), 4, 5));

        if (isHist) {
          messages.add(
              ActionMessages.GLOBAL_MESSAGE,
              new ActionMessage("Course.errorN1", "歷年資料查詢到已修過該科目,請確認,謝謝!!"));
          saveErrors(request, messages);
        } else if (stuGrade >= dtimeGrade) {
          // 判斷學生年級與課程所開班級年級
          cm.txAddSelectedSeld(seld, student, "1", true);
          String idno = getUserCredential(request.getSession(false)).getMember().getIdno();
          cm.txSaveAdcdHistory(seld.getDtimeOid(), student.getStudentNo().toUpperCase(), idno, "A");
          if (ind != StringUtils.INDEX_NOT_FOUND)
            messages.add(
                ActionMessages.GLOBAL_MESSAGE,
                new ActionMessage("Course.errorN1", "該科目於歷年資料有查詢到,但該科目未及格,所以加選成功。"));
          else
            messages.add(
                ActionMessages.GLOBAL_MESSAGE, new ActionMessage("Message.CreateSuccessful"));
          saveMessages(request, messages);
        } else {
          messages.add(
              ActionMessages.GLOBAL_MESSAGE,
              new ActionMessage(
                  "Course.messageN1",
                  "注意:學生低修高年級課程,加選作業尚未完成!<br/>"
                      + "&nbsp;&nbsp;&nbsp;&nbsp;按下[再次確定]鍵後課程才會加入學生選課資料中。"));
          saveErrors(request, messages);
          setContentPage(request.getSession(false), "course/OnlineAddHigherCourse.jsp");
          return mapping.findForward(IConstants.ACTION_MAIN_NAME);
        }

        Toolket.resetCheckboxCookie(response, SELD_LIST_NAME);
        return list(mapping, form, request, response);
      } catch (SeldException se) {
        ActionMessages errors = new ActionMessages();
        errors.add(
            ActionMessages.GLOBAL_MESSAGE, new ActionMessage("Course.errorN1", se.getMessage()));
        saveErrors(request, errors);
        if (se.getMessage().indexOf("衝堂") != StringUtils.INDEX_NOT_FOUND) {
          // 目前會拒絕衝堂課程進行加選
          dtime = cm.findDtimeBy(seld.getDtimeOid());
          Csno csno = cm.findCourseInfoByCscode(dtime.getCscode());
          request.setAttribute("csnoInfo", csno);
          request.setAttribute("classInfo", Toolket.getClassFullName(dtime.getDepartClass()));
          setContentPage(request.getSession(false), "course/ConflictList.jsp");
          return list(mapping, form, request, response);
        } else return list(mapping, form, request, response);
      }
    }
  }
コード例 #26
0
 public String[] getResourceKeys() {
   return ArrayUtils.add(super.getResourceKeys(), EVENT_RESOURCE_KEY);
 }