I want to add some code to the C source code, so I try to use ASTRewrite.
My Github project: cdt-rewrite
My code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import org.eclipse.cdt.core.dom.ast.ASTVisitor;
import org.eclipse.cdt.core.dom.ast.IASTIfStatement;
import org.eclipse.cdt.core.dom.ast.IASTStatement;
import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit;
import org.eclipse.cdt.core.dom.ast.gnu.c.GCCLanguage;
import org.eclipse.cdt.core.dom.rewrite.ASTRewrite;
import org.eclipse.cdt.core.model.ILanguage;
import org.eclipse.cdt.core.parser.DefaultLogService;
import org.eclipse.cdt.core.parser.FileContent;
import org.eclipse.cdt.core.parser.IncludeFileContentProvider;
import org.eclipse.cdt.core.parser.ScannerInfo;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.ltk.core.refactoring.Change;
public class Main {
public static void main(String[] args) throws Exception {
IASTTranslationUnit u = getTranslationUnit(new File("D:/test.c"));
System.out.println(u.getRawSignature());
ASTRewrite rw = ASTRewrite.create(u);
u.accept(new ASTVisitor(true) {
#Override
public int visit(IASTStatement stm) {
if (stm instanceof IASTIfStatement){
rw.insertBefore(stm.getParent(), stm,
rw.createLiteralNode("callTo(1,2,3);"), null);
}
return PROCESS_CONTINUE;
}
});
Change c = rw.rewriteAST();
c.perform(new NullProgressMonitor());
//String changedSource = someHowGetCode(c);
}
static IASTTranslationUnit getTranslationUnit(File source) throws Exception{
FileContent reader = FileContent.create(
source.getAbsolutePath(),
getContentFile(source).toCharArray());
return GCCLanguage.getDefault().getASTTranslationUnit(
reader,
new ScannerInfo(),
IncludeFileContentProvider.getSavedFilesProvider(),
null,
ILanguage.OPTION_IS_SOURCE_UNIT,
new DefaultLogService());
}
static String getContentFile(File file) throws IOException {
StringBuilder content = new StringBuilder();
String line;
try (BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream(file)))) {
while ((line = br.readLine()) != null)
content.append(line).append('\n');
}
return content.toString();
}
}
But when I run this code, an exception is occur:
int test(int x){
if (x < 0)
return 0;
int i, s = 0;
for (i = 1; i < x; i++)
s = s + i;
return s;
}
Exception in thread "main" java.lang.NullPointerException
at org.eclipse.cdt.internal.formatter.ChangeFormatter.formatChangedCode(ChangeFormatter.java:92)
at org.eclipse.cdt.internal.core.dom.rewrite.changegenerator.ChangeGenerator.generateChange(ChangeGenerator.java:117)
at org.eclipse.cdt.internal.core.dom.rewrite.changegenerator.ChangeGenerator.generateChange(ChangeGenerator.java:104)
at org.eclipse.cdt.internal.core.dom.rewrite.ASTRewriteAnalyzer.rewriteAST(ASTRewriteAnalyzer.java:26)
at org.eclipse.cdt.core.dom.rewrite.ASTRewrite.rewriteAST(ASTRewrite.java:212)
at Main.main(Main.java:44)
Does anyone know how to solve this exception?
Thanks you
AFAIK This code is dependent on running in OSGi, but you appear to have made a Java project with a main. You need to a plug-in project with a MANIFEST.MF that references what you require.
You can create an Eclipse Application if you want to control the entry point to the program. If you want to graduate this rewriting code to be part of Eclipse/CDT, then different entry points such as an Eclipse Command tied to a menu/toolbar/key combination may be what you want.
Related
I'm a java beginner and I'm doing a small project about dictionary, now I want to save word and translate mean in file, because my native language often have space like chicken will be con gà so, I must use other way, not by space, but I really don't know how to do that, a word and it translation in one line, separate by "tab", mean multi space like chicken con gà now I want to get 2 words and store it in my array of Words which I created before, so I want to do something like
w1=word1inline;
w2=word2inline;
Word(word1inline,word2inline);(this is a member of array);
please help me, thanks a lot, I just know how to read line from file text, and use split to get word but I am not sure how to read by multi space.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class docfile {
public static void main(String[] args)
{
String readLine;
ArrayList<String>str=new ArrayList<>(String);
try {
File file = new File("text.txt");
BufferedReader b = new BufferedReader(new FileReader(file));
while ((readLine = b.readLine()) != null) {
str.add()=readLine.split(" ");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
If you stick to using tabs as a separator, this should work:
package Application;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class Application {
public static void main(String[] args) {
String line;
ArrayList<String> str = new ArrayList<>();
try {
File file = new File("text.txt");
BufferedReader b = new BufferedReader(new FileReader(file));
while ((line = b.readLine()) != null) {
for (String s : line.split("\t")) {
str.add(s);
}
}
str.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Why not just use a properties file?
dict.properties:
chicken=con gá
Dict.java:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Properties;
public class Dict {
public static void main(String[] args) throws IOException {
Properties dict = new Properties();
dict.load(Files.newBufferedReader(Paths.get("dict.properties")));
System.out.println(dict.getProperty("chicken"));
}
}
Output:
con gá
If your line is like this chicken con gà you can use indexof() method to find the first space in the string.
Then you can substring each word by using substring() method.
readLine = b.readLine();
ArrayList<String>str=new ArrayList<>();
int i = readLine.indexOf(' ');
String firstWord = readLine.substring(0, i);
String secondWord = readLine.substring(i+1, readLine.length());
str.add(firstWord);
str.add(secondWord);
I have to run a run a python script from a maven project. I created a temporary class with main method to check if it works as expected, used the process builder and it works if I specify the absolute path of the python script and then run the java class from eclipse using RUN as Java application.
If I change it getClass().getResourceAsStream("/scripts/script.py"), it throws an exception as it cannot locate the python script.
What would be the best place to place the python script and how can I access it in the Java class without specifying the complete path. Since I am new to maven, it could be due to the method used to execute the Java program.
package discourse.apps.features;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class Test {
protected String scriptPath = "/Users/user1/project1/scripts/script.py";
protected String python3Path = "/Users/user1/.virtualenvs/python3/bin/python3";
public static void main(String[] args) throws IOException {
new Test().score();
}
public JSONObject score() {
String text1="a";
String text2="b";
JSONObject rmap =null;
try
{
String line= null;
String writedir=System.getProperty("user.dir")+ "/Tmp";
String pbCommand[] = { python3Path, scriptPath,"--stringa", text1, "--stringb",text2,"--writedir", writedir };
ProcessBuilder pb = new ProcessBuilder(pbCommand);
Process p = pb.start();
InputStream is = p.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
JSONParser parser = new JSONParser();
rmap= (JSONObject) parser.parse(line);
}
} catch (IOException | ParseException ioe) {
System.err.println("Error running script");
ioe.printStackTrace();
System.exit(0);
}
return rmap;
}
}
Here is the output from pb command
pbCommand[0]:/Users/user1/.virtualenvs/python3/bin/python3
pbCommand[1]:displays the complete python script
import os,sys
from pyrouge import Rouge155
import json
from optparse import OptionParser
def get_opts():
parser = OptionParser()
parser.add_option("--stringa", dest="str_a",help="First string")
parser.add_option("--stringb", dest= "str_b",help="second string")
parser.add_option("--writedir", dest="write_dir", help="Tmp write directory for rouge")
(options, args) = parser.parse_args()
if options.str_a is None:
print("Error: requires string")
parser.print_help()
sys.exit(-1)
if options.str_b is None:
print("Error:requires string")
parser.print_help()
sys.exit(-1)
if options.write_dir is None:
print("Error:requires write directory for rouge")
parser.print_help()
sys.exit(-1)
return (options, args)
def readTextFile(Filename):
f = open(Filename, "r", encoding='utf-8')
TextLines=f.readlines()
f.close()
return TextLines
def writeTextFile(Filename,Lines):
f = open(Filename, "w",encoding='utf-8')
f.writelines(Lines)
f.close()
def rougue(stringa, stringb, writedirRouge):
newrow={}
r = Rouge155()
count=0
dirname_sys= writedirRouge +"rougue/System/"
dirname_mod=writedirRouge +"rougue/Model/"
if not os.path.exists(dirname_sys):
os.makedirs(dirname_sys)
if not os.path.exists(dirname_mod):
os.makedirs(dirname_mod)
Filename=dirname_sys +"string_."+str(count)+".txt"
LinesA=list()
LinesA.append(stringa)
writeTextFile(Filename, LinesA)
LinesB=list()
LinesB.append(stringb)
Filename=dirname_mod+"string_.A."+str(count)+ ".txt"
writeTextFile(Filename, LinesB)
r.system_dir = dirname_sys
r.model_dir = dirname_mod
r.system_filename_pattern = 'string_.(\d+).txt'
r.model_filename_pattern = 'string_.[A-Z].#ID#.txt'
output = r.convert_and_evaluate()
output_dict = r.output_to_dict(output)
newrow["rouge_1_f_score"]=output_dict["rouge_1_f_score"]
newrow["rouge_2_f_score"]=output_dict["rouge_2_f_score"]
newrow["rouge_3_f_score"]=output_dict["rouge_3_f_score"]
newrow["rouge_4_f_score"]=output_dict["rouge_4_f_score"]
newrow["rouge_l_f_score"]=output_dict["rouge_l_f_score"]
newrow["rouge_s*_f_score"]=output_dict["rouge_s*_f_score"]
newrow["rouge_su*_f_score"]=output_dict["rouge_su*_f_score"]
newrow["rouge_w_1.2_f_score"]=output_dict["rouge_w_1.2_f_score"]
rouge_dict=json.dumps(newrow)
print (rouge_dict)
def run():
(options, args) = get_opts()
stringa=options.str_a
stringb=options.str_b
writedir=options.write_dir
rougue(stringa, stringb, writedir)
if __name__ == '__main__':
run()
pbCommand[2]:--stringa
pbCommand[3]:a
pbCommand[4]:--stringb
pbCommand[5]:b
pbCommand[6]:--writedir
pbCommand[7]:/users/user1/project1/Tmp
Put the script in the main/resources folder it will then be copied to the target folder.
Then make sure you use something like the com.google.common.io.Resources class, which you can add with
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava-io</artifactId>
<version>r03</version>
</dependency>
I then have a class like this which helps to convert resource files to Strings:
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import com.google.common.base.Charsets;
import com.google.common.io.Resources;
public class FileUtil
{
public static String convertResourceToString(URL url)
{
try
{
return Resources.toString(url, Charsets.UTF_8);
}
catch (Exception e)
{
return null;
}
}
public static String convertResourceToString(String path)
{
return convertResourceToString(Resources.getResource(path));
}
public static String convertResourceToString(URI url)
{
try
{
return convertResourceToString(url.toURL());
}
catch (MalformedURLException e)
{
return null;
}
}
}
Some advice if you are learning maven try using it instead of the IDE to run and package your application, that is what it is suppose to do. Then once you are confident that the application will function as a packaged jar then just use the IDE to run it.
I am getting arrayoutofbond error while running below given code,
sometime it is running as expected and sometime it is giving error.
Could anyone help me where I am wrong.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class getFileContent{
public void listFiles() throws IOException, InterruptedException{
File directory = new File("C:\\ScriptLogFile\\");
File[] myarray;
myarray=directory.listFiles();
int i=0;
ArrayList<String> arrayList = new ArrayList<String>();
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy_hhmmss");
Date curDate = new Date();
String strDate = sdf.format(curDate);
String fileName = strDate;
File file = new File("C:\\ExcelReport_"+fileName+".csv");
FileWriter fileWritter = new FileWriter(file, true);
BufferedWriter bwr = new BufferedWriter(fileWritter);
String filename = null;
try {
for (int j = 0; j < myarray.length; j++)
{
File path=myarray[j];
FileInputStream fis = new FileInputStream (path);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
if(path.isFile()){
if(path.getName().endsWith(".csv")){
filename = path.getName();
String line;
bwr.write(filename+",");
while ((line = br.readLine()) != null) {
if(line.contains("-")){
String[] part = line.split("-");
arrayList.add(part[1]);
bwr.write(arrayList.get(i)+",");
i++;
}
else{
}
}
bwr.write("\r\n");
}
}
}
}catch (FileNotFoundException e) {
e.printStackTrace();
}
bwr.close();
}
public static void main(String[] args) throws IOException, InterruptedException {
getFileContent gfc = new getFileContent();
gfc.listFiles();
}
}
We need a stack trace to see where the exception is raised. However you seem to be making assumptions about the length of part[]. Remember arrays are 0-indexed, the first entry would be at index 0 i.e. part[0]. Even then, in general there really needn't be many entries at all: "xyz".split("-") is an array of length 1 whose only element, "xyz", is at index 0.
How can I use Java application to add system files as an attachment to Couchdb database using Couchdb4J library?
I tried modifying the sample code below but there's an unresolved error. Does anybody know where's my mistake and how to fix it? Thanks in advance.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import com.fourspaces.couchdb.CouchResponse;
import com.fourspaces.couchdb.Database;
import com.fourspaces.couchdb.Document;
import com.fourspaces.couchdb.Session;
public class FileScanner {
Session priceListDocsSession = new Session("localhost",5984);
Database db = priceListDocsSession.getDatabase("filesdb");
public static void main(String[] args) {
FileScanner fs = new FileScanner();
fs.processDir(new File("C:\\CouchDB"));
}
void processDir(File f) {
if (f.isFile()) {
Map<String, Object> doc = new HashMap<String, Object>();
doc.put("name", f.getName());
doc.put("path", f.getAbsolutePath());
doc.put("size", f.length());
db.saveDocument(doc);
InputStream is = new FileInputStream(f);
String att=db.putAttachment(doc.getId(),doc.getRev(),f,is);
}
else {
File[] fileList = f.listFiles();
if (fileList == null) return;
for (int i = 0; i < fileList.length; i++) {
try {
processDir(fileList[i]);
} catch (Exception e) {
System.out.println(e);
}
}
}
}
}
The errors appears on the db.saveDocument(doc);
and
String att=db.putAttachment(doc.getId(),doc.getRev(),f,is); saying that .getId() and getRev() is undefined for the type Map
I managed to fixed the problem by adding some of the jcouchdb dependencies on the classpath.
Hi, I am totally new in java.
This is my java code:
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.BufferedReader;
public class readw {
public static void main(String[] args) throws IOException {
List<String> lines = new ArrayList<String>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("C:\\run\\input.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
} finally {
reader.close();
}
String[] array = lines.toArray();
}
}
When I am trying to compile it I got this type of error:
line 8: can not find symbol List (L)and ArrayList(A)
I am trying to get content of my text file and want to set in to as a array.
Add
import java.util.ArrayList;
import java.util.List;
yes its work now i want to see the array result. how?
With
System.out.println(lines);
You need to import all the classes you use.
import java.util.ArrayList;
import java.util.List;