How can I launch an Eclipse command from Java? - java

How do I launch a find and replace command without the user clicking edit->find replace or ctrl+F? I need to do this with a plug-in written in Java.

The action that launches the dialog is FindInFileActionDelegate (it has a few sister types for different scopes), this is found in the org.eclipse.search plugin.
The delegates all inherit from a common parent called RetrieverAction. The RetrieverAction's run() method shows the dialog and runs the query. You can take the relevant processing from this method. You may need to register as an ISelectionListener to track the active selection.
public void run() {
IWorkbenchPage page= getWorkbenchPage();
if (page == null) {
return;
}
TextSearchQueryProvider provider= TextSearchQueryProvider.getPreferred();
String searchForString= getSearchForString(page);
if (searchForString.length() == 0) {
MessageDialog.openInformation(getShell(), SearchMessages.RetrieverAction_dialog_title, SearchMessages.RetrieverAction_empty_selection);
return;
}
try {
ISearchQuery query= createQuery(provider, searchForString);
if (query != null) {
NewSearchUI.runQueryInBackground(query);
}
} catch (OperationCanceledException ex) {
// action cancelled
} catch (CoreException e) {
ErrorDialog.openError(getShell(), SearchMessages.RetrieverAction_error_title, SearchMessages.RetrieverAction_error_message, e.getStatus());
}
}

Related

IProgressMonitor is not able to get monitor.isCanceled() method call

Good afternoon and hope you are doing great :)
I have method in which I have written new IRunnableWithProgress and I am getting progress bar and all process updates properly no issue at all.
My issue is I can see cancel button on progress bar dailog but after clicking on it nothing is happening. In short code inside if(monitor.isCanceled()){ sysout("Heloooooooooo") } is not executing at all.
please have a look at code sample :
public void runMappers(final EObject profile, final EObject list, final Notification notification) {
this.notification = notification;
getBroker().stopNotification();
final ProgressMonitorDialog pmd = new ProgressMonitorDialog(Display.getCurrent().getActiveShell());
IRunnableWithProgress rwp = new IRunnableWithProgress() {
#Override
public void run(IProgressMonitor monitor) throws InterruptedException {
if (mappers.get(profile) != null) {
int workload = mappers.get(profile).size();
monitor.beginTask("Loading DG list configurations", workload);
Pattern pattern = Pattern.compile("ProfileTo(.*?)ViewMapper");
for (final ProfileToDgListViewMapper mapper : mappers.get(profile)) {
Matcher matcher = pattern.matcher(mapper.toString());
if (matcher.find()) {
monitor.subTask("Loading DG list configuration section " + (matcher.group(1)));
}
mapper.mapProfile(profile, list, notification);
monitor.worked(1);
if(monitor.isCanceled()){
System.out.println("Heloooooooooo");
monitor.done();
Thread.currentThread().interrupt();
return;
}
}
}
monitor.done();
}
};
try {
pmd.run(false, true, rwp);
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InterruptedException e) {
}
getBroker().continueNotification();
}
I tried so many things also some stackoverflow answers, suggesting to perform it with Jobs, But i am not sure how can i call my custome method(with some attributes) in the Job.
Please let me know best suggestion
Thanks in advance ..

Imposible to force kill freezed thread in java android

I have one very unusual case when calling an Android hidden API over reflection freezes the calling thread eternally. I cannot debug the underlying code as it is a code from Android itself normally not visible. I tried running the code in an asynctask, in a normal thread but nor asynctask.cancel nor thread.interrupt kills the thread, the thread stays visible, I can see it while debugging. Is it really not possible to run a code encapsulated and kill it completely eventually?
This problems occurs only on Android O and only on some devices, that's why I need to test-run it to see if it works on the current device and be able to activate a feature according to that. The code below, I don't really see a solution for this:
Thread endCallThread;
Runnable myRunnable;
private void checkFeatureSupport(final Context context) {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
myRunnable = new Runnable() {
#Override
public void run() {
doInBackgroundWrapper();
if (getActivity() != null) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
//handleResult();
}
});
}
}
};
endCallThread = new Thread(myRunnable, "endCallThread");
endCallThread.start();
new CountDownTimer(3000, 3000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
Log.e("TESTAUTOMATION", "endCall did not finished in 3 seconds");
// stop async task if not in progress
if (endCallThread.isAlive()) {
try {
endCallThread.interrupt();
endCallThread = null;
myRunnable = null;
System.gc();
Log.e("TESTAUTOMATION", "endCallThread interrupted");
} catch (Exception ex) {
Log.e("TESTAUTOMATION", "endCallThread interrupted exception");
}
//handleResult();
}
}
}.start();
} else {
mEndCallSupported = true;
}
}
}
private void doInBackgroundWrapper() {
try {
if (getContext() == null) {
return;
}
final TelephonyManager telMan = (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE);
if (telMan == null) {
return;
}
final Class<?> classTemp = Class.forName(telMan.getClass().getName());
final Method methodTemp = classTemp.getDeclaredMethod("getITelephony");
methodTemp.setAccessible(true);
ITelephony telephonyService = (ITelephony) methodTemp.invoke(telMan);
// If this call does not return a security exception we say the call principally works.
Log.d("TESTAUTOMATION", "endCall before");
// This call endCall may freeze depending on device, mostly seen on Nexus 5x with Android 8&8.1
telephonyService.endCall();
Log.d("TESTAUTOMATION", "endCall after");
mSupported = true;
} catch (Exception ex) {
ex.printStackTrace();
mSupported = false;
}
}
To reproduce this the device should better no have a SIM inserted.
Thread.interrupt() in a common case does not stop a thread, it just marks specific boolean field (isInterrupted) as true. If a developer wants to stop thread's work at some point (after calling Thread.interrupt()) he can rely on this boolean filed Thread.isInterrupted() when he is implementing some work in a separate thread.
So I guess there is no such checking in the reflected hidden method what you are trying to call.
To stop your thread you can try deprecated Thread.stop() but it is a really bad practice.

