I'm trying to create a Java learning Android application.
It should have a code playground for users; which can run simple Java code.
I save users code in a java code and I'm trying to run it.
I'm using JANINO, but the problem is that I can not load external class including users code with it.
Here is my code:
String UsersCodeInput;
public void Run() throws FileNotFoundException, IOException
{
File sourcepath = new File(Environment.getExternalStorageDirectory()+"/MainFolder");
File JavaFile = new File(sourcepath.getPath()+"A.java");
FileOutputStream fos = new FileOutputStream(JavaFile);
fos.write(UsersCodeInput.getBytes());
fos.close();
// now Users Code is Saved.
//trying to run it by means of janino :
ClassLoader cl = new JavaSourceClassLoader(
this.getClass().getClassLoader(), // parentClassLoader
new File[] {sourcepath}, //our sourceFolder
"UTF-8" //Encodeing
);
try
{
// problem is here. next line is not working well; throws classNotFound.
Object o = cl.loadClass(".A").newInstance();
//the class implements runnable.
((Runnable) o).run();
}
catch (ClassNotFoundException e)
{Toast.makeText(this,e.getCause().toString(),Toast.LENGTH_SHORT).show();}
catch (InstantiationException e)
{Toast.makeText(this,e.getCause().toString(),Toast.LENGTH_SHORT).show();}
catch (IllegalAccessException e)
{Toast.makeText(this,e.getCause().toString(),Toast.LENGTH_SHORT).show();}
}
And here is JANINOs tutorial ; Read "source code compiler" part
http://janino-compiler.github.io/janino/
Thanks.
Related
I am trying to read a text file twice in order to calculate an average (calcAverage) and then to filter on the average to get a results list (processFile). When the second step is run the exception,
java.io.UncheckedIOException: java.io.IOException: Stream closed
is thrown.
Below is a simplified version of my failing code and a unit-test to drive the code.
A parameter (source) of type Reader is passed into App from a unit test and is a FileReader to a text file. I dont know how to access the File handler (or filename) from the Reader object to re-open it - I've tried implementing this inside App and this would fix the problem. The method signature of runProcess (Reader source) can not be changed - the other method signatures however can be.
I am using a try-with-resources block to open the Reader object and to read it through - its then closed automatically - which is all fine. I just need a way to re-open the file from the Reader to perform the filtering for pass-2.
I have read from similar questions, that the BufferedReader is like an iterator and you can only read it once.
I have tried using the mark() and reset() methods on my source object, but this throws an exception that these aren't supported.
I could read the whole file into a List object and then use this to calculate both steps but I dont know how large my file is going to be and so if possible would like to try and find a solution using the approach below.
Does anyone know how I can implement this ?
public class App {
public static void runProcess(Reader source) {
Collection<?> col = calcAverage(source);
processFile(source).forEach(x -> System.out.println(x));
}
private static Collection processFile(Reader source) {
Collection<?> col = processFile(source, ((BufferedReader reader) -> reader.lines()
.skip(1)
.collect(Collectors.toList()))
);
return col;
}
private static Collection<?> calcAverage(Reader source) {
Collection<?> col = processFile(source, ((BufferedReader reader) -> reader.lines()
.skip(1)
.collect(Collectors.toList())));
return col;
}
private static Collection<?> processFile(Reader source, BufferedReaderProcessor p){
try (BufferedReader reader = new BufferedReader(source)) {
return p.process(reader);
}catch (FileNotFoundException f){
f.printStackTrace();
return null;
}catch (IOException e){
e.printStackTrace();
return null;
}catch (Exception ex){
ex.printStackTrace();
return null;
}
}
#FunctionalInterface
public interface BufferedReaderProcessor {
Collection<?> process(BufferedReader b) throws IOException;
}
}
public class AppTest {
#Test
public void shouldReadFileTwice() throws FileNotFoundException {
App.runProcess(openFile("src/main/java/functions/example4/resources/list-of-fruits"));
}
private static Reader openFile(String filename) throws FileNotFoundException {
return new FileReader(new File(filename));
}
}
I believe you shouldn't use try with resources. It calls close on its BufferedReader which causes all the incapsulated readers to be closed.
I.e. it closes BufferedReader, Reader and FileReader.
When you invoke calcAverage in App::runProcess it closes all the readers. Then you're trying to read closed Reader when calling processFile on the next line.
In my Spring Camel app, I try to move or delete a file base on the destinationFolder property. If destinationFolder=null, I want the file to be deleted. If destinationFolder!=null, I want the file to be moved to destinationFolder.
String destinationFolder;
//In the Camel routeBuilder:
from("file://C:/folder1?move=" + destinationFolder)
What will happen in destinationFolder is null? Does the file get move to default location?
When I set destinationFolder=null, I see the file is deleted in folder1.
If you set the move option then the file component will move the file, you cannot set it to null and then have it automatic delete the file. By default the file is moved to a folder named .camel.
So either set delete=true or set move to some folder name to move the files.
First, you should know when to use "move", "delete" &"noop" and how it will works in Apache camel
Note :1) If your destination path is not existed then file will delete automatically.
Note :2) If you are not used "noop=true" in Camel URL then file file will delete(if your destination path is null)
Reference : - enter link description here
Basic Test Code:
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
public class SFTPTest {
public static void main(String[] args) throws Exception {
DefaultCamelContext ctx = null;
try{
ctx = new DefaultCamelContext();
ctx.addRoutes(new RouteBuilder() {
#Override
public void configure() throws Exception {
String filepath = "file:///camelexample/?fileName=test.txt&move=null";
from(filepath)
.log("File processed");
}
});
ctx.start();
Thread.sleep(5000);
ctx.stop();
}catch (Exception e){
System.err.println("Exception is : "+e.getLocalizedMessage());
}finally {
try{
ctx.stop();
}catch (Exception e){
System.err.println("Exception is : "+e.getLocalizedMessage());
}
}
}
}
I want to create file path in controller
Already created file path and it's working
try {
Files.write(Paths.get("D:\\app\\app\\java.ini"), data, StandardCharsets.UTF_8, StandardOpenOption.CREATE);
} catch (IOException e) {
e.printStackTrace();
}
Now i want to change this D:\\app\\app\\java.ini and i want to create like resources/java.ini
I don't to give any system full path.
Thanx
The sample code below shows the example that you need:
public class MyClass
{
public static void main(String[] args) {
String test = MyClass.class.getProtectionDomain()
.getCodeSource().getLocation().getPath();
System.out.println(test);
}
}
Assuming that the method you are running is called MyClass, you can have this snippet inside your Java method:
try {
String location = MyClass.class.getProtectionDomain()
.getCodeSource().getLocation().getPath() + "resources/java.ini");
Files.write(location, data, StandardCharsets.UTF_8, StandardOpenOption.CREATE);
} catch (IOException e) {
e.printStackTrace();
}
I can download data via HttpUrlConnection and InputStream but I need to download raw-data. So, i want to create a DownloadManager via raw-data, then using raw-data I convert this data to binary or image format. According to my research, I see "download file from url" but I can't download file in mac? Always, I get FileNotFoundException. Please help me. How I can download data from url?
public class DownloadData extends AsyncTask<Void,Void,Void> {
#Override
protected Void doInBackground(Void... params) {
try {
downloadData("https://blablalabla/get");
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public void downloadData(String myurl) throws IOException {
URL u = new URL(myurl);
InputStream is = u.openStream();
DataInputStream dis = new DataInputStream(is);
byte[] buffer = new byte[1024];
int length;
OutputStream fos = new FileOutputStream(new File(Environment.getExternalStorageDirectory() + "/Users/ilknurpc/Desktop/text.docx"));
while ((length = dis.read(buffer))>0) {
fos.write(buffer, 0, length);
}
}
}
If you want to construct a workable download manager, I would suggest that you take a look at the
Tomcat Default Servlet Implementation
.
There a few number of HTTP headers that you need to understand such as E-Tags and Http Range Headers for a proper implementation.
Thankfully the Tomcat Default Servlet handles the prerequisites for you.
You can adapt this servlet in your code with minor changes (package declaration etc).
I'm developing an app that processes files in ODS format.The code snippet is as follows:
public static void main(String[] args) throws IOException {
// Set the platform L&F.
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
display();
//print();
}
private static void display() throws IOException {
// Load the spreadsheet.
final OpenDocument doc = new OpenDocument();
doc.loadFrom("temperature3.ods");
String styleName = "Calibri";
StyleHeader header = new StyleHeader();
header.setStyleDisplay("Testing");
StyleMasterPage page = new StyleMasterPage();
page.setStyleHeader(header);
page.setStyleName(styleName);
OfficeMasterStyles off = new OfficeMasterStyles();
off.addMasterPage(off.getMasterPageFromStyleName(styleName));
doc.setMasterStyles(off);
// Show time !
final JFrame mainFrame = new JFrame("Viewer");
DefaultDocumentPrinter printer = new DefaultDocumentPrinter();
ODSViewerPanel viewerPanel = new ODSViewerPanel(doc, true);
mainFrame.setContentPane(viewerPanel);
mainFrame.pack();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setLocation(10, 10);
mainFrame.setVisible(true);
}
I intend loading the file into a jcomponent for easy manipulation but I'm having this error message in the netbeans console:
Exception in thread "main" java.lang.IllegalArgumentException: Unable to find StyleMasterPage named:Calibri
at org.jopendocument.model.office.OfficeMasterStyles.getMasterPageFromStyleName(Unknown Source)
at starzsmarine1.PrintSpreadSheet.display(PrintSpreadSheet.java:60)
at starzsmarine1.PrintSpreadSheet.main(PrintSpreadSheet.java:45)
Is there an alternative API for this purpose?