Java Code Examples for javax.persistence.Tuple#get()

The following examples show how to use javax.persistence.Tuple#get() . 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: BridgeNameFinder.java    From zstack with Apache License 2.0 6 votes vote down vote up
@Transactional(readOnly = true)
public Map<String, String> findByL3Uuids(Collection<String> l3Uuids) {
    String sql = "select t.tag, l3.uuid" +
            " from SystemTagVO t, L3NetworkVO l3" +
            " where t.resourceType = :ttype" +
            " and t.tag like :tag" +
            " and t.resourceUuid = l3.l2NetworkUuid" +
            " and l3.uuid in (:l3Uuids)" +
            " group by l3.uuid";
    TypedQuery<Tuple> tq = dbf.getEntityManager().createQuery(sql, Tuple.class);
    tq.setParameter("tag", TagUtils.tagPatternToSqlPattern(KVMSystemTags.L2_BRIDGE_NAME.getTagFormat()));
    tq.setParameter("l3Uuids", l3Uuids);
    tq.setParameter("ttype", L2NetworkVO.class.getSimpleName());
    List<Tuple> ts = tq.getResultList();

    Map<String, String> bridgeNames = new HashMap<>();
    for (Tuple t : ts) {
        String brToken = t.get(0, String.class);
        String l3Uuid = t.get(1, String.class);
        bridgeNames.put(l3Uuid, KVMSystemTags.L2_BRIDGE_NAME.getTokenByTag(brToken, KVMSystemTags.L2_BRIDGE_NAME_TOKEN));
    }

    return bridgeNames;
}
 
Example 2
Source File: PortForwardingManagerImpl.java    From zstack with Apache License 2.0 6 votes vote down vote up
@Override
public RangeSet getVipUsePortRange(String vipUuid, String protocol, VipUseForList useForList){
    RangeSet portRangeList = new RangeSet();
    List<RangeSet.Range> portRanges = new ArrayList<RangeSet.Range>();

    if (protocol.toUpperCase().equals(PortForwardingProtocolType.UDP.toString()) || protocol.toUpperCase().equals(PortForwardingProtocolType.TCP.toString())) {
        List<Tuple> pfPortList = Q.New(PortForwardingRuleVO.class).select(PortForwardingRuleVO_.vipPortStart, PortForwardingRuleVO_.vipPortEnd)
                .eq(PortForwardingRuleVO_.vipUuid, vipUuid).eq(PortForwardingRuleVO_.protocolType, PortForwardingProtocolType.valueOf(protocol.toUpperCase())).listTuple();
        Iterator<Tuple> it = pfPortList.iterator();
        while (it.hasNext()){
            Tuple strRange = it.next();
            int start = strRange.get(0, Integer.class);
            int end = strRange.get(1, Integer.class);

            RangeSet.Range range = new RangeSet.Range(start, end);
            portRanges.add(range);
        }
    }

    portRangeList.setRanges(portRanges);
    return portRangeList;
}
 
Example 3
Source File: AbstractMybatisQuery.java    From spring-data-mybatis with Apache License 2.0 6 votes vote down vote up
@Override
public Object convert(Object source) {

	if (!(source instanceof Tuple)) {
		return source;
	}

	Tuple tuple = (Tuple) source;
	List<TupleElement<?>> elements = tuple.getElements();

	if (elements.size() == 1) {

		Object value = tuple.get(elements.get(0));

		if (type.isInstance(value) || value == null) {
			return value;
		}
	}

	return new TupleBackedMap(tuple);
}
 
Example 4
Source File: VmInstanceApiInterceptor.java    From zstack with Apache License 2.0 6 votes vote down vote up
@Transactional(readOnly = true)
private void validate(APIDetachL3NetworkFromVmMsg msg) {
    String sql = "select vm.uuid, vm.state from VmInstanceVO vm, VmNicVO nic where vm.uuid = nic.vmInstanceUuid and nic.uuid = :uuid";
    TypedQuery<Tuple> q = dbf.getEntityManager().createQuery(sql, Tuple.class);
    q.setParameter("uuid", msg.getVmNicUuid());
    Tuple t = q.getSingleResult();
    String vmUuid = t.get(0, String.class);
    VmInstanceState state = t.get(1, VmInstanceState.class);

    if (!VmInstanceState.Running.equals(state) && !VmInstanceState.Stopped.equals(state)) {
        throw new ApiMessageInterceptionException(operr("unable to detach a L3 network. The vm[uuid: %s] is not Running or Stopped; the current state is %s",
                        msg.getVmInstanceUuid(), state));
    }

    msg.setVmInstanceUuid(vmUuid);

    msg.l3Uuid = Q.New(VmNicVO.class).eq(VmNicVO_.uuid, msg.getVmNicUuid()).select(VmNicVO_.l3NetworkUuid).findValue();
}
 
