Example #1
0
  /**
   * 获取资源的服务器访问地址
   *
   * @param id 资源的服务器存储hash ID
   * @param fileType 文件类型,image、audio和video
   * @param size 文件尺寸
   * @return
   */
  public static String getResourceUrl(String id, String fileType, String... size) {
    StringBuffer urlSb = new StringBuffer();
    String sizeUrl = size.length > 0 ? "_" + size[0] : "";
    if (StringUtils.isNoneBlank(id)) {
      urlSb
          .append(SystemGlobal.IMAGE_DOMAIN)
          .append(File.separator)
          .append(fileType)
          .append(File.separator)
          .append(StringUtils.substring(id, 0, 1))
          .append(File.separator)
          .append(StringUtils.substring(id, 1, 3))
          .append(File.separator)
          .append(StringUtils.substring(id, 3, 5))
          .append(File.separator);

      if (fileType.equals(FileType.AUDIO.value)) {

        urlSb.append(id).append(sizeUrl).append(Constant.FileType.OUTPUT_AUDIO_SUFFIX_NAME);

      } else if (fileType.equals(FileType.VIDEO.value)) {

        urlSb.append(id).append(sizeUrl).append(Constant.FileType.OUTPUT_VIDEO_SUFFIX_NAME);

      } else {

        urlSb.append(id).append(sizeUrl).append(Picture.PICTURE_SUFFIX_NAME);
      }
    }
    return urlSb.toString();
  }
  private List<String> split(String source) {
    if (source == null) {
      return null;
    }

    int currentIndex = 0;
    Integer startDelimiterIndex = null;
    List<String> splitedList = new ArrayList<String>();
    for (int index = 0; index < source.length(); index++) {
      if (source.charAt(index) == START_DELIMITER) {
        startDelimiterIndex = index;
      } else if (startDelimiterIndex != null && source.charAt(index) == END_DELIMITER) {
        if (currentIndex != startDelimiterIndex) {
          splitedList.add(StringUtils.substring(source, currentIndex, startDelimiterIndex));
        }
        splitedList.add(StringUtils.substring(source, startDelimiterIndex, index + 1));
        currentIndex = index + 1;
        startDelimiterIndex = null;
      }
    }

    if (currentIndex < source.length() - 1) {
      splitedList.add(StringUtils.substring(source, currentIndex));
    }

    return splitedList;
  }
 public String shorten(String longUrl, int urlLength) {
   if (urlLength < 0 || urlLength > 6) {
     throw new IllegalArgumentException("the length of url must be between 0 and 6");
   }
   String md5Hex = DigestUtils.md5Hex(longUrl);
   // 6 digit binary can indicate 62 letter & number from 0-9a-zA-Z
   int binaryLength = urlLength * 6;
   long binaryLengthFixer = Long.valueOf(StringUtils.repeat("1", binaryLength), BINARY);
   for (int i = 0; i < 4; i++) {
     String subString = StringUtils.substring(md5Hex, i * 8, (i + 1) * 8);
     subString = Long.toBinaryString(Long.valueOf(subString, 16) & binaryLengthFixer);
     subString = StringUtils.leftPad(subString, binaryLength, "0");
     StringBuilder sbBuilder = new StringBuilder();
     for (int j = 0; j < urlLength; j++) {
       String subString2 = StringUtils.substring(subString, j * 6, (j + 1) * 6);
       int charIndex = Integer.valueOf(subString2, BINARY) & NUMBER_61;
       sbBuilder.append(DIGITS[charIndex]);
     }
     String shortUrl = sbBuilder.toString();
     if (lookupLong(shortUrl) != null) {
       continue;
     } else {
       return shortUrl;
     }
   }
   // if all 4 possibilities are already exists
   return null;
 }
 /**
  * *
  * <li><b>Substring/Left/Right/Mid</b> - null-safe substring extractions
  * <li><b>SubstringBefore/SubstringAfter/SubstringBetween</b> - substring extraction relative to
  *     other strings
  */
 @Test
 public void testSubstringLeftStringUtils() {
   System.out.println(strOne + ":" + strOne.length());
   System.out.println(StringUtils.substring(strOne, 3));
   System.out.println(StringUtils.substring(strOne, 3, 7));
   System.out.println(StringUtils.substringAfter(strOne, " "));
   System.out.println(StringUtils.substringAfterLast(strOne, " "));
   System.out.println(StringUtils.substringBefore(strOne, " "));
   System.out.println(StringUtils.substringBeforeLast(strOne, " "));
   System.out.println(StringUtils.substringBetween(strOne, "the", "not"));
 }
  private FormattedText getFormattedText(String source, char delimiter, FormattedText.Type type) {
    int delimiterIndex = StringUtils.indexOf(source, delimiter);
    if (delimiterIndex < 0) {
      return getPlainText(source);
    }

    String link = StringUtils.substring(source, 1, delimiterIndex);
    String text = StringUtils.substring(source, delimiterIndex + 1, source.length() - 1);

    return new FormattedText(text, type, link);
  }
