Archive for June 2009

Java Authenticated POST

I came across this TeamCity Twitter plugin via StackOverflow the idea is to Tweet the build status as it changes. Pretty neat idea, however it will only run under Java 1.6. I tried to install on our build server at work but the TeamCity version we are running doesn’t run under Java 1.6 There was only one thing to do, write my own that will work under Java 1.5. It has to do authenticated POST request to the Twitter REST API. The build Twitter account can be found here, not that your that interested in our build Twitter feed 🙂

//
import java.io.*;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.URLEncoder;
import java.net.URLConnection;
//
import jetbrains.buildServer.serverSide.BuildServerAdapter;
import jetbrains.buildServer.serverSide.SBuildServer;
import jetbrains.buildServer.serverSide.SRunningBuild;
import jetbrains.buildServer.messages.Status;
//
import com.intellij.openapi.diagnostic.Logger;

// Tweets build start / finish to the build account
public class TwitterNotifier extends BuildServerAdapter
{
   private final static Logger LOG = Logger.getInstance(TwitterNotifier.class.getName());
   
   
   // Constructor, register the listener ( this )
   public TwitterNotifier(SBuildServer aBuildServer)
   {
       LOG.info(“*** Notifier adding listener=” + this );

       // Register with TC
       aBuildServer.addListener(this);
   }

   // Build started, set the version number
   public void buildStarted(SRunningBuild build)
   {
       String sTcBuildNumber = build.getBuildNumber();
       sendTweet( “Build “ + sTcBuildNumber + ” started on “ + build.getAgentName() );
   }

   public void buildChangedStatus(SRunningBuild build, Status oldStatus, Status newStatus)
   {
           String sTcBuildNumber = build.getBuildNumber();
       sendTweet( “Build “ + sTcBuildNumber + ” status, “ + newStatus.getText() );
   }
     
   public void buildInterrupted(SRunningBuild build)
   {
           String sTcBuildNumber = build.getBuildNumber();
       sendTweet( “Build “ + sTcBuildNumber + ” interrupted status, “ + build.getBuildStatus().getText() );
   }
   
   public void buildFinished(SRunningBuild build)
   {
           String sTcBuildNumber = build.getBuildNumber();
       sendTweet( “Build “ + sTcBuildNumber + ” finished, “ + build.getBuildStatus().getText() );          
   }
   
   // Updates the twitter account
   public static void sendTweet( String psText )
   {
           try
           {
               LOG.info( “*** TwitterNotifier plugin, “ + psText );
              
               //  Using paramaters known to work
               String urlString = “http://twitter.com/statuses/update.xml”;
               String data = “status=” + URLEncoder.encode( psText, “UTF-8”);
               String username = “twitteruser”;
               String password = “twitterpassword”;
              
               // 
               Authenticator.setDefault(new MyAuthenticator(username, password));
               // Send data
                URL url = new URL(  urlString );
                URLConnection conn = url.openConnection();
                conn.setDoOutput(true);
                OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
                out.write(data);
                out.flush();
                
                // Get the response
                StringBuffer sb = new StringBuffer();
                BufferedReader readIn = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String line;
                while ((line = readIn.readLine()) != null)
                        sb.append(line + \n );

                //
                //System.out.println( "*** Response=" + sb.toString() );
                
                // Close       
                out.close();
                readIn.close();
           }
           catch( Exception ex )
           {
               LOG.info( “***ERROR=” + exception2string( ex ) );
           }
   }

   public static String exception2string(Exception e)
   {
      try
      {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        return “——\r\n + sw.toString() + “——\r\n;
      }
      catch(Exception ex)
      {
        return “error converting exception to string”;
      }
   }

   
   static class MyAuthenticator extends Authenticator
   {
       private String username, password;

       public MyAuthenticator(String user, String pass)
       {
         username = user;
         password = pass;
       }

       protected PasswordAuthentication getPasswordAuthentication()
       {
         /*
         System.out.println("Requesting Host  : " + getRequestingHost());
         System.out.println("Requesting Port  : " + getRequestingPort());
         System.out.println("Requesting Prompt : " + getRequestingPrompt());
         System.out.println("Requesting Protocol: "
             + getRequestingProtocol());
         System.out.println("Requesting Scheme : " + getRequestingScheme());
         System.out.println("Requesting Site  : " + getRequestingSite());
         */

         return new PasswordAuthentication(username, password.toCharArray());
       }
   }

}  // EOC
 

using nLog in C#

Finally I had a new project were I needed some logging and on opportunity to use nLog for the first time. I have wanted to check it out in the past but it just never came to that. So here is the quick run down, the sample is from their tutorial with a slight mods from me and is really all you need to get nLog up and running quickly.

//
using NLog;
using NLog.Targets;
using NLog.Config;
using NLog.Win32.Targets;

            // Step 1. Create configuration object
            LoggingConfiguration config = new LoggingConfiguration();

            // Step 2. Create targets and add them to the configuration
            ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget();
            config.AddTarget(“console”, consoleTarget);
            //
            FileTarget fileTarget = new FileTarget();
            config.AddTarget(“file”, fileTarget);

            // Step 3. Set target properties
            consoleTarget.Layout = “${date:format=HH\\:MM\\:ss}: ${message}”;
            // set the file
            fileTarget.FileName = CxUtil.getDataDir() + \\log.txt”;
            fileTarget.Layout = “${date:format=HH\\:MM\\:ss}: ${message}”;
            // don’t clutter the hard drive
            fileTarget.deleteOldFileOnStartup = true;

            // Step 4. Define rules
            LoggingRule rule1 = new LoggingRule(“*”, LogLevel.Debug, consoleTarget);
            config.LoggingRules.Add(rule1);
           
            // Only log to file in non debug mode
            #if !DEBUG
                LoggingRule rule2 = new LoggingRule(“*”, LogLevel.Debug, fileTarget);
                config.LoggingRules.Add(rule2);
            #endif

            // Step 5. Activate the configuration
            LogManager.Configuration = config;

            // Create logger
            Logger logger = LogManager.GetLogger(“Example”);
            // Example usage
            logger.Trace(“trace log message”);
            logger.Debug(“debug log message”);
            logger.Info(“info log message”);
            logger.Warn(“warn log message”);
            logger.Error(“error log message”);
            logger.Fatal(“fatal log message”);