Example 5
Source File: SystemTag.java    From zstack with Apache License 2.0 6 votes vote down vote up
public Map<String, List<String>> getTags(Collection<String> resourceUuids, Class resourceClass) {
    SimpleQuery<SystemTagVO> q = dbf.createQuery(SystemTagVO.class);
    q.select(SystemTagVO_.tag, SystemTagVO_.resourceUuid);
    q.add(SystemTagVO_.resourceType, Op.EQ, resourceClass.getSimpleName());
    q.add(SystemTagVO_.resourceUuid, Op.IN, resourceUuids);
    q.add(SystemTagVO_.tag, useOp(), useTagFormat());
    List<Tuple> ts = q.listTuple();
    Map<String, List<String>> ret = new HashMap<>();
    for (Tuple t : ts) {
        String uuid = t.get(1, String.class);
        List<String> tags = ret.get(uuid);
        if (tags == null) {
            tags = new ArrayList<>();
            ret.put(uuid, tags);
        }
        tags.add(t.get(0, String.class));
    }
    return ret;
}
 
Example 6
Source File: PageQueryTemplate.java    From mPaaS with Apache License 2.0 5 votes vote down vote up
/**
 * 查询列表属性,并追加到结果中
 */
private void queryCollectionPropAndToVO(String column,
		List<MetaProperty> props, List<V> result, List<String> ids,
		boolean filterTenant) {
	CriteriaBuilder builder = entityManager.getCriteriaBuilder();
	CriteriaQuery<Tuple> query = builder.createQuery(Tuple.class);
	QueryContextImpl<E, Tuple> context = new QueryContextImpl<>(null,
			entityClass, builder, query, filterTenant);
	query.where(context.toPredicate("fdId", Operator.eq, ids));
	// select
	ViewInfo root = new ViewInfo();
	List<Selection<?>> selects = new ArrayList<>();
	selects.add(context.getRoot().get("fdId"));
	appendSelectColumn4VO(context, column, props, selects, root);
	query.multiselect(selects);
	// 查询并转换VO对象
	List<Tuple> tuples = createQuery(query).getResultList();
	for (Tuple tuple : tuples) {
		String id = (String) tuple.get(0);
		for (int i = 0; i < ids.size(); i++) {
			if (id.equals(ids.get(i))) {
				toViewObject(tuple, root, viewClass, result.get(i));
				break;
			}
		}
	}
}
 
Example 7
Source File: FlatDhcpUpgradeExtension.java    From zstack with Apache License 2.0 5 votes vote down vote up
@Transactional(readOnly = true)
private List<L3Host> findL3NeedToDeleteDeprecatedNameSpace() {
    String sql = "select l3.uuid from L3NetworkVO l3, NetworkServiceL3NetworkRefVO ref, NetworkServiceProviderVO provider" +
            " where l3.uuid = ref.l3NetworkUuid and ref.networkServiceProviderUuid = provider.uuid" +
            " and ref.networkServiceType = :nsType and provider.type = :ptype";
    TypedQuery<String> q = dbf.getEntityManager().createQuery(sql, String.class);
    q.setParameter("nsType", NetworkServiceType.DHCP.toString());
    q.setParameter("ptype", FlatNetworkServiceConstant.FLAT_NETWORK_SERVICE_TYPE_STRING);
    List<String> l3Uuids = q.getResultList();

    if (l3Uuids.isEmpty()) {
        return null;
    }

    sql = "select l3, host.uuid from L3NetworkVO l3, HostVO host, L2NetworkClusterRefVO ref where host.hypervisorType = :htype and l3.uuid in (:uuids)" +
            " and ref.l2NetworkUuid = l3.l2NetworkUuid and host.clusterUuid = ref.clusterUuid";
    TypedQuery<Tuple> tq = dbf.getEntityManager().createQuery(sql, Tuple.class);
    tq.setParameter("htype", KVMConstant.KVM_HYPERVISOR_TYPE);
    tq.setParameter("uuids", l3Uuids);
    List<Tuple> ts = tq.getResultList();

    if (ts.isEmpty()) {
        return null;
    }

    List<L3Host> ret = new ArrayList<>();
    for (Tuple t : ts) {
        L3NetworkVO l3 = t.get(0, L3NetworkVO.class);
        String huuid = t.get(1, String.class);

        L3Host lh = new L3Host();
        lh.hostUuid= huuid;
        lh.l3 = L3NetworkInventory.valueOf(l3);
        ret.add(lh);
    }

    return ret;
}
 
