org.commonjava.tensor.maven.plugin.LogProjectBuildroot.java Source code

Java tutorial

Introduction

Here is the source code for org.commonjava.tensor.maven.plugin.LogProjectBuildroot.java

Source

package org.commonjava.tensor.maven.plugin;

/*
 * Copyright 2001-2005 The Apache Software Foundation.
 *
 * 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.
 */

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.List;

import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.MavenProject;
import org.commonjava.maven.atlas.common.ref.ProjectVersionRef;
import org.commonjava.maven.atlas.effective.EGraphManager;
import org.commonjava.maven.atlas.spi.jung.effective.JungEGraphDriver;
import org.commonjava.tensor.data.GraphWorkspaceHolder;
import org.commonjava.tensor.dto.ModuleAssociations;
import org.commonjava.tensor.inject.TensorSerializerProvider;
import org.commonjava.web.json.ser.JsonSerializer;

@Mojo(name = "touch", defaultPhase = LifecyclePhase.PROCESS_SOURCES, requiresDependencyResolution = ResolutionScope.TEST)
public class LogProjectBuildroot extends AbstractMojo {
    @Parameter(defaultValue = "${project}", required = true, readonly = true)
    private MavenProject project;

    @Parameter(defaultValue = "${project.basedir}", required = true, readonly = true)
    private File basedir;

    @Parameter(defaultValue = "${reactorProjects}", required = true, readonly = true)
    private List<MavenProject> projects;

    @Parameter(defaultValue = "${session}", required = true, readonly = true)
    private MavenSession session;

    @Parameter(defaultValue = "http://locahost:9080/aprox/api/1.0/rel", required = true, property = "tensor.url")
    private String tensorBaseUrl;

    @Parameter(defaultValue = "metadata/module-associations", required = true, property = "tensor.endpoint")
    private String tensorEndpoint;

    @Override
    public void execute() throws MojoExecutionException {
        if (isThisTheExecutionRoot()) {
            final ModuleAssociations moduleAssoc = new ModuleAssociations(
                    new ProjectVersionRef(project.getGroupId(), project.getArtifactId(), project.getVersion()));
            for (final MavenProject p : projects) {
                moduleAssoc.addModule(new ProjectVersionRef(p.getGroupId(), p.getArtifactId(), p.getVersion()));
            }

            final TensorSerializerProvider prov = new TensorSerializerProvider(
                    new EGraphManager(new JungEGraphDriver()), new GraphWorkspaceHolder());

            final JsonSerializer serializer = prov.getTensorSerializer();

            final String json = serializer.toString(moduleAssoc);
            final DefaultHttpClient client = new DefaultHttpClient();

            try {
                final HttpPut request = new HttpPut(getUrl());
                request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
                request.setEntity(new StringEntity(json));

                final HttpResponse response = client.execute(request);

                final StatusLine sl = response.getStatusLine();
                if (sl.getStatusCode() != HttpStatus.SC_CREATED) {
                    throw new MojoExecutionException("Failed to publish module-artifact association data: "
                            + sl.getStatusCode() + " " + sl.getReasonPhrase());
                }
            } catch (final UnsupportedEncodingException e) {
                throw new MojoExecutionException(
                        "Failed to publish module-artifact association data; invalid encoding for JSON: "
                                + e.getMessage(),
                        e);
            } catch (final ClientProtocolException e) {
                throw new MojoExecutionException(
                        "Failed to publish module-artifact association data; http request failed: "
                                + e.getMessage(),
                        e);
            } catch (final IOException e) {
                throw new MojoExecutionException(
                        "Failed to publish module-artifact association data; http request failed: "
                                + e.getMessage(),
                        e);
            }
        }
    }

    private URI getUrl() throws MojoExecutionException {
        final StringBuilder sb = new StringBuilder(tensorBaseUrl);
        if (!tensorBaseUrl.endsWith("/")) {
            sb.append("/");
        }

        sb.append(tensorEndpoint);

        try {
            return new URL(sb.toString()).toURI();
        } catch (final MalformedURLException e) {
            throw new MojoExecutionException(
                    "Failed to publish module-artifact association data; invalid URL: " + sb, e);
        } catch (final URISyntaxException e) {
            throw new MojoExecutionException(
                    "Failed to publish module-artifact association data; invalid URL: " + sb, e);
        }
    }

    /*
     * Copied from maven-assembly-plugin-2.3.
     */
    protected boolean isThisTheExecutionRoot() {
        final Log log = getLog();
        log.debug("Root Folder:" + session.getExecutionRootDirectory());
        log.debug("Current Folder:" + basedir);
        final boolean result = session.getExecutionRootDirectory().equalsIgnoreCase(basedir.toString());
        if (result) {
            log.debug("This is the execution root.");
        } else {
            log.debug("This is NOT the execution root.");
        }

        return result;
    }
}