Project

General

Profile

Revision 7

Added by Willibald K. over 8 years ago

changing java, cpp, hpp files to unix line endings

View differences:

JavaCodeCompiler.java
1
/**

2
  *

3
  *                      OOAS Compiler

4
  *

5
  *       Copyright 2015, AIT Austrian Institute of Technology.

6
  * This code is based on the C# Version of the OOAS Compiler, which is

7
  * copyright 2015 by the Institute of Software Technology, Graz University

8
  * of Technology with portions copyright by the AIT Austrian Institute of

9
  * Technology. All rights reserved.

10
  *

11
  * SEE THE "LICENSE" FILE FOR THE TERMS UNDER WHICH THIS FILE IS PROVIDED.

12
  *

13
  * If you modify the file please update the list of contributors below to in-

14
  * clude your name. Please also stick to the coding convention of using TABs

15
  * to do the basic (block-level) indentation and spaces for anything after

16
  * that. (Enable the display of special chars and it should be pretty obvious

17
  * what this means.) Also, remove all trailing whitespace.

18
  *

19
  * Contributors:

20
  *               Willibald Krenn (AIT)

21
  *               Stephan Zimmerer (AIT)

22
  *               Markus Demetz (AIT)

23
  *               Christoph Czurda (AIT)

24
  *

25
  */

1
/**
2
  *
3
  *                      OOAS Compiler
4
  *
5
  *       Copyright 2015, AIT Austrian Institute of Technology.
6
  * This code is based on the C# Version of the OOAS Compiler, which is
7
  * copyright 2015 by the Institute of Software Technology, Graz University
8
  * of Technology with portions copyright by the AIT Austrian Institute of
9
  * Technology. All rights reserved.
10
  *
11
  * SEE THE "LICENSE" FILE FOR THE TERMS UNDER WHICH THIS FILE IS PROVIDED.
12
  *
13
  * If you modify the file please update the list of contributors below to in-
14
  * clude your name. Please also stick to the coding convention of using TABs
15
  * to do the basic (block-level) indentation and spaces for anything after
16
  * that. (Enable the display of special chars and it should be pretty obvious
17
  * what this means.) Also, remove all trailing whitespace.
18
  *
19
  * Contributors:
20
  *               Willibald Krenn (AIT)
21
  *               Stephan Zimmerer (AIT)
22
  *               Markus Demetz (AIT)
23
  *               Christoph Czurda (AIT)
24
  *
25
  */
26 26

  
27 27

  
28
package org.momut.ooas.codegen.java;
29

  
30
import java.io.ByteArrayInputStream;
31
import java.io.ByteArrayOutputStream;
32
import java.io.IOException;
33
import java.io.InputStream;
34
import java.io.OutputStream;
35
import java.io.PrintWriter;
36
import java.io.Writer;
37
import java.lang.reflect.Method;
38
import java.net.URI;
39
import java.util.Arrays;
40
import java.util.HashMap;
41
import java.util.List;
42
import java.util.Map;
28
package org.momut.ooas.codegen.java;
43 29

  
44
import javax.tools.FileObject;
45
import javax.tools.ForwardingJavaFileManager;
46
import javax.tools.JavaCompiler;
47
import javax.tools.JavaFileObject;
48
import javax.tools.SimpleJavaFileObject;
49
import javax.tools.StandardJavaFileManager;
30
import java.io.ByteArrayInputStream;
31
import java.io.ByteArrayOutputStream;
32
import java.io.IOException;
33
import java.io.InputStream;
34
import java.io.OutputStream;
35
import java.io.PrintWriter;
36
import java.io.Writer;
37
import java.lang.reflect.Method;
38
import java.net.URI;
39
import java.util.Arrays;
40
import java.util.HashMap;
41
import java.util.List;
42
import java.util.Map;
50 43

  
51
import org.eclipse.jdt.internal.compiler.tool.EclipseCompiler;
44
import javax.tools.FileObject;
45
import javax.tools.ForwardingJavaFileManager;
46
import javax.tools.JavaCompiler;
47
import javax.tools.JavaFileObject;
48
import javax.tools.SimpleJavaFileObject;
49
import javax.tools.StandardJavaFileManager;
50

  
51
import org.eclipse.jdt.internal.compiler.tool.EclipseCompiler;
52 52
import org.momut.ooas.parser.ParserError;
53 53
import org.momut.ooas.parser.ParserState;
54

  
55
/**
56
 * This code is based on a blog entry of Morten Nobel.
57
 *
58
 * http://blog.nobel-joergensen.com/2008/07/16/using-eclipse-compiler-to-create-dynamic-java-objects-2/
59
 *
60
 */