Example #6
0
 public static String formatTextData(String text, int col) {
   if (StringUtils.isEmpty(text)) {
     return "";
   }
   if (col <= 1) {
     return StringUtils.substring(text, 1, text.length() - 1);
   } else if (col == 2) {
     return StringUtils.substring(text, 0, text.length() - 2);
   }
   return text;
 }
  /**
   * @param filterName
   * @param value
   */
  public PropertyFilter(final String filterName, final String value) {

    String matchTypeStr;
    String matchPattenCode = LikeMatchPatten.ALL.toString();
    String matchTypeCode;
    String propertyTypeCode;

    if (filterName.contains("LIKE") && filterName.charAt(0) != 'L') {
      matchTypeStr = StringUtils.substringBefore(filterName, PARAM_PREFIX);
      matchPattenCode = StringUtils.substring(matchTypeStr, 0, 1);
      matchTypeCode = StringUtils.substring(matchTypeStr, 1, matchTypeStr.length() - 1);
      propertyTypeCode =
          StringUtils.substring(matchTypeStr, matchTypeStr.length() - 1, matchTypeStr.length());
    } else {
      matchTypeStr = StringUtils.substringBefore(filterName, PARAM_PREFIX);
      matchTypeCode = StringUtils.substring(matchTypeStr, 0, matchTypeStr.length() - 1);
      propertyTypeCode =
          StringUtils.substring(matchTypeStr, matchTypeStr.length() - 1, matchTypeStr.length());
    }

    try {
      matchType = Enum.valueOf(MatchType.class, matchTypeCode);
      likeMatchPatten = Enum.valueOf(LikeMatchPatten.class, matchPattenCode);
    } catch (RuntimeException e) {
      throw new IllegalArgumentException(
          "filter name: "
              + filterName
              + "Not prepared in accordance with rules, not get more types of property.",
          e);
    }

    try {
      propertyType = Enum.valueOf(PropertyType.class, propertyTypeCode).getValue();
    } catch (RuntimeException e) {
      throw new IllegalArgumentException(
          "filter name: "
              + filterName
              + "Not prepared in accordance with the rules, attribute value types can not be.",
          e);
    }

    String propertyNameStr = StringUtils.substringAfter(filterName, PARAM_PREFIX);
    propertyNames = StringUtils.split(propertyNameStr, PropertyFilter.OR_SEPARATOR);

    Validate.isTrue(
        propertyNames.length > 0,
        "filter name: "
            + filterName
            + "Not prepared in accordance with the rules, property names can not be.");
    this.propertyValue = ConvertUtils.convert(value, propertyType);
  }
 /**
  * Computes the best file to save the response to the given URL.
  *
  * @param url the requested URL
  * @param extension the preferred extension
  * @return the file to create
  * @throws IOException if a problem occurs creating the file
  */
 private File createFile(final URL url, final String extension) throws IOException {
   String name = url.getPath().replaceFirst("/$", "").replaceAll(".*/", "");
   name = StringUtils.substringBefore(name, "?"); // remove query
   name = StringUtils.substringBefore(name, ";"); // remove additional info
   name = StringUtils.substring(name, 0, 30); // avoid exceptions due to too long file names
   if (!name.endsWith(extension)) {
     name += extension;
   }
   int counter = 0;
   while (true) {
     final String fileName;
     if (counter != 0) {
       fileName =
           StringUtils.substringBeforeLast(name, ".")
               + "_"
               + counter
               + "."
               + StringUtils.substringAfterLast(name, ".");
     } else {
       fileName = name;
     }
     final File f = new File(reportFolder_, fileName);
     if (f.createNewFile()) {
       return f;
     }
     counter++;
   }
 }
 private String getRealNumWithTwo(String number) {
   int index = 0;
   if ((index = StringUtils.indexOf(number, ".")) != -1) {
     return StringUtils.substring(number, 0, index + 2);
   }
   return number;
 }
  /**
   * Parse {@link org.joda.time.DateTime} from {@link org.apache.hadoop.fs.Path} using datetime
   * pattern.
   */
  @Override
  public TimestampedDatasetVersion getDatasetVersion(
      Path pathRelativeToDatasetRoot, FileStatus versionFileStatus) {

    String dateTimeString = null;
    try {
      // pathRelativeToDatasetRoot can be daily/2016/03/02 or 2016/03/02. In either case we need to
      // pick 2016/03/02 as version
      dateTimeString =
          StringUtils.substring(
              pathRelativeToDatasetRoot.toString(),
              pathRelativeToDatasetRoot.toString().length() - this.datePartitionPattern.length());

      return new FileStatusTimestampedDatasetVersion(
          this.formatter.parseDateTime(dateTimeString), versionFileStatus);

    } catch (IllegalArgumentException exception) {
      LOGGER.warn(
          String.format(
              "Candidate dataset version with pathRelativeToDatasetRoot: %s has inferred dataTimeString:%s. "
                  + "It does not match expected datetime pattern %s. Ignoring.",
              pathRelativeToDatasetRoot, dateTimeString, this.datePartitionPattern));
      return null;
    }
  }
 public void writePacketData(PacketBuffer data) throws IOException {
   data.writeString(StringUtils.substring(this.message, 0, 32767));
   boolean var2 = this.field_179710_b != null;
   data.writeBoolean(var2);
   if (var2) {
     data.writeBlockPos(this.field_179710_b);
   }
 }
 private String extractZETAISBN(String pageText) {
   int indexISBN = StringUtils.indexOfIgnoreCase(pageText, "ISBN");
   int indexOf = StringUtils.indexOf(pageText, " ", indexISBN + 15);
   if (indexOf > -1 && indexOf > indexISBN) {
     return StringUtils.substring(pageText, indexISBN, indexOf);
   }
   return "";
 }
  /** Writes the raw packet data to the data stream. */
  public void writePacketData(PacketBuffer buf) throws IOException {
    buf.writeString(StringUtils.substring(this.message, 0, 32767));
    boolean flag = this.targetBlock != null;
    buf.writeBoolean(flag);

    if (flag) {
      buf.writeBlockPos(this.targetBlock);
    }
  }
