Off the record

Aller au contenu | Aller au menu | Aller à la recherche

vendredi 16 décembre 2011

C# - WPF

using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Media.Effects;
using System.Windows.Controls;
using System.Media;

namespace WPFApplication
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            Window win = new Window();
            win.Title = "Hello world";  

            win.Height = 383;
            win.Width = 480;

            // change background color
            win.Background = new LinearGradientBrush(Colors.LightSeaGreen, Colors.Yellow, 45.0);

            // add an eventHandler to be run on window initialization
            win.Initialized += new EventHandler(w_Initialized);

            win.AddHandler(Control.MouseLeftButtonDownEvent, new RoutedEventHandler(OnClick));

            Application app = new Application();
            app.Run(win);

        }

        static void OnClick(object sender, RoutedEventArgs e)
        {
            if (e.Source is Ellipse)
            {
                SoundPlayer sp = new
                SoundPlayer(@"c:\windows\media\tada.wav");
                sp.Play();
            }
        }   

        static void w_Initialized(object window, EventArgs e)
        {
            Ellipse ellipse = new Ellipse();

            // add new eventsHandler to interact with the mouse
            ellipse.MouseEnter += new System.Windows.Input.MouseEventHandler(ellipse_MouseEnter);
            ellipse.MouseLeave += new System.Windows.Input.MouseEventHandler(ellipse_MouseLeave);
            
            ellipse.Width = 100;
            ellipse.Stroke = Brushes.Red;
            ellipse.StrokeThickness = 1;

            ImageBrush brush = new ImageBrush();
            ImageSourceConverter imageSourceConverter = new ImageSourceConverter();
            brush.ImageSource = (ImageSource) imageSourceConverter.ConvertFrom(@"c:\paper.jpg");
            ellipse.Fill = brush;

            ((Window)window).Content = ellipse;

        }

        static void ellipse_MouseEnter(object sender, EventArgs e) {
            Ellipse ellipse = (Ellipse)sender;
            OuterGlowBitmapEffect effect = new OuterGlowBitmapEffect();
            effect.GlowColor = Colors.DeepPink;
            effect.GlowSize = 10;
            ellipse.BitmapEffect = effect;
        }
        static void ellipse_MouseLeave(object sender, EventArgs e)
        {
            Ellipse ellipse = (Ellipse)sender;
            ellipse.BitmapEffect = null;
        }
    }
}

jeudi 15 décembre 2011

C# - WCF services

Define a service to expose logic. Expose the interface to this logic at a certain endpoint, certain channel (in our case BasicHTTPBinding).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using DM.PetShop;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // service relies on an implementation   
            ServiceHost host = new ServiceHost(typeof(OrderService));

            // service is exposed through the intreface (i.e. contract)
            host.AddServiceEndpoint(typeof(IOrderContract), new BasicHttpBinding(), "http://localhost:9000/PetShop");

            // open the service ("fire and forget" call)
            host.Open();

            // make sure the service doesn't die and print status
            Console.Title = String.Format("{0} is running ...", host.Description.Endpoints[0].Address);
            Console.Write("Server started. Press enter to stop..."); 
            Console.ReadLine();

            // close after receiving a keystroke
            host.Close();
            Console.WriteLine("Server stoppped. Press enter to quit...");
            Console.ReadLine();

        }
    }
}
Here is the contract (a.k.a. interface) that will be exposed to the world
using System.ServiceModel;

namespace DM.PetShop
{
    [ServiceContract(Name = "PetShopOrderContract", Namespace = Constants.SERVICE_NAMESPACE)]
    public interface IOrderContract
    {
        [OperationContract(Name = "PlaceOrder", Action = "PlaceOrder", ReplyAction = "PlaceOrderReply")]
        void PlaceOrder(string orderData);
    }
}
Here the implementation (note the annotations,most important part)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace DM.PetShop
{
    [ServiceBehavior(Name = "DM.PetShop.OrderService", Namespace = Constants.SERVICE_NAMESPACE)]
    public class OrderService : IOrderContract
    {
        public void PlaceOrder(string orderData)
        {
            Console.WriteLine("Diagnostic message !");
        }
    }
}
Then write a client :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Channels;
using IOrderContractChannelFactory = System.ServiceModel.ChannelFactory;
using DM.PetShop;

