Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-10 of 15 total  RSS 

Java Cons class

Very simple Cons class for Java

public class Cons<T,U>
{
    private T car;
    private U cdr;

    public Cons( T carArg, U cdrArg )
    {
        car = carArg;
        cdr = cdrArg;
    }

    public T getCar(){ return car; }
    public U getCdr(){ return cdr; }
}

Passing an XSL param from one template to another

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:variable name="xx">
  <html>
  <body>
  <xsl:call-template name="show_title">
    <xsl:with-param name="title" />
  </xsl:call-template>
  </body>
  </html>
</xsl:variable>

<xsl:template name="show_title" match="/">
  <xsl:param name="title" />
  <xsl:for-each select="catalog/cd">
    <p>Title: <xsl:value-of select="$title" /></p>
  </xsl:for-each>
</xsl:template>

</xsl:stylesheet>

source: XSLT <xsl:param> Element [w3schools.com]

Trim Template for XSLT

Common Trim function for XSLT (as a template)

<xsl:template name="left-trim">
  <xsl:param name="s" />
  <xsl:choose>
    <xsl:when test="substring($s, 1, 1) = ''">
      <xsl:value-of select="$s"/>
    </xsl:when>
    <xsl:when test="normalize-space(substring($s, 1, 1)) = ''">
      <xsl:call-template name="left-trim">
        <xsl:with-param name="s" select="substring($s, 2)" />
      </xsl:call-template>
    </xsl:when>
    <xsl:otherwise>
      <xsl:value-of select="$s" />
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

<xsl:template name="right-trim">
  <xsl:param name="s" />
  <xsl:choose>
    <xsl:when test="substring($s, 1, 1) = ''">
      <xsl:value-of select="$s"/>
    </xsl:when>
    <xsl:when test="normalize-space(substring($s, string-length($s))) = ''">
      <xsl:call-template name="right-trim">
        <xsl:with-param name="s" select="substring($s, 1, string-length($s) - 1)" />
      </xsl:call-template>
    </xsl:when>
    <xsl:otherwise>
      <xsl:value-of select="$s" />
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

<xsl:template name="trim">
  <xsl:param name="s" />
  <xsl:call-template name="right-trim">
    <xsl:with-param name="s">
      <xsl:call-template name="left-trim">
        <xsl:with-param name="s" select="$s" />
      </xsl:call-template>
    </xsl:with-param>
  </xsl:call-template>
</xsl:template>

Exception Assertion Template For Eclipse

Eclipse template for exception assertion (Create template in Eclipse > Preferences > Java > Editor > Templates > New ... OK)

How to use:
1. Select code throwing exception
2. Alt + Shift + Z -> select corresponding template.

        try
        {
            ${line_selection}${cursor}
            fail("${Exception} expected.");
        }
        catch (${Exception} e)
        {
            assertEquals(${message}, e.getMessage());
        }

Java Singleton Template for Eclipse

This is a template for easily creating an implementation of the Singleton Pattern on Eclipse. Open Window->Preferences->Java->Editor->Templates click on New and insert the code below on the pattern text area; add a name (I suggest "singleton") - whenever you type this name and press Ctrl+Space the code will be inserted in your class - and you're good to go.

private static ${enclosing_type} instance;

private ${enclosing_type}(){}

public static ${enclosing_type} getInstance(){
	if(null == instance){
		instance = new ${enclosing_type}();
	}
	return instance;
}

Ruby style string injection via Prototype Templates

Requires Prototype 1.5

I'm honestly not sure why they didn't do this out of the box.

Object.extend(String.prototype, {
  mixin: function(obj) {
    return new Template(this).evaluate(obj);
  }
});


Oh, yes.

"#{company} forever!".mixin({company: 'Unspace'}) // Unspace forever!

Simplest possible PHP templating engine

// This code takes a template name and an array of variables
// and parses them with a file
//
// Example:
// print template('hello', array('who'=>'world'));
//
// Template (/templates/hello.html)
// Hello <?=$who?>!
//
// Outputs:
// Hello world!

define('DIR_TEMPLATES', dirname(__FILE__).'/templates');

function template($__name__, $__data__=array()) {
	extract($__data__);
	ob_start();
	require(DIR_TEMPLATES.'/'.$__name__.'.html');
	return ob_get_clean();
}

