I found myself adding a Remove link throughout my JSF application. It looked like this:
<h:commandlink value="Remove" actionlistener="#{MyBean.remove}">
I wanted to add a confirm dialog. So I added this.
<h:commandlink value="Remove" actionlistener="#{MyBean.remove}" onclick="javascript return confirm('Are you sure')">
But as I copied and pasted this through 5 or 6 different pages, I got to thinking, there has to be a better way.
So I created a custom jsf component by extending Command Link.
Step 1
First step was to create my new tag. It simply wraps the default command link.
package com.acme;
import com.sun.faces.taglib.html_basic.CommandLinkTag;
import javax.el.MethodExpression;
import javax.el.ValueExpression;
import javax.faces.component.UIComponent;
import javax.faces.component.html.HtmlCommandLink;
import javax.faces.event.MethodExpressionActionListener;
import javax.faces.webapp.UIComponentELTag;
/**
* @author cmcintosh
*/
public class RemoveCommandLinkTag extends UIComponentELTag { // Declare a bean property for the hellomsg attribute.
CommandLinkTag commandLink = new CommandLinkTag();
ValueExpression value;
MethodExpression actionListener;
// Associate the renderer and component type.
public String getComponentType() {
return commandLink.getComponentType();
}
public String getRendererType() {
return commandLink.getRendererType();
}
@Override
protected void setProperties(UIComponent component) {
super.setProperties(component);
component.setValueExpression("value", value);
((HtmlCommandLink)component).addActionListener(new MethodExpressionActionListener(actionListener));
((HtmlCommandLink)component).setOnclick("javascript:return confirm('Are you sure you want to remove?')");
}
@Override
public void release() {
super.release();
commandLink.release();
}
public void setValue(ValueExpression value) {
this.value = value;
}
public void setActionListener(MethodExpression actionListener) {
this.actionListener = actionListener;
}
}
Step 2
Next I needed to create a tld.
<taglib version="2.0" xmlns="http://java.sun.com/xml/ns/j2ee" xsi="http://www.w3.org/2001/XMLSchema-instance" schemalocation="http://java.sun.com/xml/ns/j2ee web-jsptaglibrary_2_0.xsd">
<tlib-version>1.0</tlib-version>
<short-name>datastore</short-name>
<uri>/WEB-INF/tlds/datastore</uri>
<tag>
<name>RemoveCommandLink</name>
<tag-class>com.acme.datastore.web.components.tags.RemoveCommandLinkTag</tag-class>
<attribute>
<name>value</name>
<deferred-value>
<type>java.lang.String</type>
</deferred-value>
</attribute>
<attribute>
<name>actionListener</name>
<required>false</required>
<deferred-method>
<method-signature>
actionListener(javax.faces.event.ActionEvent)
</method-signature>
</deferred-method>
<type>String</type>
</attribute>
</tag>
</taglib>
This was one of the hardest parts note the deferred-method and deferredvalue. I've never encountered those before.
Step 3
Add it to the web.xml:
<jsp-config>
<taglib>
<taglib-uri>http://datastore.acme.com/datastore</taglib-uri>
<taglib-location>/WEB-INF/tlds/datastore.tld</taglib-location>
</taglib>
</jsp-config>
Step 4
Finally to use it:
<%@taglib prefix="ds" uri="http://datastore.acme.com/datastore"%>
.
.
.
<ds:removecommandlink value="Remove" actionlistener="#{ViewModifyTable.removeColumn}">
<f:param name="applicationId" value="#{ViewModifyTable.applicationId}">
<f:param name="tableName" value="#{ViewModifyTable.tableName}">
</f:param></f:param></ds:removecommandlink></h:commandlink></h:commandlink>
Monday, October 5, 2009
Friday, September 18, 2009
Configure logging level
Here is how I disabled hibernate JPA logging level in code.
Logger.getLogger("org.hibernate").setLevel(Level.SEVERE);
Logger.getLogger("org.hibernate").setLevel(Level.SEVERE);
Tuesday, August 18, 2009
Readling List
XtraDb:
http://www.mysqlperformanceblog.com/2009/08/13/xtradb-the-top-10-enhancements/
Mysql performance blog
http://www.amazon.com/gp/product/0596101716?ie=UTF8&tag=perinc-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=0596101716
http://www.mysqlperformanceblog.com/2009/08/13/xtradb-the-top-10-enhancements/
Mysql performance blog
http://www.amazon.com/gp/product/0596101716?ie=UTF8&tag=perinc-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=0596101716
Monday, August 17, 2009
Pro JSF and Ajax by Jonas Jacobi and John R. Fallows
Read On: 8/17/09
Rating: 7 /10
Pros:
Rating: 7 /10
Pros:
- I liked this summary of other applications and which component of MVC they target: Examples of frameworks are Struts (an open source controller framework);
TopLink and Hibernate (model frameworks); and Tiles, Tapestry, XUL, and ADF UIX (so-
called view frameworks).
- Can be hard to read
- Why do so many frameworks model navigation these days?
Comparing Web Frameworks: Struts, Spring MVC, Webwork, Tapestry & JSF
Read on: 08/17/2009
Rating: 2/10
Way outdated, by the time I got my hands on it. No fault of the authors it was made in 2005.
Pros:
Rating: 2/10
Way outdated, by the time I got my hands on it. No fault of the authors it was made in 2005.
Pros:
- Concise
- Its just a bunch of slides
Beginning Spring 2 by Dave Minter
Read On: 8/17/09
Rating: 8/10
Pros:
Rating: 8/10
Pros:
- Very good introduction to Spring
- Clear explanation of IoC and dependency injection
- Made a strong case for using Spring for all applications
- Would of liked more Spring annotation examples.
- The database example could of been expanded. In particular I wasn't sure what the purpose of the DAO's were.
- I would of liked a more detail on Spring MVC
Friday, August 7, 2009
My desired Java technology stack.
This blogpost will be continually updated to list my favorite application stack for various projects. I welcome any comments to help me choose the best tools that will make me most productive.
Web Container
Currently I'm biased for tomcat its easy to setup and administer and I haven't had any problems with it.
I'm having good success with also using apache with mod_proxy_balancer as a load balancer mechanism. Still need to investigate how to make the apache instance not be my single point of failure.
I do not like glassfish. For a project a couple years ago we went with that and the app is still buggy and crashing a lot. Granted its probably more of the apps problem EJB 2.0 without a lot of other kruft but glassfish didn't impress me.
To consider:
I want to investigate JBOSS again. I used it in college and I wonder if features of JBOSS would be compelling enough for me to move off of Tomcat.
Possible reasons to consider JBOSS
Display Technologies
I don't know. I've tried GWT, JSF, JavaFX, JSP/JSTL. Nothing seems like the best technology here. I seem to spend most of my time writing the front end of the application which is the part i least enjoy.
What I'm looking for ideally is an easy to use set of components to layout without much fuss. Any suggestions? Note I'm not looking for something like struts, which as far as I understand it, helps with navigation.
Configuration
Spring, looks like a good standard way of handling application configuration.
Javascript Libraries
Need to investigate and choose between:
Database
Mysql enough said, although I would use MSSQL in a heartbeat again but you can't beat the price of Mysql.
Need to investigate scaling, and replication of Mysql that is the next big task I need to tackle at work.
ORM
After EJB 2.0 hell I swore off ORM's, but using the Google Appengine I've grown found of JPA. Just started looking at Hibernate JPA. Early impressions: I like it!
Anyone else want to recommend something?
Current ordering of choices:
XML Parsing
SAX/DOM/JAXB? I don't really know yet
Web Container
Currently I'm biased for tomcat its easy to setup and administer and I haven't had any problems with it.
I'm having good success with also using apache with mod_proxy_balancer as a load balancer mechanism. Still need to investigate how to make the apache instance not be my single point of failure.
I do not like glassfish. For a project a couple years ago we went with that and the app is still buggy and crashing a lot. Granted its probably more of the apps problem EJB 2.0 without a lot of other kruft but glassfish didn't impress me.
To consider:
I want to investigate JBOSS again. I used it in college and I wonder if features of JBOSS would be compelling enough for me to move off of Tomcat.
Possible reasons to consider JBOSS
- uses tomcat, and you can configure it to run with almost no features but tomcat, but still have the ability to use enterprise class features at a later date.
- Heard about their shard memory cache, this could be useful for some of my applications
Display Technologies
I don't know. I've tried GWT, JSF, JavaFX, JSP/JSTL. Nothing seems like the best technology here. I seem to spend most of my time writing the front end of the application which is the part i least enjoy.
What I'm looking for ideally is an easy to use set of components to layout without much fuss. Any suggestions? Note I'm not looking for something like struts, which as far as I understand it, helps with navigation.
Configuration
Spring, looks like a good standard way of handling application configuration.
Javascript Libraries
Need to investigate and choose between:
- tablekit
- jquery
- fabtabulous
- anything else?
Database
Mysql enough said, although I would use MSSQL in a heartbeat again but you can't beat the price of Mysql.
Need to investigate scaling, and replication of Mysql that is the next big task I need to tackle at work.
ORM
After EJB 2.0 hell I swore off ORM's, but using the Google Appengine I've grown found of JPA. Just started looking at Hibernate JPA. Early impressions: I like it!
Anyone else want to recommend something?
Current ordering of choices:
- Hibernate JPA- using javax.persitence classes to not tie into a vendor.
- Straight JDBC
XML Parsing
SAX/DOM/JAXB? I don't really know yet
Sunday, July 26, 2009
JavaFX - Peg Game.
JavaFX is a technology from SUN ( recently taken over by Oracle ) that competes against Adobe Flash and Microsoft Silverlight.
This article shows how to build a simple JavaFX program to play the 'Peg Game'.
The Peg game is played with a triangular piece of board with 15 holes in it. One hole (usually the top) is left open and golf tees are placed into the other 14. The objective is to hop over the pegs, removing the hopped peg, and in doing so remove all but one peg from the game.
Here it is in action: http://turnbasedgames.appspot.com/lastblock/Last_Block_Standing.html
To create this game I have four files:
Main.fx
TriangleBase.fx
GameSquare.fx
Util.java
Main.fx consists of:
package javafxapplication1;
import javafx.scene.paint.Color;
import javafx.scene.paint.LinearGradient;
import javafx.scene.paint.Stop;
import javafx.scene.Scene;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafxapplication1.TriangleBase;
/**
* @author Lars Vogel
*/
Stage {
var rect: Rectangle;
var circ: Circle;
title: "Last Block Standing"
scene: Scene {
width: 500
height: 500
var myString = "Last Block Standing"
var gameInstance: TriangleBase = new TriangleBase;
content: [
gameInstance,
Rectangle {
x: 50,
y: 300
width: 50,
height: 15
arcHeight: 2
arcWidth: 2
stroke: Color.BLACK
strokeWidth: 2
fill: LinearGradient {
startX: 0.0
startY: 0.0
endX: 0.0
endY: 1.0
stops: [
Stop {
color: Color.ORANGE
offset: 0.0
},
Stop {
color: Color.DARKRED
offset: 0.3
},
Stop {
color: Color.ORANGE
offset: 1.0
},
]
}
onMouseClicked: function(me) {
gameInstance.restart();
}
}
Text {
fill: Color.WHITE
font: Font {
name: "Arial Bold"
size: 12
}
x: 55,
y: 315
content: "Restart"
}
]
}
}
Triangle Base:
/*
* TriangleBase.fx
*
* Created on Jul 23, 2009, 10:55:02 PM
*/
package javafxapplication1;
import javafx.scene.control.Control;
import javafx.scene.Group;
import javafx.scene.Node;
/**
* @author avalanche
*/
public class TriangleBase extends Control {
public override function create(): Node {
return group;
}
var group: Group =
Group {
content: [
]
};
public function buildContent() {
insert GameSquare{ SquareId:1 x1:50 y1:0 hasTee:false} into group.content;
insert GameSquare{ SquareId:2 x1:40 y1:20} into group.content;
insert GameSquare{ SquareId:3 x1:60 y1:20} into group.content;
insert GameSquare{ SquareId:4 x1:30 y1:40} into group.content;
insert GameSquare{ SquareId:5 x1:50 y1:40} into group.content;
insert GameSquare{ SquareId:6 x1:70 y1:40} into group.content;
insert GameSquare{ SquareId:7 x1:20 y1:60} into group.content;
insert GameSquare{ SquareId:8 x1:40 y1:60} into group.content;
insert GameSquare{ SquareId:9 x1:60 y1:60} into group.content;
insert GameSquare{ SquareId:10 x1:80 y1:60} into group.content;
insert GameSquare{ SquareId:11 x1:10 y1:80} into group.content;
insert GameSquare{ SquareId:12 x1:30 y1:80} into group.content;
insert GameSquare{ SquareId:13 x1:50 y1:80} into group.content;
insert GameSquare{ SquareId:14 x1:70 y1:80} into group.content;
insert GameSquare{ SquareId:15 x1:90 y1:80} into group.content;
}
public function restart() {
delete group.content;
buildContent();
println("performing restart");
}
postinit{
buildContent();
}
}
GameSquare:
/*
* Node.fx
*
* Created on Jul 23, 2009, 11:12:07 PM
*/
package javafxapplication1;
import javafx.scene.control.Control;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafxapplication1.Util;
import java.util.HashMap;
var clickedSquare: GameSquare= null;
var gameSquareMap = new HashMap();
public class GameSquare extends Control {
public var SquareId: Integer;
public var squareColor: Color = Color.GREEN;
public var x1: Number;
public var y1: Number;
public var hasTee: Boolean = true;
var rect: Rectangle =
Rectangle{
fill: bind squareColor;
height: (20 * 2)
width: (20 * 2 )
translateX: (x1 * 2 )
translateY: (y1 * 2)
stroke: Color.BLACK;
onMouseClicked: function(me){
// first click, and I have a tee
if (clickedSquare == null and this.hasTee == true) {
println("setting clickedsquare");
clickedSquare = this;
clickedSquare.setIsClicked(true)
// second click, and I don't have a tee
}else if(this.hasTee == false and clickedSquare != null) {
// Find square we jumped over.
var hoppedNode = Util.getHoppedNode(clickedSquare.SquareId, this.SquareId);
if (hoppedNode != -1 ) {
var hoppedSquare = gameSquareMap.get(hoppedNode) as GameSquare;
if (hoppedSquare.hasTee) {
// hopped square is now empty
hoppedSquare.setHasTee(false);
this.setHasTee(true);
clickedSquare.setHasTee(false);
}
}
clickedSquare.setIsClicked(false);
clickedSquare = null;
} else {
//invalid remove marker for first click so user can try again.
clickedSquare.setIsClicked(false);
clickedSquare = null;
}
}
}
public override function create(): Rectangle {
return rect;
}
function setIsClicked(arg:Boolean) {
if (arg==true) {
squareColor = Color.BROWN;
}
else {
setHasTee(hasTee); //set to proper color;
}
}
function setHasTee(arg:Boolean) {
hasTee = arg;
if (hasTee == true) {
squareColor = Color.GREEN;
} else {
squareColor = Color.RED;
}
}
postinit {
this.setHasTee(hasTee);
gameSquareMap.put(SquareId, this);
}
}
Util.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package javafxapplication1;
import java.util.HashMap;
import java.util.Map;
/**
*
* @author avalanche
*/
public class Util {
static Map connections = new HashMap();
static {
connections.put("1,4", 2);
connections.put("1,6",3);
connections.put("2,7",4);
connections.put("2,9",5);
connections.put("3,8",5);
connections.put("3,10",6);
connections.put("4,6",5);
connections.put("4,11",7);
connections.put("4,13",8);
connections.put("5,12",8);
connections.put("5,14",9);
connections.put("6,13",9);
connections.put("6,15",10);
connections.put("7,9",8);
connections.put("8,10",9);
connections.put("11,13",12);
connections.put("12,14",13);
connections.put("13,15",14);
}
static public int getHoppedNode(int x, int y ) {
int lowest = Math.min(x,y);
int highest = Math.max(x,y);
Integer value = connections.get(lowest+","+highest);
if ( value == null )
return -1;
else
return value;
}
}
(This article is a placeholder, I'm going to come back and comment later)
This article shows how to build a simple JavaFX program to play the 'Peg Game'.
The Peg game is played with a triangular piece of board with 15 holes in it. One hole (usually the top) is left open and golf tees are placed into the other 14. The objective is to hop over the pegs, removing the hopped peg, and in doing so remove all but one peg from the game.
Here it is in action: http://turnbasedgames.appspot.com/lastblock/Last_Block_Standing.html
To create this game I have four files:
Main.fx
TriangleBase.fx
GameSquare.fx
Util.java
Main.fx consists of:
package javafxapplication1;
import javafx.scene.paint.Color;
import javafx.scene.paint.LinearGradient;
import javafx.scene.paint.Stop;
import javafx.scene.Scene;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafxapplication1.TriangleBase;
/**
* @author Lars Vogel
*/
Stage {
var rect: Rectangle;
var circ: Circle;
title: "Last Block Standing"
scene: Scene {
width: 500
height: 500
var myString = "Last Block Standing"
var gameInstance: TriangleBase = new TriangleBase;
content: [
gameInstance,
Rectangle {
x: 50,
y: 300
width: 50,
height: 15
arcHeight: 2
arcWidth: 2
stroke: Color.BLACK
strokeWidth: 2
fill: LinearGradient {
startX: 0.0
startY: 0.0
endX: 0.0
endY: 1.0
stops: [
Stop {
color: Color.ORANGE
offset: 0.0
},
Stop {
color: Color.DARKRED
offset: 0.3
},
Stop {
color: Color.ORANGE
offset: 1.0
},
]
}
onMouseClicked: function(me) {
gameInstance.restart();
}
}
Text {
fill: Color.WHITE
font: Font {
name: "Arial Bold"
size: 12
}
x: 55,
y: 315
content: "Restart"
}
]
}
}
Triangle Base:
/*
* TriangleBase.fx
*
* Created on Jul 23, 2009, 10:55:02 PM
*/
package javafxapplication1;
import javafx.scene.control.Control;
import javafx.scene.Group;
import javafx.scene.Node;
/**
* @author avalanche
*/
public class TriangleBase extends Control {
public override function create(): Node {
return group;
}
var group: Group =
Group {
content: [
]
};
public function buildContent() {
insert GameSquare{ SquareId:1 x1:50 y1:0 hasTee:false} into group.content;
insert GameSquare{ SquareId:2 x1:40 y1:20} into group.content;
insert GameSquare{ SquareId:3 x1:60 y1:20} into group.content;
insert GameSquare{ SquareId:4 x1:30 y1:40} into group.content;
insert GameSquare{ SquareId:5 x1:50 y1:40} into group.content;
insert GameSquare{ SquareId:6 x1:70 y1:40} into group.content;
insert GameSquare{ SquareId:7 x1:20 y1:60} into group.content;
insert GameSquare{ SquareId:8 x1:40 y1:60} into group.content;
insert GameSquare{ SquareId:9 x1:60 y1:60} into group.content;
insert GameSquare{ SquareId:10 x1:80 y1:60} into group.content;
insert GameSquare{ SquareId:11 x1:10 y1:80} into group.content;
insert GameSquare{ SquareId:12 x1:30 y1:80} into group.content;
insert GameSquare{ SquareId:13 x1:50 y1:80} into group.content;
insert GameSquare{ SquareId:14 x1:70 y1:80} into group.content;
insert GameSquare{ SquareId:15 x1:90 y1:80} into group.content;
}
public function restart() {
delete group.content;
buildContent();
println("performing restart");
}
postinit{
buildContent();
}
}
GameSquare:
/*
* Node.fx
*
* Created on Jul 23, 2009, 11:12:07 PM
*/
package javafxapplication1;
import javafx.scene.control.Control;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafxapplication1.Util;
import java.util.HashMap;
var clickedSquare: GameSquare= null;
var gameSquareMap = new HashMap();
public class GameSquare extends Control {
public var SquareId: Integer;
public var squareColor: Color = Color.GREEN;
public var x1: Number;
public var y1: Number;
public var hasTee: Boolean = true;
var rect: Rectangle =
Rectangle{
fill: bind squareColor;
height: (20 * 2)
width: (20 * 2 )
translateX: (x1 * 2 )
translateY: (y1 * 2)
stroke: Color.BLACK;
onMouseClicked: function(me){
// first click, and I have a tee
if (clickedSquare == null and this.hasTee == true) {
println("setting clickedsquare");
clickedSquare = this;
clickedSquare.setIsClicked(true)
// second click, and I don't have a tee
}else if(this.hasTee == false and clickedSquare != null) {
// Find square we jumped over.
var hoppedNode = Util.getHoppedNode(clickedSquare.SquareId, this.SquareId);
if (hoppedNode != -1 ) {
var hoppedSquare = gameSquareMap.get(hoppedNode) as GameSquare;
if (hoppedSquare.hasTee) {
// hopped square is now empty
hoppedSquare.setHasTee(false);
this.setHasTee(true);
clickedSquare.setHasTee(false);
}
}
clickedSquare.setIsClicked(false);
clickedSquare = null;
} else {
//invalid remove marker for first click so user can try again.
clickedSquare.setIsClicked(false);
clickedSquare = null;
}
}
}
public override function create(): Rectangle {
return rect;
}
function setIsClicked(arg:Boolean) {
if (arg==true) {
squareColor = Color.BROWN;
}
else {
setHasTee(hasTee); //set to proper color;
}
}
function setHasTee(arg:Boolean) {
hasTee = arg;
if (hasTee == true) {
squareColor = Color.GREEN;
} else {
squareColor = Color.RED;
}
}
postinit {
this.setHasTee(hasTee);
gameSquareMap.put(SquareId, this);
}
}
Util.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package javafxapplication1;
import java.util.HashMap;
import java.util.Map;
/**
*
* @author avalanche
*/
public class Util {
static Map
static {
connections.put("1,4", 2);
connections.put("1,6",3);
connections.put("2,7",4);
connections.put("2,9",5);
connections.put("3,8",5);
connections.put("3,10",6);
connections.put("4,6",5);
connections.put("4,11",7);
connections.put("4,13",8);
connections.put("5,12",8);
connections.put("5,14",9);
connections.put("6,13",9);
connections.put("6,15",10);
connections.put("7,9",8);
connections.put("8,10",9);
connections.put("11,13",12);
connections.put("12,14",13);
connections.put("13,15",14);
}
static public int getHoppedNode(int x, int y ) {
int lowest = Math.min(x,y);
int highest = Math.max(x,y);
Integer value = connections.get(lowest+","+highest);
if ( value == null )
return -1;
else
return value;
}
}
(This article is a placeholder, I'm going to come back and comment later)
Thursday, June 18, 2009
Too many open files
I owned a web server about a year ago that would crash every other night. I did everything I could to try to track down the exception (Too many open files), but I couldn't figure out what was causing it. I eventually chalked it up to a glassfish bug since they did have that problem before.
Well today I hit it again, this time in a tomcat instance. I ran across a form posting suggesting I try this command:
ls -l /proc/[pid]/fd
Which is an awesome command that I wish I knew about a year ago. This showed all the files that were opened which were indeed my fault. The problem came from a dom4j reader that wasn't being closed which was leaking the file connection. By closing the datastream the problem went away.
So if you have this problem on linux try the above command and see who is opening that file.
Hope that helps,
Chris
Well today I hit it again, this time in a tomcat instance. I ran across a form posting suggesting I try this command:
ls -l /proc/[pid]/fd
Which is an awesome command that I wish I knew about a year ago. This showed all the files that were opened which were indeed my fault. The problem came from a dom4j reader that wasn't being closed which was leaking the file connection. By closing the datastream the problem went away.
So if you have this problem on linux try the above command and see who is opening that file.
Hope that helps,
Chris
Wednesday, April 22, 2009
Use Python to post to twitter
Here is an example of using python to post to twitter.
def twit(login, password, msg):
payload= {'status' : msg, 'source' : 'TinyBlurb'}
payload= urllib.urlencode(payload)
base64string = base64.encodestring('%s:%s' % (login, password))[:-1]
headers = {'Authorization': "Basic %s" % base64string}
url = "http://twitter.com/statuses/update.xml"
result = urlfetch.fetch(url, payload=payload, method=urlfetch.POST, headers=headers)
return result.content
def twit(login, password, msg):
payload= {'status' : msg, 'source' : 'TinyBlurb'}
payload= urllib.urlencode(payload)
base64string = base64.encodestring('%s:%s' % (login, password))[:-1]
headers = {'Authorization': "Basic %s" % base64string}
url = "http://twitter.com/statuses/update.xml"
result = urlfetch.fetch(url, payload=payload, method=urlfetch.POST, headers=headers)
return result.content
Tuesday, April 21, 2009
Friday, April 10, 2009
Returning immutable collections
Many times it is desirable to return an internal collection object to consumers of your class.
For example:
The method above works, but has a draw back. The elements of your internalObjects list are now mutable outside your control. In C++ you might try to return const& instead to get around this problem, but how do you solve this in Java?
The first approach might be to return a copy. e.g:
This has the desired effect but with a couple of disadvantages. First you had to perform the copy which could be a performance bottleneck. Second the consumer may no longer point to the same objects if you modify your internalObject class.
The best way, that I know of, to do this is as follows:
The returned list still points to internal list, but is read only. Also, just to be pedantic, I've marked the list as final which means the reference will never change which is more correct for this example.
I hope that helps, leave comments on what you think.
@developresource
For example:
class Foo {
List _internalObjects = new ArrayList();
List getList() {
return _internalObjects;
}
}
The method above works, but has a draw back. The elements of your internalObjects list are now mutable outside your control. In C++ you might try to return const& instead to get around this problem, but how do you solve this in Java?
The first approach might be to return a copy. e.g:
class Foo {
List _internalObjects = new ArrayList();
List getList() {
List copy = new ArrayList();
copy.addAll(_internalObjects);
return copy;
}
}
This has the desired effect but with a couple of disadvantages. First you had to perform the copy which could be a performance bottleneck. Second the consumer may no longer point to the same objects if you modify your internalObject class.
The best way, that I know of, to do this is as follows:
class Foo {
final List _internalObjects = new ArrayList();
List getList() {
return new AbstractList() {
@Override
public Object get(int index)
{
return _internalObjects.get(index);
}
@Override
public int size()
{
return _internalObjects.size();
}
};
}
}
The returned list still points to internal list, but is read only. Also, just to be pedantic, I've marked the list as final which means the reference will never change which is more correct for this example.
I hope that helps, leave comments on what you think.
@developresource
Friday, March 27, 2009
Add new line at end of file.
Working on a cross platform c++ project I find it annoying that Linux requires a new line at the end of each file. I constantly forget to do this.
I wrote this simple macro which will add the new line each time you save a file.
You don't need the whole thing. Most of this is generated in EnvironmentEvents but saved here for posterity.
I wrote this simple macro which will add the new line each time you save a file.
You don't need the whole thing. Most of this is generated in EnvironmentEvents but saved here for posterity.
Option Strict Off
Option Explicit Off
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports System.Diagnostics
Public Module EnvironmentEvents
#Region "Automatically generated code, do not modify"
'Automatically generated code, do not modify
'Event Sources Begin
Public WithEvents DTEEvents As EnvDTE.DTEEvents
Public WithEvents DocumentEvents As EnvDTE.DocumentEvents
Public WithEvents WindowEvents As EnvDTE.WindowEvents
Public WithEvents TaskListEvents As EnvDTE.TaskListEvents
Public WithEvents FindEvents As EnvDTE.FindEvents
Public WithEvents OutputWindowEvents As EnvDTE.OutputWindowEvents
Public WithEvents SelectionEvents As EnvDTE.SelectionEvents
Public WithEvents BuildEvents As EnvDTE.BuildEvents
Public WithEvents SolutionEvents As EnvDTE.SolutionEvents
Public WithEvents SolutionItemsEvents As EnvDTE.ProjectItemsEvents
Public WithEvents MiscFilesEvents As EnvDTE.ProjectItemsEvents
Public WithEvents DebuggerEvents As EnvDTE.DebuggerEvents
Public WithEvents ProjectsEvents As EnvDTE.ProjectsEvents
Public WithEvents TextDocumentKeyPressEvents As EnvDTE80.TextDocumentKeyPressEvents
Public WithEvents CodeModelEvents As EnvDTE80.CodeModelEvents
Public WithEvents DebuggerProcessEvents As EnvDTE80.DebuggerProcessEvents
Public WithEvents DebuggerExpressionEvaluationEvents As EnvDTE80.DebuggerExpressionEvaluationEvents
'Event Sources End
'End of automatically generated code
#End Region
Private Sub DocumentEvents_DocumentOpened(ByVal Document As EnvDTE.Document) Handles DocumentEvents.DocumentOpened
End Sub
Private Sub DocumentEvents_DocumentSaved(ByVal Document As EnvDTE.Document) Handles DocumentEvents.DocumentSaved
Dim textSelection As EnvDTE.TextSelection
textSelection = CType(DTE.ActiveDocument.Selection(), EnvDTE.TextSelection)
textSelection.EndOfDocument(True)
textSelection.EndOfLine()
If textSelection.Text <> vbCrLf Then
textSelection.Text = textSelection.Text & vbCrLf
End If
End Sub
End Module
Visual Studio Macros for source control.
Visual Studio allows for users to customize the environment by writing macros. With Visual Studio 2008 the macros can be written in VB.Net. VB.Net is a very powerful language as it can use any of the standard .NET object, and in addition it has access to Visual Studios ENVDTE object.
The following set of macros replace the buggy Perforce source control plugin.
The following set of macros replace the buggy Perforce source control plugin.
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports System.Diagnostics
Public Module MiscCommands
Sub P4Add()
Dim filename As String = DTE.ActiveWindow.Document.FullName
ChDir("c:\p4")
ExecuteCommand("p4.exe", "add " + filename)
End Sub
Sub P4Edit()
Dim filename As String = DTE.ActiveWindow.Document.FullName
ChDir("c:\p4")
ExecuteCommand("p4.exe", "edit " + filename)
End Sub
Sub P4Diff()
Dim filename As String = DTE.ActiveWindow.Document.FullName
ChDir("c:\p4")
ExecuteCommand("p4.exe", "diff " + filename)
End Sub
Sub P4Revert()
Dim filename As String = DTE.ActiveWindow.Document.FullName
ChDir("c:\p4")
ExecuteCommand("p4.exe", "revert " + filename)
End Sub
Sub P4Opened()
ChDir("c:\p4")
ExecuteCommand("p4.exe", "opened")
End Sub
Sub P4History()
Dim filename As String = DTE.ActiveWindow.Document.FullName
ChDir("c:\p4")
ExecuteCommand("p4.exe", "filelog " + filename)
End Sub
Public Sub ExecuteCommand(ByVal filename As String, ByVal arguments As String)
Dim p As New System.Diagnostics.Process
p.StartInfo.UseShellExecute = False
p.StartInfo.FileName = filename
p.StartInfo.Arguments = arguments
p.StartInfo.RedirectStandardOutput = True
p.StartInfo.RedirectStandardError = True
p.Start()
p.WaitForExit()
WriteToMyNewPane(filename + " " + arguments, p.StandardOutput.ReadToEnd + p.StandardError.ReadToEnd)
End Sub
Public Sub WriteToMyNewPane(ByVal command As String, ByVal results As String)
Dim win As Window = _
DTE.Windows.Item(EnvDTE.Constants.vsWindowKindOutput)
Dim ow As OutputWindow = win.Object
Dim owPane As OutputWindowPane
Dim cnt As Integer = ow.OutputWindowPanes.Count
owPane = ow.OutputWindowPanes.Item(1)
owPane.OutputString(command & vbCrLf)
owPane.OutputString(results & vbCrLf)
owPane.Activate()
End Sub
Sub OpenFile()
Dim fileName As String = InputBox("Open file:")
If String.IsNullOrEmpty(fileName) Then
Return
End If
Dim item As EnvDTE.ProjectItem = DTE.Solution.FindProjectItem(fileName)
If item Is Nothing Then
MsgBox("File not found", MsgBoxStyle.Exclamation)
Return
End If
item.Open()
item.Document.Activate()
End Sub
End Module
Thursday, February 5, 2009
C# Key Listener
CodeGuru has this post:
This post will describe how to do this in C#. We will approach this by creating an executable that could be loaded at startup. It will listen for the F12 keyboard event and present a message box.
Create a new C# Console project in Visual Studio, call it 'ListenForHotkey.'
We will use a windows hook to notify our application when a key is pressed. So in the Program.cs file you should define four win32 API's. SetWindowsHookEx, UnhookWindowsHookEx, GetModuleName, CallNextHookEx. We'll also define a delegate for the callback, and some constants.
Here is the Program.cs with these definitions.
In the code above we've defined a delegate called LowLevelKeyboardProc that is the signature of the callback. Let's add our callback.
Our callback simply prints that a key was pressed then calls the next hook if applicable. This is important else another application that register a hook may not be called.
Lastly we should register our hook, and run the app. This is done in the main method.
In main we register the callback then call Application.Run() which puts the app in an infinite loop by waiting for any system messages. When the program is ready to exit we unregister our hook.
That's it.
Hope it helps.
Hi All
Looking for a little help..
I would like to create a process that runs on both a Windows XP and Vista Machines that loads on startup, what this process will do is, on the "F12" keypress it brings up a simple form that a user fills in some details then clicks on send, then it goes back to sleep and waits on the "F12" key being pressed.
Never created a process before so any help is appreciated.
Cheers
Djbell
This post will describe how to do this in C#. We will approach this by creating an executable that could be loaded at startup. It will listen for the F12 keyboard event and present a message box.
Create a new C# Console project in Visual Studio, call it 'ListenForHotkey.'
We will use a windows hook to notify our application when a key is pressed. So in the Program.cs file you should define four win32 API's. SetWindowsHookEx, UnhookWindowsHookEx, GetModuleName, CallNextHookEx. We'll also define a delegate for the callback, and some constants.
Here is the Program.cs with these definitions.
using System;
using System.Runtime.InteropServices; //Used for dll import
using System.Diagnostics; //'Process'
namespace ListenForHotkey
{
static class Program
{
[STAThread]
static void Main()
{
}
// Define win32 api calls.
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode,
IntPtr wParam, IntPtr lParam);
//Define delegate for the callback.
private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
//Define constants
private const int WH_KEYBOARD_LL = 13;
}
}
In the code above we've defined a delegate called LowLevelKeyboardProc that is the signature of the callback. Let's add our callback.
// Callback, executed when hook is triggered. In our case on keydown.
private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
System.Console.WriteLine("key pressed");
//Call next hook in chain.
return CallNextHookEx(m_hookId, nCode, wParam, lParam);
}
Our callback simply prints that a key was pressed then calls the next hook if applicable. This is important else another application that register a hook may not be called.
Lastly we should register our hook, and run the app. This is done in the main method.
[STAThread]
static void Main()
{
using (Process curProcess = Process.GetCurrentProcess())
using (ProcessModule curModule = curProcess.MainModule)
{
m_hookId = SetWindowsHookEx(WH_KEYBOARD_LL, HookCallback, GetModuleHandle(curModule.ModuleName), 0);
}
System.Windows.Forms.Application.Run();
UnhookWindowsHookEx(m_hookId);
}
In main we register the callback then call Application.Run() which puts the app in an infinite loop by waiting for any system messages. When the program is ready to exit we unregister our hook.
That's it.
Hope it helps.
GWT Programming Concepts
GWT Programming Concepts
This tutorial will introduce the architecture of GWT. It is aimed at programmers with little or no Java experience, but with reasonable experience with other programming languages using object oriented programming.
GWT is a single application. It consists of a series of panels. There may be a single panel onto which other panels are places, or multiple panels. You create and place Widgets onto these panels. Widgets are items like hyperlinks, textbox's, buttons, etc. With each of these widgets you can attach event listeners that will be execute when appropriate. For example you can attach a click listener to a button and when the user clicks the button, the action will be performed.
The important part of GWT is that panels and widgets are added using Java code.
Each widget (which includes a Panel) is an object that is derived from a number of base classes. For example:
UIObject : the base class with properties or methods:
* Size
* Width
* toString
Widget : derived from UIObject (so has its properties and methods), extended by:
* attached
* parent
FocusWidget : derived from Widget (so has its properties and methods), extended by:
* ClickListenerCollection
* addClickListener
Button : derived from FocusWidget (so has its properties and methods), extended by:
* getHTML
* setHTML
So through a series of inherited commands, the Panel object is instructed by GWT to deliver its HTML. Before delivering its own html, it instructs its children objects to deliver their html. Before their delivery, they also ask their children. And so on, until there are no unpolled children. In this way, the panel's html incorporates all the required html for all of its children.
So as a programmer, all you need to do is to slap down some panels, add some widgets containing the text, buttons, menu items, response to button clicks etc that you want and save it.
The command to "compile" the program takes all the Java objects you have created in your code, pulls out the required html and programmed actions and creates a final html container with a large amount of Javascript that writes the html you instructed through your Java objects.
far more functional and much more fun.
This tutorial will introduce the architecture of GWT. It is aimed at programmers with little or no Java experience, but with reasonable experience with other programming languages using object oriented programming.
GWT is a single application. It consists of a series of panels. There may be a single panel onto which other panels are places, or multiple panels. You create and place Widgets onto these panels. Widgets are items like hyperlinks, textbox's, buttons, etc. With each of these widgets you can attach event listeners that will be execute when appropriate. For example you can attach a click listener to a button and when the user clicks the button, the action will be performed.
The important part of GWT is that panels and widgets are added using Java code.
Each widget (which includes a Panel) is an object that is derived from a number of base classes. For example:
UIObject : the base class with properties or methods:
* Size
* Width
* toString
Widget : derived from UIObject (so has its properties and methods), extended by:
* attached
* parent
FocusWidget : derived from Widget (so has its properties and methods), extended by:
* ClickListenerCollection
* addClickListener
Button : derived from FocusWidget (so has its properties and methods), extended by:
* getHTML
* setHTML
So through a series of inherited commands, the Panel object is instructed by GWT to deliver its HTML. Before delivering its own html, it instructs its children objects to deliver their html. Before their delivery, they also ask their children. And so on, until there are no unpolled children. In this way, the panel's html incorporates all the required html for all of its children.
So as a programmer, all you need to do is to slap down some panels, add some widgets containing the text, buttons, menu items, response to button clicks etc that you want and save it.
The command to "compile" the program takes all the Java objects you have created in your code, pulls out the required html and programmed actions and creates a final html container with a large amount of Javascript that writes the html you instructed through your Java objects.
far more functional and much more fun.
Wednesday, January 14, 2009
Protocol Buffers
Protocol buffers is another way to serialize/deserialize data.
It was written by Google and supports Java, C++, Perl, and Python.
There website is at: http://code.google.com/p/protobuf/
I'm planning on trying this out for a c++ project I maintain where we need blindingly fast ( as fast we can get ) serialization, and de-serialization performance.
Once I've played with it, I'll post more information.
It was written by Google and supports Java, C++, Perl, and Python.
There website is at: http://code.google.com/p/protobuf/
I'm planning on trying this out for a c++ project I maintain where we need blindingly fast ( as fast we can get ) serialization, and de-serialization performance.
Once I've played with it, I'll post more information.
Tuesday, January 13, 2009
Flyweight Pattern
Flyweight design pattern is a software design pattern used to minimize memory usage by sharing data. It enables use of large number of objects that would typically require a lot of memory.
A common example of the Flyweight pattern is string pooling. Consider the Java programming language. The String data type is immutable. Because it is guaranteed that the string can never be changed the strings are pooled to ensure that only one instance exists in memory at any given time.
So if you create two strings s1 and s2 which both point to "foo" you really have two pointers to the same location in memory.
Java also employs the Flyweight pattern for Integer object. new Integer(0) actually returns a pointer to pre-constructed object. So if you create one-thousand Objects which each contain an Object of type Integer you will only have one Integer(0) which is an excellent way to save memory.
While your writing your programs consider if you could use the Flyweight pattern to save memory. An example I used was for a Object that contained three Strings. This tuple uniquely identified a configuration of runs that were stored in the database. The Strings were loaded via JDBC so they didn't get the String pooling provided by Java. Instead I made the constructor to the class private and exposed a public static method called 'get'. This method took the three strings and created the object if not already existing and returned a pointer. This cut my memory usage drastically.
Here is an example of my use of the Flyweight pattern.
If your using c++ you should look at the boost flyweight class. It hides the implementation and makes adding a flyweight to your c++ code trivial. http://svn.boost.org/svn/boost/sandbox/flyweight/libs/flyweight/doc/index.html
A common example of the Flyweight pattern is string pooling. Consider the Java programming language. The String data type is immutable. Because it is guaranteed that the string can never be changed the strings are pooled to ensure that only one instance exists in memory at any given time.
So if you create two strings s1 and s2 which both point to "foo" you really have two pointers to the same location in memory.
Java also employs the Flyweight pattern for Integer object. new Integer(0) actually returns a pointer to pre-constructed object. So if you create one-thousand Objects which each contain an Object of type Integer you will only have one Integer(0) which is an excellent way to save memory.
While your writing your programs consider if you could use the Flyweight pattern to save memory. An example I used was for a Object that contained three Strings. This tuple uniquely identified a configuration of runs that were stored in the database. The Strings were loaded via JDBC so they didn't get the String pooling provided by Java. Instead I made the constructor to the class private and exposed a public static method called 'get'. This method took the three strings and created the object if not already existing and returned a pointer. This cut my memory usage drastically.
Here is an example of my use of the Flyweight pattern.
class Product {
private Product() { } // don't let anyone explicitly create this object.
private static Mapproducts = new HashMap ();
public get(String arch, String chip, String config) {
Product p = products.get(arch + chip + config).hashCode());
if (p == null)
products.put(arch + chip + config).hashCode(),new Product(arch,chip,config));
return products.get(arch + chip + config).hashCode());
}
}
If your using c++ you should look at the boost flyweight class. It hides the implementation and makes adding a flyweight to your c++ code trivial. http://svn.boost.org/svn/boost/sandbox/flyweight/libs/flyweight/doc/index.html
Counting code lines.
I was curious how many lines of code my Java application had. I found this script very useful in finding out.
Here it is, in case it is helpful:
First it finds all files with the extension java (change to cpp, or pl, or py if you need to). It runs wc -l on each file to count the lines.
Then it removes my test directory, you can use -vE for a regular expression of items to remove or remove that command all together.
I then use awk to sum up the file line count and print out the increasing amount as well as the sum at the end.
Hope that helps.
Here it is, in case it is helpful:
find . -name "*java" -exec wc -l {} \; | grep -v "/test/" | awk '{print sum+=$1} END {print "Sum: "sum}'
First it finds all files with the extension java (change to cpp, or pl, or py if you need to). It runs wc -l on each file to count the lines.
Then it removes my test directory, you can use -vE for a regular expression of items to remove or remove that command all together.
I then use awk to sum up the file line count and print out the increasing amount as well as the sum at the end.
Hope that helps.
Monday, January 12, 2009
Google Chrome planned Mac rease middle of 2009
The popular Google Chrome browser is planned to be released for Mac in the middle of 2009. This should bring competition for the current default browser, Safari.
Google Chrome is also planning to add pluggable extensions which Mozilla's firefox has had for sometime.
These two changes should make Google Chrome an even more likely choice for consumers. In the end more competition is always good and Google's entry into the market will help keep the innovations coming.
Google Chrome is also planning to add pluggable extensions which Mozilla's firefox has had for sometime.
These two changes should make Google Chrome an even more likely choice for consumers. In the end more competition is always good and Google's entry into the market will help keep the innovations coming.
Boost scoped lock
I have been very impressed with the Boost libraries. Each day I'm finding more and more uses of Boost that make C++ programming easier.
My latest enjoyment comes from boost::mutex::scoped_lock.
scoped_lock follows the RAII (Resource Allocation Is Initialization) pattern. When the lock is constructed it holds onto the mutex until it is destructed.
Here is a simple example:
One word of caution. Up to Boost 1.36 the behavior of the mutex was different on Windows vs Linux. On Windows the lock would be recursive, that is you could call another method and enter it your thread already held that lock. Whereas on Linux that would cause a deadlock. The 1.37 version has fixed this issue and the both behave like the Linux version.
My latest enjoyment comes from boost::mutex::scoped_lock.
scoped_lock follows the RAII (Resource Allocation Is Initialization) pattern. When the lock is constructed it holds onto the mutex until it is destructed.
Here is a simple example:
class Foo
{
public:
void bar()
{
// Will grab the resource or wait until free
::boost::mutex::scoped_lock lock(m_mutex);
//Critical section
// No need to unlock the lock will do that itself.
}
private:
boost::mutex m_mutex;
}
One word of caution. Up to Boost 1.36 the behavior of the mutex was different on Windows vs Linux. On Windows the lock would be recursive, that is you could call another method and enter it your thread already held that lock. Whereas on Linux that would cause a deadlock. The 1.37 version has fixed this issue and the both behave like the Linux version.
Wednesday, January 7, 2009
Pro's and Con's of returing references
I've recently began working on a moderate size C++ application. The previous developer loved the benefits of returning const&.
For those who don't know returning const& can avoid an extraneous copy. Example:
The above code avoids the copy from m_name to the function return value that would have resulted with the following client code:
After working in this code base for a while now I believe that returning references are evil and should be treated just like returning a pointer, which is avoid it.
For example the problem that arose that took a week to debug was the following:
The problem in this example is clients are calling and getting references that are stored in the vector. Now what happens after clients insert a bunch of new elements? The vector needs to resize internally and guess what happens to all those references? That's right there invalid. This caused a very hard to find bug that was simply fixed by removing the &.
The conclusion I've arrived at is that returning a & is a pre-mature optimization. If your profiling shows you your code is very slow at this point than maybe consider it. But you should also be aware that most modern compilers optimize away this extra copy anyways.
Here is a contrived example that shows problems you can get into by blindly returning references. My advice avoid them until your profiler tells you that you have a problem.
Hope that Helps
For those who don't know returning const& can avoid an extraneous copy. Example:
class Foo {
Foo(std::string s) { m_name = s; }
std::string m_name;
public:
std::string const& name() { return m_name; }
}
The above code avoids the copy from m_name to the function return value that would have resulted with the following client code:
Foo f("bar");
std::string name = f.name();
After working in this code base for a while now I believe that returning references are evil and should be treated just like returning a pointer, which is avoid it.
For example the problem that arose that took a week to debug was the following:
class Foo {
std::vector< Bar > m_vec;
public:
void insert(Bar& b) { m_vec.push_back(b); }
Bar const& getById(int id) { return m_vec[id]; }
}
The problem in this example is clients are calling and getting references that are stored in the vector. Now what happens after clients insert a bunch of new elements? The vector needs to resize internally and guess what happens to all those references? That's right there invalid. This caused a very hard to find bug that was simply fixed by removing the &.
The conclusion I've arrived at is that returning a & is a pre-mature optimization. If your profiling shows you your code is very slow at this point than maybe consider it. But you should also be aware that most modern compilers optimize away this extra copy anyways.
Here is a contrived example that shows problems you can get into by blindly returning references. My advice avoid them until your profiler tells you that you have a problem.
#include
#include
#include
using namespace std;
class foo {
std::string m_string;
public:
std::string const getName(){
static int count = 0;
count++;
std::stringstream ss;
ss << count ;
m_string = ss.str();
return m_string;
}
};
foo f;
void fun(std::string const&s) {
f.getName();
std::cout << s;
}
int main() {
std::cout << " print version " << std::endl;
fun(f.getName());
}
Hope that Helps
Subscribe to:
Posts (Atom)