fixing line ends in utils

This commit is contained in:
David Nalley 2012-04-09 20:05:41 -04:00
parent e4a41071de
commit 91fadc4a0d
28 changed files with 2142 additions and 2142 deletions

View File

@ -1,40 +1,40 @@
# management server clustering parameters, change cluster.node.IP to the machine IP address
# in which the management server(Tomcat) is running
cluster.node.IP=127.0.0.1
cluster.servlet.port=9090
# CloudStack database settings
db.cloud.username=cloud
db.cloud.password=cloud
db.cloud.host=localhost
db.cloud.port=3306
db.cloud.name=cloud
# CloudStack database tuning parameters
db.cloud.maxActive=250
db.cloud.maxIdle=30
db.cloud.maxWait=10000
db.cloud.autoReconnect=true
db.cloud.validationQuery=SELECT 1
db.cloud.testOnBorrow=true
db.cloud.testWhileIdle=true
db.cloud.timeBetweenEvictionRunsMillis=40000
db.cloud.minEvictableIdleTimeMillis=240000
db.cloud.removeAbandoned=false
db.cloud.removeAbandonedTimeout=300
db.cloud.logAbandoned=true
db.cloud.poolPreparedStatements=false
db.cloud.url.params=prepStmtCacheSize=517&cachePrepStmts=true&prepStmtCacheSqlLimit=4096
# usage database settings
db.usage.username=cloud
db.usage.password=cloud
db.usage.host=localhost
db.usage.port=3306
db.usage.name=cloud_usage
# usage database tuning parameters
db.usage.maxActive=100
db.usage.maxIdle=30
db.usage.maxWait=10000
db.usage.autoReconnect=true
# management server clustering parameters, change cluster.node.IP to the machine IP address
# in which the management server(Tomcat) is running
cluster.node.IP=127.0.0.1
cluster.servlet.port=9090
# CloudStack database settings
db.cloud.username=cloud
db.cloud.password=cloud
db.cloud.host=localhost
db.cloud.port=3306
db.cloud.name=cloud
# CloudStack database tuning parameters
db.cloud.maxActive=250
db.cloud.maxIdle=30
db.cloud.maxWait=10000
db.cloud.autoReconnect=true
db.cloud.validationQuery=SELECT 1
db.cloud.testOnBorrow=true
db.cloud.testWhileIdle=true
db.cloud.timeBetweenEvictionRunsMillis=40000
db.cloud.minEvictableIdleTimeMillis=240000
db.cloud.removeAbandoned=false
db.cloud.removeAbandonedTimeout=300
db.cloud.logAbandoned=true
db.cloud.poolPreparedStatements=false
db.cloud.url.params=prepStmtCacheSize=517&cachePrepStmts=true&prepStmtCacheSqlLimit=4096
# usage database settings
db.usage.username=cloud
db.usage.password=cloud
db.usage.host=localhost
db.usage.port=3306
db.usage.name=cloud_usage
# usage database tuning parameters
db.usage.maxActive=100
db.usage.maxIdle=30
db.usage.maxWait=10000
db.usage.autoReconnect=true

View File

@ -10,8 +10,8 @@
// limitations under the License.
//
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.utils;
public interface ActionDelegate <T> {
void action(T param);
}
package com.cloud.utils;
public interface ActionDelegate <T> {
void action(T param);
}

View File

@ -10,46 +10,46 @@
// limitations under the License.
//
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.utils;
import javax.persistence.Table;
import org.apache.log4j.Logger;
import com.cloud.utils.exception.CSExceptionErrorCode;
public class AnnotationHelper extends Object {
// This class contains routines to help query annotation elements of objects.
public static final Logger s_logger = Logger.getLogger(AnnotationHelper.class.getName());
public static String getTableName(Object proxyObj) {
// The cglib class is generated by cglib during runtime.
Class<?> curClass = proxyObj.getClass();
if (curClass == null) {
s_logger.info("\nCould not retrieve class information for proxy object\n");
return null;
}
while (curClass.getSuperclass() != null && curClass.getSuperclass().getName() != "java.lang.Object") {
curClass = curClass.getSuperclass();
}
// At this point, curClass is the root base class of proxyObj's class, and curClass is not java.lang.Object.
Table tabObj = (Table)curClass.getAnnotation(Table.class);
if (tabObj == null) {
s_logger.info("\n" + curClass + "does not have a Table annotation\n");
return null;
}
return tabObj.name();
}
}
package com.cloud.utils;
import javax.persistence.Table;
import org.apache.log4j.Logger;
import com.cloud.utils.exception.CSExceptionErrorCode;
public class AnnotationHelper extends Object {
// This class contains routines to help query annotation elements of objects.
public static final Logger s_logger = Logger.getLogger(AnnotationHelper.class.getName());
public static String getTableName(Object proxyObj) {
// The cglib class is generated by cglib during runtime.
Class<?> curClass = proxyObj.getClass();
if (curClass == null) {
s_logger.info("\nCould not retrieve class information for proxy object\n");
return null;
}
while (curClass.getSuperclass() != null && curClass.getSuperclass().getName() != "java.lang.Object") {
curClass = curClass.getSuperclass();
}
// At this point, curClass is the root base class of proxyObj's class, and curClass is not java.lang.Object.
Table tabObj = (Table)curClass.getAnnotation(Table.class);
if (tabObj == null) {
s_logger.info("\n" + curClass + "does not have a Table annotation\n");
return null;
}
return tabObj.name();
}
}

View File

@ -10,32 +10,32 @@
// limitations under the License.
//
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.utils;
import java.util.Locale;
import java.util.ResourceBundle;
public class CloudResourceBundle {
private ResourceBundle _bundle;
public CloudResourceBundle(ResourceBundle bundle) {
_bundle = bundle;
}
public static CloudResourceBundle getBundle(String baseName, Locale locale) {
return new CloudResourceBundle(ResourceBundle.getBundle(baseName, locale));
}
private String getString(String key) {
try {
return _bundle.getString(key);
} catch(Exception e) {
return key; //if translation is not found, just return original word (i.e. English).
}
}
public String t(String key) {
return getString(key);
}
}
package com.cloud.utils;
import java.util.Locale;
import java.util.ResourceBundle;
public class CloudResourceBundle {
private ResourceBundle _bundle;
public CloudResourceBundle(ResourceBundle bundle) {
_bundle = bundle;
}
public static CloudResourceBundle getBundle(String baseName, Locale locale) {
return new CloudResourceBundle(ResourceBundle.getBundle(baseName, locale));
}
private String getString(String key) {
try {
return _bundle.getString(key);
} catch(Exception e) {
return key; //if translation is not found, just return original word (i.e. English).
}
}
public String t(String key) {
return getString(key);
}
}

View File

@ -10,8 +10,8 @@
// limitations under the License.
//
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.utils;
package com.cloud.utils;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
@ -20,51 +20,51 @@ import java.util.Date;
import java.util.TimeZone;
import com.cloud.utils.exception.CloudRuntimeException;
public class DateUtil {
public static final TimeZone GMT_TIMEZONE = TimeZone.getTimeZone("GMT");
public static final String YYYYMMDD_FORMAT = "yyyyMMddHHmmss";
private static final DateFormat _outputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
public static Date currentGMTTime() {
// Date object always stores miliseconds offset based on GMT internally
return new Date();
}
public static Date currentGMTTime() {
// Date object always stores miliseconds offset based on GMT internally
return new Date();
}
// yyyy-MM-ddTHH:mm:ssZxxxx
public static Date parseTZDateString(String str) throws ParseException {
DateFormat dfParse = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'Z");
return dfParse.parse(str);
}
public static Date parseDateString(TimeZone tz, String dateString) {
return parseDateString(tz, dateString, "yyyy-MM-dd HH:mm:ss");
}
public static Date parseDateString(TimeZone tz, String dateString, String formatString) {
DateFormat df = new SimpleDateFormat(formatString);
df.setTimeZone(tz);
try {
return df.parse(dateString);
} catch (ParseException e) {
throw new CloudRuntimeException("why why ", e);
}
}
public static Date parseDateString(TimeZone tz, String dateString) {
return parseDateString(tz, dateString, "yyyy-MM-dd HH:mm:ss");
}
public static Date parseDateString(TimeZone tz, String dateString, String formatString) {
DateFormat df = new SimpleDateFormat(formatString);
df.setTimeZone(tz);
try {
return df.parse(dateString);
} catch (ParseException e) {
throw new CloudRuntimeException("why why ", e);
}
}
public static String displayDateInTimezone(TimeZone tz, Date time) {
return getDateDisplayString(tz, time, "yyyy-MM-dd HH:mm:ss z");
}
public static String getDateDisplayString(TimeZone tz, Date time) {
return getDateDisplayString(tz, time, "yyyy-MM-dd HH:mm:ss");
}
public static String getDateDisplayString(TimeZone tz, Date time, String formatString) {
DateFormat df = new SimpleDateFormat(formatString);
df.setTimeZone(tz);
return df.format(time);
public static String getDateDisplayString(TimeZone tz, Date time) {
return getDateDisplayString(tz, time, "yyyy-MM-dd HH:mm:ss");
}
public static String getDateDisplayString(TimeZone tz, Date time, String formatString) {
DateFormat df = new SimpleDateFormat(formatString);
df.setTimeZone(tz);
return df.format(time);
}
public static String getOutputString(Date date) {
@ -79,10 +79,10 @@ public class DateUtil {
}
public enum IntervalType {
HOURLY,
DAILY,
WEEKLY,
MONTHLY;
HOURLY,
DAILY,
WEEKLY,
MONTHLY;
boolean equals(String intervalType) {
return super.toString().equalsIgnoreCase(intervalType);
@ -95,145 +95,145 @@ public class DateUtil {
}
}
return null;
}
}
}
public static IntervalType getIntervalType(short type){
public static IntervalType getIntervalType(short type){
if (type < 0 || type >= IntervalType.values().length) {
return null;
}
return IntervalType.values()[type];
return IntervalType.values()[type];
}
/**
* Return next run time
* @param intervalType hourly/daily/weekly/monthly
/**
* Return next run time
* @param intervalType hourly/daily/weekly/monthly
* @param schedule MM[:HH][:DD] format. DD is day of week for weekly and day of month for monthly
* @param timezone The timezone in which the schedule string is specified
* @param startDate if specified, returns next run time after the specified startDate
* @return
*/
public static Date getNextRunTime(IntervalType type, String schedule, String timezone, Date startDate) {
String[] scheduleParts = schedule.split(":"); //MM:HH:DAY
final Calendar scheduleTime = Calendar.getInstance();
* @param timezone The timezone in which the schedule string is specified
* @param startDate if specified, returns next run time after the specified startDate
* @return
*/
public static Date getNextRunTime(IntervalType type, String schedule, String timezone, Date startDate) {
String[] scheduleParts = schedule.split(":"); //MM:HH:DAY
final Calendar scheduleTime = Calendar.getInstance();
scheduleTime.setTimeZone(TimeZone.getTimeZone(timezone));
if(startDate == null){
startDate = new Date();
startDate = new Date();
}
scheduleTime.setTime(startDate);
// Throw an ArrayIndexOutOfBoundsException if schedule is badly formatted.
scheduleTime.setLenient(false);
int minutes = 0;
int hour = 0;
int day = 0;
Date execDate = null;
switch(type){
case HOURLY:
if(scheduleParts.length < 1){
throw new CloudRuntimeException("Incorrect schedule format: "+schedule+ " for interval type:"+type.toString());
}
minutes = Integer.parseInt(scheduleParts[0]);
scheduleTime.set(Calendar.MINUTE, minutes);
scheduleTime.set(Calendar.SECOND, 0);
scheduleTime.set(Calendar.MILLISECOND, 0);
execDate = scheduleTime.getTime();
// XXX: !execDate.after(startDate) is strictly for testing.
// During testing we use a test clock which runs much faster than the real clock
// So startDate and execDate will always be ahead in the future
// and we will never increase the time here
if (execDate.before(new Date()) || !execDate.after(startDate)) {
scheduleTime.add(Calendar.HOUR_OF_DAY, 1);
}
break;
case DAILY:
if(scheduleParts.length < 2){
throw new CloudRuntimeException("Incorrect schedule format: "+schedule+ " for interval type:"+type.toString());
}
minutes = Integer.parseInt(scheduleParts[0]);
hour = Integer.parseInt(scheduleParts[1]);
scheduleTime.set(Calendar.HOUR_OF_DAY, hour);
scheduleTime.set(Calendar.MINUTE, minutes);
scheduleTime.set(Calendar.SECOND, 0);
scheduleTime.set(Calendar.MILLISECOND, 0);
execDate = scheduleTime.getTime();
// XXX: !execDate.after(startDate) is strictly for testing.
// During testing we use a test clock which runs much faster than the real clock
// So startDate and execDate will always be ahead in the future
// and we will never increase the time here
if (execDate.before(new Date()) || !execDate.after(startDate)) {
scheduleTime.add(Calendar.DAY_OF_YEAR, 1);
}
break;
case WEEKLY:
if(scheduleParts.length < 3){
throw new CloudRuntimeException("Incorrect schedule format: "+schedule+ " for interval type:"+type.toString());
}
minutes = Integer.parseInt(scheduleParts[0]);
hour = Integer.parseInt(scheduleParts[1]);
day = Integer.parseInt(scheduleParts[2]);
scheduleTime.set(Calendar.DAY_OF_WEEK, day);
scheduleTime.set(Calendar.HOUR_OF_DAY, hour);
scheduleTime.set(Calendar.MINUTE, minutes);
scheduleTime.set(Calendar.SECOND, 0);
scheduleTime.set(Calendar.MILLISECOND, 0);
execDate = scheduleTime.getTime();
// XXX: !execDate.after(startDate) is strictly for testing.
// During testing we use a test clock which runs much faster than the real clock
// So startDate and execDate will always be ahead in the future
// and we will never increase the time here
if (execDate.before(new Date()) || !execDate.after(startDate)) {
scheduleTime.add(Calendar.DAY_OF_WEEK, 7);
};
break;
case MONTHLY:
if(scheduleParts.length < 3){
throw new CloudRuntimeException("Incorrect schedule format: "+schedule+ " for interval type:"+type.toString());
}
minutes = Integer.parseInt(scheduleParts[0]);
hour = Integer.parseInt(scheduleParts[1]);
scheduleTime.setTime(startDate);
// Throw an ArrayIndexOutOfBoundsException if schedule is badly formatted.
scheduleTime.setLenient(false);
int minutes = 0;
int hour = 0;
int day = 0;
Date execDate = null;
switch(type){
case HOURLY:
if(scheduleParts.length < 1){
throw new CloudRuntimeException("Incorrect schedule format: "+schedule+ " for interval type:"+type.toString());
}
minutes = Integer.parseInt(scheduleParts[0]);
scheduleTime.set(Calendar.MINUTE, minutes);
scheduleTime.set(Calendar.SECOND, 0);
scheduleTime.set(Calendar.MILLISECOND, 0);
execDate = scheduleTime.getTime();
// XXX: !execDate.after(startDate) is strictly for testing.
// During testing we use a test clock which runs much faster than the real clock
// So startDate and execDate will always be ahead in the future
// and we will never increase the time here
if (execDate.before(new Date()) || !execDate.after(startDate)) {
scheduleTime.add(Calendar.HOUR_OF_DAY, 1);
}
break;
case DAILY:
if(scheduleParts.length < 2){
throw new CloudRuntimeException("Incorrect schedule format: "+schedule+ " for interval type:"+type.toString());
}
minutes = Integer.parseInt(scheduleParts[0]);
hour = Integer.parseInt(scheduleParts[1]);
scheduleTime.set(Calendar.HOUR_OF_DAY, hour);
scheduleTime.set(Calendar.MINUTE, minutes);
scheduleTime.set(Calendar.SECOND, 0);
scheduleTime.set(Calendar.MILLISECOND, 0);
execDate = scheduleTime.getTime();
// XXX: !execDate.after(startDate) is strictly for testing.
// During testing we use a test clock which runs much faster than the real clock
// So startDate and execDate will always be ahead in the future
// and we will never increase the time here
if (execDate.before(new Date()) || !execDate.after(startDate)) {
scheduleTime.add(Calendar.DAY_OF_YEAR, 1);
}
break;
case WEEKLY:
if(scheduleParts.length < 3){
throw new CloudRuntimeException("Incorrect schedule format: "+schedule+ " for interval type:"+type.toString());
}
minutes = Integer.parseInt(scheduleParts[0]);
hour = Integer.parseInt(scheduleParts[1]);
day = Integer.parseInt(scheduleParts[2]);
scheduleTime.set(Calendar.DAY_OF_WEEK, day);
scheduleTime.set(Calendar.HOUR_OF_DAY, hour);
scheduleTime.set(Calendar.MINUTE, minutes);
scheduleTime.set(Calendar.SECOND, 0);
scheduleTime.set(Calendar.MILLISECOND, 0);
execDate = scheduleTime.getTime();
// XXX: !execDate.after(startDate) is strictly for testing.
// During testing we use a test clock which runs much faster than the real clock
// So startDate and execDate will always be ahead in the future
// and we will never increase the time here
if (execDate.before(new Date()) || !execDate.after(startDate)) {
scheduleTime.add(Calendar.DAY_OF_WEEK, 7);
};
break;
case MONTHLY:
if(scheduleParts.length < 3){
throw new CloudRuntimeException("Incorrect schedule format: "+schedule+ " for interval type:"+type.toString());
}
minutes = Integer.parseInt(scheduleParts[0]);
hour = Integer.parseInt(scheduleParts[1]);
day = Integer.parseInt(scheduleParts[2]);
if(day > 28){
throw new CloudRuntimeException("Day cannot be greater than 28 for monthly schedule");
}
scheduleTime.set(Calendar.DAY_OF_MONTH, day);
scheduleTime.set(Calendar.HOUR_OF_DAY, hour);
scheduleTime.set(Calendar.MINUTE, minutes);
scheduleTime.set(Calendar.SECOND, 0);
scheduleTime.set(Calendar.MILLISECOND, 0);
execDate = scheduleTime.getTime();
// XXX: !execDate.after(startDate) is strictly for testing.
// During testing we use a test clock which runs much faster than the real clock
// So startDate and execDate will always be ahead in the future
// and we will never increase the time here
if (execDate.before(new Date()) || !execDate.after(startDate)) {
scheduleTime.add(Calendar.MONTH, 1);
}
break;
default:
throw new CloudRuntimeException("Incorrect interval: "+type.toString());
}
return scheduleTime.getTime();
}
scheduleTime.set(Calendar.DAY_OF_MONTH, day);
scheduleTime.set(Calendar.HOUR_OF_DAY, hour);
scheduleTime.set(Calendar.MINUTE, minutes);
scheduleTime.set(Calendar.SECOND, 0);
scheduleTime.set(Calendar.MILLISECOND, 0);
execDate = scheduleTime.getTime();
// XXX: !execDate.after(startDate) is strictly for testing.
// During testing we use a test clock which runs much faster than the real clock
// So startDate and execDate will always be ahead in the future
// and we will never increase the time here
if (execDate.before(new Date()) || !execDate.after(startDate)) {
scheduleTime.add(Calendar.MONTH, 1);
}
break;
default:
throw new CloudRuntimeException("Incorrect interval: "+type.toString());
}
return scheduleTime.getTime();
}
// test only
// test only
public static void main(String[] args) {
TimeZone localTimezone = Calendar.getInstance().getTimeZone();
TimeZone gmtTimezone = TimeZone.getTimeZone("GMT");
TimeZone estTimezone = TimeZone.getTimeZone("EST");
TimeZone localTimezone = Calendar.getInstance().getTimeZone();
TimeZone gmtTimezone = TimeZone.getTimeZone("GMT");
TimeZone estTimezone = TimeZone.getTimeZone("EST");
Date time = new Date();
System.out.println("local time :" + getDateDisplayString(localTimezone, time));
System.out.println("GMT time :" + getDateDisplayString(gmtTimezone, time));
System.out.println("EST time :" + getDateDisplayString(estTimezone, time));
//Test next run time. Expects interval and schedule as arguments
if(args.length == 2) {
System.out.println("Next run time: "+ getNextRunTime(IntervalType.getIntervalType(args[0]), args[1], "GMT", time).toString());
System.out.println("local time :" + getDateDisplayString(localTimezone, time));
System.out.println("GMT time :" + getDateDisplayString(gmtTimezone, time));
System.out.println("EST time :" + getDateDisplayString(estTimezone, time));
//Test next run time. Expects interval and schedule as arguments
if(args.length == 2) {
System.out.println("Next run time: "+ getNextRunTime(IntervalType.getIntervalType(args[0]), args[1], "GMT", time).toString());
}
time = new Date();
@ -245,6 +245,6 @@ public class DateUtil {
System.out.println("Parsed TZ time string : "+ dtParsed.toString());
} catch (ParseException e) {
}
}
}
}
}