Example 8
Source File: LoadBalancerManagerImpl.java    From zstack with Apache License 2.0 5 votes vote down vote up
@Override
public RangeSet getVipUsePortRange(String vipUuid, String protocol, VipUseForList useForList){

    RangeSet portRangeList = new RangeSet();
    List<RangeSet.Range> portRanges = new ArrayList<RangeSet.Range>();
    List<String> protocols = new ArrayList<>();
    if (LoadBalancerConstants.LB_PROTOCOL_UDP.equals(protocol.toLowerCase())) {
        protocols.add(LoadBalancerConstants.LB_PROTOCOL_UDP);
    } else {
        protocols.add(LoadBalancerConstants.LB_PROTOCOL_TCP);
        protocols.add(LoadBalancerConstants.LB_PROTOCOL_HTTP);
        protocols.add(LoadBalancerConstants.LB_PROTOCOL_HTTPS);
    }

    List<Tuple> lbPortList = SQL.New("select lbl.loadBalancerPort, lbl.loadBalancerPort from LoadBalancerListenerVO lbl, LoadBalancerVO lb "
            + "where lbl.protocol in (:protocols) and lbl.loadBalancerUuid=lb.uuid and lb.vipUuid = :vipUuid", Tuple.class).
            param("protocols", protocols).
            param("vipUuid", vipUuid).list();

    Iterator<Tuple> it = lbPortList.iterator();
    while (it.hasNext()) {
        Tuple strRange = it.next();
        int start = strRange.get(0, Integer.class);
        int end = strRange.get(1, Integer.class);

        RangeSet.Range range = new RangeSet.Range(start, end);
        portRanges.add(range);
    }
    portRangeList.setRanges(portRanges);

    return portRangeList;
}
 
Example 9
Source File: HostManagerImpl.java    From zstack with Apache License 2.0 5 votes vote down vote up
private Bucket getHostManagedByUs() {
    int qun = 10000;
    long amount = dbf.count(HostVO.class);
    int times = (int) (amount / qun) + (amount % qun != 0 ? 1 : 0);
    List<String> connected = new ArrayList<String>();
    List<String> disconnected = new ArrayList<String>();
    int start = 0;
    for (int i = 0; i < times; i++) {
        SimpleQuery<HostVO> q = dbf.createQuery(HostVO.class);
        q.select(HostVO_.uuid, HostVO_.status);
        q.setLimit(qun);
        q.setStart(start);
        List<Tuple> lst = q.listTuple();
        start += qun;
        for (Tuple t : lst) {
            String huuid = t.get(0, String.class);
            if (!destMaker.isManagedByUs(huuid)) {
                continue;
            }
            HostStatus state = t.get(1, HostStatus.class);
            if (state == HostStatus.Connected) {
                connected.add(huuid);
            } else {
                // for Disconnected and Connecting, treat as Disconnected
                disconnected.add(huuid);
            }
        }
    }

    return Bucket.newBucket(connected, disconnected);
}
 
