/* (non-Javadoc) * @see forge.util.StorageReaderFile#read(java.lang.String) */ @Override protected CardBlock read(String line, int i) { final String[] sParts = TextUtil.splitWithParenthesis(line.trim(), ',', 3); String name = sParts[0]; String[] numbers = sParts[1].trim().split("/"); int draftBoosters = StringUtils.isNumeric(numbers[0]) ? Integer.parseInt(numbers[0]) : 0; int sealedBoosters = StringUtils.isNumeric(numbers[1]) ? Integer.parseInt(numbers[1]) : 0; CardEdition landSet = editions.getEditionByCodeOrThrow(numbers[2]); List<CardEdition> sets = new ArrayList<CardEdition>(); List<MetaSet> metas = new ArrayList<MetaSet>(); String[] setNames = TextUtil.splitWithParenthesis(sParts[2], ' '); for (final String set : setNames) { if (set.startsWith("Meta-")) { String metaSpec = set.substring(5); boolean noDraft = metaSpec.startsWith("NoDraft-"); if (noDraft) metaSpec = metaSpec.substring(8); metas.add(new MetaSet(metaSpec, noDraft)); } else { sets.add(editions.getEditionByCodeOrThrow(set)); } } return new CardBlock(i + 1, name, sets, metas, landSet, draftBoosters, sealedBoosters); }
/** * 构造方法 * * @param request 传递 repage 参数,来记住页码 * @param response 用于设置 Cookie,记住页码 * @param defaultPageSize 默认分页大小,如果传递 -1 则为不分页,返回所有数据 */ public Page(HttpServletRequest request, HttpServletResponse response, int defaultPageSize) { // 设置页码参数(传递repage参数,来记住页码) String no = request.getParameter("pageNo"); if (StringUtils.isNumeric(no)) { CookieUtils.setCookie(response, "pageNo", no); this.setPageNo(Integer.parseInt(no)); } else if (request.getParameter("repage") != null) { no = CookieUtils.getCookie(request, "pageNo"); if (StringUtils.isNumeric(no)) { this.setPageNo(Integer.parseInt(no)); } } // 设置页面大小参数(传递repage参数,来记住页码大小) String size = request.getParameter("pageSize"); if (StringUtils.isNumeric(size)) { CookieUtils.setCookie(response, "pageSize", size); this.setPageSize(Integer.parseInt(size)); } else if (request.getParameter("repage") != null) { no = CookieUtils.getCookie(request, "pageSize"); if (StringUtils.isNumeric(size)) { this.setPageSize(Integer.parseInt(size)); } } else if (defaultPageSize != -2) { this.pageSize = defaultPageSize; } // 设置排序参数 String orderBy = request.getParameter("orderBy"); if (StringUtils.isNotBlank(orderBy)) { this.setOrderBy(orderBy); } }
@Override public final int compare(String[] o1, String[] o2) { String t1 = o1[this.index]; String t2 = o2[this.index]; if (StringUtils.isEmpty(t1) && StringUtils.isEmpty(t2)) { return 0; } if (StringUtils.isEmpty(t1)) { return 1; } if (StringUtils.isEmpty(t2)) { return -1; } if (StringUtils.isNumeric(t1) && StringUtils.isNumeric(t2)) { // 数値文字列の場合 Long o1l = Long.valueOf(t1); Long o2l = Long.valueOf(t2); return this.compareTo(o1l, o2l, this.order); } else if (t1.matches("(?:\\d+日)?(?:\\d+時間)?(?:\\d+分)?(?:\\d+秒)?")) { try { // 時刻文字列の場合 // SimpleDateFormatは24時間超えるような時刻でも正しく?パースしてくれる Date o1date = DateUtils.parseDate(t1, "ss秒", "mm分ss秒", "HH時間mm分", "dd日HH時間mm分"); Date o2date = DateUtils.parseDate(t2, "ss秒", "mm分ss秒", "HH時間mm分", "dd日HH時間mm分"); return this.compareTo(o1date, o2date, this.order); } catch (ParseException e) { e.printStackTrace(); } } // 文字列の場合 return this.compareTo(t1, t2, this.order); }
void setPtText(String value) { final int slashPos = value.indexOf('/'); if (slashPos == -1) { throw new RuntimeException(String.format("Creature '%s' has bad p/t stats", this.getName())); } this.power = value.substring(0, slashPos); this.toughness = value.substring(slashPos + 1); this.iPower = StringUtils.isNumeric(this.power) ? Integer.parseInt(this.power) : 0; this.iToughness = StringUtils.isNumeric(this.toughness) ? Integer.parseInt(this.toughness) : 0; }
public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Введите текст и программа даст инфомрацию о тексте: "); String text = reader.readLine(); if (StringUtils.isAllUpperCase(text)) System.out.println("В тексте только заглавные буквы"); if (StringUtils.isAllLowerCase(text)) System.out.println("В тексте только строчные буквы"); if (StringUtils.isNumeric(text)) System.out.println("Тест состоит из цифр"); String tempReverse = StringUtils.reverse(text); System.out.println("Перевернутый текст: " + tempReverse); int length = StringUtils.length(text); System.out.println("Длина текста: " + length); if (length >= 5) { String tempRight = StringUtils.right(text, 5); System.out.println("Первые 5 символов текста: " + tempRight); } else { System.out.println("Длина текста менее 5 символов"); } reader.close(); }
@Background void task(String r, String num, DialogInterface dialog) { if (currentAddress == null) { return; } String addressCompl = currentAddress.getSubAdminArea() != null ? currentAddress.getSubAdminArea() : currentAddress.getLocality(); List<Address> addresses = GPSUtils.getFromLocationName(getActivity(), r + ", " + num + " - " + (addressCompl)); if (addresses.isEmpty()) { toast(getString(R.string.address_not_found)); dialog.dismiss(); } else { final Address address = addresses.get(0); street = address.getThoroughfare(); if (!TextUtils.isEmpty(num) && StringUtils.isNumeric(num.substring(0, 1))) { number = num; } else { number = ""; } updateUiAdapter(address); } }
@Background void dialogNumberTask(String num1, DialogInterface dialog) { List<Address> addresses = GPSUtils.getFromLocationName( getActivity(), street + ", " + num1 + " - " + (currentAddress.getSubAdminArea() != null ? currentAddress.getSubAdminArea() : currentAddress.getLocality())); if (addresses.isEmpty()) { toast(getString(R.string.address_not_found)); dialog.dismiss(); } else { final Address address = addresses.get(0); street = address.getThoroughfare(); if (!num1.isEmpty() && StringUtils.isNumeric(num1.substring(0, 1))) { number = num1; } else { number = ""; } updateUiAdapter(address); } }
private long parseDateTime(String value, DateTimeZone timeZone) { // first check for timestamp if (value.length() > 4 && StringUtils.isNumeric(value)) { try { long time = Long.parseLong(value); return timeUnit.toMillis(time); } catch (NumberFormatException e) { throw new ElasticsearchParseException( "failed to parse date field [" + value + "] as timestamp", e); } } DateTimeFormatter parser = dateTimeFormatter.parser(); if (timeZone != null) { parser = parser.withZone(timeZone); } try { return parser.parseMillis(value); } catch (IllegalArgumentException e) { throw new ElasticsearchParseException( "failed to parse date field [" + value + "] with format [" + dateTimeFormatter.format() + "]", e); } }
/** * (inheritDoc) * * @see * org.goko.grbl.controller.configuration.serializer.AbstractGrblSerializer#fromSource(java.lang.Object) */ @Override public Double fromSource(String str) throws GkException { if (StringUtils.isNumeric(str)) { return Double.valueOf(str); } return null; }
/** * Tries to initializes the image cache. If the initialization fails the image cache remains * {@code null}. * * @param context the XWiki context */ private void initCache(XWikiContext context) { if (this.imageCache == null) { CacheConfiguration configuration = new CacheConfiguration(); configuration.setConfigurationId("xwiki.plugin.image"); // Set cache constraints. LRUEvictionConfiguration lru = new LRUEvictionConfiguration(); configuration.put(LRUEvictionConfiguration.CONFIGURATIONID, lru); String capacityParam = context.getWiki().Param("xwiki.plugin.image.cache.capacity"); if (!StringUtils.isBlank(capacityParam) && StringUtils.isNumeric(capacityParam.trim())) { try { this.capacity = Integer.parseInt(capacityParam.trim()); } catch (NumberFormatException e) { LOG.warn( String.format( "Failed to parse xwiki.plugin.image.cache.capacity configuration parameter. " + "Using %s as the cache capacity.", this.capacity), e); } } lru.setMaxEntries(this.capacity); try { this.imageCache = context.getWiki().getLocalCacheFactory().newCache(configuration); } catch (CacheException e) { LOG.error("Error initializing the image cache.", e); } } }
/** * This method is used to help in converting a complex object's data into a JSON string * * @param data The submitted data as a string * @return The JSON equivalent of the submitted string */ private String applyRegEx(String data) { // regular expresion for getting property names String elementPart = "([\\w]*:)"; // regular expression for getting the values String elValuePart = "(:)([\\w]*)"; // apply regular expressions to patterns Pattern elPattern = Pattern.compile(elementPart); Pattern valPattern = Pattern.compile(elValuePart); // get matchers to use patterns to match the data/String Matcher elMatcher = elPattern.matcher(data); Matcher vMatcher = valPattern.matcher(data); while (elMatcher.find()) // handles value part { String element = elMatcher.group(); data = StringUtils.replaceOnce(data, element, "\"" + element.replace(":", "\":")); } while (vMatcher.find()) // handles the value part { String value = vMatcher.group(); value = StringUtils.remove(value, ":"); if (!StringUtils.isNumeric(value) && // not a number !StringUtils.equals(value, "true") && // not a boolean value !StringUtils.equals(value, "false")) // not a boolean value { if (StringUtils.isEmpty(value)) data = data.replace(":,", ":null,"); else data = StringUtils.replaceOnce(data, value, "\"" + value + "\""); } } return data; }
@Override public IImage getPosterUrl(String id) { if (!StringUtils.isNumeric(id)) { return Image.UNKNOWN; } String posterURL = Movie.UNKNOWN; FilmInfo filmInfo; try { filmInfo = api.getFilm(NumberUtils.toInt(id)); if (filmInfo.getPosters() == null || filmInfo.getPosters().getLarge() == null) { LOG.debug("No MovieMeter Poster URL for movie: {}", id); } else { posterURL = filmInfo.getPosters().getLarge(); } } catch (MovieMeterException ex) { LOG.error("Failed retreiving MovieMeter Poster URL for movie: {}", id); LOG.error(SystemTools.getStackTrace(ex)); } if (StringTools.isValidString(posterURL)) { return new Image(posterURL); } return Image.UNKNOWN; }
@Background void cameraChangeTask() { showHideLoading(true); try { valid = ZupApi.validateCityBoundary(getActivity(), latitude, longitude); if (GPSUtils.getFromLocation(getActivity(), latitude, longitude) == null) { return; } Address addr = GPSUtils.getFromLocation(getActivity(), latitude, longitude).get(0); showHideLoading(false); verifyValid(); if (addr == null) { return; } street = addr.getThoroughfare(); if (!TextUtils.isEmpty(addr.getFeatureName()) && StringUtils.isNumeric(addr.getFeatureName().substring(0, 1))) { number = addr.getFeatureName(); } else { number = ""; } updateUiAdapter(addr); } catch (Exception e) { Log.e("ZUP", e.getMessage(), e); Crashlytics.logException(e); } }
/** * Factory function creating an instance of FileModel from cloud-ID * * @param cloudIdentifier Cloud-identifier of the file * @return an instance of FileModel */ public static FileModel fromCloudId(String cloudIdentifier) { // (version)/(hash1)/(hash2)/(ownerID)/(items)/(itemID)/(FileName) String[] splitCloudId = cloudIdentifier.split("\\/"); int index = splitCloudId[4].lastIndexOf('.'); String fileName; String ext; if (splitCloudId[2].equals(TAG_TYPE)) { // tags fileName = splitCloudId[4]; ext = ""; return new FileModel(splitCloudId[0], splitCloudId[1], fileName, TAG_TYPE, ext); } fileName = splitCloudId[4].substring(0, index); ext = splitCloudId[4].substring(index + 1); String[] splitName = fileName.split("-"); String fileType = splitName[splitName.length - 1]; if (StringUtils.isNumeric(fileType)) // Derivative recordings(respeaking, interpret) fileType = splitName[splitName.length - 2]; if (fileType.equals(METADATA_TYPE) && fileName.length() == Speaker.SPEAKER_ID_LEN + METADATA_SUFFIX.length()) { // speaker small image return new FileModel(splitCloudId[0], splitCloudId[1], splitCloudId[3], SPEAKER_TYPE, ext); } else if (fileType.equals(METADATA_TYPE)) { return null; } else if (fileTypeSet.contains(fileType)) { return new FileModel(splitCloudId[0], splitCloudId[1], fileName, fileType, ext); } else { return null; } }
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Logger log = LoggerFactory.getLogger(AddEventServlet.class); String sid = request.getParameter("id"); String scontent = request.getParameter("content"); if (sid == null || !StringUtils.isNumeric(sid)) { response.sendError(401, "非法操作,权限终结"); return; } Long id = Long.valueOf(sid); ContentService cts = new ContentService(); Content content = new Content(); HttpSession session = request.getSession(); Account account = (Account) session.getAttribute("account"); if (account != null) { content.setAccountid(account.getId()); } content.setContent(scontent); content.setCustid(id); content.setCreatetime(getNowtime()); if (cts.addContent(content) > 0) { log.debug("添加{}备注内容为:{} 存储成功", id, content); response.sendRedirect("/cust/event.do?id=" + id); return; } else { response.sendError(500, "请稍后再试"); } }
public void setFirstAired(String firstAired) { if (StringUtils.isNotBlank(firstAired) && firstAired.length() >= 4) { String year = firstAired.substring(0, 4); if (StringUtils.isNumeric(year)) { setVideoYear(Integer.parseInt(year)); } } }
public void setMaxLifetime(String maxLifetime) { if (StringUtils.isNumeric(maxLifetime)) { SessionManager.maxLifetime = Long.valueOf(maxLifetime); } else { SessionManager.maxLifetime = PropertyConverter.convertStringToTimeMillis(maxLifetime); } log.debug("Max lifetime set to {} ms", SessionManager.maxLifetime); }
/** 获取能耗分类分项分页数据 */ @ResourceMapping(value = "getEnergyitemdicts") public Page getEnergyitemdicts(ResourceRequest request, ResourceResponse response) { int page = 1, rows = 1000; if (request.getParameter("page") != null) { String sPage = request.getParameter("page"); if (org.apache.commons.lang3.StringUtils.isNumeric(sPage)) { page = Integer.parseInt(sPage); } } if (request.getParameter("rows") != null) { String sRows = request.getParameter("rows"); if (org.apache.commons.lang3.StringUtils.isNumeric(sRows)) { rows = Integer.parseInt(sRows); } } return energyitemdictService.getPagedEnergyitemdicts(page, rows); }
public Integer getPropertyAsInteger(String name, Integer defaultValue) { String value = (String) properties.get(name); if (StringUtils.isNumeric(value)) { return Integer.parseInt(properties.getProperty(name)); } else { return defaultValue; } }
/** * * * <li><b>IsAlpha/IsNumeric/IsWhitespace/IsAsciiPrintable</b> - checks the characters in a String */ @Test public void testIsAlphaIsNumericIsWhitespaceIsAsciiPrintableStringUtils() { System.out.println(strOne + ":" + strOne.length()); System.out.println(StringUtils.isAlpha(strOne)); System.out.println(StringUtils.isNumeric(strOne)); System.out.println(StringUtils.isWhitespace(strOne)); System.out.println(StringUtils.isAsciiPrintable(strOne)); }
@Override public int hashCode() { if (StringUtils.isNumeric(id)) { return Integer.valueOf(id); } else { return id.hashCode(); } }
/** * Validates if parameter isn't empty, set number to true to check if it's a string * * @param parameter * @param number * @return * @throws ParameterException * @throws MisformedParameterException */ public String validate(String parameter, boolean number) throws ParameterException { if (parameter == null || parameter.equals("")) { ParameterException exception = new ParameterException("Missing a parameter"); throw exception; } else if (!StringUtils.isNumeric(parameter) && number) { throw new ParameterException("Input should be numeric"); } else { return parameter; } }
/** * manaStackDescription. * * @param sa a {@link forge.game.spellability.SpellAbility} object. * @param abMana a {@link forge.card.spellability.AbilityMana} object. * @param af a {@link forge.game.ability.AbilityFactory} object. * @return a {@link java.lang.String} object. */ @Override protected String getStackDescription(SpellAbility sa) { final StringBuilder sb = new StringBuilder(); String mana = !sa.hasParam("Amount") || StringUtils.isNumeric(sa.getParam("Amount")) ? GameActionUtil.generatedMana(sa) : "mana"; sb.append("Add ").append(mana).append(" to your mana pool."); return sb.toString(); }
private boolean setUsername(String username, UsrAccount account) { boolean isEmail = emailValidator.isValid(username, null); if (isEmail) { account.setEmail(username); return true; } boolean isQQ = StringUtils.isNumeric(username) && (username.length() >= 5 && username.length() <= 10); if (isQQ) { account.setQq(username); return true; } boolean isTel = StringUtils.isNumeric(username) && (username.length() == 11); if (isTel) { account.setTel(username); return true; } return false; }
@Override @Transactional(readOnly = true) public String getFollowTwitterScreenNames(String followList, String userName) { if (followList != null && !followList.isEmpty()) { List<String> userList = Arrays.asList(followList.split(",")); if (null == accessTokenStr || null == accessTokenSecretStr) { UserConnection userConnection = userConnectionService.fetchByCombinedUserName(userName); accessTokenStr = userConnection.getAccessToken(); accessTokenSecretStr = userConnection.getSecret(); } long[] userIdList = null; if (userList != null) { try { userIdList = new long[userList.size()]; int j = 0; logger.info("Received string: " + followList + ", Split follow string: " + userList); for (String user : userList) { // logger.info("Looking at follow data: " + user); if (StringUtils.isNumeric(user.trim())) { try { userIdList[j] = Long.parseLong(user.trim()); // logger.info("Going to fetch twitter userData for the following twitterID: " + // userIdList[j]); ++j; } catch (Exception ex) { logger.error("Exception in parsing string to number: ", ex); } } } userIdList = ArrayUtils.subarray(userIdList, 0, j); } catch (Exception e) { e.printStackTrace(); } } List<User> dataList = new ArrayList<User>(); if (userIdList != null && userIdList.length > 0) { dataList.addAll(getUserDataFromTwitterID(userIdList, userName)); } if (!dataList.isEmpty()) { StringBuffer followScreenNames = new StringBuffer(); for (User user : dataList) { followScreenNames.append(user.getScreenName()).append(","); } followScreenNames.deleteCharAt(followScreenNames.lastIndexOf(",")); // logger.info("Created follow twitterID list: " + followScreenNames.toString()); return followScreenNames.toString(); } else { return null; } } return null; }
/** * 将阿拉伯数字字符串转换为汉字 * * @param index * @return */ public static String getCnNum(final String index) { String num = null; if (StringUtils.isNumeric(index)) { try { num = String.valueOf(numStr[Integer.parseInt(index)]); } catch (NumberFormatException e) { return num; } } return num; }
/** * Checks the code what type it is and calls the correct method * * @param code * @return */ public static AmazonResult lookUp(String code) { if (StringUtils.isEmpty(code) == true) { return null; } if (StringUtils.isNumeric(code) == true && code.length() == 13) { return lookUpByEanNR(code); } else { return lookupByAsin(code); } }
private Collection<Long> extractNumericValues(final Iterable<Entity> numberProjections) { List<Long> numericValues = Lists.newArrayList(); for (Entity projection : numberProjections) { String numberFieldValue = projection.getStringField(L_NUM_PROJECTION_ALIAS); if (StringUtils.isNumeric(numberFieldValue)) { numericValues.add(Long.valueOf(numberFieldValue)); } } return numericValues; }
/** * 세션 정보를 이용해서 사용자 객체를 가져온다. 세션 정보가 없거나 잘못된 정보라면 anonymous 객체를 반환한다. 잘못된 정보의 경우 세션 정보를 삭제한다. * * @return */ private static User getUserFromSession() { String userId = session().get(SESSION_USERID); if (userId == null) { return User.anonymous; } if (!StringUtils.isNumeric(userId)) { return invalidSession(); } User user = User.find.byId(Long.valueOf(userId)); if (user == null) { return invalidSession(); } return user; }
/** 忽略无法转换为Long的字符串 */ public static List<Long> strArrayToLongList(String[] strArrays) { List<Long> longList = new ArrayList<Long>(); if (null != strArrays && strArrays.length > 0) { for (int i = 0; i < strArrays.length; i++) { String s = strArrays[i].trim(); if (!StringUtils.isNumeric(s)) { System.out.println("忽略无法转换成为Long型的字符串"); // 使用日志进行记录 continue; } longList.add(Long.parseLong(s)); } } return longList; }