Java equivalent of PHP foreach ($array as $key=>$val)

As a follow up to my previous post, where I complained that there was no easy way in Java to deliver PHP’s foreach ($array as $key=>$val) functionality I have an update. Using Java’s HashMap or LinkedHashMap types, the same result can be achieved. The difference between the two is that LinkedHashMap retains the order of the array.

import java.util.*;
class Foo
{
    public static void main(String[] args)
    {
        Map<String, String> stateMap = new LinkedHashMap<String, String>();
        stateMap.put("ALABAMA", "AL");
        stateMap.put("ALASKA", "AK");
        // ...
        stateMap.put("WYOMING", "WY");
        for (Map.Entry<String, String> state : 
                stateMap.entrySet()) {
                    System.out.printf("The abbreviation for" + state.getKey() 
                + " is " + state.getValue() + "\n");
        }
    }
}

This utilises a HashMap which enables a key value pair to be defined and thereby replicates PHP’s foreach ($array as $key=>$val) functionality.

(sourced via stackoverflow.com)

Advertisements

Using Java application to access web application

I’ve been working a bit with needing to utilise a web service built in PHP from a Java application (it would be easier to just run a full-screen browser, but other constraints remove this option). What this has necessitated is scripting the Java app so that it makes calls to the web app’s API and then parses and utilises the data correctly.

Other than the writing of variations to the existing web app, so that function calls etc are accessed externally and correctly, the main functionality of the Java app has needed to be built into standard function calls which take in parameters and then parse them to dynamically create the correct URL to be called. Essentially the generalised function takes the parameters given and creates a URL which specifies the function required as well as necessary input data for the web app. Unfortunately, Java doesn’t have a nice foreach array iterator that can reference both the key and the value; like PHPs foreach($array as $key=>$val)):

public string makeURL(string baseURL, string pageName, string[][] params) {
    string queryURL = baseURL + "/" + pageName + "?";
    for(int i=0; i<params.length(); i++) {
	string param = params[i][0] + "=" + params[i][1] + "&";
	queryURL += param;
    }
    queryURL = queryURL.subString(0, queryURL.length() - 1);
    return queryURL;
} 

Next we use a function call to wrap up all the creation of a URL, requesting it, and receiving the response:

public string callURL(string queryURL) { 
    URLConnection queryConn = queryURL.openConnection();
    BufferedReader in = new BufferedReader(
            new InputStreamReader(
	    queryConn.getInputStream()));
    String inputLine;
    String result = ""; 
    while ((inputLine = in.readLine()) != null) {
	result += inputLine;
    }
    in.close();
    return result;
}

The second general function is given the returned data from the URL request and parses it into variables for use by the Java app; the data returned is structured as a 2-D array with the equivalent of a key and value held in the 2nd dimension:

public string[] extractData(string response, string[] nodeNames = null) { 
    string[] data = new Array();
    string[] tokens = StringUtils.splitspanserveAllTokens(response, ":");
    for(int i=0; i<tokens.length(); i++) {
	string[] step = StringUtils.splitspanserveAllTokens(tokens[i], "$");
	data[i][0] = step[0];
	data[i][1] = step[1];
    } 	
    return data; 
} 

Of course, my extractData function is extremely simplistic and only splits a string up. Parsing XML is a better solution if the URL returns XML formatted data. This would require either explicit foreknowledge of the exact nodes being returned by a request (I have allowed for this with the string[] nodeNames) or a much bigger function to allow for searching through and detecting all node names and then dynamically iterating them.

I’m sure there are cleaner, and better, implementations of this, however I felt the need to build my own since I’m dabbling back into Java at present. And once it’s built, I believe it’s best to share. Hopefully this helps someone, let me know.

here I am again

Well, here’s a sight for sore eyes….a new update. Much has been happening in the last wee while, and not much online time. I had my graduation Friday week ago (7th May) and that was AWESOME!! I’ll be posting some photos, once I get the digitals of those who had cameras. I am now officially qualified with my BA (Politics and Philosophy) and BSc (Information Systems and Computer Science). The job hunt is in full swing at present. I’ve kept coming very close 2nd at quite a few opportunities, which is getting rather frustrating I have to say. Trying to head towards a Business Analyst role, which is easier said than done. I’ve even had consultants tell me I’d be perfect with my background and previous roles; but everyone still wants 3-5 years experience. I seem to be the only one who spots the oxymoronic nature of this – that you need 3-5 years experience to get the job, but you need the job to get the 3-5 years experience. I’m keeping my search broad at present, looking down the support role and other similar roles to get in the door.