Can I use FileInputStream without giving it a path right at the start

I am trying to upload a file to a database (a .mp4 file to be specific). But when I run my code the file path is not yet chosen because, in the program a window pops up where you can select a file you want to upload. Is there a way to achieve this?
The problem I am having with FileInputStream is that it asks for a file path at the start of my program but the path is still uncertain at that point.
Greetings Pygesux
This is where I try to INSERT into the db
public void draw() {
open.draw();
openText.draw();
if (video != null) {
upload.draw();
uploadText.draw();
}
}
public void mouseClick() {
if (open.mouseOverMe()) {
selectInput("Select a file to process:", "fileSelected");
} else if (upload.mouseOverMe()) {
uploadFile();
}
}
public void fileSelect(File selection) {
video = selection;
}
public void uploadFile() {
try {
con = database.getConnect();
java.sql.PreparedStatement statement = con.prepareStatement("INSERT INTO filmpje (filmpje) VALUES (?)");
FileInputStream input = new FileInputStream(video);
statement.setBlob(1, input);
statement.executeUpdate();
}
catch (SQLException e) {
e.printStackTrace();
}
}
Why you do not create FileInputStream after the path is chosen?
Make a method, that take path, and then creates the FileInputStream, and do other job. Call this method after you know your path, after user eneter it, and accept by pressing button/enter (it is your app logic).
I think you're trying to use selectInput() correct? The reference example is not super clear. The program continues to run while the user selects a file, so you get an error if you try to run code that requires the filename. Here's an example that tests if the file is set yet or not. You would need to update it for your particular needs:
String input;
void setup() {
size(500,200);
selectInput("Select a file...", "fileSelector");
}
void draw() {
background(255);
fill(0);
noStroke();
if (input == null) {
text("No file selected.", 20,height/2);
}
else {
text(input, 20,height/2);
}
}
void fileSelector(File selection) {
if (selection == null) {
// window closed or user hit cancel button
}
else {
input = selection.getAbsolutePath();
}
}

Event calling through showInputDialog

I'm build one application that needs a request from the user. The first version of the app I made one input window myself, but I found better change to the showInputDialog since it's it's a pre-molded tool from JOptionFrame. Now I'm having problems with the event trigger; check out the code below:
SearchScreen:
public class SearchScreen extends EventSearch{
...
public SearchScreen(){
userQuery = (String) JOptionPane.showInputDialog("Type Keywords in english to be requested below:");
}
...
}
EventSearch:
public class EventSearch extends TabBuilder{
public EventSearch() {
}
public void actionPerformed(ActionEvent Ev) {
try {
System.out.println("worked");
} catch (IOException e1) {
e1.printStackTrace(); //print failure
JOptionPane.showMessageDialog(null, "FAIL");
}
};
}
TabBuilder:
public class TabBuilder implements ActionListener {
.....
}
Then I ask, How am I supposed to call an event through showInputDialog? is it possible? Who is gonna be the listener? Thanks in Advance
I found my own answer - its indeed to carry on the code the Event Search class and pull the trigger to one action like this, Instead it's better to do:
public SearchScreen(){
userQuery = (String) JOptionPane.showInputDialog("Type Keywords in english to be requested below:");
try {
//Your Action with the String
} catch (IOException e1) {
e1.printStackTrace(); //print failure
JOptionPane.showMessageDialog(null, "FAILURE");
}
}

problems with the 2 options joption

I'm having problems with these 2 different options, the first one opens up just fine to a browser for future use, but the second option opens the browser and not the dialogue in which i'd like to have open. Also can someone tell me how to make the cancel button cancel out and not open the browser, thanks in advance here's the code.
public static void CheckForUpdates(){
Object[] possibleValues = { "Check for Updates", "Check for version ID" };
Object selectedValue = JOptionPane.showInputDialog(null,
"What would you like to do?", "",
JOptionPane.INFORMATION_MESSAGE, null,
possibleValues, possibleValues[0]);
if ( JOptionPane.YES_NO_OPTION == JOptionPane.YES_OPTION) {
try {
Desktop.getDesktop().browse(new URI("www.google.ca"));
} catch (IOException | URISyntaxException e) {
}
if ( JOptionPane.YES_NO_OPTION == JOptionPane.NO_OPTION){
JOptionPane.showMessageDialog(frame, "version ID: V1");
}
}
}
Comparing constants is deterministic, i.e. you don't get any variation in behavior.
You need to check the result of showInputDialog which is an Object value. The value is null when nothing (cancel) is selected.
if (selectedValue != null) { // anything selected?
// Check for version ID?
if (selectedValue.toString().equals(possibleValues[1])) {
JOptionPane.showMessageDialog(null, "version ID: V1");
} else {
try {
Desktop.getDesktop().browse(new URI("www.google.ca"));
} catch (IOException | URISyntaxException e) {
}
}
}
Aside: Java naming conventions show that method names start with an lowercase letter such as checkForUpdates.

Categories