CodeHouse of Horrors

Swing – hey, that dialog looks neat, can I do it with a Password field instead?

leave a comment »

No, it’s not as straightforward as one would hope, but after some searching around for different solutions, I settled on this one:

String user = JOptionPane.showInputDialog(null,
“Username:”,
“Enter Username”,
JOptionPane.PLAIN_MESSAGE);

 

Equivalent JPassword Dialog:

JPanel panel = new JPanel(new GridLayout(2, 1));
JLabel passLabel = new JLabel(“Password:”);
JPasswordField pass = new JPasswordField(20);
pass.addAncestorListener(new AncestorListener() {
public void ancestorAdded(AncestorEvent e) {
JComponent component = (JComponent) e.getComponent();
component.requestFocusInWindow();
component.removeAncestorListener(this);
}

public void ancestorMoved(AncestorEvent e) { }

public void ancestorRemoved(AncestorEvent e) { }
});
panel.add(passLabel);
panel.add(pass);
int action = JOptionPane.showConfirmDialog(null, panel, “Enter Password”, JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (action == 0) {
passwd = new String(pass.getPassword());
}

Written by trumpetx

November 20, 2012 at 9:07 pm

Posted in Uncategorized

Eclipse Settings – Mockito/JUnit annoyances with importing static classes

leave a comment »

  1. Open Preferences (Window-> Preferences)
  2. Browse to Java -> Code Style -> Organize Imports
  3. Change ‘Number of static imports needed for .* to ‘1’
  4. Click Ok

OMG I can’t believe I had never found this before.  No more assertTrue & assertFalse annoyances with silly static classes.

 

Written by trumpetx

April 8, 2011 at 1:03 pm

Posted in Uncategorized

Experiences looking for a job – reflection part 1

leave a comment »

So, a couple of months ago, I started looking for a new job down in Austin, TX.  As I type this, I am still in Indiana; however, I have accepted a position with a company called Pointserve as a Java developer.  My experience in looking for a job was pretty wild.  First of all, I had never interviewed for a developer position other than at IU.  Internal changes within the university focus mainly on checking on references (e.g. previous managers.)  The “wild” part of looking for jobs in Austin was the simple lack of interest in my personal references and experience.  Now, this isn’t to say that I wasn’t asked about my experience, but most companies were MUCH more interested in quizzing/testing me on what I knew more than my experience.  I can say definitively that only one company even bothered to call a single reference (and that company didn’t even interview me as I accepted the Pointserve position before they had a chance to interview me.)

In this post, I’m going to go over the programming questions which were given to me (usually over the phone after an initial pre-screen).

Here are all of the questions I was asked.  Some questions were asked by multiple companies (the reverse a string one was very popular).  I’m including the “correct answer” which was not always what I gave.  In general, I never initialized the size of a StringBuffer object which I should have.  Apologies for the lack of indenting – wordpress hates me and I don’t feel like editing in   right now.  Maybe later…

The ever popular “Write me a method which takes in a String and returns the string reversed.”:

public String reverseString(String str){
StringBuffer sb = new StringBuffer(str.length());
for (int i = str.length()-1; i >=0; i–){
sb.append(str.toCharArray()[i]);
}
return sb.toString();
}

note: when doing this, it’s always fun to mention the StringUtils method .reverse();  (1) it explains that you know that function exists and in general that you’ve used the StringUtils functions.  (2) Always use StringBuffer or StringBuilder!  Even though you can still display an understanding of programming concepts without doing this, it shows a lack of knowledge in the Java sphere.  If you use a StringBuilder object, be prepared to be asked about thread safety re: your method.

“Write a method that takes in two strings.  One string is guaranteed to be bigger than the second.  Return a boolean value of true if the characters in the second string are all contained in the first string (in any order), otherwise return a false.”

public Boolean containsCharMethod(String littleString, String bigString){
Set<Character> bigStringSet = new HashSet<Character>(bigString.length());
// O(n)
for (int i = 0; i < bigString.toCharArray().length; i++){
bigStringSet.add(bigString.toCharArray()[i]);
}
//O(m)
for (int i = 0; i < littleString.toCharArray().length; i++){
//O(1)
if (!bigStringSet.contains(littleString.toCharArray()[i])){
return Boolean.FALSE;
}
}
//O(n+m)
return Boolean.TRUE;
}

notes: Okay, so the real question they’re asking you is “do you know how to NOT write an n^2 algorithm where an alternative exists?”  The wrong answer is to loop through the (albeit) smaller string and one at a time search through the larger string to see if the string contains each letter.  The key is to add the large string to a Set and then query the Set for each character in the second string.  Bonus points for initializing the size of the set (which I didn’t do!)

The overused, but only hit 1 time in my job search “FizzBuzz” question “Write a method that [(A) takes in an array of integers (B) loops through 0-100 (C) loops from 500-1000 (D) you get the idea ] and prints out a line for each number.  Write Fizz if the value is divisible by 3, Buzz if it is divisible by 5 and FizzBuzz if it is divisible by either 3 and 5”

public void fizzBuzz(Integer[] integerArray){
for (int i = 0; i < integerArray.length; i++){
if (integerArray[i] % 15 > 0){
System.out.println(“FizzBuzz”);
} else if (integerArray[i] % 3 > 0){
System.out.println(“Fizz”);
} else if (integerArray[i] % 5 > 0){
System.out.println(“Buzz”);
} else {
System.out.println(integerArray[i]);
}
}
}

note: this is very simple.  You can safely say (if Array[i] % 3 > 0 && Array[i] % 5 > 0) instead of (Array[i] % 15 > 0) safely.  The 15 thing is something I read in a blog somewhere and I thought “Oh yea, that’s a simple way to do it.”

“Write a method that takes in an array of integers and add them all up to a total”

public Integer addThemUp(Integer[] intsToAdd){
Integer total = 0;
for (int i=0; i < intsToAdd.length; i++){
total += intsToAdd[i];
}
return total;
}

note: out of all the questions above, I almost messed this one up the worst.  It’s amazing how nerves and phone interviews can really mess you up.  Write everything down and THEN explain what you’ve done.  If possible, use an editor like Eclipse which can catch those silly little mistakes manifested from nerves or typos.

Written by trumpetx

January 11, 2011 at 4:07 pm

Posted in Java, Programming

Your Framework Sucks

leave a comment »

Taken 100% from :

http://mooneyblog.mmdbsolutions.com/index.php/2010/12/07/the-framework-myth/

MVC frameworks like Rails and Django have caught on like wildfire, with ASP.NET MVC picking up a lot of momentum as well. Microsoft Azure and Google AppEngine are in the process of changing how we will build scalable cloud-based applications into the next decade. Have you noticed a pattern here? None of them were built by you or anyone you know.

Any yet, despite all that, most of them still sucked, and the ones we use today are the select few that survived.

The thing is this: you and your internal development team of architects are not going to build the next great framework. You’re not going to build a good one. You’re not even going to build an acceptable one.

And the other thing is this: If a framework is not great, it is awful, counterproductive, and destructive.

MVC frameworks like Rails and Django have caught on like wildfire, with ASP.NET MVC picking up a lot of momentum as well. Microsoft Azure and Google AppEngine are in the process of changing how we will build scalable cloud-based applications into the next decade. Have you noticed a pattern here? None of them were built by you or anyone you know.

Written by trumpetx

December 9, 2010 at 10:03 pm

Posted in Programming

PDF Generation from an HTML page ( jsp / Java )

leave a comment »

A while back, I posted to door64’s blog area with this.  I’m cross-posting it here for my own reference.  Enjoy!

Requirement:

I have a .jsp page which consists of some CSS formatted tables which acts as a generated report for our users. Our users want to be able to save this as a PDF.

The problem:

The initial developers on this project created two separate views and managed each for the reports. One for HTML and the other for PDF. This became a management nightmare as the PDF would consistently display different visual artifacts from the HTML page and all new additions to the reports required the two separate view files to be edited.

The solution:

After trying some commercial solutions (which worked for the most part, I was especially impressed with http://pd4ml.com/). The downside here is that PD4ML required us to purchase a multi-server deployment license ($1400 !) Yikes indeed.

So, I decided to roll my own. Below is the result…

Credits! I pride myself with NOT re-inventing the wheel when there’s no need. Google has the answer to my “how can I do ‘this'” questions 90% of the time, but this time most of the blog/tutorial results were insufficient. I did, however, use a combination of blog posts to reach this end result. The “core” of this solution was taken from http://kac-ani.xt.pl/en/node/27.

Overview:
The end result will give you a jsp tag to turn HTML into a PDF. This solution could be cleaned up a lot, but this suited 100% of my personal requirements. One could imagine this tag taking lots of optional parameters (like PD4ML) which would alter the PDF generation through some CSS styling. I’ll leave that super duper stuff up to someone else. This gets the job done!


<tagPrefix:tagName>
... HTML ...
</tagPrefix:tagName>

Prereqs:
You’ll need libraries from:

jTidy – http://jtidy.sourceforge.net/
xhtmlrenderer – https://xhtmlrenderer.dev.java.net/
iText – http://itextpdf.com/ (the latest version has changes to some of the document types – I used version 2.0.8.)

Step 1:
Create a new .tld file (Tag Library)
/WEB-INF/tlds/mytl.tld


<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"
"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<taglib xmlns="http://java.sun.com/JSP/TagLibraryDescriptor">
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>PDF Tag</short-name>
<tag>
<name>pdfTag</name>
<tag-class>com.domain.utils.PdfTag</tag-class>
<body-content>JSP</body-content>
</tag>
</taglib>

Step 2:
Create the class file referenced in the above tag library file:


import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringWriter;

import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.tidy.Tidy;
import org.xhtmlrenderer.pdf.ITextRenderer;

import antlr.StringUtils;

public class PdfTag extends BodyTagSupport {

/**
*
*/
private static final long serialVersionUID = //generate your own;

public int doAfterBody() {
try {
Tidy tidy = new Tidy();
tidy.setShowWarnings(false);
tidy.setShowErrors(0);
tidy.setXHTML(true);

InputStream inputStream = new ByteArrayInputStream(bodyContent.getString().getBytes(“UTF-8”));

StringWriter sw = new StringWriter();

tidy.parse(inputStream, sw);

InputStream documentBuilderInputStream = new ByteArrayInputStream(sw.toString().getBytes(“UTF-8”));

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setFeature(“http://apache.org/xml/features/nonvalidating/load-external-dtd&#8221;, Boolean.FALSE);
dbf.setFeature(“http://xml.org/sax/features/validation&#8221;, Boolean.FALSE);

DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(documentBuilderInputStream);

//This is where you’ll want to make changes to your CSS to allow
// the generated PDF to look good
Element style = doc.createElement(“style”);
style.setTextContent(
“body { font-family: \”Arial Unicode MS\”; }” +
“table.content { width: 700px; }” +
“td { font-size: 6pt; }” +
“th { font-size: 6pt; }” +

// and page numbering
“@page { @bottom-right { content: \”Page \” counter(page);} }”
);

// and add it to

Element root = doc.getDocumentElement();
root.getElementsByTagName(“head”).item(0).appendChild(style);

ITextRenderer renderer = new ITextRenderer();

renderer.setDocument(doc, “”);
renderer.layout();

pageContext.getResponse().setContentType(“application/pdf”);

OutputStream os = pageContext.getResponse().getOutputStream();

renderer.createPDF(os);
os.flush();
os.close();
}
catch (Exception e) {
throw new RuntimeException(e.toString());
}
return SKIP_BODY;
}
}

Step 3:
Add to your web.xml file:


<taglib>
<taglib-uri>/mytl</taglib-uri>
<taglib-location>/WEB-INF/tlds/mytl.tld</taglib-location>
</taglib>

Step 4:
At the top of your .jsp view file (or in a header file like me) add:

<%@ taglib uri="/mytl" prefix="mytl" %>

Step 5:

Example usage:

Since I link to the PDF export from the HTML page, I just use something like this:
… don’t have any HTML up here, the full html block should be inside the PDF tag. JSP header stuff is kosher though …


<c:choose>
<c:when test="${Form.exportPdf eq 'y'}">
<mytl:pdfTag>
<pre:report />
</mytl:pdfTag>
</c:when>

<c:otherwise>
<pre:report />
</c:otherwise>
</c:choose>

Written by trumpetx

December 7, 2010 at 2:09 pm

Posted in Java

First Post!

leave a comment »

Hello,

Chances are that I’m talking to myself, and that is just okay with me!  This blog is simply where I plan on keeping little notes to myself, code snippets and perhaps the occasional rant.  Should you enjoy any or all of my posts, great!

Written by trumpetx

October 19, 2010 at 5:03 pm

Posted in General

Follow

Get every new post delivered to your Inbox.