Posts

Showing posts with the label Java

Spring Boot / Embedded Tomcat - SSL

 @Bean     public ServletWebServerFactory servletContainer() {         TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {             @Override             protected void postProcessContext(Context context) {                 var securityConstraint = new SecurityConstraint();                 securityConstraint.setUserConstraint("CONFIDENTIAL");                 var collection = new SecurityCollection();                 collection.addPattern("/*");                 securityConstraint.addCollection(collection);                 context.addConstraint(securityConstraint);             }       ...

JRE - a Certificate elave etmek

Windows10 : command prompt as adminstrator olaraq run edilmelidir. java nin yerleshdiyi foldere kechib, oradan  jre  daxilinde olan bin folderine kecmek lazimdir.  keytool -import -trustcacerts -keystore "/path/to/cacerts" -storepass changeit -noprompt -alias "aliasname" -file /path/to/cerfiticate.cer result: Certificate was added to keystore menim numunemde => keytool yerleshdiyi folder : C:\Users\HamidSF\.jdks\corretto-1.8.0_302\jre\bin cacerts uchun path : C:\Users\HamidSF\.jdks\corretto-1.8.0_302\jre\lib\security\cacerts

ThreadPoolExecutor ve ThreadPoolTaskExecutor ferqleri

Arashdirdigim qederi ile aralarinda ferqli cehetler yox kimidir. ThreadPoolTaskExecutor ozu arxada ThreadPoolExecutor istifade edir.  Bir ferqli meqam var ki, TPE yaradarken, constructorda mutleq corePoolSize, maxPoolSize ve s kimi deyerlerini vermeliyik. TPTE ise, TPE ni bean-style yaratmaga imkan verir. Hetta corePoolSize ve maxPoolSize deyerlerini vermesek bele ozu arxada default deyerler saxladigina gore TPE ni yarada bilir. https://stackoverflow.com/questions/39934115/difference-and-suggest-threadpooltaskexecutor-and-threadpoolexecutor

@Transactional annotation haqqinda. Cascade istifade olunmasi

Image
Umumiyyetle bu annotation Service Layer de istifade etmek duzgundur. Repository de istifade etmek, Serivce layerden cagrilan her bir Repository method uchun tranzaksiyanin yaradilmasi demekdir.  Meselen, UserRepository de save ve remove adli method var tutaq ki ve Transactional annotation u ile qeyd olunub. Service Layerde saveAndRemoveUnused adli method var. Bu method save edib, istifade olunmayanlari remove edecek.  Eger Service Layerden bu iki methodu cagirsaq, bu zaman her bir emeliyyat uchun Tranzaksiya achilacaq ki, bu da db ni yora biler. Hell yolu olaraq, Service Layerde bu methodlarin istifade oludugun yerde @Transaction qeyd etmek kifayetdir. Bu zaman bu method ishlediyi vaxt boyunca yalniz bir tranzaksiya achilacaq. save ve update methodlari uchun ayrica tranzaksiya achilmayacaq. Diger istifadesine baxsaq meselen, update method id e gore tapir ve hemin useri hansisa field ni deyishir. Methodun bashina @Transactional yazmaqla, userRepository nin save methodunu cagirm...

Microservices Security Example #3 - Zuul Proxy Server haqqında danışırıq

Image
 Zuul Proxy Server Zuul Serveri bir qala qapısı kimi düşünə bilərik. Məsələn qalaya daxil olmaq istəyən şəxsləri yalnız vahid bir qapıdan qəbul etmək üçün və ya tanımadığınız şəxsləri qalaya buraxmamaq üçün istifadə edilə bilər.  Bunu Zuul Server-ə texniki olaraq nümunə gətirsək, məsələn user-service və auth-service lər var. Zuul vasitəsilə bu service-lərə girişi yalnız vahid bir yerdən edə bilərik. Burada Zuul Serverin işi Routing olacaq. Zuul Serverə öz servisimizi tanıtdıqdan sonra, artıq gələn sorğuya uyğun olaraq uyğun service çağrılacaq və sorğuya uyğun iş görüləcək. Zuul Serverin Routing prosesi üçün Ribbon istifadə olunur. Ribbon, Eureka Server də qeydiyyatdan keçən service-ləri özündə saxlayaraq, uyğun yönləndirmələr edə bilir. Application da istifadə olunan versiyalar: 1. spring-boot-starter-parent (2.3.8.RELEASE) 2. spring-cloud.version (Hoxton.SR9)

Microservices Security Example #2 - Servisin Eureka Serverdə qeydiyyatı

Image
 Dummy Service Eureka Server də qeydiyyatdan keçirmək üçün sadə bir service yaradırıq, sadəcə praktika məqsədli olaraq. Daha sonradan real service-lərə tətbiq olunacaq. Application-ı yaradıb uyğun dependency-ləri əlavə etdikdən sonra edəcəyimiz ilk iş Main class-ın üzərinə @EnableEurekaClient əlavə edirik. Discovery Server də Service i qeydiyyata salmaq üçün EnableEurekaClient və EnableDiscoveryClient annotationları var. Aralarındakı fərqi sadə olaraq, belə göstərirlər. Əgər Discovery Server Eureka-dırsa, @EnableEurekaClient istifadə olunması məsləhət görülür. Digər hallarda @EnableDiscoveryClient istfadə etmək lazımdır. Daha sonra application.yml faylını açırıq. Burada bəzi configuration-lar etmək qeyd etmək lazımdır.  Burada ilk parameterdə application-ın adı, növbətidə hansı port da işləyəcəyi qeyd olunur. Digər parameterlər artıq Eureka Server də bir client application kimi qeydiyyatdan keçmək üçün lazımdır. prefer-ip-address parameterinə true dəyəri verməklə, Eurekanın bi...

Microservices Security Example #1 - Eureka Discovery Server haqqında danışırıq

Image
Eureka Discovery Server Eureka Server nədir və nə üçün istifadə olunur suallarının cavabını internetdə axtarıb daha geniş məlumat tapmaq olar. Bu yazıda yalnız praktikasına fokuslanacağıq. Qısa məlumat olaraq, Spring Cloud Netflix Eureka, servislerin makina adı ve bağlantı noktasına ihtiyaç olmaksızın birbirleriyle iletişim kurmasını sağlar. Bu mimarideki tek önemli nokta, her servisin kayıt olması gereken bir servis olmasıdır. Ətraflı    Eureka Server yaratmaq standart prosedurdur.  http://start.spring.io/ keçid edərək yarada bilərik. Bu application-da istifadə olunan versiyalar: 1. spring-boot-starter-parent (2.3.8.RELEASE) 2. spring-cloud.version (Hoxton.SR9) Bu versiyaların istifadə məqsədi bundan ibarətdir ki, spring-boot 2.4.X versiyalarda spring-cloud yeni versiyanı işlətmək lazımdır (2020.0.0). Spring Cloud bu versiyada Zuul, Ribbon dəstəkləmir. Gateway kimi Spring Cloud Gateway istifadə etməyi məsləhət görülür. Sadəcə bu arxitekturada Zuul istifadə etdiyimə...

Validation for AZ phone numbers with RegEx in Java

Number bir neche formada gele biler bize. Meselen,  99451xxxxxxx 99455xxxxxxx ve s. 051xxxxxxx 055xxxxxxx ve s. 51xxxxxxx 55xxxxxxx ve s. Bu nomreleri standart formaya salmaq uchun kichik kod : public static String validate (String number){ final String prefix = "994" ; if (number.length() == 12 && number.matches( "^(994)+(50|51|55|70|77|99).*$" )) { return number ; } else if (number.length() == 10 && number.matches( "^(0)+(50|51|55|70|77|99).*$" )) { return prefix + number.substring( 1 ) ; } else if (number.length() == 9 && number.matches( "^(50|51|55|70|77|99).*$" )) { return prefix + number ; } return null; } sonda bize qayidan netice  99451xxxxxxx ve ya 99455xxxxxxx sheklinde olacaq. Eger null qayidarsa, bu methodun cagrildigi yerde uygun helli etmek olar.

Annotations in Java

@Retention(RetentionPolicy.RUNTIME) -  byte-code a yazilir ve VM runtime zamani istifade ede bilir @Retention(RetentionPolicy.CLASS) - byte-code a yazilir, VM istifade ede bilmir @Retention(RetentionPolicy.SOURCE) - byte-code a yazilmir. Yalniz compile zamani istifade olunur

Frontdan gelen base64 file contenti mail de attachment kimi gondermek

String cnt = attachmentDto.getContent(); int index = cnt.indexOf(",") + 1; // cnt = cnt.replaceFirst("^data:image/[^;]*;base64,?", ""); cnt = cnt.substring(index); byte[] bytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(cnt); mimeMessageHelper.addAttachment(    attachmentDto.getName(),    new ByteArrayResource(bytes) ); 

JWT - generate public and private key (YML example)

@SpringBootApplication public class AuthServerApplication implements CommandLineRunner { public static void main(String[] args) { SpringApplication.run(AuthServerApplication.class, args); } @Override public void run(String... args) throws Exception { KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("RSA"); keyGenerator.initialize(1024); KeyPair kp = keyGenerator.genKeyPair(); PublicKey publicKey = kp.getPublic(); PrivateKey privateKey = kp.getPrivate(); String encodedPublicKey = Base64.getEncoder().encodeToString(publicKey.getEncoded()); String encodedPrivateKey = Base64.getEncoder().encodeToString(privateKey.getEncoded()); System.out.println(convertToPublicKey(encodedPublicKey)); System.out.println(); System.out.println(convertToPrivateKey(encodedPrivateKey)); } private static String convertToPrivateKey(String key) {         StringBuilder result = new StringBuilder();         result.append(...

Apache Mail - for mail operation

 <dependency> <groupId> org.apache.commons </groupId> <artifactId> commons-email </artifactId> <version> 1.5 </version> </dependency> MimeMessageParser parser = new MimeMessageParser((MimeMessage) message).parse(); "parser" ile body ni hem html, hem de text/plain formatinda chekmek mumkundur.

Gmail, Mail.ru ve Yandex(mail) servislerinde folderler ve maillerin chekilmesinin sade mentiqi

Image
Mail.ru servisi uzerinden gelen folderler UI Language den asili olmayaraq hemishe bir dilde gelir. Lakin Gmail da bu mentiq bashqadir. UI language gore folderler hemin language de gele biler. Eger folderleri chekib bazaya yaziriqsa, aydindir ki, UI terefde dil deyishse, bizim servisimiz duzgun ishlemeyecek. Duzgun ishlemeyecek deyerken, eyni Folderler muxtelif dillerde bazamiza otura biler.  Nece hell etmeli ? IMAPFolder classi var, hansi ki, Folder classini extends edir. Bize gelen Folder classinin obyektini IMAPFolder classina cast eleye bilerik. Bu da bize bu ozellikleri verir ki, folder e aid olan attributelari cekek.  Attributelara \Inbox, \Sent, \Trash ve s gostermek olar. Bu attributelara esasen folderin eslinde hansi folder oldugunu teyin etmek olar.  Birinci if sertinde yazilan kodun izahi : Gmail da custom folder anlayishi olmadigina gore, bele bir kod yazmisham. Gmail da yalniz custom label anlayishi movcuddur. Label a ise mesaji move elemek olur. Bir nov her h...

compare two instants (month or other fields)

Duration duration = Duration.between(LocalDate.now().minusMonths(2).atStartOfDay().atZone(ZoneId.systemDefault()).toInstant(),Instant.now()); System.out.println(duration.toDays());

get file from message - JavaMail library

get bytes BASE64DecoderStream base64DecoderStream = (BASE64DecoderStream) obj; byte[] byteArray = IOUtils.toByteArray(base64DecoderStream); byte[] encodeBase64 = Base64.encodeBase64(byteArray); ========= return inputstream for download process Resource <= InputStreamResource return new InputStreamResource(part.getInputStream());

receiver mail from server - IMAP - Java

Ilk once bize host, port, username ve password lazimdir. Host ve port serverden asili olaraq deyishe biler. Hal-hazir ki, numune gmail uchundur. [ get file from message ]

Create cache with expire time

first use @EnableCaching annotation in your Main or configuration class import com.google.common.cache.CacheBuilder; import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; import org.springframework.cache.concurrent.ConcurrentMapCache; import org.springframework.cache.concurrent.ConcurrentMapCacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.concurrent.TimeUnit; @Configuration public class CachingConfig {     @Bean     public CacheManager cacheManager() {         return new ConcurrentMapCacheManager() {             @Override             protected Cache createConcurrentMapCache(String name) {                 return new ConcurrentMapCache(                         name, ...

send request with body - RestTemplate

HttpHeaders headers = new HttpHeaders();  headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);  MultiValueMap<String, String> data = new LinkedMultiValueMap<String, String>();  data.add("client_id",clientId);  data.add("client_secret",clientSecret);  data.add("grant_type",grantType);  data.add("redirect_uri",redirectUrl);  data.add("code",code.split("#")[0]);  HttpEntity<MultiValueMap<String, String>>  request = new HttpEntity<>(data, headers);  ResponseEntity<String> response = restTemplate.postForEntity(accessTokenUrl,request,String.class);

json to object - object to json methods

import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; public class JsonHelper {     public static String getJsonString(Object object) throws JsonProcessingException {         ObjectMapper mapper = new ObjectMapper();         mapper.registerModule(new JavaTimeModule());         mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);         return mapper.writeValueAsString(object);     }     public static <T> T getObjectFromJson(String json, Class<T> type) throws JsonProcessingException{         ObjectMapper mapper = new ObjectMapper();         mapper.registerModule(new JavaTimeModule());         mapper.disable(SerializationFe...

oauth/token request manual

ResponseEntity<String> response = null; RestTemplate restTemplate = new RestTemplate(); String credentials = "clientId:clientSecret"; String encodedCredentials = new String(Base64.encodeBase64(credentials.getBytes())); //        System.out.println(username); HttpHeaders headers = new HttpHeaders(); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); headers.add("Authorization", "Basic " + encodedCredentials); HttpEntity<String> request = new HttpEntity<String>(headers); String accessTokenUrl = "http://localhost:8080/api/oauth/token" + "?grant_type=password" +         "&username=username" +         "&password=password" +         "&scope=read write"; response = restTemplate.exchange(accessTokenUrl, HttpMethod.POST, request, String.class); //        System.out.println(response.getBody().split(",...