Thursday, July 28, 2011

*nix/cygwin find commands

I need to keep a record of some Linux/cygwin "find" commands that I find useful. This is sort of a cookbook or quick reference of find commands that are handy to have around.

Print files which were modified within the last 10 days but and NOT in a "CVS", "build" or "classes" folder:
find . -type d -name CVS -prune -o -name build -prune -o -name classes -prune -o -mtime -10 \! -type d -print 

Print a sorted list of the largest files above 20000k minimum size
find . -type f -size +20000k -printf '%kk %p\n' | sort -n -r 

Print files with XML extensions containing the phrase "search string"
find . -type f -name "*.xml" -exec grep "search string" '{}' /dev/null \; -print       

Copy files newer than file X

Where file-x.txt is the file, and /tmp/copy-destination/ is the place you want to copy the files to:

find . -newer file-x.txt $1 | xargs -I {} cp -p $1{} /tmp/copy-destination/

Use OutputStreamWriter not FileWriter

Search your Java code for FileWriter and replace it with OutputStreamWriter... especially if you write UTF-8 encoded documents. You can run into a nasty problem where you develop your Java code on Linux and then when it runs on Windows, character encoding problems crop up. FileWriter uses a OS System setting to determine what encoding to use, so it will change depending on what OS runs the Java code!

Here is an example of how to use OutputStreamWriter for UTF-8 encoded output.
         OutputStreamWriter out = null;