Example #14
0
 /**
  * 将用户登录名展示在actionbar上,长度大于14用。。。表示
  *
  * @return
  */
 public static String showTitileName() {
   if (StringUtils.isNotEmpty(HttpClientUtil.getAccount().getName())) {
     if (HttpClientUtil.getAccount().getName().length() <= 14) {
       return HttpClientUtil.getAccount().getName();
     } else {
       return StringUtils.substring(HttpClientUtil.getAccount().getName(), 0, 14) + "..";
     }
   }
   return null;
 }
Example #15
0
 protected static String getCreditCardNumber() {
   String pan = credit_card_number(VISA_PREFIX_LIST, 16, 1)[0];
   for (; ; ) {
     if (Integer.parseInt(StringUtils.substring(pan, -2)) < 60 && modNineCheck(pan)) {
       break;
     }
     pan = credit_card_number(VISA_PREFIX_LIST, 16, 1)[0];
   }
   return pan;
 }
Example #16
0
 @Test
 public void testPath() throws Exception {
   String packName = "com.mo008.wx.controllers.api";
   String appPackPrefix = "com.mo008";
   final String path =
       StringUtils.substring(
           packName,
           StringUtils.length(appPackPrefix + "."),
           StringUtils.indexOf(packName, ".controllers"));
   System.out.println("path = " + path);
 }
  /**
   * 处理请求zk的路径
   *
   * @param path 路径
   * @return String
   */
  private String processZkPath(String path) {
    if (StringUtils.endsWith(path, "/")) {
      path = StringUtils.substring(path, 0, StringUtils.lastIndexOf(path, "/"));
    }
    path = StringUtils.trimToEmpty(path);
    if (StringUtils.isEmpty(path)) {
      path = "/";
    }

    return path;
  }
Example #18
0
 /**
  * 获取图片的服务器访问地址
  *
  * @param id 图片的存储ID
  * @param size 图片的尺寸
  * @param suffixName 图片的后缀名
  * @return
  */
 public static String getPicUrl(String id, String size, String suffixName) {
   StringBuffer urlSb = new StringBuffer();
   if (StringUtils.isNoneBlank(id)) {
     urlSb
         .append(SystemGlobal.IMAGE_DOMAIN)
         .append(File.separator)
         .append(StringUtils.substring(id, 0, 1))
         .append(File.separator)
         .append(StringUtils.substring(id, 1, 3))
         .append(File.separator)
         .append(StringUtils.substring(id, 3, 5))
         .append(File.separator)
         .append(id)
         .append(id)
         .append("_")
         .append(size)
         .append(".")
         .append(suffixName);
   }
   return urlSb.toString();
 }
