You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by ed...@apache.org on 2013/01/15 03:04:55 UTC
[2/44] Revert "Merge remote-tracking branch 'origin/javelin' into
javelin"
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/110465b5/utils/src/com/cloud/utils/crypt/EncryptionSecretKeySender.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/crypt/EncryptionSecretKeySender.java b/utils/src/com/cloud/utils/crypt/EncryptionSecretKeySender.java
index 3904437..2dc865c 100755
--- a/utils/src/com/cloud/utils/crypt/EncryptionSecretKeySender.java
+++ b/utils/src/com/cloud/utils/crypt/EncryptionSecretKeySender.java
@@ -16,8 +16,6 @@
// under the License.
package com.cloud.utils.crypt;
-import java.io.BufferedReader;
-import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
@@ -26,39 +24,37 @@ import com.cloud.utils.NumbersUtil;
public class EncryptionSecretKeySender {
- public static void main(String args[]){
- try {
+ public static void main(String args[]){
+ try {
- // Create a socket to the host
- String hostname = "localhost";
- int port = 8097;
-
- if(args.length == 2){
- hostname = args[0];
- port = NumbersUtil.parseInt(args[1], port);
- }
-
-
- InetAddress addr = InetAddress.getByName(hostname);
- Socket socket = new Socket(addr, port);
- PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
- BufferedReader in = new BufferedReader(new InputStreamReader(
- socket.getInputStream()));
- java.io.BufferedReader stdin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
- String validationWord = "cloudnine";
- String validationInput = "";
- while(!validationWord.equals(validationInput)){
- System.out.print("Enter Validation Word:");
- validationInput = stdin.readLine();
- System.out.println();
- }
- System.out.print("Enter Secret Key:");
- String input = stdin.readLine();
- if (input != null) {
- out.println(input);
- }
- } catch (Exception e) {
- System.out.print("Exception while sending secret key "+e);
- }
- }
+ // Create a socket to the host
+ String hostname = "localhost";
+ int port = 8097;
+
+ if(args.length == 2){
+ hostname = args[0];
+ port = NumbersUtil.parseInt(args[1], port);
+ }
+
+
+ InetAddress addr = InetAddress.getByName(hostname);
+ Socket socket = new Socket(addr, port);
+ PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
+ java.io.BufferedReader stdin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
+ String validationWord = "cloudnine";
+ String validationInput = "";
+ while(!validationWord.equals(validationInput)){
+ System.out.print("Enter Validation Word:");
+ validationInput = stdin.readLine();
+ System.out.println();
+ }
+ System.out.print("Enter Secret Key:");
+ String input = stdin.readLine();
+ if (input != null) {
+ out.println(input);
+ }
+ } catch (Exception e) {
+ System.out.print("Exception while sending secret key "+e);
+ }
+ }
}
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/110465b5/utils/src/com/cloud/utils/db/GenericDao.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/db/GenericDao.java b/utils/src/com/cloud/utils/db/GenericDao.java
index 2fae1af..15d04b7 100755
--- a/utils/src/com/cloud/utils/db/GenericDao.java
+++ b/utils/src/com/cloud/utils/db/GenericDao.java
@@ -56,7 +56,7 @@ public interface GenericDao<T, ID extends Serializable> {
T findById(ID id, boolean fresh);
// Finds one unique VO using uuid
- T findByUuid(ID uuid);
+ T findByUuid(String uuid);
/**
* @return VO object ready to be used for update. It won't have any fields filled in.
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/110465b5/utils/src/com/cloud/utils/db/GenericDaoBase.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/db/GenericDaoBase.java b/utils/src/com/cloud/utils/db/GenericDaoBase.java
index 92e9e1c..880e9de 100755
--- a/utils/src/com/cloud/utils/db/GenericDaoBase.java
+++ b/utils/src/com/cloud/utils/db/GenericDaoBase.java
@@ -915,7 +915,7 @@ public abstract class GenericDaoBase<T, ID extends Serializable> implements Gene
@Override @DB(txn=false)
@SuppressWarnings("unchecked")
- public T findByUuid(final ID uuid) {
+ public T findByUuid(final String uuid) {
SearchCriteria<T> sc = createSearchCriteria();
sc.addAnd("uuid", SearchCriteria.Op.EQ, uuid);
return findOneBy(sc);
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/110465b5/utils/src/com/cloud/utils/exception/RuntimeCloudException.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/exception/RuntimeCloudException.java b/utils/src/com/cloud/utils/exception/RuntimeCloudException.java
index 2334696..a2de516 100644
--- a/utils/src/com/cloud/utils/exception/RuntimeCloudException.java
+++ b/utils/src/com/cloud/utils/exception/RuntimeCloudException.java
@@ -16,10 +16,10 @@
// under the License.
package com.cloud.utils.exception;
-import com.cloud.utils.AnnotationHelper;
-import com.cloud.utils.IdentityProxy;
import java.util.ArrayList;
+import com.cloud.utils.AnnotationHelper;
+
/**
* by the API response serializer. Any exceptions that are thrown by
* class, which extends Exception instead of RuntimeException like this
@@ -28,20 +28,22 @@ import java.util.ArrayList;
public class RuntimeCloudException extends RuntimeException {
- // This holds a list of uuids and their names. Add uuid:fieldname pairs
- protected ArrayList<String> idList = new ArrayList<String>();
+ private static final long serialVersionUID = 1783478684819198850L;
- protected int csErrorCode;
+ // This holds a list of uuids and their names. Add uuid:fieldname pairs
+ protected ArrayList<String> idList = new ArrayList<String>();
- public void addProxyObject(String uuid) {
- idList.add(uuid);
- return;
- }
+ protected int csErrorCode;
- public RuntimeCloudException(String message) {
- super(message);
- setCSErrorCode(CSExceptionErrorCode.getCSErrCode(this.getClass().getName()));
- }
+ public void addProxyObject(String uuid) {
+ idList.add(uuid);
+ return;
+ }
+
+ public RuntimeCloudException(String message) {
+ super(message);
+ setCSErrorCode(CSExceptionErrorCode.getCSErrCode(this.getClass().getName()));
+ }
public RuntimeCloudException(String message, Throwable cause) {
super(message, cause);
@@ -49,28 +51,28 @@ public class RuntimeCloudException extends RuntimeException {
}
public void addProxyObject(Object voObj, Long id, String idFieldName) {
- // Get the VO object's table name.
- String tablename = AnnotationHelper.getTableName(voObj);
- if (tablename != null) {
- addProxyObject(tablename, id, idFieldName);
- }
- return;
+ // Get the VO object's table name.
+ String tablename = AnnotationHelper.getTableName(voObj);
+ if (tablename != null) {
+ addProxyObject(tablename, id, idFieldName);
+ }
+ return;
}
- public RuntimeCloudException() {
- super();
- setCSErrorCode(CSExceptionErrorCode.getCSErrCode(this.getClass().getName()));
- }
+ public RuntimeCloudException() {
+ super();
+ setCSErrorCode(CSExceptionErrorCode.getCSErrCode(this.getClass().getName()));
+ }
- public ArrayList<String> getIdProxyList() {
- return idList;
- }
+ public ArrayList<String> getIdProxyList() {
+ return idList;
+ }
- public void setCSErrorCode(int cserrcode) {
- this.csErrorCode = cserrcode;
- }
+ public void setCSErrorCode(int cserrcode) {
+ this.csErrorCode = cserrcode;
+ }
- public int getCSErrorCode() {
- return this.csErrorCode;
- }
+ public int getCSErrorCode() {
+ return this.csErrorCode;
+ }
}
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/110465b5/utils/src/com/cloud/utils/fsm/FiniteState2.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/fsm/FiniteState2.java b/utils/src/com/cloud/utils/fsm/FiniteState2.java
index 585521d..0147ba4 100755
--- a/utils/src/com/cloud/utils/fsm/FiniteState2.java
+++ b/utils/src/com/cloud/utils/fsm/FiniteState2.java
@@ -22,7 +22,7 @@ import java.util.Set;
public interface FiniteState2<T, E> {
- StateMachine2<T, ? extends ChangeEvent, ? extends StateObject> getStateMachine();
+ StateMachine2<T, ? extends ChangeEvent, ? extends StateObject<?>> getStateMachine();
T getNextState(ChangeEvent e) throws NoTransitionException;
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/110465b5/utils/src/com/cloud/utils/log/CglibThrowableRenderer.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/log/CglibThrowableRenderer.java b/utils/src/com/cloud/utils/log/CglibThrowableRenderer.java
index 06cd0c3..83c1dce 100644
--- a/utils/src/com/cloud/utils/log/CglibThrowableRenderer.java
+++ b/utils/src/com/cloud/utils/log/CglibThrowableRenderer.java
@@ -17,7 +17,6 @@
package com.cloud.utils.log;
import java.io.PrintWriter;
-import java.lang.reflect.Method;
import java.util.ArrayList;
import org.apache.log4j.spi.ThrowableRenderer;
@@ -36,25 +35,10 @@ import org.apache.log4j.spi.ThrowableRenderer;
*/
public class CglibThrowableRenderer implements ThrowableRenderer {
/**
- * Throwable.getStackTrace() method.
- */
- private Method getStackTraceMethod;
- /**
- * StackTraceElement.getClassName() method.
- */
- private Method getClassNameMethod;
-
- /**
* Construct new instance.
*/
public CglibThrowableRenderer() {
- try {
- Class[] noArgs = null;
- getStackTraceMethod = Throwable.class.getMethod("getStackTrace", noArgs);
- Class ste = Class.forName("java.lang.StackTraceElement");
- getClassNameMethod = ste.getMethod("getClassName", noArgs);
- } catch (Exception ex) {
- }
+ super();
}
@Override
@@ -94,24 +78,4 @@ public class CglibThrowableRenderer implements ThrowableRenderer {
return null;
}
}
-
- /**
- * Find class given class name.
- *
- * @param className class name, may not be null.
- * @return class, will not be null.
- * @throws ClassNotFoundException thrown if class can not be found.
- */
- private Class findClass(final String className) throws ClassNotFoundException {
- try {
- return Thread.currentThread().getContextClassLoader().loadClass(className);
- } catch (ClassNotFoundException e) {
- try {
- return Class.forName(className);
- } catch (ClassNotFoundException e1) {
- return getClass().getClassLoader().loadClass(className);
- }
- }
- }
-
}
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/110465b5/utils/src/com/cloud/utils/net/MacAddress.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/net/MacAddress.java b/utils/src/com/cloud/utils/net/MacAddress.java
index f81127c..15350c8 100755
--- a/utils/src/com/cloud/utils/net/MacAddress.java
+++ b/utils/src/com/cloud/utils/net/MacAddress.java
@@ -60,16 +60,16 @@ public class MacAddress {
StringBuilder buff = new StringBuilder();
Formatter formatter = new Formatter(buff);
formatter.format("%02x%s%02x%s%02x%s%02x%s%02x%s%02x",
- _addr >> 40 & 0xff, separator,
- _addr >> 32 & 0xff, separator,
- _addr >> 24 & 0xff, separator,
- _addr >> 16 & 0xff, separator,
- _addr >> 8 & 0xff, separator,
- _addr & 0xff);
+ _addr >> 40 & 0xff, separator,
+ _addr >> 32 & 0xff, separator,
+ _addr >> 24 & 0xff, separator,
+ _addr >> 16 & 0xff, separator,
+ _addr >> 8 & 0xff, separator,
+ _addr & 0xff);
return buff.toString();
-
+
/*
-
+
String str = Long.toHexString(_addr);
for (int i = str.length() - 1; i >= 0; i--) {
@@ -79,11 +79,11 @@ public class MacAddress {
}
}
return buff.reverse().toString();
- */
+ */
}
@Override
- public String toString() {
+ public String toString() {
return toString(":");
}
@@ -102,7 +102,7 @@ public class MacAddress {
} else if (osname.startsWith("Solaris") || osname.startsWith("SunOS")) {
// Solaris code must appear before the generic code
String hostName = MacAddress.getFirstLineOfCommand(new String[] { "uname",
- "-n"});
+ "-n"});
if (hostName != null) {
p = Runtime.getRuntime().exec(new String[] { "/usr/sbin/arp", hostName}, null);
}
@@ -163,7 +163,7 @@ public class MacAddress {
clockSeqAndNode |= (long) (Math.random() * 0x7FFFFFFF);
}
}
-
+
s_address = new MacAddress(clockSeqAndNode);
}
@@ -262,9 +262,6 @@ public class MacAddress {
System.out.println("addr in char is " + addr.toString(":"));
}
-private static final char[] DIGITS = { '0', '1', '2', '3', '4', '5', '6',
- '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
-
/**
* Parses a <code>long</code> from a hex encoded number. This method will skip
* all characters that are not 0-9 and a-f (the String is lower cased first).
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/110465b5/utils/src/com/cloud/utils/net/NetUtils.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/net/NetUtils.java b/utils/src/com/cloud/utils/net/NetUtils.java
index c456cdc..005fe23 100755
--- a/utils/src/com/cloud/utils/net/NetUtils.java
+++ b/utils/src/com/cloud/utils/net/NetUtils.java
@@ -17,15 +17,12 @@
package com.cloud.utils.net;
import java.io.BufferedReader;
-import java.io.File;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
-import java.net.URISyntaxException;
-import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Formatter;
@@ -39,7 +36,6 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;
-import org.apache.log4j.xml.DOMConfigurator;
import com.cloud.utils.IteratorUtil;
import com.cloud.utils.Pair;
@@ -681,7 +677,7 @@ public class NetUtils {
if (avoid.size() >= range) {
return -1;
}
-
+
//Reduce the range by the size of the avoid set
//e.g., cidr = 192.168.10.0, size = /24, avoid = 192.168.10.1, 192.168.10.20, 192.168.10.254
// range = 2^8 - 1 - 3 = 252
@@ -690,9 +686,9 @@ public class NetUtils {
long ip = startIp + next;
for (Long avoidable : avoid) {
if (ip >= avoidable) {
- ip++;
+ ip++;
} else {
- break;
+ break;
}
}
@@ -796,7 +792,7 @@ public class NetUtils {
long shift = 32 - cidrBLong[1];
return ((cidrALong[0] >> shift) == (cidrBLong[0] >> shift));
}
-
+
public static Long[] cidrToLong(String cidr) {
if (cidr == null || cidr.isEmpty()) {
return null;
@@ -960,26 +956,6 @@ public class NetUtils {
return Integer.toString(portRange[0]) + ":" + Integer.toString(portRange[1]);
}
- // test only
- private static void configLog4j() {
- URL configUrl = System.class.getResource("/conf/log4j-cloud.xml");
- if (configUrl != null) {
- System.out.println("Configure log4j using log4j-cloud.xml");
-
- try {
- File file = new File(configUrl.toURI());
-
- System.out.println("Log4j configuration from : " + file.getAbsolutePath());
- DOMConfigurator.configureAndWatch(file.getAbsolutePath(), 10000);
- } catch (URISyntaxException e) {
- System.out.println("Unable to convert log4j configuration Url to URI");
- }
- // DOMConfigurator.configure(configUrl);
- } else {
- System.out.println("Configure log4j with default properties");
- }
- }
-
public static boolean verifyDomainNameLabel(String hostName, boolean isHostName) {
// must be between 1 and 63 characters long and may contain only the ASCII letters 'a' through 'z' (in a
@@ -1068,7 +1044,7 @@ public class NetUtils {
return true;
}
-
+
public static boolean isNetworksOverlap(String cidrA, String cidrB) {
Long[] cidrALong = cidrToLong(cidrA);
Long[] cidrBLong = cidrToLong(cidrB);
@@ -1122,7 +1098,7 @@ public class NetUtils {
}
return true;
}
-
+
public static boolean validateIcmpType(long icmpType) {
//Source - http://www.erg.abdn.ac.uk/~gorry/course/inet-pages/icmp-code.html
if(!(icmpType >=0 && icmpType <=255)) {
@@ -1131,15 +1107,15 @@ public class NetUtils {
}
return true;
}
-
+
public static boolean validateIcmpCode(long icmpCode) {
-
+
//Source - http://www.erg.abdn.ac.uk/~gorry/course/inet-pages/icmp-code.html
if(!(icmpCode >=0 && icmpCode <=15)) {
s_logger.warn("Icmp code should be within 0-15 range");
return false;
}
-
+
return true;
}
}
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/110465b5/utils/src/com/cloud/utils/net/NfsUtils.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/net/NfsUtils.java b/utils/src/com/cloud/utils/net/NfsUtils.java
index 7318383..19ff055 100644
--- a/utils/src/com/cloud/utils/net/NfsUtils.java
+++ b/utils/src/com/cloud/utils/net/NfsUtils.java
@@ -21,18 +21,17 @@ import java.net.URI;
import java.net.URISyntaxException;
public class NfsUtils {
-
+
public static String url2Mount(String urlStr) throws URISyntaxException {
URI url;
url = new URI(urlStr);
- int port = url.getPort();
return url.getHost() + ":" + url.getPath();
}
-
+
public static String uri2Mount(URI uri) {
return uri.getHost() + ":" + uri.getPath();
}
-
+
public static String url2PathSafeString(String urlStr) {
String safe = urlStr.replace(File.separatorChar, '-');
safe = safe.replace("?", "");
@@ -41,13 +40,13 @@ public class NfsUtils {
safe = safe.replace("/", "");
return safe;
}
-
+
public static String getHostPart(String nfsPath) {
- String toks[] = nfsPath.split(":");
- if (toks != null && toks.length == 2) {
- return toks[0];
- }
- return null;
+ String toks[] = nfsPath.split(":");
+ if (toks != null && toks.length == 2) {
+ return toks[0];
+ }
+ return null;
}
}
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/110465b5/utils/src/com/cloud/utils/nio/HandlerFactory.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/nio/HandlerFactory.java b/utils/src/com/cloud/utils/nio/HandlerFactory.java
index 0dcc83f..9cf218d 100755
--- a/utils/src/com/cloud/utils/nio/HandlerFactory.java
+++ b/utils/src/com/cloud/utils/nio/HandlerFactory.java
@@ -16,7 +16,6 @@
// under the License.
package com.cloud.utils.nio;
-import java.util.List;
/**
* WorkerFactory creates and selects workers.
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/110465b5/utils/src/com/cloud/utils/nio/Link.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/nio/Link.java b/utils/src/com/cloud/utils/nio/Link.java
index 3e3da6c..4b041f5 100755
--- a/utils/src/com/cloud/utils/nio/Link.java
+++ b/utils/src/com/cloud/utils/nio/Link.java
@@ -16,18 +16,15 @@
// under the License.
package com.cloud.utils.nio;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
-import java.nio.channels.Channels;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
-import java.nio.channels.WritableByteChannel;
import java.security.KeyStore;
import java.util.concurrent.ConcurrentLinkedQueue;
@@ -35,10 +32,10 @@ import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
+import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
-import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import org.apache.log4j.Logger;
@@ -48,7 +45,7 @@ import com.cloud.utils.PropertiesUtil;
*/
public class Link {
private static final Logger s_logger = Logger.getLogger(Link.class);
-
+
private final InetSocketAddress _addr;
private final NioConnection _connection;
private SelectionKey _key;
@@ -58,7 +55,7 @@ public class Link {
private Object _attach;
private boolean _readHeader;
private boolean _gotFollowingPacket;
-
+
private SSLEngine _sslEngine;
public Link(InetSocketAddress addr, NioConnection connection) {
@@ -71,23 +68,23 @@ public class Link {
_readHeader = true;
_gotFollowingPacket = false;
}
-
+
public Link (Link link) {
this(link._addr, link._connection);
}
-
+
public Object attachment() {
return _attach;
}
-
+
public void attach(Object attach) {
_attach = attach;
}
-
+
public void setKey(SelectionKey key) {
_key = key;
}
-
+
public void setSSLEngine(SSLEngine sslEngine) {
_sslEngine = sslEngine;
}
@@ -105,19 +102,19 @@ public class Link {
synchronized(buff) {
buff.clear();
buff.limit(4);
-
+
while (buff.hasRemaining()) {
if (ch.read(buff) == -1) {
throw new IOException("Connection closed with -1 on reading size.");
}
}
-
+
buff.flip();
-
+
int length = buff.getInt();
ByteArrayOutputStream output = new ByteArrayOutputStream(length);
WritableByteChannel outCh = Channels.newChannel(output);
-
+
int count = 0;
while (count < length) {
buff.clear();
@@ -129,19 +126,19 @@ public class Link {
buff.flip();
outCh.write(buff);
}
-
+
return output.toByteArray();
}
}
- */
-
+ */
+
private static void doWrite(SocketChannel ch, ByteBuffer[] buffers, SSLEngine sslEngine) throws IOException {
SSLSession sslSession = sslEngine.getSession();
ByteBuffer pkgBuf = ByteBuffer.allocate(sslSession.getPacketBufferSize() + 40);
SSLEngineResult engResult;
ByteBuffer headBuf = ByteBuffer.allocate(4);
-
+
int totalLen = 0;
for (ByteBuffer buffer : buffers) {
totalLen += buffer.limit();
@@ -157,7 +154,7 @@ public class Link {
engResult.getStatus() != SSLEngineResult.Status.OK) {
throw new IOException("SSL: SSLEngine return bad result! " + engResult);
}
-
+
processedLen = 0;
for (ByteBuffer buffer : buffers) {
processedLen += buffer.position();
@@ -189,7 +186,7 @@ public class Link {
}
}
}
-
+
/**
* write method to write to a socket. This method writes to completion so
* it doesn't follow the nio standard. We use this to make sure we write
@@ -204,21 +201,21 @@ public class Link {
doWrite(ch, buffers, sslEngine);
}
}
-
+
/* SSL has limitation of 16k, we may need to split packets. 18000 is 16k + some extra SSL informations */
protected static final int MAX_SIZE_PER_PACKET = 18000;
protected static final int HEADER_FLAG_FOLLOWING = 0x10000;
-
+
public byte[] read(SocketChannel ch) throws IOException {
if (_readHeader) { // Start of a packet
if (_readBuffer.position() == 0) {
_readBuffer.limit(4);
}
-
+
if (ch.read(_readBuffer) == -1) {
throw new IOException("Connection closed with -1 on reading size.");
}
-
+
if (_readBuffer.hasRemaining()) {
s_logger.trace("Need to read the rest of the packet length");
return null;
@@ -229,24 +226,24 @@ public class Link {
if (s_logger.isTraceEnabled()) {
s_logger.trace("Packet length is " + readSize);
}
-
+
if (readSize > MAX_SIZE_PER_PACKET) {
- throw new IOException("Wrong packet size: " + readSize);
+ throw new IOException("Wrong packet size: " + readSize);
}
-
+
if (!_gotFollowingPacket) {
_plaintextBuffer = ByteBuffer.allocate(2000);
}
-
+
if ((header & HEADER_FLAG_FOLLOWING) != 0) {
_gotFollowingPacket = true;
} else {
_gotFollowingPacket = false;
}
-
+
_readBuffer.clear();
_readHeader = false;
-
+
if (_readBuffer.capacity() < readSize) {
if (s_logger.isTraceEnabled()) {
s_logger.trace("Resizing the byte buffer from " + _readBuffer.capacity());
@@ -255,18 +252,18 @@ public class Link {
}
_readBuffer.limit(readSize);
}
-
+
if (ch.read(_readBuffer) == -1) {
throw new IOException("Connection closed with -1 on read.");
}
-
+
if (_readBuffer.hasRemaining()) { // We're not done yet.
if (s_logger.isTraceEnabled()) {
s_logger.trace("Still has " + _readBuffer.remaining());
}
return null;
}
-
+
_readBuffer.flip();
ByteBuffer appBuf;
@@ -287,7 +284,7 @@ public class Link {
if (remaining == _readBuffer.remaining()) {
throw new IOException("SSL: Unable to unwrap received data! still remaining " + remaining + "bytes!");
}
-
+
appBuf.flip();
if (_plaintextBuffer.remaining() < appBuf.limit()) {
// We need to expand _plaintextBuffer for more data
@@ -301,10 +298,10 @@ public class Link {
s_logger.trace("Done with packet: " + appBuf.limit());
}
}
-
+
_readBuffer.clear();
_readHeader = true;
-
+
if (!_gotFollowingPacket) {
_plaintextBuffer.flip();
byte[] result = new byte[_plaintextBuffer.limit()];
@@ -317,15 +314,15 @@ public class Link {
return null;
}
}
-
+
public void send(byte[] data) throws ClosedChannelException {
send(data, false);
}
-
+
public void send(byte[] data, boolean close) throws ClosedChannelException {
send(new ByteBuffer[] { ByteBuffer.wrap(data) }, close);
}
-
+
public void send(ByteBuffer[] data, boolean close) throws ClosedChannelException {
ByteBuffer[] item = new ByteBuffer[data.length + 1];
int remaining = 0;
@@ -333,15 +330,15 @@ public class Link {
remaining += data[i].remaining();
item[i + 1] = data[i];
}
-
+
item[0] = ByteBuffer.allocate(4);
item[0].putInt(remaining);
item[0].flip();
-
+
if (s_logger.isTraceEnabled()) {
s_logger.trace("Sending packet of length " + remaining);
}
-
+
_writeQueue.add(item);
if (close) {
_writeQueue.add(new ByteBuffer[0]);
@@ -353,17 +350,17 @@ public class Link {
_connection.change(SelectionKey.OP_WRITE, _key, null);
}
}
-
+
public void send(ByteBuffer[] data) throws ClosedChannelException {
send(data, false);
}
-
+
public synchronized void close() {
if (_key != null) {
_connection.close(_key);
}
}
-
+
public boolean write(SocketChannel ch) throws IOException {
ByteBuffer[] data = null;
while ((data = _writeQueue.poll()) != null) {
@@ -381,26 +378,26 @@ public class Link {
}
return false;
}
-
+
public InetSocketAddress getSocketAddress() {
return _addr;
}
-
+
public String getIpAddress() {
return _addr.getAddress().toString();
}
-
+
public synchronized void terminated() {
_key = null;
}
-
+
public synchronized void schedule(Task task) throws ClosedChannelException {
if (_key == null) {
throw new ClosedChannelException();
}
_connection.scheduleTask(task);
}
-
+
public static SSLContext initSSLContext(boolean isClient) throws Exception {
InputStream stream;
SSLContext sslContext = null;
@@ -408,42 +405,42 @@ public class Link {
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
KeyStore ks = KeyStore.getInstance("JKS");
TrustManager[] tms;
-
+
if (!isClient) {
- char[] passphrase = "vmops.com".toCharArray();
- File confFile= PropertiesUtil.findConfigFile("db.properties");
- /* This line may throw a NPE, but that's due to fail to find db.properities, meant some bugs in the other places */
- String confPath = confFile.getParent();
- String keystorePath = confPath + "/cloud.keystore";
- if (new File(keystorePath).exists()) {
- stream = new FileInputStream(keystorePath);
- } else {
- s_logger.warn("SSL: Fail to find the generated keystore. Loading fail-safe one to continue.");
- stream = NioConnection.class.getResourceAsStream("/cloud.keystore");
- }
- ks.load(stream, passphrase);
- stream.close();
- kmf.init(ks, passphrase);
- tmf.init(ks);
- tms = tmf.getTrustManagers();
+ char[] passphrase = "vmops.com".toCharArray();
+ File confFile= PropertiesUtil.findConfigFile("db.properties");
+ /* This line may throw a NPE, but that's due to fail to find db.properities, meant some bugs in the other places */
+ String confPath = confFile.getParent();
+ String keystorePath = confPath + "/cloud.keystore";
+ if (new File(keystorePath).exists()) {
+ stream = new FileInputStream(keystorePath);
+ } else {
+ s_logger.warn("SSL: Fail to find the generated keystore. Loading fail-safe one to continue.");
+ stream = NioConnection.class.getResourceAsStream("/cloud.keystore");
+ }
+ ks.load(stream, passphrase);
+ stream.close();
+ kmf.init(ks, passphrase);
+ tmf.init(ks);
+ tms = tmf.getTrustManagers();
} else {
- ks.load(null, null);
- kmf.init(ks, null);
- tms = new TrustManager[1];
- tms[0] = new TrustAllManager();
+ ks.load(null, null);
+ kmf.init(ks, null);
+ tms = new TrustManager[1];
+ tms[0] = new TrustAllManager();
}
-
+
sslContext = SSLContext.getInstance("TLS");
sslContext.init(kmf.getKeyManagers(), tms, null);
if (s_logger.isTraceEnabled()) {
- s_logger.trace("SSL: SSLcontext has been initialized");
+ s_logger.trace("SSL: SSLcontext has been initialized");
}
return sslContext;
}
public static void doHandshake(SocketChannel ch, SSLEngine sslEngine,
- boolean isClient) throws IOException {
+ boolean isClient) throws IOException {
if (s_logger.isTraceEnabled()) {
s_logger.trace("SSL: begin Handshake, isClient: " + isClient);
}
@@ -452,13 +449,13 @@ public class Link {
SSLSession sslSession = sslEngine.getSession();
HandshakeStatus hsStatus;
ByteBuffer in_pkgBuf =
- ByteBuffer.allocate(sslSession.getPacketBufferSize() + 40);
+ ByteBuffer.allocate(sslSession.getPacketBufferSize() + 40);
ByteBuffer in_appBuf =
- ByteBuffer.allocate(sslSession.getApplicationBufferSize() + 40);
+ ByteBuffer.allocate(sslSession.getApplicationBufferSize() + 40);
ByteBuffer out_pkgBuf =
- ByteBuffer.allocate(sslSession.getPacketBufferSize() + 40);
+ ByteBuffer.allocate(sslSession.getPacketBufferSize() + 40);
ByteBuffer out_appBuf =
- ByteBuffer.allocate(sslSession.getApplicationBufferSize() + 40);
+ ByteBuffer.allocate(sslSession.getApplicationBufferSize() + 40);
int count;
if (isClient) {
@@ -498,7 +495,7 @@ public class Link {
}
engResult = sslEngine.unwrap(in_pkgBuf, in_appBuf);
ByteBuffer tmp_pkgBuf =
- ByteBuffer.allocate(sslSession.getPacketBufferSize() + 40);
+ ByteBuffer.allocate(sslSession.getPacketBufferSize() + 40);
int loop_count = 0;
while (engResult.getStatus() == SSLEngineResult.Status.BUFFER_UNDERFLOW) {
// The client is too slow? Cut it and let it reconnect
@@ -515,13 +512,13 @@ public class Link {
throw new IOException("Connection closed with -1 on reading size.");
}
tmp_pkgBuf.flip();
-
+
in_pkgBuf.mark();
in_pkgBuf.position(in_pkgBuf.limit());
in_pkgBuf.limit(in_pkgBuf.limit() + tmp_pkgBuf.limit());
in_pkgBuf.put(tmp_pkgBuf);
in_pkgBuf.reset();
-
+
in_appBuf.clear();
engResult = sslEngine.unwrap(in_pkgBuf, in_appBuf);
loop_count ++;
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/110465b5/utils/src/com/cloud/utils/security/CertificateHelper.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/security/CertificateHelper.java b/utils/src/com/cloud/utils/security/CertificateHelper.java
index 327734a..8344d72 100644
--- a/utils/src/com/cloud/utils/security/CertificateHelper.java
+++ b/utils/src/com/cloud/utils/security/CertificateHelper.java
@@ -19,7 +19,6 @@ package com.cloud.utils.security;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
-import java.io.FileOutputStream;
import java.io.IOException;
import java.security.Key;
import java.security.KeyFactory;
@@ -38,72 +37,72 @@ import org.apache.commons.codec.binary.Base64;
import com.cloud.utils.Ternary;
public class CertificateHelper {
- public static byte[] buildAndSaveKeystore(String alias, String cert, String privateKey, String storePassword) throws KeyStoreException, CertificateException,
- NoSuchAlgorithmException, InvalidKeySpecException, IOException {
- KeyStore ks = buildKeystore(alias, cert, privateKey, storePassword);
-
- ByteArrayOutputStream os = new ByteArrayOutputStream();
- ks.store(os, storePassword != null ? storePassword.toCharArray() : null);
- os.close();
- return os.toByteArray();
- }
-
- public static byte[] buildAndSaveKeystore(List<Ternary<String, String, String>> certs, String storePassword) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, InvalidKeySpecException {
- KeyStore ks = KeyStore.getInstance("JKS");
- ks.load(null, storePassword != null ? storePassword.toCharArray() : null);
+ public static byte[] buildAndSaveKeystore(String alias, String cert, String privateKey, String storePassword) throws KeyStoreException, CertificateException,
+ NoSuchAlgorithmException, InvalidKeySpecException, IOException {
+ KeyStore ks = buildKeystore(alias, cert, privateKey, storePassword);
- //name,cert,key
- for (Ternary<String, String, String> cert : certs) {
- if (cert.third() == null) {
- Certificate c = buildCertificate(cert.second());
- ks.setCertificateEntry(cert.first(), c);
- } else {
- Certificate[] c = new Certificate[certs.size()];
- int i = certs.size();
- for (Ternary<String, String, String> ct : certs) {
- c[i - 1] = buildCertificate(ct.second());
- i--;
- }
- ks.setKeyEntry(cert.first(), buildPrivateKey(cert.third()), storePassword != null ? storePassword.toCharArray() : null, c );
- }
- }
-
- ByteArrayOutputStream os = new ByteArrayOutputStream();
- ks.store(os, storePassword != null ? storePassword.toCharArray() : null);
- os.close();
- return os.toByteArray();
- }
-
- public static KeyStore loadKeystore(byte[] ksData, String storePassword) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException {
- assert(ksData != null);
- KeyStore ks = KeyStore.getInstance("JKS");
- ks.load(new ByteArrayInputStream(ksData), storePassword != null ? storePassword.toCharArray() : null);
+ ByteArrayOutputStream os = new ByteArrayOutputStream();
+ ks.store(os, storePassword != null ? storePassword.toCharArray() : null);
+ os.close();
+ return os.toByteArray();
+ }
- return ks;
- }
-
- public static KeyStore buildKeystore(String alias, String cert, String privateKey, String storePassword) throws KeyStoreException, CertificateException,
- NoSuchAlgorithmException, InvalidKeySpecException, IOException {
-
- KeyStore ks = KeyStore.getInstance("JKS");
- ks.load(null, storePassword != null ? storePassword.toCharArray() : null);
- Certificate[] certs = new Certificate[1];
- certs[0] = buildCertificate(cert);
- ks.setKeyEntry(alias, buildPrivateKey(privateKey), storePassword != null ? storePassword.toCharArray() : null, certs );
- return ks;
- }
+ public static byte[] buildAndSaveKeystore(List<Ternary<String, String, String>> certs, String storePassword) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, InvalidKeySpecException {
+ KeyStore ks = KeyStore.getInstance("JKS");
+ ks.load(null, storePassword != null ? storePassword.toCharArray() : null);
- public static Certificate buildCertificate(String content) throws CertificateException {
- assert(content != null);
-
- BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(content.getBytes()));
- CertificateFactory cf = CertificateFactory.getInstance("X.509");
- return cf.generateCertificate(bis);
- }
+ //name,cert,key
+ for (Ternary<String, String, String> cert : certs) {
+ if (cert.third() == null) {
+ Certificate c = buildCertificate(cert.second());
+ ks.setCertificateEntry(cert.first(), c);
+ } else {
+ Certificate[] c = new Certificate[certs.size()];
+ int i = certs.size();
+ for (Ternary<String, String, String> ct : certs) {
+ c[i - 1] = buildCertificate(ct.second());
+ i--;
+ }
+ ks.setKeyEntry(cert.first(), buildPrivateKey(cert.third()), storePassword != null ? storePassword.toCharArray() : null, c );
+ }
+ }
- public static Key buildPrivateKey(String base64EncodedKeyContent) throws NoSuchAlgorithmException, InvalidKeySpecException, IOException {
- KeyFactory kf = KeyFactory.getInstance("RSA");
- PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec (Base64.decodeBase64(base64EncodedKeyContent));
- return kf.generatePrivate (keysp);
- }
+ ByteArrayOutputStream os = new ByteArrayOutputStream();
+ ks.store(os, storePassword != null ? storePassword.toCharArray() : null);
+ os.close();
+ return os.toByteArray();
+ }
+
+ public static KeyStore loadKeystore(byte[] ksData, String storePassword) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException {
+ assert(ksData != null);
+ KeyStore ks = KeyStore.getInstance("JKS");
+ ks.load(new ByteArrayInputStream(ksData), storePassword != null ? storePassword.toCharArray() : null);
+
+ return ks;
+ }
+
+ public static KeyStore buildKeystore(String alias, String cert, String privateKey, String storePassword) throws KeyStoreException, CertificateException,
+ NoSuchAlgorithmException, InvalidKeySpecException, IOException {
+
+ KeyStore ks = KeyStore.getInstance("JKS");
+ ks.load(null, storePassword != null ? storePassword.toCharArray() : null);
+ Certificate[] certs = new Certificate[1];
+ certs[0] = buildCertificate(cert);
+ ks.setKeyEntry(alias, buildPrivateKey(privateKey), storePassword != null ? storePassword.toCharArray() : null, certs );
+ return ks;
+ }
+
+ public static Certificate buildCertificate(String content) throws CertificateException {
+ assert(content != null);
+
+ BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(content.getBytes()));
+ CertificateFactory cf = CertificateFactory.getInstance("X.509");
+ return cf.generateCertificate(bis);
+ }
+
+ public static Key buildPrivateKey(String base64EncodedKeyContent) throws NoSuchAlgorithmException, InvalidKeySpecException, IOException {
+ KeyFactory kf = KeyFactory.getInstance("RSA");
+ PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec (Base64.decodeBase64(base64EncodedKeyContent));
+ return kf.generatePrivate (keysp);
+ }
}
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/110465b5/utils/test/com/cloud/utils/component/MockComponentLocator.java
----------------------------------------------------------------------
diff --git a/utils/test/com/cloud/utils/component/MockComponentLocator.java b/utils/test/com/cloud/utils/component/MockComponentLocator.java
deleted file mode 100755
index d95d262..0000000
--- a/utils/test/com/cloud/utils/component/MockComponentLocator.java
+++ /dev/null
@@ -1,121 +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.component;
-
-import java.io.Serializable;
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-
-import net.sf.cglib.proxy.Callback;
-import net.sf.cglib.proxy.NoOp;
-
-import com.cloud.utils.Pair;
-import com.cloud.utils.db.DatabaseCallback;
-import com.cloud.utils.db.DatabaseCallbackFilter;
-import com.cloud.utils.db.GenericDao;
-
-/**
- * defining mock components.
- */
-public class MockComponentLocator extends LegacyComponentLocator {
- MockComponentLibrary _library = new MockComponentLibrary();
-
- public MockComponentLocator(String server) {
- super(server);
- }
-
- public ComponentInfo<? extends GenericDao<?, ? extends Serializable>> addDao(String name, Class<? extends GenericDao<?, ? extends Serializable>> dao) {
- return _library.addDao(name, dao);
- }
-
- public ComponentInfo<Manager> addManager(String name, Class<? extends Manager> manager) {
- return _library.addManager(name, manager);
- }
-
- public <T> ComponentInfo<Adapter> addOneAdapter(Class<T> interphace, String name, Class<? extends T> adapterClass) {
- return _library.addOneAdapter(interphace, name, adapterClass);
- }
-
- public <T> List<ComponentInfo<Adapter>> addAdapterChain(Class<T> interphace, List<Pair<String, Class<? extends T>>> adapters) {
- return _library.addAdapterChain(interphace, adapters);
- }
-
- public <T> ComponentInfo<PluggableService> addService(String name, Class<T> serviceInterphace, Class<? extends PluggableService> service) {
- return _library.addService(name, serviceInterphace, service);
- }
-
- @Override
- protected Pair<XmlHandler, HashMap<String, List<ComponentInfo<Adapter>>>> parse2(String filename) {
- Pair<XmlHandler, HashMap<String, List<ComponentInfo<Adapter>>>> result = new Pair<XmlHandler, HashMap<String, List<ComponentInfo<Adapter>>>>(new XmlHandler("fake"), new HashMap<String, List<ComponentInfo<Adapter>>>());
- _daoMap = new LinkedHashMap<String, ComponentInfo<GenericDao<?, ? extends Serializable>>>();
- _managerMap = new LinkedHashMap<String, ComponentInfo<Manager>>();
- _checkerMap = new LinkedHashMap<String, ComponentInfo<SystemIntegrityChecker>>();
- _adapterMap = new HashMap<String, Adapters<? extends Adapter>>();
- _pluginsMap = new HashMap<String, ComponentInfo<PluggableService>>();
- _factories = new HashMap<Class<?>, Class<?>>();
- _daoMap.putAll(_library.getDaos());
- _managerMap.putAll(_library.getManagers());
- result.second().putAll(_library.getAdapters());
- _factories.putAll(_library.getFactories());
- _pluginsMap.putAll(_library.getPluggableServices());
- return result;
- }
-
- public void makeActive(InterceptorLibrary interceptors) {
- s_singletons.clear();
- s_locators.clear();
- s_factories.clear();
- s_callbacks = new Callback[] { NoOp.INSTANCE, new DatabaseCallback()};
- s_callbackFilter = new DatabaseCallbackFilter();
- s_interceptors.clear();
- if (interceptors != null) {
- resetInterceptors(interceptors);
- }
- s_tl.set(this);
- parse("fake file");
- }
-
- protected class MockComponentLibrary extends ComponentLibraryBase implements ComponentLibrary {
-
- @Override
- public Map<String, List<ComponentInfo<Adapter>>> getAdapters() {
- return _adapters;
- }
-
- @Override
- public Map<Class<?>, Class<?>> getFactories() {
- return new HashMap<Class<?>, Class<?>>();
- }
-
- @Override
- public Map<String, ComponentInfo<GenericDao<?, ?>>> getDaos() {
- return _daos;
- }
-
- @Override
- public Map<String, ComponentInfo<Manager>> getManagers() {
- return _managers;
- }
-
- @Override
- public Map<String, ComponentInfo<PluggableService>> getPluggableServices() {
- return _pluggableServices;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/110465b5/utils/test/com/cloud/utils/db/TransactionTest.java
----------------------------------------------------------------------
diff --git a/utils/test/com/cloud/utils/db/TransactionTest.java b/utils/test/com/cloud/utils/db/TransactionTest.java
index 96d31b4..b952be2 100644
--- a/utils/test/com/cloud/utils/db/TransactionTest.java
+++ b/utils/test/com/cloud/utils/db/TransactionTest.java
@@ -26,7 +26,7 @@ import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
-import com.cloud.utils.component.ComponentLocator;
+import com.cloud.utils.component.ComponentContext;
import com.cloud.utils.exception.CloudRuntimeException;
/**
@@ -34,7 +34,7 @@ import com.cloud.utils.exception.CloudRuntimeException;
* all its testcases to set up a test db table, and then tear down these test db artifacts after all testcases are run.
*
* @author Min Chen
- *
+ *
*/
public class TransactionTest {
@@ -76,7 +76,7 @@ public class TransactionTest {
* that the same db connection is reused rather than acquiring a new one each time in typical transaction model.
*/
public void testUserManagedConnection() {
- DbTestDao testDao = ComponentLocator.inject(DbTestDao.class);
+ DbTestDao testDao = ComponentContext.inject(DbTestDao.class);
Transaction txn = Transaction.open("SingleConnectionThread");
Connection conn = null;
try {
@@ -115,7 +115,7 @@ public class TransactionTest {
* This test is simulating ClusterHeartBeat process, where the same transaction and db connection is reused.
*/
public void testTransactionReuse() {
- DbTestDao testDao = ComponentLocator.inject(DbTestDao.class);
+ DbTestDao testDao = ComponentContext.inject(DbTestDao.class);
// acquire a db connection and keep it
Connection conn = null;
try {
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/110465b5/utils/test/com/cloud/utils/log/CglibThrowableRendererTest.java
----------------------------------------------------------------------
diff --git a/utils/test/com/cloud/utils/log/CglibThrowableRendererTest.java b/utils/test/com/cloud/utils/log/CglibThrowableRendererTest.java
index 5a9501d..59926f8 100644
--- a/utils/test/com/cloud/utils/log/CglibThrowableRendererTest.java
+++ b/utils/test/com/cloud/utils/log/CglibThrowableRendererTest.java
@@ -18,14 +18,21 @@ package com.cloud.utils.log;
import junit.framework.TestCase;
-import org.apache.log4j.Logger;
+import org.apache.log4j.*;
-import com.cloud.utils.component.ComponentLocator;
+import com.cloud.utils.component.ComponentContext;
import com.cloud.utils.db.DB;
import com.cloud.utils.exception.CloudRuntimeException;
+import org.apache.log4j.spi.RootLogger;
+import org.apache.log4j.spi.ThrowableRenderer;
+
+import java.io.CharArrayWriter;
+import java.io.Writer;
public class CglibThrowableRendererTest extends TestCase {
+ static Logger another = Logger.getLogger("TEST");
+
private final static Logger s_logger = Logger.getLogger(CglibThrowableRendererTest.class);
public static class Test {
@DB
@@ -48,13 +55,40 @@ public class CglibThrowableRendererTest extends TestCase {
}
}
}
-
+
+ private Logger getAlternateLogger(Writer writer, ThrowableRenderer renderer) {
+ Hierarchy hierarchy = new Hierarchy(new RootLogger(Level.INFO));
+ if (renderer != null) {
+ hierarchy.setThrowableRenderer(renderer);
+ }
+ Logger alternateRoot = hierarchy.getRootLogger();
+ alternateRoot.addAppender(new WriterAppender(new SimpleLayout(), writer));
+ return alternateRoot;
+ }
+
public void testException() {
- Test test = ComponentLocator.inject(Test.class);
+ Writer w = new CharArrayWriter();
+ Logger alt = getAlternateLogger(w, null);
+
+ Test test = ComponentContext.inject(Test.class);
try {
test.exception();
} catch (Exception e) {
- s_logger.warn("exception caught", e);
+ alt.warn("exception caught", e);
}
+ // first check that we actually have some call traces containing "<generated>"
+ assertTrue(w.toString().contains("<generated>"));
+
+ w = new CharArrayWriter();
+ alt = getAlternateLogger(w, new CglibThrowableRenderer());
+
+ try {
+ test.exception();
+ } catch (Exception e) {
+ alt.warn("exception caught", e);
+ }
+ // then we check that CglibThrowableRenderer indeed remove those occurrences
+ assertFalse(w.toString().contains("<generated>"));
+
}
}
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/110465b5/utils/test/com/cloud/utils/testcase/ComponentSetup.java
----------------------------------------------------------------------
diff --git a/utils/test/com/cloud/utils/testcase/ComponentSetup.java b/utils/test/com/cloud/utils/testcase/ComponentSetup.java
deleted file mode 100644
index ba9b9e7..0000000
--- a/utils/test/com/cloud/utils/testcase/ComponentSetup.java
+++ /dev/null
@@ -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.testcase;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-
-@Retention(RetentionPolicy.RUNTIME)
-public @interface ComponentSetup {
- String managerName();
- String setupXml();
- String log4j() default "log4j-cloud";
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/110465b5/utils/test/com/cloud/utils/testcase/ComponentTestCase.java
----------------------------------------------------------------------
diff --git a/utils/test/com/cloud/utils/testcase/ComponentTestCase.java b/utils/test/com/cloud/utils/testcase/ComponentTestCase.java
deleted file mode 100644
index 6fe7af1..0000000
--- a/utils/test/com/cloud/utils/testcase/ComponentTestCase.java
+++ /dev/null
@@ -1,44 +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.testcase;
-
-import java.lang.annotation.Annotation;
-
-import com.cloud.utils.component.LegacyComponentLocator;
-
-public class ComponentTestCase extends Log4jEnabledTestCase {
- @Override
- protected void setUp() {
- super.setUp();
-
- Annotation[] annotations = getClass().getAnnotations();
- if(annotations != null) {
- for(Annotation annotation : annotations) {
- if(annotation instanceof ComponentSetup) {
- LegacyComponentLocator.getLocator(
- ((ComponentSetup)annotation).managerName(),
- ((ComponentSetup)annotation).setupXml(),
- ((ComponentSetup)annotation).log4j()
- );
-
- break;
- }
- }
- }
- }
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/110465b5/utils/test/resources/com/cloud/utils/QualifierTestContext.xml
----------------------------------------------------------------------
diff --git a/utils/test/resources/com/cloud/utils/QualifierTestContext.xml b/utils/test/resources/com/cloud/utils/QualifierTestContext.xml
index c045f98..313e9d9 100644
--- a/utils/test/resources/com/cloud/utils/QualifierTestContext.xml
+++ b/utils/test/resources/com/cloud/utils/QualifierTestContext.xml
@@ -1,3 +1,21 @@
+<!--
+ 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.
+-->
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/110465b5/utils/test/resources/com/cloud/utils/db/transactionContextBuilderTest.xml
----------------------------------------------------------------------
diff --git a/utils/test/resources/com/cloud/utils/db/transactionContextBuilderTest.xml b/utils/test/resources/com/cloud/utils/db/transactionContextBuilderTest.xml
index 8a34670..fd82f81 100644
--- a/utils/test/resources/com/cloud/utils/db/transactionContextBuilderTest.xml
+++ b/utils/test/resources/com/cloud/utils/db/transactionContextBuilderTest.xml
@@ -1,3 +1,21 @@
+<!--
+ 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.
+-->
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/110465b5/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostMO.java
----------------------------------------------------------------------
diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostMO.java
index 3557048..a765b42 100755
--- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostMO.java
+++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostMO.java
@@ -840,11 +840,9 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost {
VmwareHypervisorHostResourceSummary summary = new VmwareHypervisorHostResourceSummary();
- HostConnectInfo hostInfo = _context.getService().queryHostConnectionInfo(_mor);
- HostHardwareSummary hardwareSummary = hostInfo.getHost().getHardware();
-
+ HostHardwareSummary hardwareSummary = getHostHardwareSummary();
// TODO: not sure how hyper-thread is counted in VMware resource pool
- summary.setCpuCount(hardwareSummary.getNumCpuCores()*hardwareSummary.getNumCpuPkgs());
+ summary.setCpuCount(hardwareSummary.getNumCpuCores());
summary.setMemoryBytes(hardwareSummary.getMemorySize());
summary.setCpuSpeed(hardwareSummary.getCpuMhz());
@@ -922,14 +920,13 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost {
ComputeResourceSummary resourceSummary = new ComputeResourceSummary();
// TODO: not sure how hyper-threading is counted in VMware
- short totalCores = (short)(hardwareSummary.getNumCpuCores()*hardwareSummary.getNumCpuPkgs());
- resourceSummary.setNumCpuCores(totalCores);
+ resourceSummary.setNumCpuCores(hardwareSummary.getNumCpuCores());
// Note: memory here is in Byte unit
resourceSummary.setTotalMemory(hardwareSummary.getMemorySize());
- // Total CPU is based on socket x core x Mhz
- int totalCpu = hardwareSummary.getCpuMhz() * totalCores;
+ // Total CPU is based on (# of cores) x Mhz
+ int totalCpu = hardwareSummary.getCpuMhz() * hardwareSummary.getNumCpuCores();
resourceSummary.setTotalCpu(totalCpu);
HostListSummaryQuickStats stats = getHostQuickStats();