Web-Based Java Compiler - java

I'm Trying to create an online compiler that takes the the code as a string from the web page and displays the output. I've created a servlet.The user will enetr the program code in a textarea named "uName". The code to take the input as a string and compile it is as follows
`enter code here`
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Org.WebApplication1.test;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.ServletException;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URI;
import java.util.Iterator;
import java.util.NoSuchElementException;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
class CompileString {
static String program;
CompileString(String s)
{
program=s;
}
public static void main(String[] args) throws Exception {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
Iterable<? extends JavaFileObject> fileObjects;
fileObjects = getJavaSourceFromString(program);
compiler.getTask(null, null, null, null, null, fileObjects).call();
Class<?> clazz = Class.forName("Test");
Method m = clazz.getMethod("main", new Class[] { String[].class });
Object[] _args = new Object[] { new String[0] };
m.invoke(null, _args);
}
static Iterable<JavaSourceFromString> getJavaSourceFromString(String code) {
final JavaSourceFromString jsfs;
jsfs = new JavaSourceFromString("code", code);
return new Iterable<JavaSourceFromString>() {
public Iterator<JavaSourceFromString> iterator() {
return new Iterator<JavaSourceFromString>() {
boolean isNext = true;
public boolean hasNext() {
return isNext;
}
public JavaSourceFromString next() {
if (!isNext)
throw new NoSuchElementException();
isNext = false;
return jsfs;
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
}
class JavaSourceFromString extends SimpleJavaFileObject {
final String code;
JavaSourceFromString(String name, String code) {
super(URI.create("string:///" + name.replace('.', '/') + Kind.SOURCE.extension), Kind.SOURCE);
this.code = code;
}
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return code;
}
}
/**
*
* #author RAJ
*/
public class ServletExample extends HttpServlet{
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//super.doGet(req, resp);
String name=req.getParameter("uName");
CompileString obj=new CompileString(name);
String ip=req.getRemoteAddr();
resp.getWriter().println("<html>");
resp.getWriter().println("<head>");
resp.getWriter().println("<tile>Respnse</title>");
resp.getWriter().println("</head>");
resp.getWriter().println("<body>");
resp.getWriter().println("The output is "+obj);
resp.getWriter().println("<br>");
resp.getWriter().println("Your ip address is "+ip);
resp.getWriter().println("</body>");
resp.getWriter().println("</html>");
}
}
I want to display the output of the CompileString Class but the output im getting is "Org.WebApplication.Test...#1bsvdg"

Related

want to change value of request before reaching controller in SpringBoot

i have a requirement in my project. i want to change the value of sended data through postman, like as if there is three parameter like as id, name, salary.now i am sending the data through postman
}
"id":1,
"name":"dhiraj",
"salary":787878
}
now when send the data,it should be save as actual data in database .but if i am sending like as that
}
"id":2,
"name":"",
"salary":787878
}
then name column should be null instead of empty in database.i am using following code for that, but not getting exact output,please help me .
'package com.httpmodify.test.HttpModify.filter;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Locale;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.LocaleResolver;
import com.httpmodify.test.HttpModify.model.Student;
#Component
public class RequestModify implements Filter{
private static Logger log=LoggerFactory.getLogger(Student.class);
private static final String ACCEPT_LANGUAGE = "Accept-Language";
#Autowired
LocaleResolver localeResolver;
#Override
public void init(FilterConfig filterConfig) throws ServletException {
// Need to add code if something is required to be initialized.
}
#Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
StringBuilder requestJson = new StringBuilder();
String responseJson = "";
BufferedReader bufferedReader = request.getReader();
String line = null;
if (bufferedReader != null) {
while (null != (line = bufferedReader.readLine())) {
requestJson.append(line);
}
}
if (request.getMethod().equals("POST")) {
RestAPIRequestWrapper requestWrapper = new RestAPIRequestWrapper(request,
requestJson.toString().getBytes());
RestAPIResponseWrapper responseWrapper = new RestAPIResponseWrapper(response);
chain.doFilter(requestWrapper, responseWrapper);
response.setContentType("text/plain");
responseJson = responseWrapper.getCaptureAsString();
response.getWriter().write(responseWrapper.getCaptureAsString());
} else {
chain.doFilter(request, response);
}
}
#Override
public void destroy() {
// Need to write some code if some resource needs to be destroyed.
}
/**
* #param locale
* #return String
*/
private String getAcceptLanguage(String locale) {
return locale != null ? locale : "en";
}
}
'
package com.httpmodify.test.HttpModify.filter;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
/**
* #author Ashwini Upadhyay
* #Version 1.0
* #date 2019-Apr-02 12:57:38 PM
*/
public class RestAPIRequestWrapper extends HttpServletRequestWrapper {
private final ByteArrayInputStream decryptedDataBAIS;
private HttpServletRequest wrapped;
private Map<String, String[]> parameterMap;
private Map<String, String> headerMap = new HashMap<>();
public RestAPIRequestWrapper(HttpServletRequest wrapped, byte[] decryptedData) {
super(wrapped);
this.wrapped = wrapped;
decryptedDataBAIS = new ByteArrayInputStream(decryptedData);
}
public RestAPIRequestWrapper(HttpServletRequest wrapped, byte[] decryptedData, Map<String, String> headerMap) {
super(wrapped);
this.wrapped = wrapped;
decryptedDataBAIS = new ByteArrayInputStream(decryptedData);
this.headerMap = headerMap;
}
public RestAPIRequestWrapper(HttpServletRequest wrapped) {
super(wrapped);
this.wrapped = wrapped;
decryptedDataBAIS = new ByteArrayInputStream("".getBytes());
}
public RestAPIRequestWrapper(HttpServletRequest wrapped, String paramstr) {
super(wrapped);
this.wrapped = wrapped;
decryptedDataBAIS = null;
String[] paramsArr = paramstr.split("&");
for (int i = 0; i < paramsArr.length; i++) {
String[] paramArr = paramsArr[i].split("=");
addParameter(paramArr[0], paramArr[1]);
}
}
#Override
public String getContentType() {
return super.getContentType();
}
#Override
public BufferedReader getReader() throws UnsupportedEncodingException {
return new BufferedReader(new InputStreamReader(decryptedDataBAIS, "UTF_8"));
}
#Override
public ServletInputStream getInputStream() throws IOException {
return new ServletInputStream() {
#Override
public int read() {
return decryptedDataBAIS.read();
}
#Override
public boolean isFinished() {
return decryptedDataBAIS.available() == 0;
}
#Override
public boolean isReady() {
return true;
}
#Override
public void setReadListener(ReadListener arg0) {
throw new RuntimeException("Not implemented");
}
};
}
#Override
public Enumeration<String> getParameterNames() {
if (parameterMap == null) {
return wrapped.getParameterNames();
}
return Collections.enumeration(parameterMap.keySet());
}
#Override
public String[] getParameterValues(String name) {
if (parameterMap == null) {
return wrapped.getParameterValues(name);
}
return parameterMap.get(name);
}
#Override
public String getParameter(String name) {
if (parameterMap == null) {
return wrapped.getParameter(name);
}
String[] strings = parameterMap.get(name);
if (strings != null) {
return strings[0];
}
return null;
}
public void addParameter(String name, String value) {
if (parameterMap == null) {
parameterMap = new HashMap<>();
parameterMap.putAll(wrapped.getParameterMap());
}
String[] values = parameterMap.get(name);
if (values == null) {
values = new String[0];
}
List<String> list = new ArrayList<>(values.length + 1);
list.addAll(Arrays.asList(values));
list.add(value);
parameterMap.put(name, list.toArray(new String[0]));
}
#Override
public Map<String, String[]> getParameterMap() {
if (parameterMap == null) {
return wrapped.getParameterMap();
}
return Collections.unmodifiableMap(parameterMap);
}
#Override
public String getHeader(String headerName) {
String headerValue = null;
if (headerMap.containsKey(headerName)) {
headerValue = headerMap.get(headerName);
} else {
headerValue = super.getHeader(headerName);
}
return headerValue;
}
#Override
public Enumeration<String> getHeaders(String name) {
Set<String> values = new HashSet<>();
if (headerMap.containsKey(name) || name.equalsIgnoreCase("Authorization")) {
if (headerMap.get(name) != null)
values.add(headerMap.get(name));
} else {
for (Enumeration<String> e = super.getHeaders(name); e.hasMoreElements();) {
String headerValue = e.nextElement();
values.add(headerValue);
}
}
return Collections.enumeration(values);
}
#Override
public Enumeration<String> getHeaderNames() {
Set<String> names = new HashSet<>();
for (String name : headerMap.keySet()) {
names.add(name);
}
for (Enumeration<String> e = super.getHeaderNames(); e.hasMoreElements();) {
String headerName = e.nextElement();
if (!headerName.equalsIgnoreCase("Authorization"))
names.add(headerName);
}
return Collections.enumeration(names);
}
public void addHeader(String name, String value) {
headerMap.put(name, value);
}
}
package com.httpmodify.test.HttpModify.filter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
/**
* #author Ashwini Upadhyay
* #Version 1.0
* #date 2019-Apr-02 12:57:17 PM
*/
public class RestAPIResponseWrapper extends HttpServletResponseWrapper {
private final ByteArrayOutputStream capture;
private ServletOutputStream output;
private PrintWriter writer;
public RestAPIResponseWrapper(HttpServletResponse response) {
super(response);
capture = new ByteArrayOutputStream(response.getBufferSize());
}
#Override
public ServletOutputStream getOutputStream() throws IOException {
if (writer != null) {
throw new IllegalStateException("getWriter() has already been called on this response.");
}
if (output == null) {
output = new ServletOutputStream() {
#Override
public void write(int b) throws IOException {
capture.write(b);
}
#Override
public void flush() throws IOException {
capture.flush();
}
#Override
public void close() throws IOException {
capture.close();
}
#Override
public boolean isReady() {
return false;
}
#Override
public void setWriteListener(WriteListener arg0) {
}
};
}
return output;
}
#Override
public PrintWriter getWriter() throws IOException {
if (output != null) {
throw new IllegalStateException("getOutputStream() has already been called on this response.");
}
if (writer == null) {
writer = new PrintWriter(new OutputStreamWriter(capture, getCharacterEncoding()));
}
return writer;
}
#Override
public void flushBuffer() throws IOException {
super.flushBuffer();
if (writer != null) {
writer.flush();
} else if (output != null) {
output.flush();
}
}
public byte[] getCaptureAsBytes() throws IOException {
if (writer != null) {
writer.close();
} else if (output != null) {
output.close();
}
return capture.toByteArray();
}
public String getCaptureAsString() throws IOException {
return new String(getCaptureAsBytes(), getCharacterEncoding());
}
}
After getting the request in the controller, you can validate the input value. If the input for the name is empty then make it null, and perform the same operation for other input values. After performing these operations save the object to the database.

