Java Code Examples for org.apache.commons.lang.math.NumberUtils#toInt()

The following examples show how to use org.apache.commons.lang.math.NumberUtils#toInt() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AppManageController.java    From cachecloud with Apache License 2.0 6 votes vote down vote up
/**
 * 应用重要性级别
 */
@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("");
}
 
Example 2
Source File: ExportDirectorImplService.java    From yes-cart with Apache License 2.0 6 votes vote down vote up
/** {@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());
            }}));
}
 
Example 3
Source File: AbstractMediaFileNameStrategyImpl.java    From yes-cart with Apache License 2.0 5 votes vote down vote up
/**
 * {@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;
}
 
Example 4
Source File: BulkEmptyAnonymousShoppingCartProcessorImpl.java    From yes-cart with Apache License 2.0 5 votes vote down vote up
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;

    }
 
Example 5
Source File: RedisConfigTemplateController.java    From cachecloud with Apache License 2.0 5 votes vote down vote up
/**
 * 初始化配置
 */
@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");
}
 
Example 6
Source File: AppManageController.java    From cachecloud with Apache License 2.0 5 votes vote down vote up
/**
 * 添加水平扩容节点
 * 
 * @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("");
}
 
Example 7
Source File: EchoClient.java    From JavaTutorial with Apache License 2.0 5 votes vote down vote up
/**
 * @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);
}
 
Example 8
Source File: CountConverterImpl.java    From IridiumApplicationTesting with MIT License 5 votes vote down vote up
@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);
}
 
Example 9
Source File: BaseCommand.java    From aion-germany with GNU General Public License v3.0 5 votes vote down vote up
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!");
}
 
Example 10
Source File: Connection.java    From cachecloud with Apache License 2.0 5 votes vote down vote up
/**
 * 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]);
			}
		}
	}
}
 
Example 11
Source File: BashVarImpl.java    From BashSupport with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 12
Source File: Server.java    From cachecloud with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 13
Source File: EchoServer.java    From JavaTutorial with Apache License 2.0 5 votes vote down vote up
/**
 * @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);
}
 
Example 14
Source File: AppController.java    From cachecloud with Apache License 2.0 5 votes vote down vote up
/**
 * 修改应用报警配置
 */
@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;
}
 
Example 15
Source File: ContentCms1XmlEntityHandler.java    From yes-cart with Apache License 2.0 4 votes vote down vote up
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();

    }
 
Example 16
Source File: ImageServiceImpl.java    From yes-cart with Apache License 2.0 4 votes vote down vote up
/**
 * {@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];

}
 
Example 17
Source File: MasterSlaveOffsetAlertStrategy.java    From cachecloud with Apache License 2.0 4 votes vote down vote up
/**
 * 格式:
 *     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;
}
 
Example 18
Source File: ManagerWsNodeServiceImpl.java    From yes-cart with Apache License 2.0 4 votes vote down vote up
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);

}
 
Example 19
Source File: RdsLocalBinlogEventParser.java    From canal-1.1.3 with Apache License 2.0 4 votes vote down vote up
@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);
    }
}
 
Example 20
Source File: AuthoringController.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
    * 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";
   }