public void add_rule_raiz_2x_fica_rules_count_igual_a_1()
 {
     var c = new Contracts();
     c.AddRule("/", new RootHandler());
     c.AddRule("/", new RootHandler());
     Assert.AreEqual(c.Testes_GetRulesCount(), 1);
 }
 public void add_rules_varias_especiais_fica_rules_count_igual_a_5()
 {
     var c = new Contracts();
     c.AddRule("", new RootHandler()); // regra vazia sera ignorada
     c.AddRule(" ", new RootHandler()); // regras nao vazias serao adicionadas
     c.AddRule("/", new RootHandler());
     c.AddRule("/ ", new RootHandler());
     c.AddRule(" / ", new RootHandler());
     c.AddRule(" a ", new RootHandler());
     c.AddRule("", new RootHandler()); // regra vazia sera ignorada
     c.AddRule(" ", new RootHandler()); // regras duplicadas serao ignoradas
     c.AddRule("/", new RootHandler());
     c.AddRule("/ ", new RootHandler());
     c.AddRule(" / ", new RootHandler());
     c.AddRule(" a ", new RootHandler());
     Assert.AreEqual(c.Testes_GetRulesCount(), 5);
 }
        //private Contracts contracts;

        #region 3 Construtores de Router - nao utilizados

        //public Router()
        //{
        //    this.contracts = new Contracts();
        //}

        //public Router(Contracts contracts)
        //{
        //    this.contracts = contracts ?? new Contracts();
        //}

        //public Router(Contracts contracts, List<string> listTemplates, List<IHandler> listHandlers)
        //{
        //    this.contracts = contracts ?? new Contracts();
        //    if (((listTemplates != null) && (listHandlers != null)) && (listTemplates.Count == listHandlers.Count))
        //    {
        //        for (int index = 0; index < listTemplates.Count; index++)
        //        {
        //            this.contracts.AddRule(listTemplates[index], listHandlers[index]);
        //        }
        //    }
        //}

        #endregion

        #region 2 Metodos Publicos AddRule e AddRules - nao utilizados

        //public void AddRule(string s, IHandler h)
        //{
        //    contracts.AddRule(s,h);
        //}

        //public void AddRules(List<string> listTemplates, List<IHandler> listHandlers)
        //{
        //    if (((listTemplates != null) && (listHandlers != null)) && (listTemplates.Count == listHandlers.Count))
        //    {
        //        for (int index = 0; index < listTemplates.Count; index++)
        //        {
        //            contracts.AddRule(listTemplates[index], listHandlers[index]);
        //        }
        //    }
        //}

        #endregion

        #region Metodo Publico MatchAndExecute

        //public HandlerAnswer MatchAndExecute(string uriPedido)
        static public HandlerAnswer MatchAndExecute(Contracts contracts, string uriPedido)
        {
            IHandler handlerToExecute;
            if(contracts == null)
            {
                //throw new HandlerException("Lista de Templates nula, não há template correspondente ao endereço indicado: " + uriPedido);
                return (new NullsHandler(uriPedido,false)).Handle();
            }
            else
            {
                Dictionary<string, string> paramsVarsReturned = contracts.ResolveUri(uriPedido, out handlerToExecute);
                if (handlerToExecute == null)
                {
                    //throw new HandlerException("Handler nulo, não há template correspondente ao endereço indicado: " + uriPedido);
                    handlerToExecute = new NullsHandler(uriPedido,true);
                }
                return handlerToExecute.Handle(paramsVarsReturned);
            }
        }
