org.apache.commons.lang.math.NumberUtils#toInt ( )源码实例Demo

下面列出了org.apache.commons.lang.math.NumberUtils#toInt ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: cachecloud   文件: AppManageController.java
/**
 * 应用重要性级别
 */
@RequestMapping(value = "/updateAppImportantLevel")
public ModelAndView doUpdateAppImportantLevel(HttpServletRequest request, HttpServletResponse response, Model model) {
    long appId = NumberUtils.toLong(request.getParameter("appId"));
    int importantLevel = NumberUtils.toInt(request.getParameter("importantLevel"));
    SuccessEnum successEnum = SuccessEnum.FAIL;
    if (appId > 0 && importantLevel >= 0) {
        try {
            AppDesc appDesc = appService.getByAppId(appId);
            appDesc.setImportantLevel(importantLevel);
            appService.update(appDesc);
            successEnum = SuccessEnum.SUCCESS;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
    model.addAttribute("status", successEnum.value());
    return new ModelAndView("");
}
 
源代码2 项目: yes-cart   文件: ExportDirectorImplService.java
/** {@inheritDoc} */
@Override
public JobStatus doExport(final String descriptorGroup, final String fileName, final boolean async) {

    final AsyncContext ctx = getAsyncContext();

    final String imgVault = systemService.getImageRepositoryDirectory();

    // Max char of report to UI since it will get huge and simply will crash the UI, not to mention traffic cost.
    final int logSize = NumberUtils.toInt(nodeService.getConfiguration().get(AttributeNamesKeys.System.IMPORT_JOB_LOG_SIZE), 100);
    // Timeout - just in case runnable crashes and we need to unlock through timeout.
    final int timeout = NumberUtils.toInt(nodeService.getConfiguration().get(AttributeNamesKeys.System.IMPORT_JOB_TIMEOUT_MS), 100);

    final String rootPath = resolveExportDirectory();
    final String absFile = resolveExportFile((String) ctx.getAttribute(AsyncContext.USERNAME), fileName);

    return doJob(new JobContextImpl(async, new JobStatusListenerWithLoggerImpl(new JobStatusListenerImpl(logSize, timeout), LOG),
            new HashMap<String, Object>() {{
                put(JobContextKeys.EXPORT_DESCRIPTOR_GROUP, descriptorGroup);
                put(JobContextKeys.EXPORT_FILE, absFile);
                put(JobContextKeys.IMAGE_VAULT_PATH, imgVault);
                put(JobContextKeys.EXPORT_DIRECTORY_ROOT, rootPath);
                putAll(ctx.getAttributes());
            }}));
}
 
/**
 * {@inheritDoc}
 */
@Override
public String createRollingFileName(final String fullFileName, final String code, final String suffix, final String locale) {

    final String systemPart =
                      (Constants.NO_IMAGE.equals(code) ? "" : "_" + code)
                    + "_" + (char)(NumberUtils.toInt(suffix) + 'a')
                    + (StringUtils.isNotEmpty(locale) ? "_" + locale : "");

    final int posExt = fullFileName.lastIndexOf('.');
    final String fileName;
    final String fileExt;
    if (posExt == -1) {
        fileName = fullFileName;
        fileExt = "";
    } else {
        fileName = fullFileName.substring(0, posExt);
        fileExt = fullFileName.substring(posExt); // including '.'
    }

    final String mainPart;
    if (fileName.endsWith(systemPart)) {
        mainPart = fileName.substring(0, fileName.length() - systemPart.length());
    } else {
        mainPart = fileName;
    }

    final int posRollingNumber = mainPart.lastIndexOf('-');
    if (posRollingNumber == -1 || (mainPart.length() < posRollingNumber + 1) || !NumberUtils.isDigits(mainPart.substring(posRollingNumber + 1))) {
        return mainPart + "-1" + systemPart + fileExt;
    }
    return mainPart.substring(0, posRollingNumber) + "-" + (NumberUtils.toInt(mainPart.substring(posRollingNumber + 1)) + 1) + systemPart + fileExt;
}
 
private int determineBatchSize() {

        final String av = systemService.getAttributeValue(AttributeNamesKeys.System.JOB_EMPTY_CARTS_BATCH_SIZE);

        if (av != null && StringUtils.isNotBlank(av)) {
            int batch = NumberUtils.toInt(av);
            if (batch > 0) {
                return batch;
            }
        }
        return this.batchSize;

    }
 
/**
 * 初始化配置
 */
@RequestMapping(value = "/init")
public ModelAndView init(HttpServletRequest request, HttpServletResponse response, Model model) {
    // 默认是Redis普通节点配置
    int type = NumberUtils.toInt(request.getParameter("type"), ConstUtils.CACHE_REDIS_STANDALONE);
    model.addAttribute("redisConfigList", redisConfigTemplateService.getByType(type));
    model.addAttribute("success", request.getParameter("success"));
    model.addAttribute("redisConfigActive", SuccessEnum.SUCCESS.value());
    model.addAttribute("type", type);
    return new ModelAndView("manage/redisConfig/init");
}
 
源代码6 项目: cachecloud   文件: AppManageController.java
/**
 * 添加水平扩容节点
 * 
 * @return
 */
@RequestMapping(value = "/addHorizontalNodes")
public ModelAndView doAddHorizontalNodes(HttpServletRequest request,
        HttpServletResponse response, Model model, String masterSizeSlave,
        Long appAuditId) {
    AppUser appUser = getUserInfo(request);
    logger.warn("user {} addHorizontalNodes:{}", appUser.getName(), masterSizeSlave);
    boolean isAdd = false;
    AppAudit appAudit = appService.getAppAuditById(appAuditId);
    // 解析配置
    String[] configArr = masterSizeSlave.split(ConstUtils.COLON);
    String masterHost = configArr[0];
    String memSize = configArr[1];
    int memSizeInt = NumberUtils.toInt(memSize);
    String slaveHost = null;
    if (configArr.length >= 3) {
        slaveHost = configArr[2];
    }
    try {
        isAdd = appDeployCenter.addHorizontalNodes(appAudit.getAppId(), masterHost, slaveHost, memSizeInt);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
    logger.warn("addAppClusterSharding:{}, result is {}", masterSizeSlave, isAdd);
    model.addAttribute("status", isAdd ? 1 : 0);
    return new ModelAndView("");
}
 
源代码7 项目: JavaTutorial   文件: EchoClient.java
/**
 * @param args
 */
public static void main(String[] args) {
    if (args.length != 2) {
        _logger.error("Invalid arguments。Usage:java cn.aofeng.demo.netty40x.echo.EchoClient 192.168.56.102 8080");
        System.exit(-1);
    }
    
    String host = args[0];
    int port = NumberUtils.toInt(args[1], 8080);
    EchoClient client = new EchoClient();
    client.start(host, port);
}
 
@Override
public Integer convertCountToInteger(final String timesAlias, final String times) {
	return NumberUtils.toInt(
		autoAliasUtils.getValue(
			StringUtils.defaultString(times, "1"),
			StringUtils.isNotBlank(timesAlias),
			State.getFeatureStateForThread()),
		1);
}
 
源代码9 项目: aion-germany   文件: BaseCommand.java
protected void assault(Player player, String[] params) {
	if (params.length < 3 || !NumberUtils.isNumber(params[1])) {
		showHelp(player);
		return;
	}

	int baseId = NumberUtils.toInt(params[1]);
	if (!isValidBaseLocationId(player, baseId)) {
		return;
	}

	// check if params2 is race
	Race race = null;
	try {
		race = Race.valueOf(params[2].toUpperCase());
	}
	catch (IllegalArgumentException e) {
		// ignore
	}

	// check if race is valid
	if (race == null) {
		PacketSendUtility.sendMessage(player, params[2] + " is not valid race");
		showHelp(player);
		return;
	}

	// assault
	Base base = BaseService.getInstance().getActiveBase(baseId);
	if (base != null) {
		if (base.isAttacked()) {
			PacketSendUtility.sendMessage(player, "Assault already started!");
		}
		else {
			base.spawnAttackers(race);
		}
	}
	else
		PacketSendUtility.sendMessage(player, "This Base doesn't exists!");
}
 
源代码10 项目: cachecloud   文件: Connection.java
/**
 * line format:
 * TCP: inuse 454 orphan 0 tw 159620 alloc 454 mem 79
 */
public void parse(String line, String timeKey) throws Exception{
	if(line.startsWith(FLAG)) {
		String[] items = line.split("\\s+");
		for(int i = 0; i < items.length; ++i) {
			if(items[i].equals("inuse")) {
				established = NumberUtils.toInt(items[i+1]);
			} else if(items[i].equals("orphan")) {
				orphan = NumberUtils.toInt(items[i+1]);
			} else if(items[i].equals("tw")) {
				timeWait = NumberUtils.toInt(items[i+1]);
			}
		}
	}
}
 
源代码11 项目: BashSupport   文件: BashVarImpl.java
public boolean isParameterReference() {
    if (getTextLength() > 2) {
        return false;
    }

    if (LanguageBuiltins.bashShellParamReferences.contains(getReferenceName())) {
        return true;
    }

    //slower fallback which checks if the parameter is  a number
    return NumberUtils.toInt(getReferenceName(), -1) >= 0;
}
 
源代码12 项目: JavaTutorial   文件: EchoServer.java
/**
 * @param args
 */
public static void main(String[] args) {
    if (args.length != 1) {
        _logger.error("Invalid arguments。Usage:java cn.aofeng.demo.netty40x.echo.EchoServer 8080");
        System.exit(-1);
    }
    
    int port = NumberUtils.toInt(args[0], 8080);
    EchoServer server = new EchoServer();
    server.start(port);
}
 
源代码13 项目: cachecloud   文件: AppController.java
/**
 * 修改应用报警配置
 */
@RequestMapping(value = "/changeAppAlertConfig")
public ModelAndView doChangeAppAlertConfig(HttpServletRequest request,
                                           HttpServletResponse response, Model model) {

    long appId = NumberUtils.toLong(request.getParameter("appId"), -1);
    int memAlertValue =  NumberUtils.toInt(request.getParameter("memAlertValue"), -1);
    int clientConnAlertValue =  NumberUtils.toInt(request.getParameter("clientConnAlertValue"), -1);
    SuccessEnum result = appService.changeAppAlertConfig(appId, memAlertValue,clientConnAlertValue, getUserInfo(request));
    write(response, String.valueOf(result.value()));
    return null;
}
 
源代码14 项目: cachecloud   文件: Server.java
private String parseULimit(String line, String prefix, String flag) {
	String result = null;
	if(line.startsWith(prefix)) {
		String[] tmp = line.split("\\s+");
		if(tmp.length > 0) {
			int v = NumberUtils.toInt(tmp[tmp.length - 1]);
			if(v > 0) {
				result = flag + "," + v +";";
			}
		}
	}
	return result;
}
 
源代码15 项目: lams   文件: AuthoringController.java
/**
    * This method will get necessary information from assessment question form and save or update into
    * <code>HttpSession</code> AssessmentQuestionList. Notice, this save is not persist them into database, just save
    * <code>HttpSession</code> temporarily. Only they will be persist when the entire authoring page is being
    * persisted.
    */

   @RequestMapping(value = "/saveItem", method = RequestMethod.POST)
   private String saveItem(@ModelAttribute("scratchieItemForm") ScratchieItemForm scratchieItemForm,
    HttpServletRequest request) {

SessionMap<String, Object> sessionMap = (SessionMap<String, Object>) request.getSession()
	.getAttribute(scratchieItemForm.getSessionMapID());
// check whether it is "edit(old Question)" or "add(new Question)"
SortedSet<ScratchieItem> itemList = getItemList(sessionMap);
int itemIdx = NumberUtils.toInt(scratchieItemForm.getItemIndex(), -1);
ScratchieItem item = null;

if (itemIdx == -1) { // add
    item = new ScratchieItem();
    item.setCreateDate(new Timestamp(new Date().getTime()));
    int maxSeq = 1;
    if (itemList != null && itemList.size() > 0) {
	ScratchieItem last = itemList.last();
	maxSeq = last.getOrderId() + 1;
    }
    item.setOrderId(maxSeq);
    itemList.add(item);
} else { // edit
    List<ScratchieItem> rList = new ArrayList<>(itemList);
    item = rList.get(itemIdx);
}

item.setTitle(scratchieItemForm.getTitle());
item.setDescription(scratchieItemForm.getDescription());

// set options
Set<ScratchieAnswer> answerList = getAnswersFromRequest(request, true);
Set<ScratchieAnswer> answers = new LinkedHashSet<>();
int orderId = 0;
for (ScratchieAnswer answer : answerList) {
    answer.setOrderId(orderId++);
    answers.add(answer);
}
item.setAnswers(answers);

// set session map ID so that itemlist.jsp can get sessionMAP
request.setAttribute(ScratchieConstants.ATTR_SESSION_MAP_ID, scratchieItemForm.getSessionMapID());
return "pages/authoring/parts/itemlist";
   }
 
源代码16 项目: canal-1.1.3   文件: RdsLocalBinlogEventParser.java
@Override
public void onFinish(String fileName) {
    try {
        binlogDownloadQueue.downOne();
        File needDeleteFile = new File(directory + File.separator + fileName);
        if (needDeleteFile.exists()) {
            needDeleteFile.delete();
        }
        // 处理下logManager位点问题
        LogPosition logPosition = logPositionManager.getLatestIndexBy(destination);
        Long timestamp = 0L;
        if (logPosition != null && logPosition.getPostion() != null) {
            timestamp = logPosition.getPostion().getTimestamp();
            EntryPosition position = logPosition.getPostion();
            LogPosition newLogPosition = new LogPosition();
            String journalName = position.getJournalName();
            int sepIdx = journalName.indexOf(".");
            String fileIndex = journalName.substring(sepIdx + 1);
            int index = NumberUtils.toInt(fileIndex) + 1;
            String newJournalName = journalName.substring(0, sepIdx) + "."
                                    + StringUtils.leftPad(String.valueOf(index), fileIndex.length(), "0");
            newLogPosition.setPostion(new EntryPosition(newJournalName,
                4L,
                position.getTimestamp(),
                position.getServerId()));
            newLogPosition.setIdentity(logPosition.getIdentity());
            logPositionManager.persistLogPosition(destination, newLogPosition);
        }

        if (binlogDownloadQueue.isLastFile(fileName)) {
            logger.warn("last file : " + fileName + " , timestamp : " + timestamp
                        + " , all file parse complete, switch to mysql parser!");
            finishListener.onFinish();
            return;
        } else {
            logger.warn("parse local binlog file : " + fileName + " , timestamp : " + timestamp
                        + " , try the next binlog !");
        }
        binlogDownloadQueue.prepare();
    } catch (Exception e) {
        logger.error("prepare download binlog file failed!", e);
        throw new RuntimeException(e);
    }
}
 
源代码17 项目: yes-cart   文件: ManagerWsNodeServiceImpl.java
private WsClientFactory<WebServiceInboundChannel> getWebServiceInboundChannel(final AsyncContext context,
                                                                              final String connectorUrl,
                                                                              final String timeoutKey) {


    final String userName = context.getAttribute(AsyncContext.USERNAME);
    final String password = context.getAttribute(AsyncContext.CREDENTIALS);
    final String passwordHash = context.getAttribute(AsyncContext.CREDENTIALS_HASH);
    final boolean hashed = StringUtils.isNotBlank(passwordHash);
    final String pwd = hashed ? passwordHash : password;

    final int timeout = NumberUtils.toInt(getConfiguration().get(timeoutKey), 1000);

    return wsClientAbstractFactory.getFactory(WebServiceInboundChannel.class, userName, pwd, hashed, connectorUrl, timeout);

}
 
/**
 * 格式:
 *     connected_slaves:2
 *     slave0:ip=10.10.76.151,port=6380,state=online,offset=33119690469561,lag=1
 *     slave1:ip=10.10.76.160,port=6380,state=online,offset=33119690513578,lag=0
 *     master_repl_offset:33119653194425
 */
@Override
public List<InstanceAlertValueResult> checkConfig(InstanceAlertConfig instanceAlertConfig, AlertConfigBaseData alertConfigBaseData) {
    Object connectedSlavesObject = getValueFromRedisInfo(alertConfigBaseData.getStandardStats(), RedisInfoEnum.connected_slaves.getValue());
    if (connectedSlavesObject == null) {
        return null;
    }
    int connectedSlaves = NumberUtils.toInt(connectedSlavesObject.toString());
    if (connectedSlaves == 0) {
        return null;
    }
    Object masterReplOffsetObject = getValueFromRedisInfo(alertConfigBaseData.getStandardStats(), RedisInfoEnum.master_repl_offset.getValue());
    if (masterReplOffsetObject == null) {
        return null;
    }
    List<InstanceAlertValueResult> instanceAlertValueResultList = new ArrayList<InstanceAlertValueResult>();
    for (int i = 0; i < connectedSlaves; i++) {
        Object slaveInfo = getValueFromRedisInfo(alertConfigBaseData.getStandardStats(), "slave" + i);
        if (slaveInfo == null) {
            continue;
        }
        String[] arr = slaveInfo.toString().split(",");
        if (arr.length < 5) {
            continue;
        }
        String state = arr[2];
        if (!"state=online".equals(state)) {
            continue;
        }
        String slaveHostPort = arr[0] + "," + arr[1];
        String slaveOffsetStr = arr[3];
        String[] slaveOffsetArr = slaveOffsetStr.split("=");
        if (slaveOffsetArr.length != 2) {
            continue;
        }
        String slaveOffset = slaveOffsetArr[1];
        long diffOffset = Math.abs(NumberUtils.toLong(masterReplOffsetObject.toString()) - NumberUtils.toLong(slaveOffset));
        boolean compareRight = isCompareDoubleRight(instanceAlertConfig, diffOffset);
        if (compareRight) {
            return null;
        }
        InstanceInfo instanceInfo = alertConfigBaseData.getInstanceInfo();
        InstanceAlertValueResult instanceAlertValueResult = new InstanceAlertValueResult(instanceAlertConfig, instanceInfo, String.valueOf(diffOffset),
                instanceInfo.getAppId(), EMPTY);
        String otherInfo = String.format("masterOffset is %s<br/>slaveOffset  is %s<br/>%s", masterReplOffsetObject.toString(), slaveOffset, slaveHostPort);
        instanceAlertValueResult.setOtherInfo(otherInfo);
        instanceAlertValueResultList.add(instanceAlertValueResult);
    }
    return instanceAlertValueResultList;
}
 
源代码19 项目: yes-cart   文件: ImageServiceImpl.java
/**
 * {@inheritDoc}
 */
@Override
public byte[] resizeImage(final String filename,
                          final byte[] content,
                          final String width,
                          final String height,
                          final boolean cropToFit) {

    try {

        final InputStream bis = new ByteArrayInputStream(content);

        final BufferedImage originalImg = ImageIO.read(bis);
        if (originalImg != null) {
            final String codec = getCodecFromFilename(filename);
            final boolean supportsAlpha = hasAlphaSupport(codec);

            int x = NumberUtils.toInt(width);
            int y = NumberUtils.toInt(height);
            int originalX = originalImg.getWidth();
            int originalY = originalImg.getHeight();

            boolean doCropToFit = cropToFit || x < forceCropToFitOnSize || y < forceCropToFitOnSize;

            final int imageType = originalImg.getType();

            final Image resizedImg;
            //            final BufferedImage resizedImg;
            final int padX, padY;
            if (doCropToFit) {
                // crop the original to best fit of target size
                int[] cropDims = cropImageToCenter(x, y, originalX, originalY);
                padX = 0;
                padY = 0;

                final BufferedImage croppedImg = originalImg.getSubimage(cropDims[0], cropDims[1], cropDims[2], cropDims[3]);
                resizedImg = croppedImg.getScaledInstance(x, y, Image.SCALE_SMOOTH);

                //                final BufferedImage croppedImg = originalImg.getSubimage(cropDims[0], cropDims[1], cropDims[2], cropDims[3]);
                //                resizedImg = new BufferedImage(y, x, imageType);
                //                Graphics2D graphics = resizedImg.createGraphics();
                //                graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                //                graphics.drawImage(croppedImg, 0, 0, x, y, null);
            } else {
                int[] scaleDims = scaleImageToCenter(x, y, originalX, originalY);
                padX = scaleDims[0];
                padY = scaleDims[1];

                resizedImg = originalImg.getScaledInstance(scaleDims[2], scaleDims[3], Image.SCALE_SMOOTH);

                //                resizedImg = new BufferedImage(scaleDims[3], scaleDims[2], imageType);
                //                Graphics2D graphics = resizedImg.createGraphics();
                //                graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                //                graphics.drawImage(originalImg, 0, 0, scaleDims[2], scaleDims[3], null);
            }

            // base canvas
            final BufferedImage resizedImgFinal = new BufferedImage(x, y, imageType);

            // fill base color
            final Graphics2D graphics = resizedImgFinal.createGraphics();
            graphics.setPaint(supportsAlpha ? alphaBorder : defaultBorder);
            graphics.fillRect(0, 0, x, y);

            // insert scaled image
            graphics.drawImage(resizedImg, padX, padY, null);

            final ByteArrayOutputStream bos = new ByteArrayOutputStream();

            ImageIO.write(resizedImgFinal, codec, bos);

            return bos.toByteArray();
        } else {
            LOG.warn("Image byte content could not be read {}, size is {} bytes", filename, content.length);
        }

    } catch (Exception exp) {
        LOG.error("Unable to resize image " + filename, exp);
    }

    return new byte[0];

}
 
源代码20 项目: yes-cart   文件: ContentCms1XmlEntityHandler.java
Tag tagContent(final Tag parent, final Category content) {

        final Tag tag = tag(parent, "content")
                .attr("id", content.getCategoryId())
                .attr("guid", content.getGuid())
                .attr("rank", content.getRank());

        Category root = content;
        while (root != null && !root.isRoot()) {
            root = this.categoryService.getById(root.getParentId());
        }
        if (root != null) {
            tag.attr("shop", root.getGuid()); // Root content has same GUID as shop code
        }

        final Attributable attributable = new FilteredAttributable(content);

            tag
                .tagCdata("name", content.getName())
                .tagI18n("display-name", content.getDisplayName())
                .tagCdata("description", content.getDescription());


        if (content.getParentId() > 0L) {
            final Category parentCat = this.categoryService.findById(content.getParentId());
            if (parentCat != null) {
                tag
                        .tag("parent")
                        .attr("id", parentCat.getCategoryId())
                        .attr("guid", parentCat.getGuid())
                        .end();
            }
        }

            tag
                .tag("availability")
                    .attr("disabled", content.isDisabled())
                    .tagTime("available-from", content.getAvailablefrom())
                    .tagTime("available-to", content.getAvailableto())
                .end()
                .tag("templates")
                    .tagChars("content", content.getUitemplate())
                .end()
                .tagSeo(content)
                .tagExt(attributable);

        final List<String> langs = new ArrayList<>();
        int maxChunks = 0;
        for (final AttrValue av : content.getAttributes()) {
            if (av.getAttributeCode().startsWith(CONTENT_ATTR_PREFIX)) {
                langs.add(av.getAttributeCode().substring(CONTENT_ATTR_PREFIX.length(), CONTENT_ATTR_PREFIX.length() + 2));
                final int chunkIndex = NumberUtils.toInt(av.getAttributeCode().substring(av.getAttributeCode().lastIndexOf('_') + 1));
                maxChunks = Math.max(maxChunks, chunkIndex);
            }
        }

        final Tag body = tag.tag("body");
        final Map<String, AttrValue> attrMap = content.getAllAttributesAsMap();
        for (final String lang : langs) {
            final Map<String, String> sortedMap = new TreeMap<>();
            for (int i = 1; i <= maxChunks; i++) {
                final String key = CONTENT_ATTR_PREFIX + lang + '_' + i;
                final AttrValue chunk = attrMap.get(key);
                if (chunk != null) {
                    sortedMap.put(key, chunk.getVal());
                }
            }
            final StringBuilder fullContent = new StringBuilder();
            for (final Map.Entry<String, String> entry : sortedMap.entrySet()) {
                fullContent.append(entry.getValue());
            }
            body.tag("body-content").attr("lang", lang).cdata(fullContent.toString()).end();

        }
        body.end();

        return tag
                .tagTime(content)
            .end();

    }