001 package com.khubla.pragmatach.framework.router; 002 003 import java.lang.reflect.Method; 004 import java.util.ArrayList; 005 import java.util.Collections; 006 import java.util.List; 007 import java.util.Set; 008 009 import com.khubla.pragmatach.framework.annotation.Route; 010 import com.khubla.pragmatach.framework.api.PragmatachException; 011 import com.khubla.pragmatach.framework.controller.ControllerClasses; 012 013 /** 014 * all routes, both GET and POST, sorted. 015 * 016 * @author tome 017 */ 018 public class PragmatachRoutes { 019 /** 020 * singleton 021 */ 022 private static PragmatachRoutes instance = null; 023 024 /** 025 * getter 026 */ 027 public static PragmatachRoutes getInstance() throws PragmatachException { 028 try { 029 if (null == instance) { 030 instance = new PragmatachRoutes(); 031 } 032 return instance; 033 } catch (final Exception e) { 034 throw new PragmatachException(e); 035 } 036 } 037 038 /** 039 * GET routes 040 */ 041 private final List<PragmatachRoute> GETRoutes = new ArrayList<PragmatachRoute>(); 042 /** 043 * POST routes 044 */ 045 private final List<PragmatachRoute> POSTRoutes = new ArrayList<PragmatachRoute>(); 046 047 /** 048 * ctor 049 */ 050 private PragmatachRoutes() throws PragmatachException { 051 readRoutes(); 052 } 053 054 /** 055 * get all known routes for all HTTP methods 056 */ 057 public List<PragmatachRoute> getAllRoutes() { 058 final List<PragmatachRoute> ret = new ArrayList<PragmatachRoute>(); 059 ret.addAll(GETRoutes); 060 ret.addAll(POSTRoutes); 061 return ret; 062 } 063 064 /** 065 * get all GET routes 066 */ 067 public List<PragmatachRoute> getGETRoutes() { 068 return GETRoutes; 069 } 070 071 /** 072 * get all POST routes 073 */ 074 public List<PragmatachRoute> getPOSTRoutes() { 075 return POSTRoutes; 076 } 077 078 /** 079 * read the routes 080 */ 081 private void readRoutes() throws PragmatachException { 082 try { 083 /* 084 * get the routes 085 */ 086 final Set<Method> routerMethods = ControllerClasses.getRouterMethods(); 087 if (null != routerMethods) { 088 for (final Method method : routerMethods) { 089 final Route route = method.getAnnotation(Route.class); 090 final Route.HttpMethod httpMethod = route.method(); 091 if (httpMethod == com.khubla.pragmatach.framework.annotation.Route.HttpMethod.get) { 092 GETRoutes.add(new PragmatachRoute(method)); 093 } else { 094 POSTRoutes.add(new PragmatachRoute(method)); 095 } 096 } 097 /* 098 * sort the routes 099 */ 100 Collections.sort(GETRoutes); 101 Collections.sort(POSTRoutes); 102 } 103 } catch (final Exception e) { 104 throw new PragmatachException("Exception in readRoutes", e); 105 } 106 } 107 }