Saturday, October 11, 2014

Groovy Enum Generator Using eachLine and String Interpolation

This is a very short example about how to process a file line by line in the Groovy programming language to create an enum. There are so many times I open up the Groovy console to get something done fast. In this example I use the groovy to open up a file, iterate over each line, and use string interpolation to create the output that is then copied into my enum Java file from the contents of a text file.


Code:

def tmpFile = new File("/Users/dbell/Desktop/example.txt")
def cnt = 0
def enumName = "Sports"
def enumStringBuilder = new StringBuilder()
enumStringBuilder.append("public enum ${enumName} {\n\n")
tmpFile.eachLine {
    def desc = it
    def code = desc.toUpperCase().replaceAll("\\s", "_")
    if (cnt > 0) { enumStringBuilder.append(",\n") }
    enumStringBuilder.append("\t${code}(\"${code}\",\"${desc}\")")
    cnt++
}

def enumOutput = enumStringBuilder.toString() + ";\n";
println enumOutput

println "\tString code;"
println "\tString description;\n"
println "\t${enumName}(String code, String description) {"
println "\t\tthis.code = code;"
println "\t\tthis.description = description;"
println "\t}"
println "}"


example.txt

Soccer
Football
Basketball
Hockey
Hacky Sack
Corn Hole


Generated Output

public enum Sports {

SOCCER("SOCCER","Soccer"),
FOOTBALL("FOOTBALL","Football"),
BASKETBALL("BASKETBALL","Basketball"),
HOCKEY("HOCKEY","Hockey"),
HACKY_SACK("HACKY_SACK","Hacky Sack"),
CORN_HOLE("CORN_HOLE","Corn Hole");

String code;
String description;

Sports(String code, String description) {
this.code = code;
this.description = description;
}
}


Screenshot:


Monday, September 29, 2014

A Solution To Homelessness Using Technology (aka Homebook)

Readers,

I have had an idea for quite some time and I would like to share it with you. For many years I drove to work and each day would get stopped by the same stop light at the top of the hill. Each morning there would always be someone standing there with a sign describing their situation and that anything helped. As I drove into work each and every day I always thought there had to be a better way to address these issues. My old boss Mr. Cook always said, do not complain unless you have a solution, and don't be surprised if you become the owner of that solution if it is a good one. 


So here comes my idea for Facebook for those in need, I call it HomeBook. The plan for this web and mobile program would be to sign up families and individuals in need. They would go to a center who was trained to identify individuals who truly needed assistance. These workers would put the necessary information into the web application. The individuals would then be issued an id card and number which would tie into their profile on the site: 

Example:  http://www.homebook.org/zipcode/id# 

Now that we have the information in the computer we can begin helping. Each id would be assigned a bank account. This account would be funded by donations made by people visiting the website. People could simply visit the site, put in their zip code (or let the browser do it with location services) and up comes those in your community in need. The website would also work on mobile devices and allow both reviewing of profiles and donations. If that person now wants to stand on the corner asking for help, they now can put a url on that piece of cardboard. The person in their car could simply hold up their phone, snap a picture, and visit the url later, or, they could visit the website from their mobile device with a smart and intuitive interface, allowing them to quickly enter in the id.

This system would then connect you with those you have helped. You could continue to watch progress, see how the money was spent whether it be on housing, education, child resources, etc. 

The big benefit today of Facebook is allowing us to connect and participate in peoples lives we care about. Why can't we connect and participate in the lives of those who need our help the most?


So now we have identified the problem and what we might be able to do to solve it... now where is this system going to come from, how will it be managed, how will we make sure there isn't corruption, how do we facilitate distribution of funds... these are all questions I do not have an answer. I know using Google App Engine for the back end, some jQuery and JSP pages, a credit card processor, and banking api's are a great start but there is a large amount of work that would be needed to pull this off. 

Here is my proposal, I need help talking through these points, talking about this idea, starting a discussion... Is this a smart idea... does it make sense... do we think it would work? 

What do you think?


Friday, September 19, 2014

Java EE Page View Servlet : Simple app analytics

For this post I'm going to show how you can provide a simple page view recorder using a couple lines of html and java. Sometimes you want to record simple analytics about page views in your jsp/servlet based java web application. You could always attach Google Analytics but you may have an internal application which you do not want to tell Google about. In that case here is some sample code to allow you to do this easily yourself.

