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
 

2 Comments

  1. Scott Cowan says:

    good work Orn, used your API code and added custom messages to the latest release

  2. Sean says:

    Nice! I’m installing TC EAP to play with some of the new features, look forward to implementing one of these twitter solutions.

Leave a Reply