001    package com.khubla.pragmatach.contrib.clientproxygenerator;
002    
003    import java.io.File;
004    import java.io.FileOutputStream;
005    import java.io.OutputStreamWriter;
006    import java.util.List;
007    
008    /**
009     * @author tome
010     */
011    public class ClientGenerator {
012       /**
013        * target dir
014        */
015       private final String targetDir;
016    
017       /**
018        * ctor
019        */
020       public ClientGenerator(String targetDir) {
021          this.targetDir = targetDir;
022       }
023    
024       /**
025        * generate a file
026        */
027       public void generate(RouteUrl routeUrl, String namespace) throws Exception {
028          try {
029             /*
030              * name
031              */
032             String name = routeUrl.getParts().get(routeUrl.getParts().size() - 1);
033             /*
034              * stream
035              */
036             String path = System.getProperty("user.dir") + "/" + targetDir;
037             new File(path).mkdirs();
038             FileOutputStream fos = new FileOutputStream(path + "/" + name + ".java", false);
039             /*
040              * writer
041              */
042             OutputStreamWriter osw = new OutputStreamWriter(fos);
043             /*
044              * package
045              */
046             osw.write("package " + namespace + ";\n");
047             /*
048              * HTTP Components
049              */
050             osw.write("import org.apache.http.client.methods.HttpGet;\n");
051             osw.write("import org.apache.http.impl.client.DefaultHttpClient;\n");
052             /*
053              * class
054              */
055             osw.write("public class " + name + " {\n");
056             /*
057              * method
058              */
059             osw.write("public void invoke() {\n");
060             osw.write("DefaultHttpClient client = new DefaultHttpClient();\n");
061             String url = generateUrl(routeUrl);
062             osw.write("}\n");
063             /*
064              * end of class
065              */
066             osw.write("}\n");
067             /*
068              * done
069              */
070             osw.close();
071             fos.flush();
072             fos.close();
073          } catch (final Exception e) {
074             throw new Exception("Exception in generate: '" + routeUrl.getContext() + "'", e);
075          }
076       }
077    
078       public String getTargetDir() {
079          return targetDir;
080       }
081    
082       private String generateUrl(RouteUrl routeUrl) {
083          String ret = "";
084          final List<String> parts = routeUrl.getParts();
085          for (final String part : parts) {
086             ret += "/" + part;
087          }
088          return ret;
089       }
090    }