View File

@ -10,47 +10,47 @@
// limitations under the License.
//
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.utils;
public class IdentityProxy {
private String _tableName;
private Long _value;
private String _idFieldName;
public IdentityProxy() {
}
public IdentityProxy(String tableName) {
_tableName = tableName;
}
public IdentityProxy(String tableName, Long id, String fieldName) {
_tableName = tableName;
_value = id;
_idFieldName = fieldName;
}
public String getTableName() {
return _tableName;
}
public void setTableName(String tableName) {
_tableName = tableName;
}
public Long getValue() {
return _value;
}
public void setValue(Long value) {
_value = value;
}
public void setidFieldName(String value) {
_idFieldName = value;
}
public String getidFieldName() {
return _idFieldName;
}
}
package com.cloud.utils;
public class IdentityProxy {
private String _tableName;
private Long _value;
private String _idFieldName;
public IdentityProxy() {
}
public IdentityProxy(String tableName) {
_tableName = tableName;
}
public IdentityProxy(String tableName, Long id, String fieldName) {
_tableName = tableName;
_value = id;
_idFieldName = fieldName;
}
public String getTableName() {
return _tableName;
}
public void setTableName(String tableName) {
_tableName = tableName;
}
public Long getValue() {
return _value;
}
public void setValue(Long value) {
_value = value;
}
public void setidFieldName(String value) {
_idFieldName = value;
}
public String getidFieldName() {
return _idFieldName;
}
}

View File

