Question Setup
There are a few moving parts to this question, so I will try to do my best to replicate the issue in its simplest form.
I am attempting to add a TrayIcon to a SystemTray. This is typically a very simple objective on operating systems ("platforms") that support the call (this will play an integral part in a few moments).
I am programming for and on a Windows machine, presently (this is not a question about interoperability).
Here's the logic behind the code I've got that works:
public class SomeClass {
public static void main(String[] args) {
if(SystemTray.isSupported()) {
// DO SOMETHING TO ADD AN ICON
}
}
}
With all of its inclusions, this works. However, what I am really after, is the ability to inject the SystemTray instance with it's icon already "ready to go".
That code looks something a little more like this:
public class SomeClass extends NecessarySpringExtension {
private #Setter(onMethod=#_#Resource(name="SystemTrayControl"))) SystemTrayControl systemTrayControl;
// The above uses Lombok, as well.
public static void main(String[] args) {
// DO SOME RELATED STUFF like setting the configurations for
// for the application
}
}
The resource returns an instance (#Bean) of the SystemTrayControl class which, itself, makes a call to SystemTray; however, now, SystemTray is no longer supported (see some explanation in the The Question section, below).
Some Change Detail
Here's a snippet of some of that code (obviously, I've got my head submerged in the issue. Let me know if the context needs expanding. My belief is the following should be enough code to give you a sense of the structure):
SystemTrayControl Class:
#PostConstruct
public void showIcon() {
if (SystemTray.isSupported()) {
val tray = SystemTray.getSystemTray(); ....
Resource Class:
#Configuration
public class BeansForNeeds {
#Bean
public SystemTrayControl systemTrayControl() {
return new SystemTrayControl():
} ....
For the sake of more context: if I remove the condition seen in the SystemTrayControl class , I get a HeadlessException (which I've done a bit of reading on).
The Question
The issue stems from that fact that when utilizing a SpringApplicationBuilder in your program, the .headless property defaults to true. The javadoc states:
Sets if the application is headless and should not instantiate AWT.
Defaults to true to prevent java icons appearing
If I manually set the property to false, then the application runs well; however, I am always a bit "shaky" overwriting default behavior, particular if the language of "prevents" x, y, or z makes into the mix.
So, the question is:
Why is the property defaulted to true? What are the side effects of allowing the behavior prohibited by .headless? What's it got against AWT?
Once upon a time, pulling in the AWT classes (and native stuff) on a true headless box like Unix without X would cause runtime exceptions and other nasty OS level failures. And the errors would only happen once the classes were loaded, so it could be slightly non-deterministic.
This was with Java 6 or so, I recall.Things may have changed since then. And I suppose it is important that it was a problem only for the AIX Java, which is a clean-room Java that is not based on the Sun reference implementation. It wasn't strictly a bug, though, because the reference implementations just escaped the same problem by mistake when I looked at the code for each.
In my case, we had to be careful in some startup code to not accidentally use a handy utility class if it touched AWT, because then all of it would be pulled in, and fall over as it ran into missing native UI. This would never happen on Windows, where a lot of development took place. But once deployed on a true headless AIX box the app would fail hard with a runtime exception that bubbled right up to the user.
This is because we had "client" code (that was, ostensibly, headless and did not rely on the any UI code) and "UI" code (that knew how to interact with a command line or a full Swing GUI.) The client code was changed such that it pulled in some handy utility class (I forget which one) but this caused the VM to pull in some other classes, which pulled in AWT, which hit some native code expecting there to be a native UI of some sort.
Since the AIX box had no X, these native components were not there, and the whole thing fell apart with a translated native/runtime exception.
So, not only did we have to run the VM headless, we had to make sure our code did not accidentally reference any AWT code, either directly or indirectly.
I'd want to do more research to see how this scenario interacts with the property discussed here, but the key takeaway for me is that cross-platform means cross-platform! And "headless" can mean something very specific on different platforms.
Related
I'm pretty new to java in general so I've been following a plethora of tutorials. so FEEL FREE TO CORRECT ME AT EVERY TURN! (yes even in code inefficiencies as well!!)
I currently have the issue of getting a single method to return different subclasses/types from a superclass.
The problem code is at the bottom of the post.
Get ready because I'm going to throw this at you.
I've run into a Java language barrier.
I'm in the process of following a tutorial(libGDX) to use LibGDX and another tutorial to implement component based design (see link just below)
I've never seen Objective-C code until now so these are my feeble attempts to convert the tutorial code(component design) to java
Currently the idea is to have an Entity that will use various Components to access different functional abilities(health, rendering, movement, etc) inside the game.
I'm attempting to get the Component associated with an Entity and check its fields, but I've run into some sort of issue with returning class types.
Component System
Component.java
public class Component {
}
HealthComponent.java
public class HealthComponent extends Component{
public boolean alive;
}
RenderComponent.java
public class RenderComponent extends Component {
public boolean canRender;
}
Entity System
I store Entitys with their Components each within a list(ArrayMap[LibGDX]) of available active Components so that I can get all Entitys using a specified Component. Or in this case, get a specific Component associated with an Entity
Entity.java
public class Entity {
private int eid;
public Entity (int eid) {
this.eid = eid;
}
public int eid () {
return this.eid;
}
}
EntityManager.java
public class EntityManager {
public ArrayMap<String, ArrayMap<Integer, Component>> componentsByClass;
// Some other stuff like constructors and methods
public Component getComponentOfClassForEntity(Component component, Entity entity) {
//returns Component type
return componentsByClass.get(component.getClass().getSimpleName()).get(entity.eid());
}
}
My problem comes to this part
My understanding is in order to stay as DRY as possible I don't want to have multiple different methods for each Component subclass just to return a different class type for the ExampleComponent. It would be very convenient if I could get this working smoothly with some sort of type/class smoother outer awesome thingy without any crazy hacks that are bad practices. Also, I'm assuming some if/then statements could work but it seems like there is a better way what with my limited knowledge and all.
I attempt to :
Component health = this.entityManager.getComponentOfClassForEntity(healthComponent, entity);
// No errors, however I don't really have a health component now do I?...Trying out:
if((HealthComponent)health.alive) // Cannot resolve symbol "alive"...
or the same but change the type:
HealthComponent health = this.entityManager.getComponentOfClassForEntity(healthComponent, entity);
// Required: HealthComponent
// Found: Component
// Sucks as I'd like to be able able to follow the DRY conventionthingy:
RenderComponent render = this.entityManager.getComponentOfClassForEntity(renderComponent, entity);
if(render.canRender))//plsssrenddrr
etc...
In full, I understand that you're not supposed to be able to do that, but my question is what is an ideal solution that doesn't break convention or make for a hacky and poorly coded game.
Perhaps there's a better Component based Architecture out there that is a cleaner and more do-able solution...
Thanks so much!!
I recommend you take the DRY principle to its logical conclusion and Don't Repeat Someone Else (if someone can turn that into a snazzy acronym, then let me know).
There are some good ECS libraries for Java already out there, and I highly recommend that you try to use (or extend) one of those instead of creating your own. Quite frankly, if you try to build an ECS of your own, you're probably never going to finish the game itself.
Out of the many ECS available, I'm going to recommend you start with Ashley or Artemis.
Ashley is a light-weight ECS that appears to be affiliated with the libGDX group in some way- the libGDX setup tool gives you the option to include Ashley in the gradle files it generates for you. In my humble opinion, it has more boilerplate code than I'd like, but that also means it's doing less black magic (i.e. reflection).
I personally moved to Artemis because of the syntax benefits, and it appears to be further optimized and more actively maintained. If you want to add it to your game, you can follow the instructions here.
All that being said, these are both great libraries which deserve a more in-depth comparison, and so long as you use one of these (or another ECS library) it should allow you to accomplish your goal.
Now if you're more interested in making the ECS than the game (and I've totally been there), I would still recommend you look at the approaches these two libraries took (their code is on GitHub) and see how they dealt with the syntax issue.
Is there a way to detect the end of the bootstrapping phase of the JVM?
edit::
so to provide a bit more context, what i am trying to do is to instrument the JDK. And this is a full blown instrumentation that records every LOAD, STORE, INVOKE byte code instruction. As the instructions are executed their data is sent to a static method, that is loaded from the xbootclasspath. This static method captures all this information and stores all of this as a trace for performing analysis at a later time.
Now, when i do this for the JDK, i do not want to disturb the way classes are loaded in the JVM, which might result in a program crash. I was guessing that the best way to go about it is to detect the point in time when the JVM is done bootstrapping, so that I can safely turn on my instrumentation thereafter. (I plan to not instrument any of the code, while the bootstrapping is taking place.) Is this even the right way to go about it?
In addition to my previous comment about looking into FERRARI and MAJOR I want to say several things:
Both tools are only available for download as compiled Java JAR archives.
So I wrote to the scientists who have created those tools today and asked them our question. As soon as I will receive an answer I will report back here.
Anyway, I have looked into FERRARI's architecture and think I may have found out how they do it.
So here is my educated guess (still untested) about what you could do:
Instrument your JDK classes.
Add one simple class BootstrapLock as described below.
Re-pack the instrumented + the new class into a modified rt.jar.
Write a little dummy Java agent as described below.
public class BootstrapLock {
private static volatile boolean inBootstrap = true;
public static boolean inBootstrap() {
return inBootstrap;
}
public static synchronized void setEndOfBS() {
inBootstrap = false;
}
}
public class DummyAgent {
public static void premain(String options, Instrumentation ins) {
BootstrapLock.setEndOfBS();
}
}
So basically the logic is as follows:
Agents are loaded before the main application class, but after bootstrapping.
Thus the very fact that the agent is active means that bootstrapping is finished.
Thus the agent can switch off the global marker inBootstrap.
Your instrumented classes can check the marker in order to determine if their additional instrumentation code should be bypassed or not.
I am unsure if I have enough time to test this anytime soon, but at least I wanted to post this answer here so maybe you, Vijai, can also look into it and provide some feedback. Four eyes see more than two...
Update: One of the FERRARI authors has answered my inquiry and confirmed my explanation above. You can just use a java agent as a marker of JVM having finished its bootstrapping. Maybe you do not even need the additional class, but just check if the agent has been loaded into the JVM yet. It would make things even simpler, I just do not know if it performs well. Just test it.
EDIT: There must be some way I can approach this without writing a whole new debugger. I'm currently looking into ways to build on top of the existing java debugger. If anyone has any ideas on how to grab information the Java debugger already has (about stack frames, variables, raw data etc.), that would be really helpful.
--
What I'm trying to do is I have this framework/API built on Java, and I would like to write an eclipse plugin debugger that is customized to my framework. Here is a simple example:
I have two classes, one called scope and one called variable. The scope holds a map of variables. The code is all in java, but I'm using this scope-variable relationship almost like a new language, and would like a variable debug tab that gives me a list of currently active scopes with the variables that are currently stored inside. Here is some code:
import java.util.Hashtable;
public class Scope {
private Hashtable<String, Variable> variableList = new Hashtable<String, Variable>();
// constructor
public Scope(){
}
public void put(String key, Variable v){
variableList.put(key, v);
}
public Variable get(String key){
return variableList.get(key);
}
}
public class Variable {
private String value;
private String name;
public Variable(String aName, String aValue){
name = aName;
value = aValue;
}
public String getValue(){
return value;
}
public String getName(){
return name;
}
public void setValue(String aValue){
value = aValue;
}
}
This is obviously an extremely simple example, but I would like to accomplish something similar to this where I can get a variables window, set a breakpoint, and have a "debugger" list out my active scope objects and the variable objects inside.
I've been trying to read and understand: http://www.eclipse.org/articles/Article-Debugger/how-to.html
and its pretty dense (as well as extremely outdated), but I will try to take some time to understand it. I just wanted to see if anyone had any high level recommendations on how to approach this type of problem, as I have little experience developing plugins in eclipse or making debuggers.
Thanks!
Not an easy task. That article is still the main reference, I think. Old, but not outdated. Try to digest it, and preferably to make it work. Before it, you should have a minimal experience developing Eclipse plugins.
There are many pieces in the picture, but the first thing you must understand is that when Eclipse is debugging something (assuming we are using the standard debug model), we have two separate "worlds": the Eclipse side, and the interpreter side (or, if you prefer, the "local" and "remote" sides).
Int the Eclipse side, the programming involves a cooperation between some Eclipse core classes and some classes of your own, which extend or implement some Eclipse classes/interfaces:
A "launchConfigurationType" (extension point in your plugin.xml) which causes the apparition of a new custom configuration when you click "Debug As -> New Configuration); this goes togetther with some "launchConfigurationTabGroups" definition that defines the "Tabs" dialogs that will appear in your custom launch configuration (eg) (each Tab will have its own class typically).
The launchConfigurationType is typically associated to a LaunchDelegate class, which is sort of your bootstrap class: it has the responsability of creating and starting a running/debugging instance, both on the Eclipse side and on the "interpreter" (or "remote") side.
On the Eclipse side, the running/debugging instance is represented by a IDebugTarget object and its children (the implementation is your responsability); this is created by the LaunchDelegate and "attached" to the remotely running process at launching time.
The remote side, the interpreter or program you are actually debugging, can be anything: a binary executable, a perl script, some app running in a some site (perhaps also a local Java program; but, even in this case, this would probably run in its own JVM, not in the debugging Eclipse JVM!). Your IDebugTarget object must know how to communicate to the "remote interpreter" (eg, by TCP) and perform the typical debugger tasks (place breakpoints, step, run, ask for variables, etc) - but the protocol here is up to you, it's entirely arbitrary.
What is not arbitrary is the hierarchy of your custom classes that the running Eclipse debugger will use: these should have a IDebugTarget as root, and should implement "The debug model" (see figure in article). As said above, the IDebugTarget object is who understands how to make the translation between the EClipse side and the remote side (see this image)
having worked on the eclipse edc debugger, it sounds like writing a whole debugger is not so much what you want.
it sounds like while running the debugger, you will have access to the objects that have the variables and scopes you are interested in.
you can use toString() in the classes themselves or use detail formatters to display a variation on the information you want. the toString() call can get quite detailed and nest into calls, show whole arrays, etc. detail formatters can also be quite complex.
see http://www.robertwloch.net/2012/01/eclipse-tips-tricks-detail-formatter/ . it's the best of several URLs (i have no association with the author).
once you are happy with the output of the Variable and Scope objects, you should be able to add watch expressions that will always show them in your expressions window (thus you don't have to rely on local variables in the stack frame you may be in).
this should then give you the list of Variables and Scopes from your framework that you are tracking … hopefully without having to write an entire eclipse debugger plugin to do so.
ok, i'm going to add a second answer here … i guess i'm not familiar enough with the state of your environment to know why custom detail formatters would not do the trick. for most cases, i think they'll provide you what you're looking for.
but if you're really interested in creating another view holding these items, then you could check out the eclipse jdt project . it's entirely possible that the extension points it provides will give you access to the internal variables and stack-frame information that you're looking to add, and also perhaps some UI that will make your job easier.
in other words, you might not have to write an entirely new debugger plugin, but perhaps a plug-in that can work together with jdt.
the site has pointers to the project plan, source repositories, the bugzilla issue tracking database (used for both bug-tracking and new feature discussion). perhaps some of those who are experts on jdt can help weigh in with their opinions about what will best suit your needs.
I am working on a fairly complex Java application using Swing.
On some occasions there are unwanted beeps without any user intervention. No crash, application keeps working fine, I'm respecting the EDT rules etc.
Yet in some cases a beep can be heard: I may be doing something silly triggering that beep but in any case it s not a user action for it can happen upon importing data, when the user is away.
Is it possible, for a Java application that should never ever emit any sound to configure it, say by setting a property for the whole application that says: "dont' ever emit a beep"?
I ve been Googling for that issue and I ve found message by people having the same issue but no answer: all I found was some hack saying that there was a known issue with JEditorPane and that using a putProperty("IgnoreCharsetDirective", Boolean.TRUE) was helpful to make unwanted beeps happen less often. Yet information is very scarce on the subject.
It s a real issue because the application is used in an environment where the sound is needed on the computer, but this Java application emitting noise is unacceptable.
Your problem is discussed on the Java Forum:
// Write a custom toolkit
public class MyToolkit extends sun.awt.windows.WToolkit
{
public void beep() {
}
}
// Set this property
System.setProperty("awt.toolkit", "MyPackage.MyToolkit");
NOTE: The use of this workaround is discouraged. You should still try to find the root of the problem.
Edit: Removed a link, since the thread on Java Forum is now offline.
In Swing you need to override the LookAndFeel as follows:
UIManager.setLookAndFeel(new NimbusLookAndFeel() {
#Override
public void provideErrorFeedback(Component component) {
// Your beep decision goes here
// You want error feedback
super.provideErrorFeedback(component);
}
});
Typically your beep decision would reference some kind of external configuration/preferences flag for your application.
I am looking for a way to remove all uses of a particular class, including the class itself, at compile time. Basically a form of pre-processing, but I'd like to do it without having to surround all the instances with #ifdebug ... #endif.
Is there any ant-based tool out there that can do this? If not, can anyone point me in the right direction for how to write such a tool? (not a minor undertaking I know, but if its the only option...)
The situation is I have a helper class for debugging function calls. This is instantiated at the beginning of a function and a call is made at the end. This is a JavaME application so I'm nervous about the overhead this is adding to performance. I already have a release and debug build that have pre-processor directives using ProGuard, so I would like to exclude the use of this helper class from the release build. It doesn't appear this can be done with ProGuard.
"This is instantiated at the beginning of a function and a call is made at the end. "
If this is all over your code maybe you need to look at AOP.
or a state design pattern for the helper class, in test mode it does one thing but in prod it does another(like nothing)
Do you know that this debug code will make the JavaME app slow? You could also try creating a way to conditionally call these debug methods.
A few more ideas ... I've never written a JavaME app, but I assume there is way to run/test with running on the actual device. Given this way of running/testing, perhaps you can use Eclipse/Netbeans to debug your code and use proper breakpoints instead of programmatically tracing method calls. No harm to compiled code in this case. Also consider using AspectJ to trace method calls, this can be conditionally done after code is compiled since AspectJ alters bytecode directly (not sure how this plays with JavaME). Lastly, I've heard of people using the standard GNU C/C++ preprocessor on Java. I have no idea if it works, google will help you.
Not exactly what you want but...
You could separate your code to modules (core and debug, in your case), then make sure modules call each other via reflection: use an interface available in core, create a wrapper class in core that will hide object instantiation via reflection detail/
Then, on production, just omit the debug code and have the wrapper "do nothing" if the instantiation fail / when you set a specific flag.
This way your debug classes won't make it into production and you won't have to "statically link" to them so your core production code won't care.
Of course, this is only possible if your debug code has no side effects visible to core code, but it seems that's your case (from your problem description).
Is it possible to just create the class once, on application startup, instead of creating an instance for each method? Your debug class could then look like this:
public class Debug // maybe make this a *gasp* singleton?
{
public static void start(); // called at start of method
public static void end(); // called at end, probably should be in a finally block
public static void setDebugMode(boolean debugOn); // turn off for production mode
}
Set debug mode to "true" in testing but "false" in production. When debug mode is off, none of the methods do anything (except check the state of debug mode, of course).
You don't avoid the overhead of the function call, and you do need to check the state of that boolean, but you do get to avoid jumping through hoops trying to avoid load the class at all.
This will need more work if you have a multithreaded application, too.