Example 10
Source File: HostCapacityReserveManagerImpl.java    From zstack with Apache License 2.0 5 votes vote down vote up
private void findReservedCapacityByHypervisorType() {
    SimpleQuery<HostVO> hq = dbf.createQuery(HostVO.class);
    hq.select(HostVO_.uuid, HostVO_.hypervisorType);
    hq.add(HostVO_.uuid, Op.IN, hostUuids);
    hq.add(HostVO_.state,Op.EQ, HostState.Enabled);
    hq.add(HostVO_.status,Op.EQ, HostStatus.Connected);
    List<Tuple> tuples = hq.listTuple();

    for (Tuple t : tuples) {
        String huuid = t.get(0, String.class);
        String hvType = t.get(1, String.class);

        HostReservedCapacityExtensionPoint ext = exts.get(hvType);
        if (ext == null) {
            continue;
        }

        ReservedHostCapacity hc = result.get(huuid);
        ReservedHostCapacity extHc = ext.getReservedHostCapacity(huuid);
        if (hc.getReservedMemoryCapacity() == -1) {
            hc.setReservedMemoryCapacity(extHc.getReservedMemoryCapacity());
        }
        if (hc.getReservedCpuCapacity() == -1) {
            hc.setReservedCpuCapacity(extHc.getReservedCpuCapacity());
        }
    }
}
 
Example 11
Source File: VmQuotaOperator.java    From zstack with Apache License 2.0 5 votes vote down vote up
private Pair<Integer, Long> getInstanceOfferingAsked(APICreateVmInstanceMsg msg) {

        if (msg.getInstanceOfferingUuid() != null) {
            String sql = "select i.cpuNum, i.memorySize" +
                    " from InstanceOfferingVO i" +
                    " where i.uuid = :uuid";
            TypedQuery<Tuple> iq = dbf.getEntityManager().createQuery(sql, Tuple.class);
            iq.setParameter("uuid", msg.getInstanceOfferingUuid());
            Tuple t = iq.getSingleResult();
            return new Pair<Integer, Long>(t.get(0, Integer.class), t.get(1, Long.class));
        }

        return new Pair<Integer, Long>(msg.getCpuNum(), msg.getMemorySize());
    }
 
Example 12
Source File: VmInstanceApiInterceptor.java    From zstack with Apache License 2.0 5 votes vote down vote up
private void validate(APICreateVmNicMsg msg) {
    SimpleQuery<L3NetworkVO> l3q = dbf.createQuery(L3NetworkVO.class);
    l3q.select(L3NetworkVO_.state, L3NetworkVO_.system, L3NetworkVO_.category, L3NetworkVO_.type);
    l3q.add(L3NetworkVO_.uuid, Op.EQ, msg.getL3NetworkUuid());
    Tuple t = l3q.findTuple();
    L3NetworkState l3state = t.get(0, L3NetworkState.class);

    if (l3state == L3NetworkState.Disabled) {
        throw new ApiMessageInterceptionException(operr("unable to attach a L3 network. The L3 network[uuid:%s] is disabled", msg.getL3NetworkUuid()));
    }

    if (msg.getIp() != null) {
        SimpleQuery<NormalIpRangeVO> iprq = dbf.createQuery(NormalIpRangeVO.class);
        iprq.add(NormalIpRangeVO_.l3NetworkUuid, Op.EQ, msg.getL3NetworkUuid());
        List<NormalIpRangeVO> iprs = iprq.list();

        boolean found = false;
        for (NormalIpRangeVO ipr : iprs) {
            if (NetworkUtils.isInRange(msg.getIp(), ipr.getStartIp(), ipr.getEndIp())) {
                found = true;
                break;
            }
        }

        if (!found) {
            throw new ApiMessageInterceptionException(argerr("the static IP[%s] is not in any IP range of the L3 network[uuid:%s]", msg.getIp(), msg.getL3NetworkUuid()));
        }

        SimpleQuery<UsedIpVO> uq = dbf.createQuery(UsedIpVO.class);
        uq.add(UsedIpVO_.l3NetworkUuid, Op.EQ, msg.getL3NetworkUuid());
        uq.add(UsedIpVO_.ip, Op.EQ, msg.getIp());
        if (uq.isExists()) {
            throw new ApiMessageInterceptionException(operr("the static IP[%s] has been occupied on the L3 network[uuid:%s]", msg.getIp(), msg.getL3NetworkUuid()));
        }
    }
}
 
