2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2016-2018 Ericsson. All rights reserved.
4 * Modifications Copyright (C) 2020 Nordix Foundation.
5 * ================================================================================
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
18 * SPDX-License-Identifier: Apache-2.0
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.apex.core.infrastructure.java.compile.singleclass;
24 import java.util.Arrays;
25 import java.util.List;
26 import javax.tools.Diagnostic;
27 import javax.tools.DiagnosticCollector;
28 import javax.tools.JavaCompiler;
29 import javax.tools.JavaFileObject;
30 import javax.tools.ToolProvider;
31 import org.onap.policy.apex.core.infrastructure.java.JavaHandlingException;
32 import org.slf4j.ext.XLogger;
33 import org.slf4j.ext.XLoggerFactory;
36 * The Class SingleClassBuilder is used to compile the Java code for a Java object and to create an instance of the
39 * @author Liam Fallon (liam.fallon@ericsson.com)
41 public class SingleClassBuilder {
42 // Logger for this class
43 private static final XLogger LOGGER = XLoggerFactory.getXLogger(SingleClassBuilder.class);
45 // The class name and source code for the class that we are compiling and instantiating
46 private final String className;
47 private final String sourceCode;
49 // This specialized JavaFileManager handles class loading for the single Java class
50 private SingleFileManager singleFileManager = null;
53 * Instantiates a new single class builder.
55 * @param className the class name
56 * @param sourceCode the source code
58 public SingleClassBuilder(final String className, final String sourceCode) {
59 // Save the fields of the class
60 this.className = className;
61 this.sourceCode = sourceCode;
65 * Compile the single class into byte code.
67 * @throws JavaHandlingException Thrown on compilation errors or handling errors on the single Java class
69 public void compile() throws JavaHandlingException {
70 // Get the list of compilation units, there is only one here
71 final List<? extends JavaFileObject> compilationUnits =
72 Arrays.asList(new SingleClassCompilationUnit(className, sourceCode));
74 // Allows us to get diagnostics from the compilation
75 final DiagnosticCollector<JavaFileObject> diagnosticListener = new DiagnosticCollector<>();
77 // Get the Java compiler
78 final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
80 // Set up the target file manager and call the compiler
81 singleFileManager = new SingleFileManager(compiler, new SingleClassByteCodeFileObject(className));
82 final JavaCompiler.CompilationTask task =
83 compiler.getTask(null, singleFileManager, diagnosticListener, null, null, compilationUnits);
85 // Check if the compilation worked
86 if (Boolean.FALSE.equals(task.call())) {
87 final StringBuilder builder = new StringBuilder();
88 for (final Diagnostic<? extends JavaFileObject> diagnostic : diagnosticListener.getDiagnostics()) {
89 builder.append("code:");
90 builder.append(diagnostic.getCode());
91 builder.append(", kind:");
92 builder.append(diagnostic.getKind());
93 builder.append(", position:");
94 builder.append(diagnostic.getPosition());
95 builder.append(", start position:");
96 builder.append(diagnostic.getStartPosition());
97 builder.append(", end position:");
98 builder.append(diagnostic.getEndPosition());
99 builder.append(", source:");
100 builder.append(diagnostic.getSource());
101 builder.append(", message:");
102 builder.append(diagnostic.getMessage(null));
103 builder.append("\n");
106 String message = "error compiling Java code for class \"" + className + "\": " + builder.toString();
107 LOGGER.warn(message);
108 throw new JavaHandlingException(message);
113 * Create a new instance of the Java class using its byte code definition.
115 * @return A new instance of the object
116 * @throws JavaHandlingException on errors creating the object
118 public Object createObject()
119 throws InstantiationException, IllegalAccessException, ClassNotFoundException, JavaHandlingException {
120 if (singleFileManager == null) {
121 String message = "error instantiating instance for class \"" + className + "\": code may not be compiled";
122 LOGGER.warn(message);
123 throw new JavaHandlingException(message);
127 return singleFileManager.getClassLoader(null).findClass(className).getDeclaredConstructor().newInstance();
128 } catch (Exception e) {
129 return new JavaHandlingException("could not create java class", e);