* Note: I get my user information from a session variable called user as an example.


In your JSP or HTML page:

<img src="/yourappscontextpath/PageView.servlet?page=<%=request.getRequestURI().toString()%>" style="display: none;" />

* Note: Replace the text yourappscontextpath with your actual applications context path.


Create a new Servlet called PageViewServlet and set up the servlet mapping to point to PageView.servlet:

In the doGet method add the following code:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
User user = (User) request.getSession().getAttribute("user");
String page = request.getParameter("page");
// Add your own code here to save the user and page to the database or to a file.
}

Now you can view each time a user accesses a certain page in your application using this simple process. Enjoy!

Saturday, September 13, 2014

Teaching programming using a simple game written in html css javascript

This tutorial has been created to teach individuals some of the basics of programming using a browser and html/css/javascript. The purpose of the game is to quickly find each letter or number presented. If you click on the correct item you receive 1 point and the wrong item you lose a point.

The game uses a handful of concepts in programming like loops, conditionals, functions, arrays and more to help show how things work under the hood. I hope you enjoy the game but more importantly learn a little programming in the process!





Files Involved

  • findit.html: This is the markup file which is directly accessed in the browser. This page sets up a basic user interface. A important aspect of this markup page is the <head></head> section of the page. This sets up our design file (findit.css) and our logic file (findit.js). 
  • findit.css: This file contains the styling for our game including colors, sizes, borders and more. The type of file is a cascading style sheet file denoted by the .css at the end of the file. 
  • findit.js: Here is where the real fun stuff takes place. This is the javascript file for our game and contains the logic which handles starting and stopping the game, adding and removing points, saving scores, and randomly assigning locations on the game board for our letters and numbers.
You can view the game here at www.broadlyapplicable.com/findit. Using view source you can see the html markup created for the game. Below are the includes for the styling css file and the logic javascript file:

<head>
 <link rel="stylesheet" href="http://www.broadlyapplicable.com/findit.css" type="text/css" />
 <script type="text/javascript" src="http://www.broadlyapplicable.com/findit.js"></script>
</head>

You can view those files directly by replacing the url .html part with .css or .js. Here are handy links for you also:


Looking at the logic file (findit.js) here are a few of the important methods and items to study and understand. Notice I have left a few console.log("..."); lines in the script. These output to your browser console. If you use chrome for example you can hit F12 (on Windows) or View/Developer/Developer Tools on a Mac to access the browser console. Here you can log any message like variable values so you can see what is occurring in the application.

Some concepts found in the game:
  • Looping / Iterating
    • loadTable()
      • This method loops over the available letters or numbers array and creates buttons for the game which can be clicked. It also uses a random number generator to get the color of the button border. This method calls another method called shuffle(array) and changes the order of the letters and numbers so each time you play the layout is different.
    • showScores()
      • This method iterates on the stored scores in your local browser database and displays the initials and score.
    • askQuestion()
      • This method is used to determine what to display from the list of available letters and numbers and uses a while loop to continue checking each randomly chosen value against the previously used values until one is found. Once that happens a variable called badQuestion is set to false which breaks the while loop and returns the question.
  • Conditionals (if / else statements):
    • determineLetterOrNumber(itm)
      • This method takes the item chosen that is passed into the method and checks the number and letter arrays to determine if the item is a letter or number. This is used when asking the question "Find the Letter or Find The Number ..... ".
    • testForFinishGame()
      • This method checks the array of items already chosen against the available numbers total, when these numbers match you have successfully cleared the board and the game is finished.
  • Variables
    • numbers : This is an array of numbers.
    • letters : This is an array of letters
    • lettersAndNumbers : This is a array created by combining the values from the letters and numbers array.
    • removedLettersAndNumbers : This array contains items which have been chosen and clicked on already. (notice in the startGame() method I set the length of this array to 0. This removes all the items from the array).
    • started : This is a true/false value which allows the game to know if it is currently running or not.
    • stopTimer : This value is used in the startTimer() method to set to true or false when creating the inner function for onTimer(). 
    • questionIndex : The index position of the chosen letter/number to find.
    • questionValue : This holds the letter or number you are trying to find.
    • points : this one should be obvious :)
  • HTML 5 Local Storage
    • supports_html5_storage() : This methods determines if we can use the browsers local storage system to persist your scores from game to game.
    • getScores() : Retrieves your scores from local storage.
    • showScores() : Displays scores at the bottom of the game.
    • saveScores() : Saves your score in local storage
  • CSS Manipulation
    • updateStartButton() : This method changes the start/stop button text and color

