Determine what started it - java

I have an interesting question today. Im trying to create a program that only starts if it is executed by a program, but will error if it is started by the user. Whats some code I can use to do this?

If by user you mean DIRECT user interaction:
You can control where a user may start the program from, e.g. button click. You may also control where another program may start the program from. So any direct issued command from a user should throw an exception; for example, when said button is clicked throw new Exception("I detect user");

Make the entry point something incompatible with
public void main ( String [ ] args ) throws Exception
like
int entryPoint ( String name )

Related

AppleScript Can't Get Argument Value Through Terminal

I'm working on a Java GUI and I'm trying to make a button that can start a FaceTime call with a given phone number. Here is an oversimplified version of the java code.
String cellNum = "18001234567";
try {
Runtime.getRuntime().exec("open /Users/faris/Desktop/call.app --args " + cellNum);
} catch (IOException e) {
e.printStackTrace();
}
After researching how do to this, I copied part of an AppleScript app I found online that I named call.app and modified it so it takes in an input argument phone number rather than manually entering it into the script. I've run the program with an actual phone number entered instead of the input variable and it works fine so I know that the problem lies with passing the argument.
call.app
on run args
set input to first item of args
open location "tel://" & input & "?audio=yes"
delay 1
tell application "System Events"
key code 36
end tell
end run
This is the error I get every time from the AppleScript.
Can’t get item 1. (-1728)
I've never used AppleScript before so I'm completely lost currently. Haven't found anything similar anywhere on SO. Any advice would be appreciated very much.
Cause:
Error -1728 in AppleScript is "Can't get «script»", indicating that the first item of args is a script object reference. This means that the command-line argument is not getting passed to your AppleScript's run handler.
Solution:
Instead of saving your AppleScript as an applet, save it (export it) as either a .scpt or an .applescript file. Then substitute your exec(...) Java command for this:
exec("osascript /path/to/applescript " + cellNum);

Method with args inside an event handler with java

