Removing BUCK files and other Buck-related auxiliaries.
Change-Id: I23691380efcd9bce4906695605214ed59ada0e87
diff --git a/tools/build/bazel/generate_workspace.bzl b/tools/build/bazel/generate_workspace.bzl
index 8be53fe..057ab80 100644
--- a/tools/build/bazel/generate_workspace.bzl
+++ b/tools/build/bazel/generate_workspace.bzl
@@ -1,4 +1,4 @@
-# ***** This file was auto-generated at Tue, 23 Oct 2018 17:46:21 GMT. Do not edit this file manually. *****
+# ***** This file was auto-generated at Wed, 24 Oct 2018 19:26:57 GMT. Do not edit this file manually. *****
# ***** Use onos-lib-gen *****
load("//tools/build/bazel:variables.bzl", "ONOS_GROUP_ID", "ONOS_VERSION")
@@ -1015,9 +1015,9 @@
if "apache_karaf" not in native.existing_rules():
java_import_external(
name = "apache_karaf",
- jar_sha256 = "ec317bf64c60d81fb17b666fb1c44496e138b8b2e2ffc094e1bae5eedaa9acaa",
+ jar_sha256 = "2c43a844046ea7accbe4e673838b855d438c3f9077e6a900875b267c8c1cd92c",
licenses = ["notice"],
- jar_urls = ["http://repo1.maven.org/maven2/org/onosproject/apache-karaf-offline/4.2.1-base/apache-karaf-offline-4.2.1-base.tar.gz"], )
+ jar_urls = ["http://repo1.maven.org/maven2/org/onosproject/apache-karaf-offline/4.2.1-20181024/apache-karaf-offline-4.2.1-20181024.tar.gz"], )
if "bndlib" not in native.existing_rules():
java_import_external(
name = "bndlib",
@@ -1566,7 +1566,7 @@
artifact_map["@typesafe_config//:typesafe_config"] = "mvn:com.typesafe:config:jar:1.3.2"
artifact_map["@validation_api//:validation_api"] = "mvn:javax.validation:validation-api:jar:1.1.0.Final"
artifact_map["@checkstyle//:checkstyle"] = "mvn:com.puppycrawl.tools:checkstyle:jar:NON-OSGI:8.10"
-artifact_map["@apache_karaf//:apache_karaf"] = "http://repo1.maven.org/maven2/org/onosproject/apache-karaf-offline/4.2.1-base/apache-karaf-offline-4.2.1-base.tar.gz"
+artifact_map["@apache_karaf//:apache_karaf"] = "http://repo1.maven.org/maven2/org/onosproject/apache-karaf-offline/4.2.1-20181024/apache-karaf-offline-4.2.1-20181024.tar.gz"
artifact_map["@bndlib//:bndlib"] = "mvn:biz.aQute.bnd:biz.aQute.bndlib:jar:4.0.0"
artifact_map["@bndexe//:bndexe"] = "mvn:biz.aQute.bnd:biz.aQute.bnd:jar:4.0.0"
artifact_map["@libthrift//:libthrift"] = "mvn:org.apache.thrift:libthrift:jar:0.11.0"
diff --git a/tools/build/bazel/osgi_java_library.bzl b/tools/build/bazel/osgi_java_library.bzl
index b3497c2..e5065f7 100644
--- a/tools/build/bazel/osgi_java_library.bzl
+++ b/tools/build/bazel/osgi_java_library.bzl
@@ -320,7 +320,7 @@
executable = True,
cfg = "host",
allow_files = True,
- default = Label("//tools/build/buck-plugin:swagger_generator"),
+ default = Label("//tools/build/swagger:swagger_generator"),
),
"swagger_java": attr.output(),
},
@@ -344,7 +344,7 @@
executable = True,
cfg = "host",
allow_files = True,
- default = Label("//tools/build/buck-plugin:swagger_generator"),
+ default = Label("//tools/build/swagger:swagger_generator"),
),
"swagger_json": attr.output(),
},
diff --git a/tools/build/buck-plugin/BUCK b/tools/build/buck-plugin/BUCK
deleted file mode 100644
index 8593941..0000000
--- a/tools/build/buck-plugin/BUCK
+++ /dev/null
@@ -1,46 +0,0 @@
-# Comment the remote_jar out for local buck development
-remote_jar (
- name = 'buck-api',
- out = 'buck.jar',
- url = 'https://oss.sonatype.org/content/repositories/snapshots/org/onosproject/buck-api/0.1-SNAPSHOT/buck-api-0.1-20161113.012708-6.jar',
- sha1 = 'da823563b03964eafc9ff76cd721b9253ae473a1',
- visibility = [],
-)
-
-# Uncomment the prebuilt_jar and copy buck-api to lib/buck.jar for local buck development
-# prebuilt_jar (
-# name = 'buck-api',
-# binary_jar = 'lib/buck.jar'
-# )
-
-# Use buck's guava version - 19.0
-remote_jar (
- name = 'guava',
- out = 'guava-19.0.jar',
- url = 'mvn:com.google.guava:guava:jar:19.0',
- sha1 = '6ce200f6b23222af3d8abb6b6459e6c44f4bb0e9',
- maven_coords = 'com.google.guava:guava:19.0',
-)
-
-COMPILE = [
- '//lib:qdox',
- ':guava',
- '//lib:bndlib',
- '//lib:org.apache.felix.scr.bnd'
-]
-
-java_library(
- name = 'lib',
- srcs = glob(['src/main/java/**/*.java']),
- resources = glob(['src/main/resources/**/*']),
- resources_root = 'src/main/resources',
- deps = COMPILE,
- provided_deps = [':buck-api'],
- visibility = [],
-)
-
-java_binary(
- name = 'onos',
- deps = [':lib'],
- visibility = ['PUBLIC'],
-)
diff --git a/tools/build/buck-plugin/buck-plugin-install b/tools/build/buck-plugin/buck-plugin-install
deleted file mode 100755
index 15cf0e6..0000000
--- a/tools/build/buck-plugin/buck-plugin-install
+++ /dev/null
@@ -1,14 +0,0 @@
-#!/bin/bash
-
-PLUGINS=$ONOS_ROOT/bin/plugins
-
-set -e
-
-# Build it first
-pluginJar=$(NO_BUCKD=1 onos-buck build //tools/build/buck-plugin:onos --no-cache --show-output | grep onos.jar | cut -d\ -f2)
-
-# Then install it
-mkdir -p $PLUGINS
-cp $ONOS_ROOT/$pluginJar $PLUGINS
-
-ls -l $PLUGINS
diff --git a/tools/build/buck-plugin/buck-plugin-test b/tools/build/buck-plugin/buck-plugin-test
deleted file mode 100755
index cb8fd76..0000000
--- a/tools/build/buck-plugin/buck-plugin-test
+++ /dev/null
@@ -1,3 +0,0 @@
-#!/bin/bash
-
-NO_BUCKD=1 onos-buck build //apps/dhcp/app:onos-apps-dhcp-app --no-cache --show-output
diff --git a/tools/build/buck-plugin/src/main/java/org/onosproject/onosjar/OSGiWrapper.java b/tools/build/buck-plugin/src/main/java/org/onosproject/onosjar/OSGiWrapper.java
deleted file mode 100644
index 86c6938..0000000
--- a/tools/build/buck-plugin/src/main/java/org/onosproject/onosjar/OSGiWrapper.java
+++ /dev/null
@@ -1,496 +0,0 @@
-/*
- * Copyright 2016-present Open Networking 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.
- */
-
-package org.onosproject.onosjar;
-
-import aQute.bnd.header.Attrs;
-import aQute.bnd.header.Parameters;
-import aQute.bnd.osgi.Analyzer;
-import aQute.bnd.osgi.Builder;
-import aQute.bnd.osgi.Constants;
-import aQute.bnd.osgi.Descriptors;
-import aQute.bnd.osgi.FileResource;
-import aQute.bnd.osgi.Jar;
-import aQute.bnd.osgi.Packages;
-import aQute.bnd.osgi.Processor;
-import aQute.bnd.osgi.Resource;
-import com.facebook.buck.step.ExecutionContext;
-import com.facebook.buck.step.Step;
-import com.facebook.buck.step.StepExecutionResult;
-import com.google.common.base.MoreObjects;
-import com.google.common.base.Strings;
-import com.google.common.collect.ImmutableSortedSet;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-import com.google.common.collect.Sets;
-import org.apache.felix.scrplugin.bnd.SCRDescriptorBndPlugin;
-import org.codehaus.plexus.util.DirectoryScanner;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.PrintStream;
-import java.nio.file.FileVisitResult;
-import java.nio.file.FileVisitor;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.nio.file.SimpleFileVisitor;
-import java.nio.file.attribute.BasicFileAttributes;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Set;
-import java.util.jar.Manifest;
-import java.util.stream.Collectors;
-
-import static java.nio.file.Files.walkFileTree;
-
-/**
- * BND-based wrapper to convert Buck JARs to OSGi-compatible JARs.
- */
-public class OSGiWrapper implements Step {
-
- private static final String EMBED_DEPENDENCY = "Embed-Dependency";
- private static final String EMBEDDED_ARTIFACTS = "Embedded-Artifacts";
-
- private Path inputJar;
- private Path outputJar;
- private Path sourcesDir;
- private Path classesDir;
- private List<String> classpath;
-
- private String bundleName;
- private String groupId;
- private String bundleSymbolicName;
- private String bundleVersion;
-
- private String importPackages;
- private String privatePackages;
- private String dynamicimportPackages;
- private String embeddedDependencies;
-
- private String exportPackages;
- private String includeResources;
- private Set<String> includedResources = Sets.newHashSet();
-
- private String bundleDescription;
- private String bundleLicense;
-
- private String bundleClasspath;
-
- private String webContext;
-
- private PrintStream stderr = System.err;
-
- public OSGiWrapper(Path inputJar,
- Path outputJar,
- Path sourcesDir,
- Path classesDir,
- ImmutableSortedSet<Path> classpath,
- String bundleName,
- String groupId,
- String bundleVersion,
- String bundleLicense,
- String importPackages,
- String exportPackages,
- String includeResources,
- String webContext,
- String dynamicimportPackages,
- String embeddedDependencies,
- String bundleDescription,
- String privatePackages,
- String bundleClasspath) {
- this.inputJar = inputJar;
- this.sourcesDir = sourcesDir;
- this.classesDir = classesDir;
- this.classpath = Lists.newArrayList(
- classpath.stream().map(Path::toString).collect(Collectors.toList()));
- if (!this.classpath.contains(inputJar.toString())) {
- this.classpath.add(0, inputJar.toString());
- }
- this.outputJar = outputJar;
-
- this.bundleName = bundleName;
- this.groupId = groupId;
- this.bundleSymbolicName = String.format("%s.%s", groupId, bundleName);
-
- this.bundleVersion = bundleVersion;
- this.bundleLicense = bundleLicense;
- this.bundleDescription = bundleDescription;
-
- this.importPackages = importPackages;
- this.privatePackages = privatePackages;
- this.dynamicimportPackages = dynamicimportPackages;
- this.embeddedDependencies = embeddedDependencies;
- this.exportPackages = exportPackages;
- this.includeResources = includeResources;
-
- this.webContext = webContext;
-
- this.bundleClasspath = bundleClasspath;
- }
-
- private void setProperties(Analyzer analyzer) {
-
- analyzer.setProperty(Analyzer.BUNDLE_NAME, bundleName);
- analyzer.setProperty(Analyzer.BUNDLE_SYMBOLICNAME, bundleSymbolicName);
- analyzer.setProperty(Analyzer.BUNDLE_VERSION, bundleVersion.replace('-', '.'));
-
- if (bundleDescription != null) {
- analyzer.setProperty(Analyzer.BUNDLE_DESCRIPTION, bundleDescription);
- }
- if (bundleLicense != null) {
- analyzer.setProperty(Analyzer.BUNDLE_LICENSE, bundleLicense);
- }
-
- //TODO consider using stricter version policy
- //analyzer.setProperty("-provider-policy", "${range;[===,==+)}");
- //analyzer.setProperty("-consumer-policy", "${range;[===,==+)}");
-
- if (privatePackages != null) {
- analyzer.setProperty(Analyzer.PRIVATE_PACKAGE, privatePackages);
- }
- analyzer.setProperty(Analyzer.REMOVEHEADERS, "Private-Package,Include-Resource");
-
- analyzer.setProperty(Analyzer.DYNAMICIMPORT_PACKAGE,
- dynamicimportPackages);
-
- // TODO include version in export, but not in import
- analyzer.setProperty(Analyzer.EXPORT_PACKAGE, exportPackages);
-
- // TODO we may need INCLUDE_RESOURCE, or that might be done by Buck
- // FIXME NOTE we handle this manually below
- if (includeResources != null) {
- analyzer.setProperty(Analyzer.INCLUDE_RESOURCE, includeResources);
- }
-
- if (embeddedDependencies != null) {
- analyzer.setProperty(EMBED_DEPENDENCY, embeddedDependencies);
- }
-
- // There are no good defaults so make sure you set the Import-Package
- analyzer.setProperty(Analyzer.IMPORT_PACKAGE, importPackages);
-
- if (isWab()) {
- analyzer.setProperty(Analyzer.WAB, "src/main/webapp/");
- analyzer.setProperty("Web-ContextPath", webContext);
- analyzer.setProperty(Analyzer.IMPORT_PACKAGE, importPackages +
- ",org.glassfish.jersey.servlet,org.jvnet.mimepull\n");
- }
- }
-
- public boolean execute() {
- Builder analyzer = new Builder();
- try {
-
- Jar jar = new Jar(inputJar.toFile()); // where our data is
- analyzer.setJar(jar); // give bnd the contents
-
- // You can provide additional class path entries to allow
- // bnd to pickup export version from the packageinfo file,
- // Version annotation, or their manifests.
- analyzer.addClasspath(classpath);
-
- setProperties(analyzer);
-
- // Analyze the target JAR first
- analyzer.analyze();
-
- // Scan the JAR for Felix SCR annotations and generate XML files
- Map<String, String> properties = Maps.newHashMap();
- properties.put("destdir", classesDir.toAbsolutePath().toString());
- SCRDescriptorBndPlugin scrDescriptorBndPlugin = new SCRDescriptorBndPlugin();
- scrDescriptorBndPlugin.setProperties(properties);
- scrDescriptorBndPlugin.setReporter(analyzer);
- scrDescriptorBndPlugin.analyzeJar(analyzer);
-
- //Add local packges to jar file.
- //FIXME removing this call for now; not sure what exactly it's doing
- //addLocalPackages(new File(classesDir.toString()), analyzer);
-
- //add resources.
- if (includeResources != null || embeddedDependencies != null) {
- doIncludeResources(analyzer);
- }
-
- // Repack the JAR as a WAR
- doWabStaging(analyzer);
-
- // Calculate the manifest
- Manifest manifest = analyzer.calcManifest();
-
- //Build the jar files
- //FIXME this call conflicts with some of the above
-// analyzer.build();
-
- if (analyzer.isOk()) {
- //add calculated manifest file.
- analyzer.getJar().setManifest(manifest);
- if (analyzer.save(outputJar.toFile(), true)) {
- log("Saved!\n");
- } else {
- warn("Failed to create jar \n");
- return false;
- }
- } else {
- warn("Analyzer Errors:\n%s\n", analyzer.getErrors());
- return false;
- }
-
- analyzer.close();
-
- return true;
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- }
- }
-
- private static void addLocalPackages(File outputDirectory, Analyzer analyzer) throws IOException {
- Packages packages = new Packages();
-
- if (outputDirectory != null && outputDirectory.isDirectory()) {
- // scan classes directory for potential packages
- DirectoryScanner scanner = new DirectoryScanner();
- scanner.setBasedir(outputDirectory);
- scanner.setIncludes(new String[]
- {"**/*.class"});
-
- scanner.addDefaultExcludes();
- scanner.scan();
-
- String[] paths = scanner.getIncludedFiles();
- for (int i = 0; i < paths.length; i++) {
- packages.put(analyzer.getPackageRef(getPackageName(paths[i])));
- }
- }
-
- Packages exportedPkgs = new Packages();
- Packages privatePkgs = new Packages();
-
- boolean noprivatePackages = "!*".equals(analyzer.getProperty(Analyzer.PRIVATE_PACKAGE));
-
- for (Descriptors.PackageRef pkg : packages.keySet()) {
- // mark all source packages as private by default (can be overridden by export list)
- privatePkgs.put(pkg);
-
- // we can't export the default package (".") and we shouldn't export internal packages
- String fqn = pkg.getFQN();
- if (noprivatePackages || !(".".equals(fqn) || fqn.contains(".internal") || fqn.contains(".impl"))) {
- exportedPkgs.put(pkg);
- }
- }
-
- Properties properties = analyzer.getProperties();
- String exported = properties.getProperty(Analyzer.EXPORT_PACKAGE);
- if (exported == null) {
- if (!properties.containsKey(Analyzer.EXPORT_CONTENTS)) {
- // no -exportcontents overriding the exports, so use our computed list
- for (Attrs attrs : exportedPkgs.values()) {
- attrs.put(Constants.SPLIT_PACKAGE_DIRECTIVE, "merge-first");
- }
- properties.setProperty(Analyzer.EXPORT_PACKAGE, Processor.printClauses(exportedPkgs));
- } else {
- // leave Export-Package empty (but non-null) as we have -exportcontents
- properties.setProperty(Analyzer.EXPORT_PACKAGE, "");
- }
- }
-
- String internal = properties.getProperty(Analyzer.PRIVATE_PACKAGE);
- if (internal == null) {
- if (!privatePkgs.isEmpty()) {
- for (Attrs attrs : privatePkgs.values()) {
- attrs.put(Constants.SPLIT_PACKAGE_DIRECTIVE, "merge-first");
- }
- properties.setProperty(Analyzer.PRIVATE_PACKAGE, Processor.printClauses(privatePkgs));
- } else {
- // if there are really no private packages then use "!*" as this will keep the Bnd Tool happy
- properties.setProperty(Analyzer.PRIVATE_PACKAGE, "!*");
- }
- }
- }
-
- private static String getPackageName(String filename) {
- int n = filename.lastIndexOf(File.separatorChar);
- return n < 0 ? "." : filename.substring(0, n).replace(File.separatorChar, '.');
- }
-
- private boolean isWab() {
- return webContext != null;
- }
-
- private void doWabStaging(Analyzer analyzer) throws Exception {
- if (!isWab()) {
- return;
- }
- String wab = analyzer.getProperty(analyzer.WAB);
- Jar dot = analyzer.getJar();
-
- log("wab %s", wab);
-
- if (bundleClasspath != null) {
- analyzer.setBundleClasspath("WEB-INF/classes," + bundleClasspath);
- }
-
- Set<String> paths = new HashSet<>(dot.getResources().keySet());
-
- for (String path : paths) {
- if (path.indexOf('/') > 0 && !Character.isUpperCase(path.charAt(0))) {
- log("wab: moving: %s", path);
- dot.rename(path, "WEB-INF/classes/" + path);
- }
- }
-
- Path wabRoot = Paths.get(wab);
- includeFiles(dot, null, wabRoot.toString());
- }
-
- /**
- * Parse the Bundle-Includes header. Files in the bundles Include header are
- * included in the jar. The source can be a directory or a file.
- *
- * @throws Exception
- */
- private void doIncludeResources(Analyzer analyzer) throws Exception {
- String includes = analyzer.getProperty(Analyzer.INCLUDE_RESOURCE);
- if (includes == null) {
- return;
- }
- Parameters clauses = analyzer.parseHeader(includes);
- Jar jar = analyzer.getJar();
-
- for (Map.Entry<String, Attrs> entry : clauses.entrySet()) {
- String name = entry.getKey();
- Map<String, String> extra = entry.getValue();
- // TODO consider doing something with extras
-
- String[] parts = name.split("\\s*=\\s*");
- String source = parts[0];
- String destination = parts[0];
- if (parts.length == 2) {
- source = parts[1];
- }
-
- includeFiles(jar, destination, source);
- }
- }
-
- private void includeFiles(Jar jar, String destinationRoot, String sourceRoot)
- throws IOException {
-
- Path classesBasedPath = classesDir.resolve(sourceRoot);
- Path sourceBasedPath = sourcesDir.resolve(sourceRoot);
-
- File classFile = classesBasedPath.toFile();
- File sourceFile = sourceBasedPath.toFile();
-
- if (classFile.isFile()) {
- addFileToJar(jar, destinationRoot, classesBasedPath.toAbsolutePath().toString());
- } else if (sourceFile.isFile()) {
- addFileToJar(jar, destinationRoot, sourceBasedPath.toAbsolutePath().toString());
- } else if (classFile.isDirectory()) {
- includeDirectory(jar, destinationRoot, classesBasedPath);
- } else if (sourceFile.isDirectory()) {
- includeDirectory(jar, destinationRoot, sourceBasedPath);
- } else {
- warn("Skipping resource in bundle %s: %s (File Not Found)\n",
- bundleSymbolicName, sourceRoot);
- }
- }
-
- private void includeDirectory(Jar jar, String destinationRoot, Path sourceRoot)
- throws IOException {
- // iterate through sources
- // put each source on the jar
- FileVisitor<Path> visitor = new SimpleFileVisitor<Path>() {
- @Override
- public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
- Path relativePath = sourceRoot.relativize(file);
- String destination = destinationRoot != null ?
- destinationRoot + "/" + relativePath.toString() : //TODO
- relativePath.toString();
-
- addFileToJar(jar, destination, file.toAbsolutePath().toString());
- return FileVisitResult.CONTINUE;
- }
- };
-
- walkFileTree(sourceRoot, visitor);
- }
-
- private boolean addFileToJar(Jar jar, String destination, String sourceAbsPath) {
- if (includedResources.contains(sourceAbsPath)) {
- log("Skipping already included resource: %s\n", sourceAbsPath);
- return false;
- }
- File file = new File(sourceAbsPath);
- if (!file.isFile()) {
- throw new RuntimeException(
- String.format("Skipping non-existent file: %s\n", sourceAbsPath));
- }
- Resource resource = new FileResource(file);
- if (jar.getResource(destination) != null) {
- warn("Skipping duplicate resource: %s\n", destination);
- return false;
- }
- jar.putResource(destination, resource);
- includedResources.add(sourceAbsPath);
- log("Adding resource: %s\n", destination);
- return true;
- }
-
- private void log(String format, Object... objects) {
- //System.err.printf(format, objects);
- }
-
- private void warn(String format, Object... objects) {
- stderr.printf(format, objects);
- }
-
- @Override
- public String toString() {
- return MoreObjects.toStringHelper(this)
- .add("inputJar", inputJar)
- .add("outputJar", outputJar)
- .add("classpath", classpath)
- .add("bundleName", bundleName)
- .add("groupId", groupId)
- .add("bundleSymbolicName", bundleSymbolicName)
- .add("bundleVersion", bundleVersion)
- .add("bundleDescription", bundleDescription)
- .add("bundleLicense", bundleLicense)
- .toString();
- }
-
- @Override
- public StepExecutionResult execute(ExecutionContext executionContext)
- throws IOException, InterruptedException {
- stderr = executionContext.getStdErr();
- boolean success = execute();
- stderr = System.err;
- return success ? StepExecutionResult.SUCCESS : StepExecutionResult.ERROR;
- }
-
- @Override
- public String getShortName() {
- return "osgiwrap";
- }
-
- @Override
- public String getDescription(ExecutionContext executionContext) {
- return "osgiwrap"; //FIXME
- }
-}
diff --git a/tools/build/buck-plugin/src/main/java/org/onosproject/onosjar/OnosJar.java b/tools/build/buck-plugin/src/main/java/org/onosproject/onosjar/OnosJar.java
deleted file mode 100644
index b9ec3d6..0000000
--- a/tools/build/buck-plugin/src/main/java/org/onosproject/onosjar/OnosJar.java
+++ /dev/null
@@ -1,159 +0,0 @@
-/*
- * Copyright 2016-present Open Networking 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.
- */
-package org.onosproject.onosjar;
-
-import com.facebook.buck.jvm.java.CompileToJarStepFactory;
-import com.facebook.buck.jvm.java.DefaultJavaLibrary;
-import com.facebook.buck.jvm.java.HasMavenCoordinates;
-import com.facebook.buck.jvm.java.JavaLibrary;
-import com.facebook.buck.jvm.java.MavenPublishable;
-import com.facebook.buck.model.BuildTarget;
-import com.facebook.buck.rules.AddToRuleKey;
-import com.facebook.buck.rules.BuildRule;
-import com.facebook.buck.rules.BuildRuleParams;
-import com.facebook.buck.rules.SourcePath;
-import com.facebook.buck.rules.SourcePathResolver;
-import com.google.common.base.Optional;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.ImmutableSortedMap;
-import com.google.common.collect.ImmutableSortedSet;
-
-import java.io.IOException;
-import java.math.BigInteger;
-import java.net.URL;
-import java.nio.file.Path;
-import java.security.DigestInputStream;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import java.util.Set;
-import java.util.regex.Pattern;
-
-/**
- * Implementation of a build rule that generates a onosjar.json file for a set
- * of Java sources.
- */
-public class OnosJar extends DefaultJavaLibrary
- implements MavenPublishable{
-
- // Inject the SHA of this rule's jar into the rule key
- private static String RULE_VERSION;
- static {
- URL pluginJarLocation = OnosJar.class.getProtectionDomain().getCodeSource().getLocation();
- try {
- MessageDigest md = MessageDigest.getInstance("SHA");
- DigestInputStream dis = new DigestInputStream(pluginJarLocation.openStream(), md);
- // Consume the InputStream...
- while (dis.read() != -1);
- RULE_VERSION = String.format("%032x", new BigInteger(1, md.digest()));
- } catch (NoSuchAlgorithmException | IOException e) {
- System.err.println("Failed to compute hash for OnosJar rule");
- RULE_VERSION = "nil";
- //TODO consider bailing here instead
- }
- }
- @AddToRuleKey
- private final String ruleVersion = RULE_VERSION;
-
- @AddToRuleKey
- final Optional<String> webContext;
-
- @AddToRuleKey
- final Optional<String> apiTitle;
-
- @AddToRuleKey
- final Optional<String> apiVersion;
-
- @AddToRuleKey
- final Optional<String> apiPackage;
-
- @AddToRuleKey
- final Optional<String> apiDescription;
-
- @AddToRuleKey
- final Optional<ImmutableSortedMap<String, SourcePath>> includedResources;
-
- private final ImmutableSortedSet<HasMavenCoordinates> mavenDeps;
-
- public OnosJar(BuildRuleParams params,
- SourcePathResolver resolver,
- Set<? extends SourcePath> srcs,
- Set<? extends SourcePath> resources,
- Optional<Path> generatedSourceFolder,
- Optional<SourcePath> proguardConfig,
- ImmutableList<String> postprocessClassesCommands,
- ImmutableSortedSet<BuildRule> exportedDeps,
- ImmutableSortedSet<BuildRule> providedDeps,
- SourcePath abiJar, boolean trackClassUsage,
- ImmutableSet<Path> additionalClasspathEntries,
- CompileToJarStepFactory compileStepFactory,
- Optional<Path> resourcesRoot,
- Optional<SourcePath> manifestFile,
- Optional<String> mavenCoords,
- ImmutableSortedSet<BuildTarget> tests,
- ImmutableSet<Pattern> classesToRemoveFromJar,
- Optional<String> webContext,
- Optional<String> apiTitle,
- Optional<String> apiVersion,
- Optional<String> apiPackage,
- Optional<String> apiDescription,
- Optional<ImmutableSortedMap<String, SourcePath>> includedResources) {
- super(params, resolver, srcs, resources, generatedSourceFolder,
- proguardConfig, postprocessClassesCommands, exportedDeps,
- providedDeps, abiJar, trackClassUsage, additionalClasspathEntries,
- compileStepFactory, resourcesRoot, manifestFile, mavenCoords,
- tests, classesToRemoveFromJar);
- this.webContext = webContext;
- this.apiTitle = apiTitle;
- this.apiVersion = apiVersion;
- this.apiPackage = apiPackage;
- this.apiDescription = apiDescription;
- this.includedResources = includedResources;
- this.mavenDeps = computeMavenDeps();
- }
-
- private ImmutableSortedSet<HasMavenCoordinates> computeMavenDeps() {
- ImmutableSortedSet.Builder<HasMavenCoordinates> mavenDeps = ImmutableSortedSet.naturalOrder();
- for (JavaLibrary javaLibrary : getTransitiveClasspathDeps()) {
- if (this.equals(javaLibrary)) {
- // no need to include ourself
- continue;
- } else if (HasMavenCoordinates.MAVEN_COORDS_PRESENT_PREDICATE.apply(javaLibrary)) {
- mavenDeps.add(javaLibrary);
- //FIXME BOC do we always want to exclude all of a maven jar's dependencies? probably.
- mavenDeps.addAll(javaLibrary.getTransitiveClasspathDeps());
- }
- }
- return mavenDeps.build();
- }
-
- @Override
- public Iterable<HasMavenCoordinates> getMavenDeps() {
- return mavenDeps;
- }
-
- @Override
- public Iterable<BuildRule> getPackagedDependencies() {
- //FIXME this is not supported at the moment
- return ImmutableList.of();
- }
-
- @Override
- public Optional<Path> getPomTemplate() {
- //FIXME we should consider supporting this
- return Optional.absent();
- }
-}
diff --git a/tools/build/buck-plugin/src/main/java/org/onosproject/onosjar/OnosJarDescription.java b/tools/build/buck-plugin/src/main/java/org/onosproject/onosjar/OnosJarDescription.java
deleted file mode 100644
index 3f27760..0000000
--- a/tools/build/buck-plugin/src/main/java/org/onosproject/onosjar/OnosJarDescription.java
+++ /dev/null
@@ -1,335 +0,0 @@
-/*
- * Copyright 2016-present Open Networking 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.
- */
-package org.onosproject.onosjar;
-
-import com.facebook.buck.cli.BuckConfig;
-import com.facebook.buck.jvm.java.CalculateAbi;
-import com.facebook.buck.jvm.java.DefaultJavaLibrary;
-import com.facebook.buck.jvm.java.JavaBuckConfig;
-import com.facebook.buck.jvm.java.JavaLibrary;
-import com.facebook.buck.jvm.java.JavaLibraryDescription;
-import com.facebook.buck.jvm.java.JavaOptions;
-import com.facebook.buck.jvm.java.JavaSourceJar;
-import com.facebook.buck.jvm.java.JavacOptions;
-import com.facebook.buck.jvm.java.JavacOptionsAmender;
-import com.facebook.buck.jvm.java.JavacOptionsFactory;
-import com.facebook.buck.jvm.java.JavacToJarStepFactory;
-import com.facebook.buck.jvm.java.JavadocJar;
-import com.facebook.buck.jvm.java.MavenUberJar;
-import com.facebook.buck.maven.AetherUtil;
-import com.facebook.buck.model.BuildTarget;
-import com.facebook.buck.model.Flavor;
-import com.facebook.buck.model.Flavored;
-import com.facebook.buck.model.ImmutableFlavor;
-import com.facebook.buck.parser.NoSuchBuildTargetException;
-import com.facebook.buck.rules.BuildRule;
-import com.facebook.buck.rules.BuildRuleParams;
-import com.facebook.buck.rules.BuildRuleResolver;
-import com.facebook.buck.rules.BuildRuleType;
-import com.facebook.buck.rules.BuildRules;
-import com.facebook.buck.rules.BuildTargetSourcePath;
-import com.facebook.buck.rules.Description;
-import com.facebook.buck.rules.SourcePath;
-import com.facebook.buck.rules.SourcePathResolver;
-import com.facebook.buck.rules.SourcePaths;
-import com.facebook.buck.rules.TargetGraph;
-import com.google.common.base.Function;
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.ImmutableSortedMap;
-import com.google.common.collect.ImmutableSortedSet;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
-
-import java.nio.file.Path;
-import java.util.List;
-
-import static com.facebook.buck.jvm.common.ResourceValidator.validateResources;
-
-/**
- * Description for the onos_jar rules.
- *
- * Currently, this only does Swagger generation.
- */
-public class OnosJarDescription implements Description<OnosJarDescription.Arg>, Flavored {
- public static final BuildRuleType TYPE = BuildRuleType.of("onos_jar");
- public static final Flavor NON_OSGI_JAR = ImmutableFlavor.of("non-osgi");
-
- public static final ImmutableSet<Flavor> SUPPORTED_FLAVORS = ImmutableSet.of(
- JavaLibrary.SRC_JAR,
- JavaLibrary.MAVEN_JAR,
- JavaLibrary.JAVADOC_JAR,
- NON_OSGI_JAR);
-
- private final JavacOptions defaultJavacOptions;
- private final JavaOptions defaultJavaOptions;
-
- public OnosJarDescription(BuckConfig config) {
- JavaBuckConfig javaConfig = new JavaBuckConfig(config);
- defaultJavacOptions = javaConfig.getDefaultJavacOptions();
- defaultJavaOptions = javaConfig.getDefaultJavaOptions();
- }
-
- @Override
- public BuildRuleType getBuildRuleType() {
- return TYPE;
- }
-
- @Override
- public Arg createUnpopulatedConstructorArg() {
- return new Arg();
- }
-
- @Override
- public <A extends Arg> BuildRule createBuildRule(TargetGraph targetGraph,
- BuildRuleParams params,
- BuildRuleResolver resolver,
- A args)
- throws NoSuchBuildTargetException {
-
-
- SourcePathResolver pathResolver = new SourcePathResolver(resolver);
- BuildTarget target = params.getBuildTarget();
-
- // We know that the flavour we're being asked to create is valid, since the check is done when
- // creating the action graph from the target graph.
-
- ImmutableSortedSet<Flavor> flavors = target.getFlavors();
- BuildRuleParams paramsWithMavenFlavor = null;
-
- if (flavors.contains(JavaLibrary.MAVEN_JAR)) {
- paramsWithMavenFlavor = params;
-
- // Maven rules will depend upon their vanilla versions, so the latter have to be constructed
- // without the maven flavor to prevent output-path conflict
- params = params.copyWithBuildTarget(
- params.getBuildTarget().withoutFlavors(ImmutableSet.of(JavaLibrary.MAVEN_JAR)));
- }
-
- if (flavors.contains(JavaLibrary.SRC_JAR)) {
- args.mavenCoords = args.mavenCoords.transform(
- new Function<String, String>() {
- @Override
- public String apply(String input) {
- return AetherUtil.addClassifier(input, AetherUtil.CLASSIFIER_SOURCES);
- }
- });
-
- if (!flavors.contains(JavaLibrary.MAVEN_JAR)) {
- return new JavaSourceJar(
- params,
- pathResolver,
- args.srcs.get(),
- args.mavenCoords);
- } else {
- return MavenUberJar.SourceJar.create(
- Preconditions.checkNotNull(paramsWithMavenFlavor),
- pathResolver,
- args.srcs.get(),
- args.mavenCoords,
- Optional.absent()); //FIXME
- }
- }
-
- if (flavors.contains(JavaLibrary.JAVADOC_JAR)) {
- args.mavenCoords = args.mavenCoords.transform(
- new Function<String, String>() {
- @Override
- public String apply(String input) {
- return AetherUtil.addClassifier(input, AetherUtil.CLASSIFIER_JAVADOC);
- }
- });
-
- JavadocJar.JavadocArgs.Builder javadocArgs = JavadocJar.JavadocArgs.builder()
- .addArg("-windowtitle", target.getShortName())
- .addArg("-link", "http://docs.oracle.com/javase/8/docs/api")
- .addArg("-tag", "onos.rsModel:a:\"onos model\""); //FIXME from buckconfig + rule
-
- final ImmutableSortedMap.Builder<SourcePath, Path> javadocFiles = ImmutableSortedMap.naturalOrder();
- if (args.javadocFiles.isPresent()) {
- for (SourcePath path : args.javadocFiles.get()) {
- javadocFiles.put(path,
- JavadocJar.getDocfileWithPath(pathResolver, path, args.javadocFilesRoot.orNull()));
- }
- }
-
-
- if (!flavors.contains(JavaLibrary.MAVEN_JAR)) {
- return new JavadocJar(
- params,
- pathResolver,
- args.srcs.get(),
- javadocFiles.build(),
- javadocArgs.build(),
- args.mavenCoords);
- } else {
- return MavenUberJar.MavenJavadocJar.create(
- Preconditions.checkNotNull(paramsWithMavenFlavor),
- pathResolver,
- args.srcs.get(),
- javadocFiles.build(),
- javadocArgs.build(),
- args.mavenCoords,
- Optional.absent()); //FIXME
- }
- }
-
- JavacOptions javacOptions = JavacOptionsFactory.create(
- defaultJavacOptions,
- params,
- resolver,
- pathResolver,
- args
- );
-
- BuildTarget abiJarTarget = params.getBuildTarget().withAppendedFlavors(CalculateAbi.FLAVOR);
-
- ImmutableSortedSet<BuildRule> exportedDeps = resolver.getAllRules(args.exportedDeps.get());
-
- // Build the resources string
- List<String> resourceMappings = Lists.newArrayList();
-
- if (args.includeResources.isPresent()) {
- args.includeResources.get().entrySet().forEach(p ->
- resourceMappings.add(String.format("%s=%s", p.getKey(), p.getValue())));
- }
-
- if (args.apiTitle.isPresent()) {
- resourceMappings.add("WEB-INF/classes/apidoc/swagger.json=swagger.json");
- }
-
- Optional<String> includedResourcesString = Optional.of(String.join(",", resourceMappings));
- final DefaultJavaLibrary defaultJavaLibrary;
- if (!flavors.contains(NON_OSGI_JAR)) {
- defaultJavaLibrary =
- resolver.addToIndex(
- new OnosJar(
- params.appendExtraDeps(
- Iterables.concat(
- BuildRules.getExportedRules(
- Iterables.concat(
- params.getDeclaredDeps().get(),
- exportedDeps,
- resolver.getAllRules(args.providedDeps.get()))),
- pathResolver.filterBuildRuleInputs(
- javacOptions.getInputs(pathResolver)))),
- pathResolver,
- args.srcs.get(),
- validateResources(
- pathResolver,
- params.getProjectFilesystem(),
- args.resources.get()),
- javacOptions.getGeneratedSourceFolderName(),
- args.proguardConfig.transform(
- SourcePaths.toSourcePath(params.getProjectFilesystem())),
- args.postprocessClassesCommands.get(), // FIXME this should be forbidden
- exportedDeps,
- resolver.getAllRules(args.providedDeps.get()),
- new BuildTargetSourcePath(abiJarTarget),
- javacOptions.trackClassUsage(),
- /* additionalClasspathEntries */ ImmutableSet.<Path>of(),
- new OnosJarStepFactory(javacOptions, JavacOptionsAmender.IDENTITY,
- args.webContext, args.apiTitle, args.apiVersion,
- args.apiPackage, args.apiDescription, args.resources,
- args.groupId, args.bundleName, args.bundleVersion,
- args.bundleLicense, args.bundleDescription, args.importPackages,
- args.exportPackages, includedResourcesString,
- args.dynamicimportPackages, args.privatePackages, args.embeddedDependencies, args.bundleClasspath),
- args.resourcesRoot,
- args.manifestFile,
- args.mavenCoords,
- args.tests.get(),
- javacOptions.getClassesToRemoveFromJar(),
- args.webContext,
- args.apiTitle,
- args.apiVersion,
- args.apiPackage,
- args.apiDescription,
- args.includeResources));
- } else {
- defaultJavaLibrary =
- resolver.addToIndex(
- new DefaultJavaLibrary(
- params.appendExtraDeps(
- Iterables.concat(
- BuildRules.getExportedRules(
- Iterables.concat(
- params.getDeclaredDeps().get(),
- exportedDeps,
- resolver.getAllRules(args.providedDeps.get()))),
- pathResolver.filterBuildRuleInputs(
- javacOptions.getInputs(pathResolver)))),
- pathResolver,
- args.srcs.get(),
- validateResources(
- pathResolver,
- params.getProjectFilesystem(),
- args.resources.get()),
- javacOptions.getGeneratedSourceFolderName(),
- args.proguardConfig.transform(
- SourcePaths.toSourcePath(params.getProjectFilesystem())),
- args.postprocessClassesCommands.get(),
- exportedDeps,
- resolver.getAllRules(args.providedDeps.get()),
- new BuildTargetSourcePath(abiJarTarget),
- javacOptions.trackClassUsage(),
- /* additionalClasspathEntries */ ImmutableSet.<Path>of(),
- new JavacToJarStepFactory(javacOptions, JavacOptionsAmender.IDENTITY),
- args.resourcesRoot,
- args.manifestFile,
- args.mavenCoords,
- args.tests.get(),
- javacOptions.getClassesToRemoveFromJar()));
- }
-
- resolver.addToIndex(
- CalculateAbi.of(
- abiJarTarget,
- pathResolver,
- params,
- new BuildTargetSourcePath(defaultJavaLibrary.getBuildTarget())));
-
- return defaultJavaLibrary;
- }
-
- @Override
- public boolean hasFlavors(ImmutableSet<Flavor> flavors) {
- return SUPPORTED_FLAVORS.containsAll(flavors);
- }
-
- public static class Arg extends JavaLibraryDescription.Arg {
- public Optional<String> webContext;
- public Optional<String> apiTitle;
- public Optional<String> apiVersion;
- public Optional<String> apiPackage;
- public Optional<String> apiDescription;
-
- public Optional<String> groupId;
- public Optional<String> bundleName;
- public Optional<String> bundleVersion;
- public Optional<String> bundleLicense;
- public Optional<String> bundleDescription;
-
- public Optional<String> importPackages;
- public Optional<String> privatePackages;
- public Optional<String> exportPackages;
- public Optional<ImmutableSortedMap<String, SourcePath>> includeResources;
- public Optional<String> dynamicimportPackages;
- public Optional<String> embeddedDependencies;
- public Optional<String> bundleClasspath;
- }
-}
\ No newline at end of file
diff --git a/tools/build/buck-plugin/src/main/java/org/onosproject/onosjar/OnosJarStepFactory.java b/tools/build/buck-plugin/src/main/java/org/onosproject/onosjar/OnosJarStepFactory.java
deleted file mode 100644
index 6550d89..0000000
--- a/tools/build/buck-plugin/src/main/java/org/onosproject/onosjar/OnosJarStepFactory.java
+++ /dev/null
@@ -1,227 +0,0 @@
-/*
- * Copyright 2016-present Open Networking 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.
- */
-package org.onosproject.onosjar;
-
-import com.facebook.buck.io.ProjectFilesystem;
-import com.facebook.buck.jvm.core.SuggestBuildRules;
-import com.facebook.buck.jvm.java.ClassUsageFileWriter;
-import com.facebook.buck.jvm.java.JarDirectoryStep;
-import com.facebook.buck.jvm.java.JavacOptions;
-import com.facebook.buck.jvm.java.JavacOptionsAmender;
-import com.facebook.buck.jvm.java.JavacToJarStepFactory;
-import com.facebook.buck.model.BuildTarget;
-import com.facebook.buck.rules.BuildContext;
-import com.facebook.buck.rules.BuildableContext;
-import com.facebook.buck.rules.SourcePath;
-import com.facebook.buck.rules.SourcePathResolver;
-import com.facebook.buck.step.Step;
-import com.facebook.buck.step.fs.CopyStep;
-import com.google.common.base.Optional;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.ImmutableSortedSet;
-
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.regex.Pattern;
-import java.util.stream.Collectors;
-
-/**
- * Creates the list of build steps for the onos_jar rules.
- */
-public class OnosJarStepFactory extends JavacToJarStepFactory {
-
- private static final String DEFINITIONS = "/definitions/";
- private final String webContext;
- private final String apiTitle;
- private final String apiVersion;
- private final String apiPackage;
- private final String apiDescription;
- private final Optional<ImmutableSortedSet<SourcePath>> resources;
- private final String groupId;
- private final String bundleName;
- private final String bundleVersion;
- private final String bundleLicense;
- private final String bundleDescription;
- private final String importPackages;
- private final String privatePackages;
- private final String exportPackages;
- private final String includeResources;
- private final String dynamicimportPackages;
- private final String embeddedDependencies;
- private final String bundleClasspath;
-
- public OnosJarStepFactory(JavacOptions javacOptions,
- JavacOptionsAmender amender,
- Optional<String> webContext,
- Optional<String> apiTitle,
- Optional<String> apiVersion,
- Optional<String> apiPackage,
- Optional<String> apiDescription,
- Optional<ImmutableSortedSet<SourcePath>> resources,
- Optional<String> groupId,
- Optional<String> bundleName,
- Optional<String> bundleVersion,
- Optional<String> bundleLicense,
- Optional<String> bundleDescription,
- Optional<String> importPackages,
- Optional<String> exportPackages,
- Optional<String> includeResources,
- Optional<String> dynamicimportPackages,
- Optional<String> privatePackages,
- Optional<String> embeddedDependencies,
- Optional<String> bundleClasspath) {
- super(javacOptions, amender);
- this.bundleDescription = processParameter(bundleDescription);
- this.importPackages = processParameter(importPackages);
- this.privatePackages = processParameter(privatePackages);
- this.exportPackages = processParameter(exportPackages);
- this.includeResources = processParameter(includeResources);
- this.dynamicimportPackages = processParameter(dynamicimportPackages);
- this.groupId = processParameter(groupId);
- this.bundleName = processParameter(bundleName);
- this.bundleVersion = processParameter(bundleVersion);
- this.bundleLicense = processParameter(bundleLicense);
- this.webContext = processParameter(webContext);
- this.apiTitle = processParameter(apiTitle);
- this.apiVersion = processParameter(apiVersion);
- this.apiPackage = processParameter(apiPackage);
- this.apiDescription = processParameter(apiDescription);
- this.resources = resources;
- this.embeddedDependencies = processParameter(embeddedDependencies);
- this.bundleClasspath = processParameter(bundleClasspath);
- }
-
- private String processParameter(Optional<String> p) {
- return !p.isPresent() || p.get().equals("NONE") ? null : p.get();
- }
-
- @Override
- public void createCompileToJarStep(BuildContext context,
- ImmutableSortedSet<Path> sourceFilePaths,
- BuildTarget invokingRule,
- SourcePathResolver resolver,
- ProjectFilesystem filesystem,
- ImmutableSortedSet<Path> declaredClasspathEntries,
- Path outputDirectory,
- Optional<Path> workingDirectory,
- Path pathToSrcsList,
- Optional<SuggestBuildRules> suggestBuildRules,
- ImmutableList<String> postprocessClassesCommands,
- ImmutableSortedSet<Path> entriesToJar,
- Optional<String> mainClass,
- Optional<Path> manifestFile,
- Path outputJar,
- ClassUsageFileWriter usedClassesFileWriter,
- ImmutableList.Builder<Step> steps,
- BuildableContext buildableContext,
- ImmutableSet<Pattern> classesToRemoveFromJar) {
-
- ImmutableSet.Builder<Path> sourceFilePathBuilder = ImmutableSet.builder();
- sourceFilePathBuilder.addAll(sourceFilePaths);
-
- ImmutableSet.Builder<Pattern> blacklistBuilder = ImmutableSet.builder();
- blacklistBuilder.addAll(classesToRemoveFromJar);
-
- // precompilation steps
- // - generate sources
- // add all generated sources ot pathToSrcsList
- if (webContext != null && apiTitle != null && resources.isPresent()) {
- ImmutableSortedSet<Path> resourceFilePaths = findSwaggerModelDefs(resolver, resources.get());
- blacklistBuilder.addAll(resourceFilePaths.stream()
- .map(rp -> Pattern.compile(rp.getFileName().toString(), Pattern.LITERAL))
- .collect(Collectors.toSet()));
- Path genSourcesOutput = workingDirectory.get();
-
- SwaggerStep swaggerStep = new SwaggerStep(filesystem, sourceFilePaths, resourceFilePaths,
- genSourcesOutput, outputDirectory,
- webContext, apiTitle, apiVersion,
- apiPackage, apiDescription);
- sourceFilePathBuilder.add(swaggerStep.apiRegistratorPath());
- steps.add(swaggerStep);
-
-// steps.addAll(sourceFilePaths.stream()
-// .filter(sp -> sp.startsWith("src/main/webapp/"))
-// .map(sp -> CopyStep.forFile(filesystem, sp, outputDirectory))
-// .iterator());
- }
-
- createCompileStep(context,
- ImmutableSortedSet.copyOf(sourceFilePathBuilder.build()),
- invokingRule,
- resolver,
- filesystem,
- declaredClasspathEntries,
- outputDirectory,
- workingDirectory,
- pathToSrcsList,
- suggestBuildRules,
- usedClassesFileWriter,
- steps,
- buildableContext);
-
- // post compilation steps
-
-
- // FIXME BOC: add mechanism to inject new Steps
- //context.additionalStepFactory(JavaStep.class);
-
- // build the jar
- steps.add(new JarDirectoryStep(filesystem,
- outputJar,
- ImmutableSortedSet.of(outputDirectory),
- mainClass.orNull(),
- manifestFile.orNull(),
- true,
- blacklistBuilder.build()));
-
- OSGiWrapper osgiStep = new OSGiWrapper(
- outputJar, //input jar
- outputJar, //Paths.get(outputJar.toString() + ".jar"), //output jar
- invokingRule.getBasePath(), // sources dir
- outputDirectory, // classes dir
- declaredClasspathEntries, // classpath
- bundleName, // bundle name
- groupId, // groupId
- bundleVersion, // bundle version
- bundleLicense, // bundle license
- importPackages, // import packages
- exportPackages, // export packages
- includeResources, // include resources
- webContext, // web context
- dynamicimportPackages, // dynamic import packages
- embeddedDependencies, // embedded dependencies
- bundleDescription, // bundle description
- privatePackages, // private packages
- bundleClasspath // bundle classpath
- );
- steps.add(osgiStep);
-
- //steps.add(CopyStep.forFile(filesystem, Paths.get(outputJar.toString() + ".jar"), outputJar));
-
- }
-
- private ImmutableSortedSet<Path> findSwaggerModelDefs(SourcePathResolver resolver,
- ImmutableSortedSet<SourcePath> resourcePaths) {
- if (resourcePaths == null) {
- return ImmutableSortedSet.of();
- }
- return ImmutableSortedSet.copyOf(resourcePaths.stream()
- .filter(sp -> sp.toString().contains(DEFINITIONS))
- .map(resolver::getRelativePath)
- .collect(Collectors.toList()));
- }
-}
diff --git a/tools/build/buck-plugin/src/main/java/org/onosproject/onosjar/ProjectJavadocDescription.java b/tools/build/buck-plugin/src/main/java/org/onosproject/onosjar/ProjectJavadocDescription.java
deleted file mode 100644
index 12cf48e..0000000
--- a/tools/build/buck-plugin/src/main/java/org/onosproject/onosjar/ProjectJavadocDescription.java
+++ /dev/null
@@ -1,156 +0,0 @@
-/*
- * Copyright 2016-present Open Networking 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.
- */
-package org.onosproject.onosjar;
-
-import com.facebook.buck.cli.BuckConfig;
-import com.facebook.buck.jvm.java.JavaLibrary;
-import com.facebook.buck.jvm.java.JavadocJar;
-import com.facebook.buck.model.BuildTarget;
-import com.facebook.buck.model.Flavor;
-import com.facebook.buck.model.Flavored;
-import com.facebook.buck.model.Pair;
-import com.facebook.buck.parser.NoSuchBuildTargetException;
-import com.facebook.buck.rules.BuildRule;
-import com.facebook.buck.rules.BuildRuleParams;
-import com.facebook.buck.rules.BuildRuleResolver;
-import com.facebook.buck.rules.BuildRuleType;
-import com.facebook.buck.rules.Description;
-import com.facebook.buck.rules.SourcePath;
-import com.facebook.buck.rules.SourcePathResolver;
-import com.facebook.buck.rules.TargetGraph;
-import com.google.common.base.Optional;
-import com.google.common.base.Suppliers;
-import com.google.common.collect.FluentIterable;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.ImmutableSortedMap;
-import com.google.common.collect.ImmutableSortedSet;
-import com.google.common.collect.Ordering;
-
-import java.nio.file.Path;
-import java.util.Map;
-
-/**
- * Description for the onos_jar rules.
- *
- * Currently, this only does Swagger generation.
- */
-public class ProjectJavadocDescription implements Description<ProjectJavadocDescription.Arg>, Flavored {
- public static final BuildRuleType TYPE = BuildRuleType.of("project_javadoc");
-
- public ProjectJavadocDescription(BuckConfig config) {
- //TODO
- }
-
- @Override
- public BuildRuleType getBuildRuleType() {
- return TYPE;
- }
-
- @Override
- public Arg createUnpopulatedConstructorArg() {
- return new Arg();
- }
-
- @Override
- public <A extends Arg> BuildRule createBuildRule(TargetGraph targetGraph,
- BuildRuleParams params,
- BuildRuleResolver resolver,
- A args)
- throws NoSuchBuildTargetException {
-
- ImmutableSet.Builder<SourcePath> srcs = ImmutableSet.builder();
- ImmutableSet.Builder<BuildRule> deps = ImmutableSet.builder();
- ImmutableSortedMap.Builder<SourcePath, Path> docfiles = ImmutableSortedMap.naturalOrder();
- for(BuildTarget dep : args.deps) {
- BuildRule rule = resolver.requireRule(dep.withFlavors(JavaLibrary.JAVADOC_JAR));
- if (rule instanceof JavadocJar) {
- JavadocJar jarRule = (JavadocJar) rule;
- srcs.addAll(jarRule.getSources());
- deps.addAll(jarRule.getDeps());
- docfiles.putAll(jarRule.getDocFiles());
- } else {
- throw new RuntimeException("rule is not a javalib"); //FIXME
- }
- }
-
- BuildRuleParams newParams = params.copyWithDeps(
- Suppliers.ofInstance(
- FluentIterable.from(deps.build())
- .toSortedSet(Ordering.<BuildRule>natural())),
- Suppliers.ofInstance(ImmutableSortedSet.<BuildRule>of()));
-
- SourcePathResolver sourceResolver = new SourcePathResolver(resolver);
- ImmutableList.Builder<SourcePath> auxSources = ImmutableList.builder();
-
- JavadocJar.JavadocArgs.Builder javadocArgs = JavadocJar.JavadocArgs.builder()
- .addArg("-windowtitle", args.projectTitle)
- .addArg("-doctitle", args.projectTitle)
- .addArg("-link", "http://docs.oracle.com/javase/8/docs/api")
- .addArg("-tag", "onos.rsModel:a:\"onos model\""); //FIXME from buckconfig + rule
-
- if (args.groups.isPresent()) {
- for (Pair<String, ImmutableList<String>> pair : args.groups.get()) {
- javadocArgs.addArg("-group", pair.getFirst(), pair.getSecond());
- }
- }
-
- if (args.excludePackages.isPresent() &&
- !args.excludePackages.get().isEmpty()) {
- javadocArgs.addArg("-exclude", args.excludePackages.get());
- }
-
- if (args.overview.isPresent()) {
- javadocArgs.addArg("-overview",
- sourceResolver.getAbsolutePath(args.overview.get()).toString());
-
- }
-
- if (args.javadocFiles.isPresent()) {
- for (SourcePath path : args.javadocFiles.get()) {
- docfiles.put(path,
- JavadocJar.getDocfileWithPath(sourceResolver, path, args.javadocFilesRoot.orNull()));
- }
- }
-
-
- JavadocJar javadocJar = new JavadocJar(newParams,
- sourceResolver,
- ImmutableSortedSet.copyOf(srcs.build()),
- docfiles.build(),
- javadocArgs.build(),
- /* mavenCoords */ Optional.absent());
- return javadocJar;
-
- }
-
- @Override
- public boolean hasFlavors(ImmutableSet<Flavor> flavors) {
- return false;
- }
-
- public static class Arg {
- public ImmutableSortedSet<BuildTarget> deps;
- public String projectTitle;
-
- public Optional<SourcePath> overview;
- public Optional<ImmutableSortedSet<SourcePath>> javadocFiles;
- public Optional<Path> javadocFilesRoot;
-
- public Optional<ImmutableList<String>> excludePackages;
- public Optional<ImmutableList<Pair<String, ImmutableList<String>>>> groups;
- }
-}
\ No newline at end of file
diff --git a/tools/build/buck-plugin/src/main/java/org/onosproject/onosjar/SwaggerStep.java b/tools/build/buck-plugin/src/main/java/org/onosproject/onosjar/SwaggerStep.java
deleted file mode 100644
index cbb6e82..0000000
--- a/tools/build/buck-plugin/src/main/java/org/onosproject/onosjar/SwaggerStep.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * Copyright 2016-present Open Networking 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.
- */
-package org.onosproject.onosjar;
-
-import com.facebook.buck.io.ProjectFilesystem;
-import com.facebook.buck.rules.SourcePathResolver;
-import com.facebook.buck.step.AbstractExecutionStep;
-import com.facebook.buck.step.ExecutionContext;
-import com.facebook.buck.step.StepExecutionResult;
-import com.google.common.collect.ImmutableSortedSet;
-
-import java.io.File;
-import java.io.IOException;
-import java.nio.file.Path;
-import java.util.List;
-import java.util.stream.Collectors;
-
-/**
- * Buck build step to trigger SwaggerGenerator.
- */
-public class SwaggerStep extends AbstractExecutionStep {
-
- private final ProjectFilesystem filesystem;
-
- private final ImmutableSortedSet<Path> srcs;
- private final ImmutableSortedSet<Path> resources;
- private final Path genSourcesOutput;
- private final Path genResourcesOutput;
-
- private final String webContext;
- private final String apiTitle;
- private final String apiVersion;
- private final String apiPackage;
- private final String apiDescription;
-
-
- public SwaggerStep(ProjectFilesystem filesystem,
- ImmutableSortedSet<Path> srcs,
- ImmutableSortedSet<Path> resources,
- Path genSourcesOutput, Path genResourcesOutput,
- String webContext, String apiTitle, String apiVersion,
- String apiPackage, String apiDescription) {
- super("swagger");
- this.filesystem = filesystem;
- this.srcs = srcs;
- this.resources = resources;
- this.genSourcesOutput = genSourcesOutput;
- this.genResourcesOutput = genResourcesOutput;
- this.webContext = webContext;
- this.apiTitle = apiTitle;
- this.apiVersion = apiVersion;
- this.apiPackage = apiPackage;
- this.apiDescription = apiDescription;
- }
-
- @Override
- public StepExecutionResult execute(ExecutionContext executionContext)
- throws IOException, InterruptedException {
- try {
- List<File> srcFiles = srcs.stream()
- .map(src -> filesystem.resolve(src).toFile())
- .collect(Collectors.toList());
- List<File> resourceFiles = resources.stream()
- .map(rsrc -> filesystem.resolve(rsrc).toFile())
- .collect(Collectors.toList());
- new SwaggerGenerator(srcFiles, resourceFiles, null, null,
- filesystem.resolve(genSourcesOutput).toFile(),
- filesystem.resolve(genResourcesOutput).toFile(),
- webContext,
- apiTitle,
- apiVersion,
- apiPackage,
- apiDescription).execute();
-
- return StepExecutionResult.SUCCESS;
- } catch (Exception e) {
- e.printStackTrace();
- // FIXME print the exception
- return StepExecutionResult.ERROR;
- }
- }
-
- Path apiRegistratorPath() {
- return genSourcesOutput.resolve(SwaggerGenerator.apiRegistratorPath(apiPackage));
- }
-}
diff --git a/tools/build/buck-publish b/tools/build/buck-publish
deleted file mode 100755
index 01ed7d9..0000000
--- a/tools/build/buck-publish
+++ /dev/null
@@ -1,32 +0,0 @@
-#!/bin/bash
-# -----------------------------------------------------------------------------
-# Build and publish the ONOS version of buck.
-# -----------------------------------------------------------------------------
-
-if [ $# -ne 3 -a $# -ne 4 ]; then
- echo "Usage: buck-publish-setup buck-branch onos-branch yang-branch [version] [--dry-run]"
- echo "For example, to build buck branch 11-11-2016, onos branch master, and onos-yang-tools master:"
- echo "buck-publish 11-11-2016 master master"
- exit 1
-fi
-
-if [ $# -eq 4 -a "${4}" != "--dry-run" ]; then
- echo "$4 is an invalid parameter - only --dry-run allowed"
- exit 1
-fi
-
-BUCK_BRANCH="$1"
-ONOS_BRANCH="$2"
-YANG_BRANCH="$3"
-
-if [ -z "$4" ]; then
- onos-release-prerequisites
-fi
-
-DIR=$(mktemp -d /tmp/buck-publish.XXXXX) || { echo "Failed to create temp file"; exit 1; }
-
-buck-publish-setup $BUCK_BRANCH $ONOS_BRANCH $YANG_BRANCH $DIR
-pushd $DIR && buck-publish-package $4 && popd
-cp $DIR/onos/tools/build/onos-buck $ONOS_ROOT/tools/build/onos-buck
-
-
diff --git a/tools/build/buck-publish-api b/tools/build/buck-publish-api
deleted file mode 100755
index e27f1d0..0000000
--- a/tools/build/buck-publish-api
+++ /dev/null
@@ -1,56 +0,0 @@
-#!/bin/bash
-
-BUCK_LOCAL_CONFIG=${BUCK_LOCAL_CONFIG:-$ONOS_ROOT/.buckconfig.local}
-MVN_REPO="https://oss.sonatype.org/content/repositories/snapshots"
-NO_BUCKD=1
-
-set -e
-set -x
-
-#FIXME if pwd != buck
-pushd buck
-
-# build buck
-scripts/create_tag.sh
-buck build buck --show-output
-
-# publish cli:main-fixed as buck-api
-cp $BUCK_LOCAL_CONFIG .
-buck publish //src/com/facebook/buck/cli:main-fixed \
- --remote-repo=https://oss.sonatype.org/content/repositories/snapshots/ \
- | tee ../api-publish.txt
-
-# Alternatively, we can deploy org.onosproject:buck-api with the following:
-#mvn deploy:deploy-file -DgroupId=org.onosproject -DartifactId=buck-api \
-# -Dversion=0.1-SNAPSHOT -DgeneratePom=true -Dpackaging=jar \
-# -DrepositoryId=snapshot -Durl=https://oss.sonatype.org/content/repositories/snapshots/ \
-# -Dfile=buck-out/gen/src/com/facebook/buck/cli/main-fixed/main-fixed.jar
-
-#FIXME upload API to S3 for backup
-
-popd #buck
-
-SNAPSHOT_VERSION=$(cat api-publish.txt | grep "^org.onosproject:buck-api:jar" \
- | cut -d' ' -f1 | cut -d: -f4)
-BUCK_API_URL="$MVN_REPO/org/onosproject/buck-api/0.1-SNAPSHOT/buck-api-$SNAPSHOT_VERSION.jar"
-echo $BUCK_API_URL
-
-BUCK_API_SHA=$(shasum buck/buck-out/gen/src/com/facebook/buck/cli/main-fixed/main-fixed.jar | cut -d' ' -f1)
-echo $BUCK_API_SHA
-
-pushd onos
-sed -i "" -E "s#url =.*#url = '$BUCK_API_URL',#" tools/build/buck-plugin/BUCK
-sed -i "" -E "s#sha1 =.*#sha1 = '$BUCK_API_SHA',#" tools/build/buck-plugin/BUCK
-popd #onos
-
-#pushd onos-yang-tools
-#FIXME update version (assume 0.1-SNAPSHOT for now)
-#popd #onos-yang-tools
-
-set +x
-
-echo
-echo "Please build and verify the ONOS Buck plugin and the Yang tools plugin:"
-echo " cd onos; buck build //tools/build/buck-plugin:onos"
-echo " cd onos-yang-tools; mvn clean package"
-echo "You should commit and push any required changes."
diff --git a/tools/build/buck-publish-package b/tools/build/buck-publish-package
deleted file mode 100755
index 09d1612..0000000
--- a/tools/build/buck-publish-package
+++ /dev/null
@@ -1,71 +0,0 @@
-#!/bin/bash
-
-for NEXT_VERSION in 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20; do
- DEFAULT_TAG=${TAG:-$(date +v%Y.%m.%d.$NEXT_VERSION)}
- BUCK_ZIP="buck-$DEFAULT_TAG.zip"
- DOWNLOAD_BASE="http://repo1.maven.org/maven2/org/onosproject/onos-buck/$DEFAULT_TAG"
-
- if ! curl --output /dev/null --silent --head --fail "$DOWNLOAD_BASE/$BUCK_ZIP"; then
- break;
- fi
-done
-
-NO_BUCKD=1
-
-UPLOAD_BASE="https://oss.sonatype.org/service/local/staging/deploy/maven2/org/onosproject/onos-buck/$DEFAULT_TAG"
-BUCK_ZIP="buck-$DEFAULT_TAG.zip"
-ZIP_STAGE="buck-bin"
-
-rm -rf $ZIP_STAGE
-
-set -e
-set -x
-
-# build plugins
-
-pushd buck
-onos-buck build buck
-popd #buck
-
-pushd onos
-onos-buck build //tools/build/buck-plugin:onos
-popd #onos
-
-pushd onos-yang-tools
-mvn clean package
-popd #onos-yang-tools
-
-# assemble zip
-
-mkdir -p buck-bin/plugins
-
-cp buck/buck-out/gen/programs/buck.pex $ZIP_STAGE/buck
-cp onos/buck-out/gen/tools/build/buck-plugin/onos.jar $ZIP_STAGE/plugins/onos.jar
-cp onos-yang-tools/compiler/plugin/buck/target/onos-yang-compiler-buck-plugin-*.jar $ZIP_STAGE/plugins/yang.jar
-
-BUCK_VERSION=$(buck/buck-out/gen/programs/buck.pex -V)
-echo $BUCK_VERSION > $ZIP_STAGE/.buck_version
-
-chmod 555 $ZIP_STAGE/buck
-chmod 444 $ZIP_STAGE/.buck_version
-
-pushd $ZIP_STAGE
-zip -r ../$BUCK_ZIP buck .buck_version plugins
-popd #$ZIP_STAGE
-
-if [ "$1" != "--dry-run" ]; then
- # publish zip
- curl -v -u "$SONATYPE_USER:$SONATYPE_PASSWORD" --upload-file $BUCK_ZIP $UPLOAD_BASE/$BUCK_ZIP
- echo "New buck release is in " $BUCK_ZIP
-fi
-
-# update version in onos-buck
-URL="$DOWNLOAD_BASE/$BUCK_ZIP"
-SHA=$(shasum $BUCK_ZIP | cut -d' ' -f1)
-
-sed -i "" -E "s#BUCK_URL=.*#BUCK_URL=\"$URL\"#" onos/tools/build/onos-buck
-sed -i "" -E "s#BUCK_SHA=.*#BUCK_SHA=\"$SHA\"#" onos/tools/build/onos-buck
-
-set +x
-echo
-echo "Commit and push change to onos-buck on the onos directory."
diff --git a/tools/build/buck-publish-setup b/tools/build/buck-publish-setup
deleted file mode 100755
index d180479..0000000
--- a/tools/build/buck-publish-setup
+++ /dev/null
@@ -1,28 +0,0 @@
-#!/bin/bash
-
-BUCK_REF=${1:-"11-11-2016"}
-ONOS_REF=${2:-"master"}
-YANG_REF=${3:-"master"}
-DIR=$4
-
-set -x
-
-if [ -z "$4" ]; then
- DIR=$(mktemp -d /tmp/buck-publish.XXXXX) || { echo "Failed to create temp file"; exit 1; }
-fi
-# change to tmpdir
-cd $DIR
-
-# checkout buck
-git clone -b $BUCK_REF https://github.com/bocon13/buck
-
-# checkout plugins
-git clone -b $ONOS_REF https://gerrit.onosproject.org/onos.git
-git clone -b $YANG_REF https://gerrit.onosproject.org/onos-yang-tools.git
-
-set +x
-
-echo
-echo "Buck publish area:"
-echo " cd $DIR"
-
diff --git a/tools/build/conf/BUCK b/tools/build/conf/BUCK
deleted file mode 100644
index 11ab279..0000000
--- a/tools/build/conf/BUCK
+++ /dev/null
@@ -1,81 +0,0 @@
-checkstyle_source = 'src/main/resources/onos/checkstyle.xml'
-suppression_source = 'src/main/resources/onos/suppressions.xml'
-header_source = 'src/main/resources/onos/onos-java.header'
-
-export_file (
- name = 'checkstyle-xml',
- src = checkstyle_source,
- visibility = [ 'PUBLIC' ],
-)
-
-export_file (
- name = 'suppressions-xml',
- src = suppression_source,
- visibility = [ 'PUBLIC' ],
-)
-
-export_file (
- name = 'onos-java-header',
- src = header_source,
- visibility = [ 'PUBLIC' ],
-)
-
-export_file (
- name = 'start-buck-daemon',
- visibility = [ 'PUBLIC' ],
-)
-
-COMPILE = [
- '//lib:com_google_guava_guava',
- '//lib:checkstyle',
-]
-
-RUN = [
- '//lib:commons-logging',
- '//lib:commons-beanutils',
- '//lib:commons-lang3',
- '//lib:commons-collections',
- '//lib:antlr',
-]
-
-java_library (
- name = 'checkstyle',
- srcs = glob([ 'src/main/java/**/*.java' ]),
- deps = COMPILE,
-)
-
-java_binary (
- name = 'buck-daemon-jar',
- deps = [ ':checkstyle' ] + RUN,
- main_class = 'org.onosproject.buckdaemon.BuckDaemon',
- blacklist = [ 'META-INF/.*' ],
- visibility = [ 'PUBLIC' ],
-)
-
-osgi_jar (
- name = 'onos-build-conf',
- srcs = [],
- deps = [ ':checkstyle' ] + RUN,
-)
-
-# cmd = '#!/bin/bash\n'
-# cmd += '$1 &>/dev/null < /dev/null &'
-#
-# genrule(
-# name = 'checkstyle-sh',
-# bash = "echo '%s' > $OUT && chmod +x $OUT" % cmd,
-# out = 'checkstyle.sh',
-# )
-#
-# sh_test(
-# name = 'checkstyle-runner',
-# test = ':checkstyle-sh',
-# args = [
-# '$(exe :checkstyle-jar)',
-# '$(location //lib:checkstyle)',
-# '$(location //tools/build/conf:checkstyle-xml)',
-# '`mktemp /tmp/%s-checkstyle-XXXXXX`',
-# ],
-# labels = [ 'checkstyle' ],
-# visibility = [ 'PUBLIC' ],
-# )
diff --git a/tools/build/conf/src/main/java/org/onosproject/buckdaemon/BuckDaemon.java b/tools/build/conf/src/main/java/org/onosproject/buckdaemon/BuckDaemon.java
deleted file mode 100644
index a253995..0000000
--- a/tools/build/conf/src/main/java/org/onosproject/buckdaemon/BuckDaemon.java
+++ /dev/null
@@ -1,227 +0,0 @@
-/*
- * Copyright 2016-present Open Networking 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.
- */
-
-package org.onosproject.buckdaemon;
-
-import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
-import org.onosproject.checkstyle.CheckstyleRunner;
-
-import java.io.IOException;
-import java.io.PrintStream;
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.net.ServerSocket;
-import java.net.Socket;
-import java.nio.ByteBuffer;
-import java.nio.channels.FileChannel;
-import java.nio.channels.FileLock;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Timer;
-import java.util.TimerTask;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-
-import static java.nio.file.StandardOpenOption.CREATE;
-import static java.nio.file.StandardOpenOption.WRITE;
-
-/**
- * Buck daemon process.
- */
-public final class BuckDaemon {
-
- private static final long POLLING_INTERVAL = 1000; //ms
-
- private final Map<String, BuckTask> tasks = new HashMap<>();
- private final String portLock;
- private final String buckPid;
-
- // Public construction forbidden
- private BuckDaemon(String[] args) {
- portLock = args[0];
- buckPid = args[1];
- }
-
- /**
- * Main entry point for the daemon.
- *
- * @param args command-line arguments
- * @throws CheckstyleException on checkstyle error
- * @throws IOException on I/O error
- */
- public static void main(String[] args)
- throws CheckstyleException, IOException {
- BuckDaemon daemon = new BuckDaemon(args);
- daemon.registerTasks();
- daemon.startServer();
- }
-
- /**
- * Registers re-entrant tasks by their task name.
- */
- private void registerTasks() {
- tasks.put("checkstyle", new CheckstyleRunner(System.getProperty("checkstyle.config"),
- System.getProperty("checkstyle.suppressions")));
- // tasks.put("swagger", new SwaggerGenerator());
- }
-
- /**
- * Monitors another PID and exit when that process exits.
- */
- private void watchProcess(String pid) {
- if (pid == null || pid.equals("0")) {
- return;
- }
- Timer timer = new Timer(true); // start as a daemon, so we don't hang shutdown
- timer.scheduleAtFixedRate(new TimerTask() {
- private String cmd = "kill -s 0 " + pid;
-
- @Override
- public void run() {
- try {
- Process p = Runtime.getRuntime().exec(cmd);
- p.waitFor();
- if (p.exitValue() != 0) {
- debug("shutting down...");
- System.exit(0);
- }
- } catch (IOException | InterruptedException e) {
- //no-op
- e.printStackTrace();
- }
- }
- }, POLLING_INTERVAL, POLLING_INTERVAL);
- }
-
- /**
- * Initiates a server.
- */
- private void startServer() throws IOException, CheckstyleException {
- // Use a file lock to ensure only one copy of the daemon runs
- Path portLockPath = Paths.get(portLock);
- FileChannel channel = FileChannel.open(portLockPath, WRITE, CREATE);
- FileLock lock = channel.tryLock();
- if (lock == null) {
- debug("Server is already running");
- System.exit(1);
- } //else, hold the lock until the JVM exits
-
- // Start the server and bind it to a random port
- ServerSocket server = new ServerSocket(0);
-
- // Monitor the parent buck process
- watchProcess(buckPid);
-
- // Set up hook to clean up after ourselves
- Runtime.getRuntime().addShutdownHook(new Thread(() -> {
- try {
- channel.truncate(0);
- channel.close();
- debug("tear down...");
- Files.delete(portLockPath);
- } catch (IOException e) {
- //no-op: shutting down
- e.printStackTrace();
- }
- }));
-
- // Write the bound port to the port file
- int port = server.getLocalPort();
- channel.truncate(0);
- channel.write(ByteBuffer.wrap(Integer.toString(port).getBytes()));
- channel.force(false); // flush the port number to disk
-
- // Instantiate a Checkstyle runner and executor; serve until exit...
- ExecutorService executor = Executors.newCachedThreadPool();
- while (true) {
- try {
- executor.submit(new BuckTaskRunner(server.accept()));
- } catch (Exception e) {
- e.printStackTrace();
- //no-op
- }
- }
- }
-
- /**
- * Runnable capable of invoking the appropriate Buck task with input
- * consumed form the specified socket and output produced back to that
- * socket.
- */
- private class BuckTaskRunner implements Runnable {
-
- private final Socket socket;
-
- public BuckTaskRunner(Socket socket) {
- this.socket = socket;
- }
-
- @Override
- public void run() {
- try {
- try {
- socket.setSoTimeout(1_000); //reads should time out after 1 second
- BuckTaskContext context = BuckTaskContext.createBuckTaskContext(socket.getInputStream());
- if (context == null) {
- socket.close();
- return;
- }
-
- String taskName = context.taskName();
- BuckTask task = tasks.get(taskName);
- if (task != null) {
- debug(String.format("Executing task '%s'", taskName));
- try {
- task.execute(context);
- for (String line : context.output()) {
- send(socket, line);
- }
- // TODO should we catch Exception, RuntimeException, or something specific?
- } catch (Throwable e) {
- e.printStackTrace(new PrintStream(socket.getOutputStream()));
- }
- } else {
- String message = String.format("No task named '%s'", taskName);
- debug(message);
- send(socket, message);
- }
- } catch (Throwable e) {
- StringWriter writer = new StringWriter();
- e.printStackTrace(new PrintWriter(writer));
- String stacktrace = writer.toString();
- debug(stacktrace);
- send(socket, stacktrace);
- }
- socket.getOutputStream().flush();
- socket.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- }
-
- private static void send(Socket socket, String line) throws IOException {
- socket.getOutputStream().write((line + "\n").getBytes());
- }
-
- private static void debug(String message) {
- // no-op; print to System.out if needed
- }
-}
diff --git a/tools/build/conf/src/main/java/org/onosproject/buckdaemon/BuckTask.java b/tools/build/conf/src/main/java/org/onosproject/buckdaemon/BuckTask.java
deleted file mode 100644
index d579305..0000000
--- a/tools/build/conf/src/main/java/org/onosproject/buckdaemon/BuckTask.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright 2016-present Open Networking 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.
- */
-
-package org.onosproject.buckdaemon;
-
-/**
- * Abstraction of a Buck task that can be spawned by the Buck daemon.
- */
-public interface BuckTask {
-
- /**
- * Executes the task, consuming the specified input and producing output.
- *
- * @param context context for the tast operation
- */
- void execute(BuckTaskContext context);
-
-}
diff --git a/tools/build/conf/src/main/java/org/onosproject/buckdaemon/BuckTaskContext.java b/tools/build/conf/src/main/java/org/onosproject/buckdaemon/BuckTaskContext.java
deleted file mode 100644
index 8dabfd2..0000000
--- a/tools/build/conf/src/main/java/org/onosproject/buckdaemon/BuckTaskContext.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Copyright 2016-present Open Networking 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.
- */
-
-package org.onosproject.buckdaemon;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.util.List;
-
-/**
- * Context for executing a single Buck task.
- */
-public class BuckTaskContext {
-
- private final String taskName;
- private final ImmutableList<String> input;
- private final List<String> output;
-
- public static BuckTaskContext createBuckTaskContext(InputStream inputStream) throws IOException {
- ImmutableList<String> lines = slurpInput(inputStream);
- if (lines.size() == 0) {
- return null;
- } else {
- return new BuckTaskContext(lines);
- }
- }
-
- BuckTaskContext(ImmutableList<String> lines) {
- this.taskName = lines.get(0);
- this.input = lines.subList(1, lines.size());
- this.output = Lists.newArrayList();
- }
-
- /**
- * Reads all input, line by line, from a stream until an empty line or EOF is encountered.
- *
- * @param stream input stream
- * @return the lines of the input
- * @throws IOException
- */
- private static ImmutableList<String> slurpInput(InputStream stream) throws IOException {
- ImmutableList.Builder<String> lines = ImmutableList.builder();
- BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
- while (true) {
- String line = bufferedReader.readLine();
- if (line == null || line.trim().length() == 0) {
- // Empty line or EOF
- break;
- }
- lines.add(line);
- }
- return lines.build();
- }
-
- /**
- * Returns the symbolic task name.
- *
- * @return symbolic task name
- */
- public String taskName() {
- return taskName;
- }
-
- /**
- * Returns the input data a list of strings.
- *
- * @return input data
- */
- public List<String> input() {
- return ImmutableList.copyOf(input);
- }
-
- /**
- * Returns the output data a list of strings.
- *
- * @return output data
- */
- List<String> output() {
- return ImmutableList.copyOf(output);
- }
-
- /**
- * Adds a line to the output data.
- *
- * @param line line of output data
- */
- public void output(String line) {
- output.add(line);
- }
-
-}
diff --git a/tools/build/conf/start-buck-daemon b/tools/build/conf/start-buck-daemon
deleted file mode 100755
index b747376..0000000
--- a/tools/build/conf/start-buck-daemon
+++ /dev/null
@@ -1,80 +0,0 @@
-#!/bin/bash
-# -----------------------------------------------------------------------------
-# Launches Buck daemon if not already running and requests Buck task execution.
-# -----------------------------------------------------------------------------
-
-BUCK_DAEMON=$1
-TASK=${2:-unspecified}
-DATA=${3}
-
-# TODO: Figure out how to parametrize better
-BUCK_PROPS="-Dcheckstyle.config=$4 -Dcheckstyle.suppressions=$5"
-
-PORT_FILE="$1.port"
-
-function ppid() {
- ps -p ${1:-$$} -o ppid= -o pid= -o comm=
-}
-
-function buck_pid() {
- BUCK_PID=($(ppid))
- while [ ${BUCK_PID[0]} -ne 0 ]; do
- BUCK_PID=($(ppid $BUCK_PID))
- if [ "${BUCK_PID[2]}" == "buck" ]; then
- # use parent PID of buck
- echo ${BUCK_PID[0]}
- return
- fi
- if [ "${BUCK_PID[2]}" == "buckd" ] ||
- [[ "${BUCK_PID[2]}" == *"python"* ]]; then
- # use PID of buckd or python
- echo ${BUCK_PID[1]}
- return
- fi
- done
- # fallback last read PID
- echo ${BUCK_PID[1]}
-}
-
-function port() {
- cat $PORT_FILE 2>/dev/null || echo 0
-}
-
-function check_socket() {
- printf "\n" | nc localhost $(port) 2>/dev/null
- return $?
-}
-
-# check to see if buck daemon is running; if not, start it
-if ! check_socket; then
- # Starting buck daemon...
- #FIXME change to /dev/null if/when we are confident
- nohup java $BUCK_PROPS -jar $BUCK_DAEMON $PORT_FILE $(buck_pid) >>/tmp/buck.daemon 2>&1 &
-
- TRIES=20
- i=0
- # Wait for buck daemon to start for 2 seconds
- while [ $i -lt $TRIES ]; do
- if check_socket; then
- CONNECTED=true
- break
- fi
- let i=i+1
- sleep 0.1
- done
- if [ -z "$CONNECTED" ]; then
- echo "Failed to start buck daemon"
- exit 3
- fi
-fi
-
-# run the actual buck daemon client
-OUT=$((printf "%s\n" $TASK; cat $DATA) | nc localhost $(port))
-if [ $? -ne 0 ]; then
- echo "Error connecting to buck daemon server"
- exit 2
-fi
-if [ -n "$OUT" ]; then
- printf "$OUT"
- exit 1
-fi
\ No newline at end of file
diff --git a/tools/build/jenkins/onos-buck-gerrit b/tools/build/jenkins/onos-buck-gerrit
deleted file mode 100644
index 7638a2a..0000000
--- a/tools/build/jenkins/onos-buck-gerrit
+++ /dev/null
@@ -1,37 +0,0 @@
-#!groovy
-
-pipeline {
-
- agent { node { label 'ubuntu16.04-basebuild-8c-15g' } }
-
- stages {
-
- stage('build') {
- steps {
- sh '''#!/bin/bash -l
- ONOS_ROOT=`pwd`
- source tools/build/envDefaults
- onos-buck build onos
- '''
- }
- }
-
- stage('test') {
- steps {
- parallel (
- "unit-tests": {
- sh '''#!/bin/bash -l
- ONOS_ROOT=`pwd`
- source tools/build/envDefaults
- onos-buck test
- onos-buck build //docs:external //docs:internal --show-output
- '''
- },
- // additional steps here (STC, docker buld, etc)
- )
- }
- }
- }
-
-}
-
diff --git a/tools/build/libgen/pom.xml b/tools/build/libgen/pom.xml
index 9288bb3..e28cbb7 100644
--- a/tools/build/libgen/pom.xml
+++ b/tools/build/libgen/pom.xml
@@ -31,7 +31,7 @@
<packaging>jar</packaging>
<version>1.6-SNAPSHOT</version>
- <description>Third-party library generator for Buck and Bazel workspaces</description>
+ <description>Third-party library generator for ONOS Bazel workspace</description>
<url>http://onosproject.org/</url>
<scm>
@@ -116,7 +116,7 @@
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
- <mainClass>org.onosproject.libgen.BuckLibGenerator</mainClass>
+ <mainClass>org.onosproject.libgen.BazelLibGenerator</mainClass>
</transformer>
</transformers>
<filters>
diff --git a/tools/build/libgen/src/main/java/org/onosproject/libgen/AetherResolver.java b/tools/build/libgen/src/main/java/org/onosproject/libgen/AetherResolver.java
index e97bad5..23ffc9e 100755
--- a/tools/build/libgen/src/main/java/org/onosproject/libgen/AetherResolver.java
+++ b/tools/build/libgen/src/main/java/org/onosproject/libgen/AetherResolver.java
@@ -24,10 +24,9 @@
import org.eclipse.aether.connector.basic.BasicRepositoryConnectorFactory;
import org.eclipse.aether.impl.DefaultServiceLocator;
import org.eclipse.aether.repository.LocalRepository;
+import org.eclipse.aether.repository.Proxy;
import org.eclipse.aether.repository.RemoteRepository;
import org.eclipse.aether.repository.RepositoryPolicy;
-import org.eclipse.aether.repository.Proxy;
-import org.eclipse.aether.util.repository.AuthenticationBuilder;
import org.eclipse.aether.resolution.ArtifactRequest;
import org.eclipse.aether.resolution.ArtifactResult;
import org.eclipse.aether.resolution.VersionRangeRequest;
@@ -37,6 +36,7 @@
import org.eclipse.aether.spi.connector.transport.TransporterFactory;
import org.eclipse.aether.transport.file.FileTransporterFactory;
import org.eclipse.aether.transport.http.HttpTransporterFactory;
+import org.eclipse.aether.util.repository.AuthenticationBuilder;
import org.eclipse.aether.version.Version;
import java.io.BufferedReader;
@@ -49,8 +49,8 @@
import java.util.List;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
-import java.util.regex.Pattern;
import java.util.regex.Matcher;
+import java.util.regex.Pattern;
import static org.eclipse.aether.repository.RepositoryPolicy.CHECKSUM_POLICY_WARN;
import static org.eclipse.aether.repository.RepositoryPolicy.UPDATE_POLICY_ALWAYS;
@@ -68,40 +68,38 @@
static {
DefaultServiceLocator locator = MavenRepositorySystemUtils.newServiceLocator();
- locator.addService(RepositoryConnectorFactory.class, BasicRepositoryConnectorFactory.class );
- locator.addService(TransporterFactory.class, FileTransporterFactory.class );
- locator.addService(TransporterFactory.class, HttpTransporterFactory.class );
+ locator.addService(RepositoryConnectorFactory.class, BasicRepositoryConnectorFactory.class);
+ locator.addService(TransporterFactory.class, FileTransporterFactory.class);
+ locator.addService(TransporterFactory.class, HttpTransporterFactory.class);
- locator.setErrorHandler( new DefaultServiceLocator.ErrorHandler()
- {
+ locator.setErrorHandler(new DefaultServiceLocator.ErrorHandler() {
@Override
- public void serviceCreationFailed( Class<?> type, Class<?> impl, Throwable exception )
- {
+ public void serviceCreationFailed(Class<?> type, Class<?> impl, Throwable exception) {
exception.printStackTrace();
}
- } );
+ });
- AetherResolver.system = locator.getService( RepositorySystem.class );
+ AetherResolver.system = locator.getService(RepositorySystem.class);
DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();
- LocalRepository localRepo = new LocalRepository("target/local-repo" );
- session.setLocalRepositoryManager( system.newLocalRepositoryManager( session, localRepo ) );
+ LocalRepository localRepo = new LocalRepository("target/local-repo");
+ session.setLocalRepositoryManager(system.newLocalRepositoryManager(session, localRepo));
//session.setTransferListener( new ConsoleTransferListener() );
//session.setRepositoryListener( new ConsoleRepositoryListener() );
AetherResolver.session = session;
}
- public static BuckArtifact getArtifact(String name, String uri, String repo, boolean generateForBazel) {
- return new AetherResolver(repo).build(name, uri, generateForBazel);
+ public static BazelArtifact getArtifact(String name, String uri, String repo) {
+ return new AetherResolver(repo).build(name, uri);
}
private AetherResolver(String repoUrl) {
this.repoUrl = repoUrl;
}
- private BuckArtifact build(String name, String uri, boolean generateForBazel) {
+ private BazelArtifact build(String name, String uri) {
uri = uri.replaceFirst("mvn:", "");
Artifact artifact = new DefaultArtifact(uri);
String originalVersion = artifact.getVersion();
@@ -113,20 +111,20 @@
if (originalVersion.endsWith("-SNAPSHOT")) {
String url = String.format("%s/%s/%s/%s/%s-%s.%s",
- repoUrl,
- artifact.getGroupId().replace('.', '/'),
- artifact.getArtifactId(),
- originalVersion,
- artifact.getArtifactId(),
- artifact.getVersion(),
- artifact.getExtension());
+ repoUrl,
+ artifact.getGroupId().replace('.', '/'),
+ artifact.getArtifactId(),
+ originalVersion,
+ artifact.getArtifactId(),
+ artifact.getVersion(),
+ artifact.getExtension());
String mavenCoords = String.format("%s:%s:%s",
artifact.getGroupId(),
artifact.getArtifactId(),
originalVersion);
- return BuckArtifact.getArtifact(name, url, sha, mavenCoords, osgiReady, generateForBazel);
+ return BazelArtifact.getArtifact(name, url, sha, mavenCoords, osgiReady);
}
- return BuckArtifact.getArtifact(name, artifact, sha, repoUrl, osgiReady, generateForBazel);
+ return BazelArtifact.getArtifact(name, artifact, sha, repoUrl, osgiReady);
} catch (Exception e) {
throw new RuntimeException(e);
}
@@ -157,13 +155,13 @@
// artifactId-version[-classifier].version.sha1
file.append(artifact.getArtifactId())
- .append('-').append(artifact.getVersion());
+ .append('-').append(artifact.getVersion());
if (!artifact.getClassifier().isEmpty()) {
file.append('-').append(artifact.getClassifier());
}
file.append('.').append(artifact.getExtension())
- .append(".sha1");
+ .append(".sha1");
String shaPath = Paths.get(directory, file.toString()).toString();
@@ -177,7 +175,7 @@
rangeRequest.setArtifact(artifact);
rangeRequest.setRepositories(repositories());
- VersionRangeResult rangeResult = system.resolveVersionRange(session, rangeRequest );
+ VersionRangeResult rangeResult = system.resolveVersionRange(session, rangeRequest);
Version newestVersion = rangeResult.getHighestVersion();
@@ -195,19 +193,19 @@
// set authentication
if ((proxyHostInfo.get(2) != null) && (proxyHostInfo.get(3) != null)) {
central.setProxy(
- new Proxy(Proxy.TYPE_HTTP, proxyHostInfo.get(0), Integer.valueOf(proxyHostInfo.get(1)),
- new AuthenticationBuilder()
- .addUsername(proxyHostInfo.get(2)).addPassword(proxyHostInfo.get(3)).build()));
+ new Proxy(Proxy.TYPE_HTTP, proxyHostInfo.get(0), Integer.valueOf(proxyHostInfo.get(1)),
+ new AuthenticationBuilder()
+ .addUsername(proxyHostInfo.get(2)).addPassword(proxyHostInfo.get(3)).build()));
} else {
central.setProxy(
- new Proxy(Proxy.TYPE_HTTP, proxyHostInfo.get(0), Integer.valueOf(proxyHostInfo.get(1))));
+ new Proxy(Proxy.TYPE_HTTP, proxyHostInfo.get(0), Integer.valueOf(proxyHostInfo.get(1))));
}
}
if (repoUrl != null && repoUrl.length() > 0) {
RemoteRepository.Builder other =
- new RemoteRepository.Builder("temp", "default", repoUrl)
- .setSnapshotPolicy(new RepositoryPolicy(true, UPDATE_POLICY_ALWAYS, CHECKSUM_POLICY_WARN));
+ new RemoteRepository.Builder("temp", "default", repoUrl)
+ .setSnapshotPolicy(new RepositoryPolicy(true, UPDATE_POLICY_ALWAYS, CHECKSUM_POLICY_WARN));
// set https_proxy
String env_https_proxy = System.getenv("HTTPS_PROXY");
@@ -217,12 +215,12 @@
// set authentication
if ((proxyHostInfo.get(2) != null) && (proxyHostInfo.get(3) != null)) {
other.setProxy(
- new Proxy(Proxy.TYPE_HTTPS, proxyHostInfo.get(0), Integer.valueOf(proxyHostInfo.get(1)),
- new AuthenticationBuilder()
- .addUsername(proxyHostInfo.get(2)).addPassword(proxyHostInfo.get(3)).build()));
+ new Proxy(Proxy.TYPE_HTTPS, proxyHostInfo.get(0), Integer.valueOf(proxyHostInfo.get(1)),
+ new AuthenticationBuilder()
+ .addUsername(proxyHostInfo.get(2)).addPassword(proxyHostInfo.get(3)).build()));
} else {
other.setProxy(
- new Proxy(Proxy.TYPE_HTTPS, proxyHostInfo.get(0), Integer.valueOf(proxyHostInfo.get(1))));
+ new Proxy(Proxy.TYPE_HTTPS, proxyHostInfo.get(0), Integer.valueOf(proxyHostInfo.get(1))));
}
}
diff --git a/tools/build/libgen/src/main/java/org/onosproject/libgen/BuckArtifact.java b/tools/build/libgen/src/main/java/org/onosproject/libgen/BazelArtifact.java
similarity index 71%
rename from tools/build/libgen/src/main/java/org/onosproject/libgen/BuckArtifact.java
rename to tools/build/libgen/src/main/java/org/onosproject/libgen/BazelArtifact.java
index 11f529a..ae13b56 100644
--- a/tools/build/libgen/src/main/java/org/onosproject/libgen/BuckArtifact.java
+++ b/tools/build/libgen/src/main/java/org/onosproject/libgen/BazelArtifact.java
@@ -18,40 +18,36 @@
import org.eclipse.aether.artifact.Artifact;
/**
- * Representation of a remote artifact for Buck.
+ * Representation of a remote artifact for Bazel.
*/
-public abstract class BuckArtifact {
+public abstract class BazelArtifact {
private final String name;
private final String sha;
private final boolean osgiReady;
- private final boolean generateForBazel;
- public static BuckArtifact getArtifact(String name, Artifact artifact, String sha, String repo,
- boolean osgiReady, boolean generateForBazel) {
- return new MavenArtifact(name, artifact, sha, repo, osgiReady, generateForBazel);
- }
- public static BuckArtifact getArtifact(String name, String url, String sha, String mavenCoords,
- boolean osgiReady, boolean generateForBazel) {
- return new HTTPArtifact(name, url, sha, mavenCoords, osgiReady, generateForBazel);
- }
- public static BuckArtifact getArtifact(String name, String url, String sha, boolean generateForBazel) {
- return new HTTPArtifact(name, url, sha, null, true, generateForBazel);
+ public static BazelArtifact getArtifact(String name, Artifact artifact, String sha, String repo,
+ boolean osgiReady) {
+ return new MavenArtifact(name, artifact, sha, repo, osgiReady);
}
- public BuckArtifact(String name, String sha, boolean osgiReady, boolean generateForBazel) {
+ public static BazelArtifact getArtifact(String name, String url, String sha, String mavenCoords,
+ boolean osgiReady) {
+ return new HTTPArtifact(name, url, sha, mavenCoords, osgiReady);
+ }
+
+ public static org.onosproject.libgen.BazelArtifact getArtifact(String name, String url, String sha) {
+ return new HTTPArtifact(name, url, sha, null, true);
+ }
+
+ public BazelArtifact(String name, String sha, boolean osgiReady) {
this.name = name;
this.sha = sha;
this.osgiReady = osgiReady;
- this.generateForBazel = generateForBazel;
}
public String name() {
- if (!generateForBazel) {
- return name;
- } else {
- return name.replaceAll("[.-]", "_");
- }
+ return name.replaceAll("[.-]", "_");
}
abstract String fileName();
@@ -72,10 +68,6 @@
return osgiReady;
}
- boolean isGenerateForBazel() {
- return generateForBazel;
- }
-
String httpUrl() {
return "";
}
@@ -92,27 +84,9 @@
return fileName().endsWith(".jar");
}
- private String extractRepo() {
- // This is a hack because the code above us already got rid of the maven repo
- // info for artifacts
- String url = url();
- if (url.startsWith("http")) {
- return url.substring(0, url.indexOf(fileName()) - mavenCoords().length() - 1);
- } else {
- return "";
- }
- }
-
- String getBazelMavenJarFragment() {
+ String getMavenJarFragment() {
System.out.println(name + " == " + httpUrl());
-
- //String repo = extractRepo();
- //String repoAttribute = "";
- //if (!"".equals(repo)) {
- // repoAttribute = " repository = \"" + repo + "\",\n";
- //}
-
- String sha256 = BuckLibGenerator.getHttpSha256(name, httpUrl());
+ String sha256 = BazelLibGenerator.getHttpSha256(name, httpUrl());
String format = "\n" +
" if \"%s\" not in native.existing_rules():\n" +
" java_import_external(\n" +
@@ -126,7 +100,7 @@
}
- public String getBuckFragment() {
+ String getFragment() {
String visibility = isPublic() ? "[ 'PUBLIC' ]" : "[]";
String output = (isJar() ? "remote_jar" : "remote_file") + " (\n" +
@@ -134,21 +108,21 @@
" out = '%s',\n" + // jar file name
" url = '%s',\n" + // maven url
" sha1 = '%s',\n" + // artifact sha
- ( isJar() && mavenCoords() != null ?
- " maven_coords = '"+ mavenCoords()+"',\n" : "" ) +
+ (isJar() && mavenCoords() != null ?
+ " maven_coords = '" + mavenCoords() + "',\n" : "") +
" visibility = %s,\n" +
")\n\n";
return String.format(output, jarTarget(), fileName(), url(), sha, visibility);
}
- private static class HTTPArtifact extends BuckArtifact {
+ private static class HTTPArtifact extends BazelArtifact {
private final String url;
private final String mavenCoords;
public HTTPArtifact(String name, String url, String sha,
- String mavenCoords, boolean osgiReady, boolean generateForBazel) {
- super(name, sha, osgiReady, generateForBazel);
+ String mavenCoords, boolean osgiReady) {
+ super(name, sha, osgiReady);
this.url = url;
this.mavenCoords = mavenCoords;
}
@@ -180,13 +154,13 @@
}
}
- private static class MavenArtifact extends BuckArtifact {
+ private static class MavenArtifact extends BazelArtifact {
private final Artifact artifact;
private final String repo;
private MavenArtifact(String name, Artifact artifact, String sha,
- String repo, boolean osgiReady, boolean generateForBazel) {
- super(name, sha, osgiReady, generateForBazel);
+ String repo, boolean osgiReady) {
+ super(name, sha, osgiReady);
this.artifact = artifact;
this.repo = repo;
}
@@ -199,8 +173,8 @@
mvnUrl.append(repo).append(':');
}
mvnUrl.append(artifact.getGroupId()).append(':')
- .append(artifact.getArtifactId()).append(':')
- .append(artifact.getExtension()).append(':');
+ .append(artifact.getArtifactId()).append(':')
+ .append(artifact.getExtension()).append(':');
if (artifact.getClassifier() != null && artifact.getClassifier().length() > 0) {
mvnUrl.append(artifact.getClassifier()).append(':');
}
@@ -234,10 +208,6 @@
@Override
String mavenCoords() {
String classifer = artifact.getClassifier();
- if (!isOsgiReady() && !isGenerateForBazel()) {
- classifer = "NON-OSGI" + classifer;
- }
-
if ("jar".equals(artifact.getExtension().toLowerCase()) &&
classifer.length() == 0) {
// shorter form
diff --git a/tools/build/libgen/src/main/java/org/onosproject/libgen/BazelLibGenerator.java b/tools/build/libgen/src/main/java/org/onosproject/libgen/BazelLibGenerator.java
new file mode 100755
index 0000000..991d4dd
--- /dev/null
+++ b/tools/build/libgen/src/main/java/org/onosproject/libgen/BazelLibGenerator.java
@@ -0,0 +1,320 @@
+/*
+ * Copyright 2016-present Open Networking 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.
+ */
+package org.onosproject.libgen;
+
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.PrintWriter;
+import java.net.Authenticator;
+import java.net.InetSocketAddress;
+import java.net.PasswordAuthentication;
+import java.net.Proxy;
+import java.net.URL;
+import java.net.URLConnection;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.time.Instant;
+import java.time.ZoneId;
+import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Stream;
+
+/**
+ * Generates a worspace inclusion file from a JSON file containing third-party
+ * library dependencies.
+ */
+public class BazelLibGenerator {
+
+ private final ObjectNode jsonRoot;
+ private final List<BazelArtifact> artifacts = new ArrayList<>();
+ private final List<BazelLibrary> libraries = new ArrayList<>();
+
+ /**
+ * Main entry point.
+ *
+ * @param args command-line arguments; JSON input file and Bazel workspace output file
+ */
+ public static void main(String[] args) throws Exception {
+ if (args.length < 2) {
+ System.err.println("sage: onos-lib-gen <input-deps.json> <output-workspace.bzl>");
+ System.exit(5);
+ }
+
+ // Parse args
+ String jsonFilePath = args[0];
+ String outputWorkspaceFilePath = args[1];
+
+ // Load and parse input JSON file
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
+ ObjectNode json = (ObjectNode) mapper.reader()
+ .readTree(new FileInputStream(jsonFilePath));
+
+ // Traverse dependencies and build a dependency graph (DAG)
+ org.onosproject.libgen.BazelLibGenerator generator = new org.onosproject.libgen.BazelLibGenerator(json).resolve();
+
+ // Write the output workspace file
+ generator.write(outputWorkspaceFilePath);
+ System.out.printf("\nFinish writing %s\n", outputWorkspaceFilePath);
+ }
+
+ public BazelLibGenerator(ObjectNode root) {
+ this.jsonRoot = root;
+ }
+
+ private BazelArtifact parseArtifact(Map.Entry<String, JsonNode> entry) {
+ String name = entry.getKey();
+ JsonNode value = entry.getValue();
+ String uri;
+ String repo = null;
+ if (value.isTextual()) {
+ uri = value.asText();
+ } else if (value.isObject()) {
+ uri = value.get("uri").asText();
+ repo = value.get("repo").asText("");
+ } else {
+ throw new RuntimeException("Unknown element for name: " + name +
+ " of type: " + value.getNodeType());
+ }
+
+ System.out.print(name + " ");
+ System.out.flush();
+ BazelArtifact bazelArtifact;
+ if (uri.startsWith("http")) {
+ String sha = getHttpSha256(name, uri);
+ bazelArtifact = BazelArtifact.getArtifact(name, uri, sha);
+ } else if (uri.startsWith("mvn")) {
+ uri = uri.replaceFirst("mvn:", "");
+ bazelArtifact = AetherResolver.getArtifact(name, uri, repo);
+ } else {
+ throw new RuntimeException("Unsupported artifact uri: " + uri);
+ }
+ System.out.println(bazelArtifact.url());
+ return bazelArtifact;
+ }
+
+ private BazelLibrary parseLibrary(Map.Entry<String, JsonNode> entry) {
+ String libraryName = entry.getKey();
+ JsonNode list = entry.getValue();
+ if (list.size() == 0) {
+ throw new RuntimeException("Empty library: " + libraryName);
+ }
+
+ List<String> libraryTargets = new ArrayList<>(list.size());
+ list.forEach(node -> {
+ String name;
+ if (node.isObject()) {
+ name = node.get("name").asText();
+ } else if (node.isTextual()) {
+ name = node.asText();
+ } else {
+ throw new RuntimeException("Unknown node type: " + node.getNodeType());
+ }
+ if (!name.contains(":")) {
+ name = ':' + name;
+ }
+ libraryTargets.add(name);
+ });
+
+ return BazelLibrary.getLibrary(libraryName, libraryTargets);
+ }
+
+ public org.onosproject.libgen.BazelLibGenerator resolve() {
+ jsonRoot.get("artifacts").fields().forEachRemaining(entry -> {
+ BazelArtifact bazelArtifact = parseArtifact(entry);
+ artifacts.add(bazelArtifact);
+ });
+
+ jsonRoot.get("libraries").fields().forEachRemaining(entry -> {
+ BazelLibrary library = parseLibrary(entry);
+ libraries.add(library);
+ });
+
+ return this;
+ }
+
+ private String generateArtifacts() {
+ StringBuilder sb = new StringBuilder();
+ StringBuilder mavenJars = new StringBuilder();
+ mavenJars.append("\ndef generated_maven_jars():");
+ artifacts.forEach(artifact -> {
+ mavenJars.append(artifact.getMavenJarFragment());
+ });
+ sb.append(mavenJars);
+ return sb.toString();
+ }
+
+ private String generateArtifactMap() {
+ StringBuilder artifactMap = new StringBuilder();
+
+ artifactMap.append("\nartifact_map = {}");
+
+ artifacts.forEach(artifact -> {
+ artifactMap.append("\nartifact_map[\"" + artifact.bazelExport() + "\"] = \"" + artifact.url(true) + "\"");
+ });
+
+ artifactMap.append(
+ "\n\n" +
+ "def maven_coordinates(label):\n" +
+ " label_string = str(label)\n" +
+ " if label_string in artifact_map:\n" +
+ " return artifact_map[label_string]\n" +
+ " if (label_string.endswith(\":jar\")):\n" +
+ " label_string = label_string.replace(\":jar\", \"\")\n" +
+ " if label_string in artifact_map:\n" +
+ " return artifact_map[label_string]\n" +
+ " if type(label) == \"string\":\n" +
+ " return \"mvn:%s:%s:%s\" % (ONOS_GROUP_ID, label_string, ONOS_VERSION)\n" +
+ " return \"mvn:%s:%s:%s\" % (ONOS_GROUP_ID, label.name, ONOS_VERSION)\n"
+ );
+
+ return artifactMap.toString();
+ }
+
+ void write(String outputFilePath) {
+ DateTimeFormatter formatter = DateTimeFormatter.RFC_1123_DATE_TIME.withZone(ZoneId.of("UTC"));
+ File outputFile = new File(outputFilePath);
+ if (!outputFile.setWritable(true)) {
+ error("Failed to make %s to writeable.", outputFilePath);
+ }
+ try (PrintWriter writer = new PrintWriter(outputFile)) {
+ writer.write(String.format(
+ "# ***** This file was auto-generated at %s. Do not edit this file manually. *****\n",
+ formatter.format(Instant.now())));
+ writer.write("# ***** Use onos-lib-gen *****\n");
+
+ writer.write("\nload(\"//tools/build/bazel:variables.bzl\", \"ONOS_GROUP_ID\", \"ONOS_VERSION\")\n\n");
+ writer.write("\nload(\"@bazel_tools//tools/build_defs/repo:java.bzl\", \"java_import_external\")\n\n");
+
+ libraries.forEach(library -> writer.print(library.getFragment()));
+ writer.print(generateArtifacts());
+ writer.print(generateArtifactMap());
+ writer.flush();
+ } catch (FileNotFoundException e) {
+ error("File not found: %s", outputFilePath);
+ }
+ if (!outputFile.setReadOnly()) {
+ error("Failed to set %s to read-only.", outputFilePath);
+ }
+ }
+
+ static String getHttpSha1(String name, String urlStr) {
+ return getHttpSha(name, urlStr, "SHA-1");
+ }
+
+ static String getHttpSha256(String name, String urlStr) {
+ return getHttpSha(name, urlStr, "SHA-256");
+ }
+
+ private static String getHttpSha(String name, String urlStr, String algorithm) {
+ try {
+ MessageDigest md = MessageDigest.getInstance(algorithm);
+ byte[] buffer = new byte[8192];
+
+ URL url = new URL(urlStr);
+
+ Optional<File> cache = Optional.ofNullable(System.getenv("ONOS_ROOT"))
+ .map(Paths::get)
+ .map(Stream::of)
+ .orElseGet(Stream::empty)
+ .map(Path::toFile)
+ .filter(File::canRead)
+ .findAny();
+
+ System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
+
+ URLConnection connection;
+ String env_http_proxy = System.getenv("HTTP_PROXY");
+ if (env_http_proxy != null) {
+ List<String> proxyHostInfo = getProxyHostInfo(env_http_proxy);
+ Proxy http_proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHostInfo.get(0),
+ Integer.valueOf(proxyHostInfo.get(1))));
+
+ if ((proxyHostInfo.get(2) != null) && (proxyHostInfo.get(3) != null)) {
+ Authenticator authenticator = new Authenticator() {
+ public PasswordAuthentication getPasswordAuthentication() {
+ return (new PasswordAuthentication(proxyHostInfo.get(2), proxyHostInfo.get(3).toCharArray()));
+ }
+ };
+
+ Authenticator.setDefault(authenticator);
+ }
+
+ connection = url.openConnection(http_proxy);
+ } else {
+ connection = url.openConnection();
+ }
+
+ connection.connect();
+ InputStream stream = connection.getInputStream();
+
+ int read;
+ while ((read = stream.read(buffer)) >= 0) {
+ md.update(buffer, 0, read);
+ }
+ StringBuilder result = new StringBuilder();
+ byte[] digest = md.digest();
+ for (byte b : digest) {
+ result.append(String.format("%02x", b));
+ }
+ return result.toString();
+ } catch (IOException | NoSuchAlgorithmException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private static List<String> getProxyHostInfo(String proxyUrl) {
+ if (proxyUrl == null) {
+ return null;
+ }
+
+ // matching pattern
+ // http://(host):(port) or http://(user):(pass)@(host):(port)
+ // https://(host):(port) or https://(user):(pass)@(host):(port)
+ Pattern p = Pattern.compile("^(http|https):\\/\\/(([^:\\@]+):([^\\@]+)\\@)?([^:\\@\\/]+):([0-9]+)\\/?$");
+ Matcher m = p.matcher(proxyUrl);
+ if (!m.find()) {
+ return null;
+ }
+
+ // matcher group 3:user 4:pass 5:host 6:port (null if not set)
+ return Arrays.asList(m.group(5), m.group(6), m.group(3), m.group(4));
+ }
+
+ private void error(String format, String... args) {
+ if (!format.endsWith("\n")) {
+ format += '\n';
+ }
+ System.err.printf(format, args);
+ System.exit(1);
+ }
+}
diff --git a/tools/build/libgen/src/main/java/org/onosproject/libgen/BazelLibrary.java b/tools/build/libgen/src/main/java/org/onosproject/libgen/BazelLibrary.java
new file mode 100644
index 0000000..1bbbd57
--- /dev/null
+++ b/tools/build/libgen/src/main/java/org/onosproject/libgen/BazelLibrary.java
@@ -0,0 +1,76 @@
+/*
+ * Copyright 2016-present Open Networking 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.
+ */
+package org.onosproject.libgen;
+
+import java.util.List;
+
+/**
+ * Representation of a java library for Bazel.
+ */
+public class BazelLibrary {
+
+ private final String name;
+ private final List<String> targets;
+
+ public static BazelLibrary getLibrary(String libraryName, List<String> libraryTargets) {
+ return new BazelLibrary(libraryName, libraryTargets);
+ }
+
+ private BazelLibrary(String name, List<String> targets) {
+ this.name = name;
+ this.targets = targets;
+ }
+
+ private String normalizeName(String name) {
+ if (!name.startsWith("//")) {
+ return name.replaceAll("[.-]", "_");
+ } else {
+ return name;
+ }
+ }
+
+ private String convertTargetName(String targetName) {
+ return normalizeName((targetName.startsWith("//") ?
+ targetName : targetName.replaceFirst(":", "@")));
+ }
+
+ private boolean isAllUpper(String s) {
+ return s.toUpperCase().equals(s);
+ }
+
+ public String name() {
+ return normalizeName(name);
+ }
+
+ public String getFragment() {
+ StringBuilder output = new StringBuilder()
+ .append(name())
+ .append(" = [");
+
+ targets.forEach(target -> {
+ if (isAllUpper(target)) {
+ output.append(String.format("] + %s + [", target.replaceFirst(":", "")));
+ } else {
+ String pathEnd = target.startsWith("//") ? "" : "//jar";
+ output.append(String.format("\n \"%s%s\",", convertTargetName(target), pathEnd));
+ }
+ });
+ output.append("\n]\n");
+
+ return output.toString();
+ }
+
+}
\ No newline at end of file
diff --git a/tools/build/libgen/src/main/java/org/onosproject/libgen/BuckLibGenerator.java b/tools/build/libgen/src/main/java/org/onosproject/libgen/BuckLibGenerator.java
deleted file mode 100755
index 9be3ef7..0000000
--- a/tools/build/libgen/src/main/java/org/onosproject/libgen/BuckLibGenerator.java
+++ /dev/null
@@ -1,382 +0,0 @@
-/*
- * Copyright 2016-present Open Networking 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.
- */
-package org.onosproject.libgen;
-
-import com.fasterxml.jackson.core.JsonParser;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.node.ObjectNode;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.PrintWriter;
-import java.net.URL;
-import java.net.URLConnection;
-import java.net.PasswordAuthentication;
-import java.net.Authenticator;
-import java.net.Proxy;
-import java.net.InetSocketAddress;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import java.time.Instant;
-import java.time.ZoneId;
-import java.time.format.DateTimeFormatter;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.stream.Stream;
-import java.util.regex.Pattern;
-import java.util.regex.Matcher;
-
-/**
- * Generates a BUCK file from a JSON file containing third-party library
- * dependencies.
- */
-public class BuckLibGenerator {
-
-// public static final String MAVEN_COORDS = "maven_coords";
-// public static final String COMPILE_ONLY = "compile_only";
-// public static final String RUNTIME_ONLY = "runtime_only";
-
- private final ObjectNode jsonRoot;
- private final List<BuckArtifact> artifacts = new ArrayList<>();
- private final List<BuckLibrary> libraries = new ArrayList<>();
-
- private static boolean generateForBazel = false;
-
- /**
- * Main entry point.
- *
- * @param args command-line arguments; JSON input file and BUCK output file
- */
- public static void main(String[] args) throws Exception {
- if (args.length < 2) {
- System.err.println("Not enough args.\n\nUSAGE: <json file> <output>");
- System.exit(5);
- }
-
- if (args.length == 3 && "--bazel".equals(args[2])) {
- generateForBazel = true;
- }
-
- // Parse args
- String jsonFilePath = args[0];
- String outputBuckPath = args[1];
-
- // Load and parse input JSON file
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
- ObjectNode json = (ObjectNode) mapper.reader()
- .readTree(new FileInputStream(jsonFilePath));
-
- // Traverse dependencies and build a dependency graph (DAG)
- BuckLibGenerator generator = new BuckLibGenerator(json).resolve();
-
- // Write the output BUCK file
- generator.write(outputBuckPath);
- System.out.printf("\nFinish writing %s\n", outputBuckPath);
- }
-
- public BuckLibGenerator(ObjectNode root) {
- this.jsonRoot = root;
- }
-
- private BuckArtifact parseArtifact(Map.Entry<String, JsonNode> entry) {
- String name = entry.getKey();
- JsonNode value = entry.getValue();
- String uri;
- String repo = null;
- if (value.isTextual()) {
- uri = value.asText();
- } else if (value.isObject()) {
- uri = value.get("uri").asText();
- repo = value.get("repo").asText("");
- } else {
- throw new RuntimeException("Unknown element for name: " + name +
- " of type: " + value.getNodeType());
- }
-
- System.out.print(name + " ");
- System.out.flush();
- BuckArtifact buckArtifact;
- if (uri.startsWith("http")) {
- String sha = generateForBazel ? getHttpSha256(name, uri) : getHttpSha1(name, uri);
- buckArtifact = BuckArtifact.getArtifact(name, uri, sha, generateForBazel);
- } else if (uri.startsWith("mvn")) {
- uri = uri.replaceFirst("mvn:", "");
-// if (repo != null) {
-// System.out.println(name + " " + repo);
-// }
- buckArtifact = AetherResolver.getArtifact(name, uri, repo, generateForBazel);
- } else {
- throw new RuntimeException("Unsupported artifact uri: " + uri);
- }
- System.out.println(buckArtifact.url());
- return buckArtifact;
- }
-
- private BuckLibrary parseLibrary(Map.Entry<String, JsonNode> entry) {
- String libraryName = entry.getKey();
- JsonNode list = entry.getValue();
- if (list.size() == 0) {
- throw new RuntimeException("Empty library: " + libraryName);
- }
-
- List<String> libraryTargets = new ArrayList<>(list.size());
- list.forEach(node -> {
- String name;
- if (node.isObject()) {
- name = node.get("name").asText();
- } else if (node.isTextual()) {
- name = node.asText();
- } else {
- throw new RuntimeException("Unknown node type: " + node.getNodeType());
- }
- if (!name.contains(":")) {
- name = ':' + name;
- }
- libraryTargets.add(name);
- });
-
- return BuckLibrary.getLibrary(libraryName, libraryTargets, generateForBazel);
- }
-
- public BuckLibGenerator resolve() {
- jsonRoot.get("artifacts").fields().forEachRemaining(entry -> {
- BuckArtifact buckArtifact = parseArtifact(entry);
- artifacts.add(buckArtifact);
-// String artifactName = buckArtifact.name();
-// if (artifacts.putIfAbsent(artifactName, buckArtifact) != null) {
-// error("Duplicate artifact: %s", artifactName);
-// }
- });
-
- jsonRoot.get("libraries").fields().forEachRemaining(entry -> {
- BuckLibrary library = parseLibrary(entry);
- libraries.add(library);
-// String libraryName = library.name();
-// if (libraries.putIfAbsent(libraryName, library) != null) {
-// error("Duplicate library: %s", libraryName);
-// }
- });
-
- return this;
- }
-
- private String generateArtifacts() {
- StringBuilder sb = new StringBuilder();
- if (!generateForBazel) {
- artifacts.forEach(artifact -> sb.append(artifact.getBuckFragment()));
- } else {
- StringBuilder mavenJars = new StringBuilder();
- mavenJars.append("\ndef generated_maven_jars():");
- artifacts.forEach(artifact -> {
- mavenJars.append(artifact.getBazelMavenJarFragment());
- });
- sb.append(mavenJars);
- }
- return sb.toString();
- }
-
- private String generateArtifactMap() {
- StringBuilder artifactMap = new StringBuilder();
-
- artifactMap.append("\nartifact_map = {}");
-
- artifacts.forEach(artifact -> {
- artifactMap.append("\nartifact_map[\"" + artifact.bazelExport() + "\"] = \"" + artifact.url(true) + "\"");
- });
-
- artifactMap.append(
- "\n\n" +
- "def maven_coordinates(label):\n" +
- " label_string = str(label)\n" +
- " if label_string in artifact_map:\n" +
- " return artifact_map[label_string]\n" +
- " if (label_string.endswith(\":jar\")):\n" +
- " label_string = label_string.replace(\":jar\", \"\")\n" +
- " if label_string in artifact_map:\n" +
- " return artifact_map[label_string]\n" +
- " if type(label) == \"string\":\n" +
- " return \"mvn:%s:%s:%s\" % (ONOS_GROUP_ID, label_string, ONOS_VERSION)\n" +
- " return \"mvn:%s:%s:%s\" % (ONOS_GROUP_ID, label.name, ONOS_VERSION)\n"
- );
-
- return artifactMap.toString();
- }
-
- void write(String outputFilePath) {
- DateTimeFormatter formatter = DateTimeFormatter.RFC_1123_DATE_TIME.withZone(ZoneId.of("UTC"));
- File outputFile = new File(outputFilePath);
- if (!outputFile.setWritable(true)) {
- error("Failed to make %s to writeable.", outputFilePath);
- }
- try (PrintWriter writer = new PrintWriter(outputFile)) {
- writer.write(String.format(
- "# ***** This file was auto-generated at %s. Do not edit this file manually. *****\n",
- formatter.format(Instant.now())));
- writer.write("# ***** Use onos-lib-gen *****\n");
-
- if (!generateForBazel) {
- // TODO - have to do this somehow for bazel
- // rule to publish the onos dependency pom
- writer.write("\npass_thru_pom(\n" +
- " name = 'onos-dependencies-pom',\n" +
- " src = 'pom.xml',\n" +
- " out = 'onos-dependencies.pom',\n" +
- " artifactId = 'onos-dependencies',\n" +
- ")\n\n");
- } else {
- writer.write("\nload(\"//tools/build/bazel:variables.bzl\", \"ONOS_GROUP_ID\", \"ONOS_VERSION\")\n\n");
- writer.write("\nload(\"@bazel_tools//tools/build_defs/repo:java.bzl\", \"java_import_external\")\n\n");
- }
-
- libraries.forEach(library -> writer.print(library.getFragment()));
- writer.print(generateArtifacts());
- if (generateForBazel) {
- writer.print(generateArtifactMap());
- }
- writer.flush();
- } catch (FileNotFoundException e) {
- error("File not found: %s", outputFilePath);
- }
- if (!outputFile.setReadOnly()) {
- error("Failed to set %s to read-only.", outputFilePath);
- }
- }
-
- static String getHttpSha1(String name, String urlStr) {
- return getHttpSha(name, urlStr, "SHA-1");
- }
-
- static String getHttpSha256(String name, String urlStr) {
- return getHttpSha(name, urlStr, "SHA-256");
- }
-
- private static String getHttpSha(String name, String urlStr, String algorithm) {
- try {
- MessageDigest md = MessageDigest.getInstance(algorithm);
- byte[] buffer = new byte[8192];
-
- URL url = new URL(urlStr);
- String fname = new File(url.getPath()).getName();
-
- // naively look for cache in buck-out/gen/
- // only works for `buck fetch`-ed artifacts
- // (=doesn't work for bndexe unless manually fetched)
- Optional<File> cache = Optional.ofNullable(System.getenv("ONOS_ROOT"))
- .map(Paths::get)
- .map(Stream::of)
- .orElseGet(Stream::empty)
- // look for remote_file, remote_jar path
- .flatMap(root -> Stream.of(root.resolve("buck-out/gen/lib/" + name + "/" + fname),
- root.resolve("buck-out/gen/lib/" + fname + "/" + fname)))
- .map(Path::toFile)
- .filter(File::canRead)
- .findAny();
-
- if (cache.isPresent() && !generateForBazel) {
- try (FileInputStream stream = new FileInputStream(cache.get())) {
- int read;
- while ((read = stream.read(buffer)) >= 0) {
- md.update(buffer, 0, read);
- }
- StringBuilder result = new StringBuilder();
- byte[] digest = md.digest();
- for (byte b : digest) {
- result.append(String.format("%02x", b));
- }
- return result.toString();
- } catch (IOException e) {
- // fall back to regular download
- }
- }
-
- System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
-
- URLConnection connection;
- String env_http_proxy = System.getenv("HTTP_PROXY");
- if (env_http_proxy != null) {
- List<String> proxyHostInfo = getProxyHostInfo(env_http_proxy);
- Proxy http_proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHostInfo.get(0),
- Integer.valueOf(proxyHostInfo.get(1))));
-
- if ((proxyHostInfo.get(2) != null) && (proxyHostInfo.get(3) != null)) {
- Authenticator authenticator = new Authenticator() {
- public PasswordAuthentication getPasswordAuthentication() {
- return (new PasswordAuthentication(proxyHostInfo.get(2), proxyHostInfo.get(3).toCharArray()));
- }
- };
-
- Authenticator.setDefault(authenticator);
- }
-
- connection = url.openConnection(http_proxy);
- } else {
- connection = url.openConnection();
- }
-
- connection.connect();
- InputStream stream = connection.getInputStream();
-
- int read;
- while ((read = stream.read(buffer)) >= 0) {
- md.update(buffer, 0, read);
- }
- StringBuilder result = new StringBuilder();
- byte[] digest = md.digest();
- for (byte b : digest) {
- result.append(String.format("%02x", b));
- }
- return result.toString();
- } catch (IOException | NoSuchAlgorithmException e) {
- throw new RuntimeException(e);
- }
- }
-
- private static List<String> getProxyHostInfo(String proxyUrl) {
- if (proxyUrl == null) {
- return null;
- }
-
- // matching pattern
- // http://(host):(port) or http://(user):(pass)@(host):(port)
- // https://(host):(port) or https://(user):(pass)@(host):(port)
- Pattern p = Pattern.compile("^(http|https):\\/\\/(([^:\\@]+):([^\\@]+)\\@)?([^:\\@\\/]+):([0-9]+)\\/?$");
- Matcher m = p.matcher(proxyUrl);
- if (!m.find()) {
- return null;
- }
-
- // matcher group 3:user 4:pass 5:host 6:port (null if not set)
- return Arrays.asList(m.group(5), m.group(6), m.group(3), m.group(4));
- }
-
- private void error(String format, String... args) {
- if (!format.endsWith("\n")) {
- format += '\n';
- }
- System.err.printf(format, args);
- System.exit(1);
- }
-}
diff --git a/tools/build/libgen/src/main/java/org/onosproject/libgen/BuckLibrary.java b/tools/build/libgen/src/main/java/org/onosproject/libgen/BuckLibrary.java
deleted file mode 100644
index bb89581..0000000
--- a/tools/build/libgen/src/main/java/org/onosproject/libgen/BuckLibrary.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Copyright 2016-present Open Networking 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.
- */
-package org.onosproject.libgen;
-
-import org.eclipse.aether.artifact.Artifact;
-
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-/**
- * Representation of a java library for Buck.
- */
-public class BuckLibrary {
-
- private final String name;
- private final List<String> targets;
- private final boolean generateForBazel;
-
- private final Set<Artifact> provided = new HashSet<>();
- private final Set<Artifact> runtime = new HashSet<>();
-
- public static BuckLibrary getLibrary(String libraryName, List<String> libraryTargets, boolean generateForBazel) {
- return new BuckLibrary(libraryName, libraryTargets, generateForBazel);
- }
-
- private BuckLibrary(String name, List<String> targets, boolean generateForBazel) {
- this.name = name;
- this.targets = targets;
- this.generateForBazel = generateForBazel;
- }
-
- private String normalizeName(String name) {
- if (!name.startsWith("//")) {
- return name.replaceAll("[.-]", "_");
- } else {
- return name;
- }
- }
-
- private String convertBuckTargetName(String buckTargetName) {
- return normalizeName((buckTargetName.startsWith("//") ?
- buckTargetName : buckTargetName.replaceFirst(":", "@")));
- }
-
- private boolean isAllUpper(String s) {
- return s.toUpperCase().equals(s);
- }
-
- public String name() {
- if (!generateForBazel) {
- return name;
- } else {
- return normalizeName(name);
- }
- }
-
- public String getFragment() {
- if (generateForBazel) {
- return getBazelFragment();
- } else {
- return getBuckFragment();
- }
- }
-
- private String getBazelFragment() {
- StringBuilder output = new StringBuilder()
- .append(name())
- .append(" = [");
-
- targets.forEach(target -> {
- if (isAllUpper(target)) {
- output.append(String.format("] + %s + [", target.replaceFirst(":", "")));
- } else {
- String pathEnd = target.startsWith("//") ? "" : "//jar";
- output.append(String.format("\n \"%s%s\",", convertBuckTargetName(target), pathEnd));
- }
- });
- output.append("\n]\n");
-
- return output.toString();
- }
-
- private String getBuckFragment() {
- StringBuilder output = new StringBuilder()
- .append("osgi_feature_group(\n")
- .append(String.format(" name = '%s',\n", name))
- .append(" visibility = ['PUBLIC'],\n")
- .append(" exported_deps = [");
-
- targets.forEach(target -> output.append(String.format("\n '%s',", target)));
- output.append("\n ],\n)\n\n");
-
- return output.toString();
- }
-}
\ No newline at end of file
diff --git a/tools/build/onos-buck b/tools/build/onos-buck
deleted file mode 100755
index 0a839e0..0000000
--- a/tools/build/onos-buck
+++ /dev/null
@@ -1,130 +0,0 @@
-#!/bin/bash
-# -----------------------------------------------------------------------------
-# Runs the custom version of Buck required by ONOS.
-# -----------------------------------------------------------------------------
-
-set -e
-
-BUCK_URL="http://repo1.maven.org/maven2/org/onosproject/onos-buck/v2018.02.09.01/buck-v2018.02.09.01.zip"
-BUCK_SHA="45d8bd28f441991257babf89f7a317edb3a2b536"
-
-# onos-yang-tools buck plugin version
-YANG_VER="2.5"
-ONOS_PLUGIN_VER="1.0.3"
-MAVEN_BASE="https://repo1.maven.org/maven2"
-MAVEN_ONOSPROJECT="$MAVEN_BASE/org/onosproject"
-
-[ "-U" = "$1" ] && shift && FORCE_UPDATE=True
-
-ROOT_DIR=${ONOS_ROOT:-"$( cd "$( dirname "${BASH_SOURCE[0]}" )/../.." && pwd )"}
-
-mkdir -p $ROOT_DIR/bin
-pushd $ROOT_DIR/bin > /dev/null
-
-if [ -n "$FORCE_UPDATE" ] || [ ! -f "buck" ] || [ "$BUCK_SHA" != "$(cat .buck_sha)" ]; then
- echo "Updating Buck..." >&2
- rm -fr .buck_version .buck_sha buck plugins
- mkdir -p cache
- BUCK_FILE=$(basename $BUCK_URL)
- # Check the local cache; download to cache if required
- [ -f "cache/$BUCK_FILE" ] || curl -o cache/$BUCK_FILE -L $BUCK_URL
- if [ -n "$(which shasum)" ]; then
- SHA=$(shasum cache/$BUCK_FILE | cut -d' ' -f1)
- if [ "$SHA" != "$BUCK_SHA" ]; then
- echo "ERROR: Downloaded SHA ($SHA) does not match expected SHA ($BUCK_SHA)" &&
- rm -f cache/$BUCK_FILE && exit 1
- else
- echo "$SHA" > .buck_sha
- fi
- else
- echo "SHA cannot be verified"
- fi
- unzip -qq cache/$BUCK_FILE
- # Kill buckd
- ps -ef | egrep buckd | grep -v egrep | cut -c7-11 | xargs kill 2>/dev/null || :
- rm -rf $ROOT_DIR/buck-out
- printf "Successfully updated Buck in $ROOT_DIR/bin/buck to $BUCK_FILE\n\n"
-fi
-
-# Fetch & install onos yang tools buck plugin
-YANG_PLUGIN_CACHE="cache/onos-yang-compiler-buck-plugin-$YANG_VER.jar"
-if hash mvn 2>/dev/null; then
- if [[ $YANG_VER = *"-SNAPSHOT" ]] || [ ! -f "$YANG_PLUGIN_CACHE" ]; then
- echo "Updating Yang plugin $YANG_VER..." >&2
- ARTIFACT="org.onosproject:onos-yang-compiler-buck-plugin:$YANG_VER"
- mvn org.apache.maven.plugins:maven-dependency-plugin:3.0.2:copy \
- -Dartifact=$ARTIFACT \
- -Dtransitive=false -Dmdep.overWriteSnapshots=true \
- -DoutputDirectory=cache > /dev/null
- fi
-else
- if [ ! -f "$YANG_PLUGIN_CACHE" ]; then
- echo "Updating Yang plugin $YANG_VER..." >&2
- if [[ $YANG_VER = *"-SNAPSHOT" ]]; then
- echo "mvn command must be installed to handle SNAPSHOT version"
- exit 1
- fi
-
- curl -o "$YANG_PLUGIN_CACHE" \
- -L $MAVEN_ONOSPROJECT/onos-yang-compiler-buck-plugin/$YANG_VER/onos-yang-compiler-buck-plugin-$YANG_VER.jar
- fi
-
- if [[ $YANG_VER != *"-SNAPSHOT" ]] && hash shasum 2>/dev/null; then
- SHA=$(shasum $YANG_PLUGIN_CACHE | cut -d' ' -f1)
- if [ ! -f "$YANG_PLUGIN_CACHE".sha1 ]; then
- curl -o "$YANG_PLUGIN_CACHE".sha1 \
- -L $MAVEN_ONOSPROJECT/onos-yang-compiler-buck-plugin/$YANG_VER/onos-yang-compiler-buck-plugin-$YANG_VER.jar.sha1
- fi
- YANG_PLUGIN_SHA=$(cat "$YANG_PLUGIN_CACHE".sha1)
- if [ "$SHA" != "$YANG_PLUGIN_SHA" ]; then
- echo "ERROR: Downloaded SHA ($SHA) did not match expected SHA ($YANG_PLUGIN_SHA)" &&
- rm -f $YANG_PLUGIN_CACHE $YANG_PLUGIN_CACHE.sha1 && exit 1
- fi
- else
- echo "SHA verification skipped"
- fi
-fi
-install -Cv "$YANG_PLUGIN_CACHE" plugins/yang.jar >/dev/null
-
-# Fetch & install onos buck plugin
-
-ONOS_PLUGIN_CACHE="cache/onos-buck-plugin-$ONOS_PLUGIN_VER.jar"
-
-if [ ! -f "$ONOS_PLUGIN_CACHE" ]; then
- echo "Updating ONOS plugin $ONOS_PLUGIN_VER..." >&2
- curl -o "$ONOS_PLUGIN_CACHE" \
- -L $MAVEN_ONOSPROJECT/onos-buck-plugin/$ONOS_PLUGIN_VER/onos-buck-plugin-$ONOS_PLUGIN_VER.jar
-fi
-
-
-if hash shasum 2>/dev/null; then
- SHA=$(shasum $ONOS_PLUGIN_CACHE | cut -d' ' -f1)
- if [ ! -f "$ONOS_PLUGIN_CACHE".sha1 ]; then
- curl -o "$ONOS_PLUGIN_CACHE".sha1 \
- -L $MAVEN_ONOSPROJECT/onos-buck-plugin/$ONOS_PLUGIN_VER/onos-buck-plugin-$ONOS_PLUGIN_VER.jar.sha1
- fi
- ONOS_PLUGIN_SHA=$(cat "$ONOS_PLUGIN_CACHE".sha1)
- if [ "$SHA" != "$ONOS_PLUGIN_SHA" ]; then
- echo "ERROR: Downloaded SHA ($SHA) did not match expected SHA ($ONOS_PLUGIN_SHA)" &&
- rm -f $ONOS_PLUGIN_CACHE $ONOS_PLUGIN_CACHE.sha1 && exit 1
- fi
-else
- echo "SHA verification skipped"
-fi
-install -Cv "$ONOS_PLUGIN_CACHE" plugins/onos.jar >/dev/null
-
-popd > /dev/null
-
-BUCK=$ROOT_DIR/bin/buck
-
-if [ "${ONOS_NO_BUCKD:-1}" == "1" ]; then
- export NO_BUCKD=1
-fi
-
-# HACK: Clean-up frequent problem-causers from buck-out
-#rm -fr \
-# $ONOS_ROOT/buck-out/bin/lib/.netty \
-# $ONOS_ROOT/buck-out/bin/lib/.KRYO
-
-# Finally, run the Buck command...
-$BUCK "$@"
diff --git a/tools/build/onos-buck-build-docs b/tools/build/onos-buck-build-docs
deleted file mode 100755
index 658a539..0000000
--- a/tools/build/onos-buck-build-docs
+++ /dev/null
@@ -1,12 +0,0 @@
-#!/bin/bash
-# -----------------------------------------------------------------------------
-# Builds the ONOS Java API docs with buck.
-# -----------------------------------------------------------------------------
-
-set -e
-
-[ ! -d "$ONOS_ROOT" ] && echo "ONOS_ROOT is not defined" >&2 && exit 1
-. $ONOS_ROOT/tools/build/envDefaults
-
-onos-buck build `onos-buck query "filter('.*-javadoc', '//...')"`
-
diff --git a/tools/build/onos-buck-publish b/tools/build/onos-buck-publish
deleted file mode 100755
index a4db536..0000000
--- a/tools/build/onos-buck-publish
+++ /dev/null
@@ -1,53 +0,0 @@
-#!/bin/bash
-#
-# Script that queries buck for main and test artifacts and publishes them to
-# a remote Maven repository. Main artifacts are published with javadoc and sources
-# jars and auto-generated pom.xml files. Test artifacts are published as compiled
-# jars only. All artifacts are signed.
-#
-
-ARTIFACT_PUB=$(mktemp /tmp/onos-publish.XXXXX) &&
- echo "Created temp file for artifact publish: $ARTIFACT_PUB" ||
- { echo "Failed to create temp file"; exit 1; }
-
-TEST_PUB=$(mktemp /tmp/onos-publish-tests.XXXXX) &&
- echo "Created temp file for test artifact publish: $TEST_PUB" ||
- { echo "Failed to create temp file"; exit 1; }
-
-trap "rm -f $ARTIFACT_PUB $ARTIFACT_PUB.bak $TEST_PUB $TEST_PUB.bak" EXIT
-
-set -e
-set -x
-
-# Prepare artifact publish commands
-cat ${ONOS_ROOT}/tools/build/publish-target-list | grep -v '#' >> $ARTIFACT_PUB
-sed -i.bak 's/^/onos-buck publish --to-maven-central --include-source --include-javadoc --sign /g' $ARTIFACT_PUB
-cp $ARTIFACT_PUB $ARTIFACT_PUB.bak
-( echo "set -e"; cat $ARTIFACT_PUB.bak ) >$ARTIFACT_PUB
-
-# Print commands to be run and then run them
-cat $ARTIFACT_PUB
-bash $ARTIFACT_PUB
-
-# Prepare feature commands
-onos-buck query "filter('.*-feature', deps(filter('.*-oar', deps('//tools/package:onos-package', 1)),1))" > $TEST_PUB
-echo "//tools/package:onos-features" >> $TEST_PUB
-
-# Prepare test commands
-cat ${ONOS_ROOT}/tools/build/publish-test-target-list | grep -v '#' >> $TEST_PUB
-sed -i.bak 's#^#onos-buck publish --to-maven-central --sign #g' $TEST_PUB
-cp $TEST_PUB $TEST_PUB.bak
-( echo "set -e"; cat $TEST_PUB.bak ) >$TEST_PUB
-
-# Print commands to be run and then run them
-cat $TEST_PUB
-bash $TEST_PUB
-
-# stage ONOS poms
-onos-buck publish --to-maven-central --sign //:top-level-pom
-onos-buck publish --to-maven-central --sign //lib:onos-dependencies-pom
-
-if ! grep "maven_url" $ONOS_ROOT/.buckconfig.local | grep -v '#' | grep -q snapshots ; then
- # Close the staging area
- onos-close-staging
-fi
diff --git a/tools/build/onos-buck-publish-local b/tools/build/onos-buck-publish-local
deleted file mode 100755
index 6c52db7..0000000
--- a/tools/build/onos-buck-publish-local
+++ /dev/null
@@ -1,10 +0,0 @@
-#!/bin/bash
-
-set -e
-onos-buck -V
-
-for package in `cat ${ONOS_ROOT}/tools/build/publish-target-list ${ONOS_ROOT}/tools/build/publish-test-target-list | grep -v '#'`; do
- onos-buck publish --to-local-repo ${package}
-done
-
-
diff --git a/tools/build/onos-lib-gen b/tools/build/onos-lib-gen
index 82ddc5f..522c0ae 100755
--- a/tools/build/onos-lib-gen
+++ b/tools/build/onos-lib-gen
@@ -9,7 +9,7 @@
cd $ONOS_ROOT
REPO=${M2_REPO:-~/.m2/repository}
-VER=1.5
+VER=1.6-SNAPSHOT
ARTIFACT=org/onosproject/onos-libgen/$VER/onos-libgen-$VER.jar
JAR=$REPO/$ARTIFACT
@@ -21,4 +21,4 @@
[ -f $JAR ] && printf "Done.\n"
fi
-[ -z "$1" -o "$1" = "bazel" ] && java -jar $JAR lib/deps.json tools/build/bazel/generate_workspace.bzl --bazel
\ No newline at end of file
+java -jar $JAR lib/deps.json tools/build/bazel/generate_workspace.bzl --bazel
\ No newline at end of file
diff --git a/tools/build/push-buck-plugin b/tools/build/push-buck-plugin
deleted file mode 100755
index 97df2e5..0000000
--- a/tools/build/push-buck-plugin
+++ /dev/null
@@ -1,31 +0,0 @@
-#!/bin/bash
-# -----------------------------------------------------------------------------
-# Builds and uploads an ONOS buck plugin release
-# -----------------------------------------------------------------------------
-
-if [ $# -ne 1 ]; then
- echo "Usage: push-buck-plugin version"
- exit 1
-fi
-
-PLUGIN_VERSION="$1"
-PLUGIN_FILE="buck-out/gen/tools/build/buck-plugin/onos.jar"
-UPLOAD_BASE="https://oss.sonatype.org/service/local/staging/deploy/maven2/org/onosproject/onos-buck-plugin/$PLUGIN_VERSION"
-
-# Build the buck plugin
-onos-buck build //tools/build/buck-plugin:onos
-
-# Make the signature file
-gpg --armor --detach-sig $PLUGIN_FILE
-
-# Make the MD5 checksum file
-md5 -q $PLUGIN_FILE >$PLUGIN_FILE.md5
-
-# Make the SHA1 checksum file
-( shasum $PLUGIN_FILE | cut -d' ' -f1 ) > $PLUGIN_FILE.sha1
-
-curl -v -u "$SONATYPE_USER:$SONATYPE_PASSWORD" --upload-file $PLUGIN_FILE $UPLOAD_BASE/onos-buck-plugin-$PLUGIN_VERSION.jar
-curl -v -u "$SONATYPE_USER:$SONATYPE_PASSWORD" --upload-file $PLUGIN_FILE.asc $UPLOAD_BASE/onos-buck-plugin-$PLUGIN_VERSION.jar.asc
-curl -v -u "$SONATYPE_USER:$SONATYPE_PASSWORD" --upload-file $PLUGIN_FILE.md5 $UPLOAD_BASE/onos-buck-plugin-$PLUGIN_VERSION.jar.md5
-curl -v -u "$SONATYPE_USER:$SONATYPE_PASSWORD" --upload-file $PLUGIN_FILE.sha1 $UPLOAD_BASE/onos-buck-plugin-$PLUGIN_VERSION.jar.sha1
-
diff --git a/tools/build/buck-plugin/BUILD b/tools/build/swagger/BUILD
similarity index 74%
rename from tools/build/buck-plugin/BUILD
rename to tools/build/swagger/BUILD
index e8d2c21..fff3296 100644
--- a/tools/build/buck-plugin/BUILD
+++ b/tools/build/swagger/BUILD
@@ -8,8 +8,8 @@
java_binary(
name = SWAGGER_EXECUTABLE,
- srcs = glob(["src/main/java/org/onosproject/onosjar/SwaggerGenerator.java"]),
- main_class = "org.onosproject.onosjar.SwaggerGenerator",
+ srcs = glob(["src/main/java/org/onosproject/swagger/SwaggerGenerator.java"]),
+ main_class = "org.onosproject.swagger.SwaggerGenerator",
resources = glob(["src/main/resources/registrator.javat"]),
visibility = ["//visibility:public"],
deps = COMPILE_DEPS,
diff --git a/tools/build/buck-plugin/src/main/java/org/onosproject/onosjar/SwaggerGenerator.java b/tools/build/swagger/src/main/java/org/onosproject/swagger/SwaggerGenerator.java
similarity index 99%
rename from tools/build/buck-plugin/src/main/java/org/onosproject/onosjar/SwaggerGenerator.java
rename to tools/build/swagger/src/main/java/org/onosproject/swagger/SwaggerGenerator.java
index 518bf8c..f2c6658 100644
--- a/tools/build/buck-plugin/src/main/java/org/onosproject/onosjar/SwaggerGenerator.java
+++ b/tools/build/swagger/src/main/java/org/onosproject/swagger/SwaggerGenerator.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.onosproject.onosjar;
+package org.onosproject.swagger;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
diff --git a/tools/build/buck-plugin/src/main/resources/registrator.javat b/tools/build/swagger/src/main/resources/registrator.javat
similarity index 100%
rename from tools/build/buck-plugin/src/main/resources/registrator.javat
rename to tools/build/swagger/src/main/resources/registrator.javat
diff --git a/tools/package/BUCK b/tools/package/BUCK
deleted file mode 100644
index b7adf19..0000000
--- a/tools/package/BUCK
+++ /dev/null
@@ -1,48 +0,0 @@
-KARAF = '//lib:apache-karaf'
-BRANDING = '//tools/package/branding:onos-tools-package-branding'
-PATCHES = '//lib:apache-karaf-patches'
-
-#TODO move to buck-tools
-export_file (
- name = 'onos-prep-karaf',
-)
-
-genrule(
- name = 'onos-karaf',
- srcs = glob(['bin/*', 'etc/*', 'init/*', 'runtime/bin/*']),
- bash = '$(location :onos-prep-karaf) $OUT $(location %s) %s $(location %s) $(location %s)'\
- % (KARAF, ONOS_VERSION, BRANDING, PATCHES),
- out = 'karaf.zip',
-)
-
-staged_repos = ['$(location %s-repo)' % f for f in FEATURES]
-staged_apps = ['$(location %s)' % a for a in APPS]
-
-# feature_coords = 'foo:bar:1.3'
-sources = [ '$(location //tools/package/features:onos-features)', ]
-sources += staged_repos + staged_apps
-
-tar_file(
- name = 'onos-package-runtime',
- srcs = glob(['runtime/bin/*']),
- root = 'tools/package',
- out = 'package-runtime.tar.gz',
- visibility = [ 'PUBLIC' ],
-)
-
-genrule(
- name = 'onos-package',
- srcs = glob(['bin/*', 'etc/*', 'init/*', 'config/*', 'runtime/bin/*']),
- out = 'onos.tar.gz',
- bash = '$(exe //buck-tools:onos-stage) $OUT ' + ONOS_VERSION + ' $(location :onos-karaf) ' + ' '.join(sources),
- visibility = [ 'PUBLIC' ],
-)
-
-genrule(
- name = 'onos-run',
- out = 'onos-run',
- srcs = [ 'onos-run-karaf' ],
- bash = 'sed "s#ONOS_TAR=#ONOS_TAR=$(location :onos-package)#" $SRCS > $OUT; chmod +x $OUT',
- executable = True,
- visibility = [ 'PUBLIC' ],
-)
diff --git a/tools/package/branding/BUCK b/tools/package/branding/BUCK
deleted file mode 100644
index 3a2e916..0000000
--- a/tools/package/branding/BUCK
+++ /dev/null
@@ -1,2 +0,0 @@
-osgi_jar()
-# Really... that's it
\ No newline at end of file
diff --git a/tools/package/features/BUCK b/tools/package/features/BUCK
deleted file mode 100644
index 3744cc4..0000000
--- a/tools/package/features/BUCK
+++ /dev/null
@@ -1,176 +0,0 @@
-osgi_feature (
- name="onos-thirdparty-base",
- title="ONOS 3rd party dependencies",
- required_features = [],
- included_bundles = [
- '//lib:atomix',
- '//lib:atomix-cluster',
- '//lib:atomix-gossip',
- '//lib:atomix-primary-backup',
- '//lib:atomix-primitive',
- '//lib:atomix-raft',
- '//lib:atomix-storage',
- '//lib:atomix-utils',
- '//lib:classgraph',
- '//lib:commons-lang',
- '//lib:commons-lang3',
- '//lib:commons-text',
- '//lib:commons-configuration',
- '//lib:fast-classpath-scanner',
- '//lib:com_google_guava_guava',
- '//lib:io_netty_netty',
- '//lib:io_netty_netty_common',
- '//lib:io_netty_netty_buffer',
- '//lib:io_netty_netty_transport',
- '//lib:io_netty_netty_handler',
- '//lib:io_netty_netty_codec',
- '//lib:io_netty_netty_transport_native_unix_common',
- '//lib:io_netty_netty_transport-native-epoll',
- '//lib:io_netty_netty_resolver',
- '//lib:commons-pool',
- '//lib:commons-math3',
- '//lib:joda-time',
- '//lib:metrics-core',
- '//lib:metrics-json',
- '//lib:minimal-json',
- '//lib:kryo',
- '//lib:reflectasm',
- '//lib:asm',
- '//lib:minlog',
- '//lib:objenesis',
- '//lib:jackson-core',
- '//lib:jackson-annotations',
- '//lib:jackson-databind',
- '//lib:commons-collections',
- '//lib:typesafe-config',
- '//lib:concurrent-trees',
- '//lib:commons-io',
- '//lib:jersey-client',
- '//lib:mapdb',
- '//lib:bcpkix-jdk15on',
- '//lib:bcprov-jdk15on',
- '//lib:commons-jxpath', # FIXME: move xpath lib dependency to the right place
- '//lib:commons-beanutils', # jxpath dependency
- '//lib:jdom', # jxpath dependency
- '//lib:sigar',
- ]
-)
-
-osgi_feature (
- name="onos-thirdparty-web",
- title="ONOS 3rd party dependencies for web apps",
- required_features = [ 'war', 'onos-thirdparty-base' ],
- included_bundles = [
- '//lib:jersey-common',
- '//lib:javax.annotation-api-mvn',
- '//lib:javax.ws.rs-api',
- '//lib:hk2-api',
- '//lib:hk2-locator',
- '//lib:hk2-osgi-resource-locator',
- '//lib:javax.inject',
- '//lib:jersey-server',
- '//lib:jersey-hk2',
- '//lib:aopalliance-repackaged',
- '//lib:hk2-utils',
- '//lib:validation-api',
- '//lib:javassist',
- '//lib:jersey-container-servlet',
- '//lib:jersey-container-servlet-core',
- '//lib:jersey-media-multipart',
- '//lib:mimepull',
- ]
-)
-
-osgi_feature (
- name = 'onos-api',
- title = 'ONOS services and model API',
- required_features = ['scr', 'onos-thirdparty-base'],
- included_bundles =[
- '//utils/misc:onlab-misc',
- '//utils/osgi:onlab-osgi',
- '//core/api:onos-api',
- '//incubator/api:onos-incubator-api',
- ]
-)
-
-osgi_feature (
- name='onos-core',
- title='ONOS core components',
- required_features = ['onos-api'],
- included_bundles = [
- '//core/net:onos-core-net',
- '//core/common:onos-core-common',
- '//core/store/dist:onos-core-dist',
- '//core/store/primitives:onos-core-primitives',
- '//core/store/persistence:onos-core-persistence',
- '//core/store/serializers:onos-core-serializers',
- ]
-)
-
-osgi_feature (
- name='onos-incubator',
- title='ONOS core incubator components',
- required_features = ['onos-core'],
- included_bundles = [
- '//incubator/net:onos-incubator-net',
- '//incubator/store:onos-incubator-store',
- '//incubator/rpc:onos-incubator-rpc',
- ]
-)
-
-osgi_feature (
- name="onos-rest",
- title="ONOS REST API components",
- required_features = ['onos-api', 'onos-thirdparty-web'],
- included_bundles = [
- '//utils/rest:onlab-rest',
- '//web/api:onos-rest',
- ]
-)
-
-osgi_feature (
- name = 'onos-gui',
- title = 'ONOS GUI console components',
- required_features = ['onos-api', 'onos-thirdparty-web'],
- included_bundles = [
- '//lib:jetty-websocket',
- '//utils/rest:onlab-rest',
- '//web/gui:onos-gui',
- ]
-)
-
-osgi_feature (
- name = 'onos-gui2',
- title = 'ONOS GUI2 console components',
- required_features = ['onos-api', 'onos-thirdparty-web'],
- included_bundles = [
- '//lib:jetty-websocket',
- '//utils/rest:onlab-rest',
- '//web/gui2:onos-gui2',
- ]
-)
-
-osgi_feature (
- name = 'onos-cli',
- title="ONOS admin command console components",
- required_features = ['onos-api'],
- included_bundles = [
- '//cli:onos-cli',
- ]
-)
-
-osgi_feature (
- name = 'onos-security',
- title="Security-Mode ONOS",
- required_features = ['onos-api'],
- included_bundles = [
- '//lib:org.apache.felix.framework.security',
- '//core/security:onos-security',
- ]
-)
-
-compile_features(
- name = 'onos-features',
- features = FEATURES,
- maven_coords = 'org.onosproject:onos-features:xml:features:' + ONOS_VERSION,
-)