try {
try {
out = new OutputStreamWriter(new FileOutputStream(outputFile),"UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e.getMessage,e);
}
try {
out.append(yourStringDataToWriteToOutputFile);
out.flush();
} catch (IOException e) {
throw new RuntimeException(e.getMessage,e);
}
} catch (FileNotFoundException e) {
throw new RuntimeException(e.getMessage,e);
} finally {
try {
out.close();
} catch (IOException e) {
throw new RuntimeException(e.getMessage,e);
}
}

Hope this helps you get past file character encoding bugs with Java. Here is a great link on various Java Anti-Patterns which should be avoided when writing enterprise class robust code:

Saturday, June 18, 2011

How do I use my web resource bundle within my Spring controller?



Here is how I did it:



In my controller:




import org.springframework.context.ApplicationContext; ...
@Autowired private ApplicationContext context;



In the resource bundle ApplicationResources.properties


gotocode.error.notfound=Sorry {0} is not recognized as a code. 



Back in the controller




public static final String GOTOCODE_NOTFOUND_KEY = "gotocode.error.notfound";
public
static final String CODE_NOT_FOUND_MESSAGE = "Sorry the entry {0} is not recognized as a code.";
...
public ModelAndView findNextInSeries(String code,..
String errorMessage = context.getMessage(
GOTOCODE_NOTFOUND_KEY, new Object[] { code }, CODE_NOT_FOUND_MESSAGE, Locale.getDefault());   

Previously my ApplicationResources.properties was configured in the web.xml







http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" id="WebApp_1270163143862"></web-app>

<display-name>Sample Spring Resource Bundle
<distributable>

<context-param>
<param-name>javax.servlet.jsp.jstl.fmt.localizationContext
<param-value>ApplicationResources



As well as in the Spring Application context configuration (dispatcher-servlet.xml):

Setting up Eclipse TPTP for performance monitoring of Jetty run from Maven

This is a document to help you setup Eclipse TPTP plugin for performance monitoring of J2EE application deployed to Jetty using the jetty-maven-plugin.

Open MyEclipse Configuration center and search for TPTP, download the newest version of TPTP plugin, restart your IDE after the install finishes.

Next go to the TPTP homepage and download the Agent controller for your architecture (I downloaded windows IA32).

Extract the Agent controller zip to C:\Tools\agntctrl.win_ia32-TPTP-4.7.2

Edit your system environment variables and add

RASERVER_HOME=C:\Tools\agntctrl.win_ia32-TPTP-4.7.2 PATH=C:\Tools\agntctrl.win_ia32-TPTP-4.7.2\bin;%PATH%  Open a command prompt and goto agent controller cd C:\Tools\agntctrl.win_ia32-TPTP-4.7.2\bin SetConfig.bat 

This should display the following:

C:\Tools\agntctrl.win_ia32-TPTP-4.7.2\bin>SetConfig.bat Specify the fully qualified path of "javaw.exe" (e.g. c:\jdk1.4\jre\bin\javaw.ex e):   Default>"C:\Program Files\IBM\WebSphere\AppServer\java\jre\bin\javaw.exe" (Pre ss  to accept the default value)   New value> Network access mode (ALL=allow any host, LOCAL=allow only this host, CUSTOM=list  of hosts):   Default>"LOCAL" (Press  to accept the default value)   New value>ALL Security enabled. (true/false):   Default>"FALSE" (Press  to accept the default value)   New value> 

Start the Agent Controller by launching a command console window with Administrator privledges (Run as Admni..) The change your working directory to

cd C:\Tools\agntctrl.win_ia32-TPTP-4.7.2\bin
ACServer.exe

See this link for more agent controller info http://dev.eclipse.org/viewcvs/viewvc.cgi/platform/org.eclipse.tptp.platform.agentcontroller/src-native-new/packaging_md/windows/getting_started.html?root=TPTP_Project&view=co

This is also a link with good info on TPTP http://eclipse.sys-con.com/node/508048?page=0,2

Configure piAgent and start your application with Maven by adding this to MAVEN_OPTS environment variable:

-XrunpiAgent:server=enabled 

From eclipse navigate to Run | Profile Configurations... | Attach to Agent | New

ACServer should be running on localhost port 10002, check this with netstat -a -b -n command or test button in eclipse

Jetty JVM Agent should be detected on the Agent tab. select ONLY ONE of the profile probes, CPU --or-- MEMORY etc.. do NOT select more than one, treat them as mutually exclusive radio buttons rather than check boxes.

You can then perform tasks in your application and save the data captured. Also you can create new reports from the captured data with TPTP eclipse tools.

See http://www.eclipse.org/articles/Article-TPTP-Profiling-Tool/tptpProfilingArticle.html

Why your web browser should be updated often.

I was reading a book online about 20 things people should understand about the Internet. Number 7 is about keeping your browser updated. Here are the3 simple reasons given:

First, old browsers are vulnerable to attacks

Second, the web evolves quickly. Old browsers will miss out.

Third and last, old browsers slow down innovation on the web.


I wish I had this in mind when working with a client who insisted on a dynamic Web 2.0 look to the complex application but also demanded compatibility with IE7.

Delivering on both of these requirements (latest Internet bells and whistles like AJAX as well as backward compatibility with older browser versions) increases the difficulty level and cost of the site development considerably. First you have to test on these older browser versions in addition to testing on the common browsers, which increases the development time. Next you have to pare down features and functionality so that it works consistently everywhere, so you might have had a nice dynamic form or navigation control working in IE9 and FireFox 4, but it all gets tossed out when it cannot work in IE7 (see holding up innovation reason given above). Also for some "must have" site features or functionality: developers will usually have to code around older browser version quirks, so instead of writing code in one place to perform a task, it is written one place or one way for modern browsers and another place or another way for older browsers. This causes a code maintenance issue as you now have multiple places to check to fix problems or update code for a single feature or site behavior. This is a problem for HTML, CSS, and Javascript as all three can behave differently on different browsers. Yet another problem that can arise is your performance can vary widely in different browser flavors and versions, for example IE7 javascript benchmarks are miserably slow when compared with more recent versions of IE and other browsers like FireFox or Chrome. This can cause problems where failing to test on the required browser versions can really bite you. If a performance issue (or any browser version issue) is found late in the development cycle, either because the testing was not done along side development in that version or because developers only used modern browsers for their self verification and validation of the application, then the time to fix the problem is much larger and more difficult than if it had been caught earlier.
The best defense to this situation of having to develop Javascript for modern sites to be used by clunky old browser versions is to use a good library like GWT, jQuery or Dojo. These abstract away many of the browser specific cruft that would drive you mad when trying to implement your site. I am not sure of a solution for this problem as it relates to HTML/CSS however, cross browser CSS is a major pain in the you know what.



Thursday, April 28, 2011

Body for Life meal plan

Read about Body for Life Champion Joshua Sundquist

This was his daily meal plan:
6:00am Meal 1
Multivitamin
1.5 cups of whole grain rolled oats (old fashioned oatmeal) cooked with water and mixed with a scoop of 100% Whey Protein and a teaspoon of Flax Seed Oil (good source of Omega Oils).

7:00–8:00am Workout

8:30am Meal 2
Post-workout meal: Two servings of 100% Whey Protein mixed with a teaspoon of chocolate syrup (this is the only sugar I ate—I like to give my muscles some quick energy for recovery).

11:00am Meal 3
Sandwich made with two slices of 100% whole grain bread, natural peanut butter and two sliced bananas.

2:00pm Meal 4
Grilled chicken breast, brown rice, a serving of raw vegetables

6:00 pm Meal 5
Whole grain pasta, soy protein isolate shake, a serving of raw vegetables

9:00pm Meal 6
Bowl of whole grain cereal (Cheerios®*, Shredded Wheat®*, etc) and 100% Whey Protein shake

12:00pm Meal 7
Natural (unsweetened) applesauce mixed with low-fat cottage cheese, serving of Casein Protein shake

3:00am Bonus nutrition
100% Whey Protein shake



per day serving per week per month per challenge
flax Seed Oil 1 6 24 72
chocolate Syrup 1 6 24 72
100% Whey Protein 4 24 96 288
casein protein 1 6 24 72
unsweetend applesauce 1 6 24 72
chicken breasts 1 6 24 72
raw vegetables 2 12 48 144
100% whole grain bread 2 12 48 144
natural peanut butter 1 6 24 72
bananas 2 12 48 144
oatmeal 1.5 9 36 108
low fat cottage cheese 1 6 24 72
Cheerios 1 6 24 72
Skim Milk 1 6 24 72
Soy Protein Powder 1 6 24 72
Whole grain Pasta 1 6 24 72

Got all that? Great but let me tell you, I gave this plan a shot back in October of 2010, stuck it out for 12 weeks. I actually hated this toward the end, also did not get anywhere on it. I even tried to modify it by reducing portions or eliminating some of the late night meals after not seeing results for 6 weeks. I guess the lesson there is don't do something for 12 weeks if it does not work by 4 weeks. My current weight is under 215lb, I just finished a 12 week challenge at work a "biggest loser" competition, I lost about 20 lbs and 3% body fat. My sister is doing great on an HCG-style program, and so if I gain a single pound back, I am jumping on HCG so hard it might break something. She has lost more weight in 30 days than I lost in 90.

So far 12 Steps to Whole Foods Steps 1-3 are working out for me very consistently (well that along with 6-10 workouts per week.) I do feel great when I workout and eat better, now if I could just get enough sleep. I am surprised that adding two quarts of green smoothies and big salads for lunch and dinner is able to keep me from having hunger pains. I am not vegetarian but I have reduced my meat intake down to a 10th of what it was. Reading the book has made me avoid meat at almost every opportunity, I just see it crawling with diseases and squirming with parasites (or imagine it decaying inside my intestines) and order the vegetarian option.

I also took a running class from Ken Harper who owns the Runners Corner in Orem, that class was great and helped inspire me to make running outside a part of my weekly exercise. I read Born to Run and got the Vibrams Five Fingers which I think is helping to strengthen my weak feet and legs . I am also incorporating weight lifting with a partner from work, supposedly this is a great way to gain muscle and lose fat. The only things I am not doing that I may try are team sports, organized races, and swimming.

Sunday, January 2, 2011

Validating XML against a Schema (XSD)

Notepad++
Notepad++ has an optional plugin to allow you to validate an XML file against an XSD (this is good because it is a free "gratis" tool).

First, download and install Notepad ++ here

Download and add XML tools plugin for Notepad ++ here

Download the ExternalTools.zip as well from the sourceforge link above and extract the contents to the Notepad++ install folder.

Restart Notepad ++

Open XML file to validate, Click Plugins | XML Tools | Validate now

A window will pop up with errors or validation successfully completed message.


jEdit
jEdit also has optional plugin to validate XML against an XSD.

First download jEdit here

Open jEdit and click Plugins | Plugin Manager

Check the box for XML plugin, click install button

Open the XML file, validation errors appear as red underlines.

Also in jEdit you can open Plugins | XML | Parse as XML will open a window and show a tree navigation of the XML jumping to the first error found if any.

cygwin
An optional package to install in cygwin is called libXML2, this package includes a command line tool named xmllint which can also validate XML against an XSD
$ xmllint --schema /cygdrive/c/path/to/xsd/myschema.xsd /cygdrive/c/path/to/xml/myxml.xml

About Me

My photo
Lead Java Developer Husband and Father

Tags