Example #19
0
 private static <T> Pair<T, BoundType> parseLowerBoundary(
     String lower, Function<String, T> parser) {
   BoundType bound;
   String value;
   if (lower.length() > 1) {
     String boundChar = StringUtils.left(lower, 1);
     if ("(".equals(boundChar) || "[".equals(boundChar)) {
       bound = BoundType.CLOSED;
       value = StringUtils.substring(lower, 1);
     } else if (")".equals(boundChar) || "]".equals(boundChar)) {
       bound = BoundType.OPEN;
       value = StringUtils.substring(lower, 1);
     } else {
       bound = BoundType.CLOSED;
       value = lower;
     }
   } else {
     bound = BoundType.CLOSED;
     value = lower;
   }
   return Pair.of(parser.apply(value), bound);
 }
Example #20
0
  /**
   * parse maxmind asn result
   *
   * @return ASXXXX formatted string
   */
  private String parseASN(String asn) {

    if (asn != null) {
      int pos = StringUtils.indexOf(asn, ' ');
      if (pos != -1) {
        return StringUtils.substring(asn, 0, pos);
      }
      // not a valid asn string
      return "UNKN";
    }
    // not found
    return null;
  }
  public void testTCPClient() {
    String result;
    String comando;
    TCPClient tcpclient = new TCPClient();
    try {

      /**
       * Este teste pega uma palavra válida de comando, faz o cálculo do checksum e envia para o CLP
       * acionando a classe TCPClient.
       *
       * <p>Estes comandos... comando = ccsum.calcCheckSum("00SA00000C101010101010",12874); comando
       * = ccsum.calcCheckSum("00SA00000C010101010101",12874); comando =
       * ccsum.calcCheckSum("00RA00000C",12874); comando = ccsum.calcCheckSum("00RC",12874);
       *
       * <p>Após o cálculo do checksum (ccsum), assumem esses valores:
       * tcpclient.sendCLP("/00SA00000C1010101010106D");
       * tcpclient.sendCLP("/00SA00000C0101010101016D"); tcpclient.sendCLP("/00RA00000C26");
       * tcpclient.sendCLP("/00RCF5");
       */
      CalcCheckSum ccsum = new CalcCheckSum();
      comando = ccsum.calcCheckSum("00SA00000C101010101010", 12874);

      result = tcpclient.sendCLP(comando);
      System.out.println("Resultado retornado pela classe TCPClient: " + result);

      checkSend = StringUtils.substring(comando, 8, 12);
      checkReturn = StringUtils.substring(result, 2, 6);

      assertEquals(checkReturn, checkSend);

    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      assertEquals(true, false);
    }
  }
