http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/org/apache/commons/httpclient/contrib/ssl/EasySSLProtocolSocketFactory.java ---------------------------------------------------------------------- diff --git a/utils/src/main/java/org/apache/commons/httpclient/contrib/ssl/EasySSLProtocolSocketFactory.java b/utils/src/main/java/org/apache/commons/httpclient/contrib/ssl/EasySSLProtocolSocketFactory.java new file mode 100644 index 0000000..5ff5819 --- /dev/null +++ b/utils/src/main/java/org/apache/commons/httpclient/contrib/ssl/EasySSLProtocolSocketFactory.java @@ -0,0 +1,210 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.commons.httpclient.contrib.ssl; + +import org.apache.cloudstack.utils.security.SSLUtils; +import org.apache.commons.httpclient.ConnectTimeoutException; +import org.apache.commons.httpclient.HttpClientError; +import org.apache.commons.httpclient.params.HttpConnectionParams; +import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.net.SocketFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.TrustManager; +import java.io.IOException; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.net.SocketAddress; +import java.net.UnknownHostException; + +/** + * <p> + * EasySSLProtocolSocketFactory can be used to create SSL {@link Socket}s + * that accept self-signed certificates. + * </p> + * <p> + * This socket factory SHOULD NOT be used for productive systems + * due to security reasons, unless it is a concious decision and + * you are perfectly aware of security implications of accepting + * self-signed certificates + * </p> + * + * <p> + * Example of using custom protocol socket factory for a specific host: + * <pre> + * Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443); + * + * URI uri = new URI("https://localhost/", true); + * // use relative url only + * GetMethod httpget = new GetMethod(uri.getPathQuery()); + * HostConfiguration hc = new HostConfiguration(); + * hc.setHost(uri.getHost(), uri.getPort(), easyhttps); + * HttpClient client = new HttpClient(); + * client.executeMethod(hc, httpget); + * </pre> + * </p> + * <p> + * Example of using custom protocol socket factory per default instead of the standard one: + * <pre> + * Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443); + * Protocol.registerProtocol("https", easyhttps); + * + * HttpClient client = new HttpClient(); + * GetMethod httpget = new GetMethod("https://localhost/"); + * client.executeMethod(httpget); + * </pre> + * </p> + * + * @author <a href="mailto:oleg -at- ural.ru">Oleg Kalnichevski</a> + * + * <p> + * DISCLAIMER: HttpClient developers DO NOT actively support this component. + * The component is provided as a reference material, which may be inappropriate + * for use without additional customization. + * </p> + */ + +public class EasySSLProtocolSocketFactory implements ProtocolSocketFactory { + + /** Log object for this class. */ + private static final Log LOG = LogFactory.getLog(EasySSLProtocolSocketFactory.class); + + private SSLContext sslcontext = null; + + /** + * Constructor for EasySSLProtocolSocketFactory. + */ + public EasySSLProtocolSocketFactory() { + super(); + } + + private static SSLContext createEasySSLContext() { + try { + SSLContext context = SSLUtils.getSSLContext(); + context.init(null, new TrustManager[] {new EasyX509TrustManager(null)}, null); + return context; + } catch (Exception e) { + LOG.error(e.getMessage(), e); + throw new HttpClientError(e.toString()); + } + } + + private SSLContext getSSLContext() { + if (sslcontext == null) { + sslcontext = createEasySSLContext(); + } + return sslcontext; + } + + /** + * @see ProtocolSocketFactory#createSocket(java.lang.String,int,java.net.InetAddress,int) + */ + @Override + public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort) throws IOException, UnknownHostException { + Socket socket = getSSLContext().getSocketFactory().createSocket(host, port, clientHost, clientPort); + if (socket instanceof SSLSocket) { + ((SSLSocket)socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)socket).getEnabledProtocols())); + } + return socket; + } + + /** + * Attempts to get a new socket connection to the given host within the given time limit. + * <p> + * To circumvent the limitations of older JREs that do not support connect timeout a + * controller thread is executed. The controller thread attempts to create a new socket + * within the given limit of time. If socket constructor does not return until the + * timeout expires, the controller terminates and throws an {@link ConnectTimeoutException} + * </p> + * + * @param host the host name/IP + * @param port the port on the host + * @param localAddress the local host name/IP to bind the socket to + * @param localPort the port on the local machine + * @param params {@link HttpConnectionParams Http connection parameters} + * + * @return Socket a new socket + * + * @throws IOException if an I/O error occurs while creating the socket + * @throws UnknownHostException if the IP address of the host cannot be + * determined + */ + @Override + public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params) + throws IOException, UnknownHostException, ConnectTimeoutException { + if (params == null) { + throw new IllegalArgumentException("Parameters may not be null"); + } + int timeout = params.getConnectionTimeout(); + SocketFactory socketfactory = getSSLContext().getSocketFactory(); + if (timeout == 0) { + Socket socket = socketfactory.createSocket(host, port, localAddress, localPort); + if (socket instanceof SSLSocket) { + ((SSLSocket)socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)socket).getEnabledProtocols())); + } + return socket; + } else { + Socket socket = socketfactory.createSocket(); + if (socket instanceof SSLSocket) { + ((SSLSocket)socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)socket).getEnabledProtocols())); + } + SocketAddress localaddr = new InetSocketAddress(localAddress, localPort); + SocketAddress remoteaddr = new InetSocketAddress(host, port); + socket.bind(localaddr); + socket.connect(remoteaddr, timeout); + return socket; + } + } + + /** + * @see ProtocolSocketFactory#createSocket(java.lang.String,int) + */ + @Override + public Socket createSocket(String host, int port) throws IOException, UnknownHostException { + Socket socket = (Socket) getSSLContext().getSocketFactory().createSocket(host, port); + if (socket instanceof SSLSocket) { + ((SSLSocket)socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)socket).getEnabledProtocols())); + } + return socket; + } + + public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException { + Socket s = getSSLContext().getSocketFactory().createSocket(socket, host, port, autoClose); + if (s instanceof SSLSocket) { + ((SSLSocket)s).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)s).getEnabledProtocols())); + } + return s; + } + + @Override + public boolean equals(Object obj) { + return ((obj != null) && obj.getClass().equals(EasySSLProtocolSocketFactory.class)); + } + + @Override + public int hashCode() { + return EasySSLProtocolSocketFactory.class.hashCode(); + } + +}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/java/org/apache/commons/httpclient/contrib/ssl/EasyX509TrustManager.java ---------------------------------------------------------------------- diff --git a/utils/src/main/java/org/apache/commons/httpclient/contrib/ssl/EasyX509TrustManager.java b/utils/src/main/java/org/apache/commons/httpclient/contrib/ssl/EasyX509TrustManager.java new file mode 100644 index 0000000..eb23eb2 --- /dev/null +++ b/utils/src/main/java/org/apache/commons/httpclient/contrib/ssl/EasyX509TrustManager.java @@ -0,0 +1,110 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package org.apache.commons.httpclient.contrib.ssl; + +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; + +import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactory; +import javax.net.ssl.X509TrustManager; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** + * <p> + * EasyX509TrustManager unlike default {@link X509TrustManager} accepts + * self-signed certificates. + * </p> + * <p> + * This trust manager SHOULD NOT be used for productive systems + * due to security reasons, unless it is a concious decision and + * you are perfectly aware of security implications of accepting + * self-signed certificates + * </p> + * + * @author <a href="mailto:adrian.sut...@ephox.com">Adrian Sutton</a> + * @author <a href="mailto:o...@ural.ru">Oleg Kalnichevski</a> + * + * <p> + * DISCLAIMER: HttpClient developers DO NOT actively support this component. + * The component is provided as a reference material, which may be inappropriate + * for use without additional customization. + * </p> + */ + +public class EasyX509TrustManager implements X509TrustManager { + private X509TrustManager standardTrustManager = null; + + /** Log object for this class. */ + private static final Log LOG = LogFactory.getLog(EasyX509TrustManager.class); + + /** + * Constructor for EasyX509TrustManager. + */ + public EasyX509TrustManager(KeyStore keystore) throws NoSuchAlgorithmException, KeyStoreException { + super(); + TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + factory.init(keystore); + TrustManager[] trustmanagers = factory.getTrustManagers(); + if (trustmanagers.length == 0) { + throw new NoSuchAlgorithmException("no trust manager found"); + } + standardTrustManager = (X509TrustManager)trustmanagers[0]; + } + + /** + * @see javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate[],String authType) + */ + @Override + public void checkClientTrusted(X509Certificate[] certificates, String authType) throws CertificateException { + standardTrustManager.checkClientTrusted(certificates, authType); + } + + /** + * @see javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[],String authType) + */ + @Override + public void checkServerTrusted(X509Certificate[] certificates, String authType) throws CertificateException { + if ((certificates != null) && LOG.isDebugEnabled()) { + LOG.debug("Server certificate chain:"); + for (int i = 0; i < certificates.length; i++) { + LOG.debug("X509Certificate[" + i + "]=" + certificates[i]); + } + } + if ((certificates != null) && (certificates.length == 1)) { + certificates[0].checkValidity(); + } else { + standardTrustManager.checkServerTrusted(certificates, authType); + } + } + + /** + * @see javax.net.ssl.X509TrustManager#getAcceptedIssuers() + */ + @Override + public X509Certificate[] getAcceptedIssuers() { + return standardTrustManager.getAcceptedIssuers(); + } +} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/main/resources/cloud.keystore ---------------------------------------------------------------------- diff --git a/utils/src/main/resources/cloud.keystore b/utils/src/main/resources/cloud.keystore new file mode 100644 index 0000000..33d7777 Binary files /dev/null and b/utils/src/main/resources/cloud.keystore differ http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/org/apache/cloudstack/utils/baremetal/BaremetalUtils.java ---------------------------------------------------------------------- diff --git a/utils/src/org/apache/cloudstack/utils/baremetal/BaremetalUtils.java b/utils/src/org/apache/cloudstack/utils/baremetal/BaremetalUtils.java deleted file mode 100644 index 85704a5..0000000 --- a/utils/src/org/apache/cloudstack/utils/baremetal/BaremetalUtils.java +++ /dev/null @@ -1,24 +0,0 @@ -// -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -// - -package org.apache.cloudstack.utils.baremetal; - -public class BaremetalUtils { - public static final String BAREMETAL_SYSTEM_ACCOUNT_NAME = "baremetal-system-account"; -} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/org/apache/cloudstack/utils/graphite/GraphiteClient.java ---------------------------------------------------------------------- diff --git a/utils/src/org/apache/cloudstack/utils/graphite/GraphiteClient.java b/utils/src/org/apache/cloudstack/utils/graphite/GraphiteClient.java deleted file mode 100644 index 4143f09..0000000 --- a/utils/src/org/apache/cloudstack/utils/graphite/GraphiteClient.java +++ /dev/null @@ -1,123 +0,0 @@ -// -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -// - -package org.apache.cloudstack.utils.graphite; - -import java.io.IOException; -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.HashMap; -import java.util.Map; - -public class GraphiteClient { - - private String graphiteHost; - private int graphitePort; - - /** - * Create a new Graphite client - * - * @param graphiteHost Hostname of the Graphite host - * @param graphitePort UDP port of the Graphite host - */ - public GraphiteClient(String graphiteHost, int graphitePort) { - this.graphiteHost = graphiteHost; - this.graphitePort = graphitePort; - } - - /** - * Create a new Graphite client - * - * @param graphiteHost Hostname of the Graphite host. Will default to port 2003 - */ - public GraphiteClient(String graphiteHost) { - this.graphiteHost = graphiteHost; - graphitePort = 2003; - } - - /** - * Get the current system timestamp to pass to Graphite - * - * @return Seconds passed since epoch (01-01-1970) - */ - protected long getCurrentSystemTime() { - return System.currentTimeMillis() / 1000; - } - - /** - * Send a array of metrics to graphite. - * - * @param metrics the metrics as key-value-pairs - */ - public void sendMetrics(Map<String, Integer> metrics) { - sendMetrics(metrics, getCurrentSystemTime()); - } - - /** - * Send a array of metrics with a given timestamp to graphite. - * - * @param metrics the metrics as key-value-pairs - * @param timeStamp the timestamp - */ - public void sendMetrics(Map<String, Integer> metrics, long timeStamp) { - try (DatagramSocket sock = new DatagramSocket()){ - java.security.Security.setProperty("networkaddress.cache.ttl", "0"); - InetAddress addr = InetAddress.getByName(this.graphiteHost); - - for (Map.Entry<String, Integer> metric: metrics.entrySet()) { - byte[] message = new String(metric.getKey() + " " + metric.getValue() + " " + timeStamp + "\n").getBytes(); - DatagramPacket packet = new DatagramPacket(message, message.length, addr, graphitePort); - sock.send(packet); - } - } catch (UnknownHostException e) { - throw new GraphiteException("Unknown host: " + graphiteHost); - } catch (IOException e) { - throw new GraphiteException("Error while writing to graphite: " + e.getMessage(), e); - } - } - - /** - * Send a single metric with the current time as timestamp to graphite. - * - * @param key The metric key - * @param value the metric value - * - * @throws GraphiteException if sending data to graphite failed - */ - public void sendMetric(String key, int value) { - sendMetric(key, value, getCurrentSystemTime()); - } - - /** - * Send a single metric with a given timestamp to graphite. - * - * @param key The metric key - * @param value The metric value - * @param timeStamp the timestamp to use - * - * @throws GraphiteException if sending data to graphite failed - */ - public void sendMetric(final String key, final int value, long timeStamp) { - HashMap metrics = new HashMap<String, Integer>(); - metrics.put(key, value); - sendMetrics(metrics, timeStamp); - } -} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/org/apache/cloudstack/utils/graphite/GraphiteException.java ---------------------------------------------------------------------- diff --git a/utils/src/org/apache/cloudstack/utils/graphite/GraphiteException.java b/utils/src/org/apache/cloudstack/utils/graphite/GraphiteException.java deleted file mode 100644 index 9148764..0000000 --- a/utils/src/org/apache/cloudstack/utils/graphite/GraphiteException.java +++ /dev/null @@ -1,31 +0,0 @@ -// -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -// - -package org.apache.cloudstack.utils.graphite; - -public class GraphiteException extends RuntimeException { - - public GraphiteException(String message) { - super(message); - } - - public GraphiteException(String message, Throwable cause) { - super(message, cause); - } -} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/org/apache/cloudstack/utils/identity/ManagementServerNode.java ---------------------------------------------------------------------- diff --git a/utils/src/org/apache/cloudstack/utils/identity/ManagementServerNode.java b/utils/src/org/apache/cloudstack/utils/identity/ManagementServerNode.java deleted file mode 100644 index fdd80f7..0000000 --- a/utils/src/org/apache/cloudstack/utils/identity/ManagementServerNode.java +++ /dev/null @@ -1,63 +0,0 @@ -// -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -// - -package org.apache.cloudstack.utils.identity; - -import javax.ejb.Local; - -import org.apache.log4j.Logger; - -import com.cloud.utils.component.AdapterBase; -import com.cloud.utils.component.ComponentLifecycle; -import com.cloud.utils.component.SystemIntegrityChecker; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.utils.net.MacAddress; - -@Local(value = {SystemIntegrityChecker.class}) -public class ManagementServerNode extends AdapterBase implements SystemIntegrityChecker { - private static final Logger s_logger = Logger.getLogger(ManagementServerNode.class); - - private static final long s_nodeId = MacAddress.getMacAddress().toLong(); - - public ManagementServerNode() { - setRunLevel(ComponentLifecycle.RUN_LEVEL_FRAMEWORK_BOOTSTRAP); - } - - @Override - public void check() { - if (s_nodeId <= 0) { - throw new CloudRuntimeException("Unable to get the management server node id"); - } - } - - public static long getManagementServerId() { - return s_nodeId; - } - - @Override - public boolean start() { - try { - check(); - } catch (Exception e) { - s_logger.error("System integrity check exception", e); - System.exit(1); - } - return true; - } -} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/org/apache/cloudstack/utils/imagestore/ImageStoreUtil.java ---------------------------------------------------------------------- diff --git a/utils/src/org/apache/cloudstack/utils/imagestore/ImageStoreUtil.java b/utils/src/org/apache/cloudstack/utils/imagestore/ImageStoreUtil.java deleted file mode 100644 index ed13360..0000000 --- a/utils/src/org/apache/cloudstack/utils/imagestore/ImageStoreUtil.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.cloudstack.utils.imagestore; - -import com.cloud.utils.script.Script; -import org.apache.commons.lang.StringUtils; -import org.apache.log4j.Logger; - -public class ImageStoreUtil { - public static final Logger s_logger = Logger.getLogger(ImageStoreUtil.class.getName()); - - public static String generatePostUploadUrl(String ssvmUrlDomain, String ipAddress, String uuid) { - String hostname = ipAddress; - - //if ssvm url domain is present, use it to construct hostname in the format 1-2-3-4.domain - // if the domain name is not present, ssl validation fails and has to be ignored - if(StringUtils.isNotBlank(ssvmUrlDomain)) { - hostname = ipAddress.replace(".", "-"); - hostname = hostname + ssvmUrlDomain.substring(1); - } - - //only https works with postupload and url format is fixed - return "https://" + hostname + "/upload/" + uuid; - } - - // given a path, returns empty if path is supported image, and the file type if unsupported - // this is meant to catch things like accidental upload of ASCII text .vmdk descriptor - public static String checkTemplateFormat(String path, String uripath) { - // note 'path' was generated by us so it should be safe on the cmdline, be wary of 'url' - String command = "file "; - if (isCompressedExtension(uripath)) { - command = "file -z "; - } - String output = Script.runSimpleBashScript(command + path + " | cut -d: -f2", 60000); - - // vmdk - if ((output.contains("VMware") || output.contains("data")) && isCorrectExtension(uripath, "vmdk")) { - s_logger.debug("File at path " + path + " looks like a vmware image :" + output); - return ""; - } - // raw - if ((output.contains("x86 boot") || output.contains("data")) && (isCorrectExtension(uripath, "raw") || isCorrectExtension(uripath, "img"))) { - s_logger.debug("File at path " + path + " looks like a raw image :" + output); - return ""; - } - // qcow2 - if (output.contains("QEMU QCOW") && isCorrectExtension(uripath, "qcow2")) { - s_logger.debug("File at path " + path + " looks like QCOW2 : " + output); - return ""; - } - // vhd - if (output.contains("Microsoft Disk Image") && (isCorrectExtension(uripath, "vhd") || isCorrectExtension(uripath, "vhdx"))) { - s_logger.debug("File at path " + path + " looks like vhd : " + output); - return ""; - } - // ova - if (output.contains("POSIX tar") && isCorrectExtension(uripath, "ova")) { - s_logger.debug("File at path " + path + " looks like ova : " + output); - return ""; - } - - //lxc - if (output.contains("POSIX tar") && isCorrectExtension(uripath, "tar")) { - s_logger.debug("File at path " + path + " looks like just tar : " + output); - return ""; - } - - if (output.contains("ISO 9660") && isCorrectExtension(uripath, "iso")) { - s_logger.debug("File at path " + path + " looks like an iso : " + output); - return ""; - } - return output; - } - - private static boolean isCorrectExtension(String path, String ext) { - if (path.toLowerCase().endsWith(ext) - || path.toLowerCase().endsWith(ext + ".gz") - || path.toLowerCase().endsWith(ext + ".bz2") - || path.toLowerCase().endsWith(ext + ".zip")) { - return true; - } - return false; - } - - private static boolean isCompressedExtension(String path) { - if (path.toLowerCase().endsWith(".gz") - || path.toLowerCase().endsWith(".bz2") - || path.toLowerCase().endsWith(".zip")) { - return true; - } - return false; - } -} - http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/org/apache/cloudstack/utils/security/SSLUtils.java ---------------------------------------------------------------------- diff --git a/utils/src/org/apache/cloudstack/utils/security/SSLUtils.java b/utils/src/org/apache/cloudstack/utils/security/SSLUtils.java deleted file mode 100644 index c1fc2d6..0000000 --- a/utils/src/org/apache/cloudstack/utils/security/SSLUtils.java +++ /dev/null @@ -1,58 +0,0 @@ -// -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -// - -package org.apache.cloudstack.utils.security; - -import org.apache.log4j.Logger; - -import javax.net.ssl.SSLContext; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; - -public class SSLUtils { - public static final Logger s_logger = Logger.getLogger(SSLUtils.class); - - public static String[] getSupportedProtocols(String[] protocols) { - Set<String> set = new HashSet<String>(); - for (String s : protocols) { - if (s.equals("SSLv3") || s.equals("SSLv2Hello")) { - continue; - } - set.add(s); - } - return (String[]) set.toArray(new String[set.size()]); - } - - public static String[] getSupportedCiphers() throws NoSuchAlgorithmException { - String[] availableCiphers = getSSLContext().getSocketFactory().getSupportedCipherSuites(); - Arrays.sort(availableCiphers); - return availableCiphers; - } - - public static SSLContext getSSLContext() throws NoSuchAlgorithmException { - return SSLContext.getInstance("TLSv1"); - } - - public static SSLContext getSSLContext(String provider) throws NoSuchAlgorithmException, NoSuchProviderException { - return SSLContext.getInstance("TLSv1", provider); - } -} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/org/apache/cloudstack/utils/security/SecureSSLSocketFactory.java ---------------------------------------------------------------------- diff --git a/utils/src/org/apache/cloudstack/utils/security/SecureSSLSocketFactory.java b/utils/src/org/apache/cloudstack/utils/security/SecureSSLSocketFactory.java deleted file mode 100644 index fa9d492..0000000 --- a/utils/src/org/apache/cloudstack/utils/security/SecureSSLSocketFactory.java +++ /dev/null @@ -1,124 +0,0 @@ -// -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -// - -package org.apache.cloudstack.utils.security; - -import org.apache.log4j.Logger; - -import javax.net.ssl.KeyManager; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSocket; -import javax.net.ssl.SSLSocketFactory; -import javax.net.ssl.TrustManager; -import java.io.IOException; -import java.net.InetAddress; -import java.net.Socket; -import java.net.UnknownHostException; -import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; - -public class SecureSSLSocketFactory extends SSLSocketFactory { - - public static final Logger s_logger = Logger.getLogger(SecureSSLSocketFactory.class); - private SSLContext _sslContext; - - public SecureSSLSocketFactory() throws NoSuchAlgorithmException { - _sslContext = SSLUtils.getSSLContext(); - } - - public SecureSSLSocketFactory(SSLContext sslContext) throws NoSuchAlgorithmException { - if (sslContext != null) { - _sslContext = sslContext; - } else { - _sslContext = SSLUtils.getSSLContext(); - } - } - - public SecureSSLSocketFactory(KeyManager[] km, TrustManager[] tm, SecureRandom random) throws NoSuchAlgorithmException, KeyManagementException, IOException { - _sslContext = SSLUtils.getSSLContext(); - _sslContext.init(km, tm, random); - } - - @Override - public String[] getDefaultCipherSuites() { - return getSupportedCipherSuites(); - } - - @Override - public String[] getSupportedCipherSuites() { - String[] ciphers = null; - try { - ciphers = SSLUtils.getSupportedCiphers(); - } catch (NoSuchAlgorithmException e) { - s_logger.error("SecureSSLSocketFactory::getDefaultCipherSuites found no cipher suites"); - } - return ciphers; - } - - @Override - public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException { - SSLSocketFactory factory = _sslContext.getSocketFactory(); - Socket socket = factory.createSocket(s, host, port, autoClose); - if (socket instanceof SSLSocket) { - ((SSLSocket)socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)socket).getEnabledProtocols())); - } - return socket; - } - - @Override - public Socket createSocket(String host, int port) throws IOException, UnknownHostException { - SSLSocketFactory factory = _sslContext.getSocketFactory(); - Socket socket = factory.createSocket(host, port); - if (socket instanceof SSLSocket) { - ((SSLSocket)socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)socket).getEnabledProtocols())); - } - return socket; - } - - @Override - public Socket createSocket(String host, int port, InetAddress inetAddress, int localPort) throws IOException, UnknownHostException { - SSLSocketFactory factory = _sslContext.getSocketFactory(); - Socket socket = factory.createSocket(host, port, inetAddress, localPort); - if (socket instanceof SSLSocket) { - ((SSLSocket)socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)socket).getEnabledProtocols())); - } - return socket; - } - - @Override - public Socket createSocket(InetAddress inetAddress, int localPort) throws IOException { - SSLSocketFactory factory = _sslContext.getSocketFactory(); - Socket socket = factory.createSocket(inetAddress, localPort); - if (socket instanceof SSLSocket) { - ((SSLSocket)socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)socket).getEnabledProtocols())); - } - return socket; - } - - @Override - public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException { - SSLSocketFactory factory = this._sslContext.getSocketFactory(); - Socket socket = factory.createSocket(address, port, localAddress, localPort); - if (socket instanceof SSLSocket) { - ((SSLSocket)socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)socket).getEnabledProtocols())); - } - return socket; - } -} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/org/apache/cloudstack/utils/usage/UsageUtils.java ---------------------------------------------------------------------- diff --git a/utils/src/org/apache/cloudstack/utils/usage/UsageUtils.java b/utils/src/org/apache/cloudstack/utils/usage/UsageUtils.java deleted file mode 100644 index a97aed1..0000000 --- a/utils/src/org/apache/cloudstack/utils/usage/UsageUtils.java +++ /dev/null @@ -1,24 +0,0 @@ -// -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -// - -package org.apache.cloudstack.utils.usage; - -public class UsageUtils { - public static final int USAGE_AGGREGATION_RANGE_MIN = 1; -} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/org/apache/commons/httpclient/contrib/ssl/EasySSLProtocolSocketFactory.java ---------------------------------------------------------------------- diff --git a/utils/src/org/apache/commons/httpclient/contrib/ssl/EasySSLProtocolSocketFactory.java b/utils/src/org/apache/commons/httpclient/contrib/ssl/EasySSLProtocolSocketFactory.java deleted file mode 100644 index 5ff5819..0000000 --- a/utils/src/org/apache/commons/httpclient/contrib/ssl/EasySSLProtocolSocketFactory.java +++ /dev/null @@ -1,210 +0,0 @@ -// -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -// - -package org.apache.commons.httpclient.contrib.ssl; - -import org.apache.cloudstack.utils.security.SSLUtils; -import org.apache.commons.httpclient.ConnectTimeoutException; -import org.apache.commons.httpclient.HttpClientError; -import org.apache.commons.httpclient.params.HttpConnectionParams; -import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.net.SocketFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSocket; -import javax.net.ssl.TrustManager; -import java.io.IOException; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.Socket; -import java.net.SocketAddress; -import java.net.UnknownHostException; - -/** - * <p> - * EasySSLProtocolSocketFactory can be used to create SSL {@link Socket}s - * that accept self-signed certificates. - * </p> - * <p> - * This socket factory SHOULD NOT be used for productive systems - * due to security reasons, unless it is a concious decision and - * you are perfectly aware of security implications of accepting - * self-signed certificates - * </p> - * - * <p> - * Example of using custom protocol socket factory for a specific host: - * <pre> - * Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443); - * - * URI uri = new URI("https://localhost/", true); - * // use relative url only - * GetMethod httpget = new GetMethod(uri.getPathQuery()); - * HostConfiguration hc = new HostConfiguration(); - * hc.setHost(uri.getHost(), uri.getPort(), easyhttps); - * HttpClient client = new HttpClient(); - * client.executeMethod(hc, httpget); - * </pre> - * </p> - * <p> - * Example of using custom protocol socket factory per default instead of the standard one: - * <pre> - * Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443); - * Protocol.registerProtocol("https", easyhttps); - * - * HttpClient client = new HttpClient(); - * GetMethod httpget = new GetMethod("https://localhost/"); - * client.executeMethod(httpget); - * </pre> - * </p> - * - * @author <a href="mailto:oleg -at- ural.ru">Oleg Kalnichevski</a> - * - * <p> - * DISCLAIMER: HttpClient developers DO NOT actively support this component. - * The component is provided as a reference material, which may be inappropriate - * for use without additional customization. - * </p> - */ - -public class EasySSLProtocolSocketFactory implements ProtocolSocketFactory { - - /** Log object for this class. */ - private static final Log LOG = LogFactory.getLog(EasySSLProtocolSocketFactory.class); - - private SSLContext sslcontext = null; - - /** - * Constructor for EasySSLProtocolSocketFactory. - */ - public EasySSLProtocolSocketFactory() { - super(); - } - - private static SSLContext createEasySSLContext() { - try { - SSLContext context = SSLUtils.getSSLContext(); - context.init(null, new TrustManager[] {new EasyX509TrustManager(null)}, null); - return context; - } catch (Exception e) { - LOG.error(e.getMessage(), e); - throw new HttpClientError(e.toString()); - } - } - - private SSLContext getSSLContext() { - if (sslcontext == null) { - sslcontext = createEasySSLContext(); - } - return sslcontext; - } - - /** - * @see ProtocolSocketFactory#createSocket(java.lang.String,int,java.net.InetAddress,int) - */ - @Override - public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort) throws IOException, UnknownHostException { - Socket socket = getSSLContext().getSocketFactory().createSocket(host, port, clientHost, clientPort); - if (socket instanceof SSLSocket) { - ((SSLSocket)socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)socket).getEnabledProtocols())); - } - return socket; - } - - /** - * Attempts to get a new socket connection to the given host within the given time limit. - * <p> - * To circumvent the limitations of older JREs that do not support connect timeout a - * controller thread is executed. The controller thread attempts to create a new socket - * within the given limit of time. If socket constructor does not return until the - * timeout expires, the controller terminates and throws an {@link ConnectTimeoutException} - * </p> - * - * @param host the host name/IP - * @param port the port on the host - * @param localAddress the local host name/IP to bind the socket to - * @param localPort the port on the local machine - * @param params {@link HttpConnectionParams Http connection parameters} - * - * @return Socket a new socket - * - * @throws IOException if an I/O error occurs while creating the socket - * @throws UnknownHostException if the IP address of the host cannot be - * determined - */ - @Override - public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params) - throws IOException, UnknownHostException, ConnectTimeoutException { - if (params == null) { - throw new IllegalArgumentException("Parameters may not be null"); - } - int timeout = params.getConnectionTimeout(); - SocketFactory socketfactory = getSSLContext().getSocketFactory(); - if (timeout == 0) { - Socket socket = socketfactory.createSocket(host, port, localAddress, localPort); - if (socket instanceof SSLSocket) { - ((SSLSocket)socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)socket).getEnabledProtocols())); - } - return socket; - } else { - Socket socket = socketfactory.createSocket(); - if (socket instanceof SSLSocket) { - ((SSLSocket)socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)socket).getEnabledProtocols())); - } - SocketAddress localaddr = new InetSocketAddress(localAddress, localPort); - SocketAddress remoteaddr = new InetSocketAddress(host, port); - socket.bind(localaddr); - socket.connect(remoteaddr, timeout); - return socket; - } - } - - /** - * @see ProtocolSocketFactory#createSocket(java.lang.String,int) - */ - @Override - public Socket createSocket(String host, int port) throws IOException, UnknownHostException { - Socket socket = (Socket) getSSLContext().getSocketFactory().createSocket(host, port); - if (socket instanceof SSLSocket) { - ((SSLSocket)socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)socket).getEnabledProtocols())); - } - return socket; - } - - public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException { - Socket s = getSSLContext().getSocketFactory().createSocket(socket, host, port, autoClose); - if (s instanceof SSLSocket) { - ((SSLSocket)s).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)s).getEnabledProtocols())); - } - return s; - } - - @Override - public boolean equals(Object obj) { - return ((obj != null) && obj.getClass().equals(EasySSLProtocolSocketFactory.class)); - } - - @Override - public int hashCode() { - return EasySSLProtocolSocketFactory.class.hashCode(); - } - -} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/org/apache/commons/httpclient/contrib/ssl/EasyX509TrustManager.java ---------------------------------------------------------------------- diff --git a/utils/src/org/apache/commons/httpclient/contrib/ssl/EasyX509TrustManager.java b/utils/src/org/apache/commons/httpclient/contrib/ssl/EasyX509TrustManager.java deleted file mode 100644 index eb23eb2..0000000 --- a/utils/src/org/apache/commons/httpclient/contrib/ssl/EasyX509TrustManager.java +++ /dev/null @@ -1,110 +0,0 @@ -// -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -// - -package org.apache.commons.httpclient.contrib.ssl; - -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; - -import javax.net.ssl.TrustManager; -import javax.net.ssl.TrustManagerFactory; -import javax.net.ssl.X509TrustManager; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * <p> - * EasyX509TrustManager unlike default {@link X509TrustManager} accepts - * self-signed certificates. - * </p> - * <p> - * This trust manager SHOULD NOT be used for productive systems - * due to security reasons, unless it is a concious decision and - * you are perfectly aware of security implications of accepting - * self-signed certificates - * </p> - * - * @author <a href="mailto:adrian.sut...@ephox.com">Adrian Sutton</a> - * @author <a href="mailto:o...@ural.ru">Oleg Kalnichevski</a> - * - * <p> - * DISCLAIMER: HttpClient developers DO NOT actively support this component. - * The component is provided as a reference material, which may be inappropriate - * for use without additional customization. - * </p> - */ - -public class EasyX509TrustManager implements X509TrustManager { - private X509TrustManager standardTrustManager = null; - - /** Log object for this class. */ - private static final Log LOG = LogFactory.getLog(EasyX509TrustManager.class); - - /** - * Constructor for EasyX509TrustManager. - */ - public EasyX509TrustManager(KeyStore keystore) throws NoSuchAlgorithmException, KeyStoreException { - super(); - TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - factory.init(keystore); - TrustManager[] trustmanagers = factory.getTrustManagers(); - if (trustmanagers.length == 0) { - throw new NoSuchAlgorithmException("no trust manager found"); - } - standardTrustManager = (X509TrustManager)trustmanagers[0]; - } - - /** - * @see javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate[],String authType) - */ - @Override - public void checkClientTrusted(X509Certificate[] certificates, String authType) throws CertificateException { - standardTrustManager.checkClientTrusted(certificates, authType); - } - - /** - * @see javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[],String authType) - */ - @Override - public void checkServerTrusted(X509Certificate[] certificates, String authType) throws CertificateException { - if ((certificates != null) && LOG.isDebugEnabled()) { - LOG.debug("Server certificate chain:"); - for (int i = 0; i < certificates.length; i++) { - LOG.debug("X509Certificate[" + i + "]=" + certificates[i]); - } - } - if ((certificates != null) && (certificates.length == 1)) { - certificates[0].checkValidity(); - } else { - standardTrustManager.checkServerTrusted(certificates, authType); - } - } - - /** - * @see javax.net.ssl.X509TrustManager#getAcceptedIssuers() - */ - @Override - public X509Certificate[] getAcceptedIssuers() { - return standardTrustManager.getAcceptedIssuers(); - } -} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/DateUtilTest.java ---------------------------------------------------------------------- diff --git a/utils/src/test/java/com/cloud/utils/DateUtilTest.java b/utils/src/test/java/com/cloud/utils/DateUtilTest.java new file mode 100644 index 0000000..ba88505 --- /dev/null +++ b/utils/src/test/java/com/cloud/utils/DateUtilTest.java @@ -0,0 +1,60 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// +package com.cloud.utils; + +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.TimeZone; + +import com.cloud.utils.DateUtil.IntervalType; + + +public class DateUtilTest { + + // command line test tool + public static void main(String[] args) { + TimeZone localTimezone = Calendar.getInstance().getTimeZone(); + TimeZone gmtTimezone = TimeZone.getTimeZone("GMT"); + TimeZone estTimezone = TimeZone.getTimeZone("EST"); + + Date time = new Date(); + System.out.println("local time :" + DateUtil.getDateDisplayString(localTimezone, time)); + System.out.println("GMT time :" + DateUtil.getDateDisplayString(gmtTimezone, time)); + System.out.println("EST time :" + DateUtil.getDateDisplayString(estTimezone, time)); + //Test next run time. Expects interval and schedule as arguments + if (args.length == 2) { + System.out.println("Next run time: " + DateUtil.getNextRunTime(IntervalType.getIntervalType(args[0]), args[1], "GMT", time).toString()); + } + + time = new Date(); + DateFormat dfDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'Z"); + String str = dfDate.format(time); + System.out.println("Formated TZ time string : " + str); + try { + Date dtParsed = DateUtil.parseTZDateString(str); + System.out.println("Parsed TZ time string : " + dtParsed.toString()); + } catch (ParseException e) { + System.err.println("Parsing failed\n string : " + str + "\nexception :" + e.getLocalizedMessage()); + } + } + +} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/DummyImpl.java ---------------------------------------------------------------------- diff --git a/utils/src/test/java/com/cloud/utils/DummyImpl.java b/utils/src/test/java/com/cloud/utils/DummyImpl.java new file mode 100644 index 0000000..e2360c0 --- /dev/null +++ b/utils/src/test/java/com/cloud/utils/DummyImpl.java @@ -0,0 +1,31 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils; + +import org.springframework.stereotype.Component; + +@Component +public class DummyImpl implements DummyInterface { + + @Override + public void foo() { + System.out.println("Basic foo implementation"); + } +} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/DummyInterface.java ---------------------------------------------------------------------- diff --git a/utils/src/test/java/com/cloud/utils/DummyInterface.java b/utils/src/test/java/com/cloud/utils/DummyInterface.java new file mode 100644 index 0000000..4f6a777 --- /dev/null +++ b/utils/src/test/java/com/cloud/utils/DummyInterface.java @@ -0,0 +1,24 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils; + +public interface DummyInterface { + void foo(); +} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/DummyPremiumImpl.java ---------------------------------------------------------------------- diff --git a/utils/src/test/java/com/cloud/utils/DummyPremiumImpl.java b/utils/src/test/java/com/cloud/utils/DummyPremiumImpl.java new file mode 100644 index 0000000..9c71368 --- /dev/null +++ b/utils/src/test/java/com/cloud/utils/DummyPremiumImpl.java @@ -0,0 +1,28 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils; + +public class DummyPremiumImpl implements DummyInterface { + + @Override + public void foo() { + System.out.println("Premium foo implementation"); + } +} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/HttpUtilsTest.java ---------------------------------------------------------------------- diff --git a/utils/src/test/java/com/cloud/utils/HttpUtilsTest.java b/utils/src/test/java/com/cloud/utils/HttpUtilsTest.java new file mode 100644 index 0000000..e10a5a3 --- /dev/null +++ b/utils/src/test/java/com/cloud/utils/HttpUtilsTest.java @@ -0,0 +1,94 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils; + +import org.junit.Test; +import org.springframework.mock.web.MockHttpSession; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpSession; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +public class HttpUtilsTest { + + @Test + public void findCookieTest() { + Cookie[] cookies = null; + String cookieName = null; + + // null test + assertNull(HttpUtils.findCookie(cookies, cookieName)); + cookieName = ""; + assertNull(HttpUtils.findCookie(cookies, cookieName)); + + // value test + cookieName = "daakuBandar"; + cookies = new Cookie[]{new Cookie(cookieName, "someValue")}; + assertNull(HttpUtils.findCookie(cookies, "aalasiLangur")); + assertNotNull(HttpUtils.findCookie(cookies, cookieName)); + } + + @Test + public void validateSessionKeyTest() { + HttpSession session = null; + Map<String, Object[]> params = null; + String sessionKeyString = null; + Cookie[] cookies = null; + final String sessionKeyValue = "randomUniqueSessionID"; + + // session and sessionKeyString null test + assertFalse(HttpUtils.validateSessionKey(session, params, cookies, sessionKeyString)); + sessionKeyString = "sessionkey"; + assertFalse(HttpUtils.validateSessionKey(session, params, cookies, sessionKeyString)); + + // param and cookie null test + session = new MockHttpSession(); + session.setAttribute(sessionKeyString, sessionKeyValue); + assertFalse(HttpUtils.validateSessionKey(session, params, cookies, sessionKeyString)); + + // param null, cookies not null test + params = null; + cookies = new Cookie[]{new Cookie(sessionKeyString, sessionKeyValue)}; + assertFalse(HttpUtils.validateSessionKey(session, params, cookies, "randomString")); + assertTrue(HttpUtils.validateSessionKey(session, params, cookies, sessionKeyString)); + + // param not null, cookies null test + params = new HashMap<String, Object[]>(); + params.put(sessionKeyString, new String[]{"randomString"}); + cookies = null; + assertFalse(HttpUtils.validateSessionKey(session, params, cookies, sessionKeyString)); + params.put(sessionKeyString, new String[]{sessionKeyValue}); + assertTrue(HttpUtils.validateSessionKey(session, params, cookies, sessionKeyString)); + + // both param and cookies not null test + params = new HashMap<String, Object[]>(); + cookies = new Cookie[]{new Cookie(sessionKeyString, sessionKeyValue)}; + params.put(sessionKeyString, new String[]{"incorrectValue"}); + assertFalse(HttpUtils.validateSessionKey(session, params, cookies, sessionKeyString)); + params.put(sessionKeyString, new String[]{sessionKeyValue}); + assertTrue(HttpUtils.validateSessionKey(session, params, cookies, sessionKeyString)); + } +} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/NumbersUtilTest.java ---------------------------------------------------------------------- diff --git a/utils/src/test/java/com/cloud/utils/NumbersUtilTest.java b/utils/src/test/java/com/cloud/utils/NumbersUtilTest.java new file mode 100644 index 0000000..82b2305 --- /dev/null +++ b/utils/src/test/java/com/cloud/utils/NumbersUtilTest.java @@ -0,0 +1,47 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils; + +import static org.junit.Assert.assertEquals; + +import java.util.Locale; + +import org.junit.Test; + +public class NumbersUtilTest { + + @Test + public void toReadableSize() { + Locale.setDefault(Locale.US); // Fixed locale for the test + assertEquals("1.0000 TB", NumbersUtil.toReadableSize((1024l * 1024l * 1024l * 1024l))); + assertEquals("1.00 GB", NumbersUtil.toReadableSize(1024 * 1024 * 1024)); + assertEquals("1.00 MB", NumbersUtil.toReadableSize(1024 * 1024)); + assertEquals("1.00 KB", NumbersUtil.toReadableSize((1024))); + assertEquals("1023 bytes", NumbersUtil.toReadableSize((1023))); + } + + @Test + public void bytesToLong() { + assertEquals(0, NumbersUtil.bytesToLong(new byte[] {0, 0, 0, 0, 0, 0, 0, 0})); + assertEquals(1, NumbersUtil.bytesToLong(new byte[] {0, 0, 0, 0, 0, 0, 0, 1})); + assertEquals(257, NumbersUtil.bytesToLong(new byte[] {0, 0, 0, 0, 0, 0, 1, 1})); + } + +} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/PasswordGeneratorTest.java ---------------------------------------------------------------------- diff --git a/utils/src/test/java/com/cloud/utils/PasswordGeneratorTest.java b/utils/src/test/java/com/cloud/utils/PasswordGeneratorTest.java new file mode 100644 index 0000000..413b866 --- /dev/null +++ b/utils/src/test/java/com/cloud/utils/PasswordGeneratorTest.java @@ -0,0 +1,42 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils; + +import org.junit.Assert; +import org.junit.Test; + +public class PasswordGeneratorTest { + @Test + public void generateRandomPassword() { + // actual length is requested length, minimum length is 3 + Assert.assertTrue(PasswordGenerator.generateRandomPassword(0).length() == 3); + Assert.assertTrue(PasswordGenerator.generateRandomPassword(1).length() == 3); + Assert.assertTrue(PasswordGenerator.generateRandomPassword(5).length() == 5); + String password = PasswordGenerator.generateRandomPassword(8); + // TODO: this might give more help to bruteforcing than desired + // the actual behavior is that the first character is a random lowercase + // char + Assert.assertTrue(Character.isLowerCase(password.charAt(0))); + // the second character is a random upper case char + Assert.assertTrue(Character.isUpperCase(password.charAt(1))); + // and the third is a digit + Assert.assertTrue(Character.isDigit(password.charAt(2))); + } +} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/ProcessUtilTest.java ---------------------------------------------------------------------- diff --git a/utils/src/test/java/com/cloud/utils/ProcessUtilTest.java b/utils/src/test/java/com/cloud/utils/ProcessUtilTest.java new file mode 100644 index 0000000..38e25a3 --- /dev/null +++ b/utils/src/test/java/com/cloud/utils/ProcessUtilTest.java @@ -0,0 +1,76 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils; + +import java.io.File; +import java.io.IOException; + +import javax.naming.ConfigurationException; + +import junit.framework.Assert; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.lang.SystemUtils; +import org.junit.After; +import org.junit.Assume; +import org.junit.Before; +import org.junit.Test; + +public class ProcessUtilTest { + + File pidFile; + + @Before + public void setup() throws IOException { + pidFile = File.createTempFile("test", ".pid"); + } + + @After + public void cleanup() { + FileUtils.deleteQuietly(pidFile); + } + + @Test + public void pidCheck() throws ConfigurationException, IOException { + Assume.assumeTrue(SystemUtils.IS_OS_LINUX); + FileUtils.writeStringToFile(pidFile, "123456\n"); + ProcessUtil.pidCheck(pidFile.getParent(), pidFile.getName()); + String pidStr = FileUtils.readFileToString(pidFile); + Assert.assertFalse("pid can not be blank", pidStr.isEmpty()); + int pid = Integer.parseInt(pidStr.trim()); + int maxPid = Integer.parseInt(FileUtils.readFileToString(new File("/proc/sys/kernel/pid_max")).trim()); + Assert.assertTrue(pid <= maxPid); + } + + @Test(expected = ConfigurationException.class) + public void pidCheckBadPid() throws ConfigurationException, IOException { + Assume.assumeTrue(SystemUtils.IS_OS_LINUX); + FileUtils.writeStringToFile(pidFile, "intentionally not number"); + ProcessUtil.pidCheck(pidFile.getParent(), pidFile.getName()); + } + + @Test(expected = ConfigurationException.class) + public void pidCheckEmptyPid() throws ConfigurationException, IOException { + Assume.assumeTrue(SystemUtils.IS_OS_LINUX); + FileUtils.writeStringToFile(pidFile, "intentionally not number"); + ProcessUtil.pidCheck(pidFile.getParent(), pidFile.getName()); + } + +} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/PropertiesUtilsTest.java ---------------------------------------------------------------------- diff --git a/utils/src/test/java/com/cloud/utils/PropertiesUtilsTest.java b/utils/src/test/java/com/cloud/utils/PropertiesUtilsTest.java new file mode 100644 index 0000000..e20d7bf --- /dev/null +++ b/utils/src/test/java/com/cloud/utils/PropertiesUtilsTest.java @@ -0,0 +1,64 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils; + +import java.io.File; +import java.io.IOException; +import java.util.Map; +import java.util.Properties; + +import org.apache.commons.io.FileUtils; +import org.junit.Assert; +import org.junit.Test; + +public class PropertiesUtilsTest { + @Test + public void findConfigFile() { + File configFile = PropertiesUtil.findConfigFile("notexistingresource"); + Assert.assertNull(configFile); + } + + @Test + public void loadFromFile() throws IOException { + File file = File.createTempFile("test", ".properties"); + FileUtils.writeStringToFile(file, "a=b\nc=d\n"); + Properties properties = new Properties(); + PropertiesUtil.loadFromFile(properties, file); + Assert.assertEquals("b", properties.get("a")); + } + + @Test + public void loadPropertiesFromFile() throws IOException { + File file = File.createTempFile("test", ".properties"); + FileUtils.writeStringToFile(file, "a=b\nc=d\n"); + Properties properties = PropertiesUtil.loadFromFile(file); + Assert.assertEquals("b", properties.get("a")); + } + + @Test + public void processConfigFile() throws IOException { + File tempFile = File.createTempFile("temp", ".properties"); + FileUtils.writeStringToFile(tempFile, "a=b\nc=d\n"); + Map<String, String> config = PropertiesUtil.processConfigFile(new String[] {tempFile.getAbsolutePath()}); + Assert.assertEquals("b", config.get("a")); + Assert.assertEquals("d", config.get("c")); + tempFile.delete(); + } +} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/ReflectUtilTest.java ---------------------------------------------------------------------- diff --git a/utils/src/test/java/com/cloud/utils/ReflectUtilTest.java b/utils/src/test/java/com/cloud/utils/ReflectUtilTest.java new file mode 100644 index 0000000..c024a2e --- /dev/null +++ b/utils/src/test/java/com/cloud/utils/ReflectUtilTest.java @@ -0,0 +1,148 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils; + +import static com.cloud.utils.ReflectUtil.flattenProperties; +import static com.google.common.collect.Lists.newArrayList; +import static java.lang.Boolean.TRUE; +import static java.util.Collections.emptyList; +import static org.junit.Assert.assertEquals; + +import java.lang.reflect.Field; +import java.util.List; +import java.util.Set; + +import org.junit.Assert; +import org.junit.Test; + +public final class ReflectUtilTest { + + @Test + public void testFlattenNonNullProperties() throws Exception { + + final List<String> expectedResult = newArrayList("booleanProperty", TRUE.toString(), "intProperty", "1", "stringProperty", "foo"); + + final Bean bean = new Bean(1, true, "foo"); + + assertEquals(expectedResult, flattenProperties(bean, Bean.class)); + + } + + @Test + public void testFlattenNullProperties() throws Exception { + + final List<String> expectedResult = newArrayList("booleanProperty", TRUE.toString(), "intProperty", "1", "stringProperty", "null"); + + final Bean bean = new Bean(1, true, null); + + assertEquals(expectedResult, flattenProperties(bean, Bean.class)); + + } + + @Test + public void testFlattenPropertiesNullTarget() throws Exception { + assertEquals(emptyList(), flattenProperties(null, Bean.class)); + } + + public static final class Bean { + + private final int intProperty; + private final boolean booleanProperty; + private final String stringProperty; + + private Bean(final int intProperty, final boolean booleanProperty, final String stringProperty) { + + super(); + + this.intProperty = intProperty; + this.booleanProperty = booleanProperty; + this.stringProperty = stringProperty; + + } + + public int getIntProperty() { + return intProperty; + } + + public boolean isBooleanProperty() { + return booleanProperty; + } + + public String getStringProperty() { + return stringProperty; + } + + } + + static class Empty { + } + + static class Foo { + String fooField; + int fooIntField; + } + + static class Bar extends Foo { + String barField; + int barIntField; + } + + static class Baz extends Foo { + String bazField; + int bazIntField; + } + + @Test + public void getAllFieldsForClassWithFoo() throws NoSuchFieldException, SecurityException { + Set<Field> fooFields = ReflectUtil.getAllFieldsForClass(Foo.class, new Class<?>[] {}); + Assert.assertNotNull(fooFields); + Assert.assertTrue(fooFields.contains(Foo.class.getDeclaredField("fooField"))); + Assert.assertTrue(fooFields.contains(Foo.class.getDeclaredField("fooIntField"))); + } + + @Test + public void getAllFieldsForClassWithBar() throws NoSuchFieldException, SecurityException { + Set<Field> barFields = ReflectUtil.getAllFieldsForClass(Bar.class, new Class<?>[] {}); + Assert.assertNotNull(barFields); + Assert.assertTrue(barFields.contains(Foo.class.getDeclaredField("fooField"))); + Assert.assertTrue(barFields.contains(Foo.class.getDeclaredField("fooIntField"))); + Assert.assertTrue(barFields.contains(Bar.class.getDeclaredField("barField"))); + Assert.assertTrue(barFields.contains(Bar.class.getDeclaredField("barIntField"))); + } + + @Test + public void getAllFieldsForClassWithBarWithoutFoo() throws NoSuchFieldException, SecurityException { + Set<Field> barFields = ReflectUtil.getAllFieldsForClass(Bar.class, new Class<?>[] {Foo.class}); + Assert.assertNotNull(barFields); + Assert.assertTrue(barFields.contains(Bar.class.getDeclaredField("barField"))); + Assert.assertTrue(barFields.contains(Bar.class.getDeclaredField("barIntField"))); + } + + @Test + public void getAllFieldsForClassWithBazWithoutBar() throws NoSuchFieldException, SecurityException { + Set<Field> bazFields = ReflectUtil.getAllFieldsForClass(Baz.class, new Class<?>[] {Bar.class}); + Assert.assertNotNull(bazFields); + Assert.assertTrue(bazFields.contains(Foo.class.getDeclaredField("fooField"))); + Assert.assertTrue(bazFields.contains(Foo.class.getDeclaredField("fooIntField"))); + Assert.assertTrue(bazFields.contains(Baz.class.getDeclaredField("bazField"))); + Assert.assertTrue(bazFields.contains(Baz.class.getDeclaredField("bazIntField"))); + } + +} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/ScriptTest.java ---------------------------------------------------------------------- diff --git a/utils/src/test/java/com/cloud/utils/ScriptTest.java b/utils/src/test/java/com/cloud/utils/ScriptTest.java new file mode 100644 index 0000000..99059bf --- /dev/null +++ b/utils/src/test/java/com/cloud/utils/ScriptTest.java @@ -0,0 +1,135 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils; + +import java.io.BufferedReader; +import java.io.IOException; + +import org.apache.commons.lang.SystemUtils; +import org.apache.log4j.Logger; +import org.junit.Assert; +import org.junit.Assume; +import org.junit.Ignore; +import org.junit.Test; +import org.mockito.Matchers; +import org.mockito.Mockito; + +import com.cloud.utils.script.OutputInterpreter; +import com.cloud.utils.script.Script; + +public class ScriptTest { + @Test + public void testEcho() { + Assume.assumeTrue(SystemUtils.IS_OS_LINUX); + Script script = new Script("/bin/echo"); + script.add("bar"); + OutputInterpreter.AllLinesParser resultParser = new OutputInterpreter.AllLinesParser(); + String result = script.execute(resultParser); + // With allLinesParser, result is not comming from the return value + Assert.assertNull(result); + Assert.assertEquals("bar\n", resultParser.getLines()); + } + + @Test + public void testLogger() { + Assume.assumeTrue(SystemUtils.IS_OS_LINUX); + Logger mock = Mockito.mock(Logger.class); + Mockito.doNothing().when(mock).debug(Matchers.any()); + Script script = new Script("/bin/echo", mock); + script.execute(); + } + + @Test + public void testToString() { + Assume.assumeTrue(SystemUtils.IS_OS_LINUX); + Script script = new Script("/bin/echo"); + script.add("foo"); + Assert.assertEquals("/bin/echo foo ", script.toString()); + } + + @Test + public void testSet() { + Assume.assumeTrue(SystemUtils.IS_OS_LINUX); + Script script = new Script("/bin/echo"); + script.add("foo"); + script.add("bar", "baz"); + script.set("blah", "blah"); + Assert.assertEquals("/bin/echo foo bar baz blah blah ", + script.toString()); + } + + @Test + @Ignore + public void testExecute() { + Assume.assumeTrue(SystemUtils.IS_OS_LINUX); + Logger mock = Mockito.mock(Logger.class); + Mockito.doNothing().when(mock).debug(Matchers.any()); + for (int i = 0; i < 100000; i++) { + Script script = new Script("/bin/false", mock); + script.execute(); + } + } + + @Test + public void testRunSimpleBashScript() { + Assume.assumeTrue(SystemUtils.IS_OS_LINUX); + Assert.assertEquals("hello world!", + Script.runSimpleBashScript("echo 'hello world!'")); + } + + @Test + public void executeWithOutputInterpreter() { + Assume.assumeTrue(SystemUtils.IS_OS_LINUX); + Script script = new Script("/bin/bash"); + script.add("-c"); + script.add("echo 'hello world!'"); + String value = script.execute(new OutputInterpreter() { + + @Override + public String interpret(BufferedReader reader) throws IOException { + throw new IllegalArgumentException(); + } + }); + // it is a stack trace in this case as string + Assert.assertNotNull(value); + } + + @Test + public void runSimpleBashScriptNotExisting() { + Assume.assumeTrue(SystemUtils.IS_OS_LINUX); + String output = Script.runSimpleBashScript("/not/existing/scripts/" + + System.currentTimeMillis()); + Assert.assertNull(output); + } + + @Test + public void testRunSimpleBashScriptWithTimeout() { + Assume.assumeTrue(SystemUtils.IS_OS_LINUX); + Assert.assertEquals("hello world!", + Script.runSimpleBashScript("echo 'hello world!'", 1000)); + } + + @Test + public void testFindScript() { + Assume.assumeTrue(SystemUtils.IS_OS_LINUX); + String script = Script.findScript("/bin", "pwd"); + Assert.assertNotNull("/bin/pwd shoud be there on linux", script); + } +}