Search in sources :

Example 1 with ObjectUtils.defaultIfNull

use of org.apache.commons.lang3.ObjectUtils.defaultIfNull in project plugin-prov by ligoj.

the class ProvQuoteInstanceResource method lookup.

private QuoteInstanceLookup lookup(final ProvQuote configuration, final double cpu, final int ram, final Boolean constant, final VmOs osName, final String type, final boolean ephemeral, final String location, final String usageName) {
    final String node = configuration.getSubscription().getNode().getId();
    final int subscription = configuration.getSubscription().getId();
    // Resolve
    final VmOs os = Optional.ofNullable(osName).map(VmOs::toPricingOs).orElse(null);
    // Resolve the location to use
    final String locationR = location == null ? configuration.getLocation().getName() : location;
    // Compute the rate to use
    final ProvUsage usage = usageName == null ? ObjectUtils.defaultIfNull(configuration.getUsage(), USAGE_DEFAULT) : resource.findConfiguredByName(usageRepository, usageName, subscription);
    final double rate = usage.getRate() / 100d;
    final int duration = usage.getDuration();
    // Resolve the required instance type
    final Integer typeId = type == null ? null : assertFound(itRepository.findByName(subscription, type), type).getId();
    // Return only the first matching instance
    // Template instance
    final QuoteInstanceLookup template = ipRepository.findLowestPrice(node, cpu, ram, constant, os, typeId, ephemeral, locationR, rate, duration, PageRequest.of(0, 1)).stream().findFirst().map(ip -> newPrice((ProvInstancePrice) ip[0], (double) ip[2])).orElse(null);
    // Custom instance
    final QuoteInstanceLookup custom = ipRepository.findLowestCustomPrice(node, Math.ceil(cpu), Math.ceil(ram / 1024), constant, os, locationR, PageRequest.of(0, 1)).stream().findFirst().map(ip -> newPrice((ProvInstancePrice) ip[0], rate * (double) ip[1])).orElse(null);
    // Select the best price term
    if (template == null) {
        return custom;
    }
    if (custom == null) {
        return template;
    }
    return custom.getCost() < template.getCost() ? custom : template;
}
Also used : CsvForBean(org.ligoj.bootstrap.core.csv.CsvForBean) Produces(javax.ws.rs.Produces) ProvInstancePriceRepository(org.ligoj.app.plugin.prov.dao.ProvInstancePriceRepository) Path(javax.ws.rs.Path) ProvUsageRepository(org.ligoj.app.plugin.prov.dao.ProvUsageRepository) Autowired(org.springframework.beans.factory.annotation.Autowired) StringUtils(org.apache.commons.lang3.StringUtils) ValidationJsonException(org.ligoj.bootstrap.core.validation.ValidationJsonException) MediaType(javax.ws.rs.core.MediaType) QueryParam(javax.ws.rs.QueryParam) ByteArrayInputStream(java.io.ByteArrayInputStream) Consumes(javax.ws.rs.Consumes) ProvLocation(org.ligoj.app.plugin.prov.model.ProvLocation) ProvInstanceTypeRepository(org.ligoj.app.plugin.prov.dao.ProvInstanceTypeRepository) DataTableAttributes(org.ligoj.bootstrap.core.json.datatable.DataTableAttributes) Map(java.util.Map) Multipart(org.apache.cxf.jaxrs.ext.multipart.Multipart) DefaultValue(javax.ws.rs.DefaultValue) Subscription(org.ligoj.app.model.Subscription) DescribedBean(org.ligoj.bootstrap.core.DescribedBean) DELETE(javax.ws.rs.DELETE) Context(javax.ws.rs.core.Context) Transactional(javax.transaction.Transactional) PageRequest(org.springframework.data.domain.PageRequest) Reader(java.io.Reader) StandardCharsets(java.nio.charset.StandardCharsets) ProvInstancePrice(org.ligoj.app.plugin.prov.model.ProvInstancePrice) Objects(java.util.Objects) ProvQuoteStorageRepository(org.ligoj.app.plugin.prov.dao.ProvQuoteStorageRepository) IOUtils(org.apache.commons.io.IOUtils) Slf4j(lombok.extern.slf4j.Slf4j) Optional(java.util.Optional) UriInfo(javax.ws.rs.core.UriInfo) TableItem(org.ligoj.bootstrap.core.json.TableItem) PathParam(javax.ws.rs.PathParam) GET(javax.ws.rs.GET) HashMap(java.util.HashMap) ArrayUtils(org.apache.commons.lang3.ArrayUtils) BooleanUtils(org.apache.commons.lang3.BooleanUtils) ProvQuoteInstance(org.ligoj.app.plugin.prov.model.ProvQuoteInstance) Function(java.util.function.Function) CollectionUtils(org.apache.commons.collections4.CollectionUtils) ObjectUtils(org.apache.commons.lang3.ObjectUtils) Service(org.springframework.stereotype.Service) ProvUsage(org.ligoj.app.plugin.prov.model.ProvUsage) POST(javax.ws.rs.POST) SequenceInputStream(java.io.SequenceInputStream) ProvQuoteInstanceRepository(org.ligoj.app.plugin.prov.dao.ProvQuoteInstanceRepository) IOException(java.io.IOException) InputStreamReader(java.io.InputStreamReader) ProvInstancePriceTermRepository(org.ligoj.app.plugin.prov.dao.ProvInstancePriceTermRepository) VmOs(org.ligoj.app.plugin.prov.model.VmOs) StringReader(java.io.StringReader) ProvInstancePriceTerm(org.ligoj.app.plugin.prov.model.ProvInstancePriceTerm) PUT(javax.ws.rs.PUT) ProvQuote(org.ligoj.app.plugin.prov.model.ProvQuote) BufferedReader(java.io.BufferedReader) ProvInstanceType(org.ligoj.app.plugin.prov.model.ProvInstanceType) InputStream(java.io.InputStream) VmOs(org.ligoj.app.plugin.prov.model.VmOs) ProvUsage(org.ligoj.app.plugin.prov.model.ProvUsage)

