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 11-20 of 255 total

How to get a parameter from the RequestContext in Spring

// How to get a parameter from the org.springframework.webflow.execution.RequestContext in Spring framework

// Java:
String myParameter = context.getExternalContext().getRequestParameterMap().get("myParameterPath");


// JSP:
<form:select path="myParameterPath" id="myParameterId">
    ...
</form:select>


// HTML rendered as:
<select name="myParameterPath" id="myParameterId">
...
</select>

How to eat an elephant in Java

How do you eat an elephant? Well, 'bite by bite', they told me. In Java, this may look like this:

  Elephant elephant = ...; // get the elephant from somewhere

  while (!elephant.isEatenCompletely()) {
    elephant.haveOneBite();
  }



Why am I writing this? Well, simply to test my dzone account ;)

Convert Java date to GMT

This function converts a local date to GMT. This version corrects the bug common to this type of conversion where the date is incorrectly converted when the time is close to the DST crossover.

private static Date cvtToGmt( Date date )
{
   TimeZone tz = TimeZone.getDefault();
   Date ret = new Date( date.getTime() - tz.getRawOffset() );

   // if we are now in DST, back off by the delta.  Note that we are checking the GMT date, this is the KEY.
   if ( tz.inDaylightTime( ret ))
   {
      Date dstDate = new Date( ret.getTime() - tz.getDSTSavings() );

      // check to make sure we have not crossed back into standard time
      // this happens when we are on the cusp of DST (7pm the day before the change for PDT)
      if ( tz.inDaylightTime( dstDate ))
      {
         ret = dstDate;
      }
   }

   return ret;
}

socket program in java to copy and delete files from server

// description of your code here

// insert code here..

Applying Python to modify Java code

Python script intended to open each Java's project file, add the license term on the start of the file as a Java comment and writing it to the disk.

1) You'll need a Python interpreter. Check this out in http://python.org.
2) You'll need to enter the root file directory of the Java project, like
python AddLicense.py ${path}
where ${path} defines user project root directory.
3) See http://fcmanager.wiki.sourceforge.net

 1:# Python script to add the LGPL notices to each java file of the FileContentManager project.
 2:import os, glob, sys
 3:License = """\
 4:/**
 5:*FileContentManager is a Java based file manager desktop application, 
 6:*it can show, edit and manipulate the content of the files archived inside a zip.
 7:*
 8:*Copyright (C) 2008 
 9:*
10:*Created by Camila Sanchez [http://mimix.wordpress.com/], Rafael Naufal [http://rnaufal.livejournal.com] 
11:and Rodrigo [rdomartins@gmail.com]
12:*
13:*FileContentManager is free software; you can redistribute it and/or
14:*modify it under the terms of the GNU Lesser General Public
15:*License as published by the Free Software Foundation; either
16:*version 2.1 of the License, or (at your option) any later version.
17:*
18:*This library is distributed in the hope that it will be useful,
19:*but WITHOUT ANY WARRANTY; without even the implied warranty of
20:*MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21:*Lesser General Public License for more details.
22:*
23:*You should have received a copy of the GNU Lesser General Public
24:*License along with FileContentManager; if not, write to the Free Software
25:*Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """
26:
27:size = len(sys.argv)
28:if size == 1 or size > 2:
29:    print "Usage: AddLicense.py $1"
30:    sys.exit(1)
31:inputPath = sys.argv[1]
32:if not os.path.exists(inputPath):
33:    print inputPath, "does not exist on disk"
34:    sys.exit(1)
35:if not os.path.isdir(inputPath):
36:    print inputPath, "isn't a dir"
37:    sys.exit(1)   
38:for path, dirs, files in os.walk(inputPath):
39:    fileWithLicense = ''
40:    for filepath in [ os.path.join(path, f)
41:            for f in files if f.endswith(".java")]:
42:        content = file(filepath).read()
43:        f = file(filepath, "w")
44:        print >>f, License + "\n" + content
45:        f.close()
46:        
47:    

Using JavaScript for ETL transformations

Scriptella provides a simple way to perform various transformations in JavaScript (or other scripting language which have a corresponding driver).
Our example transformation consists of 3 steps:
1) Select rows from source table.
2) Transform a column value from number to text
3) Insert a transformed value into a destination table.


