All Downloads are FREE. Search and download functionalities are using the official Maven repository.

foundation.cmo.api.mls.graphql.autoconfigure.MGraphQLAutoConfiguration Maven / Gradle / Ivy

There is a newer version: 1.0.21
Show newest version
package foundation.cmo.api.mls.graphql.autoconfigure;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.hibernate.boot.model.naming.Identifier;
import org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationListener;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.stereotype.Component;

import foundation.cmo.api.mls.graphql.mappers.MCaseTypeMapper;
import foundation.cmo.api.mls.graphql.mappers.MCpfCnpjTypeMapper;
import foundation.cmo.api.mls.graphql.mappers.MDateTypeMapper;
import foundation.cmo.api.mls.graphql.properties.MGraphQLProperties;
import foundation.cmo.api.mls.graphql.properties.annotations.MCase;
import foundation.cmo.api.mls.graphql.properties.annotations.MCase.EmumTypeCase;
import foundation.cmo.api.mls.graphql.security.MHttpSecurityConfig;
import foundation.cmo.api.mls.graphql.security.MUserSecurityConfig;
import foundation.cmo.api.mls.graphql.security.services.JwtService;
import foundation.cmo.api.mls.graphql.security.services.MUserService;
import foundation.cmo.api.mls.libs.MLogStarting;
import foundation.cmo.api.mls.libs.components.MGraphBean;
import graphql.GraphQL;
import graphql.execution.AsyncExecutionStrategy;
import graphql.execution.AsyncSerialExecutionStrategy;
import graphql.schema.GraphQLSchema;
import io.leangen.graphql.ExtensionProvider;
import io.leangen.graphql.GeneratorConfiguration;
import io.leangen.graphql.annotations.GraphQLQuery;
import io.leangen.graphql.generator.mapping.TypeMapper;
import io.leangen.graphql.metadata.messages.MessageBundle;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@AutoConfiguration
@EnableConfigurationProperties(MGraphQLProperties.class)
@ConditionalOnProperty(name = "foundation.cmo.api.mls.graphql.enable", havingValue = "true", matchIfMissing = true)
public class MGraphQLAutoConfiguration {

	private final Map> mapMessages = new HashMap<>();

	@Value("${FORMAT_MESSAGES:true}")
	private boolean format;

	@Bean("foundation.cmo.api.mls.graphql.log")
	void log() {
		new MLogStarting().log(this);
	}

//	@Bean
	MGraphBean graphQLBean() {
		return new MGraphBean();
	}

//	@Service
//	@GraphQLApi()
	public class MGraphQLStartupService {

		@MCase(EmumTypeCase.UPPERCASE)
		@GraphQLQuery(name = "query_api_test")
		public String getApiTest() {
			return "GraphQL Service Loading...";
		}
	}

	@Bean
	GraphQL graphQL(GraphQLSchema schema) {

		return GraphQL.newGraphQL(schema)
				.subscriptionExecutionStrategy(new AsyncExecutionStrategy(new MGraphQLExceptionHandler()))
				.queryExecutionStrategy(new AsyncExecutionStrategy(new MGraphQLExceptionHandler()))
				.mutationExecutionStrategy(new AsyncSerialExecutionStrategy(new MGraphQLExceptionHandler())).build();
	}

	@Bean
	JwtService getJwtService() {
		return new JwtService();
	}

	@Bean
	MHttpSecurityConfig getMHttpSecurityConfig() {
		return new MHttpSecurityConfig();
	}

	MUserSecurityConfig getMUserSecurityConfig() {
		return new MUserSecurityConfig();
	}

	@Bean
	MUserService loadMUserService() {
		return new MUserService();
	}

	@Bean
	MessageBundle messageBundle() {
		return key -> getString(key);
	}