Beispiel #4
0
        public void isvariable_ctx_com_chavetas_fica_true()
        {
            var c = new Contracts();

            Assert.True(c.Testes_IsVariable("{ctx}"));
        }
 public void resolve_entre_regras_ctx_e_assemblyName_e_uris_ok_ficam_handlers_esperados_iguais_ao_retornados_e_ctx_ola_assemblyName_adeus()
 {
     var c = new Contracts();
     IHandler hroot = new RootHandler();
     IHandler hcontext = new ContextNameHandler();
     IHandler hnamespace = new NamespacePrefixContextHandler();
     IHandler hassembly = new AssemblyNameContextHandler();
     c.AddRule("/", hroot);
     c.AddRule("/ ", hnamespace); // exemplo de um terceiro handler, apenas para efeitos de testes
     c.AddRule("/{ctx}", hcontext); // colocar o esperado em ultimo na lista de regrashandlers
     IHandler hres, hres2;
     var d = c.ResolveUri("/ola", out hres);
     Assert.NotNull(hres);
     Assert.AreEqual(hcontext, hres);
     Assert.AreEqual("ctx", d.First().Key);
     Assert.AreEqual("ola", d.First().Value);
     c.AddRule("/{ctx}/as/{assemblyName}", hassembly); // colocar o esperado em ultimo na lista de regrashandlers
     var d2 = c.ResolveUri("/ola/as/adeus", out hres2);
     Assert.NotNull(hres2);
     Assert.AreEqual(hassembly, hres2);
     Assert.AreEqual("ctx", d2.First().Key);
     Assert.AreEqual("ola", d2.First().Value);
     Assert.AreEqual("assemblyName", d2.Last().Key);
     Assert.AreEqual("adeus", d2.Last().Value);
 }
 public void add_rule_vazia_fica_rules_count_igual_a_0()
 {
     var c = new Contracts();
     c.AddRule("", new RootHandler());
     Assert.AreEqual(c.Testes_GetRulesCount(), 0);
 }
 public void resolve_entre_regra_ctx_e_uri_ola_ambos_ok_fica_handler_esperado_igual_ao_retornado()
 {
     var c = new Contracts();
     IHandler h = new NamespacePrefixContextHandler();
     c.AddRule("/{ctx}", h);
     IHandler hres;
     var d = c.ResolveUri("/ola", out hres);
     Assert.AreEqual(h, hres);
 }
 public void resolve_entre_regra_ctx_e_uri_ola_com_subdir_a_ambos_com_barra_antes_fica_handler_esperado_diferente_do_retornado_nulo()
 {
     var c = new Contracts();
     IHandler h = new NamespacePrefixContextHandler();
     c.AddRule("/{ctx}", h);
     IHandler hres;
     var d = c.ResolveUri("/ola/a", out hres);
     Assert.Null(hres);
     Assert.AreNotEqual(h, hres);
 }
 public void isvariable_vazia_fica_false()
 {
     var c = new Contracts();
     Assert.False(c.Testes_IsVariable(""));
 }
 public void match_entre_regra_ctx_e_uri_ola_ambos_ok_fica_handler_nao_nulo()
 {
     var c = new Contracts();
     IHandler h = new NamespacePrefixContextHandler();
     c.AddRule("/{ctx}", h);
     IHandler hres;
     List<string> sres;
     c.Testes_Match("/ola", out sres, out hres);
     Assert.NotNull(hres);
 }
 public void isconstant_ns_com_doispontos_no_inicio_e_fim_fica_true()
 {
     var c = new Contracts();
     Assert.True(c.Testes_IsConstant(":ns:"));
 }
 public void isvariable_ctx_sem_chaveta_direita_final_fica_false()
 {
     var c = new Contracts();
     Assert.False(c.Testes_IsVariable("{ctx"));
 }
Beispiel #13
0
        public void isvariable_ctx_sem_chaveta_esquerda_inicial_fica_false()
        {
            var c = new Contracts();

            Assert.False(c.Testes_IsVariable("ctx}"));
        }
 public void isconstant_vazia_fica_false()
 {
     var c = new Contracts();
     Assert.False(c.Testes_IsConstant(""));
 }
 public void isconstant_ns_sem_doispontos_nem_no_inicio_nem_no_fim_fica_true()
 {
     var c = new Contracts();
     //Assert.False(c.Testes_IsConstant("ns"));
     Assert.True(c.Testes_IsConstant("ns"));
 }
 public void isconstant_ns_sem_doispontos_esquerdo_inicial_fica_true()
 {
     var c = new Contracts();
     //Assert.False(c.Testes_IsConstant("ns:"));
     Assert.True(c.Testes_IsConstant("ns:"));
 }
 public void isconstant_ns_sem_doispontos_direito_final_fica_true()
 {
     var c = new Contracts();
     //Assert.False(c.Testes_IsConstant(":ns"));
     Assert.True(c.Testes_IsConstant(":ns"));
 }
 public void isvariable_ctx_com_chavetas_fica_true()
 {
     var c = new Contracts();
     Assert.True(c.Testes_IsVariable("{ctx}"));
 }