Example 2 with ObjectUtils.defaultIfNull

use of org.apache.commons.lang3.ObjectUtils.defaultIfNull in project plugin-prov by ligoj.

the class ProvQuoteStorageResource method lookup.

private List<QuoteStorageLoopup> lookup(final ProvQuote configuration, final int size, final Rate latency, final Integer instance, final ProvStorageOptimized optimized, final String location) {
    // Get the attached node and check the security on this subscription
    final String node = configuration.getSubscription().getNode().getRefined().getId();
    final ProvQuoteInstance qi = checkInstance(node, instance);
    // The the right location from instance first, then the request one
    String iLocation = Optional.ofNullable(qi).map(qiResource::getLocation).map(ProvLocation::getName).orElse(location);
    iLocation = ObjectUtils.defaultIfNull(iLocation, configuration.getLocation().getName());
    if (location != null && !location.equals(iLocation)) {
        // Not compatible locations
        return Collections.emptyList();
    }
    return spRepository.findLowestPrice(node, size, latency, instance, optimized, iLocation, PageRequest.of(0, 10)).stream().map(spx -> (ProvStoragePrice) spx[0]).map(sp -> newPrice(sp, size, getCost(sp, size))).collect(Collectors.toList());
}
Also used : ProvStorageType(org.ligoj.app.plugin.prov.model.ProvStorageType) PathParam(javax.ws.rs.PathParam) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) Path(javax.ws.rs.Path) Autowired(org.springframework.beans.factory.annotation.Autowired) ProvQuoteStorage(org.ligoj.app.plugin.prov.model.ProvQuoteStorage) ProvQuoteInstance(org.ligoj.app.plugin.prov.model.ProvQuoteInstance) Function(java.util.function.Function) ValidationJsonException(org.ligoj.bootstrap.core.validation.ValidationJsonException) MediaType(javax.ws.rs.core.MediaType) QueryParam(javax.ws.rs.QueryParam) ServicePluginLocator(org.ligoj.app.resource.ServicePluginLocator) Consumes(javax.ws.rs.Consumes) ProvLocation(org.ligoj.app.plugin.prov.model.ProvLocation) ObjectUtils(org.apache.commons.lang3.ObjectUtils) DataTableAttributes(org.ligoj.bootstrap.core.json.datatable.DataTableAttributes) Service(org.springframework.stereotype.Service) ProvStorageTypeRepository(org.ligoj.app.plugin.prov.dao.ProvStorageTypeRepository) DefaultValue(javax.ws.rs.DefaultValue) Rate(org.ligoj.app.plugin.prov.model.Rate) DescribedBean(org.ligoj.bootstrap.core.DescribedBean) DELETE(javax.ws.rs.DELETE) INamableBean(org.ligoj.bootstrap.core.INamableBean) POST(javax.ws.rs.POST) Context(javax.ws.rs.core.Context) Transactional(javax.transaction.Transactional) ProvQuoteInstanceRepository(org.ligoj.app.plugin.prov.dao.ProvQuoteInstanceRepository) PageRequest(org.springframework.data.domain.PageRequest) Collectors(java.util.stream.Collectors) ProvInstancePrice(org.ligoj.app.plugin.prov.model.ProvInstancePrice) ProvQuoteStorageRepository(org.ligoj.app.plugin.prov.dao.ProvQuoteStorageRepository) List(java.util.List) Optional(java.util.Optional) PUT(javax.ws.rs.PUT) ProvQuote(org.ligoj.app.plugin.prov.model.ProvQuote) ProvStoragePrice(org.ligoj.app.plugin.prov.model.ProvStoragePrice) UriInfo(javax.ws.rs.core.UriInfo) TableItem(org.ligoj.bootstrap.core.json.TableItem) Collections(java.util.Collections) ProvStorageOptimized(org.ligoj.app.plugin.prov.model.ProvStorageOptimized) ProvStoragePriceRepository(org.ligoj.app.plugin.prov.dao.ProvStoragePriceRepository) ProvQuoteInstance(org.ligoj.app.plugin.prov.model.ProvQuoteInstance)

