Bring over from vmsync changes in utils package. Simple changes. New files are not being used yet in master

This commit is contained in:
ahuang 2013-07-17 18:29:42 -07:00
parent 52e6ef7eb8
commit 11971b5a58
44 changed files with 542 additions and 652 deletions

View File

@ -28,16 +28,18 @@ import java.util.regex.Pattern;
import javax.inject.Inject;
import org.apache.cloudstack.affinity.AffinityGroupService;
import com.cloud.server.ResourceMetaDataService;
import org.apache.cloudstack.network.element.InternalLoadBalancerElementService;
import org.apache.cloudstack.network.lb.ApplicationLoadBalancerService;
import org.apache.cloudstack.network.lb.InternalLoadBalancerVMService;
import org.apache.cloudstack.query.QueryService;
import org.apache.cloudstack.usage.UsageService;
import org.apache.log4j.Logger;
import com.cloud.configuration.ConfigurationService;
import com.cloud.dao.EntityManager;
import com.cloud.domain.Domain;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException;
@ -76,6 +78,7 @@ import com.cloud.user.AccountService;
import com.cloud.user.DomainService;
import com.cloud.user.ResourceLimitService;
import com.cloud.utils.Pair;
import com.cloud.utils.db.EntityManager;
import com.cloud.vm.UserVmService;
import com.cloud.vm.snapshot.VMSnapshotService;

View File

@ -17,7 +17,6 @@
package org.apache.cloudstack.api.command.user.region.ha.gslb;
import com.cloud.dao.EntityManager;
import com.cloud.event.EventTypes;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.network.rules.LoadBalancer;
@ -25,6 +24,7 @@ import com.cloud.region.ha.GlobalLoadBalancerRule;
import com.cloud.region.ha.GlobalLoadBalancingRulesService;
import com.cloud.user.Account;
import com.cloud.utils.StringUtils;
import com.cloud.utils.db.EntityManager;
import org.apache.cloudstack.api.*;
import org.apache.cloudstack.api.response.FirewallRuleResponse;

View File