Comments and questions are always welcome, I hope you enjoy the game, please pull the source down to your local machine and hack away!


This application code has been uploaded to github. Please visit https://github.com/dtbell99/FindIt for the most recent source code.



Thursday, September 11, 2014

Query the Internet Chunk Norris Database using Java and Gson

This tutorial will show you how to use Java and the Google Gson library to query the Internet Chuck Norris Database and return a quote you can display in your application.


Step 1: Download Google Gson here: https://code.google.com/p/google-gson/

Step 2: Familiarize yourself with the icndb rest api: http://www.icndb.com

Step 3: Create a new Java project in your favorite IDE or editor and add the Gson jar library to your application and class path.

Step 4: Create a new class called Value.java:

package com.broadlyapplicable.icndb;

public class Value {

private int id;
private String joke;

public Value() {
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getJoke() {
return joke;
}

public void setJoke(String joke) {
this.joke = joke;
}

}


Step 5: Create a new class called Quote.java:

package com.broadlyapplicable.icndb;

public class Quote {

private String type;
private Value value;

public Quote() {
}

public String getType() {
return type;
}

public void setType(String type) {
this.type = type;
}

public Value getValue() {
return value;
}

public void setValue(Value value) {
this.value = value;
}

}

Step 6: Create a new class called RestUtil.java which will return a Quote object you can then use inside your application:


package com.broadlyapplicable.icndb;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import com.google.gson.Gson;

public class RestUtil {

private static final String URLPATH = "http://api.icndb.com/jokes/random";
private static final String METHOD = "GET";
private static final String CONTENT_TYPE = "application/json";

public RestUtil() {
}

public Quote getQuote(String types) {
String jsonFromRestCall = getJson(types);
Gson gson = new Gson();
Quote quote = null;
if (jsonFromRestCall != null && !jsonFromRestCall.isEmpty()) {
quote = gson.fromJson(jsonFromRestCall, Quote.class);
System.out.println(jsonFromRestCall);
}
return quote;
}

private String getJson(String types) {
String urlPath = URLPATH;
if (types != null && !types.isEmpty()) {
urlPath = urlPath + "?limitTo=" + types;
}

StringBuilder resp = new StringBuilder();
BufferedReader bufferedReader = null;
try {

HttpURLConnection conn = getConnection(urlPath);
bufferedReader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String lne = null;
while ((lne = bufferedReader.readLine()) != null) {
resp.append(lne);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
return resp.toString();
}

private HttpURLConnection getConnection(String urlPath) throws IOException {
URL url = new URL(urlPath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(METHOD);
conn.addRequestProperty("Context-Type", CONTENT_TYPE);
conn.setDoOutput(true);
return conn;
}
}


Step 7: Create a new class called Test.java and call the new RestUtil getQuote method passing in the types of quotes you wish to be queried after reviewing the rest api from the link above.

package com.broadlyapplicable.icndb;

public class Test {

public static void main(String[] args) {
String types = "nerdy";
RestUtil restUtil = new RestUtil();
Quote quote = restUtil.getQuote(types);
System.out.println(quote.getValue().getJoke());
}
}


Step 8: Run the Test class and you should see output similar to below:
{ "type": "success", "value": { "id": 529, "joke": "Chuck Norris doesn't use Oracle, he is the Oracle.", "categories": ["nerdy"] } }
Chuck Norris doesn't use Oracle, he is the Oracle.


I hope you enjoyed this tutorial, if you have questions or comments please leave them below, happy coding!

Wednesday, September 3, 2014

Welcome

Hello and welcome to the Broadly Applicable blog. I have created this blog to dump out code, concepts, and ideas while doing Java, Groovy, Scala, Swift, Javascript, and other language programming. 

I have always repeated the saying that if you love what you do you don’t work a day in your life. With computer programming I have had the luxury of feeling like that for years and hopefully I am blessed with many more. So welcome to this blog! I hope you find the content meaningful and please reach out if you have any comments or concerns!

Thanks,
David Bell
Broadly Applicable LLC Founder/Engineer
www.broadlyapplicable.com