namespace Project_Client1
{
    class Client1App
    {
        static void Main(string[] args)
        {
            IOrderContractChannelFactory factory = new IOrderContractChannelFactory(new BasicHttpBinding());
            IOrderContract channel = factory.CreateChannel(new EndpointAddress("http://localhost:9000/PetShop/"));
            channel.PlaceOrder("1 parrot");

            IClientChannel clientChannel = (IClientChannel)channel;
            try
            {
                if (clientChannel.State != CommunicationState.Closed)
                    clientChannel.Close();
            }
            catch
            {
                clientChannel.Abort();
            }
        }
    }
}

mercredi 14 décembre 2011

Multithreading in C# (Java relies on the same foundation though)

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Threading;
using System.Collections.Generic;
using System.Diagnostics;

/// 
/// Summary description for JokeServer
/// 
public static class MOTDServer
{
    static Queue MessageQueue = new Queue();
    static Random rng = new Random();
    static Thread ProducerThread;

    static string[] Messages =
        {
            "A bird in the hand is worth two in the bush",
            "A rolling stone gathers no moss",
            "A penny saved is a penny earned",
            "I'd rather have a bottle in front of me than a frontal lobotomy",
            "When life hands you lemons, make lemonade"
        };

    private static void Init()
    {
        ProducerThread = new Thread(ProduceMessages);
        ProducerThread.Priority = ThreadPriority.Lowest;
        ProducerThread.Start();
    }


    public static string GetNextMessage()
    {
        if (ProducerThread == null)
            Init();

        string retval = null;

            Monitor.Enter(MessageQueue);
            while(MessageQueue.Count == 0)
                Monitor.Wait(MessageQueue);
            retval = MessageQueue.Dequeue();
            Monitor.Exit(MessageQueue);

        return retval;
    }

    static void ProduceMessages()
    {
        for (; ; )
        {
            if (MessageQueue.Count == 0)
            {
                Monitor.Enter(MessageQueue);
                MessageQueue.Enqueue(Messages[rng.Next(Messages.Length)]);
                Monitor.Pulse(MessageQueue);
                Monitor.Exit(MessageQueue);
            }

            Thread.Sleep(rng.Next(5000) + 2000);
            Debug.WriteLine("finished waiting");
        }
    }
}

C# - delegates and asynchronous programming


    // define the delegate needed for async calls below
    delegate List GetQuoteDelegate(DateTime dt);

    // Use Async invocation to request the quotes in parallel
    List[] GetQuotes(DateTime dt)
    {
        ReservationServices reservationService = new ReservationServices();
        List[] retval = new List[3];

        List getQuoteDelegates = new List();

        getQuoteDelegates.Add(reservationService.GetAirlineQuotes);
        getQuoteDelegates.Add(reservationService.GetCarRentalQuotes);
        getQuoteDelegates.Add(reservationService.GetHotelQuotes);

        CountdownEvent cde = new CountdownEvent(3);

        for(int i=0; i<3; i++)
        {
            int localI = i;
            GetQuoteDelegate getQuoteDelegate = getQuoteDelegates[i];
            getQuoteDelegate.BeginInvoke(dt,
                iar => {
                    retval[localI] = (List)getQuoteDelegate.EndInvoke(iar);
                    cde.Signal();
                }, 
                null
            );
        }

        // wait for all to be finished
        cde.Wait();

        return retval;
    }

lundi 12 décembre 2011

C# training - one more.

Material : tinyurl.com/89 sj qvn

Iterators and anonymous methods