@ -10,41 +10,41 @@
// limitations under the License.
//
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.utils;
import java.util.Enumeration;
import java.util.Iterator;
public class IteratorUtil {
public static <T> Iterable<T> enumerationAsIterable(final Enumeration<T> e) {
return new Iterable<T> () {
public Iterator<T> iterator() {
return new Iterator<T>() {
public boolean hasNext() {
return e.hasMoreElements();
}
public T next() {
return e.nextElement();
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
public static <T> Enumeration<T> iteratorAsEnumeration(final Iterator<T> it) {
return new Enumeration<T>() {
public boolean hasMoreElements() {
return it.hasNext();
}
public T nextElement() {
return it.next();
}
};
}
}
package com.cloud.utils;
import java.util.Enumeration;
import java.util.Iterator;
public class IteratorUtil {
public static <T> Iterable<T> enumerationAsIterable(final Enumeration<T> e) {
return new Iterable<T> () {
public Iterator<T> iterator() {
return new Iterator<T>() {
public boolean hasNext() {
return e.hasMoreElements();
}
public T next() {
return e.nextElement();
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
public static <T> Enumeration<T> iteratorAsEnumeration(final Iterator<T> it) {
return new Enumeration<T>() {
public boolean hasMoreElements() {
return it.hasNext();
}
public T nextElement() {
return it.next();
}
};
}
}

View File

@ -10,8 +10,8 @@
// limitations under the License.
//
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.utils;
package com.cloud.utils;
import java.nio.ByteBuffer;
import java.text.ParseException;
import java.text.SimpleDateFormat;
@ -19,247 +19,247 @@ import java.util.Date;
import java.util.Formatter;
import com.cloud.utils.exception.CloudRuntimeException;
public class NumbersUtil {
public static long parseLong(String s, long defaultValue) {
if (s == null) {
return defaultValue;
}
try {
return Long.parseLong(s);
} catch (NumberFormatException e) {
return defaultValue;
}
}
public static int parseInt(String s, int defaultValue) {
if (s == null) {
return defaultValue;
}
try {
return Integer.parseInt(s);
} catch (NumberFormatException e) {
return defaultValue;
}
}
public static float parseFloat(String s, float defaultValue) {
if (s == null) {
return defaultValue;
}
try {
return Float.parseFloat(s);
} catch (NumberFormatException e) {
return defaultValue;
}
}
/**
* Converts bytes to short on input.
*/
public static int bytesToShort(byte b[]) {
return (b[1] & 0xff) | ((b[0] << 8) & 0xff00);
}
public static int bytesToShort(byte b[], int pos) {
return (b[pos + 1] & 0xff) | ((b[pos] << 8) & 0xff00);
}
/**
* Converts bytes to long on input.
*/
public static int bytesToInt(byte b[]) {
return bytesToInt(b, 0);
}
public static int bytesToInt(byte b[], int pos) {
int value = b[pos + 3] & 0xff;
value |= (b[pos + 2] << 8) & 0xff00;
value |= (b[pos + 1] << 16) & 0xff0000;
value |= (b[pos] << 24) & 0xff000000;
return value;
}
/**
* Converts a short to a series of bytes for output. Must be 2 bytes long.
*/
public static byte[] shortToBytes(int n) {
byte b[] = new byte[2];
b[1] = (byte) (n & 0xff);
b[0] = (byte) ((n >> 8) & 0xff);
return b;
}
public static char encodeByte(int b) {
if (b < 10) {
return (char) (b + '0');
} else if (b < 36) {
return (char) (b - 10 + 'A');
} else if (b < 62) {
return (char) (b - 36 + 'a');
} else if (b == 62) {
return '(';
} else if (b == 63) {
return ')';
}
return (char) 255;
}
public static int decodeByte(char b) {
if (b >= 'A' && b <= 'Z') {
return b + 10 - 'A';
} else if (b >= 'a' && b <= 'z') {
return b + 36 - 'a';
} else if (b >= '0' && b <= '9') {
return b - '0';
} else if (b == ')') {
return 63;
} else if (b == '(') {
return 62;
}
return -1;
}
/**
* Converts a long to a series of bytes for output. Must be 4 bytes long.
*/
public static byte[] intToBytes(int n) {
byte b[] = new byte[4];
b[3] = (byte) (n & 0xff);
b[2] = (byte) ((n >> 8) & 0xff);
b[1] = (byte) ((n >> 16) & 0xff);
b[0] = (byte) ((n >> 24) & 0xff);
return b;
}
/**
* Sorry for the bad naming but the longToBytes is already taken. Returns an 8 byte long byte array.
**/
public static byte[] longToBytes(long n) {
byte b[] = new byte[8];
b[7] = (byte) (n & 0xff);
b[6] = (byte) ((n >> 8) & 0xff);
b[5] = (byte) ((n >> 16) & 0xff);
b[4] = (byte) ((n >> 24) & 0xff);
b[3] = (byte) ((n >> 32) & 0xff);
b[2] = (byte) ((n >> 40) & 0xff);
b[1] = (byte) ((n >> 48) & 0xff);
b[0] = (byte) ((n >> 56) & 0xff);
return b;
}
/**
* Converts bytes to long on input.
*/
public static long bytesToLong(byte b[]) {
return bytesToLong(b, 0);
}
public static long bytesToLong(byte b[], int pos) {
ByteBuffer buf = ByteBuffer.wrap(b, pos, 8);
return buf.getLong();
/*
* long value = b[pos + 7] & 0xff;
* value |= (b[pos + 6] << 8) & 0xff00;
* value |= (b[pos + 5] << 16) & 0xff0000;
* value |= (b[pos + 4] << 24) & 0xff000000;
* value |= (b[pos + 3] << 32) & 0xff00000000;
* value |= (b[pos + 2] << 40) & 0xff0000000000;
* value |= (b[pos + 1] << 48) & 0xff000000000000;
* value |= (b[pos + 0] << 56) & 0xff00000000000000;
* return value;
*/
}
/**
* Converts a byte array to a hex readable string.
**/
public static String bytesToString(byte[] data, int start, int end) {
StringBuilder buf = new StringBuilder();
if (end > data.length) {
end = data.length;
}
for (int i = start; i < end; i++) {
buf.append(" ");
buf.append(Integer.toHexString(data[i] & 0xff));
}
return buf.toString();
}
protected static final long KB = 1024;
protected static final long MB = 1024 * KB;
protected static final long GB = 1024 * MB;
protected static final long TB = 1024 * GB;
public static String toReadableSize(long bytes) {
if (bytes <= KB && bytes >= 0) {
return Long.toString(bytes) + " bytes";
} else if (bytes <= MB) {
StringBuilder builder = new StringBuilder();
Formatter format = new Formatter(builder);
format.format("%.2f KB", (float)bytes / (float)KB);
return builder.toString();
} else if (bytes <= GB) {
StringBuilder builder = new StringBuilder();
Formatter format = new Formatter(builder);
format.format("%.2f MB", (float)bytes / (float)MB);
return builder.toString();
} else if (bytes <= TB) {
StringBuilder builder = new StringBuilder();
Formatter format = new Formatter(builder);
format.format("%.2f GB", (float)bytes / (float)GB);
return builder.toString();
} else {
StringBuilder builder = new StringBuilder();
Formatter format = new Formatter(builder);
format.format("%.4f TB", (float)bytes / (float)TB);
return builder.toString();
}
}
/**
* Converts a string of the format 'yy-MM-dd'T'HH:mm:ss.SSS" into ms.
*
* @param str containing the interval.
* @param defaultValue value to return if str doesn't parse. If -1, throws VmopsRuntimeException
* @return interval in ms
*/
public static long parseInterval(String str, long defaultValue) {
SimpleDateFormat sdf = null;
if (str.contains("D")) {
sdf = new SimpleDateFormat("dd'D'HH'h'mm'M'ss'S'SSS'ms'");
} else if (str.contains("h")) {
sdf = new SimpleDateFormat("HH'h'mm'M'ss'S'SSS'ms'");
} else if (str.contains("M")) {
sdf = new SimpleDateFormat("mm'M'ss'S'SSS'ms'");
} else if (str.contains("S")) {
sdf = new SimpleDateFormat("ss'S'SSS'ms'");
} else if (str.contains("ms")) {
sdf = new SimpleDateFormat("SSS'ms'");
}
Date date;
try {
if (str == null || sdf == null) {
throw new ParseException("String is wrong", 0);
}
date = sdf.parse(str);
return date.getTime();
} catch (ParseException e) {
if (defaultValue != -1) {
return defaultValue;
} else {
throw new CloudRuntimeException("Unable to parse: " + str, e);
}
}
public class NumbersUtil {
public static long parseLong(String s, long defaultValue) {
if (s == null) {
return defaultValue;
}
try {
return Long.parseLong(s);
} catch (NumberFormatException e) {
return defaultValue;
}
}
public static int parseInt(String s, int defaultValue) {
if (s == null) {
return defaultValue;
}
try {
return Integer.parseInt(s);
} catch (NumberFormatException e) {
return defaultValue;
}
}
public static float parseFloat(String s, float defaultValue) {
if (s == null) {
return defaultValue;
}
try {
return Float.parseFloat(s);
} catch (NumberFormatException e) {
return defaultValue;
}
}
/**
* Converts bytes to short on input.
*/
public static int bytesToShort(byte b[]) {
return (b[1] & 0xff) | ((b[0] << 8) & 0xff00);
}
public static int bytesToShort(byte b[], int pos) {
return (b[pos + 1] & 0xff) | ((b[pos] << 8) & 0xff00);
}
/**
* Converts bytes to long on input.
*/
public static int bytesToInt(byte b[]) {
return bytesToInt(b, 0);
}
public static int bytesToInt(byte b[], int pos) {
int value = b[pos + 3] & 0xff;
value |= (b[pos + 2] << 8) & 0xff00;
value |= (b[pos + 1] << 16) & 0xff0000;
value |= (b[pos] << 24) & 0xff000000;
return value;
}
/**
* Converts a short to a series of bytes for output. Must be 2 bytes long.
*/
public static byte[] shortToBytes(int n) {
byte b[] = new byte[2];
b[1] = (byte) (n & 0xff);
b[0] = (byte) ((n >> 8) & 0xff);
return b;
}
public static char encodeByte(int b) {
if (b < 10) {
return (char) (b + '0');
} else if (b < 36) {
return (char) (b - 10 + 'A');
} else if (b < 62) {
return (char) (b - 36 + 'a');
} else if (b == 62) {
return '(';
} else if (b == 63) {
return ')';
}
return (char) 255;
}
public static int decodeByte(char b) {
if (b >= 'A' && b <= 'Z') {
return b + 10 - 'A';
} else if (b >= 'a' && b <= 'z') {
return b + 36 - 'a';
} else if (b >= '0' && b <= '9') {
return b - '0';
} else if (b == ')') {
return 63;
} else if (b == '(') {
return 62;
}
return -1;
}
/**
* Converts a long to a series of bytes for output. Must be 4 bytes long.
*/
public static byte[] intToBytes(int n) {
byte b[] = new byte[4];
b[3] = (byte) (n & 0xff);
b[2] = (byte) ((n >> 8) & 0xff);
b[1] = (byte) ((n >> 16) & 0xff);
b[0] = (byte) ((n >> 24) & 0xff);
return b;
}
/**
* Sorry for the bad naming but the longToBytes is already taken. Returns an 8 byte long byte array.
**/
public static byte[] longToBytes(long n) {
byte b[] = new byte[8];
b[7] = (byte) (n & 0xff);
b[6] = (byte) ((n >> 8) & 0xff);
b[5] = (byte) ((n >> 16) & 0xff);
b[4] = (byte) ((n >> 24) & 0xff);
b[3] = (byte) ((n >> 32) & 0xff);
b[2] = (byte) ((n >> 40) & 0xff);
b[1] = (byte) ((n >> 48) & 0xff);
b[0] = (byte) ((n >> 56) & 0xff);
return b;
}
/**
* Converts bytes to long on input.
*/
public static long bytesToLong(byte b[]) {
return bytesToLong(b, 0);
}
public static long bytesToLong(byte b[], int pos) {
ByteBuffer buf = ByteBuffer.wrap(b, pos, 8);
return buf.getLong();
/*
* long value = b[pos + 7] & 0xff;
* value |= (b[pos + 6] << 8) & 0xff00;
* value |= (b[pos + 5] << 16) & 0xff0000;
* value |= (b[pos + 4] << 24) & 0xff000000;
* value |= (b[pos + 3] << 32) & 0xff00000000;
* value |= (b[pos + 2] << 40) & 0xff0000000000;
* value |= (b[pos + 1] << 48) & 0xff000000000000;
* value |= (b[pos + 0] << 56) & 0xff00000000000000;
* return value;
*/
}
/**
* Converts a byte array to a hex readable string.
**/
public static String bytesToString(byte[] data, int start, int end) {
StringBuilder buf = new StringBuilder();
if (end > data.length) {
end = data.length;
}
for (int i = start; i < end; i++) {
buf.append(" ");
buf.append(Integer.toHexString(data[i] & 0xff));
}
return buf.toString();
}
protected static final long KB = 1024;
protected static final long MB = 1024 * KB;
protected static final long GB = 1024 * MB;
protected static final long TB = 1024 * GB;
public static String toReadableSize(long bytes) {
if (bytes <= KB && bytes >= 0) {
return Long.toString(bytes) + " bytes";
} else if (bytes <= MB) {
StringBuilder builder = new StringBuilder();
Formatter format = new Formatter(builder);
format.format("%.2f KB", (float)bytes / (float)KB);
return builder.toString();
} else if (bytes <= GB) {
StringBuilder builder = new StringBuilder();
Formatter format = new Formatter(builder);
format.format("%.2f MB", (float)bytes / (float)MB);
return builder.toString();
} else if (bytes <= TB) {
StringBuilder builder = new StringBuilder();
Formatter format = new Formatter(builder);
format.format("%.2f GB", (float)bytes / (float)GB);
return builder.toString();
} else {
StringBuilder builder = new StringBuilder();
Formatter format = new Formatter(builder);
format.format("%.4f TB", (float)bytes / (float)TB);
return builder.toString();
}
}
/**
* Converts a string of the format 'yy-MM-dd'T'HH:mm:ss.SSS" into ms.
*
* @param str containing the interval.
* @param defaultValue value to return if str doesn't parse. If -1, throws VmopsRuntimeException
* @return interval in ms
*/
public static long parseInterval(String str, long defaultValue) {
SimpleDateFormat sdf = null;
if (str.contains("D")) {
sdf = new SimpleDateFormat("dd'D'HH'h'mm'M'ss'S'SSS'ms'");
} else if (str.contains("h")) {
sdf = new SimpleDateFormat("HH'h'mm'M'ss'S'SSS'ms'");
} else if (str.contains("M")) {
sdf = new SimpleDateFormat("mm'M'ss'S'SSS'ms'");
} else if (str.contains("S")) {
sdf = new SimpleDateFormat("ss'S'SSS'ms'");
} else if (str.contains("ms")) {
sdf = new SimpleDateFormat("SSS'ms'");
}
Date date;
try {
if (str == null || sdf == null) {
throw new ParseException("String is wrong", 0);
}
date = sdf.parse(str);
return date.getTime();
} catch (ParseException e) {
if (defaultValue != -1) {
return defaultValue;
} else {
throw new CloudRuntimeException("Unable to parse: " + str, e);
}
}
}
public static int hash(long value) {
return (int)(value^(value>>>32));
}
public static void main(String[] args) {
long interval = parseInterval(args[0], -1);
System.out.println(args[0] + " is " + interval);
}
}
}
public static void main(String[] args) {
long interval = parseInterval(args[0], -1);
System.out.println(args[0] + " is " + interval);
}
}

View File

@ -10,99 +10,99 @@
// limitations under the License.
//
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.naming.ConfigurationException;
import org.apache.log4j.Logger;
package com.cloud.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.naming.ConfigurationException;
import org.apache.log4j.Logger;
import com.cloud.utils.PropertiesUtil;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.script.OutputInterpreter;
import com.cloud.utils.script.Script;
import java.util.Properties;
public class ProcessUtil {
private static final Logger s_logger = Logger.getLogger(ProcessUtil.class.getName());
// paths cannot be hardcoded
public static void pidCheck(String pidDir, String run) throws ConfigurationException {
String dir = pidDir==null?"/var/run":pidDir;
try {
final File propsFile = PropertiesUtil.findConfigFile("environment.properties");
if (propsFile == null) {
s_logger.debug("environment.properties could not be opened");
}
else {
final FileInputStream finputstream = new FileInputStream(propsFile);
final Properties props = new Properties();
props.load(finputstream);
finputstream.close();
dir = props.getProperty("paths.pid");
if (dir == null) {
dir = "/var/run";
}
}
} catch (IOException e) {
s_logger.debug("environment.properties could not be opened");
}
final File pidFile = new File(dir + File.separator + run);
try {
if (!pidFile.createNewFile()) {
if (!pidFile.exists()) {
throw new ConfigurationException("Unable to write to " + pidFile.getAbsolutePath() + ". Are you sure you're running as root?");
}
final FileInputStream is = new FileInputStream(pidFile);
final BufferedReader reader = new BufferedReader(new InputStreamReader(is));
final String pidLine = reader.readLine();
if (pidLine == null) {
throw new ConfigurationException("Java process is being started twice. If this is not true, remove " + pidFile.getAbsolutePath());
}
try {
final long pid = Long.parseLong(pidLine);
final Script script = new Script("bash", 120000, s_logger);
script.add("-c", "ps -p " + pid);
final String result = script.execute();
if (result == null) {
throw new ConfigurationException("Java process is being started twice. If this is not true, remove " + pidFile.getAbsolutePath());
}
if (!pidFile.delete()) {
throw new ConfigurationException("Java process is being started twice. If this is not true, remove " + pidFile.getAbsolutePath());
}
if (!pidFile.createNewFile()) {
throw new ConfigurationException("Java process is being started twice. If this is not true, remove " + pidFile.getAbsolutePath());
}
} catch (final NumberFormatException e) {
throw new ConfigurationException("Java process is being started twice. If this is not true, remove " + pidFile.getAbsolutePath());
}
}
pidFile.deleteOnExit();
final Script script = new Script("bash", 120000, s_logger);
script.add("-c", "echo $PPID");
final OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser();
script.execute(parser);
final String pid = parser.getLine();
final FileOutputStream strm = new FileOutputStream(pidFile);
strm.write((pid + "\n").getBytes());
strm.close();
} catch (final IOException e) {
throw new CloudRuntimeException("Unable to create the " + pidFile.getAbsolutePath() + ". Are you running as root?", e);
}
import java.util.Properties;
public class ProcessUtil {
private static final Logger s_logger = Logger.getLogger(ProcessUtil.class.getName());
// paths cannot be hardcoded
public static void pidCheck(String pidDir, String run) throws ConfigurationException {
String dir = pidDir==null?"/var/run":pidDir;
try {
final File propsFile = PropertiesUtil.findConfigFile("environment.properties");
if (propsFile == null) {
s_logger.debug("environment.properties could not be opened");
}
else {
final FileInputStream finputstream = new FileInputStream(propsFile);
final Properties props = new Properties();
props.load(finputstream);
finputstream.close();
dir = props.getProperty("paths.pid");
if (dir == null) {
dir = "/var/run";
}
}
} catch (IOException e) {
s_logger.debug("environment.properties could not be opened");
}
final File pidFile = new File(dir + File.separator + run);
try {
if (!pidFile.createNewFile()) {
if (!pidFile.exists()) {
throw new ConfigurationException("Unable to write to " + pidFile.getAbsolutePath() + ". Are you sure you're running as root?");
}
final FileInputStream is = new FileInputStream(pidFile);
final BufferedReader reader = new BufferedReader(new InputStreamReader(is));
final String pidLine = reader.readLine();
if (pidLine == null) {
throw new ConfigurationException("Java process is being started twice. If this is not true, remove " + pidFile.getAbsolutePath());
}
try {
final long pid = Long.parseLong(pidLine);
final Script script = new Script("bash", 120000, s_logger);
script.add("-c", "ps -p " + pid);
final String result = script.execute();
if (result == null) {
throw new ConfigurationException("Java process is being started twice. If this is not true, remove " + pidFile.getAbsolutePath());
}
if (!pidFile.delete()) {
throw new ConfigurationException("Java process is being started twice. If this is not true, remove " + pidFile.getAbsolutePath());
}
if (!pidFile.createNewFile()) {
throw new ConfigurationException("Java process is being started twice. If this is not true, remove " + pidFile.getAbsolutePath());
}
} catch (final NumberFormatException e) {
throw new ConfigurationException("Java process is being started twice. If this is not true, remove " + pidFile.getAbsolutePath());
}
}
pidFile.deleteOnExit();
final Script script = new Script("bash", 120000, s_logger);
script.add("-c", "echo $PPID");
final OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser();
script.execute(parser);
final String pid = parser.getLine();
final FileOutputStream strm = new FileOutputStream(pidFile);
strm.write((pid + "\n").getBytes());
strm.close();
} catch (final IOException e) {
throw new CloudRuntimeException("Unable to create the " + pidFile.getAbsolutePath() + ". Are you running as root?", e);
}
}
public static String dumpStack() {
@ -114,5 +114,5 @@ public class ProcessUtil {
}
}
return sb.toString();
}
}
}
}

View File

@ -10,32 +10,32 @@
// limitations under the License.
//
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.utils;
public class Profiler {
private Long startTickInMs;
private Long stopTickInMs;
public Profiler() {
startTickInMs = null;
stopTickInMs = null;
}
public long start() {
startTickInMs = System.currentTimeMillis();
return startTickInMs.longValue();
}
public long stop() {
stopTickInMs = System.currentTimeMillis();
return stopTickInMs.longValue();
}
package com.cloud.utils;
public class Profiler {
private Long startTickInMs;
private Long stopTickInMs;
public Profiler() {
startTickInMs = null;
stopTickInMs = null;
}
public long start() {
startTickInMs = System.currentTimeMillis();
return startTickInMs.longValue();
}
public long stop() {
stopTickInMs = System.currentTimeMillis();
return stopTickInMs.longValue();
}
public long getDuration() {
if(startTickInMs != null && stopTickInMs != null)
if(startTickInMs != null && stopTickInMs != null)
return stopTickInMs.longValue() - startTickInMs.longValue();
return -1;
return -1;
}
public boolean isStarted() {
@ -55,4 +55,4 @@ public class Profiler {
return "Done. Duration: " + getDuration() + "ms";
}
}
}

View File

@ -10,39 +10,39 @@
// limitations under the License.
//
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.utils;
/**
* purposes. This is purely on an honor system though. You should always
**/
public interface SerialVersionUID {
public static final long Base = 0x564D4F70 << 32; // 100 brownie points if you guess what this is and tell me.
public static final long UUID = Base | 0x1;
public static final long CloudRuntimeException = Base | 0x2;
public static final long CloudStartupServlet = Base | 0x3;
package com.cloud.utils;
/**
* purposes. This is purely on an honor system though. You should always
**/
public interface SerialVersionUID {
public static final long Base = 0x564D4F70 << 32; // 100 brownie points if you guess what this is and tell me.
public static final long UUID = Base | 0x1;
public static final long CloudRuntimeException = Base | 0x2;
public static final long CloudStartupServlet = Base | 0x3;
public static final long CloudServiceImpl = Base | 0x4;
public static final long AccountLimitException = Base | 0x5;
public static final long InsufficientVirtualNetworkCapacityException = Base | 0x7;
public static final long NetworkUnavailableException = Base | 0x8;
public static final long Ip = Base | 0x9;
public static final long UnsupportedVersionException = Base | 0xb;
public static final long DataCenterIpAddressPK = Base | 0xc;
public static final long UnableToExecuteException = Base | 0xd;
public static final long ExecutionException = Base | 0xe;
public static final long VnetKey = Base | 0xf;
public static final long InsufficientServerCapacityException = Base | 0x10;
public static final long InsufficientAddressCapacityException = Base | 0x11;
public static final long ManagementServerException = Base | 0x12;
public static final long HAStateException = Base | 0x13;
public static final long InsufficientStorageCapacityException = Base | 0x14;
public static final long InsufficientCapacityException = Base | 0x15;
public static final long ConcurrentOperationException = Base | 0x16;
public static final long AgentUnavailableException = Base | 0x17;
public static final long OperationTimedoutException = Base | 0x18;
public static final long StorageUnavailableException = Base | 0x19;
public static final long UnsupportedVersionException = Base | 0xb;
public static final long DataCenterIpAddressPK = Base | 0xc;
public static final long UnableToExecuteException = Base | 0xd;
public static final long ExecutionException = Base | 0xe;
public static final long VnetKey = Base | 0xf;
public static final long InsufficientServerCapacityException = Base | 0x10;
public static final long InsufficientAddressCapacityException = Base | 0x11;
public static final long ManagementServerException = Base | 0x12;
public static final long HAStateException = Base | 0x13;
public static final long InsufficientStorageCapacityException = Base | 0x14;
public static final long InsufficientCapacityException = Base | 0x15;
public static final long ConcurrentOperationException = Base | 0x16;
public static final long AgentUnavailableException = Base | 0x17;
public static final long OperationTimedoutException = Base | 0x18;
public static final long StorageUnavailableException = Base | 0x19;
public static final long InfficientVirtualNetworkCapacityException = Base | 0x1a;
public static final long DiscoveryException = Base | 0x1b;
public static final long DiscoveryException = Base | 0x1b;
public static final long ConflictingNetworkSettingException = Base | 0x1c;
public static final long CloudAuthenticationException = Base | 0x1d;
public static final long AsyncCommandQueued = Base | 0x1e;
@ -57,4 +57,4 @@ public interface SerialVersionUID {
public static final long CloudExecutionException = Base | 0x27;
public static final long CallFailedException = Base | 0x28;
public static final long UnableDeleteHostException = Base | 0x29;
}
}

View File

@ -10,33 +10,33 @@
// limitations under the License.
//
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.utils;
package com.cloud.utils;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
// StringUtils exists in Apache Commons Lang, but rather than import the entire JAR to our system, for now
// just implement the method needed
// StringUtils exists in Apache Commons Lang, but rather than import the entire JAR to our system, for now
// just implement the method needed
public class StringUtils {
private static final char[] hexChar = {
'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'
};
public static String join(Iterable<? extends Object> iterable, String delim) {
StringBuilder sb = new StringBuilder();
if (iterable != null) {
Iterator<? extends Object> iter = iterable.iterator();
if (iter.hasNext()) {
Object next = iter.next();
sb.append(next.toString());
}
while (iter.hasNext()) {
Object next = iter.next();
sb.append(delim + next.toString());
}
}
return sb.toString();
public static String join(Iterable<? extends Object> iterable, String delim) {
StringBuilder sb = new StringBuilder();
if (iterable != null) {
Iterator<? extends Object> iter = iterable.iterator();
if (iter.hasNext()) {
Object next = iter.next();
sb.append(next.toString());
}
while (iter.hasNext()) {
Object next = iter.next();
sb.append(delim + next.toString());
}
}
return sb.toString();
}
@ -124,4 +124,4 @@ public class StringUtils {
return sb.toString();
}
}
}

View File

@ -10,73 +10,73 @@
// limitations under the License.
//
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.utils.concurrency;
import org.apache.log4j.Logger;
public class SynchronizationEvent {
protected final static Logger s_logger = Logger.getLogger(SynchronizationEvent.class);
private boolean signalled;
public SynchronizationEvent() {
signalled = false;
}
public SynchronizationEvent(boolean signalled) {
this.signalled = signalled;
}
public void setEvent() {
synchronized(this) {
signalled = true;
notifyAll();
}
}
public void resetEvent() {
synchronized(this) {
signalled = false;
}
}
public boolean waitEvent() throws InterruptedException {
synchronized(this) {
if(signalled)
return true;
while(true) {
try {
wait();
assert(signalled);
return signalled;
} catch (InterruptedException e) {
s_logger.debug("unexpected awaken signal in wait()");
throw e;
}
}
}
}
public boolean waitEvent(long timeOutMiliseconds) throws InterruptedException {
synchronized(this) {
if(signalled)
return true;
try {
wait(timeOutMiliseconds);
return signalled;
} catch (InterruptedException e) {
// TODO, we don't honor time out semantics when the waiting thread is interrupted
s_logger.debug("unexpected awaken signal in wait(...)");
throw e;
}
}
}
public boolean isSignalled() {
synchronized(this) {
return signalled;
}
}
}
package com.cloud.utils.concurrency;
import org.apache.log4j.Logger;
public class SynchronizationEvent {
protected final static Logger s_logger = Logger.getLogger(SynchronizationEvent.class);
private boolean signalled;
public SynchronizationEvent() {
signalled = false;
}
public SynchronizationEvent(boolean signalled) {
this.signalled = signalled;
}
public void setEvent() {
synchronized(this) {
signalled = true;
notifyAll();
}
}
public void resetEvent() {
synchronized(this) {
signalled = false;
}
}
public boolean waitEvent() throws InterruptedException {
synchronized(this) {
if(signalled)
return true;
while(true) {
try {
wait();
assert(signalled);
return signalled;
} catch (InterruptedException e) {
s_logger.debug("unexpected awaken signal in wait()");
throw e;
}
}
}
}
public boolean waitEvent(long timeOutMiliseconds) throws InterruptedException {
synchronized(this) {
if(signalled)
return true;
try {
wait(timeOutMiliseconds);
return signalled;
} catch (InterruptedException e) {
// TODO, we don't honor time out semantics when the waiting thread is interrupted
s_logger.debug("unexpected awaken signal in wait(...)");
throw e;
}
}
}
public boolean isSignalled() {
synchronized(this) {
return signalled;
}
}
}

View File

@ -10,91 +10,91 @@
// limitations under the License.
//
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.utils.db;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
package com.cloud.utils.db;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
import com.cloud.utils.Profiler;
//
// Wrapper class for global database lock to reduce contention for database connections from within process
//
// Example of using dynamic named locks
//
// GlobalLock lock = GlobalLock.getInternLock("some table name" + rowId);
//
// if(lock.lock()) {
// try {
// do something
// } finally {
// lock.unlock();
// }
// }
// lock.releaseRef();
//
public class GlobalLock {
protected final static Logger s_logger = Logger.getLogger(GlobalLock.class);
private String name;
private int lockCount = 0;
private Thread ownerThread = null;
//
// Wrapper class for global database lock to reduce contention for database connections from within process
//
// Example of using dynamic named locks
//
// GlobalLock lock = GlobalLock.getInternLock("some table name" + rowId);
//
// if(lock.lock()) {
// try {
// do something
// } finally {
// lock.unlock();
// }
// }
// lock.releaseRef();
//
public class GlobalLock {
protected final static Logger s_logger = Logger.getLogger(GlobalLock.class);
private String name;
private int lockCount = 0;
private Thread ownerThread = null;
private int referenceCount = 0;
private long holdingStartTick = 0;
private static Map<String, GlobalLock> s_lockMap = new HashMap<String, GlobalLock>();
private GlobalLock(String name) {
this.name = name;
}
public int addRef() {
synchronized(this) {
referenceCount++;
return referenceCount;
}
}
public int releaseRef() {
private int referenceCount = 0;
private long holdingStartTick = 0;
private static Map<String, GlobalLock> s_lockMap = new HashMap<String, GlobalLock>();
private GlobalLock(String name) {
this.name = name;
}
public int addRef() {
synchronized(this) {
referenceCount++;
return referenceCount;
}
}
public int releaseRef() {
int refCount;
boolean needToRemove = false;
synchronized(this) {
referenceCount--;
refCount = referenceCount;
if(referenceCount < 0)
s_logger.warn("Unmatched Global lock " + name + " reference usage detected, check your code!");
synchronized(this) {
referenceCount--;
refCount = referenceCount;
if(referenceCount < 0)
s_logger.warn("Unmatched Global lock " + name + " reference usage detected, check your code!");
if(referenceCount == 0)
needToRemove = true;
needToRemove = true;
}
if(needToRemove)
releaseInternLock(name);
return refCount;
}
return refCount;
}
public static GlobalLock getInternLock(String name) {
synchronized(s_lockMap) {
if(s_lockMap.containsKey(name)) {
GlobalLock lock = s_lockMap.get(name);
lock.addRef();
return lock;
} else {
GlobalLock lock = new GlobalLock(name);
lock.addRef();
s_lockMap.put(name, lock);
return lock;
}
}
}
private static void releaseInternLock(String name) {
public static GlobalLock getInternLock(String name) {
synchronized(s_lockMap) {
if(s_lockMap.containsKey(name)) {
GlobalLock lock = s_lockMap.get(name);
lock.addRef();
return lock;
} else {
GlobalLock lock = new GlobalLock(name);
lock.addRef();
s_lockMap.put(name, lock);
return lock;
}
}
}
private static void releaseInternLock(String name) {
synchronized(s_lockMap) {
GlobalLock lock = s_lockMap.get(name);
if(lock != null) {
@ -103,45 +103,45 @@ public class GlobalLock {
} else {
s_logger.warn("Releasing " + name + ", but it is already released.");
}
}
}
public boolean lock(int timeoutSeconds) {
int remainingMilliSeconds = timeoutSeconds*1000;
Profiler profiler = new Profiler();
boolean interrupted = false;
try {
while(true) {
synchronized(this) {
if(ownerThread != null && ownerThread == Thread.currentThread()) {
s_logger.warn("Global lock re-entrance detected");
lockCount++;
if(s_logger.isTraceEnabled())
s_logger.trace("lock " + name + " is acquired, lock count :" + lockCount);
return true;
}
if(ownerThread != null) {
profiler.start();
try {
wait(((long)timeoutSeconds)*1000L);
} catch (InterruptedException e) {
interrupted = true;
}
profiler.stop();
remainingMilliSeconds -= profiler.getDuration();
if(remainingMilliSeconds < 0)
return false;
continue;
}
}
public boolean lock(int timeoutSeconds) {
int remainingMilliSeconds = timeoutSeconds*1000;
Profiler profiler = new Profiler();
boolean interrupted = false;
try {
while(true) {
synchronized(this) {
if(ownerThread != null && ownerThread == Thread.currentThread()) {
s_logger.warn("Global lock re-entrance detected");
lockCount++;
if(s_logger.isTraceEnabled())
s_logger.trace("lock " + name + " is acquired, lock count :" + lockCount);
return true;
}
if(ownerThread != null) {
profiler.start();
try {
wait(((long)timeoutSeconds)*1000L);
} catch (InterruptedException e) {
interrupted = true;
}
profiler.stop();
remainingMilliSeconds -= profiler.getDuration();
if(remainingMilliSeconds < 0)
return false;
continue;
} else {
// take ownership temporarily to prevent others enter into stage of acquiring DB lock
// take ownership temporarily to prevent others enter into stage of acquiring DB lock
ownerThread = Thread.currentThread();
addRef();
}
}
}
if(DbUtil.getGlobalLock(name, remainingMilliSeconds / 1000)) {
@ -160,41 +160,41 @@ public class GlobalLock {
return false;
}
}
}
} finally {
if(interrupted) {
Thread.currentThread().interrupt();
}
}
}
public boolean unlock() {
synchronized(this) {
if(ownerThread != null && ownerThread == Thread.currentThread()) {
lockCount--;
if(lockCount == 0) {
ownerThread = null;
DbUtil.releaseGlobalLock(name);
if(s_logger.isTraceEnabled())
s_logger.trace("lock " + name + " is returned to free state, total holding time :" +
(System.currentTimeMillis() - holdingStartTick));
holdingStartTick = 0;
// release holding position in intern map when we released the DB connection
releaseRef();
notifyAll();
}
if(s_logger.isTraceEnabled())
s_logger.trace("lock " + name + " is released, lock count :" + lockCount);
return true;
}
return false;
}
}
public String getName() {
return name;
}
}
}
} finally {
if(interrupted) {
Thread.currentThread().interrupt();
}
}
}
public boolean unlock() {
synchronized(this) {
if(ownerThread != null && ownerThread == Thread.currentThread()) {
lockCount--;
if(lockCount == 0) {
ownerThread = null;
DbUtil.releaseGlobalLock(name);
if(s_logger.isTraceEnabled())
s_logger.trace("lock " + name + " is returned to free state, total holding time :" +
(System.currentTimeMillis() - holdingStartTick));
holdingStartTick = 0;
// release holding position in intern map when we released the DB connection
releaseRef();
notifyAll();
}
if(s_logger.isTraceEnabled())
s_logger.trace("lock " + name + " is released, lock count :" + lockCount);
return true;
}
return false;
}
}
public String getName() {
return name;
}
}

View File

@ -10,200 +10,200 @@
// limitations under the License.
//
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.utils.db;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.persistence.Transient;
import net.sf.cglib.proxy.Factory;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import com.cloud.utils.db.GenericSearchBuilder.Condition;
import com.cloud.utils.db.GenericSearchBuilder.Select;
import com.cloud.utils.db.SearchCriteria.Func;
import com.cloud.utils.db.SearchCriteria.Op;
import com.cloud.utils.db.SearchCriteria.SelectType;
public class SearchCriteria2<T, K> implements SearchCriteriaService<T, K>, MethodInterceptor{
GenericDao<? extends Serializable, ? extends Serializable> _dao;
final protected Map<String, Attribute> _attrs;
protected ArrayList<Attribute> _specifiedAttrs;
protected T _entity;
protected ArrayList<GenericSearchBuilder.Condition> _conditions;
protected ArrayList<Select> _selects;
private final HashMap<String, Object[]> _params = new HashMap<String, Object[]>();
protected Class<K> _resultType;
protected SelectType _selectType;
protected Class<T> _entityBeanType;
protected SearchCriteria2(T entity, Class<K> resultType, final Map<String, Attribute> attrs, GenericDao<? extends Serializable, ? extends Serializable> dao) {
_entityBeanType = (Class<T>)entity.getClass();
_dao = dao;
_resultType = resultType;
_attrs = attrs;
_entity = entity;
_conditions = new ArrayList<Condition>();
_specifiedAttrs = new ArrayList<Attribute>();
}
static public <T, K> SearchCriteria2<T, K> create(Class<T> entityType, Class<K> resultType) {
GenericDao<? extends Serializable, ? extends Serializable> dao = (GenericDao<? extends Serializable, ? extends Serializable>)GenericDaoBase.getDao(entityType);
assert dao != null : "Can not find DAO for " + entityType.getName();
SearchCriteria2<T, K> sc = dao.createSearchCriteria2(resultType);
return sc;
}
static public <T, K> SearchCriteria2<T, K> create(Class<T> entityType) {
GenericDao<? extends Serializable, ? extends Serializable> dao = (GenericDao<? extends Serializable, ? extends Serializable>)GenericDaoBase.getDao(entityType);
assert dao != null : "Can not find DAO for " + entityType.getName();
SearchCriteria2<T, K> sc = dao.createSearchCriteria2();
return sc;
}
@Override
public void selectField(Object... useless) {
assert _entity != null : "SearchBuilder cannot be modified once it has been setup";
assert _specifiedAttrs.size() > 0 : "You didn't specify any attributes";
if (_selects == null) {
_selects = new ArrayList<Select>();
}
for (Attribute attr : _specifiedAttrs) {
Field field = null;
try {
field = _resultType.getDeclaredField(attr.field.getName());
field.setAccessible(true);
} catch (SecurityException e) {
} catch (NoSuchFieldException e) {
}
_selects.add(new Select(Func.NATIVE, attr, field, null));
}
_specifiedAttrs.clear();
}
private void constructCondition(String conditionName, String cond, Attribute attr, Op op) {
assert _entity != null : "SearchBuilder cannot be modified once it has been setup";
assert op == null || _specifiedAttrs.size() == 1 : "You didn't select the attribute.";
assert op != Op.SC : "Call join";
GenericSearchBuilder.Condition condition = new GenericSearchBuilder.Condition(conditionName, cond, attr, op);
_conditions.add(condition);
_specifiedAttrs.clear();
}
private void setParameters(String conditionName, Object... params) {
assert _conditions.contains(new Condition(conditionName)) : "Couldn't find " + conditionName;
_params.put(conditionName, params);
}
@Override
public void addAnd(Object useless, Op op, Object...values) {
String uuid = UUID.randomUUID().toString();
constructCondition(uuid, " AND ", _specifiedAttrs.get(0), op);
setParameters(uuid, values);
}
@Override
public List<K> list() {
done();
SearchCriteria sc1 = createSearchCriteria();
if (isSelectAll()) {
return (List<K>)_dao.search(sc1, null);
} else {
return (List<K>)_dao.customSearch(sc1, null);
}
}
private boolean isSelectAll() {
return _selects == null || _selects.size() == 0;
}
@Override
public T getEntity() {
return (T) _entity;
}
private SearchCriteria<K> createSearchCriteria() {
return new SearchCriteria<K>(_attrs, _conditions, _selects, _selectType, _resultType, _params);
}
private void set(String name) {
Attribute attr = _attrs.get(name);
assert (attr != null) : "Searching for a field that's not there: " + name;
_specifiedAttrs.add(attr);
}
private void done() {
if (_entity != null) {
Factory factory = (Factory)_entity;
factory.setCallback(0, null);
_entity = null;
}
if (_selects == null || _selects.size() == 0) {
_selectType = SelectType.Entity;
assert _entityBeanType.equals(_resultType) : "Expecting " + _entityBeanType + " because you didn't specify any selects but instead got " + _resultType;
return;
}
for (Select select : _selects) {
if (select.field == null) {
assert (_selects.size() == 1) : "You didn't specify any fields to put the result in but you're specifying more than one select so where should I put the selects?";
_selectType = SelectType.Single;
return;
}
if (select.func != null) {
_selectType = SelectType.Result;
return;
}
}
_selectType = SelectType.Fields;
}
@Override
public Object intercept(Object object, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
String name = method.getName();
if (method.getAnnotation(Transient.class) == null) {
if (name.startsWith("get")) {
String fieldName = Character.toLowerCase(name.charAt(3)) + name.substring(4);
set(fieldName);
return null;
} else if (name.startsWith("is")) {
String fieldName = Character.toLowerCase(name.charAt(2)) + name.substring(3);
set(fieldName);
return null;
} else {
name = name.toLowerCase();
for (String fieldName : _attrs.keySet()) {
if (name.endsWith(fieldName.toLowerCase())) {
set(fieldName);
return null;
}
}
assert false : "Perhaps you need to make the method start with get or is?";
}
}
return methodProxy.invokeSuper(object, args);
}
@Override
public <K> K find() {
assert isSelectAll() : "find doesn't support select search";
done();
SearchCriteria sc1 = createSearchCriteria();
return (K)_dao.findOneBy(sc1);
}
}
package com.cloud.utils.db;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.persistence.Transient;
import net.sf.cglib.proxy.Factory;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import com.cloud.utils.db.GenericSearchBuilder.Condition;
import com.cloud.utils.db.GenericSearchBuilder.Select;
import com.cloud.utils.db.SearchCriteria.Func;
import com.cloud.utils.db.SearchCriteria.Op;
import com.cloud.utils.db.SearchCriteria.SelectType;
public class SearchCriteria2<T, K> implements SearchCriteriaService<T, K>, MethodInterceptor{
GenericDao<? extends Serializable, ? extends Serializable> _dao;
final protected Map<String, Attribute> _attrs;
protected ArrayList<Attribute> _specifiedAttrs;
protected T _entity;
protected ArrayList<GenericSearchBuilder.Condition> _conditions;
protected ArrayList<Select> _selects;
private final HashMap<String, Object[]> _params = new HashMap<String, Object[]>();
protected Class<K> _resultType;
protected SelectType _selectType;
protected Class<T> _entityBeanType;
protected SearchCriteria2(T entity, Class<K> resultType, final Map<String, Attribute> attrs, GenericDao<? extends Serializable, ? extends Serializable> dao) {
_entityBeanType = (Class<T>)entity.getClass();
_dao = dao;
_resultType = resultType;
_attrs = attrs;
_entity = entity;
_conditions = new ArrayList<Condition>();
_specifiedAttrs = new ArrayList<Attribute>();
}
static public <T, K> SearchCriteria2<T, K> create(Class<T> entityType, Class<K> resultType) {
GenericDao<? extends Serializable, ? extends Serializable> dao = (GenericDao<? extends Serializable, ? extends Serializable>)GenericDaoBase.getDao(entityType);
assert dao != null : "Can not find DAO for " + entityType.getName();
SearchCriteria2<T, K> sc = dao.createSearchCriteria2(resultType);
return sc;
}
static public <T, K> SearchCriteria2<T, K> create(Class<T> entityType) {
GenericDao<? extends Serializable, ? extends Serializable> dao = (GenericDao<? extends Serializable, ? extends Serializable>)GenericDaoBase.getDao(entityType);
assert dao != null : "Can not find DAO for " + entityType.getName();
SearchCriteria2<T, K> sc = dao.createSearchCriteria2();
return sc;
}
@Override
public void selectField(Object... useless) {
assert _entity != null : "SearchBuilder cannot be modified once it has been setup";
assert _specifiedAttrs.size() > 0 : "You didn't specify any attributes";
if (_selects == null) {
_selects = new ArrayList<Select>();
}
for (Attribute attr : _specifiedAttrs) {
Field field = null;
try {
field = _resultType.getDeclaredField(attr.field.getName());
field.setAccessible(true);
} catch (SecurityException e) {
} catch (NoSuchFieldException e) {
}
_selects.add(new Select(Func.NATIVE, attr, field, null));
}
_specifiedAttrs.clear();
}
private void constructCondition(String conditionName, String cond, Attribute attr, Op op) {
assert _entity != null : "SearchBuilder cannot be modified once it has been setup";
assert op == null || _specifiedAttrs.size() == 1 : "You didn't select the attribute.";
assert op != Op.SC : "Call join";
GenericSearchBuilder.Condition condition = new GenericSearchBuilder.Condition(conditionName, cond, attr, op);
_conditions.add(condition);
_specifiedAttrs.clear();
}
private void setParameters(String conditionName, Object... params) {
assert _conditions.contains(new Condition(conditionName)) : "Couldn't find " + conditionName;
_params.put(conditionName, params);
}
@Override
public void addAnd(Object useless, Op op, Object...values) {
String uuid = UUID.randomUUID().toString();
constructCondition(uuid, " AND ", _specifiedAttrs.get(0), op);
setParameters(uuid, values);
}
@Override
public List<K> list() {
done();
SearchCriteria sc1 = createSearchCriteria();
if (isSelectAll()) {
return (List<K>)_dao.search(sc1, null);
} else {
return (List<K>)_dao.customSearch(sc1, null);
}
}
private boolean isSelectAll() {
return _selects == null || _selects.size() == 0;
}
@Override
public T getEntity() {
return (T) _entity;
}
private SearchCriteria<K> createSearchCriteria() {
return new SearchCriteria<K>(_attrs, _conditions, _selects, _selectType, _resultType, _params);
}
private void set(String name) {
Attribute attr = _attrs.get(name);
assert (attr != null) : "Searching for a field that's not there: " + name;
_specifiedAttrs.add(attr);
}
private void done() {
if (_entity != null) {
Factory factory = (Factory)_entity;
factory.setCallback(0, null);
_entity = null;
}
if (_selects == null || _selects.size() == 0) {
_selectType = SelectType.Entity;
assert _entityBeanType.equals(_resultType) : "Expecting " + _entityBeanType + " because you didn't specify any selects but instead got " + _resultType;
return;
}
for (Select select : _selects) {
if (select.field == null) {
assert (_selects.size() == 1) : "You didn't specify any fields to put the result in but you're specifying more than one select so where should I put the selects?";
_selectType = SelectType.Single;
return;
}
if (select.func != null) {
_selectType = SelectType.Result;
return;
}
}
_selectType = SelectType.Fields;
}
@Override
public Object intercept(Object object, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
String name = method.getName();
if (method.getAnnotation(Transient.class) == null) {
if (name.startsWith("get")) {
String fieldName = Character.toLowerCase(name.charAt(3)) + name.substring(4);
set(fieldName);
return null;
} else if (name.startsWith("is")) {
String fieldName = Character.toLowerCase(name.charAt(2)) + name.substring(3);
set(fieldName);
return null;
} else {
name = name.toLowerCase();
for (String fieldName : _attrs.keySet()) {
if (name.endsWith(fieldName.toLowerCase())) {
set(fieldName);
return null;
}
}
assert false : "Perhaps you need to make the method start with get or is?";
}
}
return methodProxy.invokeSuper(object, args);
}
@Override
public <K> K find() {
assert isSelectAll() : "find doesn't support select search";
done();
SearchCriteria sc1 = createSearchCriteria();
return (K)_dao.findOneBy(sc1);
}
}

View File

@ -10,16 +10,16 @@
// limitations under the License.
//
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.utils.db;
import java.util.List;
import com.cloud.utils.db.SearchCriteria.Op;
public interface SearchCriteriaService<T, K> {
public void selectField(Object... useless);
public void addAnd(Object useless, Op op, Object...values);
public List<K> list();
public T getEntity();
public <K> K find();
}
package com.cloud.utils.db;
import java.util.List;
import com.cloud.utils.db.SearchCriteria.Op;
public interface SearchCriteriaService<T, K> {
public void selectField(Object... useless);
public void addAnd(Object useless, Op op, Object...values);
public List<K> list();
public T getEntity();
public <K> K find();
}

View File

@ -10,28 +10,28 @@
// limitations under the License.
//
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.utils.events;
import java.io.Serializable;
public class EventArgs implements Serializable {
private static final long serialVersionUID = 30659016120504139L;
public static EventArgs Empty = new EventArgs();
private String subject;
public EventArgs() {
}
public EventArgs(String subject) {
this.subject = subject;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
}
package com.cloud.utils.events;
import java.io.Serializable;
public class EventArgs implements Serializable {
private static final long serialVersionUID = 30659016120504139L;
public static EventArgs Empty = new EventArgs();
private String subject;
public EventArgs() {
}
public EventArgs(String subject) {
this.subject = subject;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
}

View File

@ -10,53 +10,53 @@
// limitations under the License.
//
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.utils.events;
public class EventsTest {
public void onWeatherChange(Object sender, EventArgs args) {
System.out.println("onWeatherChange, weather: " + ((WeatherChangeEventArgs)args).getWeather());
}
public void onTrafficChange(Object sender, EventArgs args) {
System.out.println("onTrafficChange");
}
public void run() {
SubscriptionMgr mgr = SubscriptionMgr.getInstance();
try {
mgr.subscribe("weather", this, "onWeatherChange");
mgr.subscribe("traffic", this, "onTrafficChange");
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
mgr.notifySubscribers("weather", null, new WeatherChangeEventArgs("weather", "Sunny"));
mgr.notifySubscribers("traffic", null, EventArgs.Empty);
}
public static void main(String[] args) {
EventsTest test = new EventsTest();
test.run();
}
}
class WeatherChangeEventArgs extends EventArgs {
private static final long serialVersionUID = -952166331523609047L;
private String weather;
public WeatherChangeEventArgs() {
}
public WeatherChangeEventArgs(String subject, String weather) {
super(subject);
this.weather = weather;
}
public String getWeather() { return weather; }
public void setWeather(String weather) {
this.weather = weather;
}
}
package com.cloud.utils.events;
public class EventsTest {
public void onWeatherChange(Object sender, EventArgs args) {
System.out.println("onWeatherChange, weather: " + ((WeatherChangeEventArgs)args).getWeather());
}
public void onTrafficChange(Object sender, EventArgs args) {
System.out.println("onTrafficChange");
}
public void run() {
SubscriptionMgr mgr = SubscriptionMgr.getInstance();
try {
mgr.subscribe("weather", this, "onWeatherChange");
mgr.subscribe("traffic", this, "onTrafficChange");
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
mgr.notifySubscribers("weather", null, new WeatherChangeEventArgs("weather", "Sunny"));
mgr.notifySubscribers("traffic", null, EventArgs.Empty);
}
public static void main(String[] args) {
EventsTest test = new EventsTest();
test.run();
}
}
class WeatherChangeEventArgs extends EventArgs {
private static final long serialVersionUID = -952166331523609047L;
private String weather;
public WeatherChangeEventArgs() {
}
public WeatherChangeEventArgs(String subject, String weather) {
super(subject);
this.weather = weather;
}
public String getWeather() { return weather; }
public void setWeather(String weather) {
this.weather = weather;
}
}

View File

@ -10,155 +10,155 @@
// limitations under the License.
//
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.utils.events;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
public class SubscriptionMgr {
protected final static Logger s_logger = Logger.getLogger(SubscriptionMgr.class);
private static SubscriptionMgr s_instance = new SubscriptionMgr();
private Map<String, List<SubscriberInfo>> registry;
private SubscriptionMgr() {
registry = new HashMap<String, List<SubscriberInfo>>();
}
public static SubscriptionMgr getInstance() {
return s_instance;
}
public <T> void subscribe(String subject, T subscriber, String listenerMethod)
throws SecurityException, NoSuchMethodException {
synchronized(this) {
List<SubscriberInfo> l = getAndSetSubscriberList(subject);
Class<?> clazz = subscriber.getClass();
SubscriberInfo subscribeInfo = new SubscriberInfo(clazz, subscriber, listenerMethod);
if(!l.contains(subscribeInfo))
l.add(subscribeInfo);
}
}
public <T> void unsubscribe(String subject, T subscriber, String listenerMethod) {
synchronized(this) {
List<SubscriberInfo> l = getSubscriberList(subject);
if(l != null) {
for(SubscriberInfo info : l) {
if(info.isMe(subscriber.getClass(), subscriber, listenerMethod)) {
l.remove(info);
return;
}
}
}
}
}
public void notifySubscribers(String subject, Object sender, EventArgs args) {
List<SubscriberInfo> l = getExecutableSubscriberList(subject);
if(l != null) {
for(SubscriberInfo info : l) {
try {
info.execute(sender, args);
} catch (IllegalArgumentException e) {
s_logger.warn("Exception on notifying event subscribers: ", e);
} catch (IllegalAccessException e) {
s_logger.warn("Exception on notifying event subscribers: ", e);
} catch (InvocationTargetException e) {
s_logger.warn("Exception on notifying event subscribers: ", e);
}
}
}
}
private List<SubscriberInfo> getAndSetSubscriberList(String subject) {
List<SubscriberInfo> l = registry.get(subject);
if(l == null) {
l = new ArrayList<SubscriberInfo>();
registry.put(subject, l);
}
return l;
}
private List<SubscriberInfo> getSubscriberList(String subject) {
return registry.get(subject);
}
private synchronized List<SubscriberInfo> getExecutableSubscriberList(String subject) {
List<SubscriberInfo> l = registry.get(subject);
if(l != null) {
// do a shadow clone
ArrayList<SubscriberInfo> clonedList = new ArrayList<SubscriberInfo>(l.size());
for(SubscriberInfo info : l)
clonedList.add(info);
return clonedList;
}
return null;
}
private static class SubscriberInfo {
private Class<?> clazz;
private Object subscriber;
private String methodName;
private Method method;
public SubscriberInfo(Class<?> clazz, Object subscriber, String methodName)
throws SecurityException, NoSuchMethodException {
this.clazz = clazz;
this.subscriber = subscriber;
this.methodName = methodName;
for(Method method : clazz.getMethods()) {
if(method.getName().equals(methodName)) {
Class<?>[] paramTypes = method.getParameterTypes();
if(paramTypes != null && paramTypes.length == 2 &&
paramTypes[0] == Object.class &&
EventArgs.class.isAssignableFrom(paramTypes[1])) {
this.method = method;
break;
}
}
}
if(this.method == null)
throw new NoSuchMethodException();
}
public void execute(Object sender, EventArgs args)
throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
method.invoke(subscriber, sender, args);
}
public boolean isMe(Class<?> clazz, Object subscriber, String methodName) {
return this.clazz == clazz &&
this.subscriber == subscriber &&
this.methodName.equals(methodName);
}
public boolean equals(Object o) {
if(o == null)
return false;
if(o instanceof SubscriberInfo) {
return this.clazz == ((SubscriberInfo)o).clazz &&
this.subscriber == ((SubscriberInfo)o).subscriber &&
this.methodName.equals(((SubscriberInfo)o).methodName);
}
return false;
}
}
}
package com.cloud.utils.events;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
public class SubscriptionMgr {
protected final static Logger s_logger = Logger.getLogger(SubscriptionMgr.class);
private static SubscriptionMgr s_instance = new SubscriptionMgr();
private Map<String, List<SubscriberInfo>> registry;
private SubscriptionMgr() {
registry = new HashMap<String, List<SubscriberInfo>>();
}
public static SubscriptionMgr getInstance() {
return s_instance;
}
public <T> void subscribe(String subject, T subscriber, String listenerMethod)
throws SecurityException, NoSuchMethodException {
synchronized(this) {
List<SubscriberInfo> l = getAndSetSubscriberList(subject);
Class<?> clazz = subscriber.getClass();
SubscriberInfo subscribeInfo = new SubscriberInfo(clazz, subscriber, listenerMethod);
if(!l.contains(subscribeInfo))
l.add(subscribeInfo);
}
}
public <T> void unsubscribe(String subject, T subscriber, String listenerMethod) {
synchronized(this) {
List<SubscriberInfo> l = getSubscriberList(subject);
if(l != null) {
for(SubscriberInfo info : l) {
if(info.isMe(subscriber.getClass(), subscriber, listenerMethod)) {
l.remove(info);
return;
}
}
}
}
}
public void notifySubscribers(String subject, Object sender, EventArgs args) {
List<SubscriberInfo> l = getExecutableSubscriberList(subject);
if(l != null) {
for(SubscriberInfo info : l) {
try {
info.execute(sender, args);
} catch (IllegalArgumentException e) {
s_logger.warn("Exception on notifying event subscribers: ", e);
} catch (IllegalAccessException e) {
s_logger.warn("Exception on notifying event subscribers: ", e);
} catch (InvocationTargetException e) {
s_logger.warn("Exception on notifying event subscribers: ", e);
}
}
}
}
private List<SubscriberInfo> getAndSetSubscriberList(String subject) {
List<SubscriberInfo> l = registry.get(subject);
if(l == null) {
l = new ArrayList<SubscriberInfo>();
registry.put(subject, l);
}
return l;
}
private List<SubscriberInfo> getSubscriberList(String subject) {
return registry.get(subject);
}
private synchronized List<SubscriberInfo> getExecutableSubscriberList(String subject) {
List<SubscriberInfo> l = registry.get(subject);
if(l != null) {
// do a shadow clone
ArrayList<SubscriberInfo> clonedList = new ArrayList<SubscriberInfo>(l.size());
for(SubscriberInfo info : l)
clonedList.add(info);
return clonedList;
}
return null;
}
private static class SubscriberInfo {
private Class<?> clazz;
private Object subscriber;
private String methodName;
private Method method;
public SubscriberInfo(Class<?> clazz, Object subscriber, String methodName)
throws SecurityException, NoSuchMethodException {
this.clazz = clazz;
this.subscriber = subscriber;
this.methodName = methodName;
for(Method method : clazz.getMethods()) {
if(method.getName().equals(methodName)) {
Class<?>[] paramTypes = method.getParameterTypes();
if(paramTypes != null && paramTypes.length == 2 &&
paramTypes[0] == Object.class &&
EventArgs.class.isAssignableFrom(paramTypes[1])) {
this.method = method;
break;
}
}
}
if(this.method == null)
throw new NoSuchMethodException();
}
public void execute(Object sender, EventArgs args)
throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
method.invoke(subscriber, sender, args);
}
public boolean isMe(Class<?> clazz, Object subscriber, String methodName) {
return this.clazz == clazz &&
this.subscriber == subscriber &&
this.methodName.equals(methodName);
}
public boolean equals(Object o) {
if(o == null)
return false;
if(o instanceof SubscriberInfo) {
return this.clazz == ((SubscriberInfo)o).clazz &&
this.subscriber == ((SubscriberInfo)o).subscriber &&
this.methodName.equals(((SubscriberInfo)o).methodName);
}
return false;
}
}
}

View File

@ -10,110 +10,110 @@
// limitations under the License.
//
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.utils.exception;
import java.util.HashMap;
import org.apache.log4j.Logger;
import org.apache.commons.codec.binary.Base64;
/**
* CSExceptionErrorCode lists the CloudStack error codes that correspond
*/
public class CSExceptionErrorCode {
public static final Logger s_logger = Logger.getLogger(CSExceptionErrorCode.class.getName());
// Declare a hashmap of CloudStack Error Codes for Exceptions.
protected static final HashMap<String, Integer> ExceptionErrorCodeMap;
static {
try {
ExceptionErrorCodeMap = new HashMap<String, Integer>();
ExceptionErrorCodeMap.put("com.cloud.utils.exception.CloudRuntimeException", 4250);
ExceptionErrorCodeMap.put("com.cloud.utils.exception.ExceptionUtil", 4255);
ExceptionErrorCodeMap.put("com.cloud.utils.exception.ExecutionException", 4260);
ExceptionErrorCodeMap.put("com.cloud.utils.exception.HypervisorVersionChangedException", 4265);
ExceptionErrorCodeMap.put("com.cloud.utils.exception.RuntimeCloudException", 4270);
ExceptionErrorCodeMap.put("com.cloud.exception.CloudException", 4275);
ExceptionErrorCodeMap.put("com.cloud.exception.AccountLimitException", 4280);
ExceptionErrorCodeMap.put("com.cloud.exception.AgentUnavailableException", 4285);
ExceptionErrorCodeMap.put("com.cloud.exception.CloudAuthenticationException", 4290);
ExceptionErrorCodeMap.put("com.cloud.exception.CloudExecutionException", 4295);
ExceptionErrorCodeMap.put("com.cloud.exception.ConcurrentOperationException", 4300);
ExceptionErrorCodeMap.put("com.cloud.exception.ConflictingNetworkSettingsException", 4305);
ExceptionErrorCodeMap.put("com.cloud.exception.DiscoveredWithErrorException", 4310);
ExceptionErrorCodeMap.put("com.cloud.exception.HAStateException", 4315);
ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientAddressCapacityException", 4320);
ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientCapacityException", 4325);
ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientNetworkCapacityException", 4330);
ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientServerCapacityException", 4335);
ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientStorageCapacityException", 4340);
ExceptionErrorCodeMap.put("com.cloud.exception.InternalErrorException", 4345);
ExceptionErrorCodeMap.put("com.cloud.exception.InvalidParameterValueException", 4350);
ExceptionErrorCodeMap.put("com.cloud.exception.ManagementServerException", 4355);
ExceptionErrorCodeMap.put("com.cloud.exception.NetworkRuleConflictException", 4360);
ExceptionErrorCodeMap.put("com.cloud.exception.PermissionDeniedException", 4365);
ExceptionErrorCodeMap.put("com.cloud.exception.ResourceAllocationException", 4370);
ExceptionErrorCodeMap.put("com.cloud.exception.ResourceInUseException", 4375);
ExceptionErrorCodeMap.put("com.cloud.exception.ResourceUnavailableException", 4380);
ExceptionErrorCodeMap.put("com.cloud.exception.StorageUnavailableException", 4385);
ExceptionErrorCodeMap.put("com.cloud.exception.UnsupportedServiceException", 4390);
ExceptionErrorCodeMap.put("com.cloud.exception.VirtualMachineMigrationException", 4395);
ExceptionErrorCodeMap.put("com.cloud.exception.AccountLimitException", 4400);
ExceptionErrorCodeMap.put("com.cloud.exception.AgentUnavailableException", 4405);
ExceptionErrorCodeMap.put("com.cloud.exception.CloudAuthenticationException", 4410);
ExceptionErrorCodeMap.put("com.cloud.exception.CloudException", 4415);
ExceptionErrorCodeMap.put("com.cloud.exception.CloudExecutionException", 4420);
ExceptionErrorCodeMap.put("com.cloud.exception.ConcurrentOperationException", 4425);
ExceptionErrorCodeMap.put("com.cloud.exception.ConflictingNetworkSettingsException", 4430);
ExceptionErrorCodeMap.put("com.cloud.exception.ConnectionException", 4435);
ExceptionErrorCodeMap.put("com.cloud.exception.DiscoveredWithErrorException", 4440);
ExceptionErrorCodeMap.put("com.cloud.exception.DiscoveryException", 4445);
ExceptionErrorCodeMap.put("com.cloud.exception.HAStateException", 4450);
ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientAddressCapacityException", 4455);
ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientCapacityException", 4460);
ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientNetworkCapacityException", 4465);
ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientServerCapacityException", 4470);
ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientStorageCapacityException", 4475);
ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientVirtualNetworkCapcityException", 4480);
ExceptionErrorCodeMap.put("com.cloud.exception.InternalErrorException", 4485);
ExceptionErrorCodeMap.put("com.cloud.exception.InvalidParameterValueException", 4490);
ExceptionErrorCodeMap.put("com.cloud.exception.ManagementServerException", 4495);
ExceptionErrorCodeMap.put("com.cloud.exception.NetworkRuleConflictException", 4500);
ExceptionErrorCodeMap.put("com.cloud.exception.PermissionDeniedException", 4505);
ExceptionErrorCodeMap.put("com.cloud.exception.ResourceAllocationException", 4510);
ExceptionErrorCodeMap.put("com.cloud.exception.ResourceInUseException", 4515);
ExceptionErrorCodeMap.put("com.cloud.exception.ResourceUnavailableException", 4520);
ExceptionErrorCodeMap.put("com.cloud.exception.StorageUnavailableException", 4525);
ExceptionErrorCodeMap.put("com.cloud.exception.UnsupportedServiceException", 4530);
ExceptionErrorCodeMap.put("com.cloud.exception.VirtualMachineMigrationException", 4535);
// Have a special error code for ServerApiException when it is
// thrown in a standalone manner when failing to detect any of the above
// standard exceptions.
ExceptionErrorCodeMap.put("com.cloud.api.ServerApiException", 9999);
} catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
}
public static HashMap<String, Integer> getErrCodeList() {
return ExceptionErrorCodeMap;
}
public static int getCSErrCode(String exceptionName) {
if (ExceptionErrorCodeMap.containsKey(exceptionName)) {
return ExceptionErrorCodeMap.get(exceptionName);
} else {
s_logger.info("Could not find exception: " + exceptionName + " in error code list for exceptions");
return -1;
}
}
public static String getCurMethodName() {
StackTraceElement stackTraceCalls[] = (new Throwable()).getStackTrace();
return stackTraceCalls[1].toString();
}
}
package com.cloud.utils.exception;
import java.util.HashMap;
import org.apache.log4j.Logger;
import org.apache.commons.codec.binary.Base64;
/**
* CSExceptionErrorCode lists the CloudStack error codes that correspond
*/
public class CSExceptionErrorCode {
public static final Logger s_logger = Logger.getLogger(CSExceptionErrorCode.class.getName());
// Declare a hashmap of CloudStack Error Codes for Exceptions.
protected static final HashMap<String, Integer> ExceptionErrorCodeMap;
static {
try {
ExceptionErrorCodeMap = new HashMap<String, Integer>();
ExceptionErrorCodeMap.put("com.cloud.utils.exception.CloudRuntimeException", 4250);
ExceptionErrorCodeMap.put("com.cloud.utils.exception.ExceptionUtil", 4255);
ExceptionErrorCodeMap.put("com.cloud.utils.exception.ExecutionException", 4260);
ExceptionErrorCodeMap.put("com.cloud.utils.exception.HypervisorVersionChangedException", 4265);
ExceptionErrorCodeMap.put("com.cloud.utils.exception.RuntimeCloudException", 4270);
ExceptionErrorCodeMap.put("com.cloud.exception.CloudException", 4275);
ExceptionErrorCodeMap.put("com.cloud.exception.AccountLimitException", 4280);
ExceptionErrorCodeMap.put("com.cloud.exception.AgentUnavailableException", 4285);
ExceptionErrorCodeMap.put("com.cloud.exception.CloudAuthenticationException", 4290);
ExceptionErrorCodeMap.put("com.cloud.exception.CloudExecutionException", 4295);
ExceptionErrorCodeMap.put("com.cloud.exception.ConcurrentOperationException", 4300);
ExceptionErrorCodeMap.put("com.cloud.exception.ConflictingNetworkSettingsException", 4305);
ExceptionErrorCodeMap.put("com.cloud.exception.DiscoveredWithErrorException", 4310);
ExceptionErrorCodeMap.put("com.cloud.exception.HAStateException", 4315);
ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientAddressCapacityException", 4320);
ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientCapacityException", 4325);
ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientNetworkCapacityException", 4330);
ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientServerCapacityException", 4335);
ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientStorageCapacityException", 4340);
ExceptionErrorCodeMap.put("com.cloud.exception.InternalErrorException", 4345);
ExceptionErrorCodeMap.put("com.cloud.exception.InvalidParameterValueException", 4350);
ExceptionErrorCodeMap.put("com.cloud.exception.ManagementServerException", 4355);
ExceptionErrorCodeMap.put("com.cloud.exception.NetworkRuleConflictException", 4360);
ExceptionErrorCodeMap.put("com.cloud.exception.PermissionDeniedException", 4365);
ExceptionErrorCodeMap.put("com.cloud.exception.ResourceAllocationException", 4370);
ExceptionErrorCodeMap.put("com.cloud.exception.ResourceInUseException", 4375);
ExceptionErrorCodeMap.put("com.cloud.exception.ResourceUnavailableException", 4380);
ExceptionErrorCodeMap.put("com.cloud.exception.StorageUnavailableException", 4385);
ExceptionErrorCodeMap.put("com.cloud.exception.UnsupportedServiceException", 4390);
ExceptionErrorCodeMap.put("com.cloud.exception.VirtualMachineMigrationException", 4395);
ExceptionErrorCodeMap.put("com.cloud.exception.AccountLimitException", 4400);
ExceptionErrorCodeMap.put("com.cloud.exception.AgentUnavailableException", 4405);
ExceptionErrorCodeMap.put("com.cloud.exception.CloudAuthenticationException", 4410);
ExceptionErrorCodeMap.put("com.cloud.exception.CloudException", 4415);
ExceptionErrorCodeMap.put("com.cloud.exception.CloudExecutionException", 4420);
ExceptionErrorCodeMap.put("com.cloud.exception.ConcurrentOperationException", 4425);
ExceptionErrorCodeMap.put("com.cloud.exception.ConflictingNetworkSettingsException", 4430);
ExceptionErrorCodeMap.put("com.cloud.exception.ConnectionException", 4435);
ExceptionErrorCodeMap.put("com.cloud.exception.DiscoveredWithErrorException", 4440);
ExceptionErrorCodeMap.put("com.cloud.exception.DiscoveryException", 4445);
ExceptionErrorCodeMap.put("com.cloud.exception.HAStateException", 4450);
ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientAddressCapacityException", 4455);
ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientCapacityException", 4460);
ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientNetworkCapacityException", 4465);
ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientServerCapacityException", 4470);
ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientStorageCapacityException", 4475);
ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientVirtualNetworkCapcityException", 4480);
ExceptionErrorCodeMap.put("com.cloud.exception.InternalErrorException", 4485);
ExceptionErrorCodeMap.put("com.cloud.exception.InvalidParameterValueException", 4490);
ExceptionErrorCodeMap.put("com.cloud.exception.ManagementServerException", 4495);
ExceptionErrorCodeMap.put("com.cloud.exception.NetworkRuleConflictException", 4500);
ExceptionErrorCodeMap.put("com.cloud.exception.PermissionDeniedException", 4505);
ExceptionErrorCodeMap.put("com.cloud.exception.ResourceAllocationException", 4510);
ExceptionErrorCodeMap.put("com.cloud.exception.ResourceInUseException", 4515);
ExceptionErrorCodeMap.put("com.cloud.exception.ResourceUnavailableException", 4520);
ExceptionErrorCodeMap.put("com.cloud.exception.StorageUnavailableException", 4525);
ExceptionErrorCodeMap.put("com.cloud.exception.UnsupportedServiceException", 4530);
ExceptionErrorCodeMap.put("com.cloud.exception.VirtualMachineMigrationException", 4535);
// Have a special error code for ServerApiException when it is
// thrown in a standalone manner when failing to detect any of the above
// standard exceptions.
ExceptionErrorCodeMap.put("com.cloud.api.ServerApiException", 9999);
} catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
}
public static HashMap<String, Integer> getErrCodeList() {
return ExceptionErrorCodeMap;
}
public static int getCSErrCode(String exceptionName) {
if (ExceptionErrorCodeMap.containsKey(exceptionName)) {
return ExceptionErrorCodeMap.get(exceptionName);
} else {
s_logger.info("Could not find exception: " + exceptionName + " in error code list for exceptions");
return -1;
}
}
public static String getCurMethodName() {
StackTraceElement stackTraceCalls[] = (new Throwable()).getStackTrace();
return stackTraceCalls[1].toString();
}
}

View File

@ -10,63 +10,63 @@
// limitations under the License.
//
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.utils.exception;
import com.cloud.utils.AnnotationHelper;
import com.cloud.utils.IdentityProxy;
import java.util.ArrayList;
/**
* by the API response serializer. Any exceptions that are thrown by
* class, which extends Exception instead of RuntimeException like this
* class does.
*/
public class RuntimeCloudException extends RuntimeException {
// This holds a list of uuids and their names. Add uuid:fieldname pairs
protected ArrayList<IdentityProxy> idList = new ArrayList<IdentityProxy>();
protected int csErrorCode;
public void addProxyObject(String tableName, Long id, String idFieldName) {
idList.add(new IdentityProxy(tableName, id, idFieldName));
return;
}
public RuntimeCloudException(String message) {
super(message);
setCSErrorCode(CSExceptionErrorCode.getCSErrCode(this.getClass().getName()));
}
public RuntimeCloudException(String message, Throwable cause) {
super(message, cause);
setCSErrorCode(CSExceptionErrorCode.getCSErrCode(this.getClass().getName()));
}
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;
}
public RuntimeCloudException() {
super();
setCSErrorCode(CSExceptionErrorCode.getCSErrCode(this.getClass().getName()));
}
public ArrayList<IdentityProxy> getIdProxyList() {
return idList;
}
public void setCSErrorCode(int cserrcode) {
this.csErrorCode = cserrcode;
}
public int getCSErrorCode() {
return this.csErrorCode;
}
}
package com.cloud.utils.exception;
import com.cloud.utils.AnnotationHelper;
import com.cloud.utils.IdentityProxy;
import java.util.ArrayList;
/**
* by the API response serializer. Any exceptions that are thrown by
* class, which extends Exception instead of RuntimeException like this
* class does.
*/
public class RuntimeCloudException extends RuntimeException {
// This holds a list of uuids and their names. Add uuid:fieldname pairs
protected ArrayList<IdentityProxy> idList = new ArrayList<IdentityProxy>();
protected int csErrorCode;
public void addProxyObject(String tableName, Long id, String idFieldName) {
idList.add(new IdentityProxy(tableName, id, idFieldName));
return;
}
public RuntimeCloudException(String message) {
super(message);
setCSErrorCode(CSExceptionErrorCode.getCSErrCode(this.getClass().getName()));
}
public RuntimeCloudException(String message, Throwable cause) {
super(message, cause);
setCSErrorCode(CSExceptionErrorCode.getCSErrCode(this.getClass().getName()));
}
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;
}
public RuntimeCloudException() {
super();
setCSErrorCode(CSExceptionErrorCode.getCSErrCode(this.getClass().getName()));
}
public ArrayList<IdentityProxy> getIdProxyList() {
return idList;
}
public void setCSErrorCode(int cserrcode) {
this.csErrorCode = cserrcode;
}
public int getCSErrorCode() {
return this.csErrorCode;
}
}

View File

@ -10,374 +10,374 @@
// limitations under the License.
//
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.utils.net;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Formatter;
package com.cloud.utils.net;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Formatter;
import com.cloud.utils.NumbersUtil;
/**
* copied from the public domain utility from John Burkard.
* @author <a href="mailto:jb@eaio.com">Johann Burkard</a>
* @version 2.1.3
**/
public class MacAddress {
private long _addr = 0;
protected MacAddress() {
}
public MacAddress(long addr) {
_addr = addr;
}
public long toLong() {
return _addr;
}
public byte[] toByteArray() {
byte[] bytes = new byte[6];
bytes[0] = (byte)((_addr >> 40) & 0xff);
bytes[1] = (byte)((_addr >> 32) & 0xff);
bytes[2] = (byte)((_addr >> 24) & 0xff);
bytes[3] = (byte)((_addr >> 16) & 0xff);
bytes[4] = (byte)((_addr >> 8) & 0xff);
bytes[5] = (byte)((_addr >> 0) & 0xff);
return bytes;
}
public String toString(String separator) {
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);
return buff.toString();
/*
String str = Long.toHexString(_addr);
for (int i = str.length() - 1; i >= 0; i--) {
buff.append(str.charAt(i));
if (separator != null && (str.length() - i) % 2 == 0) {
buff.append(separator);
}
}
return buff.reverse().toString();
*/
}
@Override
public String toString() {
return toString(":");
}
private static MacAddress s_address;
static {
String macAddress = null;
Process p = null;
BufferedReader in = null;
try {
String osname = System.getProperty("os.name");
if (osname.startsWith("Windows")) {
p = Runtime.getRuntime().exec(new String[] { "ipconfig", "/all"}, null);
} else if (osname.startsWith("Solaris") || osname.startsWith("SunOS")) {
// Solaris code must appear before the generic code
String hostName = MacAddress.getFirstLineOfCommand(new String[] { "uname",
"-n"});
if (hostName != null) {
p = Runtime.getRuntime().exec(new String[] { "/usr/sbin/arp", hostName}, null);
}
} else if (new File("/usr/sbin/lanscan").exists()) {
p = Runtime.getRuntime().exec(new String[] { "/usr/sbin/lanscan"}, null);
} else if (new File("/sbin/ifconfig").exists()) {
p = Runtime.getRuntime().exec(new String[] { "/sbin/ifconfig", "-a"}, null);
}
if (p != null) {
in = new BufferedReader(new InputStreamReader(p.getInputStream()), 128);
String l = null;
while ((l = in.readLine()) != null) {
macAddress = MacAddress.parse(l);
if (macAddress != null && MacAddress.parseShort(macAddress) != 0xff)
break;
}
}
} catch (SecurityException ex) {
} catch (IOException ex) {
} finally {
if (p != null) {
if (in != null) {
try {
in.close();
} catch (IOException ex) {
}
}
try {
p.getErrorStream().close();
} catch (IOException ex) {
}
try {
p.getOutputStream().close();
} catch (IOException ex) {
}
p.destroy();
}
}
long clockSeqAndNode = 0;
if (macAddress != null) {
if (macAddress.indexOf(':') != -1) {
clockSeqAndNode |= MacAddress.parseLong(macAddress);
} else if (macAddress.startsWith("0x")) {
clockSeqAndNode |= MacAddress.parseLong(macAddress.substring(2));
}
} else {
try {
byte[] local = InetAddress.getLocalHost().getAddress();
clockSeqAndNode |= (local[0] << 24) & 0xFF000000L;
clockSeqAndNode |= (local[1] << 16) & 0xFF0000;
clockSeqAndNode |= (local[2] << 8) & 0xFF00;
clockSeqAndNode |= local[3] & 0xFF;
} catch (UnknownHostException ex) {
clockSeqAndNode |= (long) (Math.random() * 0x7FFFFFFF);
}
}
s_address = new MacAddress(clockSeqAndNode);
}
public static MacAddress getMacAddress() {
return s_address;
}
private static String getFirstLineOfCommand(String[] commands) throws IOException {
Process p = null;
BufferedReader reader = null;
try {
p = Runtime.getRuntime().exec(commands);
reader = new BufferedReader(new InputStreamReader(p.getInputStream()), 128);
return reader.readLine();
} finally {
if (p != null) {
if (reader != null) {
try {
reader.close();
} catch (IOException ex) {
}
}
try {
p.getErrorStream().close();
} catch (IOException ex) {
}
try {
p.getOutputStream().close();
} catch (IOException ex) {
}
p.destroy();
}
}
}
/**
* The MAC address parser attempts to find the following patterns:
* <ul>
* <li>.{1,2}:.{1,2}:.{1,2}:.{1,2}:.{1,2}:.{1,2}</li>
* <li>.{1,2}-.{1,2}-.{1,2}-.{1,2}-.{1,2}-.{1,2}</li>
* </ul>
*
* This is copied from the author below. The author encouraged copying
* it.
*
*/
static String parse(String in) {
// lanscan
int hexStart = in.indexOf("0x");
if (hexStart != -1) {
int hexEnd = in.indexOf(' ', hexStart);
if (hexEnd != -1) {
return in.substring(hexStart, hexEnd);
}
}
int octets = 0;
int lastIndex, old, end;
if (in.indexOf('-') > -1) {
in = in.replace('-', ':');
}
lastIndex = in.lastIndexOf(':');
if (lastIndex > in.length() - 2) return null;
end = Math.min(in.length(), lastIndex + 3);
++octets;
old = lastIndex;
while (octets != 5 && lastIndex != -1 && lastIndex > 1) {
lastIndex = in.lastIndexOf(':', --lastIndex);
if (old - lastIndex == 3 || old - lastIndex == 2) {
++octets;
old = lastIndex;
}
}
if (octets == 5 && lastIndex > 1) {
return in.substring(lastIndex - 2, end).trim();
}
return null;
}
public static void main(String[] args) {
MacAddress addr = MacAddress.getMacAddress();
System.out.println("addr in integer is " + addr.toLong());
System.out.println("addr in bytes is " + NumbersUtil.bytesToString(addr.toByteArray(), 0, addr.toByteArray().length));
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).
* Returns 0 if the String does not contain any interesting characters.
*
* @param s the String to extract a <code>long</code> from, may not be <code>null</code>
* @return a <code>long</code>
* @throws NullPointerException if the String is <code>null</code>
*/
public static long parseLong(String s) throws NullPointerException {
s = s.toLowerCase();
long out = 0;
byte shifts = 0;
char c;
for (int i = 0; i < s.length() && shifts < 16; i++) {
c = s.charAt(i);
if ((c > 47) && (c < 58)) {
out <<= 4;
++shifts;
out |= c - 48;
}
else if ((c > 96) && (c < 103)) {
++shifts;
out <<= 4;
out |= c - 87;
}
}
return out;
}
/**
* Parses an <code>int</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).
* Returns 0 if the String does not contain any interesting characters.
*
* @param s the String to extract an <code>int</code> from, may not be <code>null</code>
* @return an <code>int</code>
* @throws NullPointerException if the String is <code>null</code>
*/
public static int parseInt(String s) throws NullPointerException {
s = s.toLowerCase();
int out = 0;
byte shifts = 0;
char c;
for (int i = 0; i < s.length() && shifts < 8; i++) {
c = s.charAt(i);
if ((c > 47) && (c < 58)) {
out <<= 4;
++shifts;
out |= c - 48;
}
else if ((c > 96) && (c < 103)) {
++shifts;
out <<= 4;
out |= c - 87;
}
}
return out;
}
/**
* Parses a <code>short</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).
* Returns 0 if the String does not contain any interesting characters.
*
* @param s the String to extract a <code>short</code> from, may not be <code>null</code>
* @return a <code>short</code>
* @throws NullPointerException if the String is <code>null</code>
*/
public static short parseShort(String s) throws NullPointerException {
s = s.toLowerCase();
short out = 0;
byte shifts = 0;
char c;
for (int i = 0; i < s.length() && shifts < 4; i++) {
c = s.charAt(i);
if ((c > 47) && (c < 58)) {
out <<= 4;
++shifts;
out |= c - 48;
}
else if ((c > 96) && (c < 103)) {
++shifts;
out <<= 4;
out |= c - 87;
}
}
return out;
}
/**
* Parses a <code>byte</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).
* Returns 0 if the String does not contain any interesting characters.
*
* @param s the String to extract a <code>byte</code> from, may not be <code>null</code>
* @return a <code>byte</code>
* @throws NullPointerException if the String is <code>null</code>
*/
public static byte parseByte(String s) throws NullPointerException {
s = s.toLowerCase();
byte out = 0;
byte shifts = 0;
char c;
for (int i = 0; i < s.length() && shifts < 2; i++) {
c = s.charAt(i);
if ((c > 47) && (c < 58)) {
out <<= 4;
++shifts;
out |= c - 48;
}
else if ((c > 96) && (c < 103)) {
++shifts;
out <<= 4;
out |= c - 87;
}
}
return out;
}
}
/**
* copied from the public domain utility from John Burkard.
* @author <a href="mailto:jb@eaio.com">Johann Burkard</a>
* @version 2.1.3
**/
public class MacAddress {
private long _addr = 0;
protected MacAddress() {
}
public MacAddress(long addr) {
_addr = addr;
}
public long toLong() {
return _addr;
}
public byte[] toByteArray() {
byte[] bytes = new byte[6];
bytes[0] = (byte)((_addr >> 40) & 0xff);
bytes[1] = (byte)((_addr >> 32) & 0xff);
bytes[2] = (byte)((_addr >> 24) & 0xff);
bytes[3] = (byte)((_addr >> 16) & 0xff);
bytes[4] = (byte)((_addr >> 8) & 0xff);
bytes[5] = (byte)((_addr >> 0) & 0xff);
return bytes;
}
public String toString(String separator) {
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);
return buff.toString();
/*
String str = Long.toHexString(_addr);
for (int i = str.length() - 1; i >= 0; i--) {
buff.append(str.charAt(i));
if (separator != null && (str.length() - i) % 2 == 0) {
buff.append(separator);
}
}
return buff.reverse().toString();
*/
}
@Override
public String toString() {
return toString(":");
}
private static MacAddress s_address;
static {
String macAddress = null;
Process p = null;
BufferedReader in = null;
try {
String osname = System.getProperty("os.name");
if (osname.startsWith("Windows")) {
p = Runtime.getRuntime().exec(new String[] { "ipconfig", "/all"}, null);
} else if (osname.startsWith("Solaris") || osname.startsWith("SunOS")) {
// Solaris code must appear before the generic code
String hostName = MacAddress.getFirstLineOfCommand(new String[] { "uname",
"-n"});
if (hostName != null) {
p = Runtime.getRuntime().exec(new String[] { "/usr/sbin/arp", hostName}, null);
}
} else if (new File("/usr/sbin/lanscan").exists()) {
p = Runtime.getRuntime().exec(new String[] { "/usr/sbin/lanscan"}, null);
} else if (new File("/sbin/ifconfig").exists()) {
p = Runtime.getRuntime().exec(new String[] { "/sbin/ifconfig", "-a"}, null);
}
if (p != null) {
in = new BufferedReader(new InputStreamReader(p.getInputStream()), 128);
String l = null;
while ((l = in.readLine()) != null) {
macAddress = MacAddress.parse(l);
if (macAddress != null && MacAddress.parseShort(macAddress) != 0xff)
break;
}
}
} catch (SecurityException ex) {
} catch (IOException ex) {
} finally {
if (p != null) {
if (in != null) {
try {
in.close();
} catch (IOException ex) {
}
}
try {
p.getErrorStream().close();
} catch (IOException ex) {
}
try {
p.getOutputStream().close();
} catch (IOException ex) {
}
p.destroy();
}
}
long clockSeqAndNode = 0;
if (macAddress != null) {
if (macAddress.indexOf(':') != -1) {
clockSeqAndNode |= MacAddress.parseLong(macAddress);
} else if (macAddress.startsWith("0x")) {
clockSeqAndNode |= MacAddress.parseLong(macAddress.substring(2));
}
} else {
try {
byte[] local = InetAddress.getLocalHost().getAddress();
clockSeqAndNode |= (local[0] << 24) & 0xFF000000L;
clockSeqAndNode |= (local[1] << 16) & 0xFF0000;
clockSeqAndNode |= (local[2] << 8) & 0xFF00;
clockSeqAndNode |= local[3] & 0xFF;
} catch (UnknownHostException ex) {
clockSeqAndNode |= (long) (Math.random() * 0x7FFFFFFF);
}
}
s_address = new MacAddress(clockSeqAndNode);
}
public static MacAddress getMacAddress() {
return s_address;
}
private static String getFirstLineOfCommand(String[] commands) throws IOException {
Process p = null;
BufferedReader reader = null;
try {
p = Runtime.getRuntime().exec(commands);
reader = new BufferedReader(new InputStreamReader(p.getInputStream()), 128);
return reader.readLine();
} finally {
if (p != null) {
if (reader != null) {
try {
reader.close();
} catch (IOException ex) {
}
}
try {
p.getErrorStream().close();
} catch (IOException ex) {
}
try {
p.getOutputStream().close();
} catch (IOException ex) {
}
p.destroy();
}
}
}
/**
* The MAC address parser attempts to find the following patterns:
* <ul>
* <li>.{1,2}:.{1,2}:.{1,2}:.{1,2}:.{1,2}:.{1,2}</li>
* <li>.{1,2}-.{1,2}-.{1,2}-.{1,2}-.{1,2}-.{1,2}</li>
* </ul>
*
* This is copied from the author below. The author encouraged copying
* it.
*
*/
static String parse(String in) {
// lanscan
int hexStart = in.indexOf("0x");
if (hexStart != -1) {
int hexEnd = in.indexOf(' ', hexStart);
if (hexEnd != -1) {
return in.substring(hexStart, hexEnd);
}
}
int octets = 0;
int lastIndex, old, end;
if (in.indexOf('-') > -1) {
in = in.replace('-', ':');
}
lastIndex = in.lastIndexOf(':');
if (lastIndex > in.length() - 2) return null;
end = Math.min(in.length(), lastIndex + 3);
++octets;
old = lastIndex;
while (octets != 5 && lastIndex != -1 && lastIndex > 1) {
lastIndex = in.lastIndexOf(':', --lastIndex);
if (old - lastIndex == 3 || old - lastIndex == 2) {
++octets;
old = lastIndex;
}
}
if (octets == 5 && lastIndex > 1) {
return in.substring(lastIndex - 2, end).trim();
}
return null;
}
public static void main(String[] args) {
MacAddress addr = MacAddress.getMacAddress();
System.out.println("addr in integer is " + addr.toLong());
System.out.println("addr in bytes is " + NumbersUtil.bytesToString(addr.toByteArray(), 0, addr.toByteArray().length));
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).
* Returns 0 if the String does not contain any interesting characters.
*
* @param s the String to extract a <code>long</code> from, may not be <code>null</code>
* @return a <code>long</code>
* @throws NullPointerException if the String is <code>null</code>
*/
public static long parseLong(String s) throws NullPointerException {
s = s.toLowerCase();
long out = 0;
byte shifts = 0;
char c;
for (int i = 0; i < s.length() && shifts < 16; i++) {
c = s.charAt(i);
if ((c > 47) && (c < 58)) {
out <<= 4;
++shifts;
out |= c - 48;
}
else if ((c > 96) && (c < 103)) {
++shifts;
out <<= 4;
out |= c - 87;
}
}
return out;
}
/**
* Parses an <code>int</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).
* Returns 0 if the String does not contain any interesting characters.
*
* @param s the String to extract an <code>int</code> from, may not be <code>null</code>
* @return an <code>int</code>
* @throws NullPointerException if the String is <code>null</code>
*/
public static int parseInt(String s) throws NullPointerException {
s = s.toLowerCase();
int out = 0;
byte shifts = 0;
char c;
for (int i = 0; i < s.length() && shifts < 8; i++) {
c = s.charAt(i);
if ((c > 47) && (c < 58)) {
out <<= 4;
++shifts;
out |= c - 48;
}
else if ((c > 96) && (c < 103)) {
++shifts;
out <<= 4;
out |= c - 87;
}
}
return out;
}
/**
* Parses a <code>short</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).
* Returns 0 if the String does not contain any interesting characters.
*
* @param s the String to extract a <code>short</code> from, may not be <code>null</code>
* @return a <code>short</code>
* @throws NullPointerException if the String is <code>null</code>
*/
public static short parseShort(String s) throws NullPointerException {
s = s.toLowerCase();
short out = 0;
byte shifts = 0;
char c;
for (int i = 0; i < s.length() && shifts < 4; i++) {
c = s.charAt(i);
if ((c > 47) && (c < 58)) {
out <<= 4;
++shifts;
out |= c - 48;
}
else if ((c > 96) && (c < 103)) {
++shifts;
out <<= 4;
out |= c - 87;
}
}
return out;
}
/**
* Parses a <code>byte</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).
* Returns 0 if the String does not contain any interesting characters.
*
* @param s the String to extract a <code>byte</code> from, may not be <code>null</code>
* @return a <code>byte</code>
* @throws NullPointerException if the String is <code>null</code>
*/
public static byte parseByte(String s) throws NullPointerException {
s = s.toLowerCase();
byte out = 0;
byte shifts = 0;
char c;
for (int i = 0; i < s.length() && shifts < 2; i++) {
c = s.charAt(i);
if ((c > 47) && (c < 58)) {
out <<= 4;
++shifts;
out |= c - 48;
}
else if ((c > 96) && (c < 103)) {
++shifts;
out <<= 4;
out |= c - 87;
}
}
return out;
}
}

View File

@ -10,56 +10,56 @@
// limitations under the License.
//
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.utils.script;
import java.util.HashMap;
import org.apache.log4j.Logger;
public class Script2 extends Script {
HashMap<String, ParamType> _params = new HashMap<String, ParamType>();
public static enum ParamType {
NORMAL,
PASSWORD,
}
public Script2(String command, Logger logger) {
this(command, 0, logger);
}
public Script2(String command, long timeout, Logger logger) {
super(command, timeout, logger);
}
public void add(String param, ParamType type) {
_params.put(param, type);
super.add(param);
}
@Override
public void add(String param) {
add(param, ParamType.NORMAL);
}
private ParamType getType(String cmd) {
return _params.get(cmd);
}
@Override
protected String buildCommandLine(String[] command) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < command.length; i++) {
String cmd = command[i];
ParamType type = getType(cmd);
if (type == ParamType.PASSWORD) {
builder.append("******").append(" ");
} else {
builder.append(command[i]).append(" ");
}
}
return builder.toString();
}
}
package com.cloud.utils.script;
import java.util.HashMap;
import org.apache.log4j.Logger;
public class Script2 extends Script {
HashMap<String, ParamType> _params = new HashMap<String, ParamType>();
public static enum ParamType {
NORMAL,
PASSWORD,
}
public Script2(String command, Logger logger) {
this(command, 0, logger);
}
public Script2(String command, long timeout, Logger logger) {
super(command, timeout, logger);
}
public void add(String param, ParamType type) {
_params.put(param, type);
super.add(param);
}
@Override
public void add(String param) {
add(param, ParamType.NORMAL);
}
private ParamType getType(String cmd) {
return _params.get(cmd);
}
@Override
protected String buildCommandLine(String[] command) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < command.length; i++) {
String cmd = command[i];
ParamType type = getType(cmd);
if (type == ParamType.PASSWORD) {
builder.append("******").append(" ");
} else {
builder.append(command[i]).append(" ");
}
}
return builder.toString();
}
}

View File

@ -10,32 +10,32 @@
// limitations under the License.
//
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.utils;
import org.apache.log4j.Logger;
import org.junit.Assert;
package com.cloud.utils;
import org.apache.log4j.Logger;
import org.junit.Assert;
import com.cloud.utils.Profiler;
import com.cloud.utils.testcase.Log4jEnabledTestCase;
public class TestProfiler extends Log4jEnabledTestCase {
protected final static Logger s_logger = Logger.getLogger(TestProfiler.class);
public void testProfiler() {
s_logger.info("testProfiler() started");
Profiler pf = new Profiler();
pf.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
pf.stop();
s_logger.info("Duration : " + pf.getDuration());
Assert.assertTrue(pf.getDuration() >= 1000);
s_logger.info("testProfiler() stopped");
}
}
public class TestProfiler extends Log4jEnabledTestCase {
protected final static Logger s_logger = Logger.getLogger(TestProfiler.class);
public void testProfiler() {
s_logger.info("testProfiler() started");
Profiler pf = new Profiler();
pf.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
pf.stop();
s_logger.info("Duration : " + pf.getDuration());
Assert.assertTrue(pf.getDuration() >= 1000);
s_logger.info("testProfiler() stopped");
}
}

View File

@ -10,42 +10,42 @@
// limitations under the License.
//
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.utils.net;
import java.util.Set;
import java.util.TreeSet;
import junit.framework.TestCase;
import org.junit.Test;
public class NetUtilsTest extends TestCase {
@Test
public void testGetRandomIpFromCidr() {
String cidr = "192.168.124.1";
long ip = NetUtils.getRandomIpFromCidr(cidr, 24, new TreeSet<Long>());
assertEquals("The ip " + NetUtils.long2Ip(ip) + " retrieved must be within the cidr " + cidr + "/24", cidr.substring(0, 12), NetUtils.long2Ip(ip).substring(0, 12));
ip = NetUtils.getRandomIpFromCidr(cidr, 16, new TreeSet<Long>());
assertEquals("The ip " + NetUtils.long2Ip(ip) + " retrieved must be within the cidr " + cidr + "/16", cidr.substring(0, 8), NetUtils.long2Ip(ip).substring(0, 8));
ip = NetUtils.getRandomIpFromCidr(cidr, 8, new TreeSet<Long>());
assertEquals("The ip " + NetUtils.long2Ip(ip) + " retrieved must be within the cidr " + cidr + "/8", cidr.substring(0, 4), NetUtils.long2Ip(ip).substring(0, 4));
Set<Long> avoid = new TreeSet<Long>();
ip = NetUtils.getRandomIpFromCidr(cidr, 30, avoid);
assertTrue("We should be able to retrieve an ip on the first call.", ip != -1);
avoid.add(ip);
ip = NetUtils.getRandomIpFromCidr(cidr, 30, avoid);
assertTrue("We should be able to retrieve an ip on the second call.", ip != -1);
assertTrue("ip returned is not in the avoid list", !avoid.contains(ip));
avoid.add(ip);
ip = NetUtils.getRandomIpFromCidr(cidr, 30, avoid);
assertTrue("We should be able to retrieve an ip on the third call.", ip != -1);
assertTrue("ip returned is not in the avoid list", !avoid.contains(ip));
avoid.add(ip);
ip = NetUtils.getRandomIpFromCidr(cidr, 30, avoid);
assertEquals("This should be -1 because we ran out of ip addresses: " + ip, ip, -1);
}
}
package com.cloud.utils.net;
import java.util.Set;
import java.util.TreeSet;
import junit.framework.TestCase;
import org.junit.Test;
public class NetUtilsTest extends TestCase {
@Test
public void testGetRandomIpFromCidr() {
String cidr = "192.168.124.1";
long ip = NetUtils.getRandomIpFromCidr(cidr, 24, new TreeSet<Long>());
assertEquals("The ip " + NetUtils.long2Ip(ip) + " retrieved must be within the cidr " + cidr + "/24", cidr.substring(0, 12), NetUtils.long2Ip(ip).substring(0, 12));
ip = NetUtils.getRandomIpFromCidr(cidr, 16, new TreeSet<Long>());
assertEquals("The ip " + NetUtils.long2Ip(ip) + " retrieved must be within the cidr " + cidr + "/16", cidr.substring(0, 8), NetUtils.long2Ip(ip).substring(0, 8));
ip = NetUtils.getRandomIpFromCidr(cidr, 8, new TreeSet<Long>());
assertEquals("The ip " + NetUtils.long2Ip(ip) + " retrieved must be within the cidr " + cidr + "/8", cidr.substring(0, 4), NetUtils.long2Ip(ip).substring(0, 4));
Set<Long> avoid = new TreeSet<Long>();
ip = NetUtils.getRandomIpFromCidr(cidr, 30, avoid);
assertTrue("We should be able to retrieve an ip on the first call.", ip != -1);
avoid.add(ip);
ip = NetUtils.getRandomIpFromCidr(cidr, 30, avoid);
assertTrue("We should be able to retrieve an ip on the second call.", ip != -1);
assertTrue("ip returned is not in the avoid list", !avoid.contains(ip));
avoid.add(ip);
ip = NetUtils.getRandomIpFromCidr(cidr, 30, avoid);
assertTrue("We should be able to retrieve an ip on the third call.", ip != -1);
assertTrue("ip returned is not in the avoid list", !avoid.contains(ip));
avoid.add(ip);
ip = NetUtils.getRandomIpFromCidr(cidr, 30, avoid);
assertEquals("This should be -1 because we ran out of ip addresses: " + ip, ip, -1);
}
}

View File

@ -10,15 +10,15 @@
// limitations under the License.
//
// Automatically generated by addcopyright.py at 04/03/2012
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";
}
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";
}

View File

@ -10,31 +10,31 @@
// limitations under the License.
//
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.utils.testcase;
package com.cloud.utils.testcase;
import java.lang.annotation.Annotation;
import com.cloud.utils.component.ComponentLocator;
public class ComponentTestCase extends Log4jEnabledTestCase {
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) {
ComponentLocator.getLocator(
((ComponentSetup)annotation).managerName(),
protected void setUp() {
super.setUp();
Annotation[] annotations = getClass().getAnnotations();
if(annotations != null) {
for(Annotation annotation : annotations) {
if(annotation instanceof ComponentSetup) {
ComponentLocator.getLocator(
((ComponentSetup)annotation).managerName(),
((ComponentSetup)annotation).setupXml(),
((ComponentSetup)annotation).log4j()
);
break;
}
}
}
}
}
((ComponentSetup)annotation).log4j()
);
break;
}
}
}
}
}

View File

@ -10,34 +10,34 @@
// limitations under the License.
//
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.utils.testcase;
import java.io.File;
import java.net.URISyntaxException;
import java.net.URL;
package com.cloud.utils.testcase;
import java.io.File;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Random;
import org.apache.log4j.xml.DOMConfigurator;
import junit.framework.TestCase;
public class Log4jEnabledTestCase extends TestCase {
protected void setUp() {
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");
}
} else {
System.out.println("Configure log4j with default properties");
}
import org.apache.log4j.xml.DOMConfigurator;
import junit.framework.TestCase;
public class Log4jEnabledTestCase extends TestCase {
protected void setUp() {
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");
}
} else {
System.out.println("Configure log4j with default properties");
}
}
public static int getRandomMilliseconds(int rangeLo, int rangeHi) {
@ -47,4 +47,4 @@ public class Log4jEnabledTestCase extends TestCase {
long iRange = (long)Integer.MAX_VALUE - (long)Integer.MIN_VALUE;
return rangeLo + (int)((rangeHi - rangeLo)*pos/iRange);
}
}
}