how can i instantiate an object from a compilationunit - java

I am trying to develop a plugin, which from a java file generate test and tables classes... when I select a Java source, I will be able to have an option "generate class test", the problem that I am recupering the Java file as ICompliationUnit, then I have a method that xtract methods of an object, that's why; I want to parse the IComplilationUnit to an instance of the class which represents, I tried to use Class.forName but it doesn't work , that's the code:
private void write(String dir, ICompilationUnit cu) throws JavaModelException
{
try
{
cu.getCorrespondingResource().getName();
System.out.println("0000000000000" + cu.getJavaProject().getProject().toString());
}
catch (JavaModelException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
String test = cu.getCorrespondingResource().getName();
IPackageDeclaration[] test1 = cu.getPackageDeclarations();
// Need
String[] name = test.split("\\.");
String contentFile = dir + "\\" + name[0] + "content.txt";
GenerateFitnessTable inst = new GenerateFitnessTable();
try
{
String pack = test1[0].toString().substring(7, test1[0].toString().indexOf("[") - 1) + "." + name[0];
#SuppressWarnings("rawtypes")
Class classe = Class.forName(cu.getJavaProject().getProject().toString()
.substring(cu.getJavaProject().getProject().toString().indexOf("/"), cu.getJavaProject().getProject().toString().length())
+ pack);
try
{
classe.newInstance();
}
catch (InstantiationException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalAccessException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
catch (ClassNotFoundException e1)
{
System.out.print("****************************la classe n'existe pas");
}
try
{
inst.generateContent(cu, contentFile);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}

this the right way ;)) , i found it :
// nouveau region
region = JavaCore.newRegion();
// ajout de la classe selectionné a cette region
region.add(cu);
if (JavaCore.getGeneratedResources(region, true).length == 0)
{
// bug
}
// recuperer l'url de .class
String url = "file:" + JavaCore.getGeneratedResources(region, true)[0].getLocation().makeAbsolute();
URL myUrl = new URL(url);
URLConnection connection = myUrl.openConnection();
InputStream input = connection.getInputStream();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int data = input.read();
while (data != -1)
{
buffer.write(data);
data = input.read();
}
input.close();
byte[] classData = buffer.toByteArray();
clas = defineClass(pack.substring(1, pack.length()), classData, 0, classData.length);

Related

Python output not displayed in jar file

I have created a java gui which takes values from the user send it to python file for processing and then displays the output from the python file onto the java gui. This is working perfectly on eclipse but when i exported it into a jar file the output is not displayed. I've seen a bunch of other questions like this but they do not give a solution that would help me.
This is how i connect my python script to java.
public void connection(String name)
{
ProcessBuilder pb= new ProcessBuilder("python","recomold.py","--movie_name",name);
///System.out.println("running file");
Process process = null;
try {
process = pb.start();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
int err = 0;
try {
err = process.waitFor();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// System.out.println("any errors?"+(err==0 ? "no" : "yes"));
/* try {
System.out.println("python output "+ output(process.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
try {
matches.setText(output(process.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String output(InputStream inputStream) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader br = null;
try{
br= new BufferedReader(new InputStreamReader(inputStream));
String line = null;
while((line=br.readLine())!=null)
{
sb.append(line+"\n");
//descp.setText("<html><br/><html>");
//sb.append("\n");
}
}
finally
{
br.close();
}
return sb.toString();
}

mocking url.openStream() should return InputStream

My actual class accepting URL as input and calling url.openStream(),this should return InputStream.
public static Map<String, Object> parseA(URL url) throws Exception {
byte[] readData = new byte[25*1024*1024];
// Here url.openStream() returning null
InputStream is = url.openStream();
while((readLength = is.read(readData, 0, 25*1024*1024)) != -1){
br = new BufferedReader(new InputStreamReader(new
ByteArrayInputStream(readData)));
// All CW_* strings are collected first
}
My test class is
#Rule
public TemporaryFolder folder= new TemporaryFolder();
#Test(enabled = true)
public void parseATest() {
File file=null;
try {
file =folder.newFile("testingData.txt");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
final URLConnection mockConnection = EasyMock.createMock(URLConnection.class);
final URLStreamHandler handler = new URLStreamHandler() {
#Override
protected URLConnection openConnection(final URL arg0)
throws IOException {
return mockConnection;
}
};
URL url=null;
try {
url = new URL("http://foo.bar", "foo.bar", 80, "", handler);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
InputStream is=null;
try {
is = new FileInputStream(file);
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
EasyMock.expect(url.openStream()).andReturn(is).anyTimes();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
// imageHeaderParser is object of actual class
imageHeaderParser.parseA(url);
} catch (IfmSwimParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Here TemporaryFolder used to create temp file.And I dont want URL to go network.It can be just dummy URL and when i call url.openStream(),it should return stream of temp file i mentioned.
A file can be converted to an URL, so just do that :
Url testUrl = Paths.get("folder",("testingData.txt").toUri().toURL();
Map<String, Object> map = parseA(testUrl);
// assert map content
Besides you don't need any mock if you want to test with the file processing behavior.

Extracting RAR with JunRAR [duplicate]

I asked a question earlier about extracting RAR archives in Java and someone pointed me to JUnrar. The official site is down but it seems to be quite widely used as I found a lot of discussions about it online.
Could someone show me how to use JUnrar to extract all the files in an archive? I found a little snippet online but it doesn't seem to work. It shows each item in the archive to be a directory even if it is a file.
Archive rar = new Archive(new File("C://Weather_Icons.rar"));
FileHeader fh = rar.nextFileHeader();
while(fh != null){
if (fh.isDirectory()) {
logger.severe("directory: " + fh.getFileNameString() );
}
//File out = new File(fh.getFileNameString());
//FileOutputStream os = new FileOutputStream(out);
//rar.extractFile(fh, os);
//os.close();
fh=rar.nextFileHeader();
}
Thanks.
May be you should also check this snippet code. A copy of which can be found below.
public class MVTest {
/**
* #param args
*/
public static void main(String[] args) {
String filename = "/home/rogiel/fs/home/movies/vp.mp3.part1.rar";
File f = new File(filename);
Archive a = null;
try {
a = new Archive(new FileVolumeManager(f));
} catch (RarException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (a != null) {
a.getMainHeader().print();
FileHeader fh = a.nextFileHeader();
while (fh != null) {
try {
File out = new File("/home/rogiel/fs/test/"
+ fh.getFileNameString().trim());
System.out.println(out.getAbsolutePath());
FileOutputStream os = new FileOutputStream(out);
a.extractFile(fh, os);
os.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RarException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fh = a.nextFileHeader();
}
}
}
}

Why am I getting InvocationTargetException at ClassLoaders.callStaticFunction Java Eclipse? [duplicate]

I have created a program to convert text to xml by using ReverseXSL API.
This program is to be executed by an application by calling static method (static int transformXSL).
I am able to execute and produce output with running from Eclipse. However, When I ran program (jar) by using application it stuck somewhere and I couldnt find anything.
Then, I debugged by "Debug as...-> Remote Java Application" in Eclipse from Application and found "InvocationTargetException" at ClassLoaders.callStaticFunction.
Below Static method is called by application.
public class MyTest4 {
public MyTest4()
{
}
public static int transformXSL(String defFile, String inputFile, String XSLFile, String OutputFile) {
System.out.println("Dheeraj's method is called");
// start time
FileWriter fw=null;
try {
fw = new FileWriter("D://Countime.txt");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedWriter output=new BufferedWriter(fw);
DateFormat sd=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date dt= new Date();
System.out.println("Date is calculated");
try {
output.write("Start Time:"+sd.format(dt).toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(sd.format(dt));
FileReader myDEFReader=null, myXSLReader=null;
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t=null;
FileInputStream inStream = null;
ByteArrayOutputStream outStream = null;
// Step 1:
//instantiate a transformer with the specified DEF and XSLT
if (new File(defFile).canRead())
{
try {
myDEFReader = new FileReader(defFile);
System.out.println("Definition file is read");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
else myDEFReader = null;
if (new File(XSLFile).canRead())
try {
myXSLReader = new FileReader(XSLFile);
System.out.println("XSL file is read");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
else myXSLReader = null;
try {
t = tf.newTransformer(myDEFReader, myXSLReader);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Step 1: DEF AND XSLT Transformation completed");
// Step 2:
// Read Input data
try {
inStream = new FileInputStream(inputFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
outStream = new ByteArrayOutputStream();
System.out.println("Step 2: Reading Input file: completed");
// Step 3:
// Transform Input
try {
try (BufferedReader br = new BufferedReader(new FileReader("D://2.txt"))) {
String line = null;
while ((line = br.readLine()) != null) {
System.out.println("Content: "+line);
}
}
System.out.println("File: "+inputFile.toString());
System.out.println("\n content: \n"+ inStream.toString());
System.out.println("Calling Transform Function");
t.transform(inStream, outStream);
System.out.println("Transformation is called");
outStream.close();
try(OutputStream outputStream = new FileOutputStream(OutputFile)) {
outStream.writeTo(outputStream);
System.out.println("Outstream is generated; Output file is creating");
}
System.out.println(outStream.toString());
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerFactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (javax.xml.transform.TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("output file is created");
// End time
Date dt2= new Date();
System.out.println(sd.format(dt2));
System.out.println("End time:"+dt2.toString());
try {
output.append("End Time:"+sd.format(dt2).toString());
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
}

Java - Jackson to a file

I have a JSON file like this:
{
"Product":
{
"ID": "08-17-96-71-D9-68",
"Licences":
{
"total": 40,
"used": 0,
"remain": 40
}
}
}
I used jackson to convert it to a Java Object and I get all the values (so far, so good).
My problem is that I want to change these values and re-write the JSON file but when I do that, the result is like this:
"{\"Product\":{\"IaD\": \"08-17-96-71-D9-68\",\"Licences\":{\"total\": 40,\"used\": 1,\"remain\": 39}}}"
So when I tried to read it again it gives me an error because it cannot read the first and last character (") and also it reads the \ character.
This is my code:
public class UsingJason {
String theJsonString = "";
ObjectMapper mapper = new ObjectMapper();
public class Product{
Licences lic;
public class Licences{
int total;
int used;
int remain;
}
}
public void readJson(){
if(new File("asset/testJson.json").exists()){
theJsonString = "";
try {
BufferedReader in = new BufferedReader(new FileReader("asset/testJson.json"));
String line;
while ((line = in.readLine()) != null){
theJsonString += line;
}
in.close();
} catch (IOException e1) {
e1.printStackTrace();
}
System.out.println("JSON String: "+ theJsonString);
}else{
System.out.println("NO FILE FOUND");
}
JsonNode rootNode = null;
try {
rootNode = mapper.readValue(theJsonString, JsonNode.class);
} catch (JsonParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (JsonMappingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
JsonNode totalNode = rootNode.get("Product").get("Licences").get("total");
JsonNode usedNode = rootNode.get("Product").get("Licences").get("used");
JsonNode remainNode = rootNode.get("Product").get("Licences").get("remain");
JsonNode idStringNode = rootNode.get("Product").get("ID");
// Parse it into a Java object.
try {
int totalObject = mapper.readValue(totalNode, Integer.class);
System.out.println("INTEGER? HAS TO BE... 40: "+totalObject);
String idString = mapper.readValue(idStringNode, String.class);
System.out.println("String? Has to be 08-17-96-71-D9-68: "+idString + " True? "
+ idString.equals("08-17-96-71-D9-68") );
int usedObject = mapper.readValue(usedNode, int.class);
int remainObject = mapper.readValue(remainNode, int.class);
System.out.println("Going to rest 1");
usedObject ++;
remainObject = totalObject - usedObject;
String toJackson = "{\"Product\":{\"I\\D\": \"08-17-96-71-D9-68\",\"Licences\":{\"total\": "+totalObject+",\"used\": "+usedObject+",\"remain\": "+remainObject+"}}}";
System.out.println("String created: " +toJackson);
// THIS toJackson String returns the string without \ and without the "
// IT PRINT THIS: {"Product":{"ID": "08-17-96-71-D9-68","Licences":{"total": 40,"used": 1,"remain": 39}}}
// EXACTLY WHAT I WANT TO Write in the Json file but it writes the \ ..
mapper.writeValue(new File("asset/testJson.json"), toJackson);
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Can anyone tell me what I am doing wrong?
In your code here:
mapper.writeValue(new File("asset/testJson.json"), toJackson);
You are serializing not an object, but the string to the file. I suppose this is the reason why it gets escaped, like any string.
The input value should be an object with your structure.
Something like this:
// Initialize an object
Product myProduct = new Product();
myProduct.lic = new Procuct.Licences();
myProduct.lic.total = totalObject;
myProduct.lic.used = usedObject;
myProduct.lic.remain = remainObject;
// Serialize the object into JSON
mapper.writeValue(new File("asset/testJson.json"), myProduct);

Categories