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

About this user

Douglas Wyatt

« Newer Snippets
Older Snippets »
Showing 1-8 of 8 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; }
}

Common keytool commands needed for living with Java

// generate a key -- make it long lived so we dont have to do this again
keytool -genkey -alias tomcat -keyalg RSA -validity 3650 -storepass changeit

// export cert to a file
keytool -export -rfc -v -file tomcatCert.crt -alias tomcat -storepass changeit
 
// look at the cert in the file
keytool -printcert -file tomcatCert.crt -storepass changeit


// delete pre-existing cert
keytool -delete -alias tomcat -keystore c:/apps/jdk/jre/lib/security/cacerts -storepass changeit

// import cert into a keystore
keytool -import -file tomcatCert.crt -trustcacerts -alias tomcat -keystore c:/apps/jdk/jre/lib/security/cacerts -storepass changeit

// look at the imported cert
keytool -list -alias tomcat -keystore c:/apps/jdk/jre/lib/security/cacerts -storepass changeit

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;
}

Drop an unnamed constraint from SqlServer 2000

// description of your code here

declare @name nvarchar(32), 
    @sql nvarchar(1000)

-- find constraint name
select @name = O.name 
from sysobjects AS O
left join sysobjects AS T
    on O.parent_obj = T.id
where isnull(objectproperty(O.id,'IsMSShipped'),1) = 0
    and O.name not like '%dtproper%'
    and O.name not like 'dt[_]%'
    and T.name = 'MyTable'
    and O.name like 'DF__MyTable__MyColu%'

-- delete if found
if not @name is null
begin
    select @sql = 'ALTER TABLE [MyTable] DROP CONSTRAINT [' + @name + ']'
    execute sp_executesql @sql
end

-- do your ALTER TABLE here

-- replace the constraint
select @sql = 'ALTER TABLE [MyTable] ADD CONSTRAINT [' + @name + '] DEFAULT (0) FOR [MyColumn]'
execute sp_executesql @sql

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();

Java filecopy using NIO

    public static void fileCopy( File in, File out )
            throws IOException
    {
        FileChannel inChannel = new FileInputStream( in ).getChannel();
        FileChannel outChannel = new FileOutputStream( out ).getChannel();
        try
        {
//          inChannel.transferTo(0, inChannel.size(), outChannel);      // original -- apparently has trouble copying large files on Windows

            // magic number for Windows, 64Mb - 32Kb)
            int maxCount = (64 * 1024 * 1024) - (32 * 1024);
            long size = inChannel.size();
            long position = 0;
            while ( position < size )
            {
               position += inChannel.transferTo( position, maxCount, outChannel );
            }
        }
        finally
        {
            if ( inChannel != null )
            {
               inChannel.close();
            }
            if ( outChannel != null )
            {
                outChannel.close();
            }
        }
    }

Example file download servlet

// description of your code here

  /**
     *  Sends a file to the ServletResponse output stream.  Typically
     *  you want the browser to receive a different name than the
     *  name the file has been saved in your local database, since
     *  your local names need to be unique.
     *
     *  @param req The request
     *  @param resp The response
     *  @param filename The name of the file you want to download.
     *  @param original_filename The name the browser should receive.
     */
    private void doDownload( HttpServletRequest req, HttpServletResponse resp,
                             String filename, String original_filename )
        throws IOException
    {
        File                f        = new File(filename);
        int                 length   = 0;
        ServletOutputStream op       = resp.getOutputStream();
        ServletContext      context  = getServletConfig().getServletContext();
        String              mimetype = context.getMimeType( filename );

        //
        //  Set the response and go!
        //
        //
        resp.setContentType( (mimetype != null) ? mimetype : "application/octet-stream" );
        resp.setContentLength( (int)f.length() );
        resp.setHeader( "Content-Disposition", "attachment; filename=\"" + original_filename + "\"" );

        //
        //  Stream to the requester.
        //
        byte[] bbuf = new byte[BUFSIZE];
        DataInputStream in = new DataInputStream(new FileInputStream(f));

        while ((in != null) && ((length = in.read(bbuf)) != -1))
        {
            op.write(bbuf,0,length);
        }

        in.close();
        op.flush();
        op.close();
    }

Get a String version of a stacktrace

// Get a String version of a stacktrace

    Throwable t = new Throwable();  // test code

    final Writer result = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(result);
    t.printStackTrace(printWriter);
    result.toString();
« Newer Snippets
Older Snippets »
Showing 1-8 of 8 total  RSS