.classpath | 6 modules/plugins/jboss-as-7/pom.xml | 21 modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ASUploadConnection.java | 282 ++++++---- modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseComponent.java | 90 +-- modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/DeploymentComponent.java | 111 ++- modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ServerGroupComponent.java | 87 +-- modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/nonpc/AbstractIntegrationTest.java | 27 7 files changed, 383 insertions(+), 241 deletions(-)
New commits: commit 072ce8deb4aa14cb5968739752002e1a765f4397 Author: Thomas SEGISMONT tsegismo@redhat.com Date: Fri Dec 21 14:23:35 2012 +0100
as7plugin switch to httpclient: first compiling version Creating new child resource of type deployment now works
diff --git a/.classpath b/.classpath index ab18820..f493247 100644 --- a/.classpath +++ b/.classpath @@ -222,7 +222,7 @@ <classpathentry exported="true" kind="var" path="M2_REPO/org/jetbrains/annotations/7.0.2/annotations-7.0.2.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/org/apache/ant/ant-launcher/1.8.0/ant-launcher-1.8.0.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/cglib/cglib-nodep/2.1_3/cglib-nodep-2.1_3.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/commons-logging/commons-logging/1.1.1/commons-logging-1.1.1.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/commons-logging/commons-logging/1.1.1/commons-logging-1.1.1.jar" sourcepath="/M2_REPO/commons-logging/commons-logging/1.1.1/commons-logging-1.1.1-sources.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/commons-lang/commons-lang/2.4/commons-lang-2.4.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/javax/faces/jsf-api/1.2_14/jsf-api-1.2_14.jar" sourcepath="/M2_REPO/javax/faces/jsf-api/1.2_14/jsf-api-1.2_14-sources.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/javax/faces/jsf-impl/1.2_14/jsf-impl-1.2_14.jar" sourcepath="/M2_REPO/javax/faces/jsf-impl/1.2_14/jsf-impl-1.2_14-sources.jar"/> @@ -274,8 +274,8 @@ <classpathentry exported="true" kind="var" path="M2_REPO/org/unitils/unitils-dbunit/3.1/unitils-dbunit-3.1.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/org/unitils/unitils-orm/3.1/unitils-orm-3.1.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/org/unitils/unitils-testng/3.1/unitils-testng-3.1.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/org/codehaus/jackson/jackson-core-asl/1.8.5/jackson-core-asl-1.8.5.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/org/codehaus/jackson/jackson-mapper-asl/1.8.5/jackson-mapper-asl-1.8.5.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/codehaus/jackson/jackson-core-asl/1.8.5/jackson-core-asl-1.8.5.jar" sourcepath="/M2_REPO/org/codehaus/jackson/jackson-core-asl/1.8.5/jackson-core-asl-1.8.5-sources.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/codehaus/jackson/jackson-mapper-asl/1.8.5/jackson-mapper-asl-1.8.5.jar" sourcepath="/M2_REPO/org/codehaus/jackson/jackson-mapper-asl/1.8.5/jackson-mapper-asl-1.8.5-sources.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/org/mongodb/mongo-java-driver/2.6.5/mongo-java-driver-2.6.5.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/com/googlecode/java-diff-utils/diffutils/1.2.1/diffutils-1.2.1.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/com/google/code/morphia/morphia/0.99/morphia-0.99.jar"/> diff --git a/modules/plugins/jboss-as-7/pom.xml b/modules/plugins/jboss-as-7/pom.xml index 8a2b9e0..6c9a833 100644 --- a/modules/plugins/jboss-as-7/pom.xml +++ b/modules/plugins/jboss-as-7/pom.xml @@ -66,12 +66,26 @@ <version>${jboss.sasl.version}</version> </dependency>
+ <!-- For communication with AS7 http management interface --> + <dependency> <groupId>commons-httpclient</groupId> <artifactId>commons-httpclient</artifactId> <version>${commons-httpclient.version}</version> + <exclusions> + <exclusion> + <groupId>commons-codec</groupId> + <artifactId>commons-codec</artifactId> + </exclusion> + </exclusions> </dependency> - + + <dependency> + <groupId>commons-codec</groupId> + <artifactId>commons-codec</artifactId> + <version>${commons-codec.version}</version> + </dependency> + <!-- === Test Deps === -->
<dependency> @@ -130,6 +144,11 @@ <groupId>commons-httpclient</groupId> <artifactId>commons-httpclient</artifactId> </artifactItem> + + <artifactItem> + <groupId>commons-codec</groupId> + <artifactId>commons-codec</artifactId> + </artifactItem>
</artifactItems> <outputDirectory>${project.build.outputDirectory}/lib</outputDirectory> diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ASUploadConnection.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ASUploadConnection.java index 3a3b651..f97eb83 100644 --- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ASUploadConnection.java +++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ASUploadConnection.java @@ -1,6 +1,6 @@ /* * RHQ Management Platform - * Copyright (C) 2005-2011 Red Hat, Inc. + * Copyright (C) 2005-2012 Red Hat, Inc. * All rights reserved. * * This program is free software; you can redistribute it and/or modify @@ -19,46 +19,76 @@ package org.rhq.modules.plugins.jbossas7;
import java.io.BufferedOutputStream; -import java.io.BufferedReader; import java.io.Closeable; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; -import java.io.InputStreamReader; +import java.io.InputStream; import java.io.OutputStream;
import org.apache.commons.httpclient.Credentials; import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.httpclient.SimpleHttpConnectionManager; import org.apache.commons.httpclient.UsernamePasswordCredentials; import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; +import org.apache.commons.httpclient.methods.multipart.FilePart; +import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity; +import org.apache.commons.httpclient.methods.multipart.Part; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.map.ObjectMapper;
import org.rhq.core.util.StringUtil; +import org.rhq.modules.plugins.jbossas7.helper.ServerPluginConfiguration;
/** - * TODO review comments of the class. Add message to say that's it's callers resonsability to call finishUpload or cancelUpload in order to free resources - * * Connection for uploading of content. - * Partially taken from https://github.com/jbossas/jboss-as/blob/master/testsuite/smoke/src/test/jav... + * + * This class needs to cache the content to be uploaded. Users of this class should: + * <ol> + * <li>Call {@link #getOutputStream()} an write their content to the returned {@link OutputStream}</li> + * <li>Call {@link #finishUpload()} to actually upload the content</li> + * </ol> + * + * As instances of this class held some resources it is the caller responsibility to call {@link #cancelUpload()} + * instead of {@link #finishUpload()} if, for example, an {@link IOException} occured while writing their content + * to the {@link OutputStream}. + * + * Original code taken from https://github.com/jbossas/jboss-as/blob/master/testsuite/smoke/src/test/jav... * * @author Jonathan Pearlin (of the original code) * @author Heiko W. Rupp - * + * @author Thomas Segismont */ public class ASUploadConnection {
private static final String HTTP_SCHEME = "http";
- private static final String UPLOAD_URL_PATH = ASConnection.MANAGEMENT + "/add-content"; + private static final int SOCKET_CONNECTION_TIMEOUT = 30 * 1000; // 60sec
private static final int SOCKET_READ_TIMEOUT = 60 * 1000; // 30sec
- private static final int SOCKET_CONNECTION_TIMEOUT = 30 * 1000; // 60sec + private static final String TRIGGER_AUTH_URL_PATH = ASConnection.MANAGEMENT; + + private static final String UPLOAD_URL_PATH = ASConnection.MANAGEMENT + "/add-content"; + + private static final int FILE_POST_MAX_LOGGABLE_RESPONSE_LENGTH = 1024 * 2; // 2k max + + private static final String SYSTEM_LINE_SEPARATOR = System.getProperty("line.separator"); + + private static final String EMPTY_JSON_TREE = "{}"; + + private static final String JSON_NODE_FAILURE_DESCRIPTION = "failure-description"; + + private static final String JSON_NODE_FAILURE_DESCRIPTION_VALUE_DEFAULT = "FailureDescription: -input was null-"; + + private static final String JSON_NODE_OUTCOME = "outcome"; + + private static final String JSON_NODE_OUTCOME_VALUE_FAILED = "failed";
private static final Log log = LogFactory.getLog(ASUploadConnection.class);
@@ -76,14 +106,22 @@ public class ASUploadConnection {
private BufferedOutputStream cacheOutputStream;
- private boolean credentialsProvided() { - // If null user or password is given to the constructor - // no credentials instance is created - return credentials != null; - } - - public ASUploadConnection(String dcHost, int port, String user, String password, String fileName) { - if (dcHost == null) { + /** + * Creates a new {@link ASUploadConnection} for a remote http management interface. + * + * If null user or password is given, this instance will not be able to reply to an authentication challenge. + * + * It's the responsibility of the caller to make sure either {@link #finishUpload()} or {@link #cancelUpload()} + * will be called to free resources this class helds. + * + * @param host - hostname of the remote http management interface + * @param port - port of the remote http management interface + * @param user - username to logon with to the remote http management interface. + * @param password - password to logon with to the remote http management interface + * @param fileName - fileName of the content (to provide in multipart post request) + */ + public ASUploadConnection(String host, int port, String user, String password, String fileName) { + if (host == null) { throw new IllegalArgumentException("Management host cannot be null."); } if (port <= 0 || port > 65535) { @@ -92,7 +130,7 @@ public class ASUploadConnection { if (StringUtil.isBlank(fileName)) { throw new IllegalArgumentException("Filename cannot be blank"); } - this.host = dcHost; + this.host = host; this.port = port; if (user != null && password != null) { credentials = new UsernamePasswordCredentials(user, password); @@ -101,143 +139,158 @@ public class ASUploadConnection { }
/** - * TODO : more - * Gives an outpustream where callers should write the content that will be uploaded to AS7 when {@link #finishUpload()} will be called. + * This factory method simplifies creation of a new {@link ASUploadConnection} instance given the caller has + * access to the {@link ServerPluginConfiguration}. + * + * @param pluginConfig - the {@link ServerPluginConfiguration} + * @param fileName - fileName of the content (to provide in multipart post request) + * @return + */ + public static ASUploadConnection newInstanceForServerPluginConfiguration(ServerPluginConfiguration pluginConfig, + String fileName) { + return new ASUploadConnection(pluginConfig.getHostname(), pluginConfig.getPort(), pluginConfig.getUser(), + pluginConfig.getPassword(), fileName); + } + + /** + * Gives an outpustream where callers should write the content which will be uploaded to AS7 + * when {@link #finishUpload()} will be called. * - * @return an outputstream or null if it could not be created. + * @return an {@link OutputStream} or null if it could not be created. */ public OutputStream getOutputStream() { try { - cacheFile = File.createTempFile("as7upload-" + fileName, "cache"); + cacheFile = File.createTempFile(getClass().getSimpleName(), ".cache"); cacheOutputStream = new BufferedOutputStream(new FileOutputStream(cacheFile)); return cacheOutputStream; } catch (IOException e) { log.error("Could not create outputstream for " + fileName, e); } return null; - - // String url = "http://" + host + ":" + port + UPLOAD_URL_PATH; - // try { - // // Create the HTTP connection to the upload URL - // connection = (HttpURLConnection) new URL(url).openConnection(); - // connection.setConnectTimeout(30 * 1000); // 30s - // connection.setReadTimeout(timeout * 1000); // default 60s - // connection.setDoInput(true); - // connection.setDoOutput(true); - // connection.setRequestMethod(POST_REQUEST_METHOD); - // connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY_PARAM); - // - // // Grab the test WAR file and get a stream to its contents to be included in the POST. - // os = new BufferedOutputStream(connection.getOutputStream()); - // os.write(buildPostRequestHeader(fileName)); - // - // return os; - // } - // catch (Exception e) { - // log.error("Failed to open output stream to URL [" + url + "]: " + e, e); - // } - // - // return null; }
/** - * TODO + * To be called instead of {@link #finishUpload()} if one doesn't want to upload the cached content. + * + * It's important to call this method if not actually uploading as it frees resources this class helds. */ public void cancelUpload() { closeQuietly(cacheOutputStream); - cacheFile.delete(); + deleteCacheFile(); }
/** - * TODO - * @return + * Triggers the real upload to the AS7 instance. At this point the caller should have written + * the content in the {@link OutputStream} given by {@link #getOutputStream()}. + * + * @return a {@link JsonNode} instance read from the upload response body or null if something went wrong. */ public JsonNode finishUpload() {
closeQuietly(cacheOutputStream);
- String targetURL = scheme + "://" + host + ":" + port + UPLOAD_URL_PATH; - - // TODO : we use the same url for the hack but there maybe is a management endpoint with very little response - // We will issue a simple get request in order to trigger authentication challenge. + // We will first send a simple get request in order to trigger authentication challenge. // This allows to send the potentially big file only once to the server // The typical resulting http exchange would be: + // // GET without auth <- 401 (start auth challenge : the server will name the realm and the scheme) // GET with auth <- 200 // POST big file - GetMethod triggerAuthGET = new GetMethod(targetURL); - - PostMethod filePOST = new PostMethod(targetURL); + // + // Note this only works because we use SimpleHttpConnectionManager which maintains + // only one HttpConnection + // + // A better way to avoid uploading a big file multiple times would be to use header Expect: Continue + // Unfortunately AS7 responds 100 Continue even if the authentication headers are not yet present
- HttpClient client = new HttpClient(); + SimpleHttpConnectionManager httpConnectionManager = new SimpleHttpConnectionManager(); + HttpClient client = new HttpClient(httpConnectionManager); if (credentialsProvided()) { client.getState().setCredentials(new AuthScope(host, port, AuthScope.ANY_REALM), credentials); } client.getHttpConnectionManager().getParams().setConnectionTimeout(SOCKET_CONNECTION_TIMEOUT); client.getHttpConnectionManager().getParams().setSoTimeout(SOCKET_READ_TIMEOUT);
- JsonNode tree = null; + String triggerAuthURL = scheme + "://" + host + ":" + port + TRIGGER_AUTH_URL_PATH; + GetMethod triggerAuthGET = new GetMethod(triggerAuthURL); try { - os.write(buildPostRequestFooter()); - os.flush(); + // Send GET request in order to trigger authentication + // We don't check response code because we're not already uploading the file + client.executeMethod(triggerAuthGET); + } catch (Exception ignore) { + // We don't stop trying upload if triggerAuthGET raises exception + // See comment above + } finally { + triggerAuthGET.releaseConnection(); + }
- int code = connection.getResponseCode(); - if (code != 200) { - log.warn("Response code for file upload: " + code + " " + connection.getResponseMessage()); - } - if (code == 500) - is = connection.getErrorStream(); - else - is = connection.getInputStream(); - - if (is != null) { - BufferedReader in = new BufferedReader(new InputStreamReader(is)); - String line; - StringBuilder builder = new StringBuilder(); - while ((line = in.readLine()) != null) { - builder.append(line); - } + String uploadURL = scheme + "://" + host + ":" + port + UPLOAD_URL_PATH; + PostMethod filePOST = new PostMethod(uploadURL); + try {
- ObjectMapper mapper = new ObjectMapper(); + // Now upload file with multipart POST request + Part[] parts = { new FilePart(fileName, cacheFile) }; + filePOST.setRequestEntity(new MultipartRequestEntity(parts, filePOST.getParams())); + int responseCode = client.executeMethod(filePOST); + if (responseCode != HttpStatus.SC_OK) { + logUploadDoesNotEndWithHttpOkStatus(filePOST, responseCode); + return null; + }
- String s = builder.toString(); - if (s != null) - tree = mapper.readTree(s); - else - log.warn("- no result received from InputStream -"); - } else - log.warn("- no InputStream available -"); + ObjectMapper objectMapper = new ObjectMapper(); + InputStream responseBodyAsStream = filePOST.getResponseBodyAsStream(); + if (responseBodyAsStream == null) { + log.warn("POST request has no response body"); + return objectMapper.readTree(EMPTY_JSON_TREE); + } + return objectMapper.readTree(responseBodyAsStream);
- } catch (IOException e) { + } catch (Exception e) { log.error(e); + return null; } finally { - closeQuietly(is); - closeQuietly(os); + // First release connection + filePOST.releaseConnection(); + // Then force close + httpConnectionManager.closeIdleConnections(0); + deleteCacheFile(); } - - return tree; }
+ /** + * Inspects the supplied {@link JsonNode} instance and returns the json 'failure-description' node value as text. + * + * @param jsonNode + * @return + */ public static String getFailureDescription(JsonNode jsonNode) { - if (jsonNode == null) - return "getFailureDescription: -input was null-"; - JsonNode node = jsonNode.findValue("failure-description"); + if (jsonNode == null) { + return JSON_NODE_FAILURE_DESCRIPTION_VALUE_DEFAULT; + } + JsonNode node = jsonNode.findValue(JSON_NODE_FAILURE_DESCRIPTION); + if (node == null) { + return JSON_NODE_FAILURE_DESCRIPTION_VALUE_DEFAULT; + } return node.getValueAsText(); }
- static boolean isErrorReply(JsonNode in) { - if (in == null) + /** + * Inspects the supplied {@link JsonNode} instance to determine if it represents an error outcome. + * + * @param jsonNode + * @return + */ + public static boolean isErrorReply(JsonNode jsonNode) { + if (jsonNode == null) { return true; + }
- if (in.has("outcome")) { + if (jsonNode.has(JSON_NODE_OUTCOME)) { String outcome = null; try { - JsonNode outcomeNode = in.findValue("outcome"); + JsonNode outcomeNode = jsonNode.findValue(JSON_NODE_OUTCOME); outcome = outcomeNode.getTextValue(); - if (outcome.equals("failed")) { - JsonNode reasonNode = in.findValue("failure-description"); - - reasonNode.getTextValue(); + if (outcome.equals(JSON_NODE_OUTCOME_VALUE_FAILED)) { return true; } } catch (Exception e) { @@ -248,6 +301,29 @@ public class ASUploadConnection { return false; }
+ private boolean credentialsProvided() { + // If null user or password is given to the constructor + // no credentials instance is created + return credentials != null; + } + + private void logUploadDoesNotEndWithHttpOkStatus(PostMethod filePOST, int responseCode) { + StringBuilder logMessageBuilder = new StringBuilder("File upload failed: ").append(HttpStatus + .getStatusText(responseCode)); + // If it's sure there is a response body and it's not too long + if (filePOST.getResponseContentLength() > 0 + && filePOST.getResponseContentLength() < FILE_POST_MAX_LOGGABLE_RESPONSE_LENGTH) { + try { + // It is safe to call getResponseBodyAsString as we know the body is not too long + String responseBodyAsString = filePOST.getResponseBodyAsString(); + logMessageBuilder.append(SYSTEM_LINE_SEPARATOR).append(responseBodyAsString); + } catch (IOException ignore) { + // If we can't get the response body, we'll just not log it + } + } + log.warn(logMessageBuilder.toString()); + } + private void closeQuietly(final Closeable closeable) { if (closeable != null) { try { @@ -257,4 +333,10 @@ public class ASUploadConnection { } }
+ private void deleteCacheFile() { + if (cacheFile != null) { + cacheFile.delete(); + } + } + } diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseComponent.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseComponent.java index 080c60f..2451728 100644 --- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseComponent.java +++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseComponent.java @@ -63,7 +63,6 @@ import org.rhq.core.pluginapi.measurement.MeasurementFacet; import org.rhq.core.pluginapi.operation.OperationFacet; import org.rhq.core.pluginapi.operation.OperationResult; import org.rhq.core.pluginapi.util.StartScriptConfiguration; -import org.rhq.modules.plugins.jbossas7.helper.ServerPluginConfiguration; import org.rhq.modules.plugins.jbossas7.json.Address; import org.rhq.modules.plugins.jbossas7.json.CompositeOperation; import org.rhq.modules.plugins.jbossas7.json.Operation; @@ -80,7 +79,7 @@ import org.rhq.modules.plugins.jbossas7.json.Result; * @param <T> the type of the component's parent resource component */ public class BaseComponent<T extends ResourceComponent<?>> implements AS7Component<T>, MeasurementFacet, - ConfigurationFacet, DeleteResourceFacet, CreateChildResourceFacet, OperationFacet { + ConfigurationFacet, DeleteResourceFacet, CreateChildResourceFacet, OperationFacet {
private static final String INTERNAL = "_internal:"; private static final int INTERNAL_SIZE = INTERNAL.length(); @@ -105,6 +104,7 @@ public class BaseComponent<T extends ResourceComponent<?>> implements AS7Compone * Start the resource connection * @see org.rhq.core.pluginapi.inventory.ResourceComponent#start(org.rhq.core.pluginapi.inventory.ResourceContext) */ + @Override public void start(ResourceContext<T> context) throws InvalidPluginConfigurationException, Exception { this.context = context; pluginConfiguration = context.getPluginConfiguration(); @@ -132,6 +132,7 @@ public class BaseComponent<T extends ResourceComponent<?>> implements AS7Compone * Return availability of this resource * @see org.rhq.core.pluginapi.inventory.ResourceComponent#getAvailability() */ + @Override public AvailabilityType getAvailability() { ReadResource op = new ReadResource(address); Result res = getASConnection().execute(op); @@ -147,7 +148,7 @@ public class BaseComponent<T extends ResourceComponent<?>> implements AS7Compone while ((component != null) && !(component instanceof BaseServerComponent)) { component = (BaseComponent<?>) component.context.getParentResourceComponent(); } - return (BaseServerComponent)component; + return (BaseServerComponent) component; }
public BaseServerComponent getServerComponent() { @@ -158,6 +159,7 @@ public class BaseComponent<T extends ResourceComponent<?>> implements AS7Compone * Gather measurement data * @see org.rhq.core.pluginapi.measurement.MeasurementFacet#getValues(org.rhq.core.domain.measurement.MeasurementReport, java.util.Set) */ + @Override public void getValues(MeasurementReport report, Set<MeasurementScheduleRequest> metrics) throws Exception {
for (MeasurementScheduleRequest req : metrics) { @@ -262,19 +264,22 @@ public class BaseComponent<T extends ResourceComponent<?>> implements AS7Compone report.addData(data); }
+ @Override public ASConnection getASConnection() { return (this.testConnection != null) ? this.testConnection : getServerComponent().getASConnection(); }
+ @Override public String getPath() { return path; }
+ @Override public Configuration loadResourceConfiguration() throws Exception {
ConfigurationDefinition configDef = context.getResourceType().getResourceConfigurationDefinition(); ConfigurationLoadDelegate delegate = new ConfigurationLoadDelegate(configDef, getASConnection(), address, - includeRuntime); + includeRuntime); Configuration configuration = delegate.loadResourceConfiguration();
// Read server state @@ -289,7 +294,8 @@ public class BaseComponent<T extends ResourceComponent<?>> implements AS7Compone }
if (res.isReloadRequired()) { - PropertySimple oobMessage = new PropertySimple("__OOB","The server needs a reload for the latest changes to come effective."); + PropertySimple oobMessage = new PropertySimple("__OOB", + "The server needs a reload for the latest changes to come effective."); configuration.put(oobMessage); } if (res.isRestartRequired()) { @@ -300,6 +306,7 @@ public class BaseComponent<T extends ResourceComponent<?>> implements AS7Compone return configuration; }
+ @Override public void updateResourceConfiguration(ConfigurationUpdateReport report) {
ConfigurationDefinition configDef = context.getResourceType().getResourceConfigurationDefinition(); @@ -354,18 +361,19 @@ public class BaseComponent<T extends ResourceComponent<?>> implements AS7Compone // check if there is already a child with th desired type is present Configuration pluginConfig = report.getPluginConfiguration(); PropertySimple pathProperty = pluginConfig.getSimple("path"); - if (path==null || path.isEmpty()) { + if (path == null || path.isEmpty()) { report.setErrorMessage("No path property found in plugin configuration"); report.setStatus(CreateResourceStatus.INVALID_CONFIGURATION); return report; }
- ReadChildrenNames op = new ReadChildrenNames(address,pathProperty.getStringValue()); + ReadChildrenNames op = new ReadChildrenNames(address, pathProperty.getStringValue()); Result res = connection.execute(op); if (res.isSuccess()) { List<String> entries = (List<String>) res.getResult(); if (!entries.isEmpty()) { - report.setErrorMessage("Resource is a singleton, but there are already children " + entries + " please remove them and retry"); + report.setErrorMessage("Resource is a singleton, but there are already children " + entries + + " please remove them and retry"); report.setStatus(CreateResourceStatus.FAILURE); return report; } @@ -395,11 +403,23 @@ public class BaseComponent<T extends ResourceComponent<?>> implements AS7Compone ContentServices contentServices = cctx.getContentServices(); String resourceTypeName = report.getResourceType().getName();
- ServerPluginConfiguration serverPluginConfig = getServerComponent().getServerPluginConfiguration(); - ASUploadConnection uploadConnection = new ASUploadConnection(serverPluginConfig.getHostname(), - serverPluginConfig.getPort(), serverPluginConfig.getUser(), serverPluginConfig.getPassword()); - OutputStream out = uploadConnection.getOutputStream(details.getKey().getName()); - contentServices.downloadPackageBitsForChildResource(cctx, resourceTypeName, details.getKey(), out); + ASUploadConnection uploadConnection = ASUploadConnection.newInstanceForServerPluginConfiguration( + getServerComponent().getServerPluginConfiguration(), details.getKey().getName()); + + OutputStream out = uploadConnection.getOutputStream(); + if (out == null) { + report.setStatus(CreateResourceStatus.FAILURE); + report.setErrorMessage("An error occured while the agent was preparing for content download"); + return report; + } + try { + contentServices.downloadPackageBitsForChildResource(cctx, resourceTypeName, details.getKey(), out); + } catch (Exception e) { + uploadConnection.cancelUpload(); + report.setStatus(CreateResourceStatus.FAILURE); + report.setErrorMessage("An error occured while the agent was downloading the content"); + return report; + }
JsonNode uploadResult = uploadConnection.finishUpload(); if (verbose) { @@ -409,12 +429,11 @@ public class BaseComponent<T extends ResourceComponent<?>> implements AS7Compone if (ASUploadConnection.isErrorReply(uploadResult)) { report.setStatus(CreateResourceStatus.FAILURE); report.setErrorMessage(ASUploadConnection.getFailureDescription(uploadResult)); - return report; }
// Key is available from UI and CLI - String fileName = details.getKey().getName(); + String fileName = details.getKey().getName();
String runtimeName = report.getPackageDetails().getDeploymentTimeConfiguration().getSimpleValue("runtimeName"); if (runtimeName == null || runtimeName.isEmpty()) { @@ -523,14 +542,12 @@ public class BaseComponent<T extends ResourceComponent<?>> implements AS7Compone int colonPos = name.indexOf(':'); what = name.substring(0, colonPos); op = name.substring(colonPos + 1); - } - else { - what=""; // dummy value + } else { + what = ""; // dummy value op = name; } Operation operation = null;
- Address theAddress = new Address();
if (what.equals("server-group")) { @@ -583,11 +600,10 @@ public class BaseComponent<T extends ResourceComponent<?>> implements AS7Compone if (prop instanceof PropertySimple) { PropertySimple ps = (PropertySimple) prop; if (ps.getStringValue() != null) { - Object val = getObjectForProperty(ps,op); - operation.addAdditionalProperty(ps.getName(),val); + Object val = getObjectForProperty(ps, op); + operation.addAdditionalProperty(ps.getName(), val); } - } - else if (prop instanceof PropertyList) { + } else if (prop instanceof PropertyList) { PropertyList pl = (PropertyList) prop; List<Object> items = new ArrayList<Object>(pl.getList().size()); // Loop over the inner elements of the list @@ -595,14 +611,13 @@ public class BaseComponent<T extends ResourceComponent<?>> implements AS7Compone if (p2 instanceof PropertySimple) { PropertySimple ps = (PropertySimple) p2; if (ps.getStringValue() != null) { - Object val = getObjectForPropertyList(ps,pl,op); + Object val = getObjectForPropertyList(ps, pl, op); items.add(val); } } } - operation.addAdditionalProperty(pl.getName(),items); - } - else { + operation.addAdditionalProperty(pl.getName(), items); + } else { log.error("PropertyMap for " + prop.getName() + " not yet supported"); } } @@ -637,7 +652,7 @@ public class BaseComponent<T extends ResourceComponent<?>> implements AS7Compone */ Object getObjectForProperty(PropertySimple prop, String operationName) { ConfigurationDefinition parameterDefinitions = getParameterDefinitionsForOperation(operationName); - if (parameterDefinitions==null) + if (parameterDefinitions == null) return null;
PropertyDefinition pd = parameterDefinitions.get(prop.getName()); @@ -660,14 +675,14 @@ public class BaseComponent<T extends ResourceComponent<?>> implements AS7Compone */ Object getObjectForPropertyList(PropertySimple prop, PropertyList propertyList, String operationName) { ConfigurationDefinition parameterDefinitions = getParameterDefinitionsForOperation(operationName); - if (parameterDefinitions==null) + if (parameterDefinitions == null) return null;
PropertyDefinition def = parameterDefinitions.get(propertyList.getName()); - if (def instanceof PropertyDefinitionList) { + if (def instanceof PropertyDefinitionList) { PropertyDefinitionList definitionList = (PropertyDefinitionList) def; PropertyDefinition tmp = definitionList.getMemberDefinition(); - if (tmp instanceof PropertyDefinitionSimple) { + if (tmp instanceof PropertyDefinitionSimple) { return getObjectForProperty(prop, (PropertyDefinitionSimple) tmp); } } @@ -755,7 +770,7 @@ public class BaseComponent<T extends ResourceComponent<?>> implements AS7Compone Result res = getASConnection().execute(op); if (!res.isSuccess()) { throw new Exception("Failed to read attribute [" + name + "] of address [" + getAddress().getPath() - + "] - response: " + res); + + "] - response: " + res); } return (T) res.getResult(); } @@ -797,11 +812,13 @@ public class BaseComponent<T extends ResourceComponent<?>> implements AS7Compone int endIndex = expressionValue.indexOf('}', beginIndex); if (endIndex >= 0) { String expression = expressionValue.substring(beginIndex + 2, endIndex); - StartScriptConfiguration startScriptConfig = getServerComponent().getStartScriptConfiguration(); + StartScriptConfiguration startScriptConfig = getServerComponent() + .getStartScriptConfiguration(); List<String> startScriptArgs = startScriptConfig.getStartScriptArgs(); for (String startScriptArg : startScriptArgs) { if (startScriptArg.startsWith("-Djboss.default.multicast.address=")) { - multicastHost = startScriptArg.substring("-Djboss.default.multicast.address=".length()); + multicastHost = startScriptArg.substring("-Djboss.default.multicast.address=" + .length()); break; } } @@ -812,7 +829,7 @@ public class BaseComponent<T extends ResourceComponent<?>> implements AS7Compone multicastHost = defaultValue; } else { log.error("Failed to resolve expression value [" + expressionValue - + "] of 'multicast-address' attribute."); + + "] of 'multicast-address' attribute."); } } } @@ -822,7 +839,8 @@ public class BaseComponent<T extends ResourceComponent<?>> implements AS7Compone } multicastPort = readAttribute(jgroupsSocketBindingAddress, "multicast-port", Integer.class); } catch (Exception e) { - throw new RuntimeException("Failed to lookup multicast address for socket binding [" + socketBinding + "]."); + throw new RuntimeException("Failed to lookup multicast address for socket binding [" + socketBinding + + "]."); }
if (multicastHost != null && multicastPort != null) { diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/DeploymentComponent.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/DeploymentComponent.java index 3cf2cdb..0d166b4 100644 --- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/DeploymentComponent.java +++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/DeploymentComponent.java @@ -50,34 +50,35 @@ import org.rhq.modules.plugins.jbossas7.json.Result; * Deal with deployments * @author Heiko W. Rupp */ -public class DeploymentComponent extends BaseComponent<ResourceComponent<?>> implements OperationFacet, ContentFacet { +public class DeploymentComponent extends BaseComponent<ResourceComponent<?>> implements OperationFacet, ContentFacet {
private static final String DOMAIN_DATA_CONTENT_SUBDIR = "/data/content"; private boolean verbose = ASConnection.verbose; private File deploymentFile;
@Override - public void start(ResourceContext<ResourceComponent<?>> context) throws InvalidPluginConfigurationException, Exception { + public void start(ResourceContext<ResourceComponent<?>> context) throws InvalidPluginConfigurationException, + Exception { super.start(context); deploymentFile = determineDeploymentFile(); }
@Override public AvailabilityType getAvailability() { - Operation op = new ReadAttribute(getAddress(),"enabled"); + Operation op = new ReadAttribute(getAddress(), "enabled"); Result res = getASConnection().execute(op); if (!res.isSuccess()) return AvailabilityType.DOWN;
- if (res.getResult()== null || !(Boolean)(res.getResult())) + if (res.getResult() == null || !(Boolean) (res.getResult())) return AvailabilityType.DOWN;
return AvailabilityType.UP; }
@Override - public OperationResult invokeOperation(String name, - Configuration parameters) throws InterruptedException, Exception { + public OperationResult invokeOperation(String name, Configuration parameters) throws InterruptedException, + Exception {
if (name.equals("enable")) { return invokeSimpleOperation("deploy"); @@ -86,7 +87,7 @@ public class DeploymentComponent extends BaseComponent<ResourceComponent<?>> imp } else if (name.equals("restart")) { OperationResult result = invokeSimpleOperation("undeploy");
- if(result.getErrorMessage() == null){ + if (result.getErrorMessage() == null) { result = invokeSimpleOperation("deploy"); }
@@ -97,7 +98,7 @@ public class DeploymentComponent extends BaseComponent<ResourceComponent<?>> imp }
private OperationResult invokeSimpleOperation(String action) { - Operation op = new Operation(action,getAddress()); + Operation op = new Operation(action, getAddress()); Result res = getASConnection().execute(op); OperationResult result = new OperationResult(); if (res.isSuccess()) { @@ -115,19 +116,17 @@ public class DeploymentComponent extends BaseComponent<ResourceComponent<?>> imp return result; }
- @Override public List<DeployPackageStep> generateInstallationSteps(ResourcePackageDetails packageDetails) { return new ArrayList<DeployPackageStep>(); }
@Override - public DeployPackagesResponse deployPackages(Set<ResourcePackageDetails> packages, - ContentServices contentServices) { + public DeployPackagesResponse deployPackages(Set<ResourcePackageDetails> packages, ContentServices contentServices) { log.debug("Starting deployment.."); DeployPackagesResponse response = new DeployPackagesResponse();
- if (packages.size()!=1) { + if (packages.size() != 1) { response.setOverallRequestResult(ContentResponseResult.FAILURE); response.setOverallRequestErrorMessage("Can only deploy one package at a time"); log.warn("deployPackages can only deploy one package at a time"); @@ -135,14 +134,27 @@ public class DeploymentComponent extends BaseComponent<ResourceComponent<?>> imp
ResourcePackageDetails detail = packages.iterator().next();
- ASUploadConnection uploadConnection = new ASUploadConnection(getASConnection()); - OutputStream out = uploadConnection.getOutputStream(detail.getKey().getName()); + ASUploadConnection uploadConnection = ASUploadConnection.newInstanceForServerPluginConfiguration( + getServerComponent().getServerPluginConfiguration(), detail.getKey().getName()); + OutputStream out = uploadConnection.getOutputStream(); + if (out == null) { + response.setOverallRequestResult(ContentResponseResult.FAILURE); + response + .setOverallRequestErrorMessage("An error occured while the agent was preparing for content download"); + return response; + } ResourceType resourceType = context.getResourceType();
- log.info("Deploying " + resourceType.getName() + " Resource with key [" + detail.getKey() +"]..."); + log.info("Deploying " + resourceType.getName() + " Resource with key [" + detail.getKey() + "]...");
- contentServices.downloadPackageBits(context.getContentContext(), - detail.getKey(), out, true); + try { + contentServices.downloadPackageBits(context.getContentContext(), detail.getKey(), out, true); + } catch (Exception e) { + uploadConnection.cancelUpload(); + response.setOverallRequestResult(ContentResponseResult.FAILURE); + response.setOverallRequestErrorMessage("An error occured while the agent was downloading the content"); + return response; + }
JsonNode uploadResult = uploadConnection.finishUpload(); if (verbose) { @@ -152,32 +164,29 @@ public class DeploymentComponent extends BaseComponent<ResourceComponent<?>> imp if (ASUploadConnection.isErrorReply(uploadResult)) { response.setOverallRequestResult(ContentResponseResult.FAILURE); response.setOverallRequestErrorMessage(ASUploadConnection.getFailureDescription(uploadResult)); - return response; } + JsonNode resultNode = uploadResult.get("result"); String hash = resultNode.get("BYTES_VALUE").getTextValue();
- - CreateResourceReport report1 = new CreateResourceReport("", resourceType, new Configuration(), - new Configuration(), detail); - //CreateResourceReport report = runDeploymentMagicOnServer(report1,detail.getKey().getName(),hash, hash); + new CreateResourceReport("", resourceType, new Configuration(), new Configuration(), detail);
try { redeployOnServer(detail.getKey().getName(), hash); response.setOverallRequestResult(ContentResponseResult.SUCCESS); //we just deployed a different file on the AS7 server, so let's refresh ourselves deploymentFile = determineDeploymentFile(); - DeployIndividualPackageResponse packageResponse = new DeployIndividualPackageResponse(detail.getKey(), ContentResponseResult.SUCCESS); - response.addPackageResponse(packageResponse); + DeployIndividualPackageResponse packageResponse = new DeployIndividualPackageResponse(detail.getKey(), + ContentResponseResult.SUCCESS); + response.addPackageResponse(packageResponse);
- } - catch (Exception e) { + } catch (Exception e) { response.setOverallRequestResult(ContentResponseResult.FAILURE); }
- log.info("Result of deployment of " + resourceType.getName() + " Resource with key [" + detail.getKey() - + "]: " + response); + log.info("Result of deployment of " + resourceType.getName() + " Resource with key [" + detail.getKey() + "]: " + + response);
return response; } @@ -185,12 +194,12 @@ public class DeploymentComponent extends BaseComponent<ResourceComponent<?>> imp private void redeployOnServer(String name, String hash) throws Exception {
Operation op = new Operation("full-replace-deployment", new Address()); - op.addAdditionalProperty("name",name); + op.addAdditionalProperty("name", name); List<Object> content = new ArrayList<Object>(1); - Map<String,Object> contentValues = new HashMap<String,Object>(); - contentValues.put("hash",new PROPERTY_VALUE("BYTES_VALUE",hash)); + Map<String, Object> contentValues = new HashMap<String, Object>(); + contentValues.put("hash", new PROPERTY_VALUE("BYTES_VALUE", hash)); content.add(contentValues); - op.addAdditionalProperty("content",content); + op.addAdditionalProperty("content", content); Result result = getASConnection().execute(op); if (result.isRolledBack()) throw new Exception(result.getFailureDescription()); @@ -257,12 +266,12 @@ public class DeploymentComponent extends BaseComponent<ResourceComponent<?>> imp // No content -> check for server group if (path.startsWith(("server-group="))) { // Server group has no content of its own - use the domain deployment - String name = (String) path.substring(path.lastIndexOf("=")+1); - op = new ReadResource(new Address("deployment",name)); + String name = (String) path.substring(path.lastIndexOf("=") + 1); + op = new ReadResource(new Address("deployment", name)); result = getASConnection().execute(op); if (result.isSuccess()) { @SuppressWarnings("unchecked") - Map<String,Object> contentMap = (Map<String, Object>) result.getResult(); + Map<String, Object> contentMap = (Map<String, Object>) result.getResult(); content = (List<Map<String, Object>>) contentMap.get("content"); if (content.get(0).containsKey("path")) { String path = (String) content.get(0).get("path"); @@ -270,19 +279,21 @@ public class DeploymentComponent extends BaseComponent<ResourceComponent<?>> imp deploymentFile = getDeploymentFileFromPath(relativeTo, path); } else if (content.get(0).containsKey("hash")) { @SuppressWarnings("unchecked") - String base64Hash = ((Map<String, String>)content.get(0).get("hash")).get("BYTES_VALUE"); + String base64Hash = ((Map<String, String>) content.get(0).get("hash")).get("BYTES_VALUE"); byte[] hash = Base64.decode(base64Hash); ServerGroupComponent sgc = (ServerGroupComponent) context.getParentResourceComponent(); - String baseDir = ((HostControllerComponent) sgc.context.getParentResourceComponent()).pluginConfiguration.getSimpleValue("baseDir"); - String contentPath = new File(baseDir , "/data/content").getAbsolutePath(); + String baseDir = ((HostControllerComponent) sgc.context.getParentResourceComponent()).pluginConfiguration + .getSimpleValue("baseDir"); + String contentPath = new File(baseDir, "/data/content").getAbsolutePath(); deploymentFile = getDeploymentFileFromHash(hash, contentPath); } return deploymentFile; } + } else { + log.warn("Could not determine the location of the deployment - the content descriptor wasn't found for deployment" + + getAddress() + "."); + return null; } - else { - log.warn("Could not determine the location of the deployment - the content descriptor wasn't found for deployment" + getAddress() + "."); - return null;} }
Boolean archive = (Boolean) content.get(0).get("archive"); @@ -298,17 +309,16 @@ public class DeploymentComponent extends BaseComponent<ResourceComponent<?>> imp deploymentFile = getDeploymentFileFromPath(relativeTo, path); } else if (content.get(0).containsKey("hash")) { @SuppressWarnings("unchecked") - String base64Hash = ((Map<String, String>)content.get(0).get("hash")).get("BYTES_VALUE"); + String base64Hash = ((Map<String, String>) content.get(0).get("hash")).get("BYTES_VALUE"); byte[] hash = Base64.decode(base64Hash); Address contentPathAddress; if (context.getParentResourceComponent() instanceof ManagedASComponent) { // -> managed server we need to check for host=x/server=y, but the path brings host=x,server-config=y String p = ((ManagedASComponent) context.getParentResourceComponent()).getPath(); - p = p.replaceAll("server-config=","server="); + p = p.replaceAll("server-config=", "server="); contentPathAddress = new Address(p); contentPathAddress.add("core-service", "server-environment"); - } - else { + } else { // standalone contentPathAddress = new Address("core-service", "server-environment"); } @@ -321,16 +331,17 @@ public class DeploymentComponent extends BaseComponent<ResourceComponent<?>> imp } else { // No success above -> check if this is a domain deployment if (this instanceof DomainDeploymentComponent) { - String baseDir = ((HostControllerComponent) context.getParentResourceComponent()).pluginConfiguration.getSimpleValue("baseDir"); - contentPath = new File(baseDir , DOMAIN_DATA_CONTENT_SUBDIR).getAbsolutePath(); - } - else { + String baseDir = ((HostControllerComponent) context.getParentResourceComponent()).pluginConfiguration + .getSimpleValue("baseDir"); + contentPath = new File(baseDir, DOMAIN_DATA_CONTENT_SUBDIR).getAbsolutePath(); + } else { contentPath = "-unknown-"; } } deploymentFile = getDeploymentFileFromHash(hash, contentPath); } else { - log.warn("Failed to determine the deployment file of " + getAddress() + " deployment. Neither path nor hash attributes were available."); + log.warn("Failed to determine the deployment file of " + getAddress() + + " deployment. Neither path nor hash attributes were available."); }
return deploymentFile; diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ServerGroupComponent.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ServerGroupComponent.java index 82b1042..71967e5 100644 --- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ServerGroupComponent.java +++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ServerGroupComponent.java @@ -44,7 +44,6 @@ import org.rhq.core.pluginapi.content.ContentServices; import org.rhq.core.pluginapi.inventory.CreateChildResourceFacet; import org.rhq.core.pluginapi.operation.OperationFacet; import org.rhq.core.pluginapi.operation.OperationResult; -import org.rhq.modules.plugins.jbossas7.helper.ServerPluginConfiguration; import org.rhq.modules.plugins.jbossas7.json.Address; import org.rhq.modules.plugins.jbossas7.json.CompositeOperation; import org.rhq.modules.plugins.jbossas7.json.Operation; @@ -58,24 +57,23 @@ import org.rhq.modules.plugins.jbossas7.json.Result; */ @SuppressWarnings("unused") public class ServerGroupComponent extends BaseComponent implements ContentFacet, CreateChildResourceFacet, - OperationFacet { + OperationFacet {
private static final String SUCCESS = "success"; private static final String OUTCOME = "outcome";
@Override - public OperationResult invokeOperation(String name, - Configuration parameters) throws InterruptedException, Exception { + public OperationResult invokeOperation(String name, Configuration parameters) throws InterruptedException, + Exception {
- Operation op = new Operation(name,getAddress()); + Operation op = new Operation(name, getAddress()); Result res = getASConnection().execute(op);
OperationResult result = new OperationResult();
if (res.isSuccess()) { result.setSimpleResult(SUCCESS); - } - else { + } else { result.setErrorMessage(res.getFailureDescription()); } return result; @@ -84,13 +82,12 @@ public class ServerGroupComponent extends BaseComponent implements ContentFacet,
@Override public List<DeployPackageStep> generateInstallationSteps(ResourcePackageDetails packageDetails) { - return null; // TODO: Customise this generated block + return null; // TODO: Customise this generated block }
// TODO I think this package code is not used. @Override - public DeployPackagesResponse deployPackages(Set<ResourcePackageDetails> packages, - ContentServices contentServices) { + public DeployPackagesResponse deployPackages(Set<ResourcePackageDetails> packages, ContentServices contentServices) {
ContentContext cctx = context.getContentContext();
@@ -98,13 +95,28 @@ public class ServerGroupComponent extends BaseComponent implements ContentFacet,
for (ResourcePackageDetails details : packages) {
- ServerPluginConfiguration serverPluginConfig = getServerComponent().getServerPluginConfiguration(); - ASUploadConnection uploadConnection = new ASUploadConnection(serverPluginConfig.getHostname(), - serverPluginConfig.getPort(), serverPluginConfig.getUser(), serverPluginConfig.getPassword()); String packageName = details.getName(); - OutputStream out = uploadConnection.getOutputStream(packageName); - contentServices.downloadPackageBits(cctx, details.getKey(), out, false); + + ASUploadConnection uploadConnection = ASUploadConnection.newInstanceForServerPluginConfiguration( + getServerComponent().getServerPluginConfiguration(), packageName); + OutputStream out = uploadConnection.getOutputStream(); + if (out == null) { + response.addPackageResponse(new DeployIndividualPackageResponse(details.getKey(), + ContentResponseResult.FAILURE)); + continue; + } + + try { + contentServices.downloadPackageBits(cctx, details.getKey(), out, false); + } catch (Exception e) { + uploadConnection.cancelUpload(); + response.addPackageResponse(new DeployIndividualPackageResponse(details.getKey(), + ContentResponseResult.FAILURE)); + continue; + } + JsonNode uploadResult = uploadConnection.finishUpload(); + if (uploadResult.has(OUTCOME)) { String outcome = uploadResult.get(OUTCOME).getTextValue(); if (outcome.equals(SUCCESS)) { // Upload was successful, so now add the file to the server group @@ -114,20 +126,20 @@ public class ServerGroupComponent extends BaseComponent implements ContentFacet,
Address deploymentsAddress = new Address(); deploymentsAddress.add("deployment", packageName); - Operation step1 = new Operation("add",deploymentsAddress); -// step1.addAdditionalProperty("hash", new PROPERTY_VALUE("BYTES_VALUE", hash)); + Operation step1 = new Operation("add", deploymentsAddress); + // step1.addAdditionalProperty("hash", new PROPERTY_VALUE("BYTES_VALUE", hash)); List<Object> content = new ArrayList<Object>(1); - Map<String,Object> contentValues = new HashMap<String,Object>(); - contentValues.put("hash",new PROPERTY_VALUE("BYTES_VALUE",hash)); + Map<String, Object> contentValues = new HashMap<String, Object>(); + contentValues.put("hash", new PROPERTY_VALUE("BYTES_VALUE", hash)); content.add(contentValues); - step1.addAdditionalProperty("content",content); + step1.addAdditionalProperty("content", content);
step1.addAdditionalProperty("name", packageName);
Address serverGroupAddress = new Address(context.getResourceKey()); serverGroupAddress.add("deployment", packageName); - Operation step2 = new Operation("add",serverGroupAddress); - Operation step3 = new Operation("deploy",serverGroupAddress); + Operation step2 = new Operation("add", serverGroupAddress); + Operation step3 = new Operation("deploy", serverGroupAddress);
CompositeOperation cop = new CompositeOperation(); cop.addStep(step1); @@ -136,36 +148,35 @@ public class ServerGroupComponent extends BaseComponent implements ContentFacet,
Result result = connection.execute(cop); if (!result.isSuccess()) // TODO get failure message into response - response.addPackageResponse(new DeployIndividualPackageResponse(details.getKey(),ContentResponseResult.FAILURE)); + response.addPackageResponse(new DeployIndividualPackageResponse(details.getKey(), + ContentResponseResult.FAILURE)); else { DeployIndividualPackageResponse individualPackageResponse = new DeployIndividualPackageResponse( - details.getKey(), ContentResponseResult.SUCCESS); + details.getKey(), ContentResponseResult.SUCCESS); response.addPackageResponse(individualPackageResponse); response.setOverallRequestResult(ContentResponseResult.SUCCESS); } - } - else - response.addPackageResponse(new DeployIndividualPackageResponse(details.getKey(),ContentResponseResult.FAILURE)); - } - else { - response.addPackageResponse( - new DeployIndividualPackageResponse(details.getKey(), ContentResponseResult.FAILURE)); + } else + response.addPackageResponse(new DeployIndividualPackageResponse(details.getKey(), + ContentResponseResult.FAILURE)); + } else { + response.addPackageResponse(new DeployIndividualPackageResponse(details.getKey(), + ContentResponseResult.FAILURE)); } }
- return response; }
@Override public RemovePackagesResponse removePackages(Set<ResourcePackageDetails> packages) { - return null; // TODO: Customise this generated block + return null; // TODO: Customise this generated block }
@Override public Set<ResourcePackageDetails> discoverDeployedPackages(PackageType type) {
- Operation op = new ReadChildrenNames(address,"deployment"); // TODO read full packages not only names + Operation op = new ReadChildrenNames(address, "deployment"); // TODO read full packages not only names Result node = getASConnection().execute(op); if (!node.isSuccess()) return null; @@ -175,11 +186,11 @@ public class ServerGroupComponent extends BaseComponent implements ContentFacet, for (String file : resultList) { String t; if (file.contains(".")) - t = file.substring(file.lastIndexOf(".")+1); + t = file.substring(file.lastIndexOf(".") + 1); else t = "-none-";
- ResourcePackageDetails detail = new ResourcePackageDetails(new PackageDetailsKey(file,"1.0",t,"all")); + ResourcePackageDetails detail = new ResourcePackageDetails(new PackageDetailsKey(file, "1.0", t, "all")); details.add(detail); } return details; @@ -188,11 +199,11 @@ public class ServerGroupComponent extends BaseComponent implements ContentFacet,
@Override public InputStream retrievePackageBits(ResourcePackageDetails packageDetails) { - return null; // TODO: Customise this generated block + return null; // TODO: Customise this generated block }
private String serverGroupFromKey() { String key1 = context.getResourceKey(); - return key1.substring(key1.lastIndexOf("/")+1); + return key1.substring(key1.lastIndexOf("/") + 1); } } diff --git a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/nonpc/AbstractIntegrationTest.java b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/nonpc/AbstractIntegrationTest.java index 130f7f3..428f854 100644 --- a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/nonpc/AbstractIntegrationTest.java +++ b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/nonpc/AbstractIntegrationTest.java @@ -59,7 +59,7 @@ import org.rhq.modules.plugins.jbossas7.json.PROPERTY_VALUE; * * @author Heiko W. Rupp */ -@Test(groups = {"integration", "nonpc"}, dependsOnGroups = "discovery") +@Test(groups = { "integration", "nonpc" }, dependsOnGroups = "discovery") public abstract class AbstractIntegrationTest {
protected static final String PLUGIN_NAME = "JBossAS7"; @@ -71,19 +71,19 @@ public abstract class AbstractIntegrationTest { protected static final String MAVEN_REPO_LOCAL = System.getProperty("settings.localRepository");
String uploadToAs(String deploymentPath) throws IOException { - ASUploadConnection conn = new ASUploadConnection(DC_HOST, DC_HTTP_PORT, DC_USER, DC_PASS); String fileName = new File(deploymentPath).getName(); - OutputStream os = conn.getOutputStream(fileName); + ASUploadConnection conn = new ASUploadConnection(DC_HOST, DC_HTTP_PORT, DC_USER, DC_PASS, fileName); + OutputStream os = conn.getOutputStream();
-// URL url = getClass().getClassLoader().getResource("."); -// System.out.println(url); + // URL url = getClass().getClassLoader().getResource("."); + // System.out.println(url);
InputStream fis = getClass().getClassLoader().getResourceAsStream(deploymentPath); if (fis == null) { File inputFile = new File(deploymentPath); if (!inputFile.canRead()) { throw new FileNotFoundException("Input stream for path [" + deploymentPath - + "] could not be opened - does the file exist either in the test classpath or on the filesystem?"); + + "] could not be opened - does the file exist either in the test classpath or on the filesystem?"); } fis = new FileInputStream(inputFile); } @@ -96,7 +96,7 @@ public abstract class AbstractIntegrationTest { }
JsonNode node = conn.finishUpload(); -// System.out.println(node); + // System.out.println(node); assert node != null : "No result from upload - node was null"; assert node.has("outcome") : "No outcome from upload"; String outcome = node.get("outcome").getTextValue(); @@ -111,13 +111,12 @@ public abstract class AbstractIntegrationTest { return connection; }
- Operation addDeployment(String deploymentName, String bytes_value) - { + Operation addDeployment(String deploymentName, String bytes_value) { Address deploymentsAddress = new Address("deployment", deploymentName); Operation op = new Operation("add", deploymentsAddress); List<Object> content = new ArrayList<Object>(1); - Map<String,Object> contentValues = new HashMap<String,Object>(); - contentValues.put("hash",new PROPERTY_VALUE("BYTES_VALUE", bytes_value)); + Map<String, Object> contentValues = new HashMap<String, Object>(); + contentValues.put("hash", new PROPERTY_VALUE("BYTES_VALUE", bytes_value)); content.add(contentValues); op.addAdditionalProperty("content", content); op.addAdditionalProperty("name", deploymentName); // this needs to be unique per upload @@ -156,7 +155,8 @@ public abstract class AbstractIntegrationTest { List<ServerDescriptor> servers = pluginDescriptor.getServers();
ServerDescriptor serverDescriptor = findServer(serverName, servers); - assert serverDescriptor != null : "Server descriptor for server [" + serverName + "] not found in test plugin descriptor"; + assert serverDescriptor != null : "Server descriptor for server [" + serverName + + "] not found in test plugin descriptor";
return ConfigurationMetadataParser.parse("null", serverDescriptor.getResourceConfiguration()); } @@ -165,7 +165,8 @@ public abstract class AbstractIntegrationTest { List<ServiceDescriptor> services = pluginDescriptor.getServices();
ServiceDescriptor serviceDescriptor = findService(serviceName, services); - assert serviceDescriptor != null : "Service descriptor for service [" + serviceName + "] not found in plugin descriptor"; + assert serviceDescriptor != null : "Service descriptor for service [" + serviceName + + "] not found in plugin descriptor";
return ConfigurationMetadataParser.parse("null", serviceDescriptor.getResourceConfiguration()); }
rhq-commits@lists.fedorahosted.org