Example 13
Source File: VirtualRouterPortForwardingBackend.java    From zstack with Apache License 2.0 5 votes vote down vote up
private List<PortForwardingRuleTO> findPortforwardingsOnVmNic(VmNicInventory nic, VirtualRouterVmInventory vr) {
    List<Tuple> pfs = findPortForwardingTuplesOnVmNic(nic);

    if (pfs == null || pfs.isEmpty()) {
        return null;
    }

    List<PortForwardingRuleTO> tos = new ArrayList<>();
    for (Tuple t : pfs) {
        PortForwardingRuleVO pf = t.get(0, PortForwardingRuleVO.class);
        VipVO vipVO = dbf.findByUuid(pf.getVipUuid(), VipVO.class);
        PortForwardingRuleTO to = new PortForwardingRuleTO();
        to.setUuid(pf.getUuid());
        to.setAllowedCidr(pf.getAllowedCidr());
        to.setPrivateIp(t.get(1, String.class));
        to.setPrivateMac(
                vr.getVmNics().stream()
                        .filter(n -> n.getL3NetworkUuid().equals(nic.getL3NetworkUuid()))
                        .findFirst().get().getMac());
        to.setPublicMac(
                vr.getVmNics().stream()
                        .filter(n -> n.getL3NetworkUuid().equals(vipVO.getL3NetworkUuid()))
                        .findFirst().get().getMac());
        to.setPrivatePortStart(pf.getPrivatePortStart());
        to.setPrivatePortEnd(pf.getPrivatePortEnd());
        to.setProtocolType(pf.getProtocolType().toString());
        to.setSnatInboundTraffic(PortForwardingGlobalConfig.SNAT_INBOUND_TRAFFIC.value(Boolean.class));
        to.setVipIp(pf.getVipIp());
        to.setVipPortStart(pf.getVipPortStart());
        to.setVipPortEnd(pf.getVipPortEnd());
        tos.add(to);
    }

    return tos;
}
 
Example 14
Source File: PageQueryTemplate.java    From mPass with Apache License 2.0 5 votes vote down vote up
/**
 * 查询列表属性,并追加到结果中
 */
private void queryCollectionPropAndToVO(String column,
		List<MetaProperty> props, List<V> result, List<String> ids,
		boolean filterTenant) {
	CriteriaBuilder builder = entityManager.getCriteriaBuilder();
	CriteriaQuery<Tuple> query = builder.createQuery(Tuple.class);
	QueryContextImpl<E, Tuple> context = new QueryContextImpl<>(null,
			entityClass, builder, query, filterTenant);
	query.where(context.toPredicate("fdId", Operator.eq, ids));
	// select
	ViewInfo root = new ViewInfo();
	List<Selection<?>> selects = new ArrayList<>();
	selects.add(context.getRoot().get("fdId"));
	appendSelectColumn4VO(context, column, props, selects, root);
	query.multiselect(selects);
	// 查询并转换VO对象
	List<Tuple> tuples = createQuery(query).getResultList();
	for (Tuple tuple : tuples) {
		String id = (String) tuple.get(0);
		for (int i = 0; i < ids.size(); i++) {
			if (id.equals(ids.get(i))) {
				toViewObject(tuple, root, viewClass, result.get(i));
				break;
			}
		}
	}
}
 
Example 15
Source File: LocalStorageBase.java    From zstack with Apache License 2.0 4 votes vote down vote up
@Transactional
protected void returnStorageCapacityToHostByResourceUuid(String resUuid) {
    String sql = "select href, rref" +
            " from LocalStorageHostRefVO href, LocalStorageResourceRefVO rref" +
            " where href.hostUuid = rref.hostUuid" +
            " and href.primaryStorageUuid = rref.primaryStorageUuid" +
            " and rref.resourceUuid = :resUuid" +
            " and rref.primaryStorageUuid = :puuid";
    TypedQuery<Tuple> q = dbf.getEntityManager().createQuery(sql, Tuple.class);
    q.setLockMode(LockModeType.PESSIMISTIC_WRITE);
    q.setParameter("resUuid", resUuid);
    q.setParameter("puuid", self.getUuid());
    List<Tuple> tupleList = q.getResultList();
    if (tupleList == null || tupleList.isEmpty()) {
        return;
    }

    DebugUtils.Assert(tupleList.size() == 1,
            "should not get more than one LocalStorageHostRefVO/LocalStorageResourceRefVO");
    Tuple twoRefs = tupleList.get(0);
    LocalStorageHostRefVO href = twoRefs.get(0, LocalStorageHostRefVO.class);
    LocalStorageResourceRefVO rref = twoRefs.get(1, LocalStorageResourceRefVO.class);

    long requiredSize = rref.getSize();
    if (VolumeVO.class.getSimpleName().equals(rref.getResourceType())) {
        requiredSize = ratioMgr.calculateByRatio(self.getUuid(), requiredSize);
    }

    LocalStorageHostCapacityStruct s = new LocalStorageHostCapacityStruct();
    s.setSizeBeforeOverProvisioning(rref.getSize());
    s.setHostUuid(href.getHostUuid());
    s.setLocalStorage(getSelfInventory());
    s.setSize(requiredSize);
    for (LocalStorageReturnHostCapacityExtensionPoint ext : pluginRgty.getExtensionList(
            LocalStorageReturnHostCapacityExtensionPoint.class)) {
        ext.beforeReturnLocalStorageCapacityOnHost(s);
    }

    href.setAvailableCapacity(href.getAvailableCapacity() + s.getSize());
    dbf.getEntityManager().merge(href);
}
 
