7695e29fde18bbd41572f371485fa93388e64cab
[policy/apex-pdp.git] / core / core-infrastructure / src / main / java / org / onap / policy / apex / core / infrastructure / java / compile / singleclass / SingleClassBuilder.java
1 /*-
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
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
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.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.apex.core.infrastructure.java.compile.singleclass;
23
24 import java.util.Arrays;
25 import java.util.List;
26
27 import javax.tools.Diagnostic;
28 import javax.tools.DiagnosticCollector;
29 import javax.tools.JavaCompiler;
30 import javax.tools.JavaFileObject;
31 import javax.tools.ToolProvider;
32
33 import org.onap.policy.apex.core.infrastructure.java.JavaHandlingException;
34 import org.slf4j.ext.XLogger;
35 import org.slf4j.ext.XLoggerFactory;
36
37 /**
38  * The Class SingleClassBuilder is used to compile the Java code for a Java object and to create an instance of the
39  * object.
40  *
41  * @author Liam Fallon (liam.fallon@ericsson.com)
42  */
43 public class SingleClassBuilder {
44     // Logger for this class
45     private static final XLogger LOGGER = XLoggerFactory.getXLogger(SingleClassBuilder.class);
46
47     // The class name and source code for the class that we are compiling and instantiating
48     private final String className;
49     private final String sourceCode;
50
51     // This specialized JavaFileManager handles class loading for the single Java class
52     private SingleFileManager singleFileManager = null;
53
54     /**
55      * Instantiates a new single class builder.
56      *
57      * @param className the class name
58      * @param sourceCode the source code
59      */
60     public SingleClassBuilder(final String className, final String sourceCode) {
61         // Save the fields of the class
62         this.className = className;
63         this.sourceCode = sourceCode;
64     }
65
66     /**
67      * Compile the single class into byte code.
68      *
69      * @throws JavaHandlingException Thrown on compilation errors or handling errors on the single Java class
70      */
71     public void compile() throws JavaHandlingException {
72         // Get the list of compilation units, there is only one here
73         final List<? extends JavaFileObject> compilationUnits =
74                 Arrays.asList(new SingleClassCompilationUnit(className, sourceCode));
75
76         // Allows us to get diagnostics from the compilation
77         final DiagnosticCollector<JavaFileObject> diagnosticListener = new DiagnosticCollector<>();
78
79         // Get the Java compiler
80         final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
81
82         // Set up the target file manager and call the compiler
83         singleFileManager = new SingleFileManager(compiler, new SingleClassByteCodeFileObject(className));
84         final JavaCompiler.CompilationTask task =
85                 compiler.getTask(null, singleFileManager, diagnosticListener, null, null, compilationUnits);
86
87         // Check if the compilation worked
88         if (Boolean.FALSE.equals(task.call())) {
89             final StringBuilder builder = new StringBuilder();
90             for (final Diagnostic<? extends JavaFileObject> diagnostic : diagnosticListener.getDiagnostics()) {
91                 builder.append("code:");
92                 builder.append(diagnostic.getCode());
93                 builder.append(", kind:");
94                 builder.append(diagnostic.getKind());
95                 builder.append(", position:");
96                 builder.append(diagnostic.getPosition());
97                 builder.append(", start position:");
98                 builder.append(diagnostic.getStartPosition());
99                 builder.append(", end position:");
100                 builder.append(diagnostic.getEndPosition());
101                 builder.append(", source:");
102                 builder.append(diagnostic.getSource());
103                 builder.append(", message:");
104                 builder.append(diagnostic.getMessage(null));
105                 builder.append("\n");
106             }
107
108             String message = "error compiling Java code for class \"" + className + "\": " + builder.toString();
109             LOGGER.warn(message);
110             throw new JavaHandlingException(message);
111         }
112     }
113
114     /**
115      * Create a new instance of the Java class using its byte code definition.
116      *
117      * @return A new instance of the object
118      * @throws JavaHandlingException on errors creating the object
119      */
120     public Object createObject()
121             throws InstantiationException, IllegalAccessException, ClassNotFoundException, JavaHandlingException {
122         if (singleFileManager == null) {
123             String message = "error instantiating instance for class \"" + className + "\": code may not be compiled";
124             LOGGER.warn(message);
125             throw new JavaHandlingException(message);
126         }
127
128         try {
129             return singleFileManager.getClassLoader(null).findClass(className).getDeclaredConstructor().newInstance();
130         } catch (Exception e) {
131             return new JavaHandlingException("could not create java class", e);
132         }
133
134     }
135 }