Compile Java code in-memory [duplicate]

This question already has answers here:
Compile code fully in memory with javax.tools.JavaCompiler [duplicate]
(7 answers)
Closed 6 years ago.
I want to treat a String as a Java file then compile and run it. In other words, use Java as a script language.
To get better performance, we should avoid writing .class files to disk.
This answer is from one of my blogs, Compile and Run Java Source Code in Memory.
Here are the three source code files.
MemoryJavaCompiler.java
package me.soulmachine.compiler;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.tools.*;
/**
* Simple interface to Java compiler using JSR 199 Compiler API.
*/
public class MemoryJavaCompiler {
private javax.tools.JavaCompiler tool;
private StandardJavaFileManager stdManager;
public MemoryJavaCompiler() {
tool = ToolProvider.getSystemJavaCompiler();
if (tool == null) {
throw new RuntimeException("Could not get Java compiler. Please, ensure that JDK is used instead of JRE.");
}
stdManager = tool.getStandardFileManager(null, null, null);
}
/**
* Compile a single static method.
*/
public Method compileStaticMethod(final String methodName, final String className,
final String source)
throws ClassNotFoundException {
final Map<String, byte[]> classBytes = compile(className + ".java", source);
final MemoryClassLoader classLoader = new MemoryClassLoader(classBytes);
final Class clazz = classLoader.loadClass(className);
final Method[] methods = clazz.getDeclaredMethods();
for (final Method method : methods) {
if (method.getName().equals(methodName)) {
if (!method.isAccessible()) method.setAccessible(true);
return method;
}
}
throw new NoSuchMethodError(methodName);
}
public Map<String, byte[]> compile(String fileName, String source) {
return compile(fileName, source, new PrintWriter(System.err), null, null);
}
/**
* compile given String source and return bytecodes as a Map.
*
* #param fileName source fileName to be used for error messages etc.
* #param source Java source as String
* #param err error writer where diagnostic messages are written
* #param sourcePath location of additional .java source files
* #param classPath location of additional .class files
*/
private Map<String, byte[]> compile(String fileName, String source,
Writer err, String sourcePath, String classPath) {
// to collect errors, warnings etc.
DiagnosticCollector<JavaFileObject> diagnostics =
new DiagnosticCollector<JavaFileObject>();
// create a new memory JavaFileManager
MemoryJavaFileManager fileManager = new MemoryJavaFileManager(stdManager);
// prepare the compilation unit
List<JavaFileObject> compUnits = new ArrayList<JavaFileObject>(1);
compUnits.add(fileManager.makeStringSource(fileName, source));
return compile(compUnits, fileManager, err, sourcePath, classPath);
}
private Map<String, byte[]> compile(final List<JavaFileObject> compUnits,
final MemoryJavaFileManager fileManager,
Writer err, String sourcePath, String classPath) {
// to collect errors, warnings etc.
DiagnosticCollector<JavaFileObject> diagnostics =
new DiagnosticCollector<JavaFileObject>();
// javac options
List<String> options = new ArrayList<String>();
options.add("-Xlint:all");
// options.add("-g:none");
options.add("-deprecation");
if (sourcePath != null) {
options.add("-sourcepath");
options.add(sourcePath);
}
if (classPath != null) {
options.add("-classpath");
options.add(classPath);
}
// create a compilation task
javax.tools.JavaCompiler.CompilationTask task =
tool.getTask(err, fileManager, diagnostics,
options, null, compUnits);
if (task.call() == false) {
PrintWriter perr = new PrintWriter(err);
for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
perr.println(diagnostic);
}
perr.flush();
return null;
}
Map<String, byte[]> classBytes = fileManager.getClassBytes();
try {
fileManager.close();
} catch (IOException exp) {
}
return classBytes;
}
}
MemoryJavaFileManager.java
package me.soulmachine.compiler;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.nio.CharBuffer;
import java.util.HashMap;
import java.util.Map;
import javax.tools.FileObject;
import javax.tools.ForwardingJavaFileManager;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.JavaFileObject.Kind;
import javax.tools.SimpleJavaFileObject;
/**
* JavaFileManager that keeps compiled .class bytes in memory.
*/
#SuppressWarnings("unchecked")
final class MemoryJavaFileManager extends ForwardingJavaFileManager {
/** Java source file extension. */
private final static String EXT = ".java";
private Map<String, byte[]> classBytes;
public MemoryJavaFileManager(JavaFileManager fileManager) {
super(fileManager);
classBytes = new HashMap<>();
}
public Map<String, byte[]> getClassBytes() {
return classBytes;
}
public void close() throws IOException {
classBytes = null;
}
public void flush() throws IOException {
}
/**
* A file object used to represent Java source coming from a string.
*/
private static class StringInputBuffer extends SimpleJavaFileObject {
final String code;
StringInputBuffer(String fileName, String code) {
super(toURI(fileName), Kind.SOURCE);
this.code = code;
}
public CharBuffer getCharContent(boolean ignoreEncodingErrors) {
return CharBuffer.wrap(code);
}
}
/**
* A file object that stores Java bytecode into the classBytes map.
*/
private class ClassOutputBuffer extends SimpleJavaFileObject {
private String name;
ClassOutputBuffer(String name) {
super(toURI(name), Kind.CLASS);
this.name = name;
}
public OutputStream openOutputStream() {
return new FilterOutputStream(new ByteArrayOutputStream()) {
public void close() throws IOException {
out.close();
ByteArrayOutputStream bos = (ByteArrayOutputStream)out;
classBytes.put(name, bos.toByteArray());
}
};
}
}
public JavaFileObject getJavaFileForOutput(JavaFileManager.Location location,
String className,
Kind kind,
FileObject sibling) throws IOException {
if (kind == Kind.CLASS) {
return new ClassOutputBuffer(className);
} else {
return super.getJavaFileForOutput(location, className, kind, sibling);
}
}
static JavaFileObject makeStringSource(String fileName, String code) {
return new StringInputBuffer(fileName, code);
}
static URI toURI(String name) {
File file = new File(name);
if (file.exists()) {
return file.toURI();
} else {
try {
final StringBuilder newUri = new StringBuilder();
newUri.append("mfm:///");
newUri.append(name.replace('.', '/'));
if(name.endsWith(EXT)) newUri.replace(newUri.length() - EXT.length(), newUri.length(), EXT);
return URI.create(newUri.toString());
} catch (Exception exp) {
return URI.create("mfm:///com/sun/script/java/java_source");
}
}
}
}
MemoryClassLoader.java
package me.soulmachine.compiler;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
/**
* ClassLoader that loads .class bytes from memory.
*/
final class MemoryClassLoader extends URLClassLoader {
private Map<String, byte[]> classBytes;
public MemoryClassLoader(Map<String, byte[]> classBytes,
String classPath, ClassLoader parent) {
super(toURLs(classPath), parent);
this.classBytes = classBytes;
}
public MemoryClassLoader(Map<String, byte[]> classBytes, String classPath) {
this(classBytes, classPath, ClassLoader.getSystemClassLoader());
}
public MemoryClassLoader(Map<String, byte[]> classBytes) {
this(classBytes, null, ClassLoader.getSystemClassLoader());
}
public Class load(String className) throws ClassNotFoundException {
return loadClass(className);
}
public Iterable<Class> loadAll() throws ClassNotFoundException {
List<Class> classes = new ArrayList<Class>(classBytes.size());
for (String name : classBytes.keySet()) {
classes.add(loadClass(name));
}
return classes;
}
protected Class findClass(String className) throws ClassNotFoundException {
byte[] buf = classBytes.get(className);
if (buf != null) {
// clear the bytes in map -- we don't need it anymore
classBytes.put(className, null);
return defineClass(className, buf, 0, buf.length);
} else {
return super.findClass(className);
}
}
private static URL[] toURLs(String classPath) {
if (classPath == null) {
return new URL[0];
}
List<URL> list = new ArrayList<URL>();
StringTokenizer st = new StringTokenizer(classPath, File.pathSeparator);
while (st.hasMoreTokens()) {
String token = st.nextToken();
File file = new File(token);
if (file.exists()) {
try {
list.add(file.toURI().toURL());
} catch (MalformedURLException mue) {}
} else {
try {
list.add(new URL(token));
} catch (MalformedURLException mue) {}
}
}
URL[] res = new URL[list.size()];
list.toArray(res);
return res;
}
}
Explanations:
In order to represent a Java source file in memory instead of disk, I defined a StringInputBuffer class in the MemoryJavaFileManager.java.
To save the compiled .class files in memory, I implemented a class MemoryJavaFileManager. The main idea is to override the function getJavaFileForOutput() to store bytecodes into a map.
To load the bytecodes in memory, I have to implement a customized classloader MemoryClassLoader, which reads bytecodes in the map and turn them into classes.
Here is a unite test.
package me.soulmachine.compiler;
import org.junit.Test;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import static org.junit.Assert.assertEquals;
public class MemoryJavaCompilerTest {
private final static MemoryJavaCompiler compiler = new MemoryJavaCompiler();
#Test public void compileStaticMethodTest()
throws ClassNotFoundException, InvocationTargetException, IllegalAccessException {
final String source = "public final class Solution {\n"
+ "public static String greeting(String name) {\n"
+ "\treturn \"Hello \" + name;\n" + "}\n}\n";
final Method greeting = compiler.compileStaticMethod("greeting", "Solution", source);
final Object result = greeting.invoke(null, "soulmachine");
assertEquals("Hello soulmachine", result.toString());
}
}
Reference
JavaCompiler.java from Cloudera Morphlines
How to create an object from a string in Java (how to eval a string)?
InMemoryJavaCompiler
Java-Runtime-Compiler
动态的Java - 无废话JavaCompilerAPI中文指南