Beispiel #19
0
        public void isvariable_ctx_sem_chaveta_direita_final_fica_false()
        {
            var c = new Contracts();

            Assert.False(c.Testes_IsVariable("{ctx"));
        }
 public void isvariable_ctx_sem_chaveta_esquerda_inicial_fica_false()
 {
     var c = new Contracts();
     Assert.False(c.Testes_IsVariable("ctx}"));
 }
        static void Main(string[] args)
        {
            var contracts = new Contracts();
            contracts.AddRule("/", new RootHandler());
            contracts.AddRule("/{ctx}", new ContextNameHandler());
            contracts.AddRule("/{ctx}/as", new AssembliesContextHandler());
            contracts.AddRule("/{ctx}/ns", new NamespacesContextHandler());
            contracts.AddRule("/{ctx}/as/{assemblyName}", new AssemblyNameContextHandler());
            contracts.AddRule("/{ctx}/ns/{namespacePrefix}", new NamespacePrefixContextHandler());
            contracts.AddRule("/{ctx}/ns/{namespace}/{shortName}", new TypeShortNameNamespaceContextHandler());
            contracts.AddRule("/{ctx}/ns/{namespace}/{shortName}/m/{methodName}", new MethodNameTypeNamespaceContextHandler());
            contracts.AddRule("/{ctx}/ns/{namespace}/{shortName}/c", new ConstructsTypeNamespaceContextHandler());
            contracts.AddRule("/{ctx}/ns/{namespace}/{shortName}/f/{fieldName}", new FieldTypeNamespaceContextHandler());
            contracts.AddRule("/{ctx}/ns/{namespace}/{shortName}/p/{propName}", new PropTypeNamespaceContextHandler());
            contracts.AddRule("/{ctx}/ns/{namespace}/{shortName}/e/{eventName}", new EventTypeNamespaceContextHandler());

            //var statusCodesHTTP = new Dictionary<int, HttpStatusCode>();
            //statusCodesHTTP.Add(400,HttpStatusCode.BadRequest);
            //statusCodesHTTP.Add(501,HttpStatusCode.NotImplemented);
            //statusCodesHTTP.Add(200,HttpStatusCode.OK);
            //HttpStatusCode statusCodeHTTP;

            if (!HttpListener.IsSupported)
            {
                Console.WriteLine("Windows XP SP2 or Server 2003 is required to use the HttpListener class.");
            }
            else
            {
                var listener = new HttpListener();
                listener.Prefixes.Add("http://localhost:8080/"); // tem de terminar com barra, de acordo com MSDN de HttpListener Class
                //listener.Prefixes.Add("http://127.0.0.1:8080/"); // tem de terminar com barra, de acordo com MSDN de HttpListener Class
                ////listener.Prefixes.Add("http://::1:8080/"); // tem de terminar com barra, de acordo com MSDN de HttpListener Class
                //listener.Prefixes.Add("http://*:8080/"); // terminar com barra, de acordo com MSDN de HttpListener Class, e com port, host pode ser *
                listener.Start();

                bool fimDeServico = false;

                string htmlDeSaida;
                byte[] buffer;

                while (!fimDeServico)
                {
                    var listenerContext = listener.GetContext(); // context.response tem stream
                    var request = listenerContext.Request;
                    var response = listenerContext.Response;
                    var output = response.OutputStream;
                    if (request.RawUrl == "/-") // SAIDA
                    {
                        htmlDeSaida =
                            Views.processTagHTML2string(
                                Views.HTML(Views.HEAD(Views.TITLE("Encerramento da Aplicação Servidora")),
                                           Views.BODY(Views.H1("Encerramento da Aplicação Servidora ( /- ):"),
                                                      Views.H3(
                                                          "Obrigado por utilizar esta Aplicação Servidora!"),
                                                      Views.P(
                                                          "Para possibilitar o atendimento de novos pedidos,"),
                                                      Views.P(
                                                          "será necessário executá-la novamente, a partir do servidor,"),
                                                      Views.P("e abrir um browser para"),
                                                      Views.TABLE(Views.TR(Views.TD(Views.A(true, "/",
                                                                                            Views.Text2TagHTML(
                                                                                                "o endereço deste servidor.")))))
                                                    )));

                        buffer = System.Text.Encoding.UTF8.GetBytes(htmlDeSaida);
                        // HTTP status 200 = OK (request succeeded and that the requested information is in the response)
                        response.StatusCode = (int)HttpStatusCode.OK;

                        response.ContentType = "text/html";
                        response.ContentLength64 = buffer.Length;
                        output.Write(buffer, 0, buffer.Length);
                        response.Close();

                        fimDeServico = true; // alterar variavel, para se fazer o fim do servico, quebrando o ciclo while
                    }
                    else // NAO SAIR, CONTINUA O ATENDIMENTO DE PEDIDOS NO CICLO WHILE
                    {
                        HandlerAnswer respostaHTMLdeSaida;
                        try
                        {
                            respostaHTMLdeSaida = Router.MatchAndExecute(contracts, request.RawUrl);
                            htmlDeSaida =
                                Views.processTagHTML2string(
                                    Views.A(true, "/-", Views.Text2TagHTML("PARA ENCERRAR ESTA APLICAÇÃO SERVIDORA, CLIQUE AQUI = /-")),
                                    respostaHTMLdeSaida.answerContent);
                        }
                        catch (Exception exception) // EXCEPCAO
                        {
                            var innerTagHTML = new List<TagHTML>();
                            if (exception.Data != null)
                            {
                                innerTagHTML.Add(Views.P("------ Detalhes Extra ------"));
                                var innerTableHTML = new List<TagHTML>();
                                innerTableHTML.Add(Views.TR(Views.TD(Views.Text2TagHTML("Key")),
                                                            Views.TD(Views.Text2TagHTML("Value"))));
                                foreach (DictionaryEntry de in exception.Data)
                                {
                                    innerTableHTML.Add(Views.TR(Views.TD(Views.Text2TagHTML((string) de.Key)),
                                                                Views.TD(Views.Text2TagHTML((string) de.Value))));
                                }
                                innerTagHTML.Add(Views.TABLE(innerTableHTML.ToArray()));
                            }
                            innerTagHTML.Reverse();
                            innerTagHTML.Add(Views.H3(exception.Message));
                            innerTagHTML.Add(Views.H1("Excepção Ocorrida:"));
                            innerTagHTML.Add(Views.A(true, "/-", Views.Text2TagHTML("PARA ENCERRAR ESTA APLICAÇÃO SERVIDORA, CLIQUE AQUI = /-")));
                            innerTagHTML.Reverse();
                            // HTTP status 500 = InternalServerError (generic error has occurred on the server)
                            respostaHTMLdeSaida = new HandlerAnswer()
                                                      {
                                                          answerOk = false,
                                                          answerCode = HttpStatusCode.InternalServerError,
                                                          answerContent =
                                                              Views.HTML(Views.HEAD(Views.TITLE("Excepção Ocorrida")),
                                                                         Views.BODY(innerTagHTML.ToArray()))
                                                      };
                            htmlDeSaida = Views.processTagHTML2string(respostaHTMLdeSaida.answerContent);

                            //throw exception; // poder-se-ia fazer um ficheiro de log, com os dados da excepcao
                        }

                        buffer = System.Text.Encoding.UTF8.GetBytes(htmlDeSaida);

                        //if (!respostaHTMLdeSaida.answerOk)
                        //{
                        //    response.StatusCode = (int) HttpStatusCode.InternalServerError;
                        //}
                        //else
                        //{
                        response.StatusCode = (int)respostaHTMLdeSaida.answerCode;
                        //}

                        response.ContentType = "text/html";
                        response.ContentLength64 = buffer.Length;
                        output.Write(buffer, 0, buffer.Length);
                        response.Close();
                    }
                }
                listener.Stop();
                listener.Close();
            }
        }