I’ve been doing quite a bit of coding though, but offline at work. Mainly PHP and MySQL, but also keeping up on my Java and C# with re-learning Objective-C for good measure. Mainly working on a little (or, not so little if all goes well) web application of mine, as sqwi.sh is running along smoothly these days. I’ll be opening the API for sqwi.sh shortly though.

I’ll do a 2nd post with some YouTube vids etc in a few minutes. Also, I’ve roughed up quite a few tuts over the last while, so there’ll be a bit of a flurry of tutorial posts in the next few days.

casting to integers in JavaScript

I’ve been messing a little with some JavaScript fiddly bits last night and today, and I was caught out for a bit by need to cast a value to an int once divided. In Java it’s easy:

val = Integer.parseInt(numberA / numberB);

however, JavaScript isn’t that nice. Actually, once I solved it, I found JavaScript was even nicer!! By using a bitwise OR operation to cast a float/double back to an int like so:

val = (numberA / numberB) | 0;

Voila! It is cast from a float/double to an int.

another day in the life

Well, today I had to knock out an assignment in Java. I’d already done 99% of it, just had to confirm the linking back to the mySQL DB and ensure it error handled from command line. I managed to trigger almost every error message Java has, which was made less exciting because I haven’t used Java in a while. All the syntactical issues jumped up and bit me (eg ‘String’ vs ‘string’, variable types changing…) because I’ve been playing in C# and PHP all the time. My Javascript stuff kept me in good stead though. In the end though, I am not complaining about the jdbc stuff, it’s just as reasonable as PHP’s connections and calls, I’m just out of the habit.

Just to point out this year’s Stella Awards, courtesy of the good guys at dailyfailblog. Knock yourself out! Then sue.

In other parts of my day, I also found the time to get dynamic generation and downloading of files up and running for my new site (announcement soon….), and got these working for .pdf, .xls, and .csv. I have to say, it is kinda simple now that I’ve done it, but the journey was interesting. I’ll be posting some tutorials/code samples to a page on here in the next few days, and I’ll edit a link into this post. I was going to have them all with the option to open in a new page as well, but this is only really viable for .pdf, as .xls and .csv both require Excel or similar installed on the user machine, as well as then wanting to open the document outside the browser (.pdf still requires a reader, but most browsers have this, and it opens inside the browser window). I’m going to look further into linking this opening into pointing at Google Docs for example, but at the moment that’s on stand-by.

Other than that, I’ve just been tweaking the whole flow side of things, and testing and re-testing the security of my DB calls etc. It’s not like my site’s going to be “high-security”, but every site gets hacked so it’s silly to not be pro-active. On that note, a couple of great articles on PHP security are here, written by Dave Clark, and here, written by Pax Dickinson. These are five-to-ten minute reads, but are both excellent for reviewing your existing knowledge or building it up some more.

The rest of this week’s post are either going to get fairly sparse, or just be quick updates because, being final lecture week, the assignments are snow-balling. My only real distractions from these are going to be playing with cronjobs for the new site.

Anyway, to end today’s post, this video isn’t gross, but it’ll still make you squeemish. It’s worth watching, but don’t say I didn’t warn you.

and, this guy has the “worst” job in the world….

twittering, blogging, and procrastinating

Well, today I sorted out my twitter account – style, colors etc – and started following some people. I resisted the urge to follow ICHCheezburger, MC Hammer, Ashton Kutcher, and Tony Hawk; although John Mayer was an easy pass. I’ve made the somewhat lucid decision to limit my twitterati (is that a word – well, it should be!) to people I actually communicate with and care what they are doing. I am now on “following” terms with engadget. You can already see the MySpace/facebook-esque groupie thing getting well hammered on twitter. Other than the well publicised race between Oprah, Ashton et al to be the first to have a million followers on twitter, it’s a bit ridiculous to see the 1.6 million and counting people who actually believe that Britney Spears is following them in return and actually tracks their twitters.

In the real world, I found a couple of neat css tricks, and re-learnt my command-line Java; as well as consolidating some of my php scripts for dynamic geo-location components for pages. They were a bit of a mish-mash, having been done as I taught myself, and it’s amazing how cleaned up I could get them in relatively little time.

I think tomorrow’s post will be something like “css for the soul” or similar, and basically be a spewing forth of my latest tid-bits of knowledge and cunning tricks and hacks. Not that I’ve come up with much myself recently, it’s more been a pulling together and pooling of the genius available on the web and through Google. Although, I’ve now been tapping into Wolfram|Alpha as well – it’s starting to get a bit of flack, but I think that’s cause it’s in a newbie phase. The whole intent is that it is to be a humanistic learning-engine, so everytime we search it the answers get better….anyway, it can’t do any worse than Cuil has done….I did just go check, and Cuil is still alive, we just hear nothing from it these days.