Example 3 with ObjectUtils.defaultIfNull

use of org.apache.commons.lang3.ObjectUtils.defaultIfNull in project plugin-prov by ligoj.

the class ProvQuoteInstanceResource method saveOrUpdate.

/**
 * Save or update the given entity from the {@link QuoteInstanceEditionVo}. The computed cost are recursively
 * updated from the instance to the quote total cost.
 */
private UpdatedCost saveOrUpdate(final ProvQuoteInstance entity, final QuoteInstanceEditionVo vo) {
    // Compute the unbound cost delta
    final int deltaUnbound = BooleanUtils.toInteger(vo.getMaxQuantity() == null) - BooleanUtils.toInteger(entity.isUnboundCost());
    // Check the associations and copy attributes to the entity
    final ProvQuote configuration = getQuoteFromSubscription(vo.getSubscription());
    final Subscription subscription = configuration.getSubscription();
    final String providerId = subscription.getNode().getRefined().getId();
    DescribedBean.copy(vo, entity);
    entity.setConfiguration(configuration);
    final ProvLocation oldLocation = getLocation(entity);
    entity.setPrice(ipRepository.findOneExpected(vo.getPrice()));
    entity.setLocation(resource.findLocation(providerId, vo.getLocation()));
    entity.setUsage(Optional.ofNullable(vo.getUsage()).map(u -> resource.findConfiguredByName(usageRepository, u, subscription.getId())).orElse(null));
    entity.setOs(ObjectUtils.defaultIfNull(vo.getOs(), entity.getPrice().getOs()));
    entity.setRam(vo.getRam());
    entity.setCpu(vo.getCpu());
    entity.setConstant(vo.getConstant());
    entity.setEphemeral(vo.isEphemeral());
    entity.setInternet(vo.getInternet());
    entity.setMaxVariableCost(vo.getMaxVariableCost());
    entity.setMinQuantity(vo.getMinQuantity());
    entity.setMaxQuantity(vo.getMaxQuantity());
    resource.checkVisibility(entity.getPrice().getType(), providerId);
    checkConstraints(entity);
    checkOs(entity);
    // Update the unbound increment of the global quote
    configuration.setUnboundCostCounter(configuration.getUnboundCostCounter() + deltaUnbound);
    // Save and update the costs
    final UpdatedCost cost = newUpdateCost(entity);
    final Map<Integer, FloatingCost> storagesCosts = new HashMap<>();
    final boolean dirtyPrice = !oldLocation.equals(getLocation(entity));
    CollectionUtils.emptyIfNull(entity.getStorages()).stream().peek(s -> {
        if (dirtyPrice) {
            // Location has changed, the available storage price is invalidated
            storageResource.refresh(s);
            storageResource.refreshCost(s);
        }
    }).forEach(s -> storagesCosts.put(s.getId(), addCost(s, storageResource::updateCost)));
    cost.setRelatedCosts(storagesCosts);
    cost.setTotalCost(toFloatingCost(entity.getConfiguration()));
    return cost;
}
Also used : CsvForBean(org.ligoj.bootstrap.core.csv.CsvForBean) Produces(javax.ws.rs.Produces) ProvInstancePriceRepository(org.ligoj.app.plugin.prov.dao.ProvInstancePriceRepository) Path(javax.ws.rs.Path) ProvUsageRepository(org.ligoj.app.plugin.prov.dao.ProvUsageRepository) Autowired(org.springframework.beans.factory.annotation.Autowired) StringUtils(org.apache.commons.lang3.StringUtils) ValidationJsonException(org.ligoj.bootstrap.core.validation.ValidationJsonException) MediaType(javax.ws.rs.core.MediaType) QueryParam(javax.ws.rs.QueryParam) ByteArrayInputStream(java.io.ByteArrayInputStream) Consumes(javax.ws.rs.Consumes) ProvLocation(org.ligoj.app.plugin.prov.model.ProvLocation) ProvInstanceTypeRepository(org.ligoj.app.plugin.prov.dao.ProvInstanceTypeRepository) DataTableAttributes(org.ligoj.bootstrap.core.json.datatable.DataTableAttributes) Map(java.util.Map) Multipart(org.apache.cxf.jaxrs.ext.multipart.Multipart) DefaultValue(javax.ws.rs.DefaultValue) Subscription(org.ligoj.app.model.Subscription) DescribedBean(org.ligoj.bootstrap.core.DescribedBean) DELETE(javax.ws.rs.DELETE) Context(javax.ws.rs.core.Context) Transactional(javax.transaction.Transactional) PageRequest(org.springframework.data.domain.PageRequest) Reader(java.io.Reader) StandardCharsets(java.nio.charset.StandardCharsets) ProvInstancePrice(org.ligoj.app.plugin.prov.model.ProvInstancePrice) Objects(java.util.Objects) ProvQuoteStorageRepository(org.ligoj.app.plugin.prov.dao.ProvQuoteStorageRepository) IOUtils(org.apache.commons.io.IOUtils) Slf4j(lombok.extern.slf4j.Slf4j) Optional(java.util.Optional) UriInfo(javax.ws.rs.core.UriInfo) TableItem(org.ligoj.bootstrap.core.json.TableItem) PathParam(javax.ws.rs.PathParam) GET(javax.ws.rs.GET) HashMap(java.util.HashMap) ArrayUtils(org.apache.commons.lang3.ArrayUtils) BooleanUtils(org.apache.commons.lang3.BooleanUtils) ProvQuoteInstance(org.ligoj.app.plugin.prov.model.ProvQuoteInstance) Function(java.util.function.Function) CollectionUtils(org.apache.commons.collections4.CollectionUtils) ObjectUtils(org.apache.commons.lang3.ObjectUtils) Service(org.springframework.stereotype.Service) ProvUsage(org.ligoj.app.plugin.prov.model.ProvUsage) POST(javax.ws.rs.POST) SequenceInputStream(java.io.SequenceInputStream) ProvQuoteInstanceRepository(org.ligoj.app.plugin.prov.dao.ProvQuoteInstanceRepository) IOException(java.io.IOException) InputStreamReader(java.io.InputStreamReader) ProvInstancePriceTermRepository(org.ligoj.app.plugin.prov.dao.ProvInstancePriceTermRepository) VmOs(org.ligoj.app.plugin.prov.model.VmOs) StringReader(java.io.StringReader) ProvInstancePriceTerm(org.ligoj.app.plugin.prov.model.ProvInstancePriceTerm) PUT(javax.ws.rs.PUT) ProvQuote(org.ligoj.app.plugin.prov.model.ProvQuote) BufferedReader(java.io.BufferedReader) ProvInstanceType(org.ligoj.app.plugin.prov.model.ProvInstanceType) InputStream(java.io.InputStream) HashMap(java.util.HashMap) ProvLocation(org.ligoj.app.plugin.prov.model.ProvLocation) ProvQuote(org.ligoj.app.plugin.prov.model.ProvQuote) Subscription(org.ligoj.app.model.Subscription)

