List of usage examples for java.lang Short valueOf
@HotSpotIntrinsicCandidate public static Short valueOf(short s)
From source file:org.apache.ambari.server.controller.internal.UpgradeResourceProvider.java
private void makeServerSideStage(UpgradeContext context, RequestStageContainer request, UpgradeItemEntity entity, ServerSideActionTask task, boolean skippable, boolean allowRtery) throws AmbariException { Cluster cluster = context.getCluster(); Map<String, String> commandParams = new HashMap<String, String>(); commandParams.put(COMMAND_PARAM_CLUSTER_NAME, cluster.getClusterName()); commandParams.put(COMMAND_PARAM_VERSION, context.getVersion()); commandParams.put(COMMAND_PARAM_DIRECTION, context.getDirection().name().toLowerCase()); String itemDetail = entity.getText(); String stageText = StringUtils.abbreviate(entity.getText(), 255); switch (task.getType()) { case MANUAL: { ManualTask mt = (ManualTask) task; itemDetail = mt.message;//from ww w. ja va 2 s . c om if (null != mt.summary) { stageText = mt.summary; } entity.setText(itemDetail); if (null != mt.structuredOut) { commandParams.put(COMMAND_PARAM_STRUCT_OUT, mt.structuredOut); } break; } case CONFIGURE: { ConfigureTask ct = (ConfigureTask) task; Map<String, String> configProperties = ct.getConfigurationProperties(cluster); // if the properties are empty it means that the conditions in the // task did not pass; if (configProperties.isEmpty()) { stageText = "No conditions were met for this configuration task."; itemDetail = stageText; } else { commandParams.putAll(configProperties); // extract the config type, key and value to use to build the // summary and detail String configType = configProperties.get(ConfigureTask.PARAMETER_CONFIG_TYPE); String key = configProperties.get(ConfigureTask.PARAMETER_KEY); String value = configProperties.get(ConfigureTask.PARAMETER_VALUE); itemDetail = String.format("Updating config %s/%s to %s", configType, key, value); if (null != ct.summary) { stageText = ct.summary; } else { stageText = String.format("Updating Config %s", configType); } } entity.setText(itemDetail); break; } default: break; } ActionExecutionContext actionContext = new ActionExecutionContext(cluster.getClusterName(), Role.AMBARI_SERVER_ACTION.toString(), Collections.<RequestResourceFilter>emptyList(), commandParams); actionContext.setTimeout(Short.valueOf((short) -1)); actionContext.setIgnoreMaintenance(true); ExecuteCommandJson jsons = s_commandExecutionHelper.get().getCommandJson(actionContext, cluster); Stage stage = s_stageFactory.get().createNew(request.getId().longValue(), "/tmp/ambari", cluster.getClusterName(), cluster.getClusterId(), stageText, jsons.getClusterHostInfo(), jsons.getCommandParamsForStage(), jsons.getHostParamsForStage()); stage.setSkippable(skippable); long stageId = request.getLastStageId() + 1; if (0L == stageId) { stageId = 1L; } stage.setStageId(stageId); entity.setStageId(Long.valueOf(stageId)); // !!! hack hack hack String host = cluster.getAllHostsDesiredConfigs().keySet().iterator().next(); stage.addServerActionCommand(task.getImplementationClass(), getManagementController().getAuthName(), Role.AMBARI_SERVER_ACTION, RoleCommand.EXECUTE, cluster.getClusterName(), host, new ServiceComponentHostServerActionEvent(StageUtils.getHostName(), System.currentTimeMillis()), commandParams, itemDetail, null, Integer.valueOf(1200), allowRtery); request.addStages(Collections.singletonList(stage)); }
From source file:it.classhidra.core.controller.bean.java
private Object getPrimitiveArgument(String name, String s_value) { Object primArgument = null;/*from w ww. ja v a2 s . c o m*/ Class reqClass = (delegated == null) ? this.getClass() : delegated.getClass(); if (name.indexOf('.') > -1) { StringTokenizer st = new StringTokenizer(name, "."); /* Vector allfields=new Vector(); while(st.hasMoreTokens()) allfields.add(st.nextToken()); String complexName=""; for(int i=0;i<allfields.size()-1;i++){ complexName+=allfields.get(i); if(i!=allfields.size()-2) complexName+="."; } name = (String)allfields.get(allfields.size()-1); */ String complexName = ""; while (st.hasMoreTokens()) { String token = st.nextToken(); if (st.countTokens() > 0) complexName += token; if (st.countTokens() > 1) complexName += "."; if (st.countTokens() == 0) name = token; } Object writeObj = get(complexName); if (writeObj == null) return primArgument; reqClass = writeObj.getClass(); } try { java.lang.reflect.Method mtd = null; Class[] cls = new Class[0]; mtd = reqClass.getMethod("get" + util_reflect.adaptMethodName(name), cls); if (mtd != null) { Class primArgumentClass = mtd.getReturnType(); if (primArgumentClass.equals(double.class)) { primArgument = Double.valueOf(s_value); } else if (primArgumentClass.equals(int.class)) { primArgument = Integer.valueOf(s_value); } else if (primArgumentClass.equals(boolean.class)) { primArgument = Boolean.valueOf(s_value); } else if (primArgumentClass.equals(char.class)) { primArgument = s_value; } else if (primArgumentClass.equals(byte.class)) { primArgument = Byte.valueOf(s_value); } else if (primArgumentClass.equals(short.class)) { primArgument = Short.valueOf(s_value); } else if (primArgumentClass.equals(long.class)) { primArgument = Long.valueOf(s_value); } else if (primArgumentClass.equals(float.class)) { primArgument = Float.valueOf(s_value); } } } catch (Exception e) { } return primArgument; }
From source file:org.mifos.accounts.loan.business.LoanBOIntegrationTest.java
public void testApplyPeriodicFee() throws Exception { accountBO = getBasicLoanAccount();//from w ww. j a va2 s .co m Money intialTotalFeeAmount = ((LoanBO) accountBO).getLoanSummary().getOriginalFees(); TestObjectFactory.flushandCloseSession(); FeeBO periodicFee = TestObjectFactory.createPeriodicAmountFee("Periodic Fee", FeeCategory.LOAN, "200", RecurrenceType.WEEKLY, Short.valueOf("2")); accountBO = TestObjectFactory.getObject(AccountBO.class, accountBO.getAccountId()); UserContext uc = TestUtils.makeUser(); accountBO.setUserContext(uc); accountBO.applyCharge(periodicFee.getFeeId(), ((AmountFeeBO) periodicFee).getFeeAmount().getAmountDoubleValue()); StaticHibernateUtil.commitTransaction(); StaticHibernateUtil.closeSession(); accountBO = TestObjectFactory.getObject(AccountBO.class, accountBO.getAccountId()); Date lastAppliedDate = null; Map<String, String> fees1 = new HashMap<String, String>(); fees1.put("Periodic Fee", "200.0");// missing an entry fees1.put("Mainatnence Fee", "100.0"); LoanScheduleEntity[] paymentsArray = LoanBOTestUtils .getSortedAccountActionDateEntity(((LoanBO) accountBO).getAccountActionDates()); Assert.assertEquals(6, paymentsArray.length); checkFees(fees1, paymentsArray[0], false); checkFees(fees1, paymentsArray[2], false); checkFees(fees1, paymentsArray[4], false); for (AccountActionDateEntity accountActionDateEntity : accountBO.getAccountActionDates()) { LoanScheduleEntity loanScheduleEntity = (LoanScheduleEntity) accountActionDateEntity; if (loanScheduleEntity.getInstallmentId().equals(Short.valueOf("5"))) { Assert.assertEquals(2, loanScheduleEntity.getAccountFeesActionDetails().size()); lastAppliedDate = loanScheduleEntity.getActionDate(); } } Assert.assertEquals(intialTotalFeeAmount.add(new Money(getCurrency(), "600.0")), ((LoanBO) accountBO).getLoanSummary().getOriginalFees()); LoanActivityEntity loanActivityEntity = (LoanActivityEntity) ((LoanBO) accountBO).getLoanActivityDetails() .toArray()[0]; Assert.assertEquals(periodicFee.getFeeName() + " applied", loanActivityEntity.getComments()); Assert.assertEquals(((LoanBO) accountBO).getLoanSummary().getOriginalFees(), loanActivityEntity.getFeeOutstanding()); AccountFeesEntity accountFeesEntity = accountBO.getAccountFees(periodicFee.getFeeId()); Assert.assertEquals(FeeStatus.ACTIVE, accountFeesEntity.getFeeStatusAsEnum()); Assert.assertEquals(DateUtils.getDateWithoutTimeStamp(lastAppliedDate.getTime()), DateUtils.getDateWithoutTimeStamp(accountFeesEntity.getLastAppliedDate().getTime())); }
From source file:it.classhidra.core.controller.bean.java
public void set(String name, short value) { Object primArgument = getPrimitiveArgument(name, String.valueOf(value)); try {//from ww w . j a v a 2 s .co m if (primArgument != null) setCampoValueWithPoint(name, primArgument); else setCampoValueWithPoint(name, Short.valueOf(value)); } catch (Exception e) { } }
From source file:edu.ku.brc.specify.tasks.WorkbenchTask.java
/** * If the colInfo Vector is null then all the templates are added to the list to be displayed.<br> * If not, then it checks all the column in the file against the columns in each Template to see if there is a match * and then uses that.//from w w w.j a va 2 s. com * show a Dialog and returns null if there are not templates or none match. * @param colInfo the column info * @param helpContext the help context * * @return a List. The first element in the pair is false then the selection was cancelled. * Otherwise, the second element will be the selected WorkbenchTemplate or null if a new template should be created, * and the third element will be a list of columns that are not used in the selected template */ public List<?> selectExistingTemplate(final Vector<ImportColumnInfo> colInfo, final String helpContext) { WorkbenchTemplate selection = null; if (colInfo != null) { Collections.sort(colInfo); } Vector<WorkbenchTemplate> matchingTemplates = new Vector<WorkbenchTemplate>(); HashMap<WorkbenchTemplate, Vector<?>> unMappedCols = new HashMap<WorkbenchTemplate, Vector<?>>(); // Check for any matches with existing templates DataProviderSessionIFace session = DataProviderFactory.getInstance().createSession(); try { //List<?> list = session.getDataList("From WorkbenchTemplate where SpecifyUserID = " + AppContextMgr.getInstance().getClassObject(SpecifyUser.class).getSpecifyUserId()); List<?> list = session.getDataList("From WorkbenchTemplate"); for (Object obj : list) { WorkbenchTemplate template = (WorkbenchTemplate) obj; if (colInfo == null) { template.forceLoad(); matchingTemplates.add(template); //} else if (colInfo.size() <= template.getWorkbenchTemplateMappingItems().size()) } else if (colInfo.size() == template.getWorkbenchTemplateMappingItems().size()) { boolean match = true; Vector<WorkbenchTemplateMappingItem> items = new Vector<WorkbenchTemplateMappingItem>( template.getWorkbenchTemplateMappingItems()); Vector<ImportColumnInfo> mapped = new Vector<ImportColumnInfo>(); for (ImportColumnInfo col : colInfo) { int idx = indexOfName(items, col.getColName()); if (idx != -1) { mapped.add(col); items.get(idx).setViewOrder(Short.valueOf(col.getColInx().toString())); items.get(idx).setOrigImportColumnIndex(Short.valueOf(col.getColInx().toString())); } else { match = false; break; } } if (match) { Vector<WorkbenchTemplateMappingItem> unmapped = new Vector<WorkbenchTemplateMappingItem>(); for (WorkbenchTemplateMappingItem item : items) { if (indexOfName(mapped, item.getImportedColName()) == -1) { unmapped.add(item); //item.setViewOrder(c++); } } if (unmapped.size() == 0) { matchingTemplates.insertElementAt(template, 0); //put full matches at head of list } else { matchingTemplates.add(template); } unMappedCols.put(template, unmapped); //for (WorkbenchTemplateMappingItem unmappedItem : unmapped) //{ // template.getWorkbenchTemplateMappingItems().remove(unmappedItem); //} } } // else if (colInfo.size() > template.getWorkbenchTemplateMappingItems().size()) // { // boolean match = true; // Vector<WorkbenchTemplateMappingItem> items = new Vector<WorkbenchTemplateMappingItem>(template.getWorkbenchTemplateMappingItems()); // Vector<ImportColumnInfo> mapped = new Vector<ImportColumnInfo>(); // for (WorkbenchTemplateMappingItem item : items) // { // int idx = indexOfName(colInfo, item.getImportedColName()); // if (idx != -1) // { // mapped.add(colInfo.get(idx)); // item.setViewOrder(Short.valueOf(colInfo.get(idx).getColInx().toString())); // item.setOrigImportColumnIndex(Short.valueOf(colInfo.get(idx).getColInx().toString())); // } // } // for (int i=0; i<items.size(); i++) // { // WorkbenchTemplateMappingItem wbItem = items.get(i); // int origIdx = wbItem.getOrigImportColumnIndex().intValue(); // if (origIdx == -1) // { // //try the viewOrder // origIdx = wbItem.getViewOrder().intValue(); // } // ImportColumnInfo fileItem = origIdx > -1 && origIdx < colInfo.size() ? colInfo.get(origIdx) : null; // // Check to see if there is an exact match by name // if (colsMatchByName(wbItem, fileItem)) // { // //might do additional type checking // mapped.add(fileItem); // } // else // { // //log.error("["+wbItem.getImportedColName()+"]["+fileItem.getColName()+"]"); // match = false; // break; // } // } // // All columns match with their order etc. // if (match) // { // matchingTemplates.add(template); // Vector<ImportColumnInfo> unmapped = new Vector<ImportColumnInfo>(); // for (ImportColumnInfo fileItem : colInfo) // { // if (mapped.indexOf(fileItem) == -1) // { // unmapped.add(fileItem); // } // } // unMappedCols.put(template, unmapped); // } // } } } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(WorkbenchTask.class, ex); log.error(ex); ex.printStackTrace(); } finally { session.close(); } Vector<Object> result = new Vector<Object>(); // Ask the user to choose an existing template. if (matchingTemplates.size() > 0) { SelectNewOrExistingDlg<WorkbenchTemplate> dlg = new SelectNewOrExistingDlg<WorkbenchTemplate>( (Frame) UIRegistry.get(UIRegistry.FRAME), "WB_CHOOSE_DATASET_REUSE_TITLE", "WB_CREATE_NEW_MAPPING", "WB_USE_EXISTING_MAPPING", helpContext, matchingTemplates); UIHelper.centerAndShow(dlg); if (dlg.getBtnPressed() == ChooseFromListDlg.OK_BTN) { if (!dlg.isCreateNew()) { selection = dlg.getSelectedObject(); Vector<?> unmapped = unMappedCols.get(selection); if (unmapped != null && unmapped.size() > 0) { StringBuilder flds = new StringBuilder(); for (Object info : unmapped) //if there are a lot of these the message will be ugly { if (flds.length() != 0) { flds.append(", "); } flds.append(info.toString()); } String msg = unmapped.get(0) instanceof ImportColumnInfo ? String.format(UIRegistry.getResourceString("WB_UNMAPPED_NOT_IMPORTED"), flds.toString()) : String.format(UIRegistry.getResourceString("WB_UNUSED_NOT_INCLUDED"), flds.toString()); if (!UIRegistry.displayConfirm(UIRegistry.getResourceString("WB_INCOMPLETE_MAP_TITLE"), msg, UIRegistry.getResourceString("YES"), UIRegistry.getResourceString("NO"), JOptionPane.WARNING_MESSAGE)) { result.add(true); return result; // means create a new one } } // for (WorkbenchTemplateMappingItem mi : selection.getWorkbenchTemplateMappingItems()) // { // System.out.println(mi.getImportedColName() + " - " + mi.getViewOrder()); // } result.add(true); result.add(selection); result.add(unMappedCols.get(selection)); return result; // means reuse an existing one } result.add(true); return result; // means create a new one } result.add(false); return result; //cancelled } result.add(true); return result; // means create a new one }
From source file:com.aimluck.eip.mail.util.ALMailUtils.java
/** * ???//w w w. j av a 2 s . co m * * @param rundata * @param msgList * @param userId * @param accountName * @param accountType * @param mailAddress * @param mailUserName * @param smtpServerName * @param smtpPort * @param Pop3ServerName * @param pop3Port * @param pop3UserName * @param pop3Password * @param authSendFlag * @param authSendUserId * @param authSendUserPasswd * @param authReceiveFlg * @param delAtPop3Flg * @param delAtPop3BeforeDaysFlg * @param delAtPop3BeforeDays * @param nonReceivedFlg * @param signature * @param smtpEncryptionFlg * @param pop3EncryptionFlg * @return */ public static boolean insertMailAccountData(RunData rundata, List<String> msgList, int userId, String accountName, int accountType, String mailAddress, String mailUserName, String smtpServerName, int smtpPort, String Pop3ServerName, int pop3Port, String pop3UserName, String pop3Password, int authSendFlag, String authSendUserId, String authSendUserPasswd, int authReceiveFlg, int delAtPop3Flg, int delAtPop3BeforeDaysFlg, int delAtPop3BeforeDays, String nonReceivedFlg, String signature, int smtpEncryptionFlg, int pop3EncryptionFlg) { boolean enableUpdate = false; try { Date createdDate = Calendar.getInstance().getTime(); EipMMailAccount mailAccount = null; EipTMailFolder mailFolder = null; if (accountType == ACCOUNT_TYPE_INIT) { mailAccount = Database.create(EipMMailAccount.class); mailAccount.setAccountType(Integer.toString(ACCOUNT_TYPE_INIT)); } else { SelectQuery<EipMMailAccount> query = Database.query(EipMMailAccount.class); Expression exp1 = ExpressionFactory.matchExp(EipMMailAccount.USER_ID_PROPERTY, Integer.valueOf(userId)); Expression exp2 = ExpressionFactory.matchExp(EipMMailAccount.ACCOUNT_TYPE_PROPERTY, Integer.valueOf(ACCOUNT_TYPE_INIT)); EipMMailAccount account = query.andQualifier(exp1).andQualifier(exp2).fetchSingle(); if (account == null) { // ? mailAccount = Database.create(EipMMailAccount.class); SelectQuery<EipMMailAccount> query3 = Database.query(EipMMailAccount.class); Expression exp3 = ExpressionFactory.matchExp(EipMMailAccount.USER_ID_PROPERTY, Integer.valueOf(userId)); EipMMailAccount anotherAccount = query3.andQualifier(exp3).fetchSingle(); if (anotherAccount == null) { mailAccount.setAccountType(Integer.toString(ACCOUNT_TYPE_DEFAULT)); } else { mailAccount.setAccountType(Integer.toString(ACCOUNT_TYPE_NON)); } } else { mailAccount = account; if (Integer.toString(ACCOUNT_TYPE_INIT).equals(account.getAccountType())) { enableUpdate = true; mailAccount.setAccountType(Integer.toString(ACCOUNT_TYPE_DEFAULT)); } else { mailAccount.setAccountType(Integer.toString(ACCOUNT_TYPE_NON)); } } } // ID mailAccount.setUserId(Integer.valueOf(userId)); mailAccount.setAccountName(accountName); mailAccount.setSmtpserverName(smtpServerName); mailAccount.setPop3serverName(Pop3ServerName); mailAccount.setPop3userName(pop3UserName); mailAccount.setPop3password(ALMailUtils.getEncryptedMailAccountPasswd(pop3Password.getBytes())); mailAccount.setMailUserName(mailUserName); mailAccount.setMailAddress(mailAddress); mailAccount.setSmtpPort(Integer.toString(smtpPort)); mailAccount.setPop3Port(Integer.toString(pop3Port)); mailAccount.setAuthSendFlg((short) authSendFlag); mailAccount.setAuthSendUserId(authSendUserId); if (authSendUserPasswd != null) { mailAccount.setAuthSendUserPasswd( ALMailUtils.getEncryptedMailAccountPasswd(authSendUserPasswd.getBytes())); } mailAccount.setSmtpEncryptionFlg((short) smtpEncryptionFlg); mailAccount.setPop3EncryptionFlg((short) pop3EncryptionFlg); mailAccount.setAuthReceiveFlg(Short.valueOf((short) authReceiveFlg)); mailAccount.setDelAtPop3Flg(Integer.toString(delAtPop3Flg)); mailAccount.setDelAtPop3BeforeDaysFlg(Integer.toString(delAtPop3BeforeDaysFlg)); mailAccount.setDelAtPop3BeforeDays(Integer.valueOf(delAtPop3BeforeDays)); mailAccount.setNonReceivedFlg(nonReceivedFlg); mailAccount.setUpdateDate(createdDate); mailAccount.setSignature(signature); if (!enableUpdate) { // ?? mailAccount.setCreateDate(createdDate); } // ???? mailFolder = Database.create(EipTMailFolder.class); mailFolder.setEipMMailAccount(mailAccount); mailFolder.setFolderName(EipTMailFolder.DEFAULT_FOLDER_NAME); mailFolder.setCreateDate(createdDate); mailFolder.setUpdateDate(createdDate); Database.commit(); // ?ID mailAccount.setDefaultFolderId(mailFolder.getFolderId()); Database.commit(); // ?? ALEventlogFactoryService.getInstance().getEventlogHandler().log(mailAccount.getAccountId(), ALEventlogConstants.PORTLET_TYPE_WEBMAIL_ACCOUNT, mailAccount.getAccountName()); } catch (Throwable t) { Database.rollback(); logger.error("ALMailUtils.insertMailAccountData", t); return false; } return true; }
From source file:com.cloud.api.ApiServer.java
public void loginUser(HttpSession session, String username, String password, Long domainId, String domainPath, String loginIpAddress, Map<String, Object[]> requestParameters) throws CloudAuthenticationException { // We will always use domainId first. If that does not exist, we will use domain name. If THAT doesn't exist // we will default to ROOT if (domainId == null) { if (domainPath == null || domainPath.trim().length() == 0) { domainId = DomainVO.ROOT_DOMAIN; } else {/* w w w .j a va2s .c o m*/ Domain domainObj = _domainMgr.findDomainByPath(domainPath); if (domainObj != null) { domainId = domainObj.getId(); } else { // if an unknown path is passed in, fail the login call throw new CloudAuthenticationException("Unable to find the domain from the path " + domainPath); } } } UserAccount userAcct = _accountMgr.authenticateUser(username, password, domainId, loginIpAddress, requestParameters); if (userAcct != null) { String timezone = userAcct.getTimezone(); float offsetInHrs = 0f; if (timezone != null) { TimeZone t = TimeZone.getTimeZone(timezone); s_logger.info("Current user logged in under " + timezone + " timezone"); java.util.Date date = new java.util.Date(); long longDate = date.getTime(); float offsetInMs = (t.getOffset(longDate)); offsetInHrs = offsetInMs / (1000 * 60 * 60); s_logger.info("Timezone offset from UTC is: " + offsetInHrs); } Account account = _accountMgr.getAccount(userAcct.getAccountId()); // set the userId and account object for everyone session.setAttribute("userid", userAcct.getId()); UserVO user = (UserVO) _accountMgr.getActiveUser(userAcct.getId()); if (user.getUuid() != null) { session.setAttribute("user_UUID", user.getUuid()); } session.setAttribute("username", userAcct.getUsername()); session.setAttribute("firstname", userAcct.getFirstname()); session.setAttribute("lastname", userAcct.getLastname()); session.setAttribute("accountobj", account); session.setAttribute("account", account.getAccountName()); session.setAttribute("domainid", account.getDomainId()); DomainVO domain = (DomainVO) _domainMgr.getDomain(account.getDomainId()); if (domain.getUuid() != null) { session.setAttribute("domain_UUID", domain.getUuid()); } session.setAttribute("type", Short.valueOf(account.getType()).toString()); session.setAttribute("registrationtoken", userAcct.getRegistrationToken()); session.setAttribute("registered", new Boolean(userAcct.isRegistered()).toString()); if (timezone != null) { session.setAttribute("timezone", timezone); session.setAttribute("timezoneoffset", Float.valueOf(offsetInHrs).toString()); } // (bug 5483) generate a session key that the user must submit on every request to prevent CSRF, add that // to the login response so that session-based authenticators know to send the key back SecureRandom sesssionKeyRandom = new SecureRandom(); byte sessionKeyBytes[] = new byte[20]; sesssionKeyRandom.nextBytes(sessionKeyBytes); String sessionKey = Base64.encodeBase64String(sessionKeyBytes); session.setAttribute("sessionkey", sessionKey); return; } throw new CloudAuthenticationException("Failed to authenticate user " + username + " in domain " + domainId + "; please provide valid credentials"); }
From source file:org.apache.poi.hssf.usermodel.CopyOfHSSFWorkbook.java
/** * Get the font at the given index number * @param idx index number/*from ww w . ja v a 2s .com*/ * @return HSSFFont at the index */ public HSSFFont getFontAt(short idx) { if (fonts == null) fonts = new Hashtable<Short, HSSFFont>(); // So we don't confuse users, give them back // the same object every time, but create // them lazily Short sIdx = Short.valueOf(idx); if (fonts.containsKey(sIdx)) { return fonts.get(sIdx); } FontRecord font = workbook.getFontRecordAt(idx); HSSFFont retval = new HSSFFont(idx, font); fonts.put(sIdx, retval); return retval; }
From source file:org.codice.ddf.rest.impl.CatalogServiceImpl.java
private void parseAttribute(Map<String, AttributeImpl> attributeMap, String parsedName, InputStream inputStream, AttributeType.AttributeFormat attributeFormat) { try (InputStream is = inputStream; InputStream boundedStream = new BoundedInputStream(is, MAX_INPUT_SIZE + 1L)) { if (attributeFormat == OBJECT) { LOGGER.debug("Object type not supported for override"); return; }/*from www. j ava 2 s .c om*/ byte[] bytes = IOUtils.toByteArray(boundedStream); if (bytes.length > MAX_INPUT_SIZE) { LOGGER.debug("Attribute length is limited to {} bytes", MAX_INPUT_SIZE); return; } AttributeImpl attribute; if (attributeMap.containsKey(parsedName)) { attribute = attributeMap.get(parsedName); } else { attribute = new AttributeImpl(parsedName, Collections.emptyList()); attributeMap.put(parsedName, attribute); } if (attributeFormat == BINARY) { attribute.addValue(bytes); return; } String value = new String(bytes, Charset.defaultCharset()); switch (attributeFormat) { case XML: case GEOMETRY: case STRING: attribute.addValue(value); break; case BOOLEAN: attribute.addValue(Boolean.valueOf(value)); break; case SHORT: attribute.addValue(Short.valueOf(value)); break; case LONG: attribute.addValue(Long.valueOf(value)); break; case INTEGER: attribute.addValue(Integer.valueOf(value)); break; case FLOAT: attribute.addValue(Float.valueOf(value)); break; case DOUBLE: attribute.addValue(Double.valueOf(value)); break; case DATE: try { Instant instant = Instant.parse(value); attribute.addValue(Date.from(instant)); } catch (DateTimeParseException e) { LOGGER.debug("Unable to parse instant '{}'", attribute, e); } break; default: LOGGER.debug("Attribute format '{}' not supported", attributeFormat); break; } } catch (IOException e) { LOGGER.debug("Unable to read attribute to override", e); } }
From source file:com.workday.autoparse.json.parser.JsonParserUtils.java
public static Short nextShort(JsonReader reader, String name) throws IOException { if (handleNull(reader)) { return 0; }//from w ww .ja v a 2 s . c o m assertType(reader, name, JsonToken.NUMBER, JsonToken.STRING); return Short.valueOf(reader.nextString()); }