Okay, Hi guys. Currently I am taking an online course and for my final project i opted to do blackjack. Everything is running fine except for when a player needs to "hit" for another card. I have the code required for a hit within a method which uses args from a different method i created
public void Hitcardp1(int p1total, String p1scard1, String p1scard2){
int p1hitcard;
p1hitcard = (int)Math.ceil(Math.random()*10);
p1total = p1total + p1hitcard;
P1Area.setText("Card: " +p1scard1+ "\nCard: " +p1scard2+ "\nCard: +p1hitcard);
}
I need to put this in an event handler for when the hit button is clicked or interacted with. However it comes up with an error saying:
"Required int, string, string
I have tried putting the args within the event handler, however, it just creates a larger error.
I am relatively new to java and would really appreciate the help
There is not enough information about your handler and class.
Error comes because of missing args.
your method have to be run as:
Hitcardp1(p1total,p1scard1,p1scard2);
also, you have missed " in your code.
P1Area.setText("Card: " +p1scard1+ "\nCard: " +p1scard2+ "\nCard: "+p1hitcard);

Using exceptions for user error

I'm working on an IRC bot that should handle some user commands, lets take !login <username> <password> for example. Sometimes the user forgets to enter their password, so instead of sending !login myUser hunter2 they might use !login myUser. In this case, the user should be replied to with an error message. The method that actually handles the command handleCommand is always wrapped by another method wrapperMethod. Which of the following ways should I use to handle user errors: should handleCommand just message the user about what happened and exit itself, or should it throw an exception with the error message and let wrapperMethod do the rest? (String[] command is the original command without the ! and split by spaces, so !login myUser hunter2 would become {"login", "myUser", "hunter2"})
Using exceptions:
public void wrapperMethod(Object sender, Object receiver, String[] command) {
try {
handleCommand(sender, receiver, command);
catch(CommandExecutionException e) {
receiver.sendTo(sender, e.getMessage());
}
}
private void handleCommand(Object sender, Object receiver, String[] command) {
if(command.length != 3)
throw new CommandExecutionException("Things went wrong");
//Do things
}
Not using exceptions:
public void wrapperMethod(Object sender, Object receiver, String[] command) {
handleCommand(sender, receiver, command);
}
private void handleCommand(Object sender, Object receiver, String[] command)
if(command.length != 3) {
receiver.sendTo(sender, "Things went wrong");
return;
}
//Do things
}
Which type should I prefer and why? Right now, I'm thinking of going with exceptions simply because I can save a few lines of code that I really don't need. When a user error is detected, handleCommand is always halted immediately. There's also the possiblility of having handleCommand return Optional<Error> or something like that, but this seems really fishy.
I prefer option with exceptions, because it separates normal processing from error handling.
In second option method handleCommand is responsible for both.
First option follows Single responsibility principle: method handleCommand handles correct flow, if something goes wrong throw exception and allow someone else cares the problem.
Moreover, assume that within section
//Do things
you find other error. If you use exception, you may keep consistent and clean pattern that any error triggers exception and someone who catch the exception cares correct handling.
Don't worry that exceptions are expensive; planes are more expensive that bikes, but if you go for vacation to Bali, use rather plane than bike (not applicable for Bali citizens:) ). Exceptions are designed for exceptions, as long as you don't use them in regular processing, it is OK.
Exceptions are expensive. Using them as flow control is strongly discouraged. It also means that your code could complete abruptly, and makes it harder to debug or read.
I'd go a different route: use Hibernate Validators. They're not difficult to set up or establish in your code, and using them means that your input is validated before you ever attempt to manipulate things. It also keeps your validation logic and actual business logic separate.
If you don't want to go that route, I'd encourage the latter approach - although, I'd use an else instead of return from a void method.

IntelliJ and getting user input

so I'm new to using IntelliJ and I've tried googling but to no avail.
I'm creating a simple java program that basically prints hello and gets the user input (name) and prints it... Just to get the ball rolling. Normal Hello World prints fine..
But as soon as I add any [args] in it just crashes? Is there a way I can type the input in?
public class Main {
public static void main(String[] args) {
System.out.println("Hello, " + args[0] + "!");
}
}
You need to provide at least 1 argument if you access args[0] otherwise you get ArrayIndexOutOfBoundsException.
Why ? because the args[] is empty without any arguments passed so accessing the first one will throw the exception
How do you input commandline argument in IntelliJ IDEA?
There's an "edit configurations" item on the Run menu. In that panel, you can create a configuration and then you can choose the Class containing main().
add VM parameters and command-line args, specify the working directory and any environment variables.
you are done.
Sorry guys figured it out:
Go to Run
Edit Configurations > on the left side make sure you're in your Main class or whatever class you're using
Enter what you want in the program arguments. i.e. "James"

How to get the stacktrace in a mobile device?

I'm getting a NullPointerException in a Nokia S40.
I want to know what is causing this exception.
The device shows:
NullPointerException java/lang/NullPointerException
This error only occurs in the device, running in the emulator the application works fine.
I use microlog to debug my application. But the application works fine if the log is enabled.
Is there a way to get the stack trace when I get this NullPointerException? I don't need all details like the line number just which method cause this exception.
UPDATE: I installed the same application in another Nokia S40 and the same error didn't occur.
Nokia 2660 - error
Nokia 6131 - no error
UPDATE 2: Somehow I find what was causing the NullPointerException.
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
public class OuterClass extends Canvas {
private Config config;
public OuterClass() {
this.config = new Config();
}
public void paint(Graphics graphics) {
HelperClass helper = new HelperClass(this.config);
helper.doStuff();
}
public void dispose() {
this.config = null;
}
public class Config implements IConfig {
public int getSomething() {
// ...
}
}
}
public class HelperClass {
private IConfig config;
public HelperClass(IConfig) {
this.config = config;
}
public doStuff() {
config.getSomething(); // Here is thrown NullPointerException
}
}
In some situations a thread is started and call the OuterClass.dispose() before the helper.doStuff() causing the NPE. I think when I enabled the log it made the thread slower and helper.doStuff() was called when I expected it to be called.
You are not going to find any way to save a Throwable stack trace on a Nokia Series40 handset.
The usual brute force way of debugging JavaME application on Series40 is to modify your code to create a stack trace yourself in memory.
What I'm talking about is:
Each Thread that you can identify (including system callback threads) needs its own Stack object, containing strings. Obviously, this increases the memory footprint of your application somewhat but keeping it in memory should limit the impact on race conditions.
When your code enters a method, it adds the method signature to the current Thread Stack. When the method exits (and you better only have one exit point per method) it pops the top of the Stack.
You can add aditional debug info on the stack, like values of variables in different places of the code.
You don't necessarily need to add this to every single method in your code.
You can add try{}catch(Throwable){} to the entry point of every thread you identified and either dump the stack in a file or on the screen (in a Form).
Obviously, this is not the kind of change you want to manually add in a lot of places in a large existing codebase. You can however make it part of your organisation coding standards for the future and write a source code parsing script to automatically add it to existing code.
I had some trouble in the past trying to print the stack trace to somewhere else than the standard output. The standard exception class doesn't provide the printStackTrace method that receives the output stream, therefore it only prints to the standard output stream.
It's possible, at least in Java SE, to redirect the java output stream to somewhere else by simply saying that System.out = . The PrintStream class receives an OutputStream, which means that you could create your own ByteArrayOutputStream, initialize a PrintStream, sets System.out to that stream, and then call ex.printStackTrace(). I don't have a J2ME environment here but I believe that, as long as it won't break when you try to set System.out to something else (nothing says that it's readonly in the docs), you should be able to do it.
After you do that, I would recommend writing it to a RecordStore that you have specifically for that, and then upload the records of that RecordStore to your server so you can get it.
I know it's not very easy but it may work. I would first test the System.out thing. If it works, everything else should work too.
My answer was wrong. As pointed out, the System.out and System.err fields are declared final. If you can't get the stack trace, and if you can't get the error when running the application on your emulator, try creating trace bullets on your code (alerts, logs, whatever you can) to isolate the piece of code where the problem is happening. It has to be something that could change between the emulator and the real device - for example, something related to retrieving/ saving records in a RecordStore, opening a Connection, etc... What did you try to do when you had the problem?
You could use Microlog to send an e-mail when the exception occurs.
Microlog
You could try catching the exception in some high-level try/catch block and then emailing the trace to yourself.

Categories