61
/// <summary>
62
/// This class can be used to execute dynamic uncompiled code at runtime
63
/// This class is not exception safe, all function calls should be exception handled.
64
/// </summary>
65
public class JavaCodeCompiler
66
{
67
	private static class MemorySource extends SimpleJavaFileObject {
68
		private final String src;
69
		public MemorySource(String name, String src) {
70
			super(URI.create("file:///" + name + ".java"), Kind.SOURCE);
71
			this.src = src;
72
		}
73
		@Override
74
		public CharSequence getCharContent(boolean ignoreEncodingErrors) {
75
			return src;
76
		}
77
		@Override
78
		public OutputStream openOutputStream() {
79
			throw new IllegalStateException();
80
		}
81
		@Override
82
		public InputStream openInputStream() {
83
			return new ByteArrayInputStream(src.getBytes());
84
		}
85
	}
86

  
87
	private static class SpecialJavaFileManager extends ForwardingJavaFileManager<StandardJavaFileManager> {
88
		private final SpecialClassLoader xcl;
89
		public SpecialJavaFileManager(StandardJavaFileManager sjfm, SpecialClassLoader xcl) {
90
			super(sjfm);
91
			this.xcl = xcl;
92
		}
93
		@Override
94
		public JavaFileObject getJavaFileForOutput(Location location, String name, JavaFileObject.Kind kind, FileObject sibling) throws IOException {
95
			final MemoryByteCode mbc = new MemoryByteCode(name);
96
			xcl.addClass(name, mbc);
97
			return mbc;
98
		}
99
		@Override
100
		public ClassLoader getClassLoader(Location location) {
101
			return xcl;
102
		}
103
	}
104

  
105
	private static class MemoryByteCode extends SimpleJavaFileObject {
106
		private ByteArrayOutputStream baos;
107
		public MemoryByteCode(String name) {
108
			super(URI.create("byte:///" + name + ".class"), Kind.CLASS);
109
		}
110
		@Override
111
		public CharSequence getCharContent(boolean ignoreEncodingErrors) {
112
			throw new IllegalStateException();
113
		}
114
		@Override
115
		public OutputStream openOutputStream() {
116
			baos = new ByteArrayOutputStream();
117
			return baos;
118
		}
119
		@Override
120
		public InputStream openInputStream() {
121
			throw new IllegalStateException();
122
		}
123
		public byte[] getBytes() {
124
			return baos.toByteArray();
125
		}
126
	}
127

  
128
	private static class SpecialClassLoader extends ClassLoader {
129
		private final Map<String,MemoryByteCode> m = new HashMap<String, MemoryByteCode>();
130
		@Override
131
		protected Class<?> findClass(String name) throws ClassNotFoundException {
132
			MemoryByteCode mbc = m.get(name);
133
			if (mbc==null){
134
				mbc = m.get(name.replace(".","/"));
135
				if (mbc==null){
136
					return super.findClass(name);
137
				}
138
			}
139
			return defineClass(name, mbc.getBytes(), 0, mbc.getBytes().length);
140
		}
141
		public void addClass(String name, MemoryByteCode mbc) {
142
			m.put(name, mbc);
143
		}
144
	}
145

  
146
	public static Class<?> compileCode(String code, String className, String packageName, ParserState parserState)
147
	{
148
		try {
149
			final JavaCompiler javac = new EclipseCompiler();
150

  
151
			final StandardJavaFileManager sjfm = javac.getStandardFileManager(null, null, null);
152
			final SpecialClassLoader cl = new SpecialClassLoader();
153
			final SpecialJavaFileManager fileManager = new SpecialJavaFileManager(sjfm, cl);
154
			final List<String> options = Arrays.asList(new String[]{"-1.7"});
155

  
156
			final List<MemorySource> compilationUnits = Arrays.asList(new MemorySource(className, code));
157
//			DiagnosticListener<?> dianosticListener = null;
158
			final Iterable<String> classes = null;
159
			final Writer out = new PrintWriter(System.err);
160
			final JavaCompiler.CompilationTask compile = javac.getTask(out, fileManager, null, options, classes, compilationUnits);
161
			final boolean res = compile.call();
162
			if (res){
163
				return cl.findClass(packageName + "." + className);
164
			}
165
		} catch (final Exception e){
166
			parserState.AddErrorMessage(new ParserError("JavaCodeCompiler.java",0,0,e.getMessage()));
167
		}
168
		return null;
169
//		if (results.Errors.HasErrors)
170
//		{
171
//			StringBuilder errors = new StringBuilder("Compiler Errors :\r\n");
172
//			foreach (CompilerError error in results.Errors)
173
//			{
174
//				errors.AppendFormat("Line %s,%s\t: %s\n", error.Line, error.Column, error.ErrorText);
175
//			}
176
//			throw new UlyssesCompileException(errors.ToString());
177
//		}
178
//		else
179
//		{
180
//			return results.CompiledAssembly;
181
//		}
182
	}
183

  
184
	public static void ExecuteCode(Class<?> clazz, String methodname, JavaInitVisitor visitor, ParserState parserState)
185
	{
186
		try{
187
			final Object o = clazz.getConstructor().newInstance();
188
			final Method m = clazz.getMethod("start", JavaInitVisitor.class);
189
			m.invoke(o, visitor);
190
		}
191
		catch (final Exception e) {
192
			parserState.AddErrorMessage(new ParserError("JavaCodeCompiler.java",0,0,e.toString()));
193
		}
194
	}
195
}
54

  
55
/**
56
 * This code is based on a blog entry of Morten Nobel.
57
 *
58
 * http://blog.nobel-joergensen.com/2008/07/16/using-eclipse-compiler-to-create-dynamic-java-objects-2/
59
 *
60
 */