Example 4 with ObjectUtils.defaultIfNull

use of org.apache.commons.lang3.ObjectUtils.defaultIfNull in project midpoint by Evolveum.

the class AbstractOrgTabPanel method loadOrgRoots.

private List<PrismObject<OrgType>> loadOrgRoots() {
    Task task = getPageBase().createSimpleTask(OPERATION_LOAD_ORG_UNIT);
    OperationResult result = new OperationResult(OPERATION_LOAD_ORG_UNIT);
    List<PrismObject<OrgType>> list = new ArrayList<>();
    try {
        ObjectQuery query = getPageBase().getPrismContext().queryFor(OrgType.class).isRoot().asc(OrgType.F_NAME).build();
        ObjectFilter assignableItemsFilter = getAssignableItemsFilter();
        if (assignableItemsFilter != null) {
            query.addFilter(assignableItemsFilter);
        }
        list = getPageBase().getModelService().searchObjects(OrgType.class, query, null, task, result);
        // Sort org roots by displayOrder, if not set push the org to the end
        list.sort(new Comparator<PrismObject<OrgType>>() {

            @Override
            public int compare(PrismObject<OrgType> o1, PrismObject<OrgType> o2) {
                Comparator<PrismObject<OrgType>> intComparator = Comparator.comparingInt(o -> ((ObjectUtils.defaultIfNull(o.getRealValue().getDisplayOrder(), Integer.MAX_VALUE))));
                int compare = intComparator.compare(o1, o2);
                if (compare == 0) {
                    String display1 = WebComponentUtil.getDisplayName(o1);
                    if (StringUtils.isBlank(display1)) {
                        display1 = WebComponentUtil.getTranslatedPolyString(o1.getName());
                    }
                    String display2 = WebComponentUtil.getDisplayName(o2);
                    if (StringUtils.isBlank(display2)) {
                        display2 = WebComponentUtil.getTranslatedPolyString(o2.getName());
                    }
                    if (StringUtils.isEmpty(display1) && StringUtils.isEmpty(display2)) {
                        return compare;
                    }
                    if (StringUtils.isEmpty(display1)) {
                        return 1;
                    }
                    if (StringUtils.isEmpty(display2)) {
                        return -1;
                    }
                    return String.CASE_INSENSITIVE_ORDER.compare(display1, display2);
                }
                return compare;
            }
        });
        if (list.isEmpty() && isWarnMessageVisible()) {
            warn(getString("PageOrgTree.message.noOrgStructDefined"));
        }
    } catch (Exception ex) {
        LoggingUtils.logUnexpectedException(LOGGER, "Unable to load org. unit", ex);
        result.recordFatalError(getString("AbstractOrgTabPanel.message.loadOrgRoots.fatalError"), ex);
    } finally {
        result.computeStatus();
    }
    if (WebComponentUtil.showResultInPage(result)) {
        getPageBase().showResult(result);
    }
    return list;
}
Also used : OrgType(com.evolveum.midpoint.xml.ns._public.common.common_3.OrgType) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) Trace(com.evolveum.midpoint.util.logging.Trace) StringUtils(org.apache.commons.lang3.StringUtils) ObjectFilter(com.evolveum.midpoint.prism.query.ObjectFilter) ArrayList(java.util.ArrayList) ObjectUtils(org.apache.commons.lang3.ObjectUtils) ITab(org.apache.wicket.extensions.markup.html.tabs.ITab) AjaxRequestTarget(org.apache.wicket.ajax.AjaxRequestTarget) AjaxEventBehavior(org.apache.wicket.ajax.AjaxEventBehavior) IModel(org.apache.wicket.model.IModel) PolyString(com.evolveum.midpoint.prism.polystring.PolyString) AbstractTab(org.apache.wicket.extensions.markup.html.tabs.AbstractTab) Model(org.apache.wicket.model.Model) OrgStructurePanelStorage(com.evolveum.midpoint.web.session.OrgStructurePanelStorage) WebComponentUtil(com.evolveum.midpoint.gui.api.util.WebComponentUtil) PrismObject(com.evolveum.midpoint.prism.PrismObject) Task(com.evolveum.midpoint.task.api.Task) AjaxTabbedPanel(com.evolveum.midpoint.web.component.AjaxTabbedPanel) LoggingUtils(com.evolveum.midpoint.util.logging.LoggingUtils) Panel(org.apache.wicket.markup.html.panel.Panel) List(java.util.List) BasePanel(com.evolveum.midpoint.gui.api.component.BasePanel) WebMarkupContainer(org.apache.wicket.markup.html.WebMarkupContainer) PageBase(com.evolveum.midpoint.gui.api.page.PageBase) ObjectQuery(com.evolveum.midpoint.prism.query.ObjectQuery) Comparator(java.util.Comparator) TabbedPanel(com.evolveum.midpoint.web.component.TabbedPanel) LoadableModel(com.evolveum.midpoint.gui.api.model.LoadableModel) TraceManager(com.evolveum.midpoint.util.logging.TraceManager) Task(com.evolveum.midpoint.task.api.Task) ArrayList(java.util.ArrayList) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) ObjectFilter(com.evolveum.midpoint.prism.query.ObjectFilter) PolyString(com.evolveum.midpoint.prism.polystring.PolyString) ObjectQuery(com.evolveum.midpoint.prism.query.ObjectQuery) Comparator(java.util.Comparator) PrismObject(com.evolveum.midpoint.prism.PrismObject) OrgType(com.evolveum.midpoint.xml.ns._public.common.common_3.OrgType)