Example 16
Source File: VmQuotaUtil.java    From zstack with Apache License 2.0 4 votes vote down vote up
@Transactional(readOnly = true)
public VmQuota getUsedVmCpuMemory(String accountUUid, String excludeVmUuid) {
    VmQuota quota = new VmQuota();
    // get running info
    String sql = "select count(vm), sum(vm.cpuNum), sum(vm.memorySize)" +
            " from VmInstanceVO vm, AccountResourceRefVO ref" +
            " where vm.uuid = ref.resourceUuid" +
            " and ref.accountUuid = :auuid" +
            " and ref.resourceType = :rtype" +
            " and not (vm.state = :starting and vm.hostUuid is null)" +
            " and vm.state not in (:states)";

    if (excludeVmUuid != null) {
        sql += " and vm.uuid != (:excludeVmUuid)";
    }

    TypedQuery<Tuple> q = dbf.getEntityManager().createQuery(sql, Tuple.class);
    q.setParameter("auuid", accountUUid);
    q.setParameter("rtype", VmInstanceVO.class.getSimpleName());
    q.setParameter("starting", VmInstanceState.Starting);
    q.setParameter("states", list(VmInstanceState.Stopped, VmInstanceState.Destroying,
            VmInstanceState.Destroyed, VmInstanceState.Created));

    if (excludeVmUuid != null) {
        q.setParameter("excludeVmUuid", excludeVmUuid);
    }

    Tuple t = q.getSingleResult();
    Long vnum = t.get(0, Long.class);
    quota.runningVmNum = vnum == null ? 0 : vnum;
    Long cnum = t.get(1, Long.class);
    quota.runningVmCpuNum = cnum == null ? 0 : cnum;
    Long msize = t.get(2, Long.class);
    quota.runningVmMemorySize = msize == null ? 0 : msize;
    // get total vm
    String sql2 = "select count(vm)" +
            " from VmInstanceVO vm, AccountResourceRefVO ref" +
            " where vm.uuid = ref.resourceUuid" +
            " and ref.accountUuid = :auuid" +
            " and ref.resourceType = :rtype" +
            " and not (vm.hostUuid is null and vm.lastHostUuid is null)" +
            " and vm.state not in (:states)";
    TypedQuery<Long> q2 = dbf.getEntityManager().createQuery(sql2, Long.class);
    q2.setParameter("auuid", accountUUid);
    q2.setParameter("rtype", VmInstanceVO.class.getSimpleName());
    q2.setParameter("states", list(VmInstanceState.Destroyed));
    Long totalVmNum = q2.getSingleResult();
    quota.totalVmNum = totalVmNum == null ? 0 : totalVmNum;

    return quota;
}
 
Example 17
Source File: PageQueryTemplate.java    From mPass with Apache License 2.0 4 votes vote down vote up
/**
 * 转VO对象
 */