Cannot resolve symbol "IPackageDeleteObserver"

I am trying to uninstall the piracy application. I don't have the following imports in my sdk .
import android.app.PackageDeleteObserver;
import android.content.pm.IPackageDeleteObserver;
So i got the interface IPackageDeleteObserver from here https://github.com/android/platform_frameworks_base/blob/master/core/java/android/content/pm/IPackageInstallObserver2.aidl which i placed in the android/content/pm but my android studio does not detect it. Dropdown does not show android.content.pm.IPackageDeleteObserver . Does anybody knows how to solve these imports?
Here it's the whole code:
package com.vivek.light.utils;
/**
* Created by Shiva on 24-07-2015.
*/
import android.app.PackageDeleteObserver;
import android.content.pm.IPackageDeleteObserver;
import android.content.pm.PackageManager;
import android.os.RemoteException;
import android.util.Log;
import java.lang.reflect.Method;
import static com.vivek.light.utils.AntiPiracyConstants.*;
public class AntiPiracyUtils {
static final String TAG = "ANTI-PIRACY: Utilities";
private static PackageDeleteObserver sPDO;
private AntiPiracyUtils() {
sPDO = getPackageDeleteObserver();
}
private static Class<?>[] UNINSTALLTYPES = new Class[] {
String.class, IPackageDeleteObserver.class, int.class
};
public static class PackageDeleteObserver extends IPackageDeleteObserver.stub {
public void packageDeleted(String packageName, int returnCode) throws RemoteException {
if (DEBUG) Log.i(TAG, "PackageDeleteObserver: " + packageName + " removed");
}
}
public static PackageDeleteObserver getPackageDeleteObserver() {
if (sPDO == null) sPDO = new PackageDeleteObserver();
return sPDO;
}
public static Method getUninstallTypes(PackageManager pm) throws NoSuchMethodException {
try {
return pm.getClass().getMethod("deletePackage", UNINSTALLTYPES);
} catch (NoSuchMethodException WTF) {
Log.e(TAG, "NoSuchMethodException" + l);
}
return null;
}
}