Running erb templates from the command line

The following script takes the name of a template as it's argument. Within the
template the command erb is in scope to call more templates. I wrote this for a friend who was having hell with NVU templates and I suggested to write the code by hand and use this script to build his static pages.

#!/usr/bin/ruby
# Quick and dirty template processing script. It takes
# as an argument the name of the first template script
# and then executes it to standard output.

require "erb"


class QuickTemplate
   attr_reader :args, :text
   def initialize(file)
      @text = File.read(file)
   end
   def exec(args={})
      b = binding
      template = ERB.new(@text, 0, "%<>")
      result = template.result(b)
      # Chomp the trailing newline
      result.gsub(/\n$/,'')
   end
end

def erb(file, args={})
   QuickTemplate.new(file).exec(args)
end

puts erb(ARGV[0])


The erb command itself takes an optional argument of a hash which is passed to the template as the
variable name args. Thus you can parameterize your sub templates.

Call the command as

ruby erb_run.rb main.thtml


The main template

<html>
   <head>
   </head>
   <div>
    <%= erb("title.thtml") %>
   </div>
</html>


and the sub template title.thtml

<title> This is Alex's cool restraunt</title>

Velocity 101

// The most basic use of the Velocity library. You pass in a Velocity context
// containing key-value pairs and the name of a Velocity template file. It
// returns a string containing the boilerplate text generated from combining
// the two.

// Copyright (c) 2002, John Munsch
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without 
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice, 
//       this list of conditions and the following disclaimer.
// 
//     * Redistributions in binary form must reproduce the above copyright 
//       notice, this list of conditions and the following disclaimer in the 
//       documentation and/or other materials provided with the distribution.
// 
//     * Neither the name of the John Munsch nor the names of its contributors 
//       may be used to endorse or promote products derived from this software 
//       without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
// POSSIBILITY OF SUCH DAMAGE.
// 
// To learn more about open source licenses, please visit: 
// http://opensource.org/index.php

package com.johnmunsch.util;

import java.io.StringWriter;

import org.apache.log4j.*;
import org.apache.velocity.*;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.exception.*;

/**
 * Boilerplate puts together context information and a template and produces an
 * output string that has all the replacements done in it.
 */
public class Boilerplate {
    private static Logger log = Logger.getLogger(Boilerplate.class.getName());
    
    public static String apply(VelocityContext context,
            String templateFilename) throws Exception {
        Template template = null;
        StringWriter sw = new StringWriter();

        Velocity.init();

        try {
            template = Velocity.getTemplate(templateFilename);

            template.merge(context, sw);
        } catch (ResourceNotFoundException rnfe) {
            log.error("Could not find the named template file.", rnfe);
            throw rnfe;
        } catch (ParseErrorException pee) {
            log.error("Error in the template file.", pee);
            throw pee;
        } catch (MethodInvocationException mie) {
            log.error("Error in function called by the template file.", mie);
            throw mie;
        }
       
        return sw.toString();
    }
}

Barebones xHTML and CSS template pages

Ok, so this guy already did this: http://www.bigbold.com/snippets/posts/show/583 but I needed a bit more. So this is my xHTML template page (it doesn't declare xml since it makes IE kick out of standards mode):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <title>XHTML TEMPLATE</title>
  
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <meta name="description" content="THIS IS A TEMPLATE XHTML PAGE" />
  
  <link rel="stylesheet" href="main.css" type="text/css" media="screen" />
  
  <!-- <script type="text/javascript" src="prototype.js">
  </script> -->
  <script type="text/javascript" language="JavaScript"><!-- <![CDATA[
  // ]]> --></script>
</head>
<body>
  <div id="container">

  </div>
</body>
</html>


This is the accomponying CSS:

body {
  font-family :Verdana, Arial, Sans;
  font-size   :76%;
  margin      :0px; }
div#container {
  font-size   :1.0em; }

.clearfix:after {
    content: "."; 
    display: block; 
    height: 0; 
    clear: both; 
    visibility: hidden;
}

.clearfix {display: inline-table;}

/* Hides from IE-mac \*/
* html .clearfix {height: 1%;}
.clearfix {display: block;}
/* End hide from IE-mac */
« Newer Snippets
Older Snippets »
Showing 1-10 of 15 total  RSS