private <T> T toViewObject(Tuple tuple, ViewInfo viewInfo, Class<T> clazz,
		T vo) {
	for (Entry<String, ViewInfo> entry : viewInfo.children.entrySet()) {
		ViewInfo child = entry.getValue();
		Object value = null;
		if (child.arrayElementType != null && child.children != null) {
			// 数组,先从VO中获取列表,若列表为空则创建,然后往列表中追加子
			List<Object> list = null;
			if (vo == null) {
				vo = ReflectUtil.newInstance(clazz);
			} else {
				list = readProperty(vo, child.desc);
			}
			if (list == null) {
				list = new ArrayList<>();
				writeProperty(vo, child.desc, list);
			}
			value = toViewObject(tuple, child, child.arrayElementType,
					null);
			if(value != null) {
				list.add(value);
			}
		} else {
			if (child.children != null) {
				// 子对象
				value = toViewObject(tuple, child,
						child.desc.getPropertyType(), null);
			} else if (child.index > -1) {
				// 普通字段
				value = tuple.get(child.index);
				value = TypeUtils.cast(value, child.desc.getPropertyType(),
						null);
				if (child.langIndex > -1) {
					Object langValue = tuple.get(child.langIndex);
					langValue = TypeUtils.cast(langValue,
							child.desc.getPropertyType(), null);
					if (StringUtils.isNotBlank((String) langValue)) {
						value = langValue;
					}
				}
			}
			if (value != null) {
				if (vo == null) {
					vo = ReflectUtil.newInstance(clazz);
				}
				writeProperty(vo, child.desc, value);
			}
		}
	}
	return vo;
}
 
Example 18
Source File: LocalStorageCapacityRecalculator.java    From zstack with Apache License 2.0 4 votes vote down vote up
@Transactional
public LocalStorageCapacityRecalculator calculateTotalCapacity(String psUuid) {
    final long totalCapacity;
    final long availableCapacity;
    final long totalPhysicalCapacity;
    final long availablePhysicalCapacity;

    String sql = "select sum(ref.totalCapacity)," +
            " sum(ref.availableCapacity)," +
            " sum(ref.totalPhysicalCapacity)," +
            " sum(ref.availablePhysicalCapacity)" +
            " from LocalStorageHostRefVO ref" +
            " where ref.primaryStorageUuid = :psUuid" +
            " group by ref.primaryStorageUuid";
    TypedQuery<Tuple> q = dbf.getEntityManager().createQuery(sql, Tuple.class);
    q.setParameter("psUuid", psUuid);
    List<Tuple> resultList =  q.getResultList();

    if (resultList != null && !resultList.isEmpty()) {
        Tuple ts = resultList.get(0);
        totalCapacity = ts.get(0) == null ? 0 : ts.get(0, Long.class);
        availableCapacity = ts.get(1) == null ? 0 : ts.get(1, Long.class);
        totalPhysicalCapacity = ts.get(2) == null ? 0 : ts.get(2, Long.class);
        availablePhysicalCapacity = ts.get(3) == null ? 0 : ts.get(3, Long.class);
    } else {
        // LocalStorage not mounted
        // Cluster no host
        totalCapacity = 0;
        totalPhysicalCapacity = 0;
        availablePhysicalCapacity = 0;

        Long used = SQL.New("select sum(ref.size)" +
                " from LocalStorageResourceRefVO ref" +
                " where ref.primaryStorageUuid = :psUuid")
                .param("psUuid", psUuid).find();

        availableCapacity = used != null ? totalCapacity - used : 0;
    }

    PrimaryStorageCapacityUpdater pupdater = new PrimaryStorageCapacityUpdater(psUuid);
    pupdater.run(new PrimaryStorageCapacityUpdaterRunnable() {
        @Override
        public PrimaryStorageCapacityVO call(PrimaryStorageCapacityVO cap) {
            cap.setTotalCapacity(totalCapacity);
            cap.setAvailableCapacity(availableCapacity);
            cap.setTotalPhysicalCapacity(totalPhysicalCapacity);
            cap.setAvailablePhysicalCapacity(availablePhysicalCapacity);
            return cap;
        }
    });

    return this;
}
 
Example 19
Source File: PageQueryTemplate.java    From mPaaS with Apache License 2.0 4 votes vote down vote up
/**
 * 转VO对象
 */