Dynamic Compiling Without Create Physical File

I follow the tutorial from Generating Java classes dynamically through Java compiler API, the code is work but what I see is the program will create a class file after compiling it.
import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.*;
public class Compiler {
static final Logger logger = Logger.getLogger(Compiler.class.getName());
static String sourceCode = "class HelloWorld{"
+ "public static void main (String args[]){"
+ "System.out.println (\"Hello, dynamic compilation world!\");"
+ "}"
+ "}";
public void doCompilation() {
SimpleJavaFileObject fileObject = new DynamicJavaSourceCodeObject("HelloWorld", sourceCode);
JavaFileObject javaFileObjects[] = new JavaFileObject[]{fileObject};
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager stdFileManager = compiler.getStandardFileManager(null, Locale.getDefault(), null);
Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(javaFileObjects);
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
CompilationTask compilerTask = compiler.getTask(null, stdFileManager, diagnostics, null, null, compilationUnits);
boolean status = compilerTask.call();
if (!status) {
for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
System.out.format("Error on line %d in %s\n", diagnostic.getLineNumber(), diagnostic);
}
}
try {
stdFileManager.close();
} catch (IOException ex) {
Logger.getLogger(Compiler.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String args[]) {
new Compiler().doCompilation();
}
}
class DynamicJavaSourceCodeObject extends SimpleJavaFileObject {
private String qualifiedName;
private String sourceCode;
protected DynamicJavaSourceCodeObject(String name, String code) {
super(URI.create("string:///" + name.replaceAll("\\.", "/") + JavaFileObject.Kind.SOURCE.extension), JavaFileObject.Kind.SOURCE);
this.qualifiedName = name;
this.sourceCode = code;
}
#Override
public CharSequence getCharContent(boolean ignoreEncodingErrors)
throws IOException {
return sourceCode;
}
public String getQualifiedName() {
return qualifiedName;
}
public void setQualifiedName(String qualifiedName) {
this.qualifiedName = qualifiedName;
}
public String getSourceCode() {
return sourceCode;
}
public void setSourceCode(String sourceCode) {
this.sourceCode = sourceCode;
}
}
Is it possible that after call compilerTask.call(); to not create a class file? If yes how to do that?
For what your doing, I would use Janino. It appears doable using just the JavaCompiler, but not well documented. See the comment I added withe linked question for an example of going about it with the JavaCompiler.
EDIT:
I found an easy to understand example using the JavaCompiler.
To avoid creation of class file by the JavaCompiler use the argument: "-proc:only"

why i am getting the following exception

this is my nodefinder.java file
package com.acme.web.action.executer;
import java.sql.ResultSet;
import java.util.Map;
import org.alfresco.web.bean.repository.Node;
import org.alfresco.web.bean.repository.Repository;
import org.alfresco.web.ui.common.component.UIActionLink;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import org.alfresco.service.cmr.model.FileFolderService;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.cmr.search.SearchParameters;
import org.alfresco.service.cmr.search.SearchService;
public class NodeFinder {
// private static final String = null;
SearchParameters sp = new SearchParameters();
private NodeService nodeService;
private FileFolderService fileFolderService;
//geting the filefolder service
public FileFolderService getFileFolderService() {
return fileFolderService;
}
// setting the file folder service
public void setFileFolderService(FileFolderService fileFolderService) {
this.fileFolderService = fileFolderService;
}
// getting the node servise
public NodeService getNodeService() {
return nodeService;
}
// setting the node server
public void setNodeService(NodeService nodeService) {
this.nodeService = nodeService;
}
public void execute(ActionEvent event) {
ResultSet resultSet_s = null;
UIActionLink comp = (UIActionLink) event.getComponent();
Map<String, String> params = comp.getParameterMap();
String id = params.get("id1");
System.out.println("1");
NodeRef actionedUponNodeRef = new NodeRef(Repository.getStoreRef(), id);
String qry_s = "#cm\\:name:train";
System.out.println("2");
SearchParameters sp_s = new SearchParameters();
System.out.println("3");
sp_s.addStore(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);
sp_s.setLanguage(SearchService.LANGUAGE_LUCENE);
sp_s.setQuery(qry_s);
System.out.println( "4" );
Node node = new Node(actionedUponNodeRef);
System.out.println("5");
resultSet_s = (ResultSet) Repository.getServiceRegistry(
FacesContext.getCurrentInstance()).getSearchService().query(
sp_s);
System.out.println("5.1");
if (resultSet_s != null) {
System.out.println("6");
System.out.println("Node value is::::" + node.getName());
}
}
}
Because you imported java.sql.ResultSet instead of an alfresco class/interface compatible to org.alfresco.repo.search.impl.lucene.PagingLuceneResultSet
Look at that line ...(ResultSet) Repository.getServiceRegistry(..., then look at your exception and finally at your imports. There you will see that ResultSet is actually java.sql.ResultSet (which is indicated by your ClassCastException's message).
If you then look at the super classes or interfaces of org.alfresco.repo.search.impl.lucene.PagingLuceneResultSet I'd say you won't find any java.sql.ResultSet. That's why you get that exception.

Categories

Resources