<!DOCTYPE etl SYSTEM "http://scriptella.javaforge.com/dtd/etl.dtd">
<etl>
    <connection id="db" driver="auto" url="jdbc:hsqldb:mem:tst" user="sa" password="" classpath="../lib/hsqldb.jar"/>
    <connection id="js" driver="script"/> 
    <connection id="log" driver="text"/> <!-- For printing debug information on the console -->

    <script connection-id="db">
        CREATE TABLE Table_In (
            Error_Code INT
        );
        CREATE TABLE Table_Out (
            Error VARCHAR(10)
        );
        
        INSERT INTO Table_IN VALUES (1);
        INSERT INTO Table_IN VALUES (7);
    </script>

    <query connection-id="db">
        SELECT * FROM Table_In
        <script connection-id="log">
            Transforming $Error_Code
        </script>
        <!-- Transformation is described as an enclosing query
         which is executed before nested elements -->
        <query connection-id="js"> 
            <![CDATA[
               if (Error_Code < 5) {
                    Error_Code='WARNING'; //Set a transformed value
               } else {
                    Error_Code='ERROR'; //Set a transformed value
               }
               query.next(); //Don't forget to trigger nested scripts execution
            ]]>
            <script connection-id="db">
                <!-- Insert transformed value -->
                INSERT INTO Table_Out VALUES (?Error_Code); 
            </script>
            <script connection-id="log">
                Transformed to $Error_Code
            </script>
        </query>
    </query>
</etl>

Easiest way to do a POST test from Java

I need to test services with POST transactions. Using HTML to do it is the easiest way, constructed in Java (that part isn't necessary unless the args are somehow cooked or just too complex to trust hand-crafted HTML).

// write the HTML code out to stdout -- leave it to the user to redirect
System.out.print( "<html><body><form id='test' name='test' action='" );
System.out.print( url );
System.out.print( "/getStuff' method='POST'><input type='hidden' id='cid' name='cid' value=\"" );
System.out.print(  compId );
System.out.print( "\"/><input type='hidden' id='ids' name='ids' value=\"" );
System.out.print( ids );
System.out.print( "\"/>" );
System.out.print( "<input type='submit' name='Submit' value='Submit'></form></body></html>" );
System.out.println();

isWorkingDay?

// description of your code here

  public boolean isWorkingDay(Date date) {
        Calendar cal = GregorianCalendar.getInstance();
        cal.setTime(date);
        int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK); 
        if ((dayOfWeek  Calendar.SATURDAY) || (dayOfWeek  Calendar.SUNDAY)) {
            return false;
        } 
        return true;
   }

Sending/Receiving SMS from MIDlets

// Lets send an SMS now.
//get a reference to the appropriate Connection object using an appropriate url
MessageConnection conn = (MessageConnection) Connector.open("sms://:50001");
//generate a new text message
TextMessage tmsg = (TextMessage) conn.newMessage(MessageConnection.TEXT_MESSAGE);
//set the message text and the address
tmsg.setPayloadText(message);
tmsg.setAddress("sms://" + number);
//finally send our message
conn.send();


// Time to receive one.
//get reference to MessageConnection object
MessageConnection conn = (MessageConnection) Connector.open("sms://:50001");
//set message listener
conn.setMessageListener(
   new MessageListener() {
      public void notifyIncomingMessage(MessageConnection conn) {
         Message msg = conn.receive();
         //do whatever you want with the message
         if(msg instanceof TextMessage) {
            TextMessage tmsg = (TextMessage) msg;
            System.out.println(tmsg.getPayloadText());
         } else if(msg instanceof BinaryMessage) {
            .....
         } else {
            ......
         }
      }
   }
);

Cantor's Sets with Processing

This simple Processing programme generates the Cantor's Sets fractal.

Images are generated randomly, but tend to look like this.

int setHeight = 60;
color setColour = color(184 + random(-40, 40),
                        124 + random(-40, 40),
                        124 + random(-40, 40));
int wid = 600;

void setup() {
  size(wid, (int)((log(wid) / log(3) + 1) * (setHeight + 5)));
  background(0);
  smooth();
  
  cantorSet(10, 10, width - 20, setColour);
  
  save("cantorSet.png");
}

float rnd(float x) {
  return x + random(-20, 20);
}

void brushRect(int x, int y, int w, int h) {
  for (int i = 0; i < h; ++i) {
    float r = random(3);
    strokeWeight(r);
    float downpull = random(h / 4);
    float shudder = random(-2, 2);
    line(x + shudder, y + i, x + w - shudder, y + i + downpull);
  }
}

void cantorSet(int y, int offX, int wid, color col) {
  if ((y > height - 10) || (wid < 1))
    return;

  stroke(col);
  brushRect(offX, y, wid, setHeight);
  //fill(col);
  //rect(offX, y, wid, setHeight);
  
  color newCol = color(rnd(red(col)), rnd(green(col)),
                      rnd(blue(col)));
  cantorSet(y + setHeight + 5, offX, wid / 3, newCol);
  cantorSet(y + setHeight + 5, offX + wid*2/3, wid / 3, newCol);
}
« Newer Snippets
Older Snippets »
Showing 11-20 of 255 total