	public String getString(String pattern, Object... args) {
		try {
			String message =  messageSource().getMessage(pattern, args, Locale.forLanguageTag("pt-BR"));
			
			try {
				if (!pattern.startsWith("desc.")) {					
					pattern = String.format("desc.%s", pattern);
					messageSource().getMessage(pattern, args, Locale.forLanguageTag("pt-BR"));
				}
			} catch (Exception e) {
				String regex = "[^a-zA-Z0-9_]+";
				String ret = pattern.replaceAll(regex, "_");
				appendText(pattern, ret);
			}
			
			return message;
		} catch (Exception e) {
			String regex = "[^a-zA-Z0-9_]+";
			String ret = pattern.replaceAll(regex, "_");

			appendText(pattern, ret);
			return ret;
		}
	}

	private void appendText(String key, String text) {
		try {
			String skey = key.substring(0, key.indexOf("."));

			if (!mapMessages.containsKey(skey)) {
				mapMessages.put(skey, new HashMap<>());
			}

			mapMessages.get(skey).put(key, text);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Bean
	@ConditionalOnMissingBean
	ExtensionProvider pageableInputField() {
		return (config, defaults) -> defaults.prepend(new MCpfCnpjTypeMapper()).prepend(new MDateTypeMapper())
				.prepend(new MCaseTypeMapper());
	}

	@Bean(name = "messageSource")
	MessageSource messageSource() {
		ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
		messageSource.setBasenames("messages/message");
		return messageSource;
	}

	@Component
	@ConditionalOnProperty(name = "foundation.cmo.api.mls.graphql.format", matchIfMissing = true)
	public class MApplicationListener implements ApplicationListener {

		@Override
		public void onApplicationEvent(ApplicationReadyEvent event) {
			log.info("--> {}", format);

			if (format) {
				log.info("Formating messages...");
				fixUnknowMessages();
			}
		}
	}

	private void fixUnknowMessages() {

		PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(
				getClass().getClassLoader());

		try {
			Resource[] resources = resolver.getResources("classpath:messages/**/*.properties");

			for (Resource res : resources) {
				Properties properties = PropertiesLoaderUtils.loadProperties(res);

				mapMessages.forEach((key, value) -> {
					value.forEach((skey, svalue) -> {
						log.info("New message registered for key {}", skey);
						svalue = String.format("%s #ToDo ~>  change it!", svalue);
						properties.put(skey, svalue);
					});
				});

				Map> maps = new TreeMap<>();

				Pattern compile = Pattern.compile("(\\w+)\\..*");

				properties.forEach((key, value) -> {
					String skey = (String) key;
					String svalue = (String) value;
					Matcher matcher = compile.matcher(skey);
					if (matcher.matches()) {
						String ref = skey.substring(0, skey.indexOf("."));
						if (!maps.containsKey(ref)) {
							maps.put(ref, new TreeMap<>());
						}
						maps.get(ref).put(skey, svalue.trim());
					}
				});

				int maxlength = 0;

				for (String key : maps.keySet()) {
					Map map = maps.get(key);
					for (String ref : map.keySet()) {
						String ss = String.format("%s=%s\n", ref, map.get(ref));
						if (ss.length() > maxlength) {
							maxlength = ss.length();
						}
					}
				}

				StringBuilder sb = new StringBuilder();

				for (String key : maps.keySet()) {
					String aux = String.format("# ");
					sb.append(String.format("%s%s\n", aux, "=".repeat(maxlength - aux.length())));

					aux = String.format("# %s's   ", key.toUpperCase());
					sb.append(String.format("%s%s\n", aux, "-".repeat(maxlength - aux.length())));

					Map map = maps.get(key);
					int ml = 0;
					for (String key2 : map.keySet()) {
						if (key2.length() > ml) {
							ml = key2.length();
						}
					}

					for (String ref : map.keySet()) {
						String sp = " ".repeat(ml - ref.length());
						sb.append(String.format("%s%s = %s\n", ref, sp, map.get(ref).trim()));
					}
					sb.append("\n");
				}

				String sfile = String.format("src/main/resources/messages/%s", res.getFilename());

				File file = new File(sfile);
				if (file.exists()) {
					file.delete();
				}
				file.createNewFile();

				try (BufferedWriter bufferedWriter = new BufferedWriter(
						new OutputStreamWriter(new FileOutputStream(file), "ISO-8859-1"))) {
					bufferedWriter.write(sb.toString());
					bufferedWriter.newLine();
					bufferedWriter.flush();
				}

				log.info("Messages stored in {}", file.getAbsolutePath());

				// sb = new StringBuilder();

				StringBuilder sb2 = new StringBuilder();
				for (String key : maps.keySet()) {
					String skey = key.toUpperCase();
					Map map = maps.get(key);
					map.forEach((k, v) -> {
						String fieldName = String.format("public static final String %s$%s = \"${%s}\";", skey,
								k.replace(key + ".", "").replace(".", "_"), k);
						sb2.append(fieldName).append("\n");
					});
				}

				file = new File("M.java.aux");
				if (file.exists()) {
					file.delete();
				}
				file.createNewFile();

				try (BufferedWriter bufferedWriter = new BufferedWriter(
						new OutputStreamWriter(new FileOutputStream(file), "ISO-8859-1"))) {
					bufferedWriter.write(sb2.toString());
					bufferedWriter.newLine();
					bufferedWriter.flush();
				}

			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("unused")
	private void fixUnknowMessages_() {
		try {
			Map> maps = new TreeMap<>();

			mapMessages.forEach((key, map) -> {
				if (!maps.containsKey(key)) {
					maps.put(key, new TreeMap<>());
				}
				map.forEach((skey, text) -> {
					Map maps2 = maps.get(key);
					maps2.put(skey, text);
				});
			});

			System.out.println(System.getProperty("file.encoding"));

			StringBuilder sb = new StringBuilder();
			Pattern compile = Pattern.compile("(\\w+)\\..*");
			File file = new File("message.txt");

			BufferedReader buffer = new BufferedReader(
					new InputStreamReader(new FileInputStream("message.properties"), "ISO-8859-1"));
			String line = buffer.readLine();

			while (line != null) {
				Matcher matcher = compile.matcher(line);
				if (matcher.matches()) {
					String sline = line.substring(0, line.indexOf("."));
					if (!maps.containsKey(sline)) {
						maps.put(sline, new TreeMap<>());
					}

					String key = line.substring(0, line.indexOf("="));
					String value = line.substring(line.indexOf("=") + 1);
					System.out.println(value);
					maps.get(sline).put(key, value.trim());
				}
				line = buffer.readLine();
			}

			buffer.close();

			int maxlength = 0;

			for (String key : maps.keySet()) {
				Map map = maps.get(key);
				for (String ref : map.keySet()) {
					String ss = String.format("%s=%s\n", ref, map.get(ref));
					if (ss.length() > maxlength) {
						maxlength = ss.length();
					}
				}
			}

			for (String key : maps.keySet()) {
				sb.append(String.format("\n# %s #\n", "-".repeat(maxlength - 2)));
				sb.append(String.format("# %s's\n", key.toUpperCase()));
				Map map = maps.get(key);

				int ml = 0;
				for (String key2 : map.keySet()) {
					if (key2.length() > ml) {
						ml = key2.length();
					}
				}

				for (String ref : map.keySet()) {
					String sp = " ".repeat(ml - ref.length());
					sb.append(String.format("%s%s= %s\n", ref, sp, map.get(ref).trim()));
				}
			}

			file = new File("aux_message.txt");
			if (file.exists()) {
				file.delete();
			}
			file.createNewFile();

//			BufferedWriter out = Files.newBufferedWriter(Paths.of(path));

			try (FileWriter fileWriter = new FileWriter(file, true);
					BufferedWriter bufferedWriter = Files.newBufferedWriter(file.toPath());

//					BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)
			) {
				bufferedWriter.write(sb.toString());
				bufferedWriter.newLine();
				bufferedWriter.flush();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Bean
	PhysicalNamingStrategyStandardImpl physicalNamingStrategyStandard() {
		return new MPhysicalNamingImpl();
	}

	public class MPhysicalNamingImpl extends PhysicalNamingStrategyStandardImpl {
		private static final long serialVersionUID = 1L;

		@Override
		public Identifier toPhysicalSequenceName(Identifier name, JdbcEnvironment context) {
			return apply(name, context);
		}

		@Override
		public Identifier toPhysicalSchemaName(Identifier name, JdbcEnvironment context) {
			return apply(name, context);
		}

		@Override
		public Identifier toPhysicalCatalogName(Identifier name, JdbcEnvironment context) {
			return apply(name, context);
		}

		@Override
		public Identifier toPhysicalColumnName(Identifier name, JdbcEnvironment context) {
			return apply(name, context);
		}

		@Override
		public Identifier toPhysicalTableName(Identifier name, JdbcEnvironment context) {
			name = apply(name, context);
			return Identifier.toIdentifier(name.getCanonicalName().toUpperCase(), true);
		}

		private Identifier apply(Identifier name, JdbcEnvironment context) {
			if (name != null) {
				String message = name.getCanonicalName();

				message = message.replace("${", "");
				message = message.replace("}", "");

				try {
					message = messageSource().getMessage(message, null, Locale.forLanguageTag("pt-BR"));
					return Identifier.toIdentifier(message, true);
				} catch (Exception e) {

					Pattern pattern = Pattern.compile("\\b\\w+\\.\\w+\\b");
					Matcher matcher = pattern.matcher(message);

					while (matcher.find()) {
						String palavra = matcher.group();
						log.warn("Message not found for {}", palavra);

						appendText(message, palavra);
					}

				}

				return name;
			}

			return name;
		}

//		@Override
//		public Identifier toPhysicalTableName(Identifier name, JdbcEnvironment context) {
//			String message = name.getCanonicalName();
//			try {
//				if ("dtype".equalsIgnoreCase(message)) {
//					return Identifier.toIdentifier(message);
//				}
//				
//				message = message.replace("${", "");
//				message = message.replace("}" , "");
//
//				message = messageSource().getMessage(message, null, Locale.forLanguageTag("pt-BR"));
//				return Identifier.toIdentifier(message.toUpperCase());
//			} catch (Exception e) {
//				throw new UnsupportedOperationException("Message value not found: " + message);
//			}
//		}
//		
//		@Override
//		public Identifier toPhysicalCatalogName(Identifier name, JdbcEnvironment context) {
//			System.out.println(name);
//			return super.toPhysicalCatalogName(name, context);
//		}
//		
//		@Override
//		public Identifier toPhysicalSchemaName(Identifier name, JdbcEnvironment context) {
//			System.out.println(name);
//			return super.toPhysicalSchemaName(name, context);
//		}
//
//		@Override
//		public Identifier toPhysicalSequenceName(Identifier name, JdbcEnvironment context) {
//			System.out.println(name);
//			return super.toPhysicalSequenceName(name, context);
//		}
//		
//		@Override
//		public Identifier toPhysicalColumnName(Identifier name, JdbcEnvironment context) {
//			String message = name.getCanonicalName();
//			try {
//				if ("dtype".equalsIgnoreCase(message)) {
//					return Identifier.toIdentifier(message);
//				}
//
//				message = message.replace("${", "");
//				message = message.replace("}" , "");
//				
//				message = messageSource().getMessage(message, null, Locale.forLanguageTag("pt-BR"));
//				return Identifier.toIdentifier(message);
//			} catch (Exception e) {
//				throw new UnsupportedOperationException("Message value not found: " + message);
//			}
//			
//			//return messageSource().getMessage(pattern, args, Locale.forLanguageTag("pt-BR"));
//			//String regex = "[^a-zA-Z0-9_]+";
//			//String ret = name.getCanonicalName().replaceAll(regex, "_");
//			//return Identifier.toIdentifier(ret);
//		}
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy