Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Wednesday, May 18, 2022

So Many Things Forgotten

 I have an ArrayList<ArgTypes> 

public class ArgTypes 

{

// Instance

String argName;

ArgValueTypes argumentValueType;

double doubleValue;

boolean booleanValue;

int intValue;


// Constructor of each pair

public ArgTypes (String inputArgName, ArgValueTypes inputArgumentValueType, double target)

{

this.argName = inputArgName;

this.argumentValueType = inputArgumentValueType;

this.doubleValue = target;

}

};

doubleValy, booleanValue, and intValue in my C implementation of this code are a union that is a pointer to various variables.  My goal is to Double.ParseDouble a String and store the double into a variable for later reference.  In C, I store a double* and then use indirection to store the value where I want it.  What is the equivalent in Java.  Is there one?

Thursday, May 12, 2022

Java

 


I still find it frustrating that what C lets you do with an array of structs requires something this:

ArrayList<ArgTypes> argumentList = new ArrayList<ArgTypes>();
argumentList.add(new ArgTypes("-f", ArgValueTypes.DOUBLE, feedRate)); 
argumentList.add(new ArgTypes("-xs", ArgValueTypes.DOUBLE, xStart));
argumentList.add(new ArgTypes("-xe", ArgValueTypes.DOUBLE, xEnd));
argumentList.add(new ArgTypes("-ys", ArgValueTypes.DOUBLE, yStart));
argumentList.add(new ArgTypes("-ye", ArgValueTypes.DOUBLE, yEnd));

You should not need to execute code for a static array.

And while it is profoundly type unsafe, I miss union.  Unsafe types are dangerous, but fun.

C has a small number of primitive types and operators and a swarm of library functions to do just about everything reasonable; Java has the NATO of classes that once you learn them can make the Galactic Empire run in fear 

Wednesday, May 11, 2022

Java Initialize Array of Structs

A couple days ago I asked a couple Java questions that I knew perfectly in 2014 before my stroke.  There are still some mysteries there but one think that is easy in C seems to be clumsy in Java.  Initialize an array of structs without any code.  In Java you apparently need to initialize each element of the array with a new StructClass (...).  This is clumsy and ugly.

It Has Been a Long Time Since I Wrote Java

 package ArgTypes;

enum argumentValueTypes (double=0, bool=1, int=2);

// Constructor of individual pairs of argument names and types

public class ArgTypes 

{

// Instance

String argName;

argumentValueTypes argumentValueType;

// Constructor of each pair

public ArgTypes (String argName, argumentValueTypes argumentValueType)

{

this.argName = argName;

this.argumentValueType = argumentValueType;

}

}

The error messages:

Multiple markers at this line
- The declared package "" does not match the expected package 
"ArgTypes"
- The import ArgTypes cannot be resolved
- Syntax error, insert ")" to complete Arguments
- Syntax error on token "=", ( expected

What does this mean?  There is no package "".  I think it is automatically creating imports for class ArgTypes.

Wednesday, March 25, 2020

Redirecting Stdout in Eclipse

There must be some way to redirect stdout from the console to a file in Eclipse.  No instructions that I can find look like Eclipse Oxygen.  I used to know how to execute java classes from the command line. (All my early Java programming was using a command shell, the javac compiler, and emacs.  I mentioned in a job interview once and the interviewer was clearly blown away.  IDEs are nice, but hardly necessary.) 

Not as elegant as redirecting stdout:

import java.io.FileOutputStream;
import java.io.PrintStream;
 
 
System.setOut(new PrintStream(new FileOutputStream("output.txt")));
System.out.println("This is test output");

Monday, March 23, 2020

Using Map in Java

I need to translate some strings (state abbreviations for example) into corresponding integers.  There is a way to use Map to simplify this, but the examples that I am fjnding are less than clear.  There are three different tables that I need to do lookups in, and each table is static.  I am guessing that the method is something like:

public class Lookup {
    public int LookupTable(HashMap(String, Integer) table, String toLookup)
        return (table.get(toLookup));
    }
}

But how do I statically define the HashMap that I will pass to this method?
This ought to do it, I think.

    Map states = new HashMap();
    states.put("AL", new Integer(1));


But I still get errors  about syntax error on the semicolon on the states.put line.  Every example that I can find looks like this:

    HashMap states = new HashMap();
    states.put(1, "AL");


So why does my put call fail syntactically?  Not in a method.

Sunday, March 22, 2020

Writing Java Again

And finding the sort of puzzles that kept me gainfully employed for so many years. Trying to tokenize a TAB-delimited line exported from Excel, StringTokenize almost does what I want.  But empty cells produce two tabs in a row, and it seems StringTokenize ignores two tabs in a row, treating them as one tab.  Mysteries.

Definitely works in mysterious ways.  \
 
t\tThird\tFourth

keeps producing tokens with a single tab character out to infinity (or at least, index out of range).

Friday, November 2, 2018

Java Coming Back to Me Slowly

ArrayList[] argList = new ArrayList();
argList.add(new ArgList("-zs", ArgValues.FLOAT));

That first line has the error "Type Mismatch: Cannot convert from ArrayList to ArrayList"

Huh?

In C this would be something like

argList[] args = [{-zs", "FLOAT}. "-ze", FLOAT}];


I was trying to do this the hard way:
ArgList[] argList = {
new ArgList("-zs", ArgValues.FLOAT),
new ArgList("-zi", ArgValues.FLOAT),
new ArgList("-ze", ArgValues.FLOAT)};

Friday, October 26, 2018

Java

C was my first modern programming language (okay, Pascal, but I only wrote a few Pascal programs) and like your first girlfriend, there are details you will never forget, like the powerful emotions when you smell her perfume in an elevator, but finally:


An awesome song, and an awesome video.

"If I code you like this": my wife's attempt at parody.

Monday, April 28, 2014

Code Coverage Tools For MyEclipse (And Doubtless For Eclipse Too)

At one of the technical sessions of the Idaho Technical Council last week, one speaker asked how many were using code coverage tools.  I was startled to see no hands.  (It was a big room, so I might have missed some behind a column.)

If you are only peripherally involved in software development, I should explain what a code coverage tool does.  It provides a way to find out what percentage of the code in your application is actually being executed, and shows with appropriate colors whether particular parts of your classes are being partially executed, completely executed, or not executed at all.  This is especially useful, in my experience, when writing automated unit tests.  Running code coverage tools in conjunction with automated unit tests tells you how thorough your unit tests are.  If only 15% of the code in the classes that are supposed to be tested are actually being executed, you need to improve your unit tests to be more thorough -- or figure out if you have code that cannot actually be executed.

I confess to being a bit surprised at the lack of code coverage tool use.  At a previous employer, I made extensive use of Visual Studio's code coverage tools to see how thoroughly my unit tests were testing various classes.  I assumed that there were code coverage tools for Eclipse and MyEclipse, but for various reasons, simply have not put much time into finding them.  There is one called EclEmma that I have installed in MyEclipse, and I believe works with the open source Eclipse as well, that works pretty well.

Friday, April 25, 2014

Copying In Object-Oriented Languages: Be Careful What You Ask For

My boss brought to my attention that one part of the application showed 20 movement records for a particular offender -- but when we brought up the list, it showed 20 copies of the same movement record.  The Informix SPL being called returned 20 rows, all different.

On investigation, it turned out that the code was doing something like:

CNoteVO cnoteVO = some trash that filled it in
ArrayList resultList = new ArrayList();
and then for every row of data returned by the SPL:

 loadData(cnoteVO);
  resultList.add(cnoteVO);

Of course, because cnoteVO was the same object each time, the resultList.add call was just storing a pointer to the same cnoteVO object each time, and at the end of processing those 20 rows, we now had twenty pointers to the same cnoteVO -- which meant that whatever was stored in cnoteVO most recently was duplicated 20 times.

The solution was to write a clone() method -- but of course, nothing is ever that simple, because CNoteVO is a superclass, and you can't really easily write a clone() method that will handle all the subclasses.  (There is a way, with reflection, but I wanted to make sure that I understand this perfectly.)  Instead, I defined clone() in CNoteVO as an abstract class, and defined a concrete clone() method in each of the subclasses.  Now:

   cnoteVO = loadData();
   CNoteVO curRow = cnoteVO.clone();
   resultList.add(curRow);

Now every row is a distinct and different object, and I get 20 rows that are all different.

It has been many years since I ran into an issue like this; it is the only thing that helps me keep my sanity at work.

UPDATE: Of course, this isn't specific to OOPs.  I have seen this mistake made (and probably made it myself) in C, where the temptation is strong to reuse a malloced block, and then store the pointer to that block instead of doing another malloc.

Monday, July 22, 2013

Java Mysteries

If you aren't a computer nerd -- you might want to skip this one.

I have started to use the FindBugs plugin for Eclipse, and it is very nice.  It finds many obscure failures that Eclipse or MyEclipse alone does not.  One particular problem it found in the code that I am attempting to brutalize into usefulness was use of == and != operators for doing String compares.  If you program in Java, you immedately recognize that:

    if (strObject == "hello")

is wrong.  String compares are done with

   if (strObject.equals("hello")

But we had almost 200 string compares using == or !=.  So why do we not have more problems?  The always useful StackOverflow explains why this often works, in spite of being wrong.  Java is smart enough to create a single copy of a String if it is a constant and there is another constant of the same content.  As a result, == and != will work if you are comparing two String objects that are both constants.  Thus, the many compares of the form strObj == "" work because the passed in parameter strObj was initialized somewhere to "".  If for any reason strObj is created in some other manner, such as new String(""), or as the result of some concatenation operation, the use of == or != is not going to work correctly.

As a result, in many cases, these really invalid uses of == and != work -- but it is a hazardous practice!


Thursday, June 20, 2013

McCabe Cyclomatic Code Complexity Measure

I recently installed the Metrics plugin in MyEclipse at work.  It provides a great big stack of code complexity statistics -- of which the most easy to understand for non-computer geeks is the McCabe Cyclomatic Code Complexity metric.  This is effectively a measure of how many different paths there are through a particular piece of code. 

Imagine if you lived in a big city, and had to find your way to another spot in the same city.  Every place where you could make a decision of where to turn or go ahead represents complexity, in the same way that the decision points in a programming language represent complexity.  Pretty obviously, the more decision points there are, the more opportunities there are to make mistakes.  A cyclomatic code complexity greater than ten is supposed to be a sign that you need to refactor the code.  So what happens when you see lots of code with complexity measures above 30?  Oh dear.

And when I actually look at some of the functions with high code complexity measures, what do I find?  The equivalent of dropping a mouse at Santa Monica Blvd. and Ocean Avenue in Santa Monica, and telling it to find its way to Boyle Heights in East Los Angeles.

There is a lifetime (perhaps several lifetimes) of work to clean up this pile.

Monday, March 18, 2013

Java Question

The project that I am currently working on has an interesting issue.  We just started using a tool called YourKit Java Profiler, and it shows that we have 26 MB of duplicate copies of the empty string "".  My first reaction was shock: I thought all compilers were smart enough to recognize that immutable strings (such as string constants) that are identical should reference a single version of that string.  But if YourKit Java Profiler is to be believed, that is NOT happening.  I asked the question here, and the answers that I received indicated that Java does create only a single version of a string constant -- but that the problem might be:

String str = i + ""

which is a very common Java construct for converting an integer to a string, is turning into something like:

String str = new StringBuilder("").append(i).toString();  

The implication is that the new StringBuilder("") is producing a distinct object each time, because that is a mutable string.  The solution is to use the somewhat less easy 

String.valueOf(i)

to produce the string version of i instead.  Does this seem like a plausible explanation of how we end up with 26 MB of "" copies?

Monday, October 22, 2012

Java RMI: Apparently Considered Obsolete

I can't figure out if the inability to get Java RMI applications working reliably is because it is obsolete, and no one much cares about it anymore, or if it is obsolete because it was so hard to get working reliably.  It was certainly elegant on paper.

Friday, October 19, 2012

More Obscure Stuff Associated With Java RMI

I rebooted my PC, and the very simple Java RMI example that I mentioned yesterday no longer worked.  Apparently, start rmiregistry is no longer enough.  Now I need start rmiregistry -J-classpath -J. (according to this web page).  Yes, that now works...but why?  I suppose it is time to figure out what those flags to rmiregistry mean.

Someone, somewhere, must be able to make some decent money consulting on Java RMI development problems.  The whole thing is beginning to look very obscure and fragile to me -- or perhaps it is just RMI development under Windows that is problematic.

UPDATE: It also appears that for all the technical merits of RMI, it simply did not catch on, and there's not much point to using a technology that is out of fashion: you can't hire people with experience with it, nor will it make you employable anywhere else.  (Not that there is much danger of me being employable in the private sector ever again.)

Wednesday, October 17, 2012

A Better Java RMI Example Than the Oracle Tutorial

A Beginner's Guide to RMI.

Except, unfortunately, it still references the RMIC stub compiler, which is no longer needed.

Even more unfortunately, the very basic code that they supply does not work.

UPDATE: It appears that since this beginner's guide to RMI was created, not only is RMIC stub compilation no longer required, but
if (System.getSecurityManager() == null) {
    System.setSecurityManager(new SecurityManager());
}

is now required in both the server and client.  At least on the client side, this is needed to be able to load objects from the server.

Part of what makes this so complicated is the magic collection of command line arguments required when you start the server and client.  As an example: it appears that when specifying the security policy, it is expecting a file name (not a URL that can be coerced into specifying a local file name) and it needs to be inside apostrophes, like this:
-Djava.security.policy='c:/tomcat5/webapps/rmi/server.policy'
However, the server codebase is a URL, so if you are running the server locally, you need something like this:
-Djava.rmi.server.codebase='file:///c:/tomcat5/webapps/rmi/computer.jar'
Note: three slashes after file:, not two, not one, not four.  But I still have not resolved this security policy question.  By the time I have figured all this out, I will be able to write a guide to these mysteries.

UPDATE 2: Except it appears that the policy file uses a different format:

grant codeBase "file:C:/tomcat5/webapps/rmi/-" {
    permission java.security.AllPermission;
};
Yes, "file:" would suggest a URL type of path, and thus file:///, but this suggests otherwise.  Why have a consistent format, when you have multiple formats?

UPDATE 3: At least the -Djava.security.policy parameter for Windows I now understand -- and it is shockingly simple:
-Djava.security.manager=c:\rmi\hello\server.policy
 The sever.policy file (at least the one that is probably too wide open from a security standpoint, but at least it works):

grant codeBase "file:///C:/rmi/hello/*" {
    permission java.security.AllPermission;
};
UPDATE 4: It turns out that the example I mentioned at the top of this posting is actually valid.  The only parts that were a problem were the parameters passed to Java.  The following items are required to start the HelloServerImpl:
java -Djava.security.manager -Djava.security.policy=c:\rmi\hello\server.policy HelloServerImpl
The server.policy that seems to work where both server and client are running on the same Windows box:

grant codeBase "file:///C:/rmi/hello/*" {
    permission java.security.AllPermission;
};

Some web pages indicate that a - is needed, not a *, but I do not think that is current.

To start the client was much simpler:
java HelloClient


Wednesday, January 25, 2012

Threads vs. Processes

I did a consulting job in Oregon a few years back where the manager was impressed that my solution for a sample piece of code involved multiple threads.  He explained that he generally disliked use of threads, because they share too much information.  This is very true, and it is both a strength and a weakness of threads: you can share information (so each thread can see what the others are doing) but also, you can share information (so each thread can interfere with what the others are doing).

The antisocial software that I am trying to rehabilitate has one of those threading difficulties--and it took a while to figure it out.  The user interface has a Save button; you click it, and it both saves data to the database, and then checks to see if the offender's home address is the same as any other offender in the system.  If there are other matches, it throws up a popup window that displays the other offenders at the same home address.

Of course, that popup window is done through a separate thread--but the abusive software parent responsible for this piece of code did not think about the fact that both threads were sharing the same database connection object.  If the retrieve matching addresses thread finished its SQL operation before the save thread started, everything worked just fine.  But as the number of matching addresses increased much above ten, the odds were excellent that the retrieve thread would still be retrieving data when the save thread closed the connection.

The database connection is now closed: but the retrieve thread is still retrieving data.  The results were highly unpredictable, with at least four different error messages that might appear, depending on timing.  Only occasionally did the SQL Exception come up "Connection already closed" which was the tipoff that something was not right.

Sad to say, there are more than a thousand popup windows in this system, and trying to figure out which of those are this sort of multithreaded monstrosity will keep me busy for decades.  Unlike Sisyphus, at least I get to retire in a few years.

Thursday, July 14, 2011

Can't Control Applet Close Window?

I spent way too many hours trying to find the answer to this question, so in the event that someone else runs into the same problem, a search for WindowListener or JApplet or Applet will probably bring them here.

I am writing a popup applet to replace the Javascript prompt function--but with more caller control over the size of the text that the user can enter.  (It uses the JTextArea component.)  The way it works makes it easy to replace existing calls to prompt--instead, it has methods like this:


/**
* Replaces the Javascript prompt function.  It displays text in a text box, OK and Cancel buttons
* and returns a String if the user hits OK.
* @param msg: the prompt to the user
* @return: String
* @throws InterruptedException
* @throws BadLocationException
*/
 public String editableTextBox(String prompt, String defaultText, int rows, int columns);



/**
* Replaces the Javascript prompt function.  It puts up an empty text box, OK and Cancel buttons,
* and returns a String if the user hits OK.
* @param msg: the prompt to the user
* @return: String
* @throws InterruptedException
* @throws BadLocationException
*/
 public String inputTextBox(String prompt, int rows, int columns);


A little weird, but the way that this works is that it pops up a window containing these components, and then goes into a sleep loop until the user hits the OK or Cancel button.  This worked just fine, but the problem was what to do if a user hits the close window box on the popup, instead of hitting the Cancel button?

I thought that I could turn on the WindowListener interface, and catch the window closing or window close events, and from there, set the flags that simulated the user hitting Cancel--but that did not work.

 So I put the same code in the stop and destroy methods of the applet--but there was no way to force that looping thread to get control and see that we were simulating Cancel.  So I took what might seem like the least beautiful approach.  In the popup window (which is a JFrame):

     setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

The user can hit the close button all day, and nothing will happen.  He has to hit OK or Cancel.

Thursday, May 5, 2011

Eclipse

I have to brush up my Java threads for a phone interview tomorrow.  I have not written anything threaded in a long time.  I wrote a cute little multithreaded applet back in the 1990s for a class.  I also wrote a rather large Java application for regression testing a DSL access multiplexer through the SNMP interface in the late 1990s as well.  That had at least two threads in it, one to do the SNMP transactions, while the GUI was running.  But it has been so long, I needed to spend some time figuring out how this stuff works again!

Anyway, I went into Eclipse on my Linux box (from which I am posting this), and in no time at all, I was able to write a trivial little Java application to refresh my memory of how this stuff works.


public class MultipleThreads {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TestThread count1 = new TestThread(1, 10, 500);
count1.start();
while (count1.getCalcCount() < 5)
;
TestThread count2 = new TestThread(1000, 1010, 250);
count2.start();
}

}

public class TestThread extends Thread {
private int start;
private int last;
private int delayInterval;
private int calcCount;
public int getCalcCount() {
return calcCount;
}

public void setCalcCount(int calcCount) {
this.calcCount = calcCount;
}

TestThread(int begin, int end, int delay)
{
this.start = begin;
this.last = end;
this.delayInterval = delay;
calcCount = 0;
}
public void run() {
for (int i = start; i < last; i++)
{
System.out.println("sqrt(" + i + ")=" + Math.sqrt((double)i));
calcCount++;
try {
sleep(delayInterval);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

It does not anything terribly significant; I was just verifying that I knew how to create an application with two threads that could interact with the main application thread.  The cool thing is that Eclipse (which is open source) is so easy to use that I could throw this together in just a couple of minutes and get it working.