- yield keyword - internal and external iterations - anonymous methods : for throwaway methods ...
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            foreach (int i in DivisibleBy(0, 50, 5))
            {
                Console.WriteLine(i);
            }
        }

        static IEnumerable DivisibleBy(int min, int max,int divisor) {
            for (int i = min; i < max; i++)
            {
                if (i % divisor == 0) {
                    yield return i;
                }
            }
        }

    }




    class X_Enumerable : IEnumerable { 

        private int min;
        private int max;
        private int divisor;

        public X_Enumerable(int min, int max, int divisor)
        {
            this.min = min;
            this.max = max;
            this.divisor = divisor;
        }
 
        public IEnumerator GetEnumerator() {
            return new X_Enumerator(min, max, divisor); 
        } 
    }

    class X_Enumerator : IEnumerator
    {
        int min;
        int max;
        int divisor;
        int current;

        public X_Enumerator(int min, int max,int divisor)
        {
            this.min=min;
            this.max = max;
            this.divisor = divisor;
        }

        public Object Current
        {
            get { return current; }
        }

        public bool MoveNext()
        {
            this.current++;
            while (current % divisor != 0) {
                this.current++;
                if (current == max) {
                    return false;
                }
            }
            return true;
        }

        public void Reset()
        {
            this.current=min;
        }

        public void Dispose()
        {
            throw new NotImplementedException();
        }
    }
 
}

LINQ to Objects

- anonymous types :
var p = new { Name = "Andy", Age = 21 };@@
using System;
using System.Collections.Generic;
using System.Text;

namespace LINQBase
{
    class Program
    {
        static void Main(string[] args)
        {
            var people = new List();
            people.Add(new Person { Name = "Nick", Height = 1.30m });
            people.Add(new Person { Name = "Jay", Height = 1.80m });
            people.Add(new Person { Name = "Bob", Height = 2.30m });

            foreach (var littlePerson in people.Where(p => p.Height < 2))
            {
                Console.WriteLine(littlePerson.Name);
            }
        }
    }


    public class Person
    {
        public decimal Height { get; set; }
        public string Name { get; set; }
    }

    public static class Utils {
        public static IEnumerable Where(this IEnumerable items, Predicate condition)
        {
            foreach (T item in items)
            {
                if (condition(item))
                    yield return item;
            }
        }
    }
}

