I am developing an Eclipse plugin and I want to take input from the user. I had a problem before with dealing with the console as I have 2 consoles 1 in the original Eclipse application and the other in the new opened Eclipse plugin window. I used the method shown below to print in the Console of the Plugin
public static void writeToConsole(String output) {
MessageConsole console = new MessageConsole("My Console", null);
console.activate();
ConsolePlugin.getDefault().getConsoleManager().addConsoles(new IConsole[]{ console });
MessageConsoleStream stream = console.newMessageStream();
stream.println(output);
}
I just don't know how to write in the console and take what's written in a variable
N.B.
The normal methods like
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
String s = bufferRead.readLine();
System.out.println(s);
are working for the original Eclipse not the plugin
You can't tie up the UI waiting for user input so you have to handle user input when it is received. One way to do this is with a document listener. Here is an example that prints the last line typed:
console.getDocument().addDocumentListener(new IDocumentListener() {
#Override
public void documentChanged(final DocumentEvent event) {
if ("\r\n".equals(event.getText())) {
final IDocument doc = event.getDocument();
try {
final IRegion region = doc.getLineInformationOfOffset(event.getOffset());
try {
final String line = doc.get(region.getOffset(), region.getLength());
System.out.println(line);
} catch (BadLocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (BadLocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public void documentAboutToBeChanged(final DocumentEvent event) {
// TODO Auto-generated method stub
}
});
Related
I am trying to fetch the data and store it in database.
Created a Get mapping for invoking the data from url and storing it in database using service class .
#GetMapping("/")
public String root(Model model) throws IOException {
model.addAttribute("test1","Hello user");
service.populate();
return "mainTemplate";
}
my populate method in service class add data to database.
public void populate() throws IOException{
URL url = new URL("https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/01-01-2021.csv");
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
int res= connection.getResponseCode();
CSVReader reader=null;
if(res==200) {
log.info("Connected to github");
try {
BufferedReader readurl = new BufferedReader(new InputStreamReader(connection.getInputStream()),8192);
reader=new CSVReader(readurl);
String[] line;
int i=0;
while((line=reader.readNext())!=null) {
if(i==0) {
i++;
continue;
}
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
Corona corona = new Corona();
corona.setLastupDate(LocalDateTime.parse(line[4],formatter));
corona.setConfirmed(Long.valueOf(line[7]));
corona.setRecovered(Long.valueOf(line[9]));
corona.setActive(Long.valueOf(line[10]));
corona.setCombinedKey(line[11]);
log.info(corona.toString());
repo.save(corona);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (CsvValidationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
if(reader!=null) {
try {
reader.close();
} catch (IOException e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
}
}
else {
log.info("URL is wrong");
}
}
Everything is working fine when i hit the resource url ,but i have to wait for some time to show my webpage , until all data does not get stored in database.
I want to show "Data is being added" in mainTemplate.html as soon as i hit the url. So that my populate method runs in background and i don't have to wait for completion of method to show my mainTemplate .
I tired to add #Async method annotation but that does not seem to be worked .
I'm trying to get a thread to run for a swing application on button click, but the value isn't updating.
It supposed to grab the computer name I'm searching, but in order for the value to update I have to launch a new instance of the GUI.
I created a thread, but for some reason it's not working. Any help is appreciated.
(t.start is at end of code block)
searchComputerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Thread t = new Thread("my non EDT thread") {
public void run() {
//my work
testLabel.setText(CN);
}
};
String line;
BufferedWriter bw = null;
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(tempFile));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// String lineToRemove = "OU=Workstations";
String s = null;
Process p = null;
/*
* try { // p = Runtime.getRuntime().exec(
* "cmd /c start c:\\computerQuery.bat computerName"); } catch
* (IOException e1) { // TODO Auto-generated catch block
* e1.printStackTrace(); }
*/
try {
p = Runtime.getRuntime().exec("c:\\computerQuery.bat");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
StringBuffer sbuffer = new StringBuffer();
BufferedReader in = new BufferedReader(new InputStreamReader(p
.getInputStream()));
try {
while ((line = in.readLine()) != null) {
System.out.println(line);
// textArea.append(line);
String dn = "CN=FDCD111304,OU=Workstations,OU=SIM,OU=Accounts,DC=FL,DC=NET";
LdapName ldapName = new LdapName(dn);
String commonName = (String) ldapName.getRdn(
ldapName.size() - 1).getValue();
}
ComputerQuery.sendParam();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InvalidNameException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally
{
try {
fw.close();
}
catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
try {
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ComputerQuery.sendParam();
t.start();
}
});
UPDATE
private void threadStart() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
testLabel.setText(CN);
}
});
And I put the method here
JButton searchComputerButton = new JButton("Search");
searchComputerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
threadStart();
String line;
Be aware of the Swing Thread https://docs.oracle.com/javase/tutorial/uiswin/concurrency/
Have a look here:
http://www.javamex.com/tutorials/threads/invokelater.shtml
You must enqueue your JLabel update method invocation using the Method
SwingUtilities.invokeLater(???).
Following example does it
Further more i think that is has something to do with the .batch file invocations. Have a look here: How do I run a batch file from my Java Application?
Runnable task = new UpdateJob("Query: " + i);
SwingUtilities.invokeLater(task);
To make it more understandable.
Swing manages all draw-Operations, within one Thread.
It provides a queue. If you call a method from outside of that queue the behaviour is completely unpredictable.. NullPointer... RuntimeExc....
But if you call SwingUtilities.invokeLater(...) your method will be enqueued into the Swing-Queue and invoked as soon as possible!
UPDATE due to comment:
check your mainthread (GUI)
check your threads.
when a sub-thread (e.g a ActionListener) want to call JLabel::setText
it has to use the method SwingUtils::InvokeLater("...");
That means invokeLater() has to be call within all threads which not directly belong to the main threads.
UPDATE due to Question
In my oppinion you current't code doesn't need SwingUtilities.invok.. at all.
Did you change the Code assigned to you your question.
Trying to learn about Jackson some, so I'm writing a simple program that reads a file/creates one to store some JSON in it. From the Jackson website I figured out how to read and write from the file, but in the case of my rudimentary program, i'd like to append as well. I'm basically trying to store a list of shopping lists. There is a shopping list object which has store name, amd items for that store.
The trouble is that I cannot figure a way to append another entry to the end of the file (in JSON format). Here is what I am working with so far, you can ignore the first bit it's just a silly console scanner asking for input:
public class JacksonExample {
static ObjectMapper mapper = new ObjectMapper();
static File file = new File("C:/Users/stephen.protzman/Desktop/user.json");
static List<ShoppingList> master = new ArrayList<ShoppingList>();
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean running = true;
while (running) {
System.out.println("[ 1 ] Add a new shopping list");
System.out.println("[ 2 ] View all shopping lists");
System.out.println("[ 3 ] Save all shopping lists");
int choice = Integer.parseInt(in.nextLine());
switch (choice) {
case 1:
getNewList();
case 2:
display();
case 3:
running = false;
}
}
in.close();
}
public static void getNewList() {
boolean more = true;
String store, temp;
List<String> items = new ArrayList<String>();
Scanner s = new Scanner(System.in);
System.out.println("Enter the store: ");
store = s.nextLine();
System.out.println("Enter each item [If done type 'DONE'] :");
while (more) {
temp = s.nextLine();
if (temp != null) {
if (temp.toUpperCase().equals("DONE")) {
more = false;
} else {
items.add(temp);
}
}
}
save(store, items);
s.close();
}
public static void display() {
try {
ShoppingList list = mapper.readValue(file, ShoppingList.class);
System.out.println(mapper.defaultPrettyPrintingWriter()
.writeValueAsString(list));
} 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();
}
}
public static void save(String store, List<String> items) {
//load in old one
try {
ShoppingList list = mapper.readValue(file, ShoppingList.class);
System.out.println(mapper.defaultPrettyPrintingWriter()
.writeValueAsString(list));
} 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();
}
//add to end of older list
ShoppingList tempList = new ShoppingList();
tempList.setStore(store);
tempList.setItems(items);
master.add(tempList);
try {
mapper.writeValue(file, master);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I want to keep using ObjectMapper (considering im trying to learn Jackson) I just havent found a way to append yet is all. Any ideas?
To append content, you need to use Streaming API to create JsonGenerator; and then you can give this generator to ObjectMapper to write to. So something like:
JsonGenerator g = mapper.getFactory().createGenerator(outputStream);
mapper.writeValue(g, valueToWrite);
// and more
g.close();
Below method can be used to write objects into a json file in append mode. it first reads your existing json file and adds new java objects to JSON file.
public static void appendWriteToJson() {
ObjectMapper mapper = new ObjectMapper();
try {
// Object to JSON in file
JsonDaoImpl js = new JsonDaoImpl();
URL resourceUrl = js.getClass().getResource("/data/actionbean.json");
System.out.println(resourceUrl);
File file = new File(resourceUrl.toURI());
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file, true))); // append mode file writer
mapper.writeValue(out, DummyBeanObject);
} catch (Exception e) {
e.printStackTrace();
}
}
I have a Text Class to read from File, Because of long time process I don't want to read from File in one moments! and have ListView that when scrolls read remains data from File.
How should I do it brothers and sisters?
Best Regards, Minallah Tofiq
public class MyText{
private AssetManager am;
private InputStream is ;
private BufferedReader br;
private String[] text;
private String Fulltext="";
private String linetext="";
public MyText(Context context,String FILE_URL) {
am = context.getAssets();
try {
is = am.open(FILE_URL);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("READ", "cannot read from file");
}
br=new BufferedReader(new InputStreamReader(is));
}
public void process(){
try {
while((linetext=br.readLine())!= null){
Fulltext+=linetext;
}
} catch (IOException e) {
// TODO Auto-generated catch block
Log.i("ERROR", "can't read in process method");
e.printStackTrace();
}
text=Fulltext.split("\\d+");
}
public String[] returnString(){
return this.text;
}
}
You need to modify this line
while((linetext=br.readLine())!= null)
with an additional conditional. Such as
while((linetext=br.readLine())!= null && (/*your conditional here*/))
I am facing a strange programming problem. It has exhausted me but with no solution found!
My program is mainly dependent on an event (Java Listener) that is fired from an external hardware for receiving an audio message from that hardware.Inside the eventHandler i do the following
pass the received message to a static method "decode" from another class which returns data
then I open FileOutputStream, write these data "audio" to a file,and close the FileOutputStream.
I call a static method "play" from another class to play the audio file.
The problem is: whenever the method "Play" is called for the first time, it executes correctly but it causes the event to stop raising and the program to terminate but without exceptions. When I comment out the play method, everything becomes okay!
Do you have some idea about a method causing program termination ?
public void messageReceived(int to,Message message)
{
speexAudioMsg msg = (speexAudioMsg)message;
try{
byte[] output = jspeexDecoder.decode(msg.get_frame());
os = new FileOutputStream(file);
os.write(output);
os.close();
Player.play();
}
catch (IOException ex) {ex.printStackTrace();}
}
You are probably using the event thread to play the music. Try calling Player.play() in a new thread.
new Thread(new Runnable() { public void run() {Player.play()}}).start();
here is an example:
static String url = "http://www.stackoverload.com";
public static void threadTest() {
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
URL url2 = new URL(url);
url2.openStream();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).run();