Posts

Showing posts with the label Java

Profiling Java @ 2019

A good profiler can really help you in your work while coding Java (I assume while coding any coding language but I am referring to Java here) It can find memory leaks (Which object and how many of it takes the most of your limited memory?), CPU bottlenecks and other surprising data like the time consumed by each network call / DB query etc. Thus it is not so surprising to find many different java profilers around. I will try to map here the Java profiling tools lying around My short list of requirements will include the following: Profiler Requirements Constantly updated profiler (how a profiler built to profile Java6 will behave with Java11?) Clear GUI - As I will want to dive into the profiling data - it will be much simpler using UI Free (With a big advantage to the open sourced ones) (Optional) Remote profiling List of Profilers Dead Profilers (At least 5 years without an update) JIP - Java Interactive Profiler  - Last update 2010 Profiler4J - Last U...

Single Java App a Day

This idea popped into my head several days ago and doesn't leave me, so although I know I won't have time to implement it in the near future I am writing it down - feel free to steal this idea and implement it! Basic idea - for an extensive amount of time (a month? two months?) build every day a new java application, as follows: Think thoroughly about the design of the applications as they should have common componnets spanning over all of the applications, where each app will add it's added benefit (the main business login) on top of the common grounds For example, I want to have all of my applications as javafx gui applications, so I should build a common component with a main content area, a log area below that one, a menu with all common menu items already there (file->save, file->exit, help->help, help->about, help->exit) etc Each application will do an atomic action (KISS) All applications should be open sourced and on github All the commo...

Run your Java app as an EXE

My current task is deploying my JavaFX app as an EXE application Why? Because, unfortunately, "jar" files aren't looked upon (by windows) as executables which one should only double click in order to run, as if jar files are less legitimate than exe applications. This is not fair! People don't like running java applications because they need then to install a Java Virtual Machine, but they forget that in order to run those precious C# applications they need to install the .NET virtual machine, because windows does that automatically with windows updates so it is treansparent, but fundamentally they are the same, both need a virtual machine installed (JRE for java and .NET for .net apps), and a file association in order to run. Well, as I won't change the world (although I would love to see microsoft having a JRE installed using microsoft [optional] updates), I searched for a solution which will enable me to "convert" my jar file to an E...

Iterate over your whole DB using hibernate

In this post I'll assume you already have your hibernate object corresponding to your DB schema. What will we try to achieve here? I will iterate all of the DB using hibernate objects, and here is a little java program which will attempt to achieve just that: import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.HibernateException; import org.hibernate.SessionFactory; import org.hibernate.Session; import org.hibernate.Query; import org.hibernate.metadata.ClassMetadata; import java.util.Map; /** * Created by IntelliJ IDEA. * User: avih * Date: May 11, 2010 * Time: 7:43:37 AM */ public class Main { private static final SessionFactory ourSessionFactory; static { try { ourSessionFactory = new AnnotationConfiguration(). configure("hibernate.cfg.xml"). buildSessionFactory(); } catch (Throwable ex) { throw new ExceptionInInitializerError(ex); } } ...

Coding java gui using Swing designing it with CSS

Building a GUI in java isn't complicated having netbeans as a great Swing gui builder. But what if we want to have some of the design left out of the code in a CSS file? As when building a java applet which should blend with a website, out best shot will be to use the same CSS file in the swing code as we use for the website. How can we design the GUI components using swing? We will use TK-UI's SwingCSSEngine (which is opensourced). Their documentation can be reached using the following link: http://tk-ui.sourceforge.net/user-guide/cssengine/swingcssengine.html How is it done? Download the libraries: http://sourceforge.net/projects/tk-ui/files/org.akrogen.tkui.css.swing/ Copy the jar files (also those in their "lib" directory [excluding the commons if you wish]) into your project's (the swing project) lib directory. In the code before initializing the swing components (a method which is actually called init...

Log All Your Web-method Calls

After a good deal of trial-and-error, and delving into the CXF code, I've found a way to get CXF to log every web-method call -- parameters and all. Put the following into your Tomcat's log4j.xml: <logger name="org.apache.cxf.service.invoker"> <level value="trace"> </level> </logger> The level should be set to "trace" by default; you won't get ton's of output, just a line (maybe 2) every time a web method is called. Unfortunately, the line is a bit wordy, as in Invoking method public boolean com.company.entities.ws.EntityManagementImpl.login(java.lang.String,java.lang.String,java.lang.String) throws java.io.UnsupportedEncodingException on object com.company.entities.ws.EntityManagementImpl@71e6b with params [CLI, arg2, arg3]. but it was either use the built in log statement or write a whole interceptor and add it to the chain processing the call. If we get really annoyed we could always tweak the source and rebuil...

Exceptions in JUnit Tests

When an exception is thrown in a unit test, the unit test will fail, giving a red bar - unless there is a try/catch that catches the exception and swallows it quietly.  Therefore, you should make sure that catching an exception in a unit test is indeed what you really mean to do.  Should the test really handle the error and continue, perhaps succeeding, or should the test fail, giving a visual indication that something went wrong? I'd add that when the right behavior of a test case is a thrown Exception, one should add to the @TEST annotation one's expectation.  e.g. @Test(expected = NumberFormatException.class)

False condition comes true?

Image
This is a really weird bug I found in my program. I have an "if" condition, which takes a boolean variable as its condition, the variable's name is bMember. When I saw unexpected behaviour in my code and decided to debug it I saw the above surprising and un-understandable thing, the debug enters a falsed condition!? look at the picture above and see for yourselves. by the way, if someone knows why, please post a comment. Chaiavi

What does: "Fault occurred while processing" in the client mean? and how do you reveal the real exception?

I have this CXF client which sometimes throws normal exceptions but some of the other times it throws me a "Fault occurred while processing", well, what does that mean? When you get back a "Fault occurred while processing" it means that a web service threw an unchecked exception.  The CXF framework catches it and puts together a fault message which it sends back to the client.  The client’s stack trace at that point is pretty-much irrelevant . There may be a way to get CXF to log the server stack trace, but I haven’t found it yet (feel free to comment on the post if you found one).  There may also be a way to stick a handler into the flow to get the exception before constructing the fault message, but I haven’t found that yet either (ditto). If a checked-exception is thrown, then the exception – or at least its message – gets sent back to the client where it’s reconstructed and rethrown to be caught by the client. Debugging a problem like this, o...

Embed Nimbus's look and feel to your Java programs using Netbeans

This one gave me a little headache, cause it shouldn't really be an issue, but it turned out to be a non trivial tweak. What's the story? I use Netbeans 6.5 and Java 1.6.0_11 and I wanted my gui programs to "wear" the nimbus look and feel. How should I configure my netbeans gui builder to dress my program with the nimbus l&f? First thing I needed to configure my current project to use the latest JDK, it used as a default a previous version (1.6.0_07) which doesn't support the nimbus l&f. First thing was to add the latest jdk to the netbeans platform, go to Tools --> java platform and add the new jdk. The next task is to add the new jdk to the specific project; project properties --> Libraries and under the Java platform pick the new JDK to run this program.  Now that the JDK issue is set, it's time to set the actual L&F:  Project properties --> Application --> Desktop app --> Look & Feel --> com.sun.java.swing.plaf.nimbus.Nimb...

Ant Explorer graphical Ant build tool

Every serious java developer needs to create or edit some ant building script. Eclipse offers nice ant handling features which make the task much easier, eclipse's plugin (which is embeded into eclipse since version 3.1 or so) understands the ant scripting language thus enables not only syntax coloring but also nice mouse hovering which reveals values of properties, variable names which enables finding the source of each variable and also some nice debugging features. But, there is one field in which eclipse's ant handling lacks perfection, its in viewing the whole build file in one gaze graphically feature, that feature isn't supported by eclipse. Luckily enough, it is supported by YWorks, which created a nice and free util which loads an ant script file and shows it in a beautiful and so very useful way. I think that this util (which was released as a standalone as well as an eclipse and idea) is a must for any serious java developer. Unluckily, YWorks have remo...

Get a feel for what your computer can do

When examining performance with an eye to optimization, it's worth developing a feel for how fast typical software operations actually are on modern hardware. That sense will help you know when to look deeper for the real cause of a bottleneck, or when to look elsewhere, or when to mistrust the results that your profiling tools are giving you. For instance, I ran the following short bit of code: TreeSet tree = new TreeSet (); int found = 0; long time = System.currentTimeMillis(); System.out.println("add #'s to tree"); for (int i = 0; i long time2 = System.currentTimeMillis(); System.out.println("elapsed:  " + (time2 - time)); System.out.println("find #'s in tree"); for (int i = 0; i     if (tree.contains(Math.random())) found++; long time3 = System.currentTimeMillis(); System.out.println("elapsed:  " + (time3 - time2)); Here's the output: add #'s to tree elapsed: 8240 find #'s in tree elapsed: 5476 We see that filling a J...

Use Parent/Interface types rather than implementation types