Example 5 with ObjectUtils.defaultIfNull

use of org.apache.commons.lang3.ObjectUtils.defaultIfNull in project commons-lang by apache.

the class ObjectUtilsTest method testIsNull.

// -----------------------------------------------------------------------
@Test
public void testIsNull() {
    final Object o = FOO;
    final Object dflt = BAR;
    assertSame("dflt was not returned when o was null", dflt, ObjectUtils.defaultIfNull(null, dflt));
    assertSame("dflt was returned when o was not null", o, ObjectUtils.defaultIfNull(o, dflt));
}
Also used : MutableObject(org.apache.commons.lang3.mutable.MutableObject) Test(org.junit.Test)

Aggregations

ObjectUtils (org.apache.commons.lang3.ObjectUtils)4 Optional (java.util.Optional)3 Function (java.util.function.Function)3 Transactional (javax.transaction.Transactional)3 Consumes (javax.ws.rs.Consumes)3 DELETE (javax.ws.rs.DELETE)3 DefaultValue (javax.ws.rs.DefaultValue)3 GET (javax.ws.rs.GET)3 POST (javax.ws.rs.POST)3 PUT (javax.ws.rs.PUT)3 Path (javax.ws.rs.Path)3 PathParam (javax.ws.rs.PathParam)3 Produces (javax.ws.rs.Produces)3 QueryParam (javax.ws.rs.QueryParam)3 Context (javax.ws.rs.core.Context)3 MediaType (javax.ws.rs.core.MediaType)3 UriInfo (javax.ws.rs.core.UriInfo)3 StringUtils (org.apache.commons.lang3.StringUtils)3 ProvQuoteInstanceRepository (org.ligoj.app.plugin.prov.dao.ProvQuoteInstanceRepository)3 ProvQuoteStorageRepository (org.ligoj.app.plugin.prov.dao.ProvQuoteStorageRepository)3