Return-Path: X-Original-To: apmail-incubator-cloudstack-commits-archive@minotaur.apache.org Delivered-To: apmail-incubator-cloudstack-commits-archive@minotaur.apache.org Received: from mail.apache.org (hermes.apache.org [140.211.11.3]) by minotaur.apache.org (Postfix) with SMTP id CB169E624 for ; Fri, 11 Jan 2013 01:19:47 +0000 (UTC) Received: (qmail 37096 invoked by uid 500); 11 Jan 2013 01:19:47 -0000 Delivered-To: apmail-incubator-cloudstack-commits-archive@incubator.apache.org Received: (qmail 37064 invoked by uid 500); 11 Jan 2013 01:19:47 -0000 Mailing-List: contact cloudstack-commits-help@incubator.apache.org; run by ezmlm Precedence: bulk List-Help: List-Unsubscribe: List-Post: List-Id: Reply-To: cloudstack-dev@incubator.apache.org Delivered-To: mailing list cloudstack-commits@incubator.apache.org Received: (qmail 37054 invoked by uid 99); 11 Jan 2013 01:19:47 -0000 Received: from tyr.zones.apache.org (HELO tyr.zones.apache.org) (140.211.11.114) by apache.org (qpsmtpd/0.29) with ESMTP; Fri, 11 Jan 2013 01:19:47 +0000 Received: by tyr.zones.apache.org (Postfix, from userid 65534) id 49BE817FB8; Fri, 11 Jan 2013 01:19:47 +0000 (UTC) Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit From: ahuang@apache.org To: cloudstack-commits@incubator.apache.org X-Mailer: ASF-Git Admin Mailer Subject: git commit: cleanup warnings in utils Message-Id: <20130111011947.49BE817FB8@tyr.zones.apache.org> Date: Fri, 11 Jan 2013 01:19:47 +0000 (UTC) Updated Branches: refs/heads/javelin 1294cdc70 -> 757e1a931 cleanup warnings in utils Project: http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/repo Commit: http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/commit/757e1a93 Tree: http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/tree/757e1a93 Diff: http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/diff/757e1a93 Branch: refs/heads/javelin Commit: 757e1a931b94ff74206a6ba6ce2fe89081f93ebc Parents: 1294cdc Author: Alex Huang Authored: Thu Jan 10 17:19:30 2013 -0800 Committer: Alex Huang Committed: Thu Jan 10 17:19:30 2013 -0800 ---------------------------------------------------------------------- .../acl/StaticRoleBasedAPIAccessChecker.java | 2 + pom.xml | 32 +++- server/src/com/cloud/api/ApiServer.java | 3 +- .../src/com/cloud/servlet/CloudStartupServlet.java | 3 - utils/src/com/cloud/utils/UriUtils.java | 52 +++--- .../utils/crypt/EncryptionSecretKeyChecker.java | 162 +++++++------- .../utils/crypt/EncryptionSecretKeySender.java | 68 +++---- .../utils/exception/RuntimeCloudException.java | 65 +++--- utils/src/com/cloud/utils/fsm/FiniteState2.java | 2 +- .../cloud/utils/log/CglibThrowableRenderer.java | 38 +---- utils/src/com/cloud/utils/net/MacAddress.java | 27 +-- utils/src/com/cloud/utils/net/NetUtils.java | 42 +--- utils/src/com/cloud/utils/net/NfsUtils.java | 19 +- utils/src/com/cloud/utils/nio/HandlerFactory.java | 1 - utils/src/com/cloud/utils/nio/Link.java | 161 +++++++-------- .../cloud/utils/security/CertificateHelper.java | 129 ++++++------ 16 files changed, 382 insertions(+), 424 deletions(-) ---------------------------------------------------------------------- http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/757e1a93/plugins/acl/static-role-based/src/org/apache/cloudstack/acl/StaticRoleBasedAPIAccessChecker.java ---------------------------------------------------------------------- diff --git a/plugins/acl/static-role-based/src/org/apache/cloudstack/acl/StaticRoleBasedAPIAccessChecker.java b/plugins/acl/static-role-based/src/org/apache/cloudstack/acl/StaticRoleBasedAPIAccessChecker.java index 32de070..7c69301 100644 --- a/plugins/acl/static-role-based/src/org/apache/cloudstack/acl/StaticRoleBasedAPIAccessChecker.java +++ b/plugins/acl/static-role-based/src/org/apache/cloudstack/acl/StaticRoleBasedAPIAccessChecker.java @@ -32,6 +32,7 @@ import javax.inject.Inject; import javax.naming.ConfigurationException; import org.apache.log4j.Logger; +import org.springframework.stereotype.Component; import com.cloud.exception.PermissionDeniedException; import com.cloud.user.AccountManager; @@ -40,6 +41,7 @@ import com.cloud.utils.component.PluggableService; // This is the default API access checker that grab's the user's account // based on the account type, access is granted +@Component @Local(value=APIAccessChecker.class) public class StaticRoleBasedAPIAccessChecker extends AdapterBase implements APIAccessChecker { http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/757e1a93/pom.xml ---------------------------------------------------------------------- diff --git a/pom.xml b/pom.xml index 1631099..4b5e3cf 100644 --- a/pom.xml +++ b/pom.xml @@ -43,7 +43,7 @@ - true + true 1.6 UTF-8 @@ -296,6 +296,36 @@ install + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + + org.apache.maven.plugins + + + maven-antrun-plugin + + [1.7,) + + run + + + + + + + + + + org.apache.tomcat.maven tomcat7-maven-plugin http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/757e1a93/server/src/com/cloud/api/ApiServer.java ---------------------------------------------------------------------- diff --git a/server/src/com/cloud/api/ApiServer.java b/server/src/com/cloud/api/ApiServer.java index c0eedc1..0c64e58 100755 --- a/server/src/com/cloud/api/ApiServer.java +++ b/server/src/com/cloud/api/ApiServer.java @@ -155,8 +155,7 @@ public class ApiServer implements HttpRequestHandler { @Inject List _pluggableServices; @Inject IdentityDao _identityDao; - @Inject - protected List _apiAccessCheckers; + @Inject List _apiAccessCheckers; private Account _systemAccount = null; private User _systemUser = null; http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/757e1a93/server/src/com/cloud/servlet/CloudStartupServlet.java ---------------------------------------------------------------------- diff --git a/server/src/com/cloud/servlet/CloudStartupServlet.java b/server/src/com/cloud/servlet/CloudStartupServlet.java index fefcb2f..eae211b 100755 --- a/server/src/com/cloud/servlet/CloudStartupServlet.java +++ b/server/src/com/cloud/servlet/CloudStartupServlet.java @@ -37,10 +37,7 @@ public class CloudStartupServlet extends HttpServlet implements ServletContextLi @Override public void init() throws ServletException { - // Save Configuration Values - //ComponentLocator loc = ComponentLocator.getLocator(ConfigurationServer.Name); ConfigurationServer c = (ConfigurationServer)ComponentContext.getComponent(ConfigurationServer.Name); - //ConfigurationServer c = new ConfigurationServerImpl(); try { c.persistDefaultValues(); ManagementServer ms = (ManagementServer)ComponentContext.getComponent(ManagementServer.Name); http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/757e1a93/utils/src/com/cloud/utils/UriUtils.java ---------------------------------------------------------------------- diff --git a/utils/src/com/cloud/utils/UriUtils.java b/utils/src/com/cloud/utils/UriUtils.java index 4a56988..a8b5ccb 100644 --- a/utils/src/com/cloud/utils/UriUtils.java +++ b/utils/src/com/cloud/utils/UriUtils.java @@ -32,7 +32,7 @@ public class UriUtils { throw new CloudRuntimeException("Unable to form nfs URI: " + host + " - " + path); } } - + public static String formIscsiUri(String host, String iqn, Integer lun) { try { String path = iqn; @@ -48,34 +48,34 @@ public class UriUtils { public static String formFileUri(String path) { File file = new File(path); - + return file.toURI().toString(); } - + // a simple URI component helper (Note: it does not deal with URI paramemeter area) public static String encodeURIComponent(String url) { - int schemeTail = url.indexOf("://"); - - int pathStart = 0; - if(schemeTail > 0) - pathStart = url.indexOf('/', schemeTail + 3); - else - pathStart = url.indexOf('/'); - - if(pathStart > 0) { - String[] tokens = url.substring(pathStart + 1).split("/"); - if(tokens != null) { - StringBuffer sb = new StringBuffer(); - sb.append(url.substring(0, pathStart)); - for(String token : tokens) { - sb.append("/").append(URLEncoder.encode(token)); - } - - return sb.toString(); - } - } - - // no need to do URL component encoding - return url; + int schemeTail = url.indexOf("://"); + + int pathStart = 0; + if(schemeTail > 0) + pathStart = url.indexOf('/', schemeTail + 3); + else + pathStart = url.indexOf('/'); + + if(pathStart > 0) { + String[] tokens = url.substring(pathStart + 1).split("/"); + if(tokens != null) { + StringBuffer sb = new StringBuffer(); + sb.append(url.substring(0, pathStart)); + for(String token : tokens) { + sb.append("/").append(URLEncoder.encode(token)); + } + + return sb.toString(); + } + } + + // no need to do URL component encoding + return url; } } http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/757e1a93/utils/src/com/cloud/utils/crypt/EncryptionSecretKeyChecker.java ---------------------------------------------------------------------- diff --git a/utils/src/com/cloud/utils/crypt/EncryptionSecretKeyChecker.java b/utils/src/com/cloud/utils/crypt/EncryptionSecretKeyChecker.java index 78d3200..a9c670d 100755 --- a/utils/src/com/cloud/utils/crypt/EncryptionSecretKeyChecker.java +++ b/utils/src/com/cloud/utils/crypt/EncryptionSecretKeyChecker.java @@ -40,108 +40,108 @@ import com.cloud.utils.exception.CloudRuntimeException; @Local(value = {SystemIntegrityChecker.class}) public class EncryptionSecretKeyChecker implements SystemIntegrityChecker { - - private static final Logger s_logger = Logger.getLogger(EncryptionSecretKeyChecker.class); - + + private static final Logger s_logger = Logger.getLogger(EncryptionSecretKeyChecker.class); + private static final String s_keyFile = "/etc/cloud/management/key"; private static final String s_envKey = "CLOUD_SECRET_KEY"; private static StandardPBEStringEncryptor s_encryptor = new StandardPBEStringEncryptor(); private static boolean s_useEncryption = false; - + @Override public void check() { - //Get encryption type from db.properties - final File dbPropsFile = PropertiesUtil.findConfigFile("db.properties"); + //Get encryption type from db.properties + final File dbPropsFile = PropertiesUtil.findConfigFile("db.properties"); final Properties dbProps = new Properties(); try { - dbProps.load(new FileInputStream(dbPropsFile)); - - final String encryptionType = dbProps.getProperty("db.cloud.encryption.type"); - - s_logger.debug("Encryption Type: "+ encryptionType); - - if(encryptionType == null || encryptionType.equals("none")){ - return; - } - - s_encryptor.setAlgorithm("PBEWithMD5AndDES"); - String secretKey = null; - - SimpleStringPBEConfig stringConfig = new SimpleStringPBEConfig(); - - if(encryptionType.equals("file")){ - try { - BufferedReader in = new BufferedReader(new FileReader(s_keyFile)); - secretKey = in.readLine(); - //Check for null or empty secret key - } catch (FileNotFoundException e) { - throw new CloudRuntimeException("File containing secret key not found: "+s_keyFile, e); - } catch (IOException e) { - throw new CloudRuntimeException("Error while reading secret key from: "+s_keyFile, e); - } - - if(secretKey == null || secretKey.isEmpty()){ - throw new CloudRuntimeException("Secret key is null or empty in file "+s_keyFile); - } - - } else if(encryptionType.equals("env")){ - secretKey = System.getenv(s_envKey); - if(secretKey == null || secretKey.isEmpty()){ - throw new CloudRuntimeException("Environment variable "+s_envKey+" is not set or empty"); - } - } else if(encryptionType.equals("web")){ - ServerSocket serverSocket = null; - int port = 8097; - try { + dbProps.load(new FileInputStream(dbPropsFile)); + + final String encryptionType = dbProps.getProperty("db.cloud.encryption.type"); + + s_logger.debug("Encryption Type: "+ encryptionType); + + if(encryptionType == null || encryptionType.equals("none")){ + return; + } + + s_encryptor.setAlgorithm("PBEWithMD5AndDES"); + String secretKey = null; + + SimpleStringPBEConfig stringConfig = new SimpleStringPBEConfig(); + + if(encryptionType.equals("file")){ + try { + BufferedReader in = new BufferedReader(new FileReader(s_keyFile)); + secretKey = in.readLine(); + //Check for null or empty secret key + } catch (FileNotFoundException e) { + throw new CloudRuntimeException("File containing secret key not found: "+s_keyFile, e); + } catch (IOException e) { + throw new CloudRuntimeException("Error while reading secret key from: "+s_keyFile, e); + } + + if(secretKey == null || secretKey.isEmpty()){ + throw new CloudRuntimeException("Secret key is null or empty in file "+s_keyFile); + } + + } else if(encryptionType.equals("env")){ + secretKey = System.getenv(s_envKey); + if(secretKey == null || secretKey.isEmpty()){ + throw new CloudRuntimeException("Environment variable "+s_envKey+" is not set or empty"); + } + } else if(encryptionType.equals("web")){ + ServerSocket serverSocket = null; + int port = 8097; + try { serverSocket = new ServerSocket(port); } catch (IOException ioex) { - throw new CloudRuntimeException("Error initializing secret key reciever", ioex); + throw new CloudRuntimeException("Error initializing secret key reciever", ioex); + } + s_logger.info("Waiting for admin to send secret key on port "+port); + Socket clientSocket = null; + try { + clientSocket = serverSocket.accept(); + } catch (IOException e) { + throw new CloudRuntimeException("Accept failed on "+port); } - s_logger.info("Waiting for admin to send secret key on port "+port); - Socket clientSocket = null; - try { - clientSocket = serverSocket.accept(); - } catch (IOException e) { - throw new CloudRuntimeException("Accept failed on "+port); - } - PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); - BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); - String inputLine, outputLine; - if ((inputLine = in.readLine()) != null) { - secretKey = inputLine; - } - out.close(); - in.close(); - clientSocket.close(); - serverSocket.close(); - } else { - throw new CloudRuntimeException("Invalid encryption type: "+encryptionType); - } - - stringConfig.setPassword(secretKey); - s_encryptor.setConfig(stringConfig); - s_useEncryption = true; + PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); + BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); + String inputLine; + if ((inputLine = in.readLine()) != null) { + secretKey = inputLine; + } + out.close(); + in.close(); + clientSocket.close(); + serverSocket.close(); + } else { + throw new CloudRuntimeException("Invalid encryption type: "+encryptionType); + } + + stringConfig.setPassword(secretKey); + s_encryptor.setConfig(stringConfig); + s_useEncryption = true; } catch (FileNotFoundException e) { - throw new CloudRuntimeException("File db.properties not found", e); + throw new CloudRuntimeException("File db.properties not found", e); } catch (IOException e) { - throw new CloudRuntimeException("Error while reading db.properties", e); + throw new CloudRuntimeException("Error while reading db.properties", e); } } - + public static StandardPBEStringEncryptor getEncryptor() { return s_encryptor; } - + public static boolean useEncryption(){ - return s_useEncryption; + return s_useEncryption; } - + //Initialize encryptor for migration during secret key change public static void initEncryptorForMigration(String secretKey){ - s_encryptor.setAlgorithm("PBEWithMD5AndDES"); - SimpleStringPBEConfig stringConfig = new SimpleStringPBEConfig(); - stringConfig.setPassword(secretKey); - s_encryptor.setConfig(stringConfig); - s_useEncryption = true; + s_encryptor.setAlgorithm("PBEWithMD5AndDES"); + SimpleStringPBEConfig stringConfig = new SimpleStringPBEConfig(); + stringConfig.setPassword(secretKey); + s_encryptor.setConfig(stringConfig); + s_useEncryption = true; } } http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/757e1a93/utils/src/com/cloud/utils/crypt/EncryptionSecretKeySender.java ---------------------------------------------------------------------- diff --git a/utils/src/com/cloud/utils/crypt/EncryptionSecretKeySender.java b/utils/src/com/cloud/utils/crypt/EncryptionSecretKeySender.java index 3904437..2dc865c 100755 --- a/utils/src/com/cloud/utils/crypt/EncryptionSecretKeySender.java +++ b/utils/src/com/cloud/utils/crypt/EncryptionSecretKeySender.java @@ -16,8 +16,6 @@ // under the License. package com.cloud.utils.crypt; -import java.io.BufferedReader; -import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.InetAddress; import java.net.Socket; @@ -26,39 +24,37 @@ import com.cloud.utils.NumbersUtil; public class EncryptionSecretKeySender { - public static void main(String args[]){ - try { + public static void main(String args[]){ + try { - // Create a socket to the host - String hostname = "localhost"; - int port = 8097; - - if(args.length == 2){ - hostname = args[0]; - port = NumbersUtil.parseInt(args[1], port); - } - - - InetAddress addr = InetAddress.getByName(hostname); - Socket socket = new Socket(addr, port); - PrintWriter out = new PrintWriter(socket.getOutputStream(), true); - BufferedReader in = new BufferedReader(new InputStreamReader( - socket.getInputStream())); - java.io.BufferedReader stdin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in)); - String validationWord = "cloudnine"; - String validationInput = ""; - while(!validationWord.equals(validationInput)){ - System.out.print("Enter Validation Word:"); - validationInput = stdin.readLine(); - System.out.println(); - } - System.out.print("Enter Secret Key:"); - String input = stdin.readLine(); - if (input != null) { - out.println(input); - } - } catch (Exception e) { - System.out.print("Exception while sending secret key "+e); - } - } + // Create a socket to the host + String hostname = "localhost"; + int port = 8097; + + if(args.length == 2){ + hostname = args[0]; + port = NumbersUtil.parseInt(args[1], port); + } + + + InetAddress addr = InetAddress.getByName(hostname); + Socket socket = new Socket(addr, port); + PrintWriter out = new PrintWriter(socket.getOutputStream(), true); + java.io.BufferedReader stdin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in)); + String validationWord = "cloudnine"; + String validationInput = ""; + while(!validationWord.equals(validationInput)){ + System.out.print("Enter Validation Word:"); + validationInput = stdin.readLine(); + System.out.println(); + } + System.out.print("Enter Secret Key:"); + String input = stdin.readLine(); + if (input != null) { + out.println(input); + } + } catch (Exception e) { + System.out.print("Exception while sending secret key "+e); + } + } } http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/757e1a93/utils/src/com/cloud/utils/exception/RuntimeCloudException.java ---------------------------------------------------------------------- diff --git a/utils/src/com/cloud/utils/exception/RuntimeCloudException.java b/utils/src/com/cloud/utils/exception/RuntimeCloudException.java index 5222980..a2de516 100644 --- a/utils/src/com/cloud/utils/exception/RuntimeCloudException.java +++ b/utils/src/com/cloud/utils/exception/RuntimeCloudException.java @@ -16,9 +16,10 @@ // under the License. package com.cloud.utils.exception; -import com.cloud.utils.AnnotationHelper; import java.util.ArrayList; +import com.cloud.utils.AnnotationHelper; + /** * by the API response serializer. Any exceptions that are thrown by * class, which extends Exception instead of RuntimeException like this @@ -27,20 +28,22 @@ import java.util.ArrayList; public class RuntimeCloudException extends RuntimeException { - // This holds a list of uuids and their names. Add uuid:fieldname pairs - protected ArrayList idList = new ArrayList(); + private static final long serialVersionUID = 1783478684819198850L; - protected int csErrorCode; + // This holds a list of uuids and their names. Add uuid:fieldname pairs + protected ArrayList idList = new ArrayList(); - public void addProxyObject(String uuid) { - idList.add(uuid); - return; - } + protected int csErrorCode; - public RuntimeCloudException(String message) { - super(message); - setCSErrorCode(CSExceptionErrorCode.getCSErrCode(this.getClass().getName())); - } + public void addProxyObject(String uuid) { + idList.add(uuid); + return; + } + + public RuntimeCloudException(String message) { + super(message); + setCSErrorCode(CSExceptionErrorCode.getCSErrCode(this.getClass().getName())); + } public RuntimeCloudException(String message, Throwable cause) { super(message, cause); @@ -48,28 +51,28 @@ public class RuntimeCloudException extends RuntimeException { } public void addProxyObject(Object voObj, Long id, String idFieldName) { - // Get the VO object's table name. - String tablename = AnnotationHelper.getTableName(voObj); - if (tablename != null) { - addProxyObject(tablename, id, idFieldName); - } - return; + // Get the VO object's table name. + String tablename = AnnotationHelper.getTableName(voObj); + if (tablename != null) { + addProxyObject(tablename, id, idFieldName); + } + return; } - public RuntimeCloudException() { - super(); - setCSErrorCode(CSExceptionErrorCode.getCSErrCode(this.getClass().getName())); - } + public RuntimeCloudException() { + super(); + setCSErrorCode(CSExceptionErrorCode.getCSErrCode(this.getClass().getName())); + } - public ArrayList getIdProxyList() { - return idList; - } + public ArrayList getIdProxyList() { + return idList; + } - public void setCSErrorCode(int cserrcode) { - this.csErrorCode = cserrcode; - } + public void setCSErrorCode(int cserrcode) { + this.csErrorCode = cserrcode; + } - public int getCSErrorCode() { - return this.csErrorCode; - } + public int getCSErrorCode() { + return this.csErrorCode; + } } http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/757e1a93/utils/src/com/cloud/utils/fsm/FiniteState2.java ---------------------------------------------------------------------- diff --git a/utils/src/com/cloud/utils/fsm/FiniteState2.java b/utils/src/com/cloud/utils/fsm/FiniteState2.java index 585521d..0147ba4 100755 --- a/utils/src/com/cloud/utils/fsm/FiniteState2.java +++ b/utils/src/com/cloud/utils/fsm/FiniteState2.java @@ -22,7 +22,7 @@ import java.util.Set; public interface FiniteState2 { - StateMachine2 getStateMachine(); + StateMachine2> getStateMachine(); T getNextState(ChangeEvent e) throws NoTransitionException; http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/757e1a93/utils/src/com/cloud/utils/log/CglibThrowableRenderer.java ---------------------------------------------------------------------- diff --git a/utils/src/com/cloud/utils/log/CglibThrowableRenderer.java b/utils/src/com/cloud/utils/log/CglibThrowableRenderer.java index 06cd0c3..83c1dce 100644 --- a/utils/src/com/cloud/utils/log/CglibThrowableRenderer.java +++ b/utils/src/com/cloud/utils/log/CglibThrowableRenderer.java @@ -17,7 +17,6 @@ package com.cloud.utils.log; import java.io.PrintWriter; -import java.lang.reflect.Method; import java.util.ArrayList; import org.apache.log4j.spi.ThrowableRenderer; @@ -36,25 +35,10 @@ import org.apache.log4j.spi.ThrowableRenderer; */ public class CglibThrowableRenderer implements ThrowableRenderer { /** - * Throwable.getStackTrace() method. - */ - private Method getStackTraceMethod; - /** - * StackTraceElement.getClassName() method. - */ - private Method getClassNameMethod; - - /** * Construct new instance. */ public CglibThrowableRenderer() { - try { - Class[] noArgs = null; - getStackTraceMethod = Throwable.class.getMethod("getStackTrace", noArgs); - Class ste = Class.forName("java.lang.StackTraceElement"); - getClassNameMethod = ste.getMethod("getClassName", noArgs); - } catch (Exception ex) { - } + super(); } @Override @@ -94,24 +78,4 @@ public class CglibThrowableRenderer implements ThrowableRenderer { return null; } } - - /** - * Find class given class name. - * - * @param className class name, may not be null. - * @return class, will not be null. - * @throws ClassNotFoundException thrown if class can not be found. - */ - private Class findClass(final String className) throws ClassNotFoundException { - try { - return Thread.currentThread().getContextClassLoader().loadClass(className); - } catch (ClassNotFoundException e) { - try { - return Class.forName(className); - } catch (ClassNotFoundException e1) { - return getClass().getClassLoader().loadClass(className); - } - } - } - } http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/757e1a93/utils/src/com/cloud/utils/net/MacAddress.java ---------------------------------------------------------------------- diff --git a/utils/src/com/cloud/utils/net/MacAddress.java b/utils/src/com/cloud/utils/net/MacAddress.java index f81127c..15350c8 100755 --- a/utils/src/com/cloud/utils/net/MacAddress.java +++ b/utils/src/com/cloud/utils/net/MacAddress.java @@ -60,16 +60,16 @@ public class MacAddress { StringBuilder buff = new StringBuilder(); Formatter formatter = new Formatter(buff); formatter.format("%02x%s%02x%s%02x%s%02x%s%02x%s%02x", - _addr >> 40 & 0xff, separator, - _addr >> 32 & 0xff, separator, - _addr >> 24 & 0xff, separator, - _addr >> 16 & 0xff, separator, - _addr >> 8 & 0xff, separator, - _addr & 0xff); + _addr >> 40 & 0xff, separator, + _addr >> 32 & 0xff, separator, + _addr >> 24 & 0xff, separator, + _addr >> 16 & 0xff, separator, + _addr >> 8 & 0xff, separator, + _addr & 0xff); return buff.toString(); - + /* - + String str = Long.toHexString(_addr); for (int i = str.length() - 1; i >= 0; i--) { @@ -79,11 +79,11 @@ public class MacAddress { } } return buff.reverse().toString(); - */ + */ } @Override - public String toString() { + public String toString() { return toString(":"); } @@ -102,7 +102,7 @@ public class MacAddress { } else if (osname.startsWith("Solaris") || osname.startsWith("SunOS")) { // Solaris code must appear before the generic code String hostName = MacAddress.getFirstLineOfCommand(new String[] { "uname", - "-n"}); + "-n"}); if (hostName != null) { p = Runtime.getRuntime().exec(new String[] { "/usr/sbin/arp", hostName}, null); } @@ -163,7 +163,7 @@ public class MacAddress { clockSeqAndNode |= (long) (Math.random() * 0x7FFFFFFF); } } - + s_address = new MacAddress(clockSeqAndNode); } @@ -262,9 +262,6 @@ public class MacAddress { System.out.println("addr in char is " + addr.toString(":")); } -private static final char[] DIGITS = { '0', '1', '2', '3', '4', '5', '6', - '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; - /** * Parses a long from a hex encoded number. This method will skip * all characters that are not 0-9 and a-f (the String is lower cased first). http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/757e1a93/utils/src/com/cloud/utils/net/NetUtils.java ---------------------------------------------------------------------- diff --git a/utils/src/com/cloud/utils/net/NetUtils.java b/utils/src/com/cloud/utils/net/NetUtils.java index c456cdc..005fe23 100755 --- a/utils/src/com/cloud/utils/net/NetUtils.java +++ b/utils/src/com/cloud/utils/net/NetUtils.java @@ -17,15 +17,12 @@ package com.cloud.utils.net; import java.io.BufferedReader; -import java.io.File; import java.io.InputStreamReader; import java.lang.reflect.Array; import java.net.InetAddress; import java.net.InterfaceAddress; import java.net.NetworkInterface; import java.net.SocketException; -import java.net.URISyntaxException; -import java.net.URL; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Formatter; @@ -39,7 +36,6 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.log4j.Logger; -import org.apache.log4j.xml.DOMConfigurator; import com.cloud.utils.IteratorUtil; import com.cloud.utils.Pair; @@ -681,7 +677,7 @@ public class NetUtils { if (avoid.size() >= range) { return -1; } - + //Reduce the range by the size of the avoid set //e.g., cidr = 192.168.10.0, size = /24, avoid = 192.168.10.1, 192.168.10.20, 192.168.10.254 // range = 2^8 - 1 - 3 = 252 @@ -690,9 +686,9 @@ public class NetUtils { long ip = startIp + next; for (Long avoidable : avoid) { if (ip >= avoidable) { - ip++; + ip++; } else { - break; + break; } } @@ -796,7 +792,7 @@ public class NetUtils { long shift = 32 - cidrBLong[1]; return ((cidrALong[0] >> shift) == (cidrBLong[0] >> shift)); } - + public static Long[] cidrToLong(String cidr) { if (cidr == null || cidr.isEmpty()) { return null; @@ -960,26 +956,6 @@ public class NetUtils { return Integer.toString(portRange[0]) + ":" + Integer.toString(portRange[1]); } - // test only - private static void configLog4j() { - URL configUrl = System.class.getResource("/conf/log4j-cloud.xml"); - if (configUrl != null) { - System.out.println("Configure log4j using log4j-cloud.xml"); - - try { - File file = new File(configUrl.toURI()); - - System.out.println("Log4j configuration from : " + file.getAbsolutePath()); - DOMConfigurator.configureAndWatch(file.getAbsolutePath(), 10000); - } catch (URISyntaxException e) { - System.out.println("Unable to convert log4j configuration Url to URI"); - } - // DOMConfigurator.configure(configUrl); - } else { - System.out.println("Configure log4j with default properties"); - } - } - public static boolean verifyDomainNameLabel(String hostName, boolean isHostName) { // must be between 1 and 63 characters long and may contain only the ASCII letters 'a' through 'z' (in a @@ -1068,7 +1044,7 @@ public class NetUtils { return true; } - + public static boolean isNetworksOverlap(String cidrA, String cidrB) { Long[] cidrALong = cidrToLong(cidrA); Long[] cidrBLong = cidrToLong(cidrB); @@ -1122,7 +1098,7 @@ public class NetUtils { } return true; } - + public static boolean validateIcmpType(long icmpType) { //Source - http://www.erg.abdn.ac.uk/~gorry/course/inet-pages/icmp-code.html if(!(icmpType >=0 && icmpType <=255)) { @@ -1131,15 +1107,15 @@ public class NetUtils { } return true; } - + public static boolean validateIcmpCode(long icmpCode) { - + //Source - http://www.erg.abdn.ac.uk/~gorry/course/inet-pages/icmp-code.html if(!(icmpCode >=0 && icmpCode <=15)) { s_logger.warn("Icmp code should be within 0-15 range"); return false; } - + return true; } } http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/757e1a93/utils/src/com/cloud/utils/net/NfsUtils.java ---------------------------------------------------------------------- diff --git a/utils/src/com/cloud/utils/net/NfsUtils.java b/utils/src/com/cloud/utils/net/NfsUtils.java index 7318383..19ff055 100644 --- a/utils/src/com/cloud/utils/net/NfsUtils.java +++ b/utils/src/com/cloud/utils/net/NfsUtils.java @@ -21,18 +21,17 @@ import java.net.URI; import java.net.URISyntaxException; public class NfsUtils { - + public static String url2Mount(String urlStr) throws URISyntaxException { URI url; url = new URI(urlStr); - int port = url.getPort(); return url.getHost() + ":" + url.getPath(); } - + public static String uri2Mount(URI uri) { return uri.getHost() + ":" + uri.getPath(); } - + public static String url2PathSafeString(String urlStr) { String safe = urlStr.replace(File.separatorChar, '-'); safe = safe.replace("?", ""); @@ -41,13 +40,13 @@ public class NfsUtils { safe = safe.replace("/", ""); return safe; } - + public static String getHostPart(String nfsPath) { - String toks[] = nfsPath.split(":"); - if (toks != null && toks.length == 2) { - return toks[0]; - } - return null; + String toks[] = nfsPath.split(":"); + if (toks != null && toks.length == 2) { + return toks[0]; + } + return null; } } http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/757e1a93/utils/src/com/cloud/utils/nio/HandlerFactory.java ---------------------------------------------------------------------- diff --git a/utils/src/com/cloud/utils/nio/HandlerFactory.java b/utils/src/com/cloud/utils/nio/HandlerFactory.java index 0dcc83f..9cf218d 100755 --- a/utils/src/com/cloud/utils/nio/HandlerFactory.java +++ b/utils/src/com/cloud/utils/nio/HandlerFactory.java @@ -16,7 +16,6 @@ // under the License. package com.cloud.utils.nio; -import java.util.List; /** * WorkerFactory creates and selects workers. http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/757e1a93/utils/src/com/cloud/utils/nio/Link.java ---------------------------------------------------------------------- diff --git a/utils/src/com/cloud/utils/nio/Link.java b/utils/src/com/cloud/utils/nio/Link.java index 3e3da6c..4b041f5 100755 --- a/utils/src/com/cloud/utils/nio/Link.java +++ b/utils/src/com/cloud/utils/nio/Link.java @@ -16,18 +16,15 @@ // under the License. package com.cloud.utils.nio; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.InetSocketAddress; import java.nio.ByteBuffer; -import java.nio.channels.Channels; import java.nio.channels.ClosedChannelException; import java.nio.channels.SelectionKey; import java.nio.channels.SocketChannel; -import java.nio.channels.WritableByteChannel; import java.security.KeyStore; import java.util.concurrent.ConcurrentLinkedQueue; @@ -35,10 +32,10 @@ import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLEngineResult; +import javax.net.ssl.SSLEngineResult.HandshakeStatus; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; -import javax.net.ssl.SSLEngineResult.HandshakeStatus; import org.apache.log4j.Logger; @@ -48,7 +45,7 @@ import com.cloud.utils.PropertiesUtil; */ public class Link { private static final Logger s_logger = Logger.getLogger(Link.class); - + private final InetSocketAddress _addr; private final NioConnection _connection; private SelectionKey _key; @@ -58,7 +55,7 @@ public class Link { private Object _attach; private boolean _readHeader; private boolean _gotFollowingPacket; - + private SSLEngine _sslEngine; public Link(InetSocketAddress addr, NioConnection connection) { @@ -71,23 +68,23 @@ public class Link { _readHeader = true; _gotFollowingPacket = false; } - + public Link (Link link) { this(link._addr, link._connection); } - + public Object attachment() { return _attach; } - + public void attach(Object attach) { _attach = attach; } - + public void setKey(SelectionKey key) { _key = key; } - + public void setSSLEngine(SSLEngine sslEngine) { _sslEngine = sslEngine; } @@ -105,19 +102,19 @@ public class Link { synchronized(buff) { buff.clear(); buff.limit(4); - + while (buff.hasRemaining()) { if (ch.read(buff) == -1) { throw new IOException("Connection closed with -1 on reading size."); } } - + buff.flip(); - + int length = buff.getInt(); ByteArrayOutputStream output = new ByteArrayOutputStream(length); WritableByteChannel outCh = Channels.newChannel(output); - + int count = 0; while (count < length) { buff.clear(); @@ -129,19 +126,19 @@ public class Link { buff.flip(); outCh.write(buff); } - + return output.toByteArray(); } } - */ - + */ + private static void doWrite(SocketChannel ch, ByteBuffer[] buffers, SSLEngine sslEngine) throws IOException { SSLSession sslSession = sslEngine.getSession(); ByteBuffer pkgBuf = ByteBuffer.allocate(sslSession.getPacketBufferSize() + 40); SSLEngineResult engResult; ByteBuffer headBuf = ByteBuffer.allocate(4); - + int totalLen = 0; for (ByteBuffer buffer : buffers) { totalLen += buffer.limit(); @@ -157,7 +154,7 @@ public class Link { engResult.getStatus() != SSLEngineResult.Status.OK) { throw new IOException("SSL: SSLEngine return bad result! " + engResult); } - + processedLen = 0; for (ByteBuffer buffer : buffers) { processedLen += buffer.position(); @@ -189,7 +186,7 @@ public class Link { } } } - + /** * write method to write to a socket. This method writes to completion so * it doesn't follow the nio standard. We use this to make sure we write @@ -204,21 +201,21 @@ public class Link { doWrite(ch, buffers, sslEngine); } } - + /* SSL has limitation of 16k, we may need to split packets. 18000 is 16k + some extra SSL informations */ protected static final int MAX_SIZE_PER_PACKET = 18000; protected static final int HEADER_FLAG_FOLLOWING = 0x10000; - + public byte[] read(SocketChannel ch) throws IOException { if (_readHeader) { // Start of a packet if (_readBuffer.position() == 0) { _readBuffer.limit(4); } - + if (ch.read(_readBuffer) == -1) { throw new IOException("Connection closed with -1 on reading size."); } - + if (_readBuffer.hasRemaining()) { s_logger.trace("Need to read the rest of the packet length"); return null; @@ -229,24 +226,24 @@ public class Link { if (s_logger.isTraceEnabled()) { s_logger.trace("Packet length is " + readSize); } - + if (readSize > MAX_SIZE_PER_PACKET) { - throw new IOException("Wrong packet size: " + readSize); + throw new IOException("Wrong packet size: " + readSize); } - + if (!_gotFollowingPacket) { _plaintextBuffer = ByteBuffer.allocate(2000); } - + if ((header & HEADER_FLAG_FOLLOWING) != 0) { _gotFollowingPacket = true; } else { _gotFollowingPacket = false; } - + _readBuffer.clear(); _readHeader = false; - + if (_readBuffer.capacity() < readSize) { if (s_logger.isTraceEnabled()) { s_logger.trace("Resizing the byte buffer from " + _readBuffer.capacity()); @@ -255,18 +252,18 @@ public class Link { } _readBuffer.limit(readSize); } - + if (ch.read(_readBuffer) == -1) { throw new IOException("Connection closed with -1 on read."); } - + if (_readBuffer.hasRemaining()) { // We're not done yet. if (s_logger.isTraceEnabled()) { s_logger.trace("Still has " + _readBuffer.remaining()); } return null; } - + _readBuffer.flip(); ByteBuffer appBuf; @@ -287,7 +284,7 @@ public class Link { if (remaining == _readBuffer.remaining()) { throw new IOException("SSL: Unable to unwrap received data! still remaining " + remaining + "bytes!"); } - + appBuf.flip(); if (_plaintextBuffer.remaining() < appBuf.limit()) { // We need to expand _plaintextBuffer for more data @@ -301,10 +298,10 @@ public class Link { s_logger.trace("Done with packet: " + appBuf.limit()); } } - + _readBuffer.clear(); _readHeader = true; - + if (!_gotFollowingPacket) { _plaintextBuffer.flip(); byte[] result = new byte[_plaintextBuffer.limit()]; @@ -317,15 +314,15 @@ public class Link { return null; } } - + public void send(byte[] data) throws ClosedChannelException { send(data, false); } - + public void send(byte[] data, boolean close) throws ClosedChannelException { send(new ByteBuffer[] { ByteBuffer.wrap(data) }, close); } - + public void send(ByteBuffer[] data, boolean close) throws ClosedChannelException { ByteBuffer[] item = new ByteBuffer[data.length + 1]; int remaining = 0; @@ -333,15 +330,15 @@ public class Link { remaining += data[i].remaining(); item[i + 1] = data[i]; } - + item[0] = ByteBuffer.allocate(4); item[0].putInt(remaining); item[0].flip(); - + if (s_logger.isTraceEnabled()) { s_logger.trace("Sending packet of length " + remaining); } - + _writeQueue.add(item); if (close) { _writeQueue.add(new ByteBuffer[0]); @@ -353,17 +350,17 @@ public class Link { _connection.change(SelectionKey.OP_WRITE, _key, null); } } - + public void send(ByteBuffer[] data) throws ClosedChannelException { send(data, false); } - + public synchronized void close() { if (_key != null) { _connection.close(_key); } } - + public boolean write(SocketChannel ch) throws IOException { ByteBuffer[] data = null; while ((data = _writeQueue.poll()) != null) { @@ -381,26 +378,26 @@ public class Link { } return false; } - + public InetSocketAddress getSocketAddress() { return _addr; } - + public String getIpAddress() { return _addr.getAddress().toString(); } - + public synchronized void terminated() { _key = null; } - + public synchronized void schedule(Task task) throws ClosedChannelException { if (_key == null) { throw new ClosedChannelException(); } _connection.scheduleTask(task); } - + public static SSLContext initSSLContext(boolean isClient) throws Exception { InputStream stream; SSLContext sslContext = null; @@ -408,42 +405,42 @@ public class Link { TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); KeyStore ks = KeyStore.getInstance("JKS"); TrustManager[] tms; - + if (!isClient) { - char[] passphrase = "vmops.com".toCharArray(); - File confFile= PropertiesUtil.findConfigFile("db.properties"); - /* This line may throw a NPE, but that's due to fail to find db.properities, meant some bugs in the other places */ - String confPath = confFile.getParent(); - String keystorePath = confPath + "/cloud.keystore"; - if (new File(keystorePath).exists()) { - stream = new FileInputStream(keystorePath); - } else { - s_logger.warn("SSL: Fail to find the generated keystore. Loading fail-safe one to continue."); - stream = NioConnection.class.getResourceAsStream("/cloud.keystore"); - } - ks.load(stream, passphrase); - stream.close(); - kmf.init(ks, passphrase); - tmf.init(ks); - tms = tmf.getTrustManagers(); + char[] passphrase = "vmops.com".toCharArray(); + File confFile= PropertiesUtil.findConfigFile("db.properties"); + /* This line may throw a NPE, but that's due to fail to find db.properities, meant some bugs in the other places */ + String confPath = confFile.getParent(); + String keystorePath = confPath + "/cloud.keystore"; + if (new File(keystorePath).exists()) { + stream = new FileInputStream(keystorePath); + } else { + s_logger.warn("SSL: Fail to find the generated keystore. Loading fail-safe one to continue."); + stream = NioConnection.class.getResourceAsStream("/cloud.keystore"); + } + ks.load(stream, passphrase); + stream.close(); + kmf.init(ks, passphrase); + tmf.init(ks); + tms = tmf.getTrustManagers(); } else { - ks.load(null, null); - kmf.init(ks, null); - tms = new TrustManager[1]; - tms[0] = new TrustAllManager(); + ks.load(null, null); + kmf.init(ks, null); + tms = new TrustManager[1]; + tms[0] = new TrustAllManager(); } - + sslContext = SSLContext.getInstance("TLS"); sslContext.init(kmf.getKeyManagers(), tms, null); if (s_logger.isTraceEnabled()) { - s_logger.trace("SSL: SSLcontext has been initialized"); + s_logger.trace("SSL: SSLcontext has been initialized"); } return sslContext; } public static void doHandshake(SocketChannel ch, SSLEngine sslEngine, - boolean isClient) throws IOException { + boolean isClient) throws IOException { if (s_logger.isTraceEnabled()) { s_logger.trace("SSL: begin Handshake, isClient: " + isClient); } @@ -452,13 +449,13 @@ public class Link { SSLSession sslSession = sslEngine.getSession(); HandshakeStatus hsStatus; ByteBuffer in_pkgBuf = - ByteBuffer.allocate(sslSession.getPacketBufferSize() + 40); + ByteBuffer.allocate(sslSession.getPacketBufferSize() + 40); ByteBuffer in_appBuf = - ByteBuffer.allocate(sslSession.getApplicationBufferSize() + 40); + ByteBuffer.allocate(sslSession.getApplicationBufferSize() + 40); ByteBuffer out_pkgBuf = - ByteBuffer.allocate(sslSession.getPacketBufferSize() + 40); + ByteBuffer.allocate(sslSession.getPacketBufferSize() + 40); ByteBuffer out_appBuf = - ByteBuffer.allocate(sslSession.getApplicationBufferSize() + 40); + ByteBuffer.allocate(sslSession.getApplicationBufferSize() + 40); int count; if (isClient) { @@ -498,7 +495,7 @@ public class Link { } engResult = sslEngine.unwrap(in_pkgBuf, in_appBuf); ByteBuffer tmp_pkgBuf = - ByteBuffer.allocate(sslSession.getPacketBufferSize() + 40); + ByteBuffer.allocate(sslSession.getPacketBufferSize() + 40); int loop_count = 0; while (engResult.getStatus() == SSLEngineResult.Status.BUFFER_UNDERFLOW) { // The client is too slow? Cut it and let it reconnect @@ -515,13 +512,13 @@ public class Link { throw new IOException("Connection closed with -1 on reading size."); } tmp_pkgBuf.flip(); - + in_pkgBuf.mark(); in_pkgBuf.position(in_pkgBuf.limit()); in_pkgBuf.limit(in_pkgBuf.limit() + tmp_pkgBuf.limit()); in_pkgBuf.put(tmp_pkgBuf); in_pkgBuf.reset(); - + in_appBuf.clear(); engResult = sslEngine.unwrap(in_pkgBuf, in_appBuf); loop_count ++; http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/757e1a93/utils/src/com/cloud/utils/security/CertificateHelper.java ---------------------------------------------------------------------- diff --git a/utils/src/com/cloud/utils/security/CertificateHelper.java b/utils/src/com/cloud/utils/security/CertificateHelper.java index 327734a..8344d72 100644 --- a/utils/src/com/cloud/utils/security/CertificateHelper.java +++ b/utils/src/com/cloud/utils/security/CertificateHelper.java @@ -19,7 +19,6 @@ package com.cloud.utils.security; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; -import java.io.FileOutputStream; import java.io.IOException; import java.security.Key; import java.security.KeyFactory; @@ -38,72 +37,72 @@ import org.apache.commons.codec.binary.Base64; import com.cloud.utils.Ternary; public class CertificateHelper { - public static byte[] buildAndSaveKeystore(String alias, String cert, String privateKey, String storePassword) throws KeyStoreException, CertificateException, - NoSuchAlgorithmException, InvalidKeySpecException, IOException { - KeyStore ks = buildKeystore(alias, cert, privateKey, storePassword); - - ByteArrayOutputStream os = new ByteArrayOutputStream(); - ks.store(os, storePassword != null ? storePassword.toCharArray() : null); - os.close(); - return os.toByteArray(); - } - - public static byte[] buildAndSaveKeystore(List> certs, String storePassword) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, InvalidKeySpecException { - KeyStore ks = KeyStore.getInstance("JKS"); - ks.load(null, storePassword != null ? storePassword.toCharArray() : null); + public static byte[] buildAndSaveKeystore(String alias, String cert, String privateKey, String storePassword) throws KeyStoreException, CertificateException, + NoSuchAlgorithmException, InvalidKeySpecException, IOException { + KeyStore ks = buildKeystore(alias, cert, privateKey, storePassword); - //name,cert,key - for (Ternary cert : certs) { - if (cert.third() == null) { - Certificate c = buildCertificate(cert.second()); - ks.setCertificateEntry(cert.first(), c); - } else { - Certificate[] c = new Certificate[certs.size()]; - int i = certs.size(); - for (Ternary ct : certs) { - c[i - 1] = buildCertificate(ct.second()); - i--; - } - ks.setKeyEntry(cert.first(), buildPrivateKey(cert.third()), storePassword != null ? storePassword.toCharArray() : null, c ); - } - } - - ByteArrayOutputStream os = new ByteArrayOutputStream(); - ks.store(os, storePassword != null ? storePassword.toCharArray() : null); - os.close(); - return os.toByteArray(); - } - - public static KeyStore loadKeystore(byte[] ksData, String storePassword) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException { - assert(ksData != null); - KeyStore ks = KeyStore.getInstance("JKS"); - ks.load(new ByteArrayInputStream(ksData), storePassword != null ? storePassword.toCharArray() : null); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + ks.store(os, storePassword != null ? storePassword.toCharArray() : null); + os.close(); + return os.toByteArray(); + } - return ks; - } - - public static KeyStore buildKeystore(String alias, String cert, String privateKey, String storePassword) throws KeyStoreException, CertificateException, - NoSuchAlgorithmException, InvalidKeySpecException, IOException { - - KeyStore ks = KeyStore.getInstance("JKS"); - ks.load(null, storePassword != null ? storePassword.toCharArray() : null); - Certificate[] certs = new Certificate[1]; - certs[0] = buildCertificate(cert); - ks.setKeyEntry(alias, buildPrivateKey(privateKey), storePassword != null ? storePassword.toCharArray() : null, certs ); - return ks; - } + public static byte[] buildAndSaveKeystore(List> certs, String storePassword) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, InvalidKeySpecException { + KeyStore ks = KeyStore.getInstance("JKS"); + ks.load(null, storePassword != null ? storePassword.toCharArray() : null); - public static Certificate buildCertificate(String content) throws CertificateException { - assert(content != null); - - BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(content.getBytes())); - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - return cf.generateCertificate(bis); - } + //name,cert,key + for (Ternary cert : certs) { + if (cert.third() == null) { + Certificate c = buildCertificate(cert.second()); + ks.setCertificateEntry(cert.first(), c); + } else { + Certificate[] c = new Certificate[certs.size()]; + int i = certs.size(); + for (Ternary ct : certs) { + c[i - 1] = buildCertificate(ct.second()); + i--; + } + ks.setKeyEntry(cert.first(), buildPrivateKey(cert.third()), storePassword != null ? storePassword.toCharArray() : null, c ); + } + } - public static Key buildPrivateKey(String base64EncodedKeyContent) throws NoSuchAlgorithmException, InvalidKeySpecException, IOException { - KeyFactory kf = KeyFactory.getInstance("RSA"); - PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec (Base64.decodeBase64(base64EncodedKeyContent)); - return kf.generatePrivate (keysp); - } + ByteArrayOutputStream os = new ByteArrayOutputStream(); + ks.store(os, storePassword != null ? storePassword.toCharArray() : null); + os.close(); + return os.toByteArray(); + } + + public static KeyStore loadKeystore(byte[] ksData, String storePassword) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException { + assert(ksData != null); + KeyStore ks = KeyStore.getInstance("JKS"); + ks.load(new ByteArrayInputStream(ksData), storePassword != null ? storePassword.toCharArray() : null); + + return ks; + } + + public static KeyStore buildKeystore(String alias, String cert, String privateKey, String storePassword) throws KeyStoreException, CertificateException, + NoSuchAlgorithmException, InvalidKeySpecException, IOException { + + KeyStore ks = KeyStore.getInstance("JKS"); + ks.load(null, storePassword != null ? storePassword.toCharArray() : null); + Certificate[] certs = new Certificate[1]; + certs[0] = buildCertificate(cert); + ks.setKeyEntry(alias, buildPrivateKey(privateKey), storePassword != null ? storePassword.toCharArray() : null, certs ); + return ks; + } + + public static Certificate buildCertificate(String content) throws CertificateException { + assert(content != null); + + BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(content.getBytes())); + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + return cf.generateCertificate(bis); + } + + public static Key buildPrivateKey(String base64EncodedKeyContent) throws NoSuchAlgorithmException, InvalidKeySpecException, IOException { + KeyFactory kf = KeyFactory.getInstance("RSA"); + PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec (Base64.decodeBase64(base64EncodedKeyContent)); + return kf.generatePrivate (keysp); + } }