Java tutorial
/* * Copyright 2012 SixSq Sarl * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sixsq.slipstream; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.logging.Log; import org.apache.maven.project.MavenProject; import org.apache.maven.project.MavenProjectHelper; import org.apache.maven.settings.Server; import org.apache.maven.settings.Settings; /** * runs the specified deployment modules(s), adding the reports as project * artifacts * * @goal run-deployment * @requiresOnline true * @phase integration-test * */ public class SlipStreamMojo extends AbstractMojo { private static final int MILLIS_PER_SECOND = 1000; /** * @parameter default-value="${project}" * @required * @readonly */ private MavenProject project; /** * @component * @readonly */ private MavenProjectHelper projectHelper; /** * @parameter default-value="${settings}" * @readonly */ private Settings settings; /** * @parameter default-value="${project.build.directory}" * @readonly */ private String targetDirectory; /** * SlipStream server ID used in the settings.xml file. This cannot be empty * or null. The user's username and password must be available from the * settings.xml file for this server ID. * * @parameter default-value="slipstream" * @required */ private String slipstreamServerId; /** * Root URL for the SlipStream server * * @parameter * @required * */ private URL slipstreamServerUrl; /** * Name(s) of the deployment modules to run. If multiple modules are * supplied, they will be run sequentially. * * @parameter * @required */ private List<String> deploymentModuleNames; /** * Poll interval (in seconds) for checking the deployment status * * @parameter default-value="15" * @required */ private long pollIntervalInSeconds; // SlipStream server information extracted from the settings.xml file. private Server server; // SlipStream URL transformed into an URI. Maven won't do this // automatically. private URI slipstreamServerUri; public void execute() throws MojoExecutionException { Log log = getLog(); fillInAndValidateParameters(); DeploymentController controller = new DeploymentController(slipstreamServerUri, server.getUsername(), server.getPassword()); // Ensure that the output directory exists. File outputDirectory = new File(targetDirectory); if (!outputDirectory.mkdirs()) { log.error(String.format("unable to create output directory: %s", outputDirectory.getAbsolutePath())); } try { controller.checkServerResponds(); controller.login(); controller.checkLogin(); for (String module : deploymentModuleNames) { try { controller.verifyModuleExists(module); log.info(String.format("Module: %s", module)); URI runUri = controller.runModule(module); log.info(String.format("Run URI: %s", runUri.toString())); pollServerUntilDone(log, runUri, controller); List<URI> reportUris = controller.getReports(runUri); List<File> localFiles = new ArrayList<File>(); for (URI uri : reportUris) { File localFile = controller.downloadFile(uri, outputDirectory); localFiles.add(localFile); } attachArtifacts(log, localFiles); } catch (MojoExecutionException e) { log.warn(String.format("Error while running module %s: %s", module, e.getMessage())); } } } finally { closeReliably(controller, log); } } private void pollServerUntilDone(Log log, URI runUri, DeploymentController controller) throws MojoExecutionException { while (true) { String[] response = controller.getRunStatus(runUri); log.info(String.format("state=%s, status=%s", response[0], response[1])); if (isTerminalState(response[0])) { break; } try { long millis = pollIntervalInSeconds * MILLIS_PER_SECOND; Thread.sleep(millis); } catch (InterruptedException consumed) { } } } private void fillInAndValidateParameters() throws MojoExecutionException { server = settings.getServer(slipstreamServerId); if (server == null) { throw new MojoExecutionException( "cannot find entry server entry with ID=" + slipstreamServerId + " in settings.xml file"); } try { slipstreamServerUri = slipstreamServerUrl.toURI(); } catch (URISyntaxException e) { throw new MojoExecutionException("invalid URI given for slipstreamServerUrl", e); } if (pollIntervalInSeconds <= 0) { throw new MojoExecutionException("pollIntervalInSeconds must be a positive long value"); } } private boolean isTerminalState(String state) { return state.startsWith("Terminal"); } private String getFileExtension(File file) { String name = file.getName(); int index = name.lastIndexOf('.'); if (index > 0) { return name.substring(index + 1); } else { return "txt"; } } private String getFileClassifier(File file) { String name = file.getName(); int index = name.indexOf("_report"); if (index > 0) { return name.substring(0, index); } else { return name; } } private void attachArtifacts(Log log, List<File> files) { for (File file : files) { String type = getFileExtension(file); String classifier = getFileClassifier(file); projectHelper.attachArtifact(project, type, classifier, file); String fmt = "Attached artifact: %s with classifier=%s and type=%s"; String msg = String.format(fmt, file.getAbsolutePath(), classifier, type); log.info(msg); } } private void closeReliably(Closeable closeable, Log log) { if (closeable != null) { try { closeable.close(); } catch (IOException e) { log.warn("error closing HTTP client", e); } } } }