private <T> T toViewObject(Tuple tuple, ViewInfo viewInfo, Class<T> clazz,
		T vo) {
	for (Entry<String, ViewInfo> entry : viewInfo.children.entrySet()) {
		ViewInfo child = entry.getValue();
		Object value = null;
		if (child.arrayElementType != null && child.children != null) {
			// 数组,先从VO中获取列表,若列表为空则创建,然后往列表中追加子
			List<Object> list = null;
			if (vo == null) {
				vo = ReflectUtil.newInstance(clazz);
			} else {
				list = readProperty(vo, child.desc);
			}
			if (list == null) {
				list = new ArrayList<>();
				writeProperty(vo, child.desc, list);
			}
			value = toViewObject(tuple, child, child.arrayElementType,
					null);
			if(value != null) {
				list.add(value);
			}
		} else {
			if (child.children != null) {
				// 子对象
				value = toViewObject(tuple, child,
						child.desc.getPropertyType(), null);
			} else if (child.index > -1) {
				// 普通字段
				value = tuple.get(child.index);
				value = TypeUtils.cast(value, child.desc.getPropertyType(),
						null);
				if (child.langIndex > -1) {
					Object langValue = tuple.get(child.langIndex);
					langValue = TypeUtils.cast(langValue,
							child.desc.getPropertyType(), null);
					if (StringUtils.isNotBlank((String) langValue)) {
						value = langValue;
					}
				}
			}
			if (value != null) {
				if (vo == null) {
					vo = ReflectUtil.newInstance(clazz);
				}
				writeProperty(vo, child.desc, value);
			}
		}
	}
	return vo;
}
 
Example 20
Source File: TestLeastVmPreferredHostAllocationStrategy.java    From zstack with Apache License 2.0 4 votes vote down vote up
@Test
public void test() throws ApiSenderException {
    L3NetworkInventory l3 = deployer.l3Networks.get("l3Network1");
    ImageInventory imageInventory = deployer.images.get("image1");
    ClusterInventory cluster = deployer.clusters.get("cluster1");
    InstanceOfferingInventory ins = deployer.instanceOfferings.get("instanceOffering512M512HZ");
    InstanceOfferingInventory ios = new InstanceOfferingInventory();
    ios.setName("lastVmPreferred");
    ios.setAllocatorStrategy(HostAllocatorConstant.LEAST_VM_PREFERRED_HOST_ALLOCATOR_STRATEGY_TYPE);
    ios.setCpuNum(1);
    ios.setCpuSpeed(1);
    ios.setMemorySize(SizeUnit.MEGABYTE.toByte(512));
    ios = api.addInstanceOffering(ios);

    long sip = NetworkUtils.ipv4StringToLong("192.168.0.1");
    for (int i = 0; i < hostNum; i++) {
        APIAddSimulatorHostMsg amsg = new APIAddSimulatorHostMsg();
        amsg.setCpuCapacity(8 * 2600);
        amsg.setMemoryCapacity(SizeUnit.GIGABYTE.toByte(32));
        amsg.setClusterUuid(cluster.getUuid());
        amsg.setManagementIp(NetworkUtils.longToIpv4String(sip + i));
        amsg.setName(String.format("h%s", i));
        amsg.setServiceId(ApiMediatorConstant.SERVICE_ID);
        amsg.setSession(api.getAdminSession());
        ApiSender sender = new ApiSender();
        sender.send(amsg, APIAddHostEvent.class);
    }

    for (int i = 0; i < vmNum; i++) {
        VmCreator creator = new VmCreator(api);
        creator.addL3Network(l3.getUuid());
        creator.imageUuid = imageInventory.getUuid();
        creator.instanceOfferingUuid = ios.getUuid();
        //creator.instanceOfferingUuid = ins.getUuid();
        VmInstanceInventory vm = creator.create();
    }

    List<Tuple> ts = new Callable<List<Tuple>>() {
        @Override
        @Transactional(readOnly = true)
        public List<Tuple> call() {
            String sql = "select count(vm), host.name from VmInstanceVO vm, HostVO host where vm.hostUuid = host.uuid group by host.uuid";
            TypedQuery<Tuple> q = dbf.getEntityManager().createQuery(sql, Tuple.class);
            return q.getResultList();
        }
    }.call();

    for (Tuple t : ts) {
        long num = t.get(0, Long.class);
        String name = t.get(1, String.class);
        System.out.println(String.format("%s: %s", name, num));
    }
}