Example #22
0
 /**
  * @param color
  * @return
  */
 public static Color getColorFromString(final String color) {
   if (StringUtils.equalsIgnoreCase(color, TRANSPARENT_KEY)) {
     return Color.WHITE;
   }
   String[] comps =
       StringUtils.substring(
               color,
               StringUtils.indexOf(color, OPEN_PARENTHESE) + 1,
               StringUtils.indexOf(color, CLOSE_PARENTHESE))
           .split(COMPOSANT_SEPARATOR);
   return new Color(
       Integer.valueOf(comps[0].trim()),
       Integer.valueOf(comps[1].trim()),
       Integer.valueOf(comps[2].trim()));
 }
 @Override
 public void doFilter(
     ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
     throws IOException, ServletException {
   HttpServletRequest request = (HttpServletRequest) servletRequest;
   HttpServletResponse response = (HttpServletResponse) servletResponse;
   String currentURL = request.getRequestURI();
   String realUrl = StringUtils.remove(currentURL, request.getContextPath());
   boolean isCheck = true;
   NoCheckUrlEnum[] noCheckUrlEnums = NoCheckUrlEnum.values();
   for (NoCheckUrlEnum noCheckUrlEnum : noCheckUrlEnums) {
     if (noCheckUrlEnum.getCode().equals(realUrl)) {
       isCheck = false;
       break;
     }
   }
   if (isCheck) {
     HttpSession session = request.getSession(false);
     if (session == null) {
       response.sendRedirect(request.getContextPath() + LOGIN_ACTION);
       return;
     }
     BaseAdminContext baseAdminContext =
         (BaseAdminContext) session.getAttribute(AdminSystemConstant.ADMIN_SYSTEM_SESSION_KEY);
     if (baseAdminContext == null) {
       response.sendRedirect(request.getContextPath() + LOGIN_ACTION);
       return;
     } else {
       realUrl = StringUtils.remove(realUrl, ".action");
       int i = StringUtils.indexOf(realUrl, "_");
       if (i != -1) {
         realUrl = StringUtils.substring(realUrl, 0, i + 1);
       }
       if (!baseAdminContext.allow(realUrl)) {
         response.sendRedirect(request.getContextPath() + NO_PURVIEW);
         return;
       }
     }
   }
   chain.doFilter(request, response);
 }
 /**
  * 注解到对象复制,只复制能匹配上的方法。
  *
  * @param annotation
  * @param object
  */
 public static void annotationToObject(Object annotation, Object object) {
   if (annotation != null) {
     Class<?> annotationClass = annotation.getClass();
     Class<?> objectClass = object.getClass();
     for (Method m : objectClass.getMethods()) {
       if (StringUtils.startsWith(m.getName(), "set")) {
         try {
           String s = StringUtils.uncapitalize(StringUtils.substring(m.getName(), 3));
           Object obj = annotationClass.getMethod(s).invoke(annotation);
           if (obj != null && !"".equals(obj.toString())) {
             if (object == null) {
               object = objectClass.newInstance();
             }
             m.invoke(object, obj);
           }
         } catch (Exception e) {
           // 忽略所有设置失败方法
         }
       }
     }
   }
 }
  @EventHandler(priority = EventPriority.MONITOR)
  public void onPlayerJoin(PlayerJoinEvent event) {
    final Player player = event.getPlayer();
    final String ip = TFM_Util.getIp(player);
    final TFM_Player playerEntry;
    TFM_Log.info(
        "[JOIN] " + TFM_Util.formatPlayer(player) + " joined the game with IP address: " + ip,
        true);
    // Check absolute value to account for negatives
    if (Math.abs(player.getLocation().getX()) >= MAX_XY_COORD
        || Math.abs(player.getLocation().getZ()) >= MAX_XY_COORD) {
      player.teleport(player.getWorld().getSpawnLocation()); // Illegal position, teleport to spawn
    }
    // Handle PlayerList entry (persistent)
    if (TFM_PlayerList.existsEntry(player)) {
      playerEntry = TFM_PlayerList.getEntry(player);
      playerEntry.setLastLoginUnix(TFM_Util.getUnixTime());
      playerEntry.setLastLoginName(player.getName());
      playerEntry.addIp(ip);
      playerEntry.save();
    } else {
      playerEntry = TFM_PlayerList.getEntry(player);
      TFM_Log.info("Added new player: " + TFM_Util.formatPlayer(player));
    }

    // Generate PlayerData (non-persistent)
    final TFM_PlayerData playerdata = TFM_PlayerData.getPlayerData(player);
    playerdata.setSuperadminIdVerified(false);

    if (TFM_AdminList.isSuperAdmin(player)) {
      for (String storedIp : playerEntry.getIps()) {
        TFM_BanManager.unbanIp(storedIp);
        TFM_BanManager.unbanIp(TFM_Util.getFuzzyIp(storedIp));
      }

      TFM_BanManager.unbanUuid(TFM_UuidManager.getUniqueId(player));

      player.setOp(true);

      // Verify strict IP match
      if (!TFM_AdminList.isIdentityMatched(player)) {
        playerdata.setSuperadminIdVerified(false);
        TFM_Util.bcastMsg(
            "Warning: "
                + player.getName()
                + " is an admin, but is using an account not registered to one of their ip-list.",
            ChatColor.RED);
      } else {
        playerdata.setSuperadminIdVerified(true);
        TFM_AdminList.updateLastLogin(player);
      }
    }

    TFM_PlayerData.getPlayerData(player).setCommandSpy(true);

    // Handle admin impostors
    if (TFM_AdminList.isAdminImpostor(player)) {
      TFM_Util.bcastMsg(
          "Warning: " + player.getName() + " has been flagged as an impostor and has been frozen!",
          ChatColor.RED);
      TFM_Util.bcastMsg(
          ChatColor.AQUA + player.getName() + " is " + TFM_PlayerRank.getLoginMessage(player));
      player.getInventory().clear();
      player.setOp(false);
      player.setGameMode(GameMode.SURVIVAL);
      TFM_PlayerData.getPlayerData(player).setFrozen(true);
    } else if (TFM_AdminList.isSuperAdmin(player)
        || TFM_Util.DEVELOPERS.contains(player.getName())) {
      TFM_Util.bcastMsg(
          ChatColor.AQUA + player.getName() + " is " + TFM_PlayerRank.getLoginMessage(player));
    }

    // TODO: Cleanup
    String name = player.getName();
    if (TFM_Util.DEVELOPERS.contains(player.getName())) {
      name = ChatColor.DARK_PURPLE + name;
      TFM_PlayerData.getPlayerData(player).setTag("&8[&5Developer&8]");
    }
    if (TFM_Util.EXECUTIVES.contains(player.getName())) {
      name = ChatColor.DARK_BLUE + name;
      TFM_PlayerData.getPlayerData(player).setTag("&8[&1Executive&8]");
    }
    if (TFM_Util.MANAGERS.contains(player.getName())) {
      name = ChatColor.DARK_RED + name;
      TFM_PlayerData.getPlayerData(player).setTag("&8[&4Admin Manager&8]");
    } else if (TFM_AdminList.isSuperAdmin(player)) {
      if (TFM_ConfigEntry.SERVER_OWNERS.getList().contains(name)) {
        name = ChatColor.BLUE + name;
        TFM_PlayerData.getPlayerData(player).setTag("&8[&9Owner&8]");
      } else if (TFM_AdminList.isSeniorAdmin(player)) {
        name = ChatColor.LIGHT_PURPLE + name;
        TFM_PlayerData.getPlayerData(player).setTag("&8[&dSenior Admin&8]");
      } else if (TFM_AdminList.isTelnetAdmin(player, true)) {
        name = ChatColor.DARK_GREEN + name;
        TFM_PlayerData.getPlayerData(player).setTag("&8[&2Telnet Admin&8]");
      } else {
        name = ChatColor.AQUA + name;
        TFM_PlayerData.getPlayerData(player).setTag("&8[&BSuper Admin&8]");
      }
    }

    try {
      player.setPlayerListName(StringUtils.substring(name, 0, 16));
    } catch (IllegalArgumentException ex) {
    }

    new BukkitRunnable() {
      @Override
      public void run() {
        if (TFM_ConfigEntry.ADMIN_ONLY_MODE.getBoolean()) {
          player.sendMessage(ChatColor.RED + "Server is currently closed to non-superadmins.");
        }

        if (TotalFreedomMod.lockdownEnabled) {
          TFM_Util.playerMsg(
              player,
              "Warning: Server is currenty in lockdown-mode, new players will not be able to join!",
              ChatColor.RED);
        }
      }
    }.runTaskLater(TotalFreedomMod.plugin, 20L * 1L);
  }
  /**
   * 處理確定加選學生選課內容之方法
   *
   * @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);
      }
    }
  }
Example #27
0
  public Sample parse(String sampleString) {
    Sample sample = new Sample();
    sample.setSampleString(sampleString);
    boolean infrared1AngleIsValid = false;
    boolean infrared1DistanceIsValid = false;
    boolean ultrasound1AngleIsValid = false;
    boolean ultrasound1DistanceIsValid = false;
    boolean infrared2AngleIsValid = false;
    boolean infrared2DistanceIsValid = false;
    boolean ultrasound2AngleIsValid = false;
    boolean ultrasound2DistanceIsValid = false;
    if (!isValid(sampleString)) {
      log.warn("INVALID SAMPLE! \"{}\"", sampleString);
    } else {
      String[] sampleParts = sampleString.split("[;]");
      for (String part : sampleParts) {
        String value = StringUtils.substring(part, 2);

        if ("STA".equals(part)) {
        } else if ("END".equals(part)) {
        } else if (part.startsWith("NO")) {
          int messageNumber = Integer.valueOf(value);
          sample.setMessageNumber(messageNumber);
        } else if (part.startsWith("IR")) {
          float angle = (float) Math.toRadians(Integer.parseInt(value));
          angle = angle - (float) Math.PI / 2.0f;
          sample.setInfrared1Angle(angle);
          infrared1AngleIsValid = true;
        } else if (part.startsWith("ID")) {
          float distance = parseIrSensorValue(value);
          if (distance > 20.0f && distance < 150.0f) {
            sample.setInfrared1Distance(distance);
            infrared1DistanceIsValid = true;
          }
        } else if (part.startsWith("Id")) {
          float distance = Integer.parseInt(value);
          if (distance > 20.0f && distance < 150.0f) {
            sample.setInfrared1Distance(distance);
            infrared1DistanceIsValid = true;
          }
        } else if (part.startsWith("JR")) {
          float angle = (float) Math.toRadians(Integer.parseInt(value));
          angle = angle - (float) Math.PI / 2.0f;
          sample.setInfrared2Angle(angle);
          infrared2AngleIsValid = true;
        } else if (part.startsWith("JD")) {
          float distance = parseIrSensorValue(value);
          if (distance > 20.0f && distance < 150.0f) {
            sample.setInfrared2Distance(distance);
            infrared2DistanceIsValid = true;
          }
        } else if (part.startsWith("Jd")) {
          float distance = Integer.parseInt(value);
          if (distance > 20.0f && distance < 150.0f) {
            sample.setInfrared2Distance(distance);
            infrared2DistanceIsValid = true;
          }
        } else if (part.startsWith("SR")) {
          float angle = (float) Math.toRadians(Integer.parseInt(value));
          angle = angle - (float) Math.PI / 2.0f;
          sample.setUltrasound1Angle(angle);
          ultrasound1AngleIsValid = true;
        } else if (part.startsWith("SD")) {
          float distance = parseSoundSensorValue(value);
          if (distance > 15.0f && distance < 645.0f) {
            sample.setUltrasound1Distance(distance);
            ultrasound1DistanceIsValid = true;
          }
        } else if (part.startsWith("Sd")) {
          float distance = Integer.parseInt(value);
          if (distance > 15.0f && distance < 645.0f) {
            sample.setUltrasound1Distance(distance);
            ultrasound1DistanceIsValid = true;
          }
        } else if (part.startsWith("TR")) {
          float angle = (float) Math.toRadians(Integer.parseInt(value));
          angle = angle - (float) Math.PI / 2.0f;
          sample.setUltrasound2Angle(angle);
          ultrasound2AngleIsValid = true;
        } else if (part.startsWith("TD")) {
          float distance = parseSoundSensorValue(value);
          if (distance > 15.0f && distance < 645.0f) {
            sample.setUltrasound2Distance(distance);
            ultrasound2DistanceIsValid = true;
          }
        } else if (part.startsWith("Td")) {
          float distance = Integer.parseInt(value);
          if (distance > 15.0f && distance < 645.0f) {
            sample.setUltrasound2Distance(distance);
            ultrasound2DistanceIsValid = true;
          }
        } else if (part.startsWith("CD")) {
          float compass = (float) (Math.toRadians(Integer.parseInt(value)));
          sample.setCompassDirection(compass);
        } else if (part.startsWith("Cd")) {
          float compass = (float) Math.toRadians(Integer.parseInt(value));
          sample.setCompassDirection(compass);
        } else if (part.startsWith("AX")) {
          float accelerationX = (G * ((-Integer.parseInt(value)) - 24)) / 1000;
          sample.setAccelerationX(accelerationX);
        } else if (part.startsWith("Ax")) {
          sample.setAccelerationX(Float.parseFloat(value));
        } else if (part.startsWith("AY")) {
          float accelerationY = (G * ((Integer.parseInt(value) - 59))) / 1000;
          sample.setAccelerationY(accelerationY);
        } else if (part.startsWith("Ay")) {
          sample.setAccelerationY(Float.parseFloat(value));
        } else if (part.startsWith("AZ")) {
          float accelerationZ = (G * ((-Integer.parseInt(value)) - 8)) / 1000;
          sample.setAccelerationZ(accelerationZ);
        } else if (part.startsWith("Az")) {
          sample.setAccelerationZ(Float.parseFloat(value));
        } else if (part.startsWith("GX")) {
          float gyroX = Integer.parseInt(value);
          sample.setGyroX(-gyroX / 1000);
        } else if (part.startsWith("Gx")) {
          sample.setGyroX(Float.parseFloat(value));
        } else if (part.startsWith("GY")) {
          float gyroY = Integer.parseInt(value);
          sample.setGyroY(gyroY / 1000);
        } else if (part.startsWith("Gy")) {
          sample.setGyroY(Float.parseFloat(value));
        } else if (part.startsWith("GZ")) {
          float gyroZ = Integer.parseInt(value);
          sample.setGyroZ(-gyroZ / 1000);
        } else if (part.startsWith("Gz")) {
          sample.setGyroZ(Float.parseFloat(value));
        } else if (part.startsWith("RL")) {
          int ticks = Integer.parseInt(value);
          sample.setLeftTrackTicks(ticks);
        } else if (part.startsWith("RR")) {
          int ticks = Integer.parseInt(value);
          sample.setRightTrackTicks(ticks);
        } else if (part.startsWith("SB")) {
          int intensity = Integer.parseInt(value);
          sample.setSoundIntensity(intensity);
        } else if (part.startsWith("TI")) {
          long timestampMillis = Long.parseLong(value);
          sample.setTimestampMillis(timestampMillis);
        } else if (part.startsWith("CA")) {
          byte[] imageBytes = HexToBinaryUtil.hexStringToByteArray(value);
          sample.setImageBytes(imageBytes);
          try {
            sample.setImage(ImageIO.read(new ByteArrayInputStream(imageBytes)));
          } catch (IOException iex) {
            log.error("Failed to parse image", iex);
          }
        } else {
        }
      }
      sample.setInfrared1MeasurementValid(infrared1AngleIsValid && infrared1DistanceIsValid);
      sample.setUltrasound1MeasurementValid(ultrasound1AngleIsValid && ultrasound1DistanceIsValid);
      sample.setInfrared2MeasurementValid(infrared2AngleIsValid && infrared2DistanceIsValid);
      sample.setUltrasound2MeasurementValid(ultrasound2AngleIsValid && ultrasound2DistanceIsValid);
    }
    return sample;
  }
Example #28
0
 public static String getUserAgent(HttpServletRequest request) {
   String userAgent = StringUtils.substring(request.getHeader(HttpHeaders.USER_AGENT), 0, 256);
   return userAgent;
 }
Example #29
0
 public String getName() {
   String wiki = content.toWiki(true).trim();
   return StringUtils.substring(wiki, level, wiki.length() - level * 2);
 }
  @Transactional
  @RequestMapping(
      value = "/proposalDevelopment",
      params = {"methodToCall=refresh", "refreshCaller=S2sOpportunity-LookupView"})
  public ModelAndView refresh(
      @ModelAttribute("KualiForm") ProposalDevelopmentDocumentForm form,
      BindingResult result,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    ProposalDevelopmentDocument document = form.getProposalDevelopmentDocument();
    DevelopmentProposal proposal = document.getDevelopmentProposal();
    if (form.getNewS2sOpportunity() != null
        && StringUtils.isNotEmpty(form.getNewS2sOpportunity().getOpportunityId())) {

      proposal.setS2sOpportunity(form.getNewS2sOpportunity());
      proposal.getS2sOpportunity().setDevelopmentProposal(proposal);

      // Set default S2S Submission Type
      if (StringUtils.isBlank(form.getNewS2sOpportunity().getS2sSubmissionTypeCode())) {
        String defaultS2sSubmissionTypeCode =
            getProposalTypeService().getDefaultSubmissionTypeCode(proposal.getProposalTypeCode());
        proposal.getS2sOpportunity().setS2sSubmissionTypeCode(defaultS2sSubmissionTypeCode);
        getDataObjectService()
            .wrap(proposal.getS2sOpportunity())
            .fetchRelationship("s2sSubmissionType");
      }

      final String opportunityTitle = form.getNewS2sOpportunity().getOpportunityTitle();
      String trimmedTitle =
          StringUtils.substring(
              opportunityTitle, 0, ProposalDevelopmentConstants.S2sConstants.OPP_TITLE_MAX_LENGTH);
      // Set Opportunity Title and Opportunity ID in the Sponsor & Program Information section
      proposal.setProgramAnnouncementTitle(trimmedTitle);
      proposal.setCfdaNumber(form.getNewS2sOpportunity().getCfdaNumber());
      proposal.setProgramAnnouncementNumber(form.getNewS2sOpportunity().getOpportunityId());
      form.setNewS2sOpportunity(new S2sOpportunity());
    }

    S2sOpportunity s2sOpportunity = proposal.getS2sOpportunity();

    try {
      if (s2sOpportunity != null && s2sOpportunity.getSchemaUrl() != null) {
        List<String> missingMandatoryForms =
            s2sSubmissionService.setMandatoryForms(proposal, s2sOpportunity);

        if (!CollectionUtils.isEmpty(missingMandatoryForms)) {
          globalVariableService
              .getMessageMap()
              .putError(
                  Constants.NO_FIELD,
                  KeyConstants.ERROR_IF_OPPORTUNITY_ID_IS_INVALID,
                  s2sOpportunity.getOpportunityId(),
                  StringUtils.join(missingMandatoryForms, ","));
          proposal.setS2sOpportunity(null);
        }
      }
    } catch (S2sCommunicationException ex) {
      if (ex.getErrorKey().equals(KeyConstants.ERROR_GRANTSGOV_NO_FORM_ELEMENT)) {
        ex.setMessage(s2sOpportunity.getOpportunityId());
      }
      globalVariableService
          .getMessageMap()
          .putError(Constants.NO_FIELD, ex.getErrorKey(), ex.getMessageWithParams());
      proposal.setS2sOpportunity(new S2sOpportunity());
    }
    super.save(form, result, request, response);
    return getRefreshControllerService().refresh(form);
  }