List of usage examples for java.math BigDecimal floatValue
@Override public float floatValue()
From source file:nl.strohalm.cyclos.aop.MessageAspect.java
/** * Send the low units notification if needed *//* w w w . ja va 2s . co m*/ private void notifyLowUnits(final Payment payment) { if (!(payment instanceof Transfer)) { return; } final Account account = fetchService.fetch(payment.getFrom(), RelationshipHelper.nested(Account.Relationships.TYPE, AccountType.Relationships.CURRENCY), RelationshipHelper.nested(Transfer.Relationships.FROM, MemberAccount.Relationships.MEMBER, Element.Relationships.GROUP)); if (!(account instanceof MemberAccount)) { return; } final MemberAccount memberAccount = (MemberAccount) account; final Group group = memberAccount.getMember().getGroup(); final AccountType accountType = account.getType(); final MemberGroupAccountSettings mgas = groupService.loadAccountSettings(group.getId(), accountType.getId()); final BigDecimal lowUnits = mgas.getLowUnits() == null ? BigDecimal.ZERO : mgas.getLowUnits(); // If low units message is used... if (lowUnits.floatValue() > PRECISION_DELTA && StringUtils.isNotEmpty(mgas.getLowUnitsMessage())) { doSendLowUnitsNotification(memberAccount, mgas); } }
From source file:org.plasma.sdo.helper.DataConverter.java
public Object fromDecimal(Type targetType, BigDecimal value) { DataType targetDataType = DataType.valueOf(targetType.getName()); switch (targetDataType) { case Decimal: return value; case Double: return new Double(value.doubleValue()); case Float: return new Float(value.floatValue()); case Int:/* w ww. j a v a 2 s .com*/ return new Integer(value.intValue()); case Long: return new Long(value.longValue()); case Integer: return value.toBigInteger(); case String: // as per spec: ('+'|'-')? [0-9]* ('.'[0-9]*)? (('E'|'e') ('+'|'-')? [0-9]+)? /* * [123,0] "123" * [-123,0] "-123" * [123,-1] "1.23E+3" * [123,-3] "1.23E+5" * [123,1] "12.3" * [123,5] "0.00123" * [123,10] "1.23E-8" * [-123,12] "-1.23E-10" */ return value.toString(); default: throw new InvalidDataConversionException(targetDataType, DataType.Decimal, value); } }
From source file:nl.strohalm.cyclos.services.transactions.PaymentServiceImpl.java
/** * Validates the given amount//from www . j ava 2 s. c o m */ private void validateAmount(final BigDecimal amount, Account fromAccount, final Account toAccount, final Transfer transfer) { // Validate the from account credit limit ... final LocalSettings localSettings = settingsService.getLocalSettings(); if (fromAccount != null) { final BigDecimal creditLimit = fromAccount.getCreditLimit(); if (creditLimit != null) { // ... only if not unlimited final AccountStatus fromStatus = accountService.getCurrentStatus(new AccountDTO(fromAccount)); if (creditLimit.abs().floatValue() > -PRECISION_DELTA) { final BigDecimal available = localSettings.round(fromStatus.getAvailableBalance()); if (available.subtract(amount).floatValue() < -PRECISION_DELTA) { final boolean isOriginalAccount = transfer == null ? true : fromAccount.equals(transfer.getRootTransfer().getFrom()); fromAccount = fetchService.fetch(fromAccount, Account.Relationships.TYPE); throw new NotEnoughCreditsException(fromAccount, amount, isOriginalAccount); } } } } // Validate the to account upper credit limit if (toAccount != null) { final BigDecimal upperCreditLimit = toAccount.getUpperCreditLimit(); if (upperCreditLimit != null && upperCreditLimit.floatValue() > PRECISION_DELTA) { final BigDecimal balance = accountService.getBalance(new AccountDateDTO(toAccount)); if (upperCreditLimit.subtract(balance).subtract(amount).floatValue() < -PRECISION_DELTA) { throw new UpperCreditLimitReachedException( localSettings.getUnitsConverter(toAccount.getType().getCurrency().getPattern()) .toString(toAccount.getUpperCreditLimit()), toAccount, amount); } } } }
From source file:com.visionet.platform.cooperation.service.OrderService.java
/** * ??/*w w w.j ava 2s .co m*/ * * @param meta * @return * @author ? */ public BigDecimal printInvoiceApplication(String meta) { if (StringUtils.isEmpty(meta)) { throw new BizException("meta??"); } MetaDTO metaDto = JSONObject.parseObject(meta, MetaDTO.class); Order result = orderMapper.selectByPrimaryKey(metaDto.getPartnerOrderNo()); if (result == null) { throw new BizException("??"); } // ???? if (result.getStatus() != 2) { throw new BizException("??,??"); } BigDecimal invoice = new BigDecimal(0); if ("apply_invoice".equals(metaDto.getStatus())) { Customer customer = customerMapper.selectOneByPhone(result.getCustomerPhone()); if (customer != null) { if (result.getTotalPrice() < customer.getInvoiceBalance()) { invoice = new BigDecimal(result.getTotalPrice()); Double balance = customer.getInvoiceBalance() - invoice.doubleValue(); customer.setInvoiceBalance(balance); } else { invoice = new BigDecimal(customer.getInvoiceBalance()); customer.setInvoiceBalance(0d); } // ? customerMapper.updateByPrimaryKeySelective(customer); // ???? Order order = new Order(); order.setOrderId(metaDto.getPartnerOrderNo()); order.setIsInvoice(1);// order.setOtherPrice2(invoice.floatValue()); orderMapper.updateByPrimaryKeySelective(order); } } return invoice; }
From source file:nl.strohalm.cyclos.services.transactions.PaymentServiceImpl.java
/** * Validates the max amount per day//w w w. jav a2 s. c om */ @Override public void validateMaxAmountAtDate(final Calendar date, final Account account, final TransferType transferType, BigDecimal maxAmountPerDay, final BigDecimal amount) { // Test the max amount per day maxAmountPerDay = maxAmountPerDay == null ? transferType.getMaxAmountPerDay() : maxAmountPerDay; if (maxAmountPerDay != null && maxAmountPerDay.floatValue() > PRECISION_DELTA) { // Get the amount on today BigDecimal amountOnDay = transferDao.getTransactionedAmountAt(date, account, transferType); // Validate if (amountOnDay.add(amount).compareTo(maxAmountPerDay) > 0) { throw new MaxAmountPerDayExceededException(date, transferType, account, amount); } } // Test the operator max amount per day if (LoggedUser.hasUser() && LoggedUser.isOperator()) { final Operator operator = LoggedUser.element(); OperatorGroup group = operator.getOperatorGroup(); group = fetchService.fetch(group, OperatorGroup.Relationships.MAX_AMOUNT_PER_DAY_BY_TRANSFER_TYPE); final BigDecimal maxAmount = group.getMaxAmountPerDayByTransferType().get(transferType); if (maxAmount != null && maxAmount.floatValue() > PRECISION_DELTA) { // Get the amount on today BigDecimal amountOnDay = transferDao.getTransactionedAmountAt(date, operator, account, transferType); // Validate if (amountOnDay.add(amount).compareTo(maxAmount) == 1) { throw new MaxAmountPerDayExceededException(date, transferType, account, amount); } } } }
From source file:it.drwolf.ridire.session.JobManager.java
public float getAnalyzedResourcesPercentage(Job j) { int res = 0;/*from w w w. j ava2s. co m*/ if (!this.analyzedResourcesPercentage.containsKey(j.getId())) { BigDecimal percentage = null; if (this.isSemanticCrawlerUser(j.getCrawlerUser())) { percentage = (BigDecimal) this.entityManager .createNativeQuery( "SELECT count(cr.id)/(SELECT count(cr2.id) FROM CrawledResource cr2 where cr2.job_id=:job1) FROM CrawledResource cr where cr.job_id=:job2 and (cr.semanticMetadatum_id is not null or cr.deleted=true) ") .setParameter("job1", j.getId()).setParameter("job2", j.getId()).getSingleResult(); } else { percentage = (BigDecimal) this.entityManager.createNativeQuery( "SELECT count(cr.id)/(SELECT count(cr2.id) FROM CrawledResource cr2 where cr2.job_id=:job1) FROM CrawledResource cr where cr.job_id=:job2 and (cr.functionalMetadatum_id is not null or cr.deleted=true) ") .setParameter("job1", j.getId()).setParameter("job2", j.getId()).getSingleResult(); } if (percentage == null) { percentage = new BigDecimal(0); } this.analyzedResourcesPercentage.put(j.getId(), Math.round(percentage.floatValue() * 10000)); } res = this.analyzedResourcesPercentage.get(j.getId()); return res; }
From source file:org.wso2.carbon.appmgt.impl.utils.AppManagerUtil.java
/** * This method used to get WebApp from governance artifact specific to * copyAPI// w w w .j a v a 2 s .c om * * @param artifact * WebApp artifact * @param registry * Registry * @return WebApp * @throws org.wso2.carbon.appmgt.api.AppManagementException * if failed to get WebApp from artifact */ public static WebApp getAPI(GovernanceArtifact artifact, Registry registry, APIIdentifier oldId) throws AppManagementException { WebApp api; try { String providerName = artifact.getAttribute(AppMConstants.API_OVERVIEW_PROVIDER); String apiName = artifact.getAttribute(AppMConstants.API_OVERVIEW_NAME); String apiVersion = artifact.getAttribute(AppMConstants.API_OVERVIEW_VERSION); api = new WebApp(new APIIdentifier(providerName, apiName, apiVersion)); // set rating String artifactPath = GovernanceUtils.getArtifactPath(registry, artifact.getId()); BigDecimal bigDecimal = new BigDecimal(registry.getAverageRating(artifactPath)); BigDecimal res = bigDecimal.setScale(1, RoundingMode.HALF_UP); api.setRating(res.floatValue()); // set description api.setDescription(artifact.getAttribute(AppMConstants.API_OVERVIEW_DESCRIPTION)); // set last access time api.setLastUpdated(registry.get(artifactPath).getLastModified()); // set url api.setUrl(artifact.getAttribute(AppMConstants.API_OVERVIEW_ENDPOINT_URL)); api.setLogoutURL(artifact.getAttribute(AppMConstants.API_OVERVIEW_LOGOUT_URL)); api.setSandboxUrl(artifact.getAttribute(AppMConstants.API_OVERVIEW_SANDBOX_URL)); api.setStatus(getApiStatus(artifact.getAttribute(AppMConstants.API_OVERVIEW_STATUS))); api.setThumbnailUrl(artifact.getAttribute(AppMConstants.API_OVERVIEW_THUMBNAIL_URL)); api.setWsdlUrl(artifact.getAttribute(AppMConstants.API_OVERVIEW_WSDL)); api.setWadlUrl(artifact.getAttribute(AppMConstants.API_OVERVIEW_WADL)); api.setTechnicalOwner(artifact.getAttribute(AppMConstants.API_OVERVIEW_TEC_OWNER)); api.setTechnicalOwnerEmail(artifact.getAttribute(AppMConstants.API_OVERVIEW_TEC_OWNER_EMAIL)); api.setBusinessOwner(artifact.getAttribute(AppMConstants.API_OVERVIEW_BUSS_OWNER)); api.setBusinessOwnerEmail(artifact.getAttribute(AppMConstants.API_OVERVIEW_BUSS_OWNER_EMAIL)); api.setEndpointSecured( Boolean.parseBoolean(artifact.getAttribute(AppMConstants.API_OVERVIEW_ENDPOINT_SECURED))); api.setEndpointUTUsername(artifact.getAttribute(AppMConstants.API_OVERVIEW_ENDPOINT_USERNAME)); api.setEndpointUTPassword(artifact.getAttribute(AppMConstants.API_OVERVIEW_ENDPOINT_PASSWORD)); api.setTransports(artifact.getAttribute(AppMConstants.API_OVERVIEW_TRANSPORTS)); api.setEndpointConfig(artifact.getAttribute(AppMConstants.API_OVERVIEW_ENDPOINT_CONFIG)); api.setRedirectURL(artifact.getAttribute(AppMConstants.API_OVERVIEW_REDIRECT_URL)); api.setAppOwner(artifact.getAttribute(AppMConstants.API_OVERVIEW_OWNER)); api.setAdvertiseOnly( Boolean.parseBoolean(artifact.getAttribute(AppMConstants.API_OVERVIEW_ADVERTISE_ONLY))); api.setSubscriptionAvailability( artifact.getAttribute(AppMConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABILITY)); api.setSubscriptionAvailableTenants( artifact.getAttribute(AppMConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABLE_TENANTS)); api.setResponseCache(artifact.getAttribute(AppMConstants.API_OVERVIEW_RESPONSE_CACHING)); api.setSsoEnabled(artifact.getAttribute("sso_enableSso")); api.setUUID(artifact.getId()); api.setThumbnailUrl(artifact.getAttribute(AppMConstants.APP_IMAGES_THUMBNAIL)); int cacheTimeout = AppMConstants.API_RESPONSE_CACHE_TIMEOUT; try { cacheTimeout = Integer.parseInt(artifact.getAttribute(AppMConstants.API_OVERVIEW_CACHE_TIMEOUT)); } catch (NumberFormatException e) { // ignore } String tenantDomainName = MultitenantUtils.getTenantDomain(replaceEmailDomainBack(providerName)); int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager() .getTenantId(tenantDomainName); Set<Tier> availableTier = new HashSet<Tier>(); String tiers = artifact.getAttribute(AppMConstants.API_OVERVIEW_TIER); Map<String, Tier> definedTiers = getTiers(tenantId); if (tiers != null && !"".equals(tiers)) { String[] tierNames = tiers.split("\\|\\|"); for (String tierName : tierNames) { Tier definedTier = definedTiers.get(tierName); if (definedTier != null) { availableTier.add(definedTier); } else { log.warn("Unknown tier: " + tierName + " found on WebApp: " + apiName); } } } api.addAvailableTiers(availableTier); api.setContext(artifact.getAttribute(AppMConstants.API_OVERVIEW_CONTEXT)); api.setLatest(Boolean.valueOf(artifact.getAttribute(AppMConstants.API_OVERVIEW_IS_LATEST))); ArrayList<URITemplate> urlPatternsList; urlPatternsList = AppMDAO.getAllURITemplates(api.getContext(), oldId.getVersion()); Set<URITemplate> uriTemplates = new HashSet<URITemplate>(urlPatternsList); for (URITemplate uriTemplate : uriTemplates) { uriTemplate.setResourceURI(api.getUrl()); uriTemplate.setResourceSandboxURI(api.getSandboxUrl()); } api.setUriTemplates(uriTemplates); Set<String> tags = new HashSet<String>(); org.wso2.carbon.registry.core.Tag[] tag = registry.getTags(artifactPath); for (Tag tag1 : tag) { tags.add(tag1.getTagName()); } api.addTags(tags); api.setLastUpdated(registry.get(artifactPath).getLastModified()); //Set Lifecycle status if (artifact.getLifecycleState() != null && artifact.getLifecycleState() != "") { if (artifact.getLifecycleState().toUpperCase().equalsIgnoreCase(APIStatus.INREVIEW.getStatus())) { api.setLifeCycleStatus(APIStatus.INREVIEW); } else { api.setLifeCycleStatus(APIStatus.valueOf(artifact.getLifecycleState().toUpperCase())); } } api.setLifeCycleName(artifact.getLifecycleName()); } catch (GovernanceException e) { String msg = "Failed to get WebApp fro artifact "; throw new AppManagementException(msg, e); } catch (RegistryException e) { String msg = "Failed to get LastAccess time or Rating"; throw new AppManagementException(msg, e); } catch (UserStoreException e) { String msg = "Failed to get User Realm of WebApp Provider"; throw new AppManagementException(msg, e); } return api; }
From source file:com.gst.portfolio.loanaccount.service.LoanWritePlatformServiceJpaRepositoryImpl.java
private void checkIfLoanIsPaidInAdvance(final Long loanId, final BigDecimal transactionAmount) { BigDecimal overpaid = this.loanReadPlatformService.retrieveTotalPaidInAdvance(loanId).getPaidInAdvance(); if (overpaid == null || overpaid.equals(new BigDecimal(0)) || transactionAmount.floatValue() > overpaid.floatValue()) { if (overpaid == null) overpaid = BigDecimal.ZERO; throw new InvalidPaidInAdvanceAmountException(overpaid.toPlainString()); }/*from w w w . ja va 2 s . c om*/ }
From source file:com.salesmanager.core.module.impl.integration.payment.PaypalTransactionImpl.java
/** This can be invoked after a sale transaction **/ //public GatewayTransactionVO refundTransaction(MerchantStore store, // Order order, BigDecimal amnt) throws TransactionException { public GatewayTransactionVO refundTransaction(IntegrationKeys keys, IntegrationProperties properties, MerchantStore store, Order order, GatewayTransactionVO trx, Customer customer, CoreModuleService serviceDefinition, BigDecimal amnt) throws TransactionException { // TODO Auto-generated method stub try {//from ww w.j av a2 s . co m /* * '------------------------------------ ' The currencyCodeType and * paymentType ' are set to the selections made on the Integration * Assistant '------------------------------------ */ if (serviceDefinition == null) { // throw new // Exception("Central integration services not configured for " // + PaymentConstants.PAYMENT_LINKPOINTNAME + " and country id " // + origincountryid); log.error("Central integration services not configured for " + PaymentConstants.PAYMENT_PAYPALNAME + " and country id " + store.getCountry()); TransactionException te = new TransactionException( "Central integration services not configured for " + PaymentConstants.PAYMENT_PAYPALNAME + " and country id " + store.getCountry()); te.setErrorcode("01"); throw te; } String transactionId = trx.getTransactionID(); if (transactionId == null) { throw new TransactionException("capture Paypal authorizationId is null in GatewayTransaction"); } String amount = CurrencyUtil.displayFormatedAmountNoCurrency(amnt, Constants.CURRENCY_CODE_USD); // InetAddress addr = InetAddress.getLocalHost(); // Get IP Address // byte[] ipAddr = addr.getAddress(); // String ip = new String(ipAddr); // REQUEST // requiredSecurityParameters]&METHOD=RefundTransaction&AUTHORIZATIONID= // &AMT=99.12&REFUNDTYPE=Full|Partial // IPN // String ipnUrl = ReferenceUtil.buildSecureServerUrl() + // (String)conf.getString("core.salesmanager.checkout.paypalIpn"); String refundType = "Full"; boolean partial = false; if (amnt.doubleValue() < order.getTotal().doubleValue()) { partial = true; } if (partial) { refundType = "Partial"; } // String nvpstr = "&TRANSACTIONID=" + transactionId + // "&REFUNDTYPE=" + refundType + "&IPADDRESS=" + ip.toString(); String nvpstr = "&TRANSACTIONID=" + transactionId + "&REFUNDTYPE=" + refundType + "&CURRENCYCODE=" + order.getCurrency() + "&IPADDRESS="; if (amnt.floatValue() < order.getTotal().floatValue()) { partial = true; } if (partial) { nvpstr = nvpstr + "&AMT=" + amount + "&NOTE=Partial refund"; } Map nvp = httpcall(properties, serviceDefinition, "RefundTransaction", nvpstr); String strAck = nvp.get("ACK").toString(); if (strAck != null && strAck.equalsIgnoreCase("Success")) { /** * RESPONSE * [successResponseFields]&AUTHORIZATIONID= * &TRANSACTIONID * =&PARENTTRANSACTIONID= * &RECEIPTID * =&TRANSACTIONTYPE=express-checkout * &PAYMENTTYPE=instant&ORDERTIME=2006-08-15T17:31:38Z&AMT=99.12 * &CURRENCYCODE=USD&FEEAMT=3.29&TAXAMT=0.00&PAYMENTSTATUS= * Completed &PENDINGREASON=None&REASONCODE=None **/ String responseTransactionId = (String) nvp.get("REFUNDTRANSACTIONID"); String responseAuthorizationId = (String) nvp.get("REFUNDTRANSACTIONID"); try { Iterator it = nvp.keySet().iterator(); StringBuffer valueBuffer = new StringBuffer(); while (it.hasNext()) { String key = (String) it.next(); valueBuffer.append("[").append(key).append("=").append((String) nvp.get(key)).append("]"); } MerchantPaymentGatewayTrx gtrx = new MerchantPaymentGatewayTrx(); gtrx.setMerchantId(order.getMerchantId()); gtrx.setCustomerid(order.getCustomerId()); gtrx.setOrderId(order.getOrderId()); gtrx.setAmount(amnt); gtrx.setMerchantPaymentGwMethod(order.getPaymentModuleCode()); gtrx.setMerchantPaymentGwRespcode(strAck); gtrx.setMerchantPaymentGwOrderid(responseAuthorizationId);// AUTHORIZATIONID gtrx.setMerchantPaymentGwTrxid(responseTransactionId);// TRANSACTIONID gtrx.setMerchantPaymentGwAuthtype(String.valueOf(PaymentConstants.REFUND)); gtrx.setMerchantPaymentGwSession(""); // String cryptedvalue = // EncryptionUtil.encrypt(EncryptionUtil.generatekey(String.valueOf(order.getMerchantId())), // nvpstr); gtrx.setMerchantPaymentGwSent(nvpstr); gtrx.setMerchantPaymentGwReceived(valueBuffer.toString()); gtrx.setDateAdded(new Date(new Date().getTime())); PaymentService pservice = (PaymentService) ServiceFactory .getService(ServiceFactory.PaymentService); pservice.saveMerchantPaymentGatewayTrx(gtrx); GatewayTransactionVO returnVo = new GatewayTransactionVO(); returnVo.setAmount(order.getTotal()); returnVo.setCreditcard(""); returnVo.setCreditcardtransaction(false); returnVo.setExpirydate(""); returnVo.setInternalGatewayOrderId(responseTransactionId); returnVo.setTransactionDetails(gtrx); returnVo.setOrderID(String.valueOf(order.getOrderId())); returnVo.setTransactionID(responseTransactionId); returnVo.setTransactionMessage((String) nvp.get("RESPONSE")); return returnVo; // insert an off system gateway transaction // for IPN usage // OffsystemPendingOrder pending = new // OffsystemPendingOrder(); // pending.setOrderId(order.getOrderId()); // pending.setTransactionId(payerID); // pending.setPayerEmail(order.getCustomerEmailAddress()); // pservice.saveOrUpdateOffsystemPendingOrder(pending, // order); } catch (Exception e) { TransactionException te = new TransactionException( "Can't persist MerchantPaymentGatewayTrx internal id (orderid)" + order.getOrderId(), e); te.setErrorcode("01"); throw te; } } else { String ErrorCode = nvp.get("L_ERRORCODE0").toString(); String ErrorShortMsg = nvp.get("L_SHORTMESSAGE0").toString(); String ErrorLongMsg = nvp.get("L_LONGMESSAGE0").toString(); String ErrorSeverityCode = nvp.get("L_SEVERITYCODE0").toString(); TransactionException te = new TransactionException("Paypal transaction refused " + ErrorLongMsg); te.setErrorType(ErrorConstants.PAYMENT_TRANSACTION_ERROR); LogMerchantUtil.log(order.getMerchantId(), "Paypal transaction error code[" + ErrorCode + "] " + ErrorLongMsg); if (ErrorCode.equals("10415")) {// transaction already submited te = new TransactionException("Paypal transaction refused " + ErrorLongMsg); te.setErrorType(ErrorConstants.PAYMENT_DUPLICATE_TRANSACTION); } throw te; } } catch (Exception e) { if (e instanceof TransactionException) { throw (TransactionException) e; } throw new TransactionException(e); } }
From source file:org.wso2.carbon.apimgt.impl.utils.APIUtil.java
/** * This method used to get API from governance artifact specific to copyAPI * * @param artifact API artifact/*from w ww . j av a2s. com*/ * @param registry Registry * @return API * @throws APIManagementException if failed to get API from artifact */ public static API getAPI(GovernanceArtifact artifact, Registry registry, APIIdentifier oldId, String oldContext) throws APIManagementException { API api; try { String providerName = artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER); String apiName = artifact.getAttribute(APIConstants.API_OVERVIEW_NAME); String apiVersion = artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION); api = new API(new APIIdentifier(providerName, apiName, apiVersion)); int apiId = ApiMgtDAO.getInstance().getAPIID(oldId, null); if (apiId == -1) { return null; } // set rating String artifactPath = GovernanceUtils.getArtifactPath(registry, artifact.getId()); BigDecimal bigDecimal = BigDecimal.valueOf(registry.getAverageRating(artifactPath)); BigDecimal res = bigDecimal.setScale(1, RoundingMode.HALF_UP); api.setRating(res.floatValue()); //set description api.setDescription(artifact.getAttribute(APIConstants.API_OVERVIEW_DESCRIPTION)); //set last access time api.setLastUpdated(registry.get(artifactPath).getLastModified()); //set uuid api.setUUID(artifact.getId()); // set url api.setStatus(getApiStatus(artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS))); api.setThumbnailUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_THUMBNAIL_URL)); api.setWsdlUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_WSDL)); api.setWadlUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_WADL)); api.setTechnicalOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER)); api.setTechnicalOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER_EMAIL)); api.setBusinessOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER)); api.setBusinessOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER_EMAIL)); api.setEndpointSecured( Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_SECURED))); api.setEndpointAuthDigest( Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_AUTH_DIGEST))); api.setEndpointUTUsername(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_USERNAME)); api.setEndpointUTPassword(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_PASSWORD)); api.setTransports(artifact.getAttribute(APIConstants.API_OVERVIEW_TRANSPORTS)); api.setEndpointConfig(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_CONFIG)); api.setRedirectURL(artifact.getAttribute(APIConstants.API_OVERVIEW_REDIRECT_URL)); api.setApiOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_OWNER)); api.setAdvertiseOnly( Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ADVERTISE_ONLY))); api.setSubscriptionAvailability( artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABILITY)); api.setSubscriptionAvailableTenants( artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABLE_TENANTS)); api.setResponseCache(artifact.getAttribute(APIConstants.API_OVERVIEW_RESPONSE_CACHING)); api.setImplementation(artifact.getAttribute(APIConstants.PROTOTYPE_OVERVIEW_IMPLEMENTATION)); api.setVisibility(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY)); String tenantDomainName = MultitenantUtils.getTenantDomain(replaceEmailDomainBack(providerName)); int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager() .getTenantId(tenantDomainName); boolean isGlobalThrottlingEnabled = APIUtil.isAdvanceThrottlingEnabled(); if (isGlobalThrottlingEnabled) { String apiLevelTier = ApiMgtDAO.getInstance().getAPILevelTier(apiId); api.setApiLevelPolicy(apiLevelTier); } String tiers = artifact.getAttribute(APIConstants.API_OVERVIEW_TIER); Map<String, Tier> definedTiers = getTiers(tenantId); Set<Tier> availableTier = getAvailableTiers(definedTiers, tiers, apiName); api.addAvailableTiers(availableTier); api.setContext(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT)); api.setContextTemplate(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT_TEMPLATE)); api.setLatest(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_IS_LATEST))); ArrayList<URITemplate> urlPatternsList; Set<Scope> scopes = ApiMgtDAO.getInstance().getAPIScopes(oldId); api.setScopes(scopes); HashMap<String, String> resourceScopes; resourceScopes = ApiMgtDAO.getInstance().getResourceToScopeMapping(oldId); urlPatternsList = ApiMgtDAO.getInstance().getAllURITemplates(oldContext, oldId.getVersion()); Set<URITemplate> uriTemplates = new HashSet<URITemplate>(urlPatternsList); for (URITemplate uriTemplate : uriTemplates) { uriTemplate.setResourceURI(api.getUrl()); uriTemplate.setResourceSandboxURI(api.getSandboxUrl()); String resourceScopeKey = APIUtil.getResourceKey(oldContext, oldId.getVersion(), uriTemplate.getUriTemplate(), uriTemplate.getHTTPVerb()); uriTemplate.setScope(findScopeByKey(scopes, resourceScopes.get(resourceScopeKey))); } api.setUriTemplates(uriTemplates); Set<String> tags = new HashSet<String>(); Tag[] tag = registry.getTags(artifactPath); for (Tag tag1 : tag) { tags.add(tag1.getTagName()); } api.addTags(tags); api.setLastUpdated(registry.get(artifactPath).getLastModified()); api.setAsDefaultVersion( Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_IS_DEFAULT_VERSION))); String environments = artifact.getAttribute(APIConstants.API_OVERVIEW_ENVIRONMENTS); api.setEnvironments(extractEnvironmentsForAPI(environments)); api.setCorsConfiguration(getCorsConfigurationFromArtifact(artifact)); } catch (GovernanceException e) { String msg = "Failed to get API fro artifact "; throw new APIManagementException(msg, e); } catch (RegistryException e) { String msg = "Failed to get LastAccess time or Rating"; throw new APIManagementException(msg, e); } catch (UserStoreException e) { String msg = "Failed to get User Realm of API Provider"; throw new APIManagementException(msg, e); } return api; }