LINQ to XML



  
    CLR via C#, Second Edition
    
      Jeffrey Richter
    
    .Net 2.0
    .Net General
    http://www.amazon.com/gp/product/0735621632/sr=8-1/qid=1141842947/ref=pd_bbs_1/103-3403410-7338268?_encoding=UTF8
    35.99
  
  
    Creating Workflow Services and Durable Services (MSDN)
    
      Anonymous
    
    .Net 3.5
    Service Composition
    http://msdn2.microsoft.com/en-us/library/bb412181.aspx
    0.0
  
  
    Data Binding with Windows Forms 2.0
    
      Brian Noyes
    
    .Net 2.0
    Windows Forms
    http://www.amazon.com/Data-Binding-Windows-Forms-2-0/dp/032126892X/ref=pd_bxgy_b_img_b
    32.99
  
  
    Essential ASP.NET 2.0
    
      Fritz Onion
      Keith Brown
    
    .Net 2.0
    Web Apps
    http://www.amazon.com/Essential-ASP-NET-2-0-Fritz-Onion/dp/0321237706/ref=pd_bbs_sr_1/103-2749730-3599818?ie=UTF8&s=books&qid=1176902837&sr=8-1
    36.99
  
  
    Essential ASP.NET With Examples in C#
    
      Fritz Onion
    
    .Net 2.0
    Web Apps
    http://www.amazon.com/Essential-ASP-NET-Examples-Fritz-Onion/dp/0201760401/ref=pd_bbs_sr_2/103-2749730-3599818?ie=UTF8&s=books&qid=1176902837&sr=8-2
    31.49
  
  
    Essential C# 2.0
    
      Mark Michaelis
    
    .Net 2.0
    C# Language
    http://www.amazon.com/Essential-2-0-Microsoft-NET-Development/dp/0321150775/ref=pd_bxgy_b_text_b/102-4792916-8428135?ie=UTF8&qid=1174210886&sr=1-2
    37.79
  
  
    Essential Windows Presentation Foundation
    
      Chris Anderson
    
    .Net 3.0
    Presentation Foundation
    http://www.amazon.com/Essential-Presentation-Foundation-Microsoft-Development/dp/0321374479/ref=sr_1_1/002-9650384-5136050?ie=UTF8&s=books&qid=1188296520&sr=8-1
    31.49
  
  
    Essential Windows Workflow Foundation
    
      Dharma Shukla
      Bob Schmidt
    
    .Net 3.0
    Workflow Foundation
    http://www.amazon.com/Essential-Workflow-Foundation-Microsoft-Development/dp/0321399838/ref=pd_bbs_sr_1/102-1611469-3153757?ie=UTF8&s=books&qid=1192436658&sr=8-1
    31.49
  
  
    Learning WCF
    
      Michele Bustamante
    
    .Net 3.0
    Communication Foundation
    http://www.amazon.com/Learning-WCF-Hands-Michele-Bustamante/dp/0596101627/ref=pd_bbs_sr_1/103-2749730-3599818?ie=UTF8&s=books&qid=1176904112&sr=8-1
    29.69
  
  
    LINQ in Action
    
      Fabrice Marguerie
      Steve Eichert
      Jim Wooley
    
    .Net 3.5
    LINQ
    http://www.amazon.com/LINQ-Action-Fabrice-Marguerie/dp/1933988169/ref=pd_bbs_sr_1?ie=UTF8&s=books&qid=1202326210&sr=1-1
    29.69
  
  
    Programming .NET Components, 2nd Edition
    
      Juval Lowy
    
    .Net 2.0
    .Net General
    http://www.amazon.com/gp/product/0596102070/ref=pd_kar_gw_1/103-3403410-7338268?_encoding=UTF8&v=glance&n=283155
    29.67
  
  
    Programming WCF Services
    
      Juval Lowy
    
    .Net 3.0
    Communication Foundation
    http://www.amazon.com/Programming-WCF-Services-Juval-Lowy/dp/0596526997/ref=pd_bbs_sr_1/102-1611469-3153757?ie=UTF8&s=books&qid=1192436749&sr=8-1
    29.69
  
  
    Programming Windows Workflow Foundation
    
      K. Scott Allen
    
    .Net 3.0
    Workflow Foundation
    http://www.amazon.com/Programming-Windows-Workflow-Foundation-Techniques/dp/1904811213/ref=sr_1_1/102-1611469-3153757?ie=UTF8&s=books&qid=1192436585&sr=8-1
    44.99
  
  
    Smart Client Deployment with ClickOnce
    
      Brian Noyes
    
    .Net 2.0
    Windows Forms
    http://www.amazon.com/Smart-Client-Deployment-ClickOnce-Applications/dp/0321197690/ref=pd_bbs_sr_1/102-5394843-6848112?ie=UTF8&s=books&qid=1175345601&sr=8-1
    29.69
  
  
    Understanding Windows CardSpace
    
      Vittorio Bertocci
      Garrett Serack
      Caleb Baker
    
    .Net 3.0
    CardSpace
    http://www.amazon.com/Understanding-Windows-CardSpace-Introduction-Independent/dp/0321496841/ref=sr_1_1/102-1611469-3153757?ie=UTF8&s=books&qid=1192436821&sr=8-1
    32.84
  
  
    Windows Forms 2.0 Programming (2nd Edition)
    
      Chris Sells
      Michael Weinhardt
    
    .Net 2.0
    Windows Forms
    http://www.amazon.com/gp/product/0321267966/qid=1141845579/sr=1-1/ref=sr_1_1/103-3403410-7338268?s=books&v=glance&n=283155
    32.39
  
  
    Windows Presentation Foundation Unleashed
    
      Adam Nathan
    
    .Net 3.0
    Presentation Foundation
    http://www.amazon.com/Windows-Presentation-Foundation-Unleashed-WPF/dp/0672328917/ref=pd_bbs_sr_1/103-2749730-3599818?ie=UTF8&s=books&qid=1176903814&sr=8-1
    34.49
  