61
/// <summary>
62
/// This class can be used to execute dynamic uncompiled code at runtime
63
/// This class is not exception safe, all function calls should be exception handled.
64
/// </summary>
65
public class JavaCodeCompiler
66
{
67
	private static class MemorySource extends SimpleJavaFileObject {
68
		private final String src;
69
		public MemorySource(String name, String src) {
70
			super(URI.create("file:///" + name + ".java"), Kind.SOURCE);
71
			this.src = src;
72
		}
73
		@Override
74
		public CharSequence getCharContent(boolean ignoreEncodingErrors) {
75
			return src;
76
		}
77
		@Override
78
		public OutputStream openOutputStream() {
79
			throw new IllegalStateException();
80
		}
81
		@Override
82
		public InputStream openInputStream() {
83
			return new ByteArrayInputStream(src.getBytes());
84
		}
85
	}
86

  
87
	private static class SpecialJavaFileManager extends ForwardingJavaFileManager<StandardJavaFileManager> {
88
		private final SpecialClassLoader xcl;
89
		public SpecialJavaFileManager(StandardJavaFileManager sjfm, SpecialClassLoader xcl) {
90
			super(sjfm);
91
			this.xcl = xcl;
92
		}
93
		@Override
94
		public JavaFileObject getJavaFileForOutput(Location location, String name, JavaFileObject.Kind kind, FileObject sibling) throws IOException {
95
			final MemoryByteCode mbc = new MemoryByteCode(name);
96
			xcl.addClass(name, mbc);
97
			return mbc;
98
		}
99
		@Override
100
		public ClassLoader getClassLoader(Location location) {
101
			return xcl;
102
		}
103
	}
104

  
105
	private static class MemoryByteCode extends SimpleJavaFileObject {
106
		private ByteArrayOutputStream baos;
107
		public MemoryByteCode(String name) {
108
			super(URI.create("byte:///" + name + ".class"), Kind.CLASS);
109
		}
110
		@Override
111
		public CharSequence getCharContent(boolean ignoreEncodingErrors) {
112
			throw new IllegalStateException();
113
		}
114
		@Override
115
		public OutputStream openOutputStream() {
116
			baos = new ByteArrayOutputStream();
117
			return baos;
118
		}
119
		@Override
120
		public InputStream openInputStream() {
121
			throw new IllegalStateException();
122
		}
123
		public byte[] getBytes() {
124
			return baos.toByteArray();
125
		}
126
	}
127

  
128
	private static class SpecialClassLoader extends ClassLoader {
129
		private final Map<String,MemoryByteCode> m = new HashMap<String, MemoryByteCode>();
130
		@Override
131
		protected Class<?> findClass(String name) throws ClassNotFoundException {
132
			MemoryByteCode mbc = m.get(name);
133
			if (mbc==null){
134
				mbc = m.get(name.replace(".","/"));
135
				if (mbc==null){
136
					return super.findClass(name);
137
				}
138
			}
139
			return defineClass(name, mbc.getBytes(), 0, mbc.getBytes().length);
140
		}
141
		public void addClass(String name, MemoryByteCode mbc) {
142
			m.put(name, mbc);
143
		}
144
	}
145

  
146
	public static Class<?> compileCode(String code, String className, String packageName, ParserState parserState)
147
	{
148
		try {
149
			final JavaCompiler javac = new EclipseCompiler();
150

  
151
			final StandardJavaFileManager sjfm = javac.getStandardFileManager(null, null, null);
152
			final SpecialClassLoader cl = new SpecialClassLoader();
153
			final SpecialJavaFileManager fileManager = new SpecialJavaFileManager(sjfm, cl);
154
			final List<String> options = Arrays.asList(new String[]{"-1.7"});
155

  
156
			final List<MemorySource> compilationUnits = Arrays.asList(new MemorySource(className, code));
157
//			DiagnosticListener<?> dianosticListener = null;
158
			final Iterable<String> classes = null;
159
			final Writer out = new PrintWriter(System.err);
160
			final JavaCompiler.CompilationTask compile = javac.getTask(out, fileManager, null, options, classes, compilationUnits);
161
			final boolean res = compile.call();
162
			if (res){
163
				return cl.findClass(packageName + "." + className);
164
			}
165
		} catch (final Exception e){
166
			parserState.AddErrorMessage(new ParserError("JavaCodeCompiler.java",0,0,e.getMessage()));
167
		}
168
		return null;
169
//		if (results.Errors.HasErrors)
170
//		{
171
//			StringBuilder errors = new StringBuilder("Compiler Errors :\r\n");
172
//			foreach (CompilerError error in results.Errors)
173
//			{
174
//				errors.AppendFormat("Line %s,%s\t: %s\n", error.Line, error.Column, error.ErrorText);
175
//			}
176
//			throw new UlyssesCompileException(errors.ToString());
177
//		}
178
//		else
179
//		{
180
//			return results.CompiledAssembly;
181
//		}
182
	}
183

  
184
	public static void ExecuteCode(Class<?> clazz, String methodname, JavaInitVisitor visitor, ParserState parserState)
185
	{
186
		try{
187
			final Object o = clazz.getConstructor().newInstance();
188
			final Method m = clazz.getMethod("start", JavaInitVisitor.class);
189
			m.invoke(o, visitor);
190
		}
191
		catch (final Exception e) {
192
			parserState.AddErrorMessage(new ParserError("JavaCodeCompiler.java",0,0,e.toString()));
193
		}
194
	}
195
}

Also available in: Unified diff