Deleted some useless files

This commit is contained in:
Alex Huang 2012-08-24 16:56:47 -07:00
parent 239883c7a4
commit 6309253de1
27 changed files with 93 additions and 1093 deletions

View File

@ -1,3 +1,2 @@
#Mon Aug 27 14:48:15 PDT 2012
eclipse.preferences.version=1
encoding/<project>=UTF-8

View File

@ -1,3 +1,2 @@
#Mon Aug 27 14:48:16 PDT 2012
eclipse.preferences.version=1
encoding/<project>=UTF-8

View File

@ -1,3 +1,2 @@
#Mon Aug 27 14:48:15 PDT 2012
eclipse.preferences.version=1
encoding/<project>=UTF-8

View File

@ -1,3 +1,2 @@
#Mon Aug 27 14:48:15 PDT 2012
eclipse.preferences.version=1
encoding/<project>=UTF-8

View File

@ -28,7 +28,7 @@ import com.cloud.vm.VirtualMachine;
public interface OrchestrationService {
/**
* Reserves a new virtual machine
* creates a new virtual machine
*
* @param uuid externally unique name to reference the virtual machine
* @param template reference to the template
@ -42,7 +42,7 @@ public interface OrchestrationService {
* @param details extra details to store for the VM
* @return VirtualMachine
*/
VirtualMachine create(String uuid,
VirtualMachine create(String name,
String template,
String hostName,
int cpu,
@ -84,7 +84,6 @@ public interface OrchestrationService {
* @return job Id
* @throws CloudRuntimeException if error
*/
@Job(callback=)
String deploy(String reservationId);
/**

View File

@ -19,7 +19,7 @@
package org.apache.cloudstack.platform.subsystem.api.network;
public interface NetworkSubsystem {
String createNetwork();
String create();
String start(String network, String reservationId);

View File

@ -18,6 +18,12 @@
*/
package org.apache.cloudstack.platform.subsystem.api.storage;
import java.net.URI;
import com.cloud.org.Grouping;
public interface DataMigrationSubSystem {
void migrate(String volume, String storagePool, String reservationId);
Class<? extends Grouping> getScopeCoverage();
void migrate(URI source, URI dest, String reservationId);
}

View File

@ -8,6 +8,8 @@ public interface StorageSubSystem {
String getType();
Class<? extends Grouping> getScope();
create();
URI grantAccess(String vol, String reservationId);
URI RemoveAccess(String vol, String reservationId);
}

View File

@ -27,7 +27,6 @@ public interface ComputeOrchestrator {
* @param vm vm
* @param reservationId
*/
@Ipc(topic="cs.compute.start")
void start(@IpcParam String vm, @IpcParam String reservationId);
@Ipc(topic="cs.compute.cancel")

View File

@ -1,3 +1,2 @@
#Mon Aug 27 14:48:15 PDT 2012
eclipse.preferences.version=1
encoding/<project>=UTF-8

View File

@ -1011,6 +1011,7 @@ CREATE TABLE `cloud`.`vm_instance` (
`uuid` varchar(40),
`instance_name` varchar(255) NOT NULL COMMENT 'name of the vm instance running on the hosts',
`state` varchar(32) NOT NULL,
`desired_state` varchar(32) NULL,
`vm_template_id` bigint unsigned,
`guest_os_id` bigint unsigned NOT NULL,
`private_mac_address` varchar(17),

View File

@ -1,3 +1,2 @@
#Mon Aug 27 14:48:15 PDT 2012
eclipse.preferences.version=1
encoding/<project>=UTF-8

View File

@ -1,3 +1,2 @@
#Mon Aug 27 14:48:16 PDT 2012
eclipse.preferences.version=1
encoding/<project>=UTF-8

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

@ -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

@ -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,351 +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.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.log4j.Logger;
import com.cloud.utils.Pair;
import com.cloud.utils.Ternary;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.net.MacAddress;
import com.cloud.utils.time.InaccurateClock;
public class Merovingian {
private static final Logger s_logger = Logger.getLogger(Merovingian.class);
private static final String ACQUIRE_SQL = "INSERT IGNORE INTO op_lock (op_lock.key, op_lock.mac, op_lock.ip, op_lock.thread) VALUES (?, ?, ?, ?)";
private static final String INQUIRE_SQL = "SELECT op_lock.ip FROM op_lock WHERE op_lock.key = ?";
private static final String RELEASE_SQL = "DELETE FROM op_lock WHERE op_lock.key = ?";
private static final String CLEAR_SQL = "DELETE FROM op_lock WHERE op_lock.mac = ? AND op_lock.ip = ?";
private final static HashMap<String, Pair<Lock, Integer>> s_memLocks = new HashMap<String, Pair<Lock, Integer>>(1027);
private final LinkedHashMap<String, Ternary<Savepoint, Integer, Long>> _locks = new LinkedHashMap<String, Ternary<Savepoint, Integer, Long>>();
private int _previousIsolation = Connection.TRANSACTION_NONE;
private final static String s_macAddress;
private final static String s_ipAddress;
static {
s_macAddress = MacAddress.getMacAddress().toString(":");
String address = null;
try {
InetAddress addr = InetAddress.getLocalHost();
address = addr.getHostAddress().toString();
} catch (UnknownHostException e) {
address = "127.0.0.1";
}
s_ipAddress = address;
}
Connection _conn = null;
public Merovingian(short dbId) {
_conn = null;
}
protected void checkIsolationLevel(Connection conn) throws SQLException {
PreparedStatement pstmt = conn.prepareStatement("SELECT @@global.tx_isolation, @@session.tx_isolation;");
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
s_logger.info("global isolation = " + rs.getString(1));
s_logger.info("session isolation = " + rs.getString(2));
}
}
protected Connection getConnection(String key, boolean test) {
try {
if (_conn != null) {
return _conn;
}
_conn = Transaction.getStandaloneConnection();
if (_previousIsolation == Connection.TRANSACTION_NONE) {
_previousIsolation = _conn.getTransactionIsolation();
_conn.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
if (!test && !_conn.getAutoCommit()) {
_conn.setAutoCommit(false);
}
}
return _conn;
} catch (SQLException e) {
try {
_conn.rollback();
} catch (SQLException e1) {
}
throw new CloudRuntimeException("Unable to acquire db connection for locking " + key, e);
}
}
public boolean acquire(String key, int timeInSeconds) {
Pair<Lock, Integer> memLock = null;
boolean acquiredDbLock = false;
boolean acquiredMemLock = false;
try {
synchronized(s_memLocks) {
memLock = s_memLocks.get(key);
if (memLock == null) {
Lock l = new ReentrantLock(true);
memLock = new Pair<Lock, Integer>(l, 0);
s_memLocks.put(key, memLock);
}
memLock.second(memLock.second() + 1);
}
if (!memLock.first().tryLock(timeInSeconds, TimeUnit.SECONDS)) {
return false;
}
acquiredMemLock = true;
Ternary<Savepoint, Integer, Long> lock = _locks.get(key);
if (lock != null) {
lock.second(lock.second() + 1);
if (s_logger.isTraceEnabled()) {
s_logger.trace("Lock: Reacquiring " + key + " Count: " + lock.second());
}
acquiredDbLock = true;
return true;
}
long startTime = InaccurateClock.getTime();
while ((InaccurateClock.getTime() - startTime) < (timeInSeconds * 1000)) {
if (isLocked(key)) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
} else {
acquiredDbLock = doAcquire(key);
if (acquiredDbLock) {
return true;
}
}
}
if (s_logger.isTraceEnabled()) {
s_logger.trace("Lock: Timed out on acquiring lock " + key);
}
return false;
} catch (InterruptedException e) {
s_logger.debug("Interrupted while trying to acquire " + key);
return false;
} finally {
if (!acquiredMemLock || !acquiredDbLock) {
synchronized(s_memLocks) {
if (memLock.second(memLock.second() - 1) <= 0) {
s_memLocks.remove(key);
}
}
}
if (acquiredMemLock && !acquiredDbLock) {
memLock.first().unlock();
}
}
}
protected boolean doAcquire(String key) {
Connection conn = getConnection(key, true);
PreparedStatement pstmt = null;
Savepoint sp = null;
try {
sp = conn.setSavepoint(key);
} catch (SQLException e) {
s_logger.warn("Unable to set save point " + key);
return false;
}
try {
long startTime = InaccurateClock.getTime();
try {
pstmt = conn.prepareStatement(ACQUIRE_SQL);
pstmt.setString(1, key);
pstmt.setString(2, s_macAddress);
pstmt.setString(3, s_ipAddress);
pstmt.setString(4, Thread.currentThread().getName());
String exceptionMessage = null;
int rows = pstmt.executeUpdate();
if (rows == 1) {
if (s_logger.isTraceEnabled()) {
s_logger.trace("Lock: lock acquired for " + key);
}
Ternary<Savepoint, Integer, Long> lock = new Ternary<Savepoint, Integer, Long>(sp, 1, InaccurateClock.getTime());
_locks.put(key, lock);
return true;
}
} catch(SQLException e) {
s_logger.warn("Lock: Retrying lock " + key + ". Waited " + (InaccurateClock.getTime() - startTime), e);
}
conn.rollback(sp);
s_logger.trace("Lock: Unable to acquire DB lock " + key);
} catch (SQLException e) {
s_logger.warn("Lock: Unable to acquire db connection for locking " + key, e);
} finally {
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
}
}
}
return false;
}
public boolean isLocked(String key) {
Connection conn = getConnection(key, false);
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
pstmt = conn.prepareStatement(INQUIRE_SQL);
pstmt.setString(1, key);
rs = pstmt.executeQuery();
return rs.next();
} catch (SQLException e) {
s_logger.warn("SQL exception " + e.getMessage(), e);
throw new CloudRuntimeException("SQL Exception on inquiry", e);
} finally {
try {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
} catch (SQLException e) {
s_logger.warn("Unexpected SQL exception " + e.getMessage(), e);
}
}
}
public void clear() {
if (_locks.size() == 0) {
return;
}
Set<String> keys = new HashSet<String>(_locks.keySet());
//
// disable assertion, when assert support is enabled, it throws an exception
// which eventually eats the following on important messages for diagnostic
//
// assert (false) : "Who acquired locks but didn't release them? " + keys.toArray(new String[keys.size()]);
for (String key : keys) {
s_logger.warn("Lock: This is not good guys! Automatically releasing lock: " + key);
release(key);
}
_locks.clear();
}
public boolean release(String key) {
boolean validLock = false;
try {
assert _locks.size() > 0 : "There are no locks here. Why are you trying to release " + key;
Ternary<Savepoint, Integer, Long> lock = _locks.get(key);
if (lock != null) {
validLock = true;
if (lock.second() > 1) {
lock.second(lock.second() - 1);
if (s_logger.isTraceEnabled()) {
s_logger.trace("Lock: Releasing " + key + " but not in DB " + lock.second());
}
return false;
}
if (s_logger.isDebugEnabled() && !_locks.keySet().iterator().next().equals(key)) {
s_logger.trace("Lock: Releasing out of order for " + key);
}
_locks.remove(key);
if (s_logger.isTraceEnabled()) {
s_logger.trace("Lock: Releasing " + key + " after " + (InaccurateClock.getTime() - lock.third()));
}
Connection conn = getConnection(key, true);
conn.rollback(lock.first());
} else {
s_logger.warn("Merovingian.release() is called against key " + key + " but the lock of this key does not exist!");
}
if (_locks.size() == 0) {
closeConnection();
}
} catch (SQLException e) {
s_logger.warn("unable to rollback for " + key);
} finally {
synchronized(s_memLocks) {
Pair<Lock, Integer> memLock = s_memLocks.get(key);
if(memLock != null) {
memLock.second(memLock.second() - 1);
if (memLock.second() <= 0) {
s_memLocks.remove(key);
}
if(validLock)
memLock.first().unlock();
} else {
throw new CloudRuntimeException("Merovingian.release() is called for key " + key + ", but its memory lock no longer exist! This is not good, guys");
}
}
}
return true;
}
public void closeConnection() {
try {
if (_conn == null) {
_previousIsolation = Connection.TRANSACTION_NONE;
return;
}
if (_previousIsolation != Connection.TRANSACTION_NONE) {
_conn.setTransactionIsolation(_previousIsolation);
}
try { // rollback just in case but really there shoul be nothing.
_conn.rollback();
} catch (SQLException e) {
}
_conn.setAutoCommit(true);
_previousIsolation = Connection.TRANSACTION_NONE;
_conn.close();
_conn = null;
} catch (SQLException e) {
s_logger.warn("Unexpected SQL exception " + e.getMessage(), e);
}
}
}

View File

@ -1,27 +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 NextWhere<T, K> extends FirstWhere<T, K> {
NextWhere<T, K> and();
NextWhere<T, K> or();
NextWhere<T, K> not();
@Override
void done();
}

View File

@ -1,21 +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 On<S, J, T> {
}

View File

@ -1,21 +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 class ParentWhere<T> {
}

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<GenericDaoBase<?,?>, 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<GenericDaoBase<?,?>, Object>>(clazzes.length);
for (Class<?> clazz : clazzes) {
GenericDaoBase<?,?> dao = GenericDaoBase.getDao(clazz);
Enhancer searchEnhancer = new Enhancer();
searchEnhancer.setSuperclass(clazz);
searchEnhancer.setCallback(this);
Object entity = searchEnhancer.create();
_entities.put(clazz, new Pair<GenericDaoBase<?, ?>, 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<GenericDaoBase<?,?>, Object>>(1);
GenericDaoBase<?,?> dao = GenericDaoBase.getDao(entityClass);
Enhancer searchEnhancer = new Enhancer();
searchEnhancer.setSuperclass(entityClass);
searchEnhancer.setCallback(this);
Object entity = searchEnhancer.create();
_entities.put(entityClass, new Pair<GenericDaoBase<?, ?>, 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(GenericDaoBase<?, ?> 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<GenericDaoBase<?,?>, Object> daoInfo = _entities.get(entityClass);
assert (daoInfo != null) : "You need to specify " + entityClass + " as one of the entities in the Query";
GenericDaoBase<?,?> 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

@ -53,24 +53,24 @@ public class SearchCriteria<K> {
AND(" AND ", 0),
OR(" OR ", 0),
NOT(" NOT ", 0);
private final String op;
int params;
Op(String op, int params) {
this.op = op;
this.params = params;
}
@Override
public String toString() {
public String toString() {
return op;
}
public int getParams() {
return params;
}
}
public enum Func {
NATIVE("@", 1),
MAX("MAX(@)", 1),
@ -80,25 +80,25 @@ public class SearchCriteria<K> {
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;
}
}
public enum SelectType {
Fields,
Entity,
@ -117,46 +117,29 @@ public class SearchCriteria<K> {
private final List<Object> _groupByValues;
private final Class<K> _resultType;
private final SelectType _selectType;
private final QueryBuilder<?, K> _builder;
protected SearchCriteria(QueryBuilder<?, K> builder) {
_builder = builder;
_attrs = null;
_conditions = null;
_additionals = null;
_counter = 0;
_joins = null;
_selects = null;
_groupBy = null;
_groupByValues = null;
_resultType = null;
_selectType = null;
}
protected SearchCriteria(final Map<String, Attribute> attrs, ArrayList<GenericSearchBuilder.Condition> conditions, ArrayList<Select> selects, SelectType selectType, Class<K> resultType, HashMap<String, Object[]> params) {
this._attrs = attrs;
this._conditions = conditions;
this._selects = selects;
this._selectType = selectType;
this._resultType = resultType;
this._params = params;
this._builder = null;
this._additionals = new ArrayList<Condition>();
this._counter = 0;
this._joins = null;
this._groupBy = null;
this._groupByValues = null;
this._attrs = attrs;
this._conditions = conditions;
this._selects = selects;
this._selectType = selectType;
this._resultType = resultType;
this._params = params;
this._additionals = new ArrayList<Condition>();
this._counter = 0;
this._joins = null;
this._groupBy = null;
this._groupByValues = null;
}
protected SearchCriteria(GenericSearchBuilder<?, K> sb) {
this._builder = null;
this._attrs = sb._attrs;
this._attrs = sb._attrs;
this._conditions = sb._conditions;
this._additionals = new ArrayList<Condition>();
this._counter = 0;
this._joins = null;
if (sb._joins != null) {
_joins = new HashMap<String, JoinBuilder<SearchCriteria<?>>>(sb._joins.size());
_joins = new HashMap<String, JoinBuilder<SearchCriteria<?>>>(sb._joins.size());
for (Map.Entry<String, JoinBuilder<GenericSearchBuilder<?, ?>>> entry : sb._joins.entrySet()) {
JoinBuilder<GenericSearchBuilder<?, ?>> value = entry.getValue();
_joins.put(entry.getKey(), new JoinBuilder<SearchCriteria<?>>(value.getT().create(),value.getFirstAttribute(), value.getSecondAttribute(), value.getType()));
@ -172,16 +155,16 @@ public class SearchCriteria<K> {
_resultType = sb._resultType;
_selectType = sb._selectType;
}
public SelectType getSelectType() {
return _selectType;
}
public void getSelect(StringBuilder str, int insertAt) {
if (_selects == null || _selects.size() == 0) {
return;
}
for (Select select : _selects) {
String func = select.func.toString() + ",";
if (select.attr == null) {
@ -195,118 +178,118 @@ public class SearchCriteria<K> {
break;
}
}
str.delete(insertAt - 1, insertAt);
}
public List<Field> getSelectFields() {
List<Field> fields = new ArrayList<Field>(_selects.size());
for (Select select : _selects) {
fields.add(select.field);
}
return fields;
}
public void setParameters(String conditionName, Object... params) {
assert _conditions.contains(new Condition(conditionName)) || _additionals.contains(new Condition(conditionName)) : "Couldn't find " + conditionName;
_params.put(conditionName, params);
}
public boolean isSelectAll() {
return _selects == null || _selects.size() == 0;
}
protected JoinBuilder<SearchCriteria<?>> findJoin(Map<String, JoinBuilder<SearchCriteria<?>>> jbmap, String joinName) {
JoinBuilder<SearchCriteria<?>> jb = jbmap.get(joinName);
if (jb != null) {
return jb;
}
for (JoinBuilder<SearchCriteria<?>> j2 : _joins.values()) {
SearchCriteria<?> sc = j2.getT();
jb = findJoin(sc._joins, joinName);
if (jb != null) {
return jb;
}
}
assert (false) : "Unable to find a join by the name " + joinName;
return null;
JoinBuilder<SearchCriteria<?>> jb = jbmap.get(joinName);
if (jb != null) {
return jb;
}
for (JoinBuilder<SearchCriteria<?>> j2 : _joins.values()) {
SearchCriteria<?> sc = j2.getT();
jb = findJoin(sc._joins, joinName);
if (jb != null) {
return jb;
}
}
assert (false) : "Unable to find a join by the name " + joinName;
return null;
}
public void setJoinParameters(String joinName, String conditionName, Object... params) {
JoinBuilder<SearchCriteria<?>> join = findJoin(_joins, joinName);
JoinBuilder<SearchCriteria<?>> join = findJoin(_joins, joinName);
assert (join != null) : "Incorrect join name specified: " + joinName;
join.getT().setParameters(conditionName, params);
}
public void addJoinAnd(String joinName, String field, Op op, Object... values) {
JoinBuilder<SearchCriteria<?>> join = _joins.get(joinName);
JoinBuilder<SearchCriteria<?>> join = _joins.get(joinName);
assert (join != null) : "Incorrect join name specified: " + joinName;
join.getT().addAnd(field, op, values);
}
public void addJoinOr(String joinName, String field, Op op, Object... values) {
JoinBuilder<SearchCriteria<?>> join = _joins.get(joinName);
assert (join != null) : "Incorrect join name specified: " + joinName;
join.getT().addOr(field, op, values);
}
public SearchCriteria<?> getJoin(String joinName) {
return _joins.get(joinName).getT();
return _joins.get(joinName).getT();
}
public Pair<GroupBy<?, ?>, List<Object>> getGroupBy() {
return _groupBy == null ? null : new Pair<GroupBy<?, ?>, List<Object>>(_groupBy, _groupByValues);
}
public void setGroupByValues(Object... values) {
for (Object value : values) {
_groupByValues.add(value);
}
}
public Class<K> getResultType() {
return _resultType;
}
public void addAnd(String field, Op op, Object... values) {
String name = Integer.toString(_counter++);
addCondition(name, " AND ", field, op);
setParameters(name, values);
}
public void addAnd(Attribute attr, Op op, Object... values) {
String name = Integer.toString(_counter++);
addCondition(name, " AND ", attr, op);
setParameters(name, values);
}
public void addOr(String field, Op op, Object... values) {
String name = Integer.toString(_counter++);
addCondition(name, " OR ", field, op);
setParameters(name, values);
}
public void addOr(Attribute attr, Op op, Object... values) {
String name = Integer.toString(_counter++);
addCondition(name, " OR ", attr, op);
setParameters(name, values);
}
protected void addCondition(String conditionName, String cond, String fieldName, Op op) {
Attribute attr = _attrs.get(fieldName);
assert attr != null : "Unable to find field: " + fieldName;
addCondition(conditionName, cond, attr, op);
Attribute attr = _attrs.get(fieldName);
assert attr != null : "Unable to find field: " + fieldName;
addCondition(conditionName, cond, attr, op);
}
protected void addCondition(String conditionName, String cond, Attribute attr, Op op) {
Condition condition = new Condition(conditionName, /*(_conditions.size() + _additionals.size()) == 0 ? "" : */cond, attr, op);
_additionals.add(condition);
}
public String getWhereClause() {
StringBuilder sql = new StringBuilder();
int i = 0;
@ -316,17 +299,17 @@ public class SearchCriteria<K> {
condition.toSql(sql, params, i++);
}
}
for (Condition condition : _additionals) {
Object[] params = _params.get(condition.name);
if ((condition.op.params == 0) || (params != null)) {
condition.toSql(sql, params, i++);
}
}
return sql.toString();
}
public List<Pair<Attribute, Object>> getValues() {
ArrayList<Pair<Attribute, Object>> params = new ArrayList<Pair<Attribute, Object>>(_params.size());
for (Condition condition : _conditions) {
@ -335,40 +318,40 @@ public class SearchCriteria<K> {
getParams(params, condition, objs);
}
}
for (Condition condition : _additionals) {
Object[] objs = _params.get(condition.name);
if ((condition.op.params == 0) || (objs != null)) {
getParams(params, condition, objs);
}
}
return params;
}
public Collection<JoinBuilder<SearchCriteria<?>>> getJoins() {
return _joins != null ? _joins.values() : null;
}
private void getParams(ArrayList<Pair<Attribute, Object>> params, Condition condition, Object[] objs) {
if (condition.op == Op.SC) {
assert (objs != null && objs.length > 0) : " Where's your search criteria object? " + condition.name;
params.addAll(((SearchCriteria<?>)objs[0]).getValues());
return;
}
if (objs != null && objs.length > 0) {
for (Object obj : objs) {
if ((condition.op != Op.EQ && condition.op != Op.NEQ) || (obj != null)) {
params.add(new Pair<Attribute, Object>(condition.attr, obj));
params.add(new Pair<Attribute, Object>(condition.attr, obj));
}
}
}
}
public Pair<String, ArrayList<Object>> toSql() {
StringBuilder sql = new StringBuilder();
return new Pair<String, ArrayList<Object>>(sql.toString(), null);
}
}

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,28 +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;
/**
* is defined.
*/
public interface SelectQueryBuilder<T, S> {
Select<T, S> selectColumn(Object column);
T entity();
FirstWhere<T, S> where();
}

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

@ -1,3 +1,2 @@
#Mon Aug 27 14:48:16 PDT 2012
eclipse.preferences.version=1
encoding/<project>=UTF-8