public void createImage(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); response.setContentType("image/jpg"); /** 取得高度和宽度 */ String width = request.getParameter("width"); String height = request.getParameter("height"); if (StringUtils.isNumeric(width) && StringUtils.isNumeric(height)) { w = NumberUtils.toInt(width); h = NumberUtils.toInt(height); } /** */ BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); createBackground(g); /** */ String s = createCharacter(g); request.getSession().setAttribute(VALIDATE_CODE, s); g.dispose(); OutputStream out = response.getOutputStream(); ImageIO.write(image, "JPEG", out); out.close(); }
private String handleOperator(String param) { param = StringUtils.replaceChars(param, "()", ""); String oldOperator = " "; int result = 0; String tmp = ""; for (int i = 0; i < param.length(); i++) { String operator = "" + param.charAt(i); if (StringUtils.isNumeric(operator)) { tmp += param.charAt(i); } if (!StringUtils.isNumeric(operator) || i == param.length() - 1) { if (oldOperator.equals(" ")) { result += Integer.parseInt(tmp); } else if (oldOperator.equals("*")) { result *= Integer.parseInt(tmp); } else if (oldOperator.equals("-")) { result -= Integer.parseInt(tmp); } else if (oldOperator.equals("/")) { result /= Integer.parseInt(tmp); } tmp = ""; oldOperator = operator; } } return String.valueOf(result); }
@Override public Integer getFinalGrade() { final String grade = getGradeValue(); return (StringUtils.isEmpty(grade) || !StringUtils.isNumeric(grade)) ? null : Integer.valueOf(grade); }
@Override public void saveValue(String value) { if (!StringUtils.isEmpty(value) && StringUtils.isNumeric(value)) { if (isPickup) { SunnyModelProvider.INSTANCE.cityId = Long.valueOf(value); } else { SunnyModelProvider.INSTANCE.dropoffCityId = Long.valueOf(value); } } else { if (isPickup) { SunnyModelProvider.INSTANCE.cityId = 0; } else { SunnyModelProvider.INSTANCE.dropoffCityId = 0; } } if (isPickup) { logger.info("selected pickup city : " + SunnyModelProvider.INSTANCE.cityId); saveProperty("SUNNY_PICKUP_CITY", value); } else { logger.info("selected dropoff city : " + SunnyModelProvider.INSTANCE.dropoffCityId); saveProperty("SUNNY_DROPOFF_CITY", value); } }
/** 删除对象 */ public String delete() { if (items != null) for (String ids : items) { String[] idArray = ids.split(","); for (String id : idArray) { if (StringUtils.isNotEmpty(id) && StringUtils.isNumeric(id)) { cmsRequestlog = cmsRequestlogManager.getById(Long.parseLong(id)); if (cmsRequestlog != null) { // cmsRequestlog.setStatus(-1); // cmsRequestlogManager.update(cmsRequestlog); cmsRequestlogManager.removeById(cmsRequestlog.getId()); } } } // cmsRequestlogManager.removeById(Long.parseLong(id)); } if ("ajax".equalsIgnoreCase(Utils.getParam(getRequest(), "ajax"))) { Map map = new HashMap(); map.put("re", 1); return writeAjaxResponse(Json.toJson(map)); } else { return LIST_ACTION; } }
public void validateSmtp() { Validation.required("setup.smtpServer", smtpServer); if (HostNameOrIpAddressCheck.isValidHostName(smtpServer)) { if (PropertiesConfigurationValidator.validateIpList(nameservers)) { Set<String> ips = Sets.newHashSet(nameservers.split(",")); if (!DnsUtils.validateHostname(ips, smtpServer)) { Validation.addError("setup.smtpServer", "setup.smtpServer.invalidSmtpServer"); } } else if (StringUtils.isNotEmpty(nameservers)) { Validation.addError( "setup.nameservers", "setup.smtpServer.invalidNameserver", nameservers); } } if (!HostNameOrIpAddressCheck.isValidHostNameOrIp(smtpServer)) { Validation.addError("setup.smtpServer", "setup.smtpServer.invalid"); } if (!StringUtils.isNumeric(smtpPort)) { Validation.addError("setup.smtpServer", "setup.smtpServer.invalidPort"); } Validation.required("setup.smtpFrom", smtpFrom); Validation.email("setup.smtpFrom", smtpFrom); if (StringUtils.isNotBlank(smtpAuthType) && !StringUtils.equalsIgnoreCase(smtpAuthType, "None")) { Validation.required("setup.smtpUsername", smtpUsername); Validation.required("setup.smtpPassword", smtpPassword); if (PasswordUtil.isNotValid(smtpPassword)) { Validation.addError("setup.smtpPassword", "setup.password.notValid"); } } }
public void body(TableModel model, Column column) { if (column.isFirstColumn()) { rownum++; cellnum = 0; hssfRow = sheet.createRow(rownum); } String value = column.getCellDisplay(); if (StringUtils.isNumeric(value)) { value = column.getValue() == null ? "" : column.getValue().toString(); } value = value.replaceAll("\t", "").replaceAll("\n", ""); value = ExportViewUtils.parseXLS(value); HSSFCell hssfCell = hssfRow.createCell(cellnum); // modify by springside // hssfCell.setEncoding(HSSFCell.ENCODING_UTF_16); // end of modify by springside if (column.isEscapeAutoFormat()) { writeToCellAsText(hssfCell, value); } else { writeToCellFormatted(hssfCell, value); } cellnum++; }
/** * Build the number from a given number. This methods first checks if the number is not a type * numerical (without the prefix of the entry), or checks if the number already exists on an * another record field or not. * * @param entry the entry numbering * @param strNumber the number to build * @return the number * @throws DirectoryErrorException exception if the directory entry type numbering does not have * the same prefix as the number */ private int buildNumber(IEntry entry, String strNumber) throws DirectoryErrorException { int nNumber = DirectoryUtils.CONSTANT_ID_NULL; Field field = entry.getFields().get(0); String strPrefix = field.getTitle(); String strNumberTmp = strNumber; if (StringUtils.isNotBlank(strPrefix)) { if (StringUtils.isNotBlank(strNumber) && (strPrefix.length() < strNumber.length())) { strNumberTmp = strNumber.substring(strPrefix.length(), strNumber.length()); } else { throw new DirectoryErrorException( entry.getTitle(), "Directory Error - The prefix of the entry type numbering to insert is not correct."); } } if (StringUtils.isNotBlank(strNumberTmp) && StringUtils.isNumeric(strNumberTmp)) { nNumber = Integer.parseInt(strNumberTmp); } else { throw new DirectoryErrorException( entry.getTitle(), "Directory Error - The prefix of the entry type numbering to insert is not correct."); } return nNumber; }
public String getPriceChangeHist2substeps() throws Exception { if (StringUtils.isNumeric(sessionServiceId)) { servicePriceListBeanDTOList = servService.getServicePriceApproveList(Integer.parseInt(sessionServiceId)); } return "getPriceChangeHist"; }
public int validate(String certMailNo) { System.out.println("Validate Certified Mail Number..." + certMailNo); int length = certMailNo.length(); System.out.println("length::" + length); int return_val = 0; int even_num = 0; int odd_num = 0; if (StringUtils.isNumeric(certMailNo)) { for (int counter = 1; counter < length; counter++) { int mod = (counter + 1) % 2; if (mod == 0) { even_num = even_num + Integer.parseInt(certMailNo.substring(counter, counter + 1)); } else { odd_num = odd_num + Integer.parseInt(certMailNo.substring(counter, counter + 1)); } } even_num = even_num * 3; return_val = 10 - ((even_num + odd_num) % 10); if (return_val == 10) { return_val = 0; } } else { System.out.println("It is not valid certified mail number"); } return return_val; }
protected Integer getIntegerRequestParameterByMap(String name) { String val = JsfHelper.getRequestParameterMap(FacesContext.getCurrentInstance()).get(name); if (StringUtils.isNotBlank(val) && StringUtils.isNumeric(val)) { return Integer.parseInt(val); } else { return null; } }
/* * getPriceChangeHist2substeps 按照serviceId 和 breakdown 两种类型来检索价格变动信息 * zhougang 2011 05 30 */ public String getPriceChangeHist2seviceIdandbreakdown() throws Exception { if (StringUtils.isNumeric(sessionServiceId)) { servicePriceListBeanDTOList = servService.getServicePriceApproveList2breakDown( Integer.parseInt(sessionServiceId), returnType, breakDown); } return "getPriceChangeHist"; }
private void checkThatEditionisFilledAndValid(Errors errors, BookDataFormData cmd) { ValidationUtils.rejectIfEmptyOrWhitespace(errors, "edition", "empty"); if (!errors.hasFieldErrors("edition")) { if (!StringUtils.isNumeric(cmd.getEdition())) { errors.rejectValue("edition", "notvalid"); } } }
@Override public Community findByIdOrLegacyId(Context context, String id) throws SQLException { if (StringUtils.isNumeric(id)) { return findByLegacyId(context, Integer.parseInt(id)); } else { return find(context, UUID.fromString(id)); } }
@Override public void importSite(String configLocation) { Document document = loadConfiguration(configLocation); if (document != null) { Element root = document.getRootElement(); List<Node> siteNodes = root.selectNodes("site"); if (siteNodes != null) { for (Node siteNode : siteNodes) { String name = siteNode.valueOf("name"); String buildDataLocation = siteNode.valueOf("build-data-location"); String publishingChannelGroup = siteNode.valueOf("publish-channel-group"); String publishStr = siteNode.valueOf("publish"); boolean publish = (!StringUtils.isEmpty(publishStr) && publishStr.equalsIgnoreCase("true")); String publishSize = siteNode.valueOf("publish-chunk-size"); int chunkSize = (!StringUtils.isEmpty(publishSize) && StringUtils.isNumeric(publishSize)) ? Integer.valueOf(publishSize) : -1; Node foldersNode = siteNode.selectSingleNode("folders"); String sourceLocation = buildDataLocation + "/" + name; String delayIntervalStr = siteNode.valueOf("delay-interval"); int delayInterval = (!StringUtils.isEmpty(delayIntervalStr) && StringUtils.isNumeric(delayIntervalStr)) ? Integer.valueOf(delayIntervalStr) : -1; String delayLengthStr = siteNode.valueOf("delay-length"); int delayLength = (!StringUtils.isEmpty(delayLengthStr) && StringUtils.isNumeric(delayLengthStr)) ? Integer.valueOf(delayLengthStr) : -1; importFromConfigNode( name, publishingChannelGroup, foldersNode, sourceLocation, "/", publish, chunkSize, delayInterval, delayLength); } } } }
private int getDepth(Metadata sourceMetadata) { String depth = sourceMetadata.getFirstValue(MetadataTransfer.depthKeyName); if (StringUtils.isNumeric(depth)) { return Integer.parseInt(depth); } else { return -1; } }
@Override public Room convert(String source) { if (StringUtils.isEmpty(source) || !StringUtils.isNumeric(source)) { return null; } else { return new Room(Long.valueOf(source)); } }
/** * Gets the component summary for an item. * * @param contentId the content id * @return the component summary. Never <code>null</code>. * @throws PhotoGalleryException when the item does not exist */ public static PSComponentSummary getSummary(String contentId) throws PSException { if (StringUtils.isBlank(contentId) || !StringUtils.isNumeric(contentId)) { String emsg = "Content id must be numeric " + contentId; log.error(emsg); throw new IllegalArgumentException(emsg); } int id = Integer.parseInt(contentId); return getSummary(id); }
/** * @param ownerIdentifier * @param model * @param fbo * @param bindingResult * @return * @throws NotAVisitorException * @throws OwnerNotFoundException * @throws SchedulingException */ @RequestMapping(method = RequestMethod.POST) protected String createAppointment( final ModelMap model, @PathVariable("ownerIdentifier") final String ownerIdentifier, @Valid @ModelAttribute(COMMAND_ATTR_NAME) final CreateAppointmentFormBackingObject fbo, BindingResult bindingResult) throws NotAVisitorException, OwnerNotFoundException, SchedulingException { CalendarAccountUserDetailsImpl currentUser = (CalendarAccountUserDetailsImpl) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); IScheduleVisitor visitor = currentUser.getScheduleVisitor(); if (bindingResult.hasErrors()) { return "visitor/create-appointment-form"; } IScheduleOwner selectedOwner = null; if (StringUtils.isNumeric(ownerIdentifier)) { Long ownerId = Long.parseLong(ownerIdentifier); selectedOwner = findOwnerForVisitor(visitor, ownerId); } else { PublicProfile profile = publicProfileDao.locatePublicProfileByKey(ownerIdentifier); if (null != profile) { selectedOwner = ownerDao.locateOwnerByAvailableId(profile.getOwnerId()); } } if (null == selectedOwner) { throw new OwnerNotFoundException("no owner found for " + ownerIdentifier); } validateChosenStartTime( selectedOwner.getPreferredVisibleWindow(), fbo.getTargetBlock().getStartTime()); AvailableBlock finalAppointmentBlock = fbo.getTargetBlock(); if (fbo.isDoubleLengthAvailable()) { // check if selected meeting duration matches meeting durations maxLength // if it's greater, then we need to look up the next block in the schedule and attempt to // combine if (fbo.getSelectedDuration() == fbo.getMeetingDurations().getMaxLength()) { finalAppointmentBlock = availableScheduleDao.retrieveTargetDoubleLengthBlock( selectedOwner, finalAppointmentBlock.getStartTime()); } } if (null == finalAppointmentBlock) { throw new SchedulingException("requested time is not available"); } VEvent event = schedulingAssistantService.scheduleAppointment( visitor, selectedOwner, finalAppointmentBlock, fbo.getReason()); model.put("event", event); model.put("owner", selectedOwner); model.put("ownerRemindersPreference", selectedOwner.getRemindersPreference()); return "visitor/create-appointment-success"; }
/** * This method extracts a port number from the serial number of a device. It assumes that the * device name is of format [xxxx-nnnn] where nnnn is the port number. * * @param device The device to extract the port number from. * @return Returns the port number of the device */ private int extractPortFromDevice(IDevice device) { String portStr = StringUtils.substringAfterLast(device.getSerialNumber(), "-"); if (StringUtils.isNotBlank(portStr) && StringUtils.isNumeric(portStr)) { return Integer.parseInt(portStr); } // If the port is not available then return -1 return -1; }
public static PSLocator getCurrentOrEditLocator(String contentId) throws PSException { if (StringUtils.isBlank(contentId) || !StringUtils.isNumeric(contentId)) { String emsg = "Content id must be numeric " + contentId; log.error(emsg); throw new IllegalArgumentException(emsg); } int id = Integer.parseInt(contentId); return getCurrentOrEditLocator(id); }
@GET @Path("{search_id:[0-9]+}") @Produces(UTF8MediaType.APPLICATION_JSON) public Response getSearchResults( // @PathParam("search_id") long searchId, // @QueryParam("start") @DefaultValue("0") String startString, // @QueryParam("rows") @DefaultValue("100") String rowsString // ) { if (!StringUtils.isNumeric(startString) || !StringUtils.isNumeric(rowsString)) { throw new BadRequestException(); } int start = Integer.valueOf(startString); int rows = Integer.valueOf(rowsString); Map<String, Object> searchResult = searchService.getSearchResult(searchId, start, rows); addPrevNextURIs(searchResult, searchId, start, rows); ResponseBuilder builder = Response.ok(searchResult); return builder.build(); }
/* (non-Javadoc) * @see pcgen.core.prereq.PrerequisiteTest#toHtmlString(pcgen.core.prereq.Prerequisite) */ @Override public String toHtmlString(final Prerequisite prereq) { final PrerequisiteTestFactory factory = PrerequisiteTestFactory.getInstance(); StringBuilder str = new StringBuilder(250); String delimiter = ""; // $NON-NLS-1$ for (Prerequisite element : prereq.getPrerequisites()) { final PrerequisiteTest test = factory.getTest(element.getKind()); if (test == null) { Logging.errorPrintLocalised( "PreMult.cannot_find_subformatter", element.getKind()); // $NON-NLS-1$ } else { str.append(delimiter); if (test instanceof PreMult && !delimiter.equals("")) { str.append("##BR##"); } str.append(test.toHtmlString(element)); delimiter = LanguageBundle.getString("PreMult.html_delimiter"); // $NON-NLS-1$ } } // Handle some special cases - all required, one required or none required int numRequired = -1; if (StringUtils.isNumeric(prereq.getOperand())) { numRequired = Integer.parseInt(prereq.getOperand()); } if ((prereq.getOperator() == PrerequisiteOperator.GTEQ || prereq.getOperator() == PrerequisiteOperator.GT || prereq.getOperator() == PrerequisiteOperator.EQ) && numRequired == prereq.getPrerequisites().size()) { return LanguageBundle.getFormattedString( "PreMult.toHtmlAllOf", //$NON-NLS-1$ str.toString()); } if ((prereq.getOperator() == PrerequisiteOperator.GTEQ || prereq.getOperator() == PrerequisiteOperator.EQ) && numRequired == 1) { return LanguageBundle.getFormattedString( "PreMult.toHtmlEither", //$NON-NLS-1$ str.toString()); } if ((prereq.getOperator() == PrerequisiteOperator.LT && numRequired == 1) || ((prereq.getOperator() == PrerequisiteOperator.EQ || prereq.getOperator() == PrerequisiteOperator.LTEQ) && numRequired == 0)) { return LanguageBundle.getFormattedString( "PreMult.toHtmlNone", //$NON-NLS-1$ str.toString()); } return LanguageBundle.getFormattedString( "PreMult.toHtml", //$NON-NLS-1$ prereq.getOperator().toDisplayString(), prereq.getOperand(), str.toString()); }
/** * Retorna se um código de compensação passado é válido, ou seja, se está entre os valores * inteiros de 1 a 999. * * @param codigo - Código de compensação * @return true se for númerio entre 1 e 999; false caso contrário * @since 0.2 */ public boolean isCodigoValido(String codigo) { boolean codigoValido = false; if (StringUtils.isNotBlank(codigo) && StringUtils.isNumeric(codigo)) { codigoValido = isCodigoValido(Integer.valueOf(codigo.trim())); } return codigoValido; }
private void checkThatYearIsFilledAndValid(Errors errors, BookDataFormData cmd) { ValidationUtils.rejectIfEmptyOrWhitespace(errors, "year", "empty"); if (!errors.hasFieldErrors("year")) { if (!StringUtils.isNumeric(cmd.getYear())) { errors.rejectValue("year", "notvalid"); } else if (StringUtils.length(cmd.getYear()) != 4) { errors.rejectValue("year", "invalid.length"); } } }
public List<ContentMap> getLatest( String path, String maxResultSize, String nodeType, int pageNumber, String nodeTypeName) throws RepositoryException { int resultSize = DEFAULT_LATEST_COUNT; if (StringUtils.isNumeric(maxResultSize)) { resultSize = Integer.parseInt(maxResultSize); } final String sqlBlogItems = buildQuery(path, nodeType); return templatingFunctions.asContentMapList( getWrappedNodesFromQuery(sqlBlogItems, resultSize, pageNumber, nodeTypeName)); }
/** * Get all available nodes of type mgnl:news. * * @param path Start node path in hierarchy * @param maxResultSize Number of items to return. When empty <code>Integer.MAX_VALUE</code> will * be used. * @return List of news nodes sorted by date created in descending order * @throws RepositoryException */ public List<ContentMap> getNews(String path, String maxResultSize) throws RepositoryException { int resultSize = Integer.MAX_VALUE; if (StringUtils.isNumeric(maxResultSize)) { resultSize = Integer.parseInt(maxResultSize); } String customFilters = getTagPredicate(filter) + getCategoryPredicate(filter); final String sqlNewsItems = buildQuery(path, true, customFilters, NEWS_NODE_TYPE); return templatingFunctions.asContentMapList( getWrappedNodesFromQuery( sqlNewsItems, resultSize, getPageNumber(), NewsNodeTypes.News.NAME)); }
/** * 세션에 저장된 정보를 이용해서 사용자 객체를 생성한다 세션에 저장된 정보가 없다면 anonymous 객체가 리턴된다 * * @return 세션 정보 기준 조회된 사용자 객체 */ public static User currentUser() { String userId = session().get(SESSION_USERID); if (StringUtils.isEmpty(userId) || !StringUtils.isNumeric(userId)) { return User.anonymous; } User foundUser = User.find.byId(Long.valueOf(userId)); if (foundUser == null) { processLogout(); return User.anonymous; } return foundUser; }
@Override public RMAImporter createRGGElement(Element element, RGG rggInstance) { if (element.getNodeType() != Element.ELEMENT_NODE) { throw new IllegalArgumentException("elements node type must be ELEMENT_NODE"); /** * **************** initialize and set attributes values ************************************* */ } String var = element.getAttribute(RGG.getConfiguration().getString("VAR")); String colspan = element.getAttribute(RGG.getConfiguration().getString("COLUMN-SPAN")); String id = element.getAttribute(RGG.getConfiguration().getString("ID")); String othercolumns = element.getAttribute(RGG.getConfiguration().getString("OTHER-COLUMNS")); /** * ******************************************************************************************** */ RMAImporter rMAImporter = new RMAImporter(); VMAImporter vMAImporter = null; if (StringUtils.isNotBlank(othercolumns)) { vMAImporter = new VMAImporter(rggInstance, StringUtils.split(othercolumns, ',')); } else { vMAImporter = new VMAImporter(rggInstance, null); } if (StringUtils.isNotBlank(var)) { rMAImporter.setVar(var); } if (StringUtils.isNotBlank(colspan)) { if (StringUtils.isNumeric(colspan)) { vMAImporter.setColumnSpan(Integer.parseInt(colspan)); } else if (StringUtils.equals(colspan, RGG.getConfiguration().getString("FULL-SPAN"))) { vMAImporter.setColumnSpan(LayoutInfo.FULL_SPAN); } else { throw new NumberFormatException( RGG.getConfiguration().getString("COLUMN-SPAN") + " seems not to be a number: " + colspan + "nor a known keyword!"); } } if (StringUtils.isNotBlank(id)) { rggInstance.addObject(id, vMAImporter); } rMAImporter.setVMAImporter(vMAImporter); if (element.hasChildNodes()) { // it can only be <iport> setInputPorts(rMAImporter, element); } return rMAImporter; }
public String getProtocol() { String p = protocol.trim(); // Deal with ICMP(protocol number 1) specially because it need to be paired with icmp type and // code if (StringUtils.isNumeric(p)) { int protoNumber = Integer.parseInt(p); if (protoNumber == 1) { p = "icmp"; } } return p; }