From 1f8f55cb30cc2166d5cb26a0caef58f0c616c980 Mon Sep 17 00:00:00 2001 From: Felipe Garcia Date: Sat, 28 May 2022 14:15:08 -0300 Subject: [PATCH] update --- .travis.yml | 5 +- README.md | 11 +- pom.xml | 30 +- .../java/br/com/app/AuthenticationFilter.java | 74 +++ src/main/java/br/com/app/Choice.java | 46 ++ src/main/java/br/com/app/EntryPoint.java | 17 + src/main/java/br/com/app/PollsService.java | 599 ++++++++++++++++++ src/main/java/br/com/app/Question.java | 54 ++ src/main/java/br/com/app/QuestionNew.java | 28 + src/main/java/br/com/app/Secured.java | 9 + src/main/java/br/com/app/Token.java | 26 + .../java/br/com/app/client/ClientGet.java | 100 +++ .../java/br/com/app/client/ClientPost.java | 151 +++++ src/main/java/br/com/app/ws/ConnTestWS.java | 92 +++ src/main/java/br/com/app/ws/MonitorAppWS.java | 38 ++ src/main/java/br/com/app/ws/ParametroJWS.java | 100 +++ src/main/java/br/com/app/ws/ParametroWS.java | 61 ++ src/main/java/br/com/app/ws/SisClienteWS.java | 121 ++++ .../java/br/com/app/ws/UteisProjetoWS.java | 23 + src/main/java/br/com/app/ws/WS.java | 546 ++++++++++++++++ .../java/br/com/utilitarios/AppVariables.java | 52 ++ .../java/br/com/utilitarios/UteisModulos.java | 40 ++ .../java/br/com/utilitarios/UteisProjeto.java | 493 ++++++++++++++ 23 files changed, 2705 insertions(+), 11 deletions(-) create mode 100644 src/main/java/br/com/app/AuthenticationFilter.java create mode 100644 src/main/java/br/com/app/Choice.java create mode 100644 src/main/java/br/com/app/EntryPoint.java create mode 100644 src/main/java/br/com/app/PollsService.java create mode 100644 src/main/java/br/com/app/Question.java create mode 100644 src/main/java/br/com/app/QuestionNew.java create mode 100644 src/main/java/br/com/app/Secured.java create mode 100644 src/main/java/br/com/app/Token.java create mode 100644 src/main/java/br/com/app/client/ClientGet.java create mode 100644 src/main/java/br/com/app/client/ClientPost.java create mode 100644 src/main/java/br/com/app/ws/ConnTestWS.java create mode 100644 src/main/java/br/com/app/ws/MonitorAppWS.java create mode 100644 src/main/java/br/com/app/ws/ParametroJWS.java create mode 100644 src/main/java/br/com/app/ws/ParametroWS.java create mode 100644 src/main/java/br/com/app/ws/SisClienteWS.java create mode 100644 src/main/java/br/com/app/ws/UteisProjetoWS.java create mode 100644 src/main/java/br/com/app/ws/WS.java create mode 100644 src/main/java/br/com/utilitarios/AppVariables.java create mode 100644 src/main/java/br/com/utilitarios/UteisModulos.java create mode 100644 src/main/java/br/com/utilitarios/UteisProjeto.java diff --git a/.travis.yml b/.travis.yml index 7d60bc6..a1b78ae 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,5 +1,3 @@ -global: CODECOV_TOKEN="2215f466-5f0d-417f-b4f3-ea60ccdb863e" - language: java jdk: - oraclejdk8 @@ -7,4 +5,5 @@ sudo: false script: mvn clean verify script: "mvn cobertura:cobertura" after_success: -- bash <(curl -s https://codecov.io/bash) -t "2215f466-5f0d-417f-b4f3-ea60ccdb863e" +- bash <(curl -s https://codecov.io/bash) + diff --git a/README.md b/README.md index 6999122..4be6834 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,9 @@ -## Continuous Integration|Coverage|Analysis +## Coverage [![Code Climate](https://codeclimate.com/github/llyppi/polls.png)](https://codeclimate.com/github/llyppi/polls) -[![codecov](https://codecov.io/gh/llyppi/polls/branch/master/graph/badge.svg)](https://codecov.io/gh/llyppi/polls) +
[![codecov](https://codecov.io/gh/llyppi/polls/branch/master/graph/badge.svg)](https://codecov.io/gh/llyppi/polls) +## Analysis [![Codacy Badge](https://api.codacy.com/project/badge/Grade/7c7334e6f740470fbe6920c4c974ff0b)](https://www.codacy.com/app/llyppi/polls?utm_source=github.com&utm_medium=referral&utm_content=llyppi/polls&utm_campaign=Badge_Grade) +## Continuous Integration [![Build Status](https://travis-ci.org/llyppi/polls.svg?branch=master)](https://travis-ci.org/llyppi/polls) ## Synopsis @@ -11,6 +13,9 @@ ## Installation Build project,Netbeas,Eclipse +## Teste +https://multware.com/apipolls + [ClientGet](../master/src/main/java/com/app/client/ClientGet.java)
[ClientPost](../master/src/main/java/com/app/client/ClientPost.java) @@ -25,7 +30,7 @@ * Votar na Questions * POST http://localhost:8080/apipolls/polls/questions/1/choices/1 Requer Header Authorization token * Gerar Token -* POST http://localhost:8080/apipolls/polls/tokens?username=usuario&password=senha +* POST http://localhost:8084/apipolls/polls/tokens?username=usuario&password=senha ## Java diff --git a/pom.xml b/pom.xml index bc19ca5..f86c907 100644 --- a/pom.xml +++ b/pom.xml @@ -1,12 +1,12 @@ - + + 4.0.0 - com.app + + br.com.app apiPolls war 1.0-SNAPSHOT apiPolls - http://maven.apache.org @@ -175,7 +175,27 @@ genson 0.99 - + + uteisJava + uteisJava + 1.0 + + + org.apache.commons + commons-email + 1.4 + javadoc + + + org.apache.axis + axis + 1.4 + + + org.apache.axis + axis-jaxrpc + 1.4 + diff --git a/src/main/java/br/com/app/AuthenticationFilter.java b/src/main/java/br/com/app/AuthenticationFilter.java new file mode 100644 index 0000000..7bd1a2b --- /dev/null +++ b/src/main/java/br/com/app/AuthenticationFilter.java @@ -0,0 +1,74 @@ +package br.com.app; + +//import com.sun.jersey.core.util.Priority; +//import java.io.IOException; +//import java.util.Calendar; +//import java.util.Map; +//import javax.ws.rs.NotAuthorizedException; +//import javax.ws.rs.Priorities; +//import javax.ws.rs.container.ContainerRequestContext; +//import javax.ws.rs.container.ContainerRequestFilter; +//import javax.ws.rs.core.HttpHeaders; +//import javax.ws.rs.core.Response; +//import javax.ws.rs.ext.Provider; + +/** + * Classe sempre autentifica metodos que possui @Secured + * + * @author Felipe L. Garcia + */ +//@Secured +//@Provider +//@Priority(Priorities.AUTHENTICATION) +public class AuthenticationFilter {//implements ContainerRequestFilter { + +// @Override +// public void filter(ContainerRequestContext requestContext) throws IOException { +// +// // Get the HTTP Authorization header from the request +// String authorizationHeader = +// requestContext.getHeaderString(HttpHeaders.AUTHORIZATION); +// +// // Check if the HTTP Authorization header is present and formatted correctly +// if (authorizationHeader == null +// || !authorizationHeader.startsWith("token ")) { +// throw new NotAuthorizedException("Authorization header must be provided"); +// } +// +// // Extract the token from the HTTP Authorization header +// String token = authorizationHeader.substring("token ".length()).trim(); +// +// try { +// +// validateToken(token); +// +// } catch (Exception e) { +// requestContext.abortWith( +// Response.status(Response.Status.UNAUTHORIZED).build()); +// } +// } +// +// /** Validar timeCreate+timeExp > NOW*/ +// private void validateToken(String token) throws Exception { +// Map listToken = PollsService.getListToken(); +// +// for (Map.Entry entry : listToken.entrySet()) { +// Token tok = entry.getKey(); +// Long timeCreate = entry.getValue(); +// //BUSCAR TOKEN +// if(!tok.getAccess_token().equals(token)){ +// continue; +// } +// +// Calendar calendar = Calendar.getInstance(); +// calendar.setTimeInMillis(timeCreate); +// //DIMINUIR TEMPO DE EXPIRAR TOKEN +// calendar.add(Calendar.MILLISECOND, (int) tok.getExpires_in()); +// //DENTRO DO PRAZO +// if(calendar.getTimeInMillis() > System.currentTimeMillis()){ +// return ; +// } +// } +// throw new Exception("Token inválido"); +// } +} diff --git a/src/main/java/br/com/app/Choice.java b/src/main/java/br/com/app/Choice.java new file mode 100644 index 0000000..d9c0e2b --- /dev/null +++ b/src/main/java/br/com/app/Choice.java @@ -0,0 +1,46 @@ +package br.com.app; +/** + * + * @author Felipe L. Garcia + */ +public class Choice { + + private int choice_id; + private String choice; + private String url; + private int votes; + + public int getChoice_id() { + return choice_id; + } + + public void setChoice_id(int choice_id) { + this.choice_id = choice_id; + } + + public String getChoice() { + return choice; + } + + public void setChoice(String choice) { + this.choice = choice; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public int getVotes() { + return votes; + } + + public void setVotes(int votes) { + this.votes = votes; + } + + +} diff --git a/src/main/java/br/com/app/EntryPoint.java b/src/main/java/br/com/app/EntryPoint.java new file mode 100644 index 0000000..d493802 --- /dev/null +++ b/src/main/java/br/com/app/EntryPoint.java @@ -0,0 +1,17 @@ +package br.com.app; +/** + * + * @author Felipe L. Garcia + */ +public class EntryPoint { + private String url; + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + +} diff --git a/src/main/java/br/com/app/PollsService.java b/src/main/java/br/com/app/PollsService.java new file mode 100644 index 0000000..0631704 --- /dev/null +++ b/src/main/java/br/com/app/PollsService.java @@ -0,0 +1,599 @@ +package br.com.app; + +import java.lang.reflect.Method; +import java.math.BigInteger; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.ws.rs.Consumes; +import javax.ws.rs.DefaultValue; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.ResponseBuilder; +import javax.ws.rs.core.Response.Status; +import org.json.JSONObject; + +/** + * + * @author Felipe L. Garcia + */ +@Path("/polls") +public class PollsService { + + private static Map listToken; + private static List listQuestions; + + + public static Map getListToken() { + return listToken; + } + + /** + * ROOT + * Listar Entry Point + */ + @GET + @Produces(MediaType.APPLICATION_JSON) + public Response getPoints() { + System.out.println("GET /root"); + + List listEntry = new ArrayList<>(); + + Method[] listMethod = this.getClass().getDeclaredMethods(); + for (Method method : listMethod) { + Path[] paths = method.getAnnotationsByType(Path.class); + if(paths==null || paths.length==0){ + continue; + } + EntryPoint entry = new EntryPoint(); + entry.setUrl(paths[0].value()); + listEntry.add(entry); + } + String json = getJson(listEntry.toArray(new EntryPoint[listEntry.size()])); + + return Response.status(Status.OK).entity(json).build();//200 + } + + /** + * Vizualizar detalhes da Question + * @param token Requer Header Authorization token .... + */ +// @Secured + @GET + @Path("/questions/{question_id}") + @Produces(MediaType.APPLICATION_JSON) + public Response getQuestion(@PathParam("question_id") int id + ,@HeaderParam("Authorization") String token) { + + System.out.println("GET /questions/" + id); + + if(!validate(token)){ + return Response.status(Status.UNAUTHORIZED).build();//401 + } + + Question question = buscarQuestion(id); + if (question != null) { + String json = getJson(question); + + ResponseBuilder builder = Response.status(Status.OK);//200 + Response resp = builder.entity(json).build(); + + return resp; + } + return Response.noContent().build();//RETORNAR VAZIO 204 + } + + /** + * Listar Questions por página + * @param token Requer Header Authorization token .... + */ + @GET + @Path("/questions") + @Produces(MediaType.APPLICATION_JSON) + public Response getQuestionPage(@DefaultValue("0") + @QueryParam("page") int page + ,@HeaderParam("Authorization") String token) { + + System.out.println("GET /questions" + page); + + if (!validate(token)) { + return Response.status(Status.UNAUTHORIZED).build();//401 + } + + if (listQuestions == null || listQuestions.isEmpty()) { + System.out.println("listQuestions null"); + return Response.noContent().build();//RETORNAR VAZIO 204 + } + System.out.println("listQuestions "+listQuestions.size()); + + if (page < 0) { + System.out.println("page invalida"); + return Response.noContent().build();//RETORNAR VAZIO 204 + } + + if (page == 0) {//LISTAR TODOS + Question[] list = listQuestions + .toArray(new Question[listQuestions.size()]); + + String json = getJson(list); + + ResponseBuilder builder = Response.status(Status.OK);//200 + builder.header("Link",";rel=\"next\""); + + Response resp = builder.entity(json).build(); +// resp.getHeaders().add("Link", +// ";rel=\"next\""); +// resp.getMetadata().add("Link", +// ";rel=\"next\""); + + return resp; + } + + Question[] list = new Question[page]; + int pg = 1; + //MOTAR LISTA + for (Question quest : listQuestions) { + list[pg-1]=quest; + if(pg==page){ + break; + } + pg++; + } + ResponseBuilder builder = Response.status(Status.OK);//200 + builder.header("Link", ";rel=\"next\""); + + String json = getJson(list); + + Response resp = builder.entity(json).build(); + return resp; + } + + /** + * Votar na Choice + * @param token Requer Header Authorization token .... + */ +// @Secured + @POST + @Path("/questions/{question_id}/choices/{choice_id}") + @Consumes(MediaType.APPLICATION_JSON) + public Response postChoices(@PathParam("question_id") int idQuest, + @PathParam("choice_id") int idChoice + ,@HeaderParam("Authorization") String token) { + + System.out.println("POST /questions/" + idQuest + + "/choices/" + idChoice); + + if (!validate(token)) { + return Response.status(Status.UNAUTHORIZED).build();//401 + } + + Question quest = buscarQuestion(idQuest); + if (quest == null) { + return Response.serverError().build();//RETORNAR ERRO 500 + } + + Choice[] listChoice = quest.getChoices(); + Choice choice = buscarChoice(idChoice, listChoice); + if (choice == null) { + return Response.serverError().build();//RETORNAR ERRO 500 + } + choice.setVotes(choice.getVotes() + 1);//SOMAR VOTOS + + ResponseBuilder builder = Response.status(Status.CREATED);//201 + builder.header("Location", quest.getUrl()); + + Response resp = builder.build(); + return resp; + } + + /** + * Criar nova Question + * @param token Requer Header Authorization token .... + */ +// @Secured + @POST + @Path("/questions") + @Consumes(MediaType.APPLICATION_JSON) + public Response postQuestion(QuestionNew questNew + ,@HeaderParam("Authorization") String token) { + + System.out.println("POST /questions/" + getJson(questNew)); + + if (!validate(token)) { + return Response.status(Status.UNAUTHORIZED).build();//401 + } + + if (listQuestions == null) { + listQuestions = new ArrayList<>(); + } + //SE NAO CONTEM RESPOSTAS + if (questNew.getChoices() == null || questNew.getChoices().length==0) { + return Response.serverError().build();//RETORNAR ERRO 500 + } + Question question = new Question(); + question.setQuestion_id(listQuestions.size() + 1); + question.setQuestion(questNew.getQuestion()); + question.setPublished_at(getDateISO(new Date()));//DATA DE CRIACAO + + String urlQuest = "/question/" + (listQuestions.size() + 1); + question.setUrl(urlQuest);//URL REQUEST + + //MONTAR AS RESPOSTAS + String[] array = questNew.getChoices(); + + //SE NAO CONTEM RESPOSTAS + if (array == null || array.length == 0) { + return Response.serverError().build();//RETORNAR ERRO 500 + } + + Choice[] listChoice = new Choice[array.length]; + + int idx = 1; + for (String ch : array) { + Choice choice = new Choice(); + choice.setChoice_id(idx); + choice.setChoice(ch); + choice.setUrl(urlQuest + "/choices/" + idx); + + listChoice[idx - 1] = choice; + idx++; + } + question.setChoices(listChoice); + + listQuestions.add(question); + + String json = getJson(question); + + ResponseBuilder builder = Response.status(Status.CREATED);//201 + builder.header("Location", urlQuest); + + Response resp = builder.entity(json).build(); + return resp; + } + + /** + * Criar Token com usuario e senha + */ + @POST + @Path("/tokens") + @Produces(MediaType.APPLICATION_JSON) + public Response postToken(@QueryParam("username") String username, + @QueryParam("password") String password) { + + System.out.println("POST /tokens/" + username + + "/" + password); + + if (listToken == null) { + listToken = new HashMap<>(); + } + //VALIDACÃO ILUSTRATIVA + if (!validate(username, password)) { + return Response.status(Response.Status.UNAUTHORIZED).build();//401 + } + + Token token = createToken(username); + listToken.put(token, System.currentTimeMillis()); + + // Return the token on the response + return Response.status(Status.CREATED).entity(token).build();//Status 201 + + } + + /** + * Buscar Question por ID + */ + private Question buscarQuestion(int id) { + if (listQuestions == null) { + return null; + } + for (Question quest : listQuestions) { + if (quest.getQuestion_id() == id) { + return quest; + } + } + return null; + } + + /** + * Buscar Choice por ID + */ + private Choice buscarChoice(int id, Choice[] list) { + if (list == null) { + return null; + } + for (Choice choice : list) { + if (choice.getChoice_id() == id) { + return choice; + } + } + return null; + } + + /** + * Converter Date ISO + */ + public static String getDateISO(Date date) { + ZonedDateTime zone = ZonedDateTime.of( + LocalDateTime.ofInstant(date.toInstant(), + ZoneId.systemDefault()), + ZoneId.systemDefault()); + return zone.format(DateTimeFormatter.ISO_INSTANT); + } + /** + * Converter Object no formato Json + */ + public static String getJson(Object[] list) { + String json = ""; + for (Object question : list) { + String js = getJson(question); + json += "," + js; + } + json = json.replaceFirst(",", ""); + json = "[" + json + "]"; + + return json; + } + /** + * Converter Object no formato Json + */ + public static String getJson(Object obj) { + JSONObject json = new JSONObject(obj); + + String str = json.toString(); +// str = str.replaceAll("\\\"", "\""); + + return str; + } + /** + * Converter Object no formato Json + */ + public static String getJson2(Object obj) { + Method[] metodosLista = obj.getClass().getDeclaredMethods(); + + String lista = ""; + for (Method method : metodosLista) { + if (method.getReturnType().equals(Void.TYPE)) { + continue; + } + if (method.getName().equalsIgnoreCase("tostring")) { + continue; + } + String value = ""; + try { + Object invoke = method.invoke(obj); + + if(String[].class.isInstance(invoke)){ + String join = "[\""+String.join("\",\"",(String[]) invoke)+ "\"]"; + invoke = join; + } + if(Date.class.isInstance(invoke)){ + Date date = (Date) invoke; + ZonedDateTime zone = ZonedDateTime.of( + LocalDateTime.ofInstant(date.toInstant() + ,ZoneId.systemDefault()) + , ZoneId.systemDefault()); + invoke = zone.format(DateTimeFormatter.ISO_INSTANT); + } + + value = String.valueOf(invoke); + + } catch (Exception ex) { + } + String atributo = method.getName(); + atributo = atributo.replaceAll("^set|^get|^is", ""); + + lista += ",\"" + atributo.toLowerCase() + "\": \"" + value + "\""; + } + return lista.replaceFirst(",", ""); + } + + /** + * Criar Token com 1 dia de validade + */ + private Token createToken(String username) { + Token token = new Token(); + token.setExpires_in(86400);//1 DIA + + //TOKEN ILUSTRATIVO,HEX DA STRING + String tk = String.format("%040x", new BigInteger(1, username.getBytes())); + token.setAccess_token(tk); + + return token; + } + + /** + * Validar Usuário e Senha + */ + private boolean validate(String username, String password) { + return true;//INLUSTRATIVO + } + /** + * Validar timeCreate+timeExp > NOW + */ + private boolean validate(String token) { + if (token == null || token.isEmpty()) { + return false; + } + + Map listToken = PollsService.getListToken(); + + if (listToken == null || listToken.isEmpty()) { + return false; + } + + for (Map.Entry entry : listToken.entrySet()) { + Token tok = entry.getKey(); + Long timeCreate = entry.getValue(); + + token = token.replace("token ", ""); + //BUSCAR TOKEN + if(!tok.getAccess_token().equals(token)){ + continue; + } + + Calendar calendar = Calendar.getInstance(); + calendar.setTimeInMillis(timeCreate); + //DIMINUIR TEMPO DE EXPIRAR TOKEN + calendar.add(Calendar.MILLISECOND, (int) tok.getExpires_in()); + //DENTRO DO PRAZO + if(calendar.getTimeInMillis() > System.currentTimeMillis()){ + return true; + } + } + return false; + } +// @GET +// @Produces(MediaType.APPLICATION_JSON) +// public Response showAll( @Context Application application, +// @Context HttpServletRequest request){ +// String basePath = request.getRequestURL().toString(); +// +// ObjectNode root = JsonNodeFactory.instance.objectNode(); +// ArrayNode resources = JsonNodeFactory.instance.arrayNode(); +// +// root.put( "resources", resources ); +// +// for ( Class aClass : application.getClasses() ) +// { +// if ( isAnnotatedResourceClass( aClass ) ) +// { +// AbstractResource resource = IntrospectionModeller.createResource( aClass ); +// ObjectNode resourceNode = JsonNodeFactory.instance.objectNode(); +// String uriPrefix = resource.getPath().getValue(); +// +// for ( AbstractSubResourceMethod srm : resource.getSubResourceMethods() ) +// { +// String uri = uriPrefix + "/" + srm.getPath().getValue(); +// addTo( resourceNode, uri, srm, joinUri(basePath, uri) ); +// } +// +// for ( AbstractResourceMethod srm : resource.getResourceMethods() ) +// { +// addTo( resourceNode, uriPrefix, srm, joinUri( basePath, uriPrefix ) ); +// } +// +// resources.add( resourceNode ); +// } +// +// } +// +// +// return Response.ok().entity( root ).build(); +// } +//// +// private void addTo( ObjectNode resourceNode, String uriPrefix, AbstractResourceMethod srm, String path ) +// { +// if ( resourceNode.get( uriPrefix ) == null ) +// { +// ObjectNode inner = JsonNodeFactory.instance.objectNode(); +// inner.put("path", path); +// inner.put("verbs", JsonNodeFactory.instance.arrayNode()); +// resourceNode.put( uriPrefix, inner ); +// } +// +// ((ArrayNode) resourceNode.get( uriPrefix ).get("verbs")).add( srm.getHttpMethod() ); +// } +// +// +// private boolean isAnnotatedResourceClass( Class rc ) +// { +// if ( rc.isAnnotationPresent( Path.class ) ) +// { +// return true; +// } +// +// for ( Class i : rc.getInterfaces() ) +// { +// if ( i.isAnnotationPresent( Path.class ) ) +// { +// return true; +// } +// } +// +// return false; +// } + + +// @POST +// @Path("/questions/{question}/{choices}") +// @Consumes(MediaType.APPLICATION_JSON) +// public Response postNewQuestion(@PathParam("question") String strQuestion, +// @PathParam("choices") String strChoices) { +// +// System.out.println("POST /questions/" + strQuestion +// + "/" + strChoices); +// +// if (listQuestions == null) { +// listQuestions = new ArrayList<>(); +// } +// //SE NAO CONTEM RESPOSTAS +// if (strChoices == null || strChoices.isEmpty()) { +// return Response.serverError().build();//RETORNAR ERRO +// } +// +// Question question = new Question(); +// question.setQuestion_id(listQuestions.size() + 1); +// question.setQuestion(strQuestion); +// question.setPublished_at(new Date());//DATA DE CRIACAO +// +// String urlQuest = "/question/" + listQuestions.size() + 1; +// question.setUrl(urlQuest);//URL REQUEST +// +// //MONTAR AS RESPOSTAS +// strChoices = strChoices.replaceAll("\\[|\\]|\\{|\\}", ""); +// String[] array = strChoices.split(","); +// +// //SE NAO CONTEM RESPOSTAS +// if (array == null || array.length == 0) { +// return Response.serverError().build();//RETORNAR ERRO +// } +// +// Choice[] listChoice = new Choice[array.length]; +// +// int idx = 1; +// for (String ch : array) { +// Choice choice = new Choice(); +// choice.setChoice_id(idx); +// choice.setChoice(ch); +// choice.setUrl(urlQuest + "/choices/" + idx); +// +// listChoice[idx - 1] = choice; +// idx++; +// } +// question.setChoices(listChoice); +// +// listQuestions.add(question); +// +// Response resp = Response.status(Status.CREATED).entity(question).build(); +//// resp.getHeaders().putSingle("Location",urlQuest); +// resp.getMetadata().putSingle("Location", urlQuest); +// +// return resp; +// } + + + @POST + @Path("/test") + @Consumes("application/json") + public Response test(Question quest) { + System.out.println("POST /post/" + quest); + + String result = "Product created : " + quest; + return Response.status(201).entity(result).build(); + + } +} diff --git a/src/main/java/br/com/app/Question.java b/src/main/java/br/com/app/Question.java new file mode 100644 index 0000000..34f06b2 --- /dev/null +++ b/src/main/java/br/com/app/Question.java @@ -0,0 +1,54 @@ +package br.com.app; +/** + * + * @author Felipe L. Garcia + */ +public class Question { + private int question_id; + private String question; + private String published_at; + private String url; + private Choice[] choices; + + public String getQuestion() { + return question; + } + + public void setQuestion(String question) { + this.question = question; + } + + public int getQuestion_id() { + return question_id; + } + + public void setQuestion_id(int question_id) { + this.question_id = question_id; + } + + public String getPublished_at() { + return published_at; + } + + public void setPublished_at(String published_at) { + this.published_at = published_at; + } + + public Choice[] getChoices() { + return choices; + } + + public void setChoices(Choice... choices) { + this.choices = choices; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + +} + diff --git a/src/main/java/br/com/app/QuestionNew.java b/src/main/java/br/com/app/QuestionNew.java new file mode 100644 index 0000000..757bb2a --- /dev/null +++ b/src/main/java/br/com/app/QuestionNew.java @@ -0,0 +1,28 @@ +package br.com.app; +/** + * + * @author Felipe L. Garcia + */ +public class QuestionNew { + private String question; + private String[] choices; + + + public String getQuestion() { + return question; + } + + public void setQuestion(String question) { + this.question = question; + } + + public String[] getChoices() { + return choices; + } + + public void setChoices(String[] choices) { + this.choices = choices; + } + +} + diff --git a/src/main/java/br/com/app/Secured.java b/src/main/java/br/com/app/Secured.java new file mode 100644 index 0000000..b52a23e --- /dev/null +++ b/src/main/java/br/com/app/Secured.java @@ -0,0 +1,9 @@ +package br.com.app; + +/** + * Classe representa Anotation,sera usada para filtrar Authentication + * @author Felipe L. Garcia + */ +public @interface Secured { + +} diff --git a/src/main/java/br/com/app/Token.java b/src/main/java/br/com/app/Token.java new file mode 100644 index 0000000..f9225f1 --- /dev/null +++ b/src/main/java/br/com/app/Token.java @@ -0,0 +1,26 @@ +package br.com.app; +/** + * + * @author Felipe L. Garcia + */ +public class Token { + private String access_token; + private long expires_in; + + public String getAccess_token() { + return access_token; + } + + public void setAccess_token(String access_token) { + this.access_token = access_token; + } + + public long getExpires_in() { + return expires_in; + } + + public void setExpires_in(long expires_in) { + this.expires_in = expires_in; + } + +} diff --git a/src/main/java/br/com/app/client/ClientGet.java b/src/main/java/br/com/app/client/ClientGet.java new file mode 100644 index 0000000..5c3a7f4 --- /dev/null +++ b/src/main/java/br/com/app/client/ClientGet.java @@ -0,0 +1,100 @@ +package br.com.app.client; + +import br.com.app.Token; +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; + +/** + * + * @author Felipe L. Garcia + */ +public class ClientGet { + private static String urlPolls = "http://localhost:8084/apipolls/polls"; + + public static void main(String[] args) { +// String output = getURL(); +// System.out.println(output); +// +// String output = getQuestion(1); +// System.out.println(output); +// + String output = getQuestionPage(0); + System.out.println(output); + } + + public static String getURL() { + + return polls(urlPolls, null,null); + } + + public static String getQuestion(int id) { + Token token = ClientPost.getToken("usuario", "senha"); + if (token == null) { + return null; + } + String url = urlPolls+"/questions/" + id; + + return polls(url, null,token.getAccess_token()); + } + + public static String getQuestionPage(int page) { + Token token = ClientPost.getToken("usuario", "senha"); + if (token == null) { + return null; + } + String url = urlPolls+"/questions"+(page>0 + ?"?page="+page + :""); + + return polls(url, null,token.getAccess_token()); + } + + private static String polls(String urlGet,String input,String token) { + System.out.println(urlGet); + // http://localhost:8080/RESTfulExample/json/product/get + try { + URL url = new URL(urlGet); + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + conn.setRequestMethod("GET"); + conn.setRequestProperty("Accept", "application/json"); + + //Authorization + if(token!=null && !token.trim().isEmpty()){ + conn.setRequestProperty("Authorization", "token "+token); + } + + if(input!=null && !input.trim().isEmpty()){ + OutputStream os = conn.getOutputStream(); + os.write(input.getBytes()); + os.flush(); + } + + if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { + throw new RuntimeException("Failed : HTTP error code : " + + conn.getResponseCode()); + } + + BufferedReader br = new BufferedReader(new InputStreamReader( + (conn.getInputStream()))); + + String output = ""; + String read; + while ((read = br.readLine()) != null) { + output += read; + } + conn.disconnect(); + + return output; + + } catch (Exception e) { + + System.out.println(e); + + } + return null; + } + +} diff --git a/src/main/java/br/com/app/client/ClientPost.java b/src/main/java/br/com/app/client/ClientPost.java new file mode 100644 index 0000000..d2b5b7b --- /dev/null +++ b/src/main/java/br/com/app/client/ClientPost.java @@ -0,0 +1,151 @@ +package br.com.app.client; + +import br.com.app.Token; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import org.json.JSONObject; + +/** + * + * @author Felipe L. Garcia + */ +public class ClientPost { + private static String urlPolls = "http://localhost:8084/apipolls/polls"; + + public static void main(String[] args) { + String output = postToken("usuario", "senha"); + System.out.println(output); + +// String output = postNewQuestion("Qual seu nome", "Felipe","João"); +// System.out.println(output); +// output = postNewQuestion("Qual sua idade", "18","19"); +// System.out.println(output); + +// String output = postChoices(1, 2); +// System.out.println(output); + +// String output = test(); +// System.out.println(output); + + } + + public static String postChoices(int idQuest, int idChoice) { + Token token = ClientPost.getToken("usuario", "senha"); + if (token == null) { + return null; + } + + String url = urlPolls+"/questions/" + idQuest + + "/choices/" + idChoice; + + return polls(url, null, token.getAccess_token()); + } + + public static String postNewQuestion(String strQuestion, String... strchoices) { + Token token = ClientPost.getToken("usuario", "senha"); + if (token == null) { + return null; + } + + String url = urlPolls+"/questions"; + + String array = "[\""+String.join("\",\"",strchoices)+ "\"]"; + + String param = "{\"question\":\"" + strQuestion + "\"" + + ",\"choices\":" +array+ "}"; + + return polls(url, param, token.getAccess_token()); + } + + public static Token getToken(String username, String password) { + String response = ClientPost.postToken(username, password); + if(response==null){ + return null; + } + + JSONObject json = new JSONObject(response); + + Token token = new Token(); + token.setAccess_token(json.getString("access_token")); + token.setExpires_in(json.getLong("expires_in")); + + return token; + } + + public static String postToken(String username, String password) { + String url = urlPolls+"/tokens" + + "?username="+username+"&password="+password; + + return polls(url, null, null); + } + + public static String test() { + String url = urlPolls + "/test"; + +// String param = "{\"qty\":100,\"name\":\"iPad 4\"}"; + String strQuestion = "Qual seu nome"; + String[] strchoices = {"Felipe", "João"}; + String array = "[\"" + String.join("\",\"", strchoices) + "\"]"; + String param = "{\"question\":\"" + strQuestion + "\"" + + ",\"choices\":" + array + "}"; + + //System.out.println(param); + + return polls(url, param, null); + } + + private static String polls(String urlPOST, String input, String token) { + System.out.println(urlPOST); + // http://localhost:8080/RESTfulExample/json/product/post + try { + URL url = new URL(urlPOST); + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + conn.setDoOutput(true); + conn.setRequestMethod("POST"); + conn.setRequestProperty("Content-Type", "application/json"); + + //Authorization + if (token != null && !token.trim().isEmpty()) { +// System.out.println("Authorization "+token); + conn.setRequestProperty("Authorization", "token " + token); + } + + if (input != null && !input.trim().isEmpty()) { + OutputStream os = conn.getOutputStream(); + os.write(input.getBytes()); + os.flush(); + } + + if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) { + throw new RuntimeException("Failed : HTTP error code : " + + conn.getResponseCode()); + } + BufferedReader br = new BufferedReader(new InputStreamReader( + (conn.getInputStream()))); + + String output = ""; + String read; + while ((read = br.readLine()) != null) { + output += read; + } + conn.disconnect(); + + return output; + + } catch (MalformedURLException e) { + + e.printStackTrace(); + } catch (IOException e) { + + e.printStackTrace(); + + } + return null; + } + +} diff --git a/src/main/java/br/com/app/ws/ConnTestWS.java b/src/main/java/br/com/app/ws/ConnTestWS.java new file mode 100644 index 0000000..ce66885 --- /dev/null +++ b/src/main/java/br/com/app/ws/ConnTestWS.java @@ -0,0 +1,92 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package br.com.app.ws; + +import br.com.utilitarios.UteisFile; +import java.io.File; + +/** + * + * @author Felipe L. Garcia + */ +public class ConnTestWS extends WS{ + + public ConnTestWS() { + + } + + public static void main(String[] args) { + String result = new ConnTestWS().test(); + + System.out.println(result); + } + + public String getTest(int cliente){ + ParametroJWS param = new ParametroJWS(url); + + param.setDeclaringClass(getClass().getName()); + param.setMethod("getTest"); + param.setParamValue(cliente); + param.setParamName("arg0"); + param.setParamTypes(int.class); + param.setReturnType(String.class); + param.setNameSpace(getNameSpace(this.getClass())); + + Object rt = getRemoteSOAP(param); + super.setMsgErro(param.getMsgErro()); + + if(rt==null){ + return null; + } + + return (String) rt; + } + + public String test(){ + System.setProperty("java.net.useSystemProxies", "false"); +// System.setProperty("http.proxyHost", "192.168.5.1"); +// System.setProperty("http.proxyPort", "3128"); +// System.setProperty("https.proxyHost", "192.168.5.1"); +// System.setProperty("https.proxyPort", "3128"); +// System.setProperty("socksProxyHost", "192.168.5.1"); +// System.setProperty("socksProxyPort", "3128"); +// +// if(UteisMetodos.isOnline("https://webservices.producaorestrita.esocial.gov.br" +// + "/servicos/empregador/enviarloteeventos/WsEnviarLoteEventos.svc")){ +// if(!UteisMetodos.isOnlineNetwork()){ +// return "OFFLINE"; +// } + + File f = new File("C:\\Users\\Administrator\\Desktop\\XMLEsocial.xml"); + String xml = null; + try { + xml = UteisFile.read(f); + } catch (Exception ex) { + } + + ParametroJWS param = new ParametroJWS( + "https://webservices.producaorestrita.esocial.gov.br" + + "/servicos/empregador" + + "/enviarloteeventos/WsEnviarLoteEventos.svc"); + + param.setDeclaringClass(getClass().getName()); + param.setMethod("EnviarLoteEventos"); + param.setParamValue(xml); + param.setParamName("arg0"); + param.setParamTypes(String.class); + param.setReturnType(String.class); + param.setNameSpace("http://www.esocial.gov.br/schema/lote/eventos/envio/v2_4_02/"); + + Object rt = getRemoteSOAP(param); + super.setMsgErro(param.getMsgErro()); + + if (rt == null) { + return null; + } + + return (String) rt; + } +} diff --git a/src/main/java/br/com/app/ws/MonitorAppWS.java b/src/main/java/br/com/app/ws/MonitorAppWS.java new file mode 100644 index 0000000..5512576 --- /dev/null +++ b/src/main/java/br/com/app/ws/MonitorAppWS.java @@ -0,0 +1,38 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package br.com.app.ws; + +/** + * + * @author Felipe L. Garcia + */ +public class MonitorAppWS extends WS{ + + public MonitorAppWS() { + + } + + public boolean registerIP(String ip){ + ParametroJWS param = new ParametroJWS(url); + + param.setDeclaringClass(getClass().getName()); + param.setMethod("registerIP"); + param.setParamValue(ip); + param.setParamName("arg0"); + param.setParamTypes(String.class); + param.setReturnType(Boolean.class); + param.setNameSpace(getNameSpace(this.getClass())); + + Object rt = getRemoteSOAP(param); + super.setMsgErro(param.getMsgErro()); + + if(rt==null){ + return false; + } + + return Boolean.valueOf((String)rt); + } +} diff --git a/src/main/java/br/com/app/ws/ParametroJWS.java b/src/main/java/br/com/app/ws/ParametroJWS.java new file mode 100644 index 0000000..2824cd2 --- /dev/null +++ b/src/main/java/br/com/app/ws/ParametroJWS.java @@ -0,0 +1,100 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package br.com.app.ws; + +import java.io.Serializable; + +/** + * + * @author Felipe L. Garcia + */ +public class ParametroJWS implements Serializable{ + private String url; + private String method; + private Class returnType; + private String declaringClass; + private String nameSpace; + private Object[] paramValue; + private Class[] paramTypes; + private String[] paramName; + private String msgErro; + + public ParametroJWS(String url) { + this.url = url; + } + + public String getMsgErro() { + return msgErro; + } + + public void setMsgErro(String msgErro) { + this.msgErro = msgErro; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public Class[] getParamTypes() { + return paramTypes; + } + + public void setParamTypes(Class... paramTypes) { + this.paramTypes = paramTypes; + } + + public String getDeclaringClass() { + return declaringClass; + } + + public void setDeclaringClass(String declaringClass) { + this.declaringClass = declaringClass; + } + + public Class getReturnType() { + return returnType; + } + + public void setReturnType(Class returnType) { + this.returnType = returnType; + } + + public String getMethod() { + return method; + } + + public void setMethod(String method) { + this.method = method; + } + + public Object[] getParamValue() { + return paramValue; + } + + public void setParamValue(Object... paramValue) { + this.paramValue = paramValue; + } + + public String[] getParamName() { + return paramName; + } + + public void setParamName(String... paramName) { + this.paramName = paramName; + } + + public String getNameSpace() { + return nameSpace; + } + + public void setNameSpace(String nameSpace) { + this.nameSpace = nameSpace; + } + +} diff --git a/src/main/java/br/com/app/ws/ParametroWS.java b/src/main/java/br/com/app/ws/ParametroWS.java new file mode 100644 index 0000000..5577966 --- /dev/null +++ b/src/main/java/br/com/app/ws/ParametroWS.java @@ -0,0 +1,61 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package br.com.app.ws; + +import java.io.Serializable; + +/** + * + * @author Felipe L. Garcia + */ +public class ParametroWS implements Serializable{ + private String classeCreate; + private Class[] paramConstrType; + private Object[] paramConstrValue; + + private String method; + private Object[] paramMetodo; + + public Class[] getParamConstrType() { + return paramConstrType; + } + + public void setParamConstrType(Class... paramClasse) { + this.paramConstrType = paramClasse; + } + + public Object[] getParamConstrValue() { + return paramConstrValue; + } + + public void setParamConstrValue(Object... paramConstr) { + this.paramConstrValue = paramConstr; + } + + public String getClasseCreate() { + return classeCreate; + } + + public void setClasseCreate(String classeCreate) { + this.classeCreate = classeCreate; + } + + public String getMethod() { + return method; + } + + public void setMethod(String method) { + this.method = method; + } + + public Object[] getParamMetodo() { + return paramMetodo; + } + + public void setParamMetodo(Object... paramMetodo) { + this.paramMetodo = paramMetodo; + } + +} diff --git a/src/main/java/br/com/app/ws/SisClienteWS.java b/src/main/java/br/com/app/ws/SisClienteWS.java new file mode 100644 index 0000000..99924f1 --- /dev/null +++ b/src/main/java/br/com/app/ws/SisClienteWS.java @@ -0,0 +1,121 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package br.com.app.ws; + +/** + * + * @author Felipe L. Garcia + */ +public class SisClienteWS extends WS{ + + public SisClienteWS() { + } + + public boolean excluirRSA(int cliente){ + ParametroJWS param = new ParametroJWS(url); + + param.setDeclaringClass(getClass().getName()); + param.setMethod("excluirRSA"); + param.setParamValue(cliente); + param.setParamName("arg0"); + param.setParamTypes(int.class); + param.setReturnType(Boolean.class); + param.setNameSpace(getNameSpace(this.getClass())); + + Object rt = getRemoteSOAP(param); + super.setMsgErro(param.getMsgErro()); + + if(rt==null){ + return false; + } + + return Boolean.valueOf((String)rt); + } + + public String getRSA(int cliente){ + ParametroJWS param = new ParametroJWS(url); + + param.setDeclaringClass(getClass().getName()); + param.setMethod("getRSA"); + param.setParamValue(cliente); + param.setParamName("arg0"); + param.setParamTypes(int.class); + param.setReturnType(String.class); + param.setNameSpace(getNameSpace(this.getClass())); + + Object rt = getRemoteSOAP(param); + super.setMsgErro(param.getMsgErro()); + + if(rt==null){ + return null; + } + + return (String) rt; + } + + public boolean gerarRSA(int cliente,int days,String key){ + ParametroJWS param = new ParametroJWS(url); + + param.setDeclaringClass(getClass().getName()); + param.setMethod("gerarRSA"); + param.setParamValue(cliente,days,key); + param.setParamName("arg0","arg1","arg2"); + param.setParamTypes(int.class,int.class,String.class); + param.setReturnType(Boolean.class); + param.setNameSpace(getNameSpace(this.getClass())); + + Object rt = getRemoteSOAP(param); + super.setMsgErro(param.getMsgErro()); + + if(rt==null){ + return false; + } + + return Boolean.valueOf((String)rt); + } + + public boolean gerarAppRSA(int appID, int days){ + ParametroJWS param = new ParametroJWS(url); + + param.setDeclaringClass(getClass().getName()); + param.setMethod("gerarAppRSA"); + param.setParamValue(appID,days); + param.setParamName("arg0","arg1"); + param.setParamTypes(int.class,int.class); + param.setReturnType(Boolean.class); + param.setNameSpace(getNameSpace(this.getClass())); + + Object rt = getRemoteSOAP(param); + super.setMsgErro(param.getMsgErro()); + + if(rt==null){ + return false; + } + + return Boolean.valueOf((String)rt); + } + public boolean excluirAppRSA(int appID){ + ParametroJWS param = new ParametroJWS(url); + + param.setDeclaringClass(getClass().getName()); + param.setMethod("excluirAppRSA"); + param.setParamValue(appID); + param.setParamName("arg0"); + param.setParamTypes(int.class,int.class); + param.setReturnType(Boolean.class); + param.setNameSpace(getNameSpace(this.getClass())); + + Object rt = getRemoteSOAP(param); + super.setMsgErro(param.getMsgErro()); + + if(rt==null){ + return false; + } + + return Boolean.valueOf((String)rt); + } + +} diff --git a/src/main/java/br/com/app/ws/UteisProjetoWS.java b/src/main/java/br/com/app/ws/UteisProjetoWS.java new file mode 100644 index 0000000..d588e35 --- /dev/null +++ b/src/main/java/br/com/app/ws/UteisProjetoWS.java @@ -0,0 +1,23 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package br.com.app.ws; + +import java.util.Properties; + +/** + * + * @author Felipe L. Garcia + */ +public class UteisProjetoWS { + + public static Properties getConfigProperties() { + ParametroWS parametroRemoto = new ParametroWS(); + parametroRemoto.setMethod("getConfigProperties"); + parametroRemoto.setClasseCreate(UteisProjetoWS.class.getName()); + +// return (Properties) WS.getRemoteJWS(parametroJWS); + return (Properties) new WS().getRemoteWS(parametroRemoto); + } +} diff --git a/src/main/java/br/com/app/ws/WS.java b/src/main/java/br/com/app/ws/WS.java new file mode 100644 index 0000000..e02fbec --- /dev/null +++ b/src/main/java/br/com/app/ws/WS.java @@ -0,0 +1,546 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package br.com.app.ws; + +import br.com.utilitarios.UteisEmail; +import br.com.utilitarios.UteisMetodos; +import br.com.utilitarios.UteisProjeto; +import java.util.Calendar; +import java.util.Date; +import javax.xml.namespace.QName; +import javax.xml.rpc.ParameterMode; +import javax.xml.soap.MessageFactory; +import javax.xml.soap.SOAPBody; +import javax.xml.soap.SOAPBodyElement; +import javax.xml.soap.SOAPConnection; +import javax.xml.soap.SOAPConnectionFactory; +import javax.xml.soap.SOAPElement; +import javax.xml.soap.SOAPException; +import javax.xml.soap.SOAPHeader; +import javax.xml.soap.SOAPMessage; +import org.apache.axis.client.Call; +import org.apache.axis.client.Service; +import org.apache.axis.encoding.TypeMapping; +import org.apache.axis.encoding.TypeMappingRegistry; +import org.apache.axis.encoding.XMLType; +import org.apache.axis.encoding.ser.BeanDeserializerFactory; +import org.apache.axis.encoding.ser.BeanSerializerFactory; + +/** + * EXECUTA REQUISIÇÕES AO WEBSERVICE DEFINIDO NO CONFIG + * POSSUI 2 FORMAS DE COMUNICAÇÃO + * 1 - VIA CLASSE GENERICA_WS.JWS PRESENTE NO WEBSERVICE + * 2 - VIA CLASSE DIRETA ONDE URL VAI CONTER CLASSE.JWS PRESENTE NO WEBSERVICE + * + * @author Felipe L. Garcia + */ +public class WS { + private String msgErro; + + private static long lastEmailErro; + + private String urlRoot=""; + protected String url; + + public WS() { + url = UteisProjeto.getConfig("urlWebservice") + + "/" + this.getClass().getSimpleName()+"?wsdl"; + + } + + public void setUrlRoot(String urlRoot) { + this.urlRoot = urlRoot; + this.url = urlRoot+ "/" +url; + } + + public String getMsgErro() { + return msgErro; + } + + public void setMsgErro(String msgErro) { + this.msgErro = msgErro; + } + + /** + * REQUISITA CLASSE PRINCIPAL WS.CLASS NO WEBSERVICE + *

+ * CRIARA INSTANCIA DA CLASSE CONTIDA NO PARAMENTRO E EXECUTA O METODO DEZEJADO + *

+ * TODAS AS CLASSES QUE ESTAO CONTIDAS NO ParametroRemoto + * DEVEM POSSUIR implements Serializable + *

+ * RETORNA SEMPRE BYTE[] QUE SERA CONVERTIDO NO OBEJETO JA ESPERADO + * OU EXCEPTION DE ERROS OCORRIDOS NO WEBSERVICE + */ + public Object getRemoteWS(ParametroWS paramRemoto) { + //URL DA CLASSE GENERICA NO WEBSERVICE + //http://localhost:8080/webservice/WS.jws + url = urlRoot+ "/" +UteisProjeto.getConfig("urlWebservice") + +"/GenericWS.jws"; + + try { + if (paramRemoto == null) { + throw new Exception("paramRemote=null"); + } + if (paramRemoto.getClasseCreate() == null || paramRemoto.getClasseCreate().isEmpty()) { + throw new Exception("classe=null"); + } + if (paramRemoto.getMethod() == null || paramRemoto.getMethod().isEmpty()) { + throw new Exception("method=null"); + } + + Call call = new Call(url); + call.setTargetEndpointAddress(url); + + //DEFINE PARAMETRO DO METODO REMOTE(getRemote) + call.addParameter("paramRemotoBty", + getQNamePrimitive(byte[].class)//TIPO CORRESPONDENTE JAVA/XML + , byte[].class, ParameterMode.IN); + + //PARAM DO METODO getRemote NO WEBSERVICE + //public byte[] getRemote(byte[] paramRemotoBty){ + byte[] paramRemoteBty = UteisMetodos.toByte(paramRemoto); + if (paramRemoteBty == null) { + throw new Exception("paramRemoteBty not Serializable"); + } + Object[] paramInvokeWS = new Object[]{paramRemoteBty}; + + //DEFINE METODO Q SERA EXEC + call.setOperationName(new QName("urn:" + "getRemote", "getRemote")); + //DEFINE Return METODO Q SERA EXEC + call.setReturnType(XMLType.XSD_BYTE, byte[].class); + + //EXEC getRemote + Object retorno = call.invoke(paramInvokeWS); + + if (retorno == null) { + System.out.println("retorno null WEBSERVICE"); + return null; + } + + if (!(retorno instanceof byte[])) { + System.out.println("retorno UNKNOW WEBSERVICE"); + return null; + } + //DESERIALIZABLE + retorno = UteisMetodos.toObject((byte[]) retorno); + + if (retorno == null) { + throw new Exception("retorno not Serializable"); + } + + //SE HOUVER ERRO NO WEBSERVICE,retorno = Exception + if (retorno instanceof Exception) { + throw (Exception) retorno; + } + + System.out.println("retorno ok WEBSERVICE"); + return retorno; + + + } catch (Exception e) { + if (e.getCause() instanceof java.net.ConnectException) { + sendEmailOffline(url); + } + e.printStackTrace(); + }finally{ + System.out.println("WEBSERVICE "+url); + } + return null; + } + + /** + * FAZ REQUISICAO DIRETA VIA URL CLASSE.JWS + *

+ * ARQUIVO CLASSE.JWS DEVE EXISTIR NO WEBSERVICE + *

+ * PARAMENTROS NAO PRIMITIVOS SAO CONVERTIDOS/BYTE + *

+ * CLASSE.JWS JA DEVE IMPLEMENTAR METODO QUE ESPERA PARAM/BYTE + *

+ * TODOS OBJS DEVEM TER implements Serializable + * + */ + public Object getRemoteJwsByte(ParametroJWS param) { + if (param.getMethod() == null) { + System.out.println("method=null"); + return null; + } + //DEFINE RETORNO DO METODO Q SERA EXECUTADO + Class returnType = param.getReturnType(); + + //CLASSE POSSUE METODO DECLARADO + String declareClass = param.getDeclaringClass(); + declareClass = declareClass.replaceAll("\\.", "/");//SEPARACAO DE PACOTES + + String methodName = param.getMethod(); + + System.out.println("WEBSERVICE "+param.getUrl()); + + try { + Call call = new Call(param.getUrl()); + call.setTargetEndpointAddress(param.getUrl()); + + //PARAM DO METODO Q SERA REQUISITADO + Class[] paramTypes = param.getParamTypes(); + + if(paramTypes!=null){ + for (int i = 0; i < paramTypes.length; i++) { + //TIPO CORRESPONDENTE JAVA/XML + QName qParam = getQNamePrimitive(paramTypes[i]); + + if (qParam == null) { + qParam = XMLType.XSD_ANYURI; +// qParam = new QName(getNameSpace(paramTypes[i]) +// ,paramTypes[i].getName(),"tns"); +// +// //Serializer + call.registerTypeMapping(paramTypes[i], qParam + , new BeanSerializerFactory(paramTypes[i], qParam) + , new BeanDeserializerFactory(paramTypes[i], qParam)); + } + + call.addParameter(param.getParamName()[i] + , qParam, paramTypes[i], ParameterMode.IN); + + } + } + + //DEFINE METODO Q SERA EXEC + call.setOperationName(new QName(param.getNameSpace() + ,methodName)); +// call.setOperationName(new QName("urn:" + methodName, methodName)); +// call.setOperationName(methodName); + + //TIPO CORRESPONDENTE JAVA/XML + QName qReturn = getQNamePrimitive(returnType); + Object retorno; + + if (qReturn != null) {//isPrimitive TIPO + call.setReturnType(qReturn, returnType); + } else {//NOT isPrimitive SERA SEMPRE BYTE[] + call.setReturnType(XMLType.XSD_BYTE, byte[].class); + } + + retorno = call.invoke(param.getParamValue()); + + if (retorno == null) { + return null; + } + + if (retorno instanceof byte[]) { + //DESERIALIZABLE + retorno = UteisMetodos.toObject((byte[]) retorno); + + if (retorno == null) { + throw new Exception("retorno not Serializable"); + } + System.out.println("retorno ok WEBSERVICE"); + return retorno; + } + + //SE HOUVER ERRO NO WEBSERVICE,retorno = Exception + if (retorno instanceof Exception) { + throw (Exception) retorno; + } + + System.out.println("retorno ok WEBSERVICE"); + return retorno; + + } catch (Exception e) { + if (e.getCause() instanceof java.net.ConnectException) { + sendEmailOffline(param.getUrl()); + } + e.printStackTrace(); + }finally{ +// System.out.println("WEBSERVICE "+param.getUrl()); + } + return null; + } + + /** + * FAZ REQUISICAO VIA URL http://webservice/CLASSE?wsdl + *

+ */ + + public String getRemoteSOAP(ParametroJWS param){ + String declareClass = param.getDeclaringClass(); + //SEPARACAO DE PACOTES + declareClass = declareClass.replaceAll("\\.", "/"); + + System.out.println("WEBSERVICE "+param.getUrl()); + + try { + SOAPMessage message = MessageFactory.newInstance().createMessage(); + SOAPHeader header = message.getSOAPHeader(); + header.detachNode(); + /* + SOAPEnvelope envelope = message.getSOAPPart().getEnvelope(); + envelope.setAttribute("namespace","namespaceUrl"); + */ + SOAPBody body = message.getSOAPBody(); + + QName bodyName = new QName(param.getNameSpace() + , param.getMethod(), "ns"); + + SOAPBodyElement bodyElement = body.addBodyElement(bodyName); + + if(param.getParamValue()!=null){ + for (int i = 0; i < param.getParamValue().length; i++) { + + SOAPElement symbol = bodyElement + .addChildElement(param.getParamName()[i]); + + String valeu=UteisMetodos.nz(param.getParamValue()[i],""); + symbol.addTextNode(valeu); + } + } + SOAPConnection connection = SOAPConnectionFactory + .newInstance().createConnection(); + SOAPMessage response = connection.call(message, param.getUrl()); + connection.close(); + + SOAPBody responseBody = response.getSOAPBody(); + SOAPBodyElement responseElement = (SOAPBodyElement) responseBody.getChildElements().next(); + SOAPElement returnElement = (SOAPElement) responseElement.getChildElements().next(); + if (responseBody.getFault() != null) { + param.setMsgErro(responseBody.getFault().getFaultString()); + return null; + } else { + return returnElement.getValue(); + } + } catch (SOAPException ex) { +// System.out.println(param.getUrl()); + System.out.println("ERRO WEBSERVICE CONNECTION"); + System.out.println(param.getNameSpace()); +// ex.printStackTrace(); + } + return null; + } + /** + * FAZ REQUISICAO DIRETA VIA URL CLASSE.JWS + *

+ * ARQUIVO CLASSE.JWS DEVE EXISTIR NO WEBSERVICE + *

+ * PARAMENTROS NAO PRIMITIVOS DEVEM SER ESTRUTURADOS COM 'HASHMAP' + *

+ * ATRIBUTO->VALOR(KEY->VALUE) + *

+ * CLASSE.JWS JA DEVE IMPLEMENTAR METODO QUE ESPERA 'HASHMAP' + * + */ + public static Object getRemoteJwsMap(ParametroJWS param) { + if (param.getMethod() == null) { + System.out.println("method=null"); + return null; + } + //CLASSE POSSUE METODO DECLARADO + String declareClass = param.getDeclaringClass(); + declareClass = declareClass.replaceAll("\\.", "/");//SEPARACAO DE PACOTES + + String methodName = param.getMethod(); + + System.out.println("WEBSERVICE "+param.getUrl()); + + try { + Call call = new Call(param.getUrl()); + call.setTargetEndpointAddress(param.getUrl()); + + //PARAM DO METODO Q SERA REQUISITADO + Class[] paramTypes = param.getParamTypes(); + for (int i = 0; i < paramTypes.length; i++) { + //TIPO CORRESPONDENTE JAVA/XML + QName qParam = getQNamePrimitive(paramTypes[i]); + + //NOT isPrimitive + if (qParam == null) { + qParam = XMLType.SOAP_MAP; + + Object paramValue = param.getParamValue()[i]; + + //CONVERTER OBJECT/MAP + param.getParamValue()[i] + = UteisMetodos.toMap(paramValue); + continue; + } + + call.addParameter(param.getParamName()[i] + , qParam, paramTypes[i], ParameterMode.IN); + } + + //DEFINE METODO Q SERA EXEC + call.setOperationName(new QName("urn:" + methodName, methodName)); + + //DEFINE RETORNO DO METODO Q SERA EXECUTADO + Class returnType = param.getReturnType(); + //TIPO CORRESPONDENTE JAVA/XML + QName qReturn = getQNamePrimitive(returnType); + if (qReturn == null) {//not isPrimitive + registerTypeMap(call, returnType); + + qReturn = getQNameTypeMap(returnType); + } + + call.setReturnType(qReturn, returnType); + + Object retorno = call.invoke(param.getParamValue()); + + if (retorno == null) { + return null; + } + + if (retorno instanceof byte[]) { + //DESERIALIZABLE + retorno = UteisMetodos.toObject((byte[]) retorno); + + if (retorno == null) { + throw new Exception("retorno not Serializable"); + } + System.out.println("retorno ok WEBSERVICE"); + return retorno; + } + + //SE HOUVER ERRO NO WEBSERVICE,retorno = Exception + if (retorno instanceof Exception) { + throw (Exception) retorno; + } + + System.out.println("retorno ok WEBSERVICE"); + return retorno; + + } catch (Exception e) { + if (e.getCause() instanceof java.net.ConnectException) { + sendEmailOffline(param.getUrl()); + } + e.printStackTrace(); + }finally{ +// System.out.println("WEBSERVICE "+param.getUrl()); + } + return null; + } + + private static QName getQNameTypeMap(Class type) { +// String localName = Types.getLocalNameFromFullName( +// type.getName()); + +// QName qParam = new QName( +// Namespaces.makeNamespace(type.getName()) +// , localName); + QName qParam = new QName("ns:"+type.getSimpleName(),type.getSimpleName()); + + return qParam; + } + + private static void registerTypeMap(Call call,Class type) { +// ServiceFactory factory1 = ServiceFactory.newInstance(); + + QName qName = getQNameTypeMap(type); + + Service serviceTickReq = call.getService(); +// Service serviceTickReq = factory1.createService(qnTick); +// Service serviceTickReq = new org.apache.axis.client.Service(); + + TypeMappingRegistry tmr = (TypeMappingRegistry) serviceTickReq.getTypeMappingRegistry(); + + BeanSerializerFactory serializer = new BeanSerializerFactory(type, qName); + BeanDeserializerFactory deserializer = + new BeanDeserializerFactory(type, qName); + + TypeMapping tm = (TypeMapping) tmr.getDefaultTypeMapping(); +// TypeMapping tm = (TypeMapping) tmr.getOrMakeTypeMapping( +// "http://schemas.xmlsoap.org/soap/encoding/"); + + if (tm.isRegistered(type, qName)) { +// tm.removeDeserializer(type, qName); +// tm.removeSerializer(type, qName); + return ; + } + tm.register(type, qName,serializer , deserializer); +// tmr.registerDefault(tm); + } + + private static QName getQNamePrimitive(Class type) { + if (type.equals(Boolean.class)) { + return XMLType.XSD_BOOLEAN; + } + if (type.equals(boolean.class)) { + return XMLType.XSD_BOOLEAN; + } + if (type.equals(Integer.class)) { + return XMLType.XSD_INTEGER; + } + if (type.equals(int.class)) { + return XMLType.XSD_INT; + } + if (type.equals(String.class)) { + return XMLType.XSD_STRING; + } + if (type.equals(Double.class)) { + return XMLType.XSD_DOUBLE; + } + if (type.equals(double.class)) { + return XMLType.XSD_DOUBLE; + } + if (type.equals(Date.class)) { + return XMLType.XSD_DATE; + } + if (type.equals(java.sql.Date.class)) { + return XMLType.XSD_DATE; + } + if (type.equals(byte[].class)) { + return XMLType.XSD_BYTE; + } + if (type.equals(byte.class)) { + return XMLType.XSD_BYTE; + } + if (type.equals(Byte.class)) { + return XMLType.XSD_BYTE; + } + + return null; + } + + private static void sendEmailOffline(String url) { + Calendar c = Calendar.getInstance(); + long time = System.currentTimeMillis(); + + c.setTimeInMillis(time); + c.add(Calendar.HOUR_OF_DAY, -1); + + //SE OCORREU EM MENOS DE 1H + if (lastEmailErro > 0 && lastEmailErro >= c.getTimeInMillis()) { + return; + } + + lastEmailErro = time; + + UteisEmail email = new UteisEmail(); + email.setMsg("WS: " + url); + email.setAssunto("WEB SERVICE OFFLINE"); + + try { +// UteisEmail.sendEmailApache(email); + } catch (Exception ex) { + } + } + + /** + * "http://ws.sf.com.br" + */ + public String getNameSpace(Class cls){ + return getNameSpace(cls.getPackage().getName()); + } + public String getNameSpace(String cls){ + String[] pk = cls.split("\\."); + + String name=""; + + for (int i = pk.length-1; i >=0 ; i--) { + name+="."+pk[i]; + } + + return "http://"+name.replaceFirst("\\.", "")+"/"; + } +} diff --git a/src/main/java/br/com/utilitarios/AppVariables.java b/src/main/java/br/com/utilitarios/AppVariables.java new file mode 100644 index 0000000..ee70cd7 --- /dev/null +++ b/src/main/java/br/com/utilitarios/AppVariables.java @@ -0,0 +1,52 @@ + +package br.com.utilitarios; + +import java.util.Properties; + +/** + * + * @author Felipe L. Garcia + */ +public class AppVariables { + + public static final String[] entity={"br.com.app.entidade" + ,"br.com.app.entidade.auto" + ,"br.com.app.entidade.commerce" + ,"br.com.app.entidade.evento"}; + public static final String[] dao={"br.com.app.dao.my" + ,"br.com.app.dao.my.auto" + ,"br.com.app.dao.my.commerce" + ,"br.com.app.dao.my.evento"}; + + public static final String companyName="multware.com"; + public static final String byDev="by "+companyName; + public static final String Copyright=" Copyright © 2016-2019 " + +AppVariables.companyName + +" All rights reserved"; + + public static Properties properties; + + public static String pathWeb; + public static String pathAlbumEventos; + public static String pathAlbumLocalEvento; + public static String pathAlbumEstoque; + public static String pathAlbumCommerce; + + //CADA SESSION POSSUI UM IP +// public static String ipLocal; +// public static String ipRemote; + + public static String urlAPP; + + public static boolean noThread; + + public static String versionAPP; + + public final static int USER_SUPPORT = Integer.MAX_VALUE; + + public final static long MIN_BYTE_BACKUP = 10 * 1024;// 1K = 1024B + + public static String charset; + +// public static AppJavaMemory javaMemory; +} diff --git a/src/main/java/br/com/utilitarios/UteisModulos.java b/src/main/java/br/com/utilitarios/UteisModulos.java new file mode 100644 index 0000000..3ae03f5 --- /dev/null +++ b/src/main/java/br/com/utilitarios/UteisModulos.java @@ -0,0 +1,40 @@ + + +package br.com.utilitarios; + +/** + * + * @author Felipe L. Garcia + */ +public class UteisModulos { + + public static enum Sistemas { + EVENTOS(1,"G-Eventos",AppVariables.entity[3]), + AUTO_PEC(2,"G-Auto/Oficina",AppVariables.entity[1]), + MULTSERVICOS(3,"G-MultService",AppVariables.entity[0]), + COMMERCE(4,"G-Commerce",AppVariables.entity[2]), + CURSOS(5,"G-Cursos",AppVariables.entity[2]); + + private Sistemas(int value, String name,String pack) { + this.value = value; + this.name = name; + this.pack = pack; + } + + public final int value; + public final String name; + public final String pack; + + public static String getName(int value){ + return get(value).name; + } + public static Sistemas get(int value){ + for (Sistemas obj : values()) { + if (obj.value==value) { + return obj; + } + } + return null; + } + } +} diff --git a/src/main/java/br/com/utilitarios/UteisProjeto.java b/src/main/java/br/com/utilitarios/UteisProjeto.java new file mode 100644 index 0000000..a2f9fbe --- /dev/null +++ b/src/main/java/br/com/utilitarios/UteisProjeto.java @@ -0,0 +1,493 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package br.com.utilitarios; + +import br.com.utilitarios.UteisModulos.Sistemas; +import java.io.File; +import java.io.Serializable; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.*; +import javax.mail.AuthenticationFailedException; +import javax.mail.MessagingException; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; + +/** + * + * @author Felipe L. Garcia + */ +public class UteisProjeto implements Serializable{ + public static enum EmailType implements Serializable{ + INFO,ALERTA,FALHA; + } + + public static Properties getConfig() { + if (AppVariables.pathWeb == null || AppVariables.pathWeb.isEmpty()) { + System.out.println("getConfig falhou"); + System.out.println("pathWeb==null"); + return null; + } + File f = new File(AppVariables.pathWeb + + File.separator + +"WEB-INF" + + File.separator + +"config.properties"); + + return UteisMetodos.getProperties(f); + } + + public static int getConfigInt(String value) { + return UteisMetodos.nz(getConfig(value), 0); + } + public static String getConfig(String value) { + return getConfig(value, false); + } + public static String getConfig(String value,boolean reload) { + if (value == null) { + return ""; + } + Properties props = null; + if(reload || AppVariables.properties==null){ + props = getConfig(); + }else{ + props = AppVariables.properties; + } + if (props == null) { + return ""; + } + value = props.getProperty(value); + if (value == null) { + return ""; + } + + return value; + } + + public static Properties getConfig2() { + if (AppVariables.pathWeb == null || AppVariables.pathWeb.isEmpty()) { + System.out.println("getConfig falhou"); + System.out.println("pathWeb==null"); + return null; + } + + File f = new File(AppVariables.pathWeb + + File.separator + +"config.properties"); + + return UteisMetodos.getProperties(f); + } + + public static String getConfig2(String value) { + if (value == null) { + return ""; + } + + Properties props = getConfig2(); + if (props == null) { + return ""; + } + value = props.getProperty(value); + if (value == null) { + return ""; + } + + return value; + } + + public static void configEmailLogoDefault(UteisEmail email) { +// String path = AppVariables.pathWeb +// +File.separator+"vaadin" +// +File.separator+"themes" +// +File.separator+"vaadin" +// +File.separator+"images" +// +File.separator+"LogoMarca64x64.png"; +// String back = AppVariables.pathWeb +// +File.separator+"WEB-INF" +// +File.separator+"background.jpg"; + +// String bs64=""; +// byte[] byt = UteisFile.fileToByte(path); +// if(byt!=null){ +// bs64 = UteisMetodos.byteToBase64(byt); +// } +// String back64=""; +// byt = UteisFile.fileToByte(back); +// if(byt!=null){ +// back64 = UteisMetodos.byteToBase64(byt); +// } +// System.out.println(bs64); +// email.setImgByte(byt); +// email.setImgCID("imglogo"); + +//" + +"" + + +"" + +"" + +"" + +"" + +"" + +"" + +"" + +"" + +"
" + +"

" + +"" + +email.getMsg() + +"" + +"

" + +"
"; + + email.setMsg(content); + } + + public static boolean isDeveloper() { + String macLocal = UteisMetodos.getMAC(); + String macdev = getConfig("MACDEV"); + + macLocal = macLocal.replaceAll("[\\-\\.\\:]", ""); + macdev = macdev.replaceAll("[\\-\\.\\:]", ""); + + if(!macdev.contains(";")){ + return macLocal.equalsIgnoreCase(macdev);//PC DEVELOPER + } + String[] mc = macdev.split(";"); + for (String m : mc) { + if(m.equalsIgnoreCase(macLocal)){ + return true; + } + } + return false; + } + /**ALTERA DESTINATARIO CASO ENVIO SEJA EXECUTADO EM AMBIENTE DE DESENVOLVIMENTO + * EVITAR ENVIO POR ENGANO + */ + private static void configDestTest(UteisEmail email) { + if (isDeveloper()) {//PC DEVELOPER + String to = getConfig("emailsuporte"); + + email.setEmailTo(to); + System.out.println("EMAIL DESTINATARIO ALTERADO "+to); + } + } + + /**ENVIAR EMAIL USANDO LOGO DEFAULT*/ + public static void sendEmailDefault(UteisEmail... emails){ + + for (UteisEmail e : emails) { + configEmailLogoDefault(e); + } + sendEmailThead(true, emails); + } + + public static ThreadUtil sendEmailThead(UteisEmail... emails) { + return sendEmailThead(false, emails); + } + + public static ThreadUtil sendEmailThead(boolean smtpDefault,UteisEmail... emails) { + ThreadUtil thread = new ThreadUtil(); + thread.addMetodo(new Runnable() { + @Override + public void run() { + sendEmail(smtpDefault, emails); + } + }); + + thread.start(); + return thread; + } + + public static boolean sendEmail(UteisEmail... emails) { + return sendEmail(true, emails); + } + + public static boolean sendEmail(boolean smtpDefault,UteisEmail... emails){ + if (emails == null || emails.length ==0) { + return false; + } + + try { + //CONFIGURAR EMAILS P ENVIAR + for (UteisEmail e : emails) { + if (smtpDefault) { + //SERVIDOR SMTP PADRAO + configEmailSmtpDefault(e); + } + + } + + UteisEmail.sendEmailJavax(emails); + + } catch (Exception ex) { + + System.out.println(ex); + emails[0].setLog(ex.getMessage()); + + if (ex instanceof AuthenticationFailedException) { + System.out.println("Erro ao enviar email." + +" Autenticação inválida"); + } + if (ex instanceof MessagingException) { + if(ex.getMessage()!=null){ + if (ex.getMessage().contains("Server busy")) { + System.out.println("Servidor SMTP ocupado"); + } + } + } + + return false; + } + return true; + } + + public static boolean isMicrosoft(String to){ + to = to.toLowerCase(); + if (to.contains("@outlook") + || to.contains("@hotmail") + || to.contains("@live") + || to.contains("@msn")) { + return true; + } + return false; + } +// /**PARAMETRO SEGURANCA CRIPTOGRAFADA NO SMTP*/ +// public static void configEmailSSL(UteisEmail email){ +// if (email == null) { +// return; +// } +// +// if ("smtp.gmail.com".equals(email.getSmtp()) +// || "smtp.live.com".equals(email.getSmtp())) { +// email.setSSL(true); +// } +// } + /**CONFIG SMTP DEFAULT*/ + public static void configEmailSmtpDefault(UteisEmail email){ + if (email == null) { + return; + } + + Properties properties = getConfig(); + + String pwd = properties.getProperty("smtpsenha"); + String user = properties.getProperty("smtpuser"); + if (user.length() > 25) { + user = new UteisSecurity().decrypt(user); + } + if (pwd.length() > 25) { + pwd = new UteisSecurity().decrypt(pwd); + } + email.setAutentication(user,pwd); + email.setSmtp( properties.getProperty("smtphost")); + email.setPort(UteisMetodos.nz(properties.getProperty("smtpport"),25)); + email.setSSL("true".equalsIgnoreCase(properties.getProperty("smtpSSL"))); + email.setTLS("true".equalsIgnoreCase(properties.getProperty("smtpTLS"))); + email.setEmailFrom(properties.getProperty("emailenvio")); + } + public static void sendEmailInfo(UteisEmail email, int sistema,int clienteID) { + sendEmailSuporte(email, sistema, EmailType.INFO,clienteID); + } + public static void sendEmailAlerta(UteisEmail email, int sistema,int clienteID) { + sendEmailSuporte(email, sistema, EmailType.ALERTA,clienteID); + } + public static void sendEmailFalha(UteisEmail email, int sistema,int clienteID) { + sendEmailSuporte(email, sistema, EmailType.FALHA,clienteID); + } + /** + * ENVIA EMAIL P/ SUPORTE + */ + public static void sendEmailSuporte(UteisEmail email + , int sistema,EmailType tipoEmail,int clienteID) { + + String cliente = "

Cliente: "+clienteID; + + String modulo = Sistemas.getName(sistema); + String localCode = "

Projeto:"+getConfig("nameAPP") + +"

Módulo: "+modulo + +"

Versão: "+AppVariables.versionAPP; + + email.setMsg(email.getMsg() + +"

"+cliente+localCode); + + email.setAssunto(tipoEmail==null?"":tipoEmail.name()+" " + + email.getAssunto() + +" " + clienteID); + + sendEmailSuporte(email); + } + + /**ENVIA EMAIL P/ COM DETALHES DO ERRO*/ + public static void sendEmailFalhaCode(String msg,String assunto + ,Class cls,int sistema,int clienteID){ + + String cliente = "

Cliente: "+clienteID; + + String classe = ""; + if(cls!=null){ + classe = "

Classe: "+cls.getName(); + } + + String modulo = Sistemas.getName(sistema); + String localCode = classe+"

Projeto:"+getConfig("nameAPP") + +"

Módulo: "+modulo + +"

Versão: "+AppVariables.versionAPP; + + msg = cliente+localCode; + assunto = assunto+" "+clienteID; + + sendEmailSuporte(msg, assunto); + } + + /**ENVIA EMAIL P/ */ + public static void sendEmailSuporte(String msg, String assunto){ + UteisEmail email = new UteisEmail(); + email.setMsg(msg); + email.setAssunto(assunto); + + sendEmailSuporte(email); + } + + /**ENVIA EMAIL P/ */ + public static void sendEmailSuporte(UteisEmail email){ + configEmailSmtpDefault(email); + + email.setEmailTo(getConfig("emailsuporte")); + + sendEmailThead(true, email); + } + + public static String getLocalJasper() { + String path; + + path = AppVariables.pathWeb + + File.separator + +"WEB-INF" + + File.separator + +"rpt" ; + + return path; + } + + public static long getVersaoRemote(String app) { + //URL DOWNLOAD + final String url + = UteisProjeto.getConfig("urlVersoes"); + + System.out.println("URL: " + url); + + //LER XML URL + NodeList sistemaList = null; + try { + if (url.contains("http")) { +// if (!UteisMetodos.isOnline(UteisMetodos.getDomain(url))) { +// return 0; +// } + + sistemaList = UteisFile.readFileXML(new URL(url), "sistema"); + } + if (url.contains("ftp")) { + Ftp ftp = new Ftp(url); + String user = UteisProjeto.getConfig("ftpuser"); + String pw = UteisProjeto.getConfig("pwApp"); + + if (user.length() > 25) { + user = new UteisSecurity().decrypt(user); + } + if (pw.length() > 25) { + pw = new UteisSecurity().decrypt(pw); + } + + ftp.setUser(user); + ftp.setPwd(pw); + + sistemaList = UteisFile.readFileXML(ftp, "sistema"); + } + if (sistemaList == null) { + System.out.println("VERSAO NAO ECONTRADA"); + return 0; + } + + app = app.toUpperCase(); + +// if (!sistema.endsWith("WEB")) { +// sistema += "WEB"; +// } + String value = getVersao(sistemaList, app); + + if (value != null) { + System.out.println("VERSAO SITE " + app + ": " + value); + return Long.parseLong(value.replaceAll("[^0-9]", "")); + } else { + System.out.println("VERSAO NAO ENCONTRADA NO SITE: " + app); + return 0; + } + + } catch (MalformedURLException ex) { +// ex.printStackTrace(); + } + + return 0; + } + + public static String getVersaoXML(String projeto) { + String file = UteisMetodos.getTomcatDir() + + File.separator + +"webapps" + + File.separator + +"versoes" + + File.separator + + "versoes.xml"; + + NodeList sistemaList; + try { + sistemaList = UteisFile.readFileXML(file, "sistema"); + } catch (Exception ex) { + return null; + } + + String value = getVersao(sistemaList, projeto); + + System.out.println("VERSAO XML " + projeto + ": " + value); + + return value; + } + + private static String getVersao(NodeList sistemaList, String sistema) { + if (sistemaList == null) { + return null; + } + if (sistema == null || sistema.isEmpty()) { + return null; + } + + Element findElement + = UteisMetodos.getXMLElement(sistemaList, sistema, "nome"); + + if (!(findElement instanceof Element)) { + return null; + } + Element element = (Element) findElement; + return element.getElementsByTagName("versao") + .item(0).getFirstChild().getNodeValue(); + } + + public static Map getEndereco(String cep){ + String urlCorreios = getConfig("urlCorreios"); + urlCorreios = urlCorreios.replace("cep?", cep); + + return UteisMetodos.getAddress(cep,urlCorreios); + } + + +}