public class Book
    {
        // Book properties
        public string Category { get; set; }
        public string Topic { get; set; }
        public string Title { get; set; }
        public decimal Price { get; set; }
        public string[] Authors { get; set; }
        public string WebSite { get; set; }

        // Book description
        public override string ToString()
        {
            string output = string.Format("{0} by {1}",
                Title, string.Join(", ", this.Authors));
            output += string.Format("
{0}
{1}
{2}", Category, Topic, Price.ToString("c")); return output; } }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace LinqToXmlLab
{
    static class RssFeed
    {
        public static XElement GetBooksXml(string url)
        {
            XElement xml = XElement.Load(url); 
            return xml;
        }

        public static List GetBooks(XElement xml)
        {
            XNamespace ns = "http://develop.com";

            IEnumerable booksQuery = from b in xml.Elements(ns + "book") select
                new Book { Title = (string)b.Element(ns + "title"),
                           Category = (string)b.Element(ns + "category"),
                           Topic = (string)b.Element(ns+"topic"),
                           Price = (decimal)b.Element(ns + "price"),
                           WebSite = (string)b.Element(ns + "link"),
                           Authors = (from a in b.Element(ns + "authors").Elements(ns + "author") select (string)a).ToArray()
                };

            return booksQuery.ToList();
        }

        public static XElement GetFeedXml(List books) { 
            XElement xml = new XElement("rss", 
                new XAttribute("version", "2.0"), 
                new XElement("channel", 
                    new XElement("title", "Essential .Net Reading"), 
                    new XElement("link", "http://localhost:12345/books/"), 
                    new XElement("description", ".Net developer reading"), 
                    from b in books orderby b.Category, b.Topic, b.Title select new XElement(
                        "item", 
                        new XElement("title", b.Title), 
                        new XElement("link", b.WebSite), 
                        new XElement("description", b)))); 
            return xml; 
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Xml.Linq;

namespace LinqToXmlLab
{
    class Program
    {
        static void Main(string[] args)
        {
            HttpListener listener = new HttpListener();
            listener.Prefixes.Add("http://localhost:12345/books/");
            listener.Start();
            Console.WriteLine("Rss Feed Service is running");
            Console.WriteLine("Press Ctrl+C to terminate ...");

            while (true)
            {
                HttpListenerContext ctx = listener.GetContext();
                using (StreamWriter writer = new StreamWriter(ctx.Response.OutputStream))
                {
                    // Load xml from file
                    string url = @"..\..\books.xml";
                    XElement booksXml = RssFeed.GetBooksXml(url);

                    // Get books list
                    List books = RssFeed.GetBooks(booksXml);

                    // Convert books list to xml
                    XElement feedXml = RssFeed.GetFeedXml(books);

                    // Send xml to the reponse stream
                    writer.Write(feedXml);
                }
            }
        }
    }
}

samedi 2 juillet 2011

Who is occupying *my* port?

Annoying bind exception...
If it looks like :

java.net.BindException: Address already in use

Then you might start your inquiry with the following command :

Windows : netstat -nab

OSX / Unix : lsof -i :9000

And...

WTF, Firefox (might be Windows though) is responsible for the port occupation. Shut down Firefox, kill the annoying issue !

-> lsof == list open files -> man lsof

mardi 21 juin 2011

C# training day 7 : Dependency injection with MEF

Dummy example in just one class :

Lire la suite

lundi 20 juin 2011

C# training day 6

XAML, WPF and converters Write a stupid app that has 2 text boxes, each time a number is entered in the first, the second receives the double, and the first should as well reflect the second one if the second is changed.

Lire la suite

jeudi 9 juin 2011

C# training day 2

Today it is about getting familiar with the delegates and events programming paradigms (C# implementation of the observer pattern, Listeners in Java)

Lire la suite

lundi 6 juin 2011

C# training day 1

I'm getting serious about C# and had a course today on the basics : - C# overview - Visual Studio - Projects and assemblies - Collections - Generics We were finally given 2 exercises.

Lire la suite

mercredi 18 mai 2011

Read a file in Java (with somewhat recent APIs...)

FileReader fr = new FileReader(fileLocation); // read a file

BufferedReader br = new BufferedReader(fr);

String tmp = br.readLine();

while (tmp != null) { content.append(tmp + "\n"); tmp = br.readLine(); } br.close();

mardi 23 juin 2009

Attending Jazoon

Weather is quite bad here in Zürich but well, I don't mind too much as I'll be attending Jazoon, THE java dev conference in Europe. I'll be blogging mainly for my employer but I'll tweet a lot, stay tuned : http://twitter.com/#search?q=Jazoon

Right now, opening keynote by James Gosling ! Edit 12:10 James Gosling's keynote was excellent, presenting shocking numbers and funny projects, in a nutshell :

  • 10 billions Java enabled devices in the world (yes billions)
  • 15 millions downloads of the JRE Java Runtime Environment a week
  • 6 millions Java developpers

Projects mentioned, built on Java (of course) :

  • brazilian healthcare system
  • hadron collider in Geneva
  • eBay.com Orbitz.com
  • the Oyster card (London tube pass system)
  • www.lincvolt.com project transforming a 6000 pounds lincoln car into an electric car, power management done by Java o' course

Then James did a little demo of the 2 ground breaking features of Java EE6, annotated servlets and EJB injection in servlets. I knew already about it, but it remains extremely handy and simplifies the EE development a great deal !

The talk closed with a little Java FX note and the future of computers, heading to massively parrallel computing instead of increasing GHz on single cores.

Afternoon sessions i attended were "RIA, security broken by design" and "JSF and Ajax @ Credit Suisse", quite obvious for the second one !
The RIA session was mostly about demoing XSS attacks and why using a framework is a good idea to enhance the security, nothing much. On the other hand, the CS-Jsf and Ajax session by Micha Kiener was extremely interesting and will hopefully impact my daily work as of Q3 2009. (Wait a minute Q3, really?).

Jazoon updates are starting to pop all around the blogosphere, in french even...Great !

mercredi 4 mars 2009

Big numbers

GDP France 2007 : 1892 Billions EUR[1]
State budget France 2007 : 355 Billions EUR [2]

GDP world 2007 : 78 360 Billions USD[3]
Average daily trading volume on the FX market : 4000 Billions USD[4]
Average daily trading volume in NYSE : 87 Billions USD[5]

Paulson plan : 700 Billions USD[6]
USA federal budget : 2979 Billions USD[7]

dimanche 8 février 2009

Applets, Ajax ou Flex?

Pour donner suite à cet article.

D'un point de vue pragmatique, j'aurais plus comparé des frameworks dans un premier temps. Applet, par exemple n'en a pas à ma connaissance, il faudra tout programmer de A à Z, et comprendre les détails de la techno. Pour faire une RIA, ça va être long. Très long. Personne ne fait ça, c'est clair.

Ajax, à l'opposé dispose de très nombreux frameworks qui permettront d'aller directement à l'essentiel.

  • lightweight, javascript uniquement (Dojo, Striptaculous)
    • plus de contrôle
    • indépendance entre les technos UI et serveur
    • nombreux widgets
    • API pour la communication avec le serveur
  • end-to-end (.Net Ajax framework, IceFaces, Appcelerator)
    • pas de javascript
    • style de développement identique aux applis non Ajax (tags générant du HTML et du JS)
    • dépendance accrue entre les widgets et la techno serveur

Dans la mesure ou l'on parle d'un business model de développement en interne, les coûts vont être pour 0.2 dans le dev et 0.6 dans la maintenance (licences, serveurs etc sont probablement négligeables).

Avec la mobilité permanente des développeurs, investir dans une techno jeune et très marketée comme Ajax, c'est s'assurer une certaine perennité et des coûts de maintenance bas. Qui ne connait pas Ajax dans le principe...
A l'inverse, quel développeur veut marquer sur son cv "2008-2010 : développement d'applets".

Pour Flex, comme toute techno propriétaire, les ressources de dév et maintenance coûteront plus chers "par tête", mais seront probablement plus productives, de par l'intégration et la qualité de l'outillage.

Pour revenir au concret, mes récentes tentatives avec JSF puis iceFaces ont été bien accueillies par les développeurs (Ajax framework de .Net pour les Microsoft boys). Solutions maintenant éprouvées, légères, qui couvrent la majorité des besoins, simples à maintenir dans le sens ou elles sont standard.
Applets? Plusieurs legacy en ont, et c'est un véritable cauchemar en maintenance...
Allez un peu de recherche sur JavaFX maintenant !

lundi 5 janvier 2009

Java certificates...code snippet.


/*
 * Copyright 2006 Sun Microsystems, Inc.  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 Sun Microsystems 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.
 */

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

public class InstallCert {

	public static void main(String[] args) throws Exception {
		String host;
		int port;
		char[] passphrase;
		if ((args.length == 1) || (args.length == 2)) {
			String[] c = args[0].split(":");
			host = c[0];
			port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
			String p = (args.length == 1) ? "changeit" : args[1];
			passphrase = p.toCharArray();
		} else {
			System.out
					.println("Usage: java InstallCert [:port] [passphrase]");
			return;
		}

		File file = new File("jssecacerts");
		if (file.isFile() == false) {
			char SEP = File.separatorChar;
			File dir = new File(System.getProperty("java.home") + SEP + "lib"
					+ SEP + "security");
			file = new File(dir, "jssecacerts");
			if (file.isFile() == false) {
				file = new File(dir, "cacerts");
			}
		}
		System.out.println("Loading KeyStore " + file + "...");
		InputStream in = new FileInputStream(file);
		KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
		ks.load(in, passphrase);
		in.close();

		SSLContext context = SSLContext.getInstance("TLS");
		TrustManagerFactory tmf = TrustManagerFactory
				.getInstance(TrustManagerFactory.getDefaultAlgorithm());
		tmf.init(ks);
		X509TrustManager defaultTrustManager = (X509TrustManager) tmf
				.getTrustManagers()[0];
		SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
		context.init(null, new TrustManager[] { tm }, null);
		SSLSocketFactory factory = context.getSocketFactory();

		System.out
				.println("Opening connection to " + host + ":" + port + "...");
		SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
		socket.setSoTimeout(10000);
		try {
			System.out.println("Starting SSL handshake...");
			socket.startHandshake();
			socket.close();
			System.out.println();
			System.out.println("No errors, certificate is already trusted");
		} catch (SSLException e) {
			System.out.println();
			e.printStackTrace(System.out);
		}

		X509Certificate[] chain = tm.chain;
		if (chain == null) {
			System.out.println("Could not obtain server certificate chain");
			return;
		}

		BufferedReader reader = new BufferedReader(new InputStreamReader(
				System.in));

		System.out.println();
		System.out.println("Server sent " + chain.length + " certificate(s):");
		System.out.println();
		MessageDigest sha1 = MessageDigest.getInstance("SHA1");
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		for (int i = 0; i < chain.length; i++) {
			X509Certificate cert = chain[i];
			System.out.println(" " + (i + 1) + " Subject "
					+ cert.getSubjectDN());
			System.out.println("   Issuer  " + cert.getIssuerDN());
			sha1.update(cert.getEncoded());
			System.out.println("   sha1    " + toHexString(sha1.digest()));
			md5.update(cert.getEncoded());
			System.out.println("   md5     " + toHexString(md5.digest()));
			System.out.println();
		}

		System.out
				.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");
		String line = reader.readLine().trim();
		int k;
		try {
			k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
		} catch (NumberFormatException e) {
			System.out.println("KeyStore not changed");
			return;
		}

		X509Certificate cert = chain[k];
		String alias = host + "-" + (k + 1);
		ks.setCertificateEntry(alias, cert);

		OutputStream out = new FileOutputStream("jssecacerts");
		ks.store(out, passphrase);
		out.close();

		System.out.println();
		System.out.println(cert);
		System.out.println();
		System.out
				.println("Added certificate to keystore 'jssecacerts' using alias '"
						+ alias + "'");
	}

	private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();

	private static String toHexString(byte[] bytes) {
		StringBuilder sb = new StringBuilder(bytes.length * 3);
		for (int b : bytes) {
			b &= 0xff;
			sb.append(HEXDIGITS[b >> 4]);
			sb.append(HEXDIGITS[b & 15]);
			sb.append(' ');
		}
		return sb.toString();
	}

	private static class SavingTrustManager implements X509TrustManager {

		private final X509TrustManager tm;
		private X509Certificate[] chain;

		SavingTrustManager(X509TrustManager tm) {
			this.tm = tm;
		}

		public X509Certificate[] getAcceptedIssuers() {
			throw new UnsupportedOperationException();
		}

		public void checkClientTrusted(X509Certificate[] chain, String authType)
				throws CertificateException {
			throw new UnsupportedOperationException();
		}

		public void checkServerTrusted(X509Certificate[] chain, String authType)
				throws CertificateException {
			this.chain = chain;
			tm.checkServerTrusted(chain, authType);
		}
	}

}

Highlighted by Syntaxhighlighter...What a nice tool !