If you've got a method that returns, say, a  TreeMap  pointer, you can generally declare it to return a  Map ; you're unlikely to use a method of TreeMap  that isn't a method of  Map  (if there even are such things), so the calling code won't be affected. This allows you, though, to change the implementation class to, say,  HashMap  without any other code being affected. The same goes for parameters passed into a method. In general, only explicitly use the implementation type when creating the instance [i.e. new ()]. [ NOTE : There's an issue peculiar to C++ where one must make sure that the implementation class' destructor is virtual, or it won't be executed when one deletes a pointer of the parent-class type.]

The use of Java Sets

The Set interface requires that the underlying implementation can tell whether two objects added to it are the same, so that the second can be rejected (a Set is defined as only containing one copy of any given object).  Ensuring adherence to this requirement involves both the Set implementation and the mechanism by which the objects can be distinguished from one-another.  The two basic implementations that i use in my code, TreeSet and HashSet , handle this in different ways: TreeSets are ordered b-trees (or something very similar) of objects.  Because they’re ordered, the objects they contain must implement the Comparable interface, or alternatively the TreeSet itself may have a Comparator member; in either case, a compareTo () method is called to compare objects to one another.  compareTo () returns -1, 0 or 1, depending on whether the first argument is less than, equal to or greater than the second; this is how the nodes in the tree are ordered, and how the Tre...

JavaDoc tool doesn't export the Method's Javadocs

My boss wanted me to deliver a full list of all of my JUnit tests I did on my code. When he saw my exasperated expression he offered me to just export the test's javadocs and deliver it as a report, well that made me happy :-) I've adopted writing javadocs all of the time as a good coding practice, so this task shouldn't have made me any problems, but... it did. As you well know, I use Eclipse as my IDE, so I just went to file --> export --> javadoc. Cool, everything seemed to work like a charm, till I looked at the javadocs - all was documented nicely except for - the method's javadocs, and that is where most of my javadocs are written. What was my problem? I found out that because I use JUnit 4 as my unit testing engine, I must use a @Test annotation, then I write my javadoc, here's my bug, apparently, when the tool sees an annotation it assumes the method's declaration has started, so when it tries exporting javadocs it doesn't look after any annota...

Help me become a great Java developer - What should I learn?

This is the subject of an email I got today, the rest of the email is as follows: Hi Chaiavi, Whats up? I didn't work on java for a while now, i am trying to become the best Java developer ever - well not ever there will always be you ;-) so that in the future job interviews i will actually know something :-) and i need your help to guide me in the right direction :- where to start? what are more/less impotent subjects? what are the best places to learn from, so that I will learn a lot in short time with as little effort as possible that it will be easy fun and not boring and that I can finish before the next job interview (whenever it will be) i am looking for online sites, video eLearning and even books if they are really good (since books takes a lot of time to learn from) you know what, ignore everything i just said and just guide me into becoming the great Java developer i can be. Thanks, John Doe. -------------------------------------------------------------------------------...

Bad Unmarshalling of a CXF object which results in a null object

The story in short: I have a webservice which gathers some information from my DB, creates an object containing the info, then sends it to my client. Sounds like a simple CXF webservice scene? Well, for the last two days i'm fighting it; why? Cause my client gets only a nullified object, it's quite frustrating... So i caused some logs to appear and discovered that - The SOAP message actually contains the whole Object. My client just can't build it (Unmarshal it) into the object it's supposed to be. So, whose fault is it and how do I fix it? Aegis' binding is my guess (not that it helps much), so that's the road i'm taking. What did I find (OK, what did my boss find?) ? Here are some interesting things that I learned in the process of getting the Peering WS client to connect up with the Peering WS: The basic mechanism for serializing and deserializing the data of a web service is the databinding implementation.  I’ve been using Aegis, which is described ...

JUnit 4 Template Class

Each time I want to create a JUnit test class, I take a look at an older one, copy it, then remove all of the specifics of the previous tests. That isn't a good practice  :-) So I've decided to do it once more, in order to create a template - a working JUnit class which doesn't do anything, just add your specific code you want to test and run along: package org.chaiavi.TestJunit; import java.io.IOException; import org.junit.*; import static org.junit.Assert.*; public class TestJunit{ /** Use this method for all of the lines of code you want to run before the whole JUnit Class. */ @BeforeClass     public static void unitSetup() throws Exception { } /** Use this method for all of the lines of code you want to run after the whole JUnit Class. */ @AfterClass     public static void unitCleanup() throws Exception {     }  /** Use this method for all of the lines of code you want to run before each JUnit test. */ @Before     public void methodSetup() throws Exception ...

How do you know that your Unit tests cover all of your code? use a good Code Coverage tool

Unit Tests and Code Coverage Unit Tests In computer programming, unit testing is a procedure used to validate that individual units of source code are working properly. A unit is the smallest testable part of an application. In procedural programming a unit may be an individual program, function, procedure, etc., while in object-oriented programming, the smallest unit is a method; which may belong to a base/super class, abstract class or derived/child class. Ideally, each test case is independent from the others; mock objects and test harnesses can be used to assist testing a module in isolation. Unit testing is typically done by developers and not by end-users. (Taken from WikiPedia) Code Coverage The Unit tests are a good measure of testing, but how much of the code is being covered? Did the unit test check all of the paths of the code flow? These are the issues the Code coverage helps us solve. The Code Coverage Tools run the Unit Tests we created and tell us explicitly how much cod...

Did you try parsing a number residing in a String and an exception occured when that number was 8 or 9?

Parsing String numbers When parsing numbers residing in Strings one should pay attention to the parsing method. There are several parsing methods in the Integer Class, and not all of them parse the numbers in a Decimal (Base 10) order. For example if you'll try running the following line of code - an exception will be thrown: Integer i = Integer.decode("09"); The exception will be thrown due to the simple fact that there is no numeric character 09 when you use an Octalic counting base (Which is the decode method's default). Try using a different method for a Decimal based number. So, in order to correct our specific example we should use: Integer i = Integer.parseInt("09");