@ -23,11 +23,11 @@ import java.util.UUID;
import org.apache.log4j.Logger;
import org.apache.log4j.NDC;
import com.cloud.dao.EntityManager;
import com.cloud.exception.CloudAuthenticationException;
import com.cloud.user.Account;
import com.cloud.user.User;
import com.cloud.utils.UuidUtils;
import com.cloud.utils.db.EntityManager;
import com.cloud.utils.exception.CloudRuntimeException;
/**

View File

@ -840,7 +840,7 @@
<bean id="volumeTypeHelper" class="org.apache.cloudstack.engine.subsystem.api.storage.type.VolumeTypeHelper" />
<bean id="zoneRestService" class="org.apache.cloudstack.engine.rest.service.api.ZoneRestService" />
<bean id="cloudZonesStartupProcessor" class="com.cloud.hypervisor.CloudZonesStartupProcessor" />
<bean id="managementServerNode" class="com.cloud.cluster.ManagementServerNode" />
<bean id="managementServerNode" class="org.apache.cloudstack.utils.identity.ManagementServerNode" />
<bean id="testingAllocator" class="com.cloud.agent.manager.allocator.impl.TestingAllocator" />
<bean id="domainManagerImpl" class="com.cloud.user.DomainManagerImpl" />
<bean id="downloadMonitorImpl" class="com.cloud.storage.download.DownloadMonitorImpl" />

View File

@ -43,6 +43,7 @@ import org.apache.log4j.Logger;
import org.apache.cloudstack.context.ServerContexts;
import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
import org.apache.cloudstack.utils.identity.ManagementServerNode;
import com.cloud.agent.AgentManager;
import com.cloud.agent.Listener;
@ -69,7 +70,6 @@ import com.cloud.agent.transport.Request;
import com.cloud.agent.transport.Response;
import com.cloud.alert.AlertManager;
import com.cloud.capacity.dao.CapacityDao;
import com.cloud.cluster.ManagementServerNode;
import com.cloud.configuration.Config;
import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.dc.ClusterDetailsDao;

View File

@ -60,12 +60,12 @@ import org.apache.cloudstack.api.command.user.event.ListEventsCmd;
import org.apache.cloudstack.context.CallContext;
import com.cloud.async.AsyncJobManager;
import com.cloud.dao.EntityManager;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.user.Account;
import com.cloud.user.AccountManager;
import com.cloud.utils.DateUtil;
import com.cloud.utils.ReflectUtil;
import com.cloud.utils.db.EntityManager;
import com.cloud.utils.exception.CSExceptionErrorCode;
import com.cloud.utils.exception.CloudRuntimeException;

View File

@ -178,7 +178,6 @@ import com.cloud.configuration.Resource.ResourceOwnerType;
import com.cloud.configuration.Resource.ResourceType;
import com.cloud.configuration.ResourceCount;
import com.cloud.configuration.ResourceLimit;
import com.cloud.dao.EntityManager;
import com.cloud.dc.ClusterVO;
import com.cloud.dc.DataCenter;
import com.cloud.dc.HostPodVO;
@ -281,6 +280,7 @@ import com.cloud.user.UserAccount;
import com.cloud.uservm.UserVm;
import com.cloud.utils.Pair;
import com.cloud.utils.StringUtils;
import com.cloud.utils.db.EntityManager;
import com.cloud.utils.net.Ip;
import com.cloud.utils.net.NetUtils;
import com.cloud.vm.ConsoleProxyVO;

View File

@ -121,7 +121,6 @@ import com.cloud.async.AsyncJobVO;
import com.cloud.configuration.Config;
import com.cloud.configuration.ConfigurationVO;
import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.dao.EntityManager;
import com.cloud.domain.Domain;
import com.cloud.domain.DomainVO;
import com.cloud.event.ActionEventUtils;
@ -146,6 +145,7 @@ import com.cloud.utils.component.ComponentContext;
import com.cloud.utils.component.ManagerBase;
import com.cloud.utils.component.PluggableService;
import com.cloud.utils.concurrency.NamedThreadFactory;
import com.cloud.utils.db.EntityManager;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException;

View File

@ -40,12 +40,12 @@ import org.apache.cloudstack.api.BaseCmd;
import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.context.CallContext;
import com.cloud.dao.EntityManager;
import com.cloud.exception.CloudAuthenticationException;
import com.cloud.user.Account;
import com.cloud.user.AccountService;
import com.cloud.user.User;
import com.cloud.utils.StringUtils;
import com.cloud.utils.db.EntityManager;
@Component("apiServlet")
@SuppressWarnings("serial")

View File

@ -64,7 +64,6 @@ import com.cloud.cluster.ClusterManagerListener;
import com.cloud.cluster.ManagementServerHostVO;
import com.cloud.configuration.Config;
import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.dao.EntityManager;
import com.cloud.domain.DomainVO;
import com.cloud.domain.dao.DomainDao;
import com.cloud.event.EventCategory;
@ -82,6 +81,7 @@ import com.cloud.utils.component.ComponentContext;
import com.cloud.utils.component.ManagerBase;
import com.cloud.utils.concurrency.NamedThreadFactory;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.EntityManager;
import com.cloud.utils.db.GlobalLock;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException;

View File

@ -89,8 +89,11 @@ import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.exception.ExceptionUtil;
import com.cloud.utils.mgmt.JmxUtil;
import com.cloud.utils.net.NetUtils;
import com.google.gson.Gson;
import org.apache.cloudstack.utils.identity.ManagementServerNode;
@Local(value = { ClusterManager.class })
public class ClusterManagerImpl extends ManagerBase implements ClusterManager {
private static final Logger s_logger = Logger.getLogger(ClusterManagerImpl.class);

View File

@ -28,6 +28,7 @@ import org.springframework.stereotype.Component;
import net.sf.ehcache.Cache;
import com.cloud.utils.component.ManagerBase;
import com.cloud.utils.db.EntityManager;
import com.cloud.utils.db.GenericDao;
import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.GenericSearchBuilder;

View File

@ -32,7 +32,6 @@ import javax.naming.ConfigurationException;
import org.apache.cloudstack.affinity.AffinityGroupProcessor;
import org.apache.cloudstack.affinity.AffinityGroupVMMapVO;
import org.apache.cloudstack.affinity.AffinityGroupVO;
import org.apache.cloudstack.affinity.dao.AffinityGroupDao;
import org.apache.cloudstack.affinity.dao.AffinityGroupVMMapDao;
import org.apache.cloudstack.engine.cloud.entity.api.db.VMReservationVO;
@ -41,15 +40,17 @@ import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
import org.apache.cloudstack.engine.subsystem.api.storage.StoragePoolAllocator;
import org.apache.cloudstack.framework.messagebus.MessageBus;
import org.apache.cloudstack.framework.messagebus.MessageSubscriber;
import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
import org.apache.cloudstack.utils.identity.ManagementServerNode;
import org.apache.log4j.Logger;
import com.cloud.capacity.CapacityManager;
import com.cloud.capacity.dao.CapacityDao;
import com.cloud.cluster.ManagementServerNode;
import com.cloud.configuration.Config;
import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.dc.ClusterDetailsDao;

View File

@ -46,6 +46,7 @@ import org.springframework.stereotype.Component;
import org.apache.cloudstack.api.command.admin.router.UpgradeRouterCmd;
import org.apache.cloudstack.context.CallContext;
import org.apache.cloudstack.context.ServerContexts;
import org.apache.cloudstack.utils.identity.ManagementServerNode;
import com.cloud.agent.AgentManager;
import com.cloud.agent.AgentManager.OnError;
@ -94,7 +95,6 @@ import com.cloud.agent.api.to.StaticNatRuleTO;
import com.cloud.agent.manager.Commands;
import com.cloud.alert.AlertManager;
import com.cloud.cluster.ManagementServerHostVO;
import com.cloud.cluster.ManagementServerNode;
import com.cloud.cluster.dao.ManagementServerHostDao;
import com.cloud.configuration.Config;
import com.cloud.configuration.ConfigurationManager;

View File

@ -57,7 +57,6 @@ import com.cloud.agent.api.SecurityGroupRulesCmd.IpPortAndProto;
import com.cloud.agent.manager.Commands;
import com.cloud.api.query.dao.SecurityGroupJoinDao;
import com.cloud.api.query.vo.SecurityGroupJoinVO;
import com.cloud.cluster.ManagementServerNode;
import com.cloud.configuration.Config;
import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.domain.dao.DomainDao;
@ -103,6 +102,7 @@ import edu.emory.mathcs.backport.java.util.Collections;
import org.apache.cloudstack.api.command.user.securitygroup.*;
import org.apache.cloudstack.context.CallContext;
import org.apache.cloudstack.utils.identity.ManagementServerNode;
import java.util.*;

View File

@ -47,6 +47,7 @@ import org.apache.cloudstack.context.CallContext;
import org.apache.cloudstack.region.dao.RegionDao;
import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
import org.apache.cloudstack.utils.identity.ManagementServerNode;
import com.cloud.agent.AgentManager;
import com.cloud.agent.AgentManager.TapAgentsAction;
@ -68,7 +69,6 @@ import com.cloud.capacity.Capacity;
import com.cloud.capacity.CapacityVO;
import com.cloud.capacity.dao.CapacityDao;
import com.cloud.cluster.ClusterManager;
import com.cloud.cluster.ManagementServerNode;
import com.cloud.configuration.Config;
import com.cloud.configuration.ConfigurationManager;
import com.cloud.configuration.dao.ConfigurationDao;

View File

@ -49,7 +49,6 @@ import com.cloud.configuration.ResourceLimitVO;
import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.configuration.dao.ResourceCountDao;
import com.cloud.configuration.dao.ResourceLimitDao;
import com.cloud.dao.EntityManager;
import com.cloud.dc.VlanVO;
import com.cloud.dc.dao.VlanDao;
import com.cloud.domain.Domain;
@ -85,6 +84,7 @@ import com.cloud.utils.NumbersUtil;
import com.cloud.utils.component.ManagerBase;
import com.cloud.utils.concurrency.NamedThreadFactory;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.EntityManager;
import com.cloud.utils.db.Filter;
import com.cloud.utils.db.GenericSearchBuilder;
import com.cloud.utils.db.JoinBuilder;

View File

@ -37,6 +37,7 @@ import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
import org.apache.cloudstack.engine.subsystem.api.storage.ZoneScope;
import org.apache.cloudstack.storage.datastore.db.ImageStoreDao;
import org.apache.cloudstack.storage.datastore.db.ImageStoreVO;
import org.apache.cloudstack.utils.identity.ManagementServerNode;
import com.cloud.agent.AgentManager;
import com.cloud.agent.api.Answer;
@ -56,7 +57,6 @@ import com.cloud.agent.api.to.NfsTO;
import com.cloud.agent.manager.Commands;
import com.cloud.capacity.dao.CapacityDao;
import com.cloud.cluster.ClusterManager;
import com.cloud.cluster.ManagementServerNode;
import com.cloud.configuration.Config;
import com.cloud.configuration.ZoneConfig;
import com.cloud.configuration.dao.ConfigurationDao;

View File

@ -86,7 +86,6 @@ import com.cloud.configuration.Config;
import com.cloud.configuration.ConfigurationManager;
import com.cloud.configuration.Resource.ResourceType;
import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.dao.EntityManager;
import com.cloud.dc.ClusterDetailsDao;
import com.cloud.dc.ClusterDetailsVO;
import com.cloud.dc.DataCenter;
@ -173,6 +172,7 @@ import com.cloud.utils.Ternary;
import com.cloud.utils.component.ManagerBase;
import com.cloud.utils.concurrency.NamedThreadFactory;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.EntityManager;
import com.cloud.utils.db.GlobalLock;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException;

View File

@ -73,12 +73,6 @@
<artifactId>commons-discovery</artifactId>
<version>${cs.discovery.version}</version>
</dependency>
<!-- <dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${cs.guava.version}</version>
</dependency>
-->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
@ -165,14 +159,6 @@
</dependency>
</dependencies>
<build>
<defaultGoal>install</defaultGoal>
<sourceDirectory>src</sourceDirectory>
<testSourceDirectory>test</testSourceDirectory>
<testResources>
<testResource>
<directory>${project.basedir}/test/resources</directory>
</testResource>
</testResources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>

View File

@ -26,4 +26,30 @@ public class EnumUtils {
b.append("]");
return b.toString();
}
public static <T extends Enum<T>> T fromString(Class<T> clz, String value, T defaultVal) {
assert(clz != null);
if(value != null) {
try {
return Enum.valueOf(clz, value.trim());
} catch(IllegalArgumentException ex) {
assert(false);
}
}
return defaultVal;
}
public static <T extends Enum<T>> T fromString(Class<T> clz, String value) {
assert(clz != null);
if(value != null) {
try {
return Enum.valueOf(clz, value.trim());
} catch(IllegalArgumentException ex) {
assert(false);
}
}
return null;
}
}

View File

@ -0,0 +1,113 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.utils;
import java.lang.reflect.Method;
import java.util.WeakHashMap;
import net.sf.cglib.proxy.Callback;
import net.sf.cglib.proxy.CallbackFilter;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
/*
* This helper class provides a way to retrieve Method in a strong-type way. It takes advantage of power of
* Intelligent IDE(Eclipse) in code-editing
*
* DummyImpl dummy = new DummyImpl();
* MethodCapturer<DummyImpl> capturer = MethodCapturer.capture(dummy);
* Method method = capturer.get(capturer.instance().foo2());
*
*/
public class MethodCapturer<T> {
private final static int CACHE_SIZE = 1024;
private T _instance;
private Method _method;
private static WeakHashMap<Object, Object> s_cache = new WeakHashMap<Object, Object>();
private MethodCapturer() {
}
@SuppressWarnings("unchecked")
public static <T> MethodCapturer<T> capture(T obj) {
synchronized(s_cache) {
MethodCapturer<T> capturer = (MethodCapturer<T>)s_cache.get(obj);
if(capturer != null) {
return capturer;
}
final MethodCapturer<T> capturerNew = new MethodCapturer<T>();
Enhancer en = new Enhancer();
en.setSuperclass(obj.getClass());
en.setCallbacks(new Callback[] { new MethodInterceptor() {
@Override
public Object intercept(Object arg0, Method arg1, Object[] arg2,
MethodProxy arg3) throws Throwable {
capturerNew.setMethod(arg1);
return null;
}
},
new MethodInterceptor() {
@Override
public Object intercept(Object arg0, Method arg1, Object[] arg2,
MethodProxy arg3) throws Throwable {
return null;
}
}
});
en.setCallbackFilter(new CallbackFilter() {
public int accept(Method method) {
if (method.getParameterTypes().length == 0 && method.getName().equals("finalize")) {
return 1;
}
return 0;
}}
);
((MethodCapturer<T>)capturerNew).setInstance((T)en.create());
// We expect MethodCapturer is only used for singleton objects here, so we only maintain a limited cache
// here
if(s_cache.size() < CACHE_SIZE) {
s_cache.put(obj, capturerNew);
}
return capturerNew;
}
}
public T instance() {
return _instance;
}
private void setInstance(T instance) {
_instance = instance;
}
public Method get(Object... useless) {
return _method;
}
private void setMethod(Method method) {
_method = method;
}
}

View File

@ -14,8 +14,8 @@
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.utils.db;
public interface On<S, J, T> {
package com.cloud.utils;
public interface Predicate {
boolean checkCondition();
}

View File

@ -62,4 +62,5 @@ public interface SerialVersionUID {
public static final long CallFailedException = Base | 0x28;
public static final long UnableDeleteHostException = Base | 0x29;
public static final long AffinityConflictException = Base | 0x2a;
public static final long JobCancellationException = Base | 0x2b;
}

View File

@ -65,6 +65,8 @@ public class ComponentLifecycleBase implements ComponentLifecycle {
@Override
public boolean configure(String name, Map<String, Object> params)
throws ConfigurationException {
_name = name;
_configParams = params;
return true;
}

View File

@ -1,100 +0,0 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.utils.db;
import java.util.HashMap;
import com.cloud.utils.db.SearchCriteria.Op;
public class Condition<T, K> {
Where<T, K> _where;
Attribute _attr;
String _as;
SearchCriteria.Op _op;
String _paramName;
protected Condition(Where<T, K> where, Attribute attr, String as) {
assert (where != null) : "What am I going to return to the user when Where is null?";
assert (attr != null) : "What's the point of giving me a null attribute?";
_where = where;
_attr = attr;
_as = as;
}
protected NextWhere<T, K> set(Op op, String paramName) {
_op = op;
_paramName = paramName;
Where<T, K> where = _where;
_where = null;
return where;
}
public NextWhere<T, K> eq(String paramName) {
return set(Op.EQ, paramName);
}
public NextWhere<T, K> lt(String paramName) {
return set(Op.LT, paramName);
}
public NextWhere<T, K> lteq(String paramName) {
return set(Op.LTEQ, paramName);
}
public NextWhere<T, K> gt(String paramName) {
return set(Op.GT, paramName);
}
public NextWhere<T, K> isNull() {
return set(Op.NULL, null);
}
public NextWhere<T, K> isNotNull() {
return set(Op.NNULL, null);
}
public NextWhere<T, K> in(String paramName) {
_op = Op.IN;
_paramName = paramName;
return _where;
}
protected String getParamName() {
assert (_paramName instanceof String) : "Well, how can we get back a parameter name if it was not assigned one?";
return _paramName;
}
@Override
public boolean equals(Object obj) {
return _paramName.equals(obj);
}
@Override
public int hashCode() {
return _paramName.hashCode();
}
public void toSql(StringBuilder builder, HashMap<String, Object[]> values) {
if (_as != null) {
builder.append(_as);
} else {
builder.append(_attr.table);
}
builder.append(".").append(_attr.columnName);
}
}

View File

@ -14,15 +14,11 @@
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.dao;
package com.cloud.utils.db;
import java.io.Serializable;
import java.util.List;
import com.cloud.utils.db.GenericSearchBuilder;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
/**
* Generic Entity Manager to retrieve database objects.
*

View File

@ -1,29 +0,0 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.utils.db;
public interface FirstWhere<T, K> {
Condition<T, K> field(Object field);
Condition<T, K> field(Object field, String as);
NextWhere<T, K> text(String text, String... paramNames);
FirstWhere<T, K> op();
void done();
}

View File

@ -134,6 +134,8 @@ public interface GenericDao<T, ID extends Serializable> {
boolean update(ID id, T entity);
int update(T entity, SearchCriteria<T> sc);
/**
* Look for all active rows.
* @return list of entity beans.

View File

@ -68,7 +68,6 @@ import com.cloud.utils.DateUtil;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair;
import com.cloud.utils.Ternary;
import com.cloud.utils.component.ComponentContext;
import com.cloud.utils.component.ComponentLifecycle;
import com.cloud.utils.component.ComponentLifecycleBase;
import com.cloud.utils.component.ComponentMethodInterceptable;
@ -130,8 +129,8 @@ public abstract class GenericDaoBase<T, ID extends Serializable> extends Compone
protected Field[] _embeddedFields;
// This is private on purpose. Everyone should use createPartialSelectSql()
private Pair<StringBuilder, Attribute[]> _partialSelectSql;
private Pair<StringBuilder, Attribute[]> _partialQueryCacheSelectSql;
private final Pair<StringBuilder, Attribute[]> _partialSelectSql;
private final Pair<StringBuilder, Attribute[]> _partialQueryCacheSelectSql;
protected StringBuilder _discriminatorClause;
protected Map<String, Object> _discriminatorValues;
protected String _selectByIdSql;
@ -178,6 +177,7 @@ public abstract class GenericDaoBase<T, ID extends Serializable> extends Compone
return builder;
}
@Override
public Map<String, Attribute> getAllAttributes() {
return _allAttributes;
}
@ -351,7 +351,7 @@ public abstract class GenericDaoBase<T, ID extends Serializable> extends Compone
}
@Override
public List<T> searchIncludingRemoved(SearchCriteria<T> sc, final Filter filter, final Boolean lock,
public List<T> searchIncludingRemoved(SearchCriteria<T> sc, final Filter filter, final Boolean lock,
final boolean cache, final boolean enable_query_cache) {
String clause = sc != null ? sc.getWhereClause() : null;
if (clause != null && clause.length() == 0) {
@ -420,6 +420,9 @@ public abstract class GenericDaoBase<T, ID extends Serializable> extends Compone
@Override @SuppressWarnings("unchecked")
public <M> List<M> customSearchIncludingRemoved(SearchCriteria<M> sc, final Filter filter) {
if (sc.isSelectAll()) {
return (List<M>)searchIncludingRemoved((SearchCriteria<T>)sc, filter, null, false);
}
String clause = sc != null ? sc.getWhereClause() : null;
if (clause != null && clause.length() == 0) {
clause = null;
@ -1482,7 +1485,11 @@ public abstract class GenericDaoBase<T, ID extends Serializable> extends Compone
if (type == EnumType.STRING) {
pstmt.setString(j, value == null ? null : value.toString());
} else if (type == EnumType.ORDINAL) {
pstmt.setInt(j, value == null ? null : ((Enum<?>)value).ordinal());
if (value == null) {
pstmt.setObject(j, null);
} else {
pstmt.setInt(j, ((Enum<?>)value).ordinal());
}
}
} else if (attr.field.getType() == URI.class) {
pstmt.setString(j, value == null ? null : value.toString());
@ -1496,7 +1503,11 @@ public abstract class GenericDaoBase<T, ID extends Serializable> extends Compone
if (type == EnumType.STRING) {
pstmt.setString(j, value == null ? null : value.toString());
} else if (type == EnumType.ORDINAL) {
pstmt.setLong(j, value == null ? null : (value instanceof Ip) ? ((Ip)value).longValue() : NetUtils.ip2Long((String)value));
if (value == null) {
pstmt.setObject(j, null);
} else {
pstmt.setLong(j, (value instanceof Ip) ? ((Ip)value).longValue() : NetUtils.ip2Long((String)value));
}
}
} else {
pstmt.setObject(j, value);

View File

@ -22,6 +22,7 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.persistence.Column;
import javax.persistence.Transient;
@ -33,7 +34,6 @@ import net.sf.cglib.proxy.MethodProxy;
import com.cloud.utils.db.SearchCriteria.Func;
import com.cloud.utils.db.SearchCriteria.Op;
import com.cloud.utils.db.SearchCriteria.SelectType;
import com.cloud.utils.exception.CloudRuntimeException;
/**
* GenericSearchBuilder is used to build a search based on a VO object
@ -74,13 +74,19 @@ public class GenericSearchBuilder<T, K> implements MethodInterceptor {
}
protected Attribute getSpecifiedAttribute() {
assert(_entity != null && _specifiedAttrs != null && _specifiedAttrs.size() == 1) : "Now now, better specify an attribute or else we can't help you";
if (_entity == null || _specifiedAttrs == null || _specifiedAttrs.size() != 1) {
throw new RuntimeException("Now now, better specify an attribute or else we can't help you");
}
return _specifiedAttrs.get(0);
}
public GenericSearchBuilder<T, K> selectField(Object... useless) {
assert _entity != null : "SearchBuilder cannot be modified once it has been setup";
assert _specifiedAttrs.size() > 0 : "You didn't specify any attributes";
if (_entity == null) {
throw new RuntimeException("SearchBuilder cannot be modified once it has been setup");
}
if (_specifiedAttrs.size() <= 0) {
throw new RuntimeException("You didn't specify any attributes");
}
if (_selects == null) {
_selects = new ArrayList<Select>();
@ -117,9 +123,15 @@ public class GenericSearchBuilder<T, K> implements MethodInterceptor {
* @return a SearchBuilder to build more search parts.
*/
public GenericSearchBuilder<T, K> select(String fieldName, Func func, Object useless, Object... params) {
assert _entity != null : "SearchBuilder cannot be modified once it has been setup";
assert _specifiedAttrs.size() <= 1 : "You can't specify more than one field to search on";
assert func.getCount() == -1 || (func.getCount() == (params.length + 1)) : "The number of parameters does not match the function param count for " + func;
if (_entity == null) {
throw new RuntimeException("SearchBuilder cannot be modified once it has been setup");
}
if (_specifiedAttrs.size() > 1) {
throw new RuntimeException("You can't specify more than one field to search on");
}
if (func.getCount() != -1 && (func.getCount() != (params.length + 1))) {
throw new RuntimeException("The number of parameters does not match the function param count for " + func);
}
if (_selects == null) {
_selects = new ArrayList<Select>();
@ -131,12 +143,15 @@ public class GenericSearchBuilder<T, K> implements MethodInterceptor {
field = _resultType.getDeclaredField(fieldName);
field.setAccessible(true);
} catch (SecurityException e) {
throw new CloudRuntimeException("Unable to find " + fieldName, e);
throw new RuntimeException("Unable to find " + fieldName, e);
} catch (NoSuchFieldException e) {
throw new CloudRuntimeException("Unable to find " + fieldName, e);
throw new RuntimeException("Unable to find " + fieldName, e);
}
} else {
assert _selects.size() == 0 : "You're selecting more than one item and yet is not providing a container class to put these items in. So what do you expect me to do. Spin magic?";
if (_selects.size() != 0) {
throw new RuntimeException(
"You're selecting more than one item and yet is not providing a container class to put these items in. So what do you expect me to do. Spin magic?");
}
}
Select select = new Select(func, _specifiedAttrs.size() == 0 ? null : _specifiedAttrs.get(0), field, params);
@ -147,10 +162,6 @@ public class GenericSearchBuilder<T, K> implements MethodInterceptor {
return this;
}
// public GenericSearchBuilder<T, K> select(String joinName, String fieldName, Func func, Object useless, Object... params) {
//
// }
@Override
public Object intercept(Object object, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
String name = method.getName();
@ -174,7 +185,7 @@ public class GenericSearchBuilder<T, K> implements MethodInterceptor {
}
}
}
assert false : "Perhaps you need to make the method start with get or is?";
throw new RuntimeException("Perhaps you need to make the method start with get or is: " + method);
}
}
return methodProxy.invokeSuper(object, args);
@ -199,6 +210,16 @@ public class GenericSearchBuilder<T, K> implements MethodInterceptor {
return this;
}
public GenericSearchBuilder<T, K> and(Object useless, Op op, String name) {
constructCondition(name, " AND ", _specifiedAttrs.get(0), op);
return this;
}
public Preset and(Object useless, Op op) {
Condition condition = constructCondition(UUID.randomUUID().toString(), " AND ", _specifiedAttrs.get(0), op);
return new Preset(this, condition);
}
public GenericSearchBuilder<T, K> and() {
constructCondition(null, " AND ", null, null);
return this;
@ -217,19 +238,53 @@ public class GenericSearchBuilder<T, K> implements MethodInterceptor {
return and(name, useless, op);
}
public GenericSearchBuilder<T, K> where(Object useless, Op op, String name) {
return and(name, useless, op);
}
public Preset where(Object useless, Op op) {
return and(useless, op);
}
public GenericSearchBuilder<T, K> left(String name, Object useless, Op op) {
constructCondition(name, " ( ", _specifiedAttrs.get(0), op);
return this;
}
public GenericSearchBuilder<T, K> left(Object useless, Op op, String name) {
constructCondition(name, " ( ", _specifiedAttrs.get(0), op);
return this;
}
public Preset left(Object useless, Op op) {
Condition condition = constructCondition(UUID.randomUUID().toString(), " ( ", _specifiedAttrs.get(0), op);
return new Preset(this, condition);
}
public GenericSearchBuilder<T, K> op(Object useless, Op op, String name) {
return left(useless, op, name);
}
public Preset op(Object useless, Op op) {
return left(useless, op);
}
public GenericSearchBuilder<T, K> op(String name, Object useless, Op op) {
return left(name, useless, op);
}
public GenericSearchBuilder<T, K> openParen(Object useless, Op op, String name) {
return left(name, useless, op);
}
public GenericSearchBuilder<T, K> openParen(String name, Object useless, Op op) {
return left(name, useless, op);
}
public Preset openParen(Object useless, Op op) {
return left(useless, op);
}
public GroupBy<T, K> groupBy(Object... useless) {
assert _groupBy == null : "Can't do more than one group bys";
_groupBy = new GroupBy<T, K>(this);
@ -254,6 +309,16 @@ public class GenericSearchBuilder<T, K> implements MethodInterceptor {
return this;
}
public GenericSearchBuilder<T, K> or(Object useless, Op op, String name) {
constructCondition(name, " OR ", _specifiedAttrs.get(0), op);
return this;
}
public Preset or(Object useless, Op op) {
Condition condition = constructCondition(UUID.randomUUID().toString(), " OR ", _specifiedAttrs.get(0), op);
return new Preset(this, condition);
}
public GenericSearchBuilder<T, K> join(String name, GenericSearchBuilder<?, ?> builder, Object useless, Object useless2, JoinBuilder.JoinType joinType) {
assert _entity != null : "SearchBuilder cannot be modified once it has been setup";
assert _specifiedAttrs.size() == 1 : "You didn't select the attribute.";
@ -272,7 +337,7 @@ public class GenericSearchBuilder<T, K> implements MethodInterceptor {
return this;
}
protected void constructCondition(String conditionName, String cond, Attribute attr, Op op) {
protected Condition constructCondition(String conditionName, String cond, Attribute attr, Op op) {
assert _entity != null : "SearchBuilder cannot be modified once it has been setup";
assert op == null || _specifiedAttrs.size() == 1 : "You didn't select the attribute.";
assert op != Op.SC : "Call join";
@ -280,6 +345,7 @@ public class GenericSearchBuilder<T, K> implements MethodInterceptor {
Condition condition = new Condition(conditionName, cond, attr, op);
_conditions.add(condition);
_specifiedAttrs.clear();
return condition;
}
/**
@ -360,6 +426,7 @@ public class GenericSearchBuilder<T, K> implements MethodInterceptor {
protected final String cond;
protected final Op op;
protected final Attribute attr;
protected Object[] presets;
protected Condition(String name) {
this(name, null, null, null);
@ -370,8 +437,21 @@ public class GenericSearchBuilder<T, K> implements MethodInterceptor {
this.attr = attr;
this.cond = cond;
this.op = op;
this.presets = null;
}
public boolean isPreset() {
return presets != null;
}
public void setPresets(Object... presets) {
this.presets = presets;
}
public Object[] getPresets() {
return presets;
}
public void toSql(StringBuilder sql, Object[] params, int count) {
if (count > 0) {
sql.append(cond);
@ -409,7 +489,9 @@ public class GenericSearchBuilder<T, K> implements MethodInterceptor {
sql.delete(sql.length() - 5, sql.length());
sql.append(" IS NOT NULL ");
} else {
assert((op.getParams() == 0 && params == null) || (params.length == op.getParams())) : "Problem with condition: " + name;
if ((op.getParams() != 0 || params != null) && (params.length != op.getParams())) {
throw new RuntimeException("Problem with condition: " + name);
}
}
}
@ -445,4 +527,22 @@ public class GenericSearchBuilder<T, K> implements MethodInterceptor {
this.field = field;
}
}
public class Preset {
GenericSearchBuilder<T, K> builder;
Condition condition;
protected Preset(GenericSearchBuilder<T, K> builder, Condition condition) {
this.builder = builder;
this.condition = condition;
}
public GenericSearchBuilder<T, K> values(Object... params) {
if (condition.op.getParams() > 0 && condition.op.params != params.length) {
throw new RuntimeException("The # of parameters set " + params.length + " does not match # of parameters required by " + condition.op);
}
condition.setPresets(params);
return builder;
}
}
}

View File

@ -1,31 +0,0 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.utils.db;
/**
* JoinQueryBuilder builds queries for joins between multiple tables.
*
*/
public interface JoinQueryBuilder<S, T> {
Select<S, T> selectField(Object column);
<J> On<S, J, T> innerJoin(Class<J> entityClazz);
<J> J entity(Class<J> entityClazz);
FirstWhere<S, T> where();
}

View File

@ -1,194 +0,0 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.utils.db;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import com.cloud.utils.Pair;
public class QueryBuilder<S, T> implements MethodInterceptor, SimpleQueryBuilder<S>, SelectQueryBuilder<S, T>, JoinQueryBuilder<S, T> {
public enum Func {
NATIVE("@", 1),
MAX("MAX(@)", 1),
MIN("MIN(@)", 1),
FIRST("FIRST(@)", 1),
LAST("LAST(@)", 1),
SUM("SUM(@)", 1),
COUNT("COUNT(@)", 1),
DISTINCT("DISTINCT(@)", 1);
private String func;
private int count;
Func(String func, int params) {
this.func = func;
this.count = params;
}
@Override
public String toString() {
return func;
}
public int getCount() {
return count;
}
}
protected HashMap<Class<?>, Pair<GenericDao<?,?>, Object>> _entities;
protected ArrayList<Attribute> _specifiedAttrs = new ArrayList<Attribute>();
protected T _resultSetClass;
protected ArrayList<Select<S, T>> _selects;
public QueryBuilder(Class<T> resultSetClass, Class<?>... clazzes) {
_entities = new HashMap<Class<?>, Pair<GenericDao<?,?>, Object>>(clazzes.length);
for (Class<?> clazz : clazzes) {
GenericDao<?,?> dao = GenericDaoBase.getDao(clazz);
Enhancer searchEnhancer = new Enhancer();
searchEnhancer.setSuperclass(clazz);
searchEnhancer.setCallback(this);
Object entity = searchEnhancer.create();
_entities.put(clazz, new Pair<GenericDao<?, ?>, Object>(dao, entity));
}
}
protected void clean() {
_specifiedAttrs = null;
_entities = null;
}
/**
* Constructor for SelectQueryBuilder interface. Must specify the
* table to be performing the query on and the result class to place it in.
* @param entityClass entity class to do the query on.
* @param resultSetClass result class to put the result set in.
*/
public QueryBuilder(Class<S> entityClass, Class<T> resultSetClass) {
_entities = new HashMap<Class<?>, Pair<GenericDao<?,?>, Object>>(1);
GenericDao<?,?> dao = GenericDaoBase.getDao(entityClass);
Enhancer searchEnhancer = new Enhancer();
searchEnhancer.setSuperclass(entityClass);
searchEnhancer.setCallback(this);
Object entity = searchEnhancer.create();
_entities.put(entityClass, new Pair<GenericDao<?, ?>, Object>(dao, entity));
}
@Override
public SimpleQueryBuilder<S> selectFields(Object... fields) {
assert _entities != null && _entities.size() == 1 : "Now you've done it....Stop casting interfaces on the QueryBuilder";
assert _specifiedAttrs.size() > 0 : "You didn't specify any attributes";
if (_selects == null) {
_selects = new ArrayList<Select<S, T>>(fields.length);
}
for (Attribute attr : _specifiedAttrs) {
_selects.add(new Select<S, T>(this, null, attr));
}
_specifiedAttrs.clear();
return this;
}
protected void set(GenericDao<?, ?> dao , String name) {
Attribute attr = dao.getAllAttributes().get(name);
assert (attr != null) : "Searching for a field that's not there: " + name;
_specifiedAttrs.add(attr);
}
@Override
public Object intercept(Object entity, Method method, Object[] args, MethodProxy proxy) throws Throwable {
Class<?> entityClass = entity.getClass().getSuperclass();
Pair<GenericDao<?,?>, Object> daoInfo = _entities.get(entityClass);
assert (daoInfo != null) : "You need to specify " + entityClass + " as one of the entities in the Query";
GenericDao<?,?> dao = daoInfo.first();
String name = method.getName();
if (name.startsWith("get")) {
String fieldName = Character.toLowerCase(name.charAt(3)) + name.substring(4);
set(dao, fieldName);
return null;
} else if (name.startsWith("is")) {
String fieldName = Character.toLowerCase(name.charAt(2)) + name.substring(3);
set(dao, fieldName);
return null;
} else {
assert false : "Perhaps you need to make the method start with get or is?";
}
return proxy.invokeSuper(entity, args);
}
@Override
@SuppressWarnings("unchecked")
public <E> E entity(Class<E> clazz) {
return (E)_entities.get(clazz).second();
}
@Override
@SuppressWarnings("unchecked")
public S entity() {
return (S)_entities.values().iterator().next().second();
}
@Override
public FirstWhere<S, T> where() {
return new Where<S, T>(this);
}
@Override
public SimpleQueryBuilder<S> selectAll() {
return this;
}
public List<Attribute> getSpecifiedAttributes() {
return _specifiedAttrs;
}
public Attribute getSpecifiedAttribute() {
assert _specifiedAttrs.size() == 1 : "You can only specify one attribute";
return _specifiedAttrs.get(0);
}
@Override
public Select<S, T> selectColumn(Object column) {
return null;
}
@Override
public Select<S, T> selectField(Object column) {
// TODO Auto-generated method stub
return null;
}
@Override
public <J> On<S, J, T> innerJoin(Class<J> entityClazz) {
// TODO Auto-generated method stub
return null;
}
}

View File

@ -295,6 +295,9 @@ public class SearchCriteria<K> {
StringBuilder sql = new StringBuilder();
int i = 0;
for (Condition condition : _conditions) {
if (condition.isPreset()) {
_params.put(condition.name, condition.presets);
}
Object[] params = _params.get(condition.name);
if ((condition.op == null || condition.op.params == 0) || (params != null)) {
condition.toSql(sql, params, i++);
@ -302,6 +305,9 @@ public class SearchCriteria<K> {
}
for (Condition condition : _additionals) {
if (condition.isPreset()) {
_params.put(condition.name, condition.presets);
}
Object[] params = _params.get(condition.name);
if ((condition.op.params == 0) || (params != null)) {
condition.toSql(sql, params, i++);

View File

@ -1,52 +0,0 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.utils.db;
import java.lang.reflect.Field;
public class Select<S, T> {
QueryBuilder<S,T> _builder;
Class<T> _clazz;
Attribute _attr;
String _as;
Field _field;
protected Select(QueryBuilder<S, T> builder, Class<T> clazz, Attribute attr) {
_builder = builder;
_clazz = clazz;
_attr = attr;
}
public QueryBuilder<S, T> into(String fieldName) {
if (fieldName != null) {
try {
_field = _clazz.getDeclaredField(fieldName);
_field.setAccessible(true);
} catch (SecurityException e) {
throw new RuntimeException("Unable to find " + fieldName + " in " + _clazz.getName(), e);
} catch (NoSuchFieldException e) {
throw new RuntimeException("Unable to find " + fieldName + " in " + _clazz.getName(), e);
}
}
return _builder;
}
public QueryBuilder<S, T> as(String as) {
_as = as;
return _builder;
}
}

View File

@ -1,47 +0,0 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.utils.db;
/**
* SimpleQueryBuilder builds queries against a single table. The
*
*/
public interface SimpleQueryBuilder<S> {
/**
* Select all of the columns in the entity object. This is default so
* it's not necessary to make this method call at all.
*/
SimpleQueryBuilder<S> selectAll();
/**
* Select the following columns
* @param columns array of columsn to select.
*/
SimpleQueryBuilder<S> selectFields(Object... columns);
/**
* @return the entity object we're building this query for. By using this
* entity object, you can specify which column to select or form
*/
S entity();
/**
* Starts the query conditionals.
* @return
*/
FirstWhere<S, ?> where();
}

View File

@ -1,81 +0,0 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.utils.db;
import java.util.ArrayList;
import java.util.List;
/**
* Where implements any list of search conditions.
*
*/
public class Where<T, K> implements FirstWhere<T, K>, NextWhere<T, K> {
QueryBuilder<T, K> _builder;
List<Object> _conditions = new ArrayList<Object>();
protected Where(QueryBuilder<T, K> builder) {
_builder = builder;
}
@Override
public Condition<T, K> field(Object useless, String as) {
Attribute attr = _builder.getSpecifiedAttribute();
Condition<T, K> cond = new Condition<T, K>(this, attr, as);
_conditions.add(cond);
return cond;
}
@Override
public Where<T, K> and() {
_conditions.add(" (");
return this;
}
@Override
public Where<T, K> or() {
_conditions.add(" OR ");
return this;
}
@Override
public NextWhere<T, K> not() {
_conditions.add(" NOT ");
return this;
}
@Override
public NextWhere<T, K> text(String text, String... paramNames) {
assert ((paramNames.length == 0 && !text.contains("?")) || (text.matches("\\?.*{" + paramNames.length + "}")));
// TODO Auto-generated method stub
return null;
}
@Override
public Condition<T, K> field(Object useless) {
return field(useless, null);
}
@Override
public FirstWhere<T, K> op() {
_conditions.add("(");
return this;
}
@Override
public void done() {
}
}

View File

@ -29,11 +29,11 @@ public class CloudRuntimeException extends RuntimeException implements ErrorCont
private static final long serialVersionUID = SerialVersionUID.CloudRuntimeException;
protected ArrayList<Pair<Class<?>, String>> uuidList = new ArrayList<Pair<Class<?>, String>>();
// This holds a list of uuids and their descriptive names.
protected ArrayList<ExceptionProxyObject> idList = new ArrayList<ExceptionProxyObject>();
protected ArrayList<Pair<Class<?>, String>> uuidList = new ArrayList<Pair<Class<?>, String>>();
protected int csErrorCode;
@ -47,7 +47,7 @@ public class CloudRuntimeException extends RuntimeException implements ErrorCont
setCSErrorCode(CSExceptionErrorCode.getCSErrCode(this.getClass().getName()));
}
public CloudRuntimeException() {
protected CloudRuntimeException() {
super();
setCSErrorCode(CSExceptionErrorCode.getCSErrCode(this.getClass().getName()));
}
@ -65,6 +65,12 @@ public class CloudRuntimeException extends RuntimeException implements ErrorCont
idList.add(proxy);
}
@Override
public CloudRuntimeException add(Class<?> entity, String uuid) {
uuidList.add(new Pair<Class<?>, String>(entity, uuid));
return this;
}
public ArrayList<ExceptionProxyObject> getIdProxyList() {
return idList;
}
@ -78,13 +84,7 @@ public class CloudRuntimeException extends RuntimeException implements ErrorCont
}
public CloudRuntimeException(Throwable t) {
super(t);
}
@Override
public CloudRuntimeException add(Class<?> entity, String uuid) {
uuidList.add(new Pair<Class<?>, String>(entity, uuid));
return this;
super(t.getMessage(), t);
}
@Override

View File

@ -1,28 +1,25 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.utils.db;
/**
* is defined.
*/
public interface SelectQueryBuilder<T, S> {
Select<T, S> selectColumn(Object column);
T entity();
FirstWhere<T, S> where();
}
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.apache.cloudstack.config;
/**
* ConfigDepot is a repository of configurations.
*
*/
public interface ConfigDepot {
<T> ConfigValue<T> get(ConfigKey<T> key);
}

View File

@ -0,0 +1,98 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.apache.cloudstack.config;
/**
* ConfigKey supplants the original Config.java. It is just a class
* declaration where others can declare their config variables.
*
* TODO: This class should be moved to a framework project where the gathering
* of these configuration keys should be done by a config server. I
* don't have time yet to do this. Ask me about it if you want to work
* in this area. Right now, we'll just work with the actual names.
*/
public class ConfigKey<T> {
private final String _category;
public String category() {
return _category;
}
public Class<?> component() {
return _componentClass;
}
public Class<T> type() {
return _type;
}
public String key() {
return _name;
}
public String defaultValue() {
return _defaultValue;
}
public String description() {
return _description;
}
public String range() {
return _range;
}
public String scope() {
return _scope;
}
public boolean isDynamic() {
return _isDynamic;
}
@Override
public String toString() {
return _name;
}
private final Class<?> _componentClass;
private final Class<T> _type;
private final String _name;
private final String _defaultValue;
private final String _description;
private final String _range;
private final String _scope; // Parameter can be at different levels (Zone/cluster/pool/account), by default every parameter is at global
private final boolean _isDynamic;
public ConfigKey(Class<T> type, String name, String category, Class<?> componentClass, String defaultValue, String description, boolean isDynamic, String range,
String scope) {
_category = category;
_componentClass = componentClass;
_type = type;
_name = name;
_defaultValue = defaultValue;
_description = description;
_range = range;
_scope = scope;
_isDynamic = isDynamic;
}
public ConfigKey(Class<T> type, String name, String category, Class<?> componentClass, String defaultValue, String description, boolean isDynamic, String range) {
this(type, name, category, componentClass, defaultValue, description, isDynamic, range, null);
}
}

View File

@ -0,0 +1,76 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.apache.cloudstack.config;
import com.cloud.utils.db.EntityManager;
import com.cloud.utils.exception.CloudRuntimeException;
/**
* This is a match set to ConfigKey.
*
* TODO: When we create a framework project for configuration, this should be
* moved there.
*/
public class ConfigValue<T> {
ConfigKey<T> _config;
EntityManager _entityMgr;
Number _multiplier;
T _value;
public ConfigValue(EntityManager entityMgr, ConfigKey<T> config) {
_entityMgr = entityMgr;
_config = config;
_multiplier = 1;
}
public ConfigKey<T> getConfigKey() {
return _config;
}
public ConfigValue<T> setMultiplier(Number multiplier) { // Convience method
_multiplier = multiplier;
return this;
}
@SuppressWarnings("unchecked")
public T value() {
if (_value == null || _config.isDynamic()) {
Configuration vo = _entityMgr.findById(Configuration.class, _config.key());
String value = vo != null ? vo.getValue() : _config.defaultValue();
Class<T> type = _config.type();
if (type.isAssignableFrom(Boolean.class)) {
_value = (T)Boolean.valueOf(value);
} else if (type.isAssignableFrom(Integer.class)) {
_value = (T)new Integer((Integer.parseInt(value) * _multiplier.intValue()));
} else if (type.isAssignableFrom(Long.class)) {
_value = (T)new Long(Long.parseLong(value) * _multiplier.longValue());
} else if (type.isAssignableFrom(Short.class)) {
_value = (T)new Short(Short.parseShort(value));
} else if (type.isAssignableFrom(String.class)) {
_value = (T)value;
} else if (type.isAssignableFrom(Float.class)) {
_value = (T)new Float(Float.parseFloat(value) * _multiplier.floatValue());
} else {
throw new CloudRuntimeException("Unsupported data type for config values: " + type);
}
}
return _value;
}
}

View File

@ -4,9 +4,9 @@
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// the License. You may obtain a copy of the License at
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
@ -14,14 +14,20 @@
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.utils.db;
package org.apache.cloudstack.config;
public interface NextWhere<T, K> extends FirstWhere<T, K> {
NextWhere<T, K> and();
NextWhere<T, K> or();
NextWhere<T, K> not();
@Override
void done();
public interface Configuration {
public String getCategory();
public String getInstance();
public String getComponent();
public String getName();
public String getValue();
public String getDescription();
}

View File

@ -47,7 +47,7 @@ public class SpringUtils {
* useDefaultFilters=true. See the following example.
*
* <pre>
* @ComponentScan(basePackageClasses={AffinityGroupServiceImpl.class, ActionEventUtils.class},
* @ComponentScan(basePackageClasses={AffinityGroupServiceImpl.class, EventUtils.class},
* includeFilters={@Filter(value=TestConfiguration.Library.class, type=FilterType.CUSTOM)},
* useDefaultFilters=false)
* </pre>

View File

@ -14,12 +14,11 @@
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.cluster;
package org.apache.cloudstack.utils.identity;
import javax.ejb.Local;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import com.cloud.utils.component.AdapterBase;
import com.cloud.utils.component.ComponentLifecycle;
@ -27,15 +26,12 @@ import com.cloud.utils.component.SystemIntegrityChecker;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.net.MacAddress;
@Component
@Local(value = {SystemIntegrityChecker.class})
public class ManagementServerNode extends AdapterBase implements SystemIntegrityChecker {
private final Logger s_logger = Logger.getLogger(ManagementServerNode.class);
private static final long s_nodeId = MacAddress.getMacAddress().toLong();
public static enum State { Up, Down };
public ManagementServerNode() {
setRunLevel(ComponentLifecycle.RUN_LEVEL_FRAMEWORK_BOOTSTRAP);
}