I want to open Task Manager and click on its tabs like 'Process','Performance','App history', etc. by using core java only.
Tried to begin with
public class Desktop1 {
public static void main(String[] args) throws IOException {
Runtime.getRuntime().exec(System.getenv("windir") +"\\system32\\"+"Taskmgr.exe");
}
}
Exception in thread "main" java.io.IOException: Cannot run program "C:\WINDOWS\system32\Taskmgr.exe": CreateProcess error=740, The requested operation requires elevation
There are multiple ways of achieving this. The simplest way is mentioned by #mkane in his comment. Programatically, this could be achieved in the following way:
Add following dependency to your application:
<dependency>
<groupId>com.vnetpublishing.java</groupId>
<artifactId>super-user-application</artifactId>
<version>0.0.5</version>
</dependency>
Now you can make your class extend SuperUserApplication class and override its run() as:
public int run(String[] strings) {
try {
Runtime.getRuntime().exec(System.getenv("windir") +"\\system32\\"+"Taskmgr.exe");
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
Now call static run(...) of class SU passing in the instance of the class extending SuperUserApplication. Here is a complete example for your reference:
public class Main extends SuperUserApplication {
public static void main(String[] args) {
SU.run(new Main(), args);
}
// #Override
public int run(String[] strings) {
try {
Runtime.getRuntime().exec(System.getenv("windir") +"\\system32\\"+"Taskmgr.exe");
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
}
Related
I would like to two have two different methods running in catch and final blocks. I have found AutoCloseable interface, but I need something to fire in case of exception only.
Like:
SomeService service = CreateService().andOpenTransaction()
try {
service.doSomeMessyThingsInsideDB();
} catch (Exception e) {
service.rollbackTransaction();
throw e;
} finally {
service.closeConnection();
}
Is there any way to make it simpler? As I said I am familiar with AutoCloseable, but it helps me only with finally block. I still cannot use it inside the catch.
Well you could define your own interface, and then some static runner method:
public interface ErrorHandlingCloseable extends AutoCloseable {
void run() throws Exception;
void onError(Exception e);
static void execute(ErrorHandlingClosable ehc) throws Exception {
try(ErrorHandlingClosable temp = ehc) {
ehc.run();
} catch(Exception e) {
ehc.onError(e);
throw e;
}
}
}
Which you then could then call like this:
SomeService service = CreateService().andOpenTransaction();
ErrorHandlingCloseable.execute(new ErrorHandlingCloseable() {
public void run() throws Exception { service.doSomeMessyThingsInsideDB(); }
public void onError(Exception e) { service.rollbackTransaction(); }
public void close() throws Exception { service.closeConnection(); }
});
But you see, it's still messy.
You could even implement this interface in your SomeService but then you're restricted that the run() method will always call doSomeMessyThingsInsideDB().
Another way but still similar would be to use Java8 and create a helper functional interface:
public interface ThrowingRunnable {
void run() throws Exception;
}
And then a static method somewhere:
public static void execute(ThrowingRunnable action,
ThrowingRunnable onCatch,
ThrowingRunnable onFinally) throws Exception {
try(AutoCloseable ao = onFinally) {
action.run();
} catch(Exception e) {
onCatch.run();
throw e;
}
}
The interesting part is probably this: try(AutoCloseable ao = onFinally), which "registers" your onFinally method to be called when finally is reached.
This could then be called like this:
execute(
service::doSomeMessyThingsInsideDB,
service::rollbackTransaction,
service::closeConnection
);
You said you are familiar with AutoCloseable, but you don't use it.
Have you considered using try-with-resources statement?
Your code can be simplified to:
try (SomeService service = CreateService().andOpenTransaction()) {
service.doSomeMessyThingsInsideDB();
} catch(exception e){
service.rollbackTransaction();
throw e;
}
Oracle has great doc for that, including examples.
Note: A try-with-resources statement can have catch and finally blocks just like an ordinary try statement. In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.
Answering your question, this is as simple as it can get.
If your class doesn't implement Closeable then you can either implement it or use finally.
First step: Handling the exception
You evidently want the exception handled before some close. Then you need inside a try-with-resources to handle the exception.
/** throws RuntimeException */
void process(Callable<Void> work, Consumer<Exception> onFail) {
try {
work.call();
} catch (Exception e) {
onFail(e);
}
}
try (SomeService service = CreateService().andOpenTransaction()) {
process(() -> service.doSomeMessyThingsInsideDB(),
e -> {
service.rollbackTransaction();
throw new IllegalStateException(e);
});
}
This is not very satisfactory, but again also integrating the AutoCloseable, might give too few use-cases.
Second step: with AutoCloseable
<SV extends AutoCloseable> void processAutoClosing(Supplier<SV> serviceFactory,
Callable<Void> work, Consumer<Exception> onFail) {
try (SV service = serviceFactory.get()) {
process(work, onFail);
}
}
processAutoClosing(...);
I wrote a chat java application that use sockets. I have three Netbeans project, 1. Client side, 2. Server side and 3.Tester.
projects Hierarchy
In the Tester I want to start a Thread for Server class.
public class Tester {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws Exception {
//for (int i = 0; i<args.length; i++) {
final Class clazz = Class.forName("ServerSide");
new Thread(new Runnable() {
#Override
public void run() {
try{
Method main = clazz.getMethod("main", String[].class);
main.invoke(null, new Object[]{});
} catch(Exception e) {
// improper exception handling - just to keep it simple
}
}
}).start();
// }
}
}
but I always obtain ClassNotFoundException. Is the path wrong?
Thanks a lot. Sorry for the stupid question!
You must include also the package into the required classname parameter:
Class.forName("serverside.ServerSide");
Is there no way (regardless of how "hacky" it is) to detect when Java's System.err has been written to in order to be able to execute logic if and when this happens? — I'm currently working with a custom subclass of Thread (let's call it SwallowingThread) which swallows a number of exceptions in its implementation of Thread.run() in a manner similar to the following code:
public final class SwallowingThread extends Thread {
...
#Override
public void run() {
ServerSocket socket = new ServerSocket(80, 100);
try {
Socket connected = socket.accept();
// Do stuff with socket here
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In my code, however, I want to be able to handle cases of UnknownHostException and IOException which occur while using an instance of SwallowingThread; Is there no way to detect that this catching and printing to standard error after it has occured? — I had originally tried writing a UncaughtExceptionHandler to do this only to find out that it isn't catching the exceptions because they were swallowed rather than simply being e.g. wrapped in a RuntimeException and thrown onward.
Of course, a "better" way of solving this problem is to re-write the logic for the class, but is there no quick-and-dirty way of solving this issue without having to touch SwallowingThread?
You can implement your own class (I call it DelegatingErrorPrintStream) derived from PrintStream which notifies you if there's new output, and then delegates to System.err
And now you can set YOUR DelegatingErrorPrintStream as output stream for System.err using
System.setErr(err);
Full example including usage:
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
public class ErrorNotifierExample {
private static final class ErrorDelegatingPrintStream extends PrintStream {
public ErrorDelegatingPrintStream(PrintStream defaultErr)
throws FileNotFoundException, UnsupportedEncodingException {
super(defaultErr);
}
#Override
public void print(boolean b) {
super.print(b);
notifyListener(b);
}
#Override
public void print(char c) {
super.print(c);
notifyListener(c);
}
#Override
public void print(int i) {
super.print(i);
notifyListener(i);
}
#Override
public void print(long l) {
super.print(l);
notifyListener(l);
}
#Override
public void print(float f) {
super.print(f);
notifyListener(f);
}
#Override
public void print(double d) {
super.print(d);
notifyListener(d);
}
#Override
public void print(char[] s) {
super.print(s);
notifyListener(s);
}
#Override
public void print(String s) {
super.print(s);
notifyListener(s);
}
#Override
public void print(Object obj) {
super.print(obj);
notifyListener(obj);
}
#Override
public PrintStream append(CharSequence csq, int start, int end) {
notifyListener(csq); // TODO will need some special handling
return super.append(csq, start, end);
}
private void notifyListener(Object string) {
// TODO implement your handling here. System.out printing is just an
// example.
System.out.println(String.valueOf(string));
}
}
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
ErrorDelegatingPrintStream errReplacement = new ErrorDelegatingPrintStream(System.err);
System.setErr(errReplacement);
System.err.println("TEST01");
throw new RuntimeException("just a test output for ERROR handling");
}
}
As several persons already suggested, you may go with a custom PrintStream.
It will replace the standard error stream but also encapsulate it and call it when needed.
Since the exceptions and stack traces are what you are interested in, overriding print(String) should be enough (println(String) already calls this method + newLine()).
The stream could look like that :
import java.io.PrintStream;
public class CustomPrintStream extends PrintStream {
public CustomPrintStream(final PrintStream out) {
super(out);
}
#Override
public void print(final String s) {
super.print(s);
// some String is written to the error stream, Do something !
}
}
You would use it that way, at the beginning of your application, just call
System.setErr(new CustomPrintStream(System.err));
Keeps running:
package app;
import javafx.application.Application;
import javafx.stage.Stage;
public class Test extends Application {
static {
throwAnException();
}
#Override
public void start(Stage primaryStage) throws Exception {
}
public static void main(String[] args) {
launch(args);
}
private static void throwAnException() {
throw new RuntimeException();
}
}
Stops:
package app;
import javafx.application.Application;
import javafx.stage.Stage;
public class Test extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
}
public static void main(String[] args) {
throwAnException();
launch(args);
}
private static void throwAnException() {
throw new RuntimeException();
}
}
Why?
In the first case the program keeps running, even with the exception.
In the second case the program stops before calling the javafx thread.
The static initializer should run before the main method, right?
My english is vary bad so i didn't write much.
I hope you understand my question.
This is kind of a cheap answer
It keeps running because there are 4(3) other Threads running ..
when you exit/close/shutdown your application through stop() you kill it the right way, also i think, the main Thread is triggered after the stop() method so if you have an exception there, it pretty much happens after the show, if you throw the exception in the init() method the app shutdowns for real - the init() method starts two additional threads..
replace this and see
static {
new Thread(new Runnable() {
#Override
public void run() {
while(true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("There are "+ Thread.activeCount()+" still running");
}
}
}).start();
throwAnException();
}
This is something that's been bugging me for a while with regards to Program Flow.
I wanted to know if it's possible to catch an error from a Method in order to stop it from executing the Method that would normally follow it like the example bellow that I can't get to work.
public class MyClass {
public static void main(String[] args) {
// this method catches an exception and stops running
method01();
// this method will continue anyway which I don't want
method02();
};
};
I would normally have a static int variable that will initialize as 0 when the program is run and then if a method ever catches an exception it will increment that int and each method will only run if the int is 0.
This works but I was just wondering if I could replace the int shindig with exception handling.
Can you try:
try {
method01()
} catch (final Exception e) {
// do something
return; ///stop processing exit
}
the method01 will throw Exception:
private void method01() throws Exception {
// something
}
If you only want to terminate the whole program in case of an exception you just need to throw a RuntimeException without any further declaration. There are also specialized sub classes for explicit types of exceptions, like NullPointerException or IllegalStateException. See the "Direct Known Subclasses" section in the JavaDoc.
public class MyClass {
public static void main(String[] args) {
method01();
method02(); //method02 won't be called in case of an exception
}
private static void method01() {
// ...
if (true) // something goes wrong
throw new RuntimeException();
// further code won't be executed in case of an exception
}
private static void method02() {
System.out.println("method02 called");
}
}
Optionally it is possible to handle the exception with a try-catch-block:
public static void main(String[] args) {
try {
method01();
method02(); // method02 won't be called in case of an exception
} catch (Exception e) {
System.err.println("something went wrong");
}
}
// other code keeps unchanged...
If you want to enforce exception handling, you have to throw a subclass of Exception that is not derived from RuntimeException. But those exceptions have to be declared within the method Signature.
private static void method01() throws IOException {
throw new IOException();
}
You put method01 and method02 in to same try block:
public class MyClass {
public static void main(String[] args) {
try {
// This method catches an exception and stops running.
method01();
// This method will not continue if method01 have exception.
method02();
} catch (Exception e) {
e.printStackTrace();
}
}
// declare method01, method02, others...
}
Notice: You have mistakes at the end of code block ( }; }; )
Depends on what your method really does.
If your program should continue working also when an exception arise (e.g. NumberFormatException when parsing an input or in general a checked exception) a lot of people will suggest you to not use exception for flow control, but IMHO in very well defined cases (like NumberFormatException) the flow CAN be controlled by try catch statements and exceptions, it's really up to you.
A way to do so is to use the method returned parameter (also #Nikola answer works in this way, the point is to use the catch part of a try catch as flow control):
public class MyClass {
public static void main(String[] args) {
if(method01()) method02();
};
};
public boolean method01(){
try{
//some business
}catch(MyCheckedException e){
e.printStackTrace();
return false;
}
return true;
}
NB: You should use this approach only in well defined situations! If a file CAN be absent in a directory while opening it (checked FileNotFoundException), you COULD use this approach. If the file SHOULD be there and its not, the exception MUST stop the program.