Sunday, 29 December 2019

This week 3/2019 - WebApp with Spring Security

Yesterday I did small exercise. I upgraded one of my old applications from xml (web.xml) configuration to class version as a first step to later upgrading.
There was no problems until I run application and all world could see everything what only an authorized user should see.

I couldn't find simple example which I could I adopt to my needs so I decided to describe this by my self.

Some examples proposed to extend AbstractSecurityWebApplicationInitializer, other proposed to import just import security configuration but it wasn't work as I expected. I created servlet initializer as below.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class StockDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

  @Override
  protected Class<?>[] getRootConfigClasses() {
    return new Class<?>[]{MySecurityConfig.class, MyRootConfig.class};
  }

  @Override
  protected Class<?>[] getServletConfigClasses() {
    return new Class<?>[]{MyServletConfig.class};
  }

  @Override
  protected String[] getServletMappings() {
    return new String[]{"/"};
  }

  protected Filter[] getServletFilters() {
    return new Filter[]{new DelegatingFilterProxy("springSecurityFilterChain")};
  }

}


MySecurityConfig I extended with WebSecurityConfigurerAdapter and implemented configure method as below:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
@EnableWebSecurity
@Configuration
@ComponentScan("org.my")
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  private final MyLogoutSuccessHandler myLogoutSuccessHandler;
  private final MyAuthenticationProviderImpl myAuthenticationProvider;

  public SecurityConfig(final MyLogoutSuccessHandler myLogoutSuccessHandler,
                        final MyAuthenticationProviderImpl myAuthenticationProvider) {
    this.myLogoutSuccessHandler = myLogoutSuccessHandler;
    this.myAuthenticationProvider = myAuthenticationProvider;
  }


  @Autowired
  public void configureGlobal(final AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(myAuthenticationProvider);
  }

  @Override
  public void configure(final WebSecurity web) {
    web.ignoring()
       .antMatchers("/css/**")
       .antMatchers("/img/**");
  }


  @Override
  protected void configure(final HttpSecurity http) throws Exception {
    formLogin(http);
    logout(http);
    headers(http);
    authorizeRequests(http);
    sessionManagement(http);
  }
.......
}


MyServletConfig looks like


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
@EnableWebMvc
@Configuration
@ComponentScan({"org.**.mvc"})
public class StockServletConfig implements WebMvcConfigurer {

  @Override
  public void addResourceHandlers(final ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/img/**").addResourceLocations("/img/");
    registry.addResourceHandler("/css/**").addResourceLocations("/css/");
  }

  @Bean
  ViewResolver viewResolver() {
    return new InternalResourceViewResolver("/WEB-INF/jsp/", ".jsp");
  }

  @Bean
  PropertiesFactoryBean propertiesFactoryBean() {
    final PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
    propertiesFactoryBean.setLocation(new ClassPathResource("version.properties"));
    return propertiesFactoryBean;
  }

  @Bean
  ObjectMapper customObjectMapper() {
    return new CustomObjectMapper();
  }

  @Bean
  LocaleResolver localeResolver() {
    final SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver();
    sessionLocaleResolver.setDefaultLocale(ENGLISH);
    return sessionLocaleResolver;
  }

  @Bean
  public LocaleChangeInterceptor localeChangeInterceptor() {
    final LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
    localeChangeInterceptor.setParamName("lang");
    return localeChangeInterceptor;
  }

  @Override
  public void addInterceptors(final InterceptorRegistry registry) {
    registry.addInterceptor(localeChangeInterceptor());
  }

  @Override
  public void configureMessageConverters(final List<HttpMessageConverter<?>> messageConverters) {
    messageConverters.add(new MappingJackson2HttpMessageConverter(customObjectMapper()));
  }
}


Now I am analysing MyServletConfig and it is possible to do it other way - by adding some specific interceptor. Nevertheless current solution works:)

Any other better ideas ???

--
I used in example Spring/Spring Security 5.2.1 and Apache Tomcat 8.5.50

Wednesday, 25 December 2019

This week 2/2019 - Spring Integration


This is my first meet with Spring Integration. I started with version 4.3 so I will not mention of older version which I don't know.
For whom who don't know what is it Spring Integration. In a nutshell, this is a framework to create flows between betweens input adapters and endpoints.

In a short story I describe what I'd like to reach.

I've got some configuration in XML version which is included in to class version of configuration. I have as well test context (class version) which override some beens - adapters from/to external world). I'd like to translate this XML to have:
  • consistent configuration in production and test code,
  • to be able override production configuration of some adapters (ex. file adapters)
  • to use inline transformations (not included in example).
Below I added a sample of configuration for class version and commented out a equivalent XML code.



  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
@Configuration
//@ImportResource("/spring-int.xml")
@EnableIntegration
public class IntConfig {


//    <int:channel id="inChannel"/>

//    <int:transformer input-channel="inChannel"
//                     output-channel="srcEmailChannel"
//                     ref="inTransformer"/>
//    <bean id="inTransformer" class="PublisherTransformer"/>
//

    @Bean
    @Transformer(inputChannel = "inChannel", outputChannel = "srcEmailChannel")
    PublisherTransformer inTransformer() {
        return new PublisherTransformer();
    }

//    <int:channel id="srcEmailChannel">
//        <int:interceptors>
//            <int:wire-tap channel="backup"></int:wire-tap>
//        </int:interceptors>
//    </int:channel>


    @Bean
    public MessageChannel backup() {
        return new DirectChannel();
    }

    @Bean
    public MessageChannel srcEmailChannel() {
        final DirectChannel directChannel = new DirectChannel();
        directChannel.addInterceptor(new WireTap(backup()));
        return directChannel;
    }


//    <int:router input-channel="backup" expression="headers.country">
//        <int:mapping value="PL" channel="plChannel"/>
//        <int:mapping value="EN" channel="enChannel"/>
//    </int:router>

    @Bean
    @Router(inputChannel = "backup")
    public AbstractMessageRouter backupRouter() {
        HeaderValueRouter router = new HeaderValueRouter("country");
        router.setChannelMapping("PL", "plChannel");
        router.setChannelMapping("EN", "enChannel");
        return router;
    }


//    <int:channel id="plChannel"/>
//    <int-file:outbound-channel-adapter id="plChannelOutFile"
//                                       directory="/tmp/plChannel/"
//                                       channel="plChannel"
//                                       mode="APPEND"
//                                       charset="UTF-8"/>

    @Bean
    @ServiceActivator(inputChannel = "plChannel")
    MessageHandler plChannelOutFile() {
        final FileWritingMessageHandler fileWritingMessageHandler = 
                new FileWritingMessageHandler(new File("/tmp/plChannel/"));
        fileWritingMessageHandler.setCharset(UTF_8);
        fileWritingMessageHandler.setFileExistsMode(APPEND);
        fileWritingMessageHandler.setExpectReply(false);
        return fileWritingMessageHandler;
    }

//    <int:channel id="enChannel"/>
//    <int-file:outbound-channel-adapter  id="enChannelOutFile"
//                                        directory="/tmp/enChannel/"
//                                        channel="enChannel"
//                                        mode="APPEND"
//                                        filename-generator="fileGenerator"
//                                        charset="UTF-8"/>
//    <bean id="fileGenerator" class="FileNameGen"/>

    @Bean
    @ServiceActivator(inputChannel = "enChannel")
    MessageHandler enChannelOutFile() {
        final FileWritingMessageHandler fileWritingMessageHandler = 
                new FileWritingMessageHandler(new File("/tmp/enChannel/"));
        fileWritingMessageHandler.setCharset(UTF_8);
        fileWritingMessageHandler.setFileExistsMode(APPEND);
        fileWritingMessageHandler.setExpectReply(false); // I don't need return
        fileWritingMessageHandler.setFileNameGenerator(new FileNameGen());
        return fileWritingMessageHandler;
    }


//    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"/>
      // this not complete mail server configutation
      @Bean
      MailSender mailSender() {       
          return new JavaMailSenderImpl();
      }
//
//
//    <int-mail:outbound-channel-adapter channel="srcEmailChannel" mail-sender="mailSender"/>
    @Bean
    @ServiceActivator(inputChannel = "srcEmailChannel")
    MessageHandler messageHandler(MailSender mailSender) {
       return new MailSendingMessageHandler(mailSender);
    }
    @Bean
    PublisherService publisherService() {
        return new PublisherService();
    }
}

As you can see all of used channels must be defined manualy in XML version. In class version I defined only those which I'd like add some additional behaviour.

Is it true that in Java we can't change Spring Integration configuration with simple editor an restart applicaton - we need compile this configuration but we have plenty of possibilities to do.

Starting from version 5.0 there is additional implementation supporting mixed configuration in test, ex.
  • @SpringIntegrationTest
  • MockIntegrationContext
However this works in other way than overrding bean definition as I did it. This stops current MessageHandler lifecycle and replace condext with mocked bean.

In version 5 it was added as well DSL to make configuration more readable. More information in [1]


Sunday, 13 January 2019

This week 1/2019 - STM32 microcontroller

Today I'd like to write about my first experiences with STMicroelectronic. My set is Nucleo board with STM32F466RE chipset - 160Mhz with 512k flesh memory.
I started from looking for articles and YouTube tutorials about hardware platrorm. I didn't know difference between Raspberry PI and Andurino. I found a few interesting [in resources] and then I decided to buy STM32 hardware platform with at least 256kB flash memory.
Next step was to choose IDE. I'd like to use IntelliJ because daily I work in this IDE, unfortunately JetBrains has other tool with separate licence and not so popular as other IDEs. Finally I chosen Atollic TrueSTUDIO for STM32 9.2.0 especially it is supported by tool STM32Cube MX.
STM32Cube MX is a tool to generate project for selected IDE with C code initializing selected by developer modules and ports of STM32 processor.
To create and load first program on microchip we need to install compiler. I am using Linux system that's why I executed commands:
sudo apt-get install gcc-arm-none-eabi
sudo apt-get install binutils-arm-linux-gnueabi
sudo apt-get install libnewlib-arm-none-eabi
My hardware platform has integrated ST-link and storage where I can copy my binary file and load it automatically on my STM microchip. No additional tool needed.
At the beginning I used external libraries libopencm3 [5] with examples. However there is no tool to generate initializing methods like STM32Cube MX what it is useful at the beginning.
I watched presentation [10] and I was inspired to create code in C++. Bartosz convincing that C++ takes similar resources. In come cases is even much better then code from C compiler.


Till now I created following projects basing on examples:
  1. Change GPIO port state. Both sources of code have example of blinking LED. I used my own external LED to blink.
  2. Read GPIO port state. We can read state of each pin. For pin 1 it will be value 0 or 1, for pin 2 value 0 or 2 and so on. I closed selected pin with 3.3V source.
  3. Communicate via serial port USART. I get connected using ST-link integrated with nucleo board and by external ST-link module.
  4. Read system time. This operation looks different than in OS Linux system. We need to open timer module of chip and then we can read counter.
  5. Ethernet connection. I have Ethernet module with chip ENC28J60. I connected it to SPI connectors however I couldn't run it. :( After spend some time I found correct example and adopted it in my project [8]. It works fine. However I don't know why one request is processed 4 times. Maybe clock of buffer reader is too fast. I must check it.
  6. DAC - set voltage on output an modulate speaker.
  7. ADC - read voltage on input in range 0-3,3V.
  8. Store and read data from flash memory [9]. I have to change memory mapper file.


Resources:
  1. How to start
  2. STM32 tutorial
  3. List of useful links
  4. STM32 HAL layer - documentation
  5. Alternative library with examples - libopencm3
  6. STM32Cube MX tutorial
  7. Setting STM32 clock speed
  8. Ethernet module - ENC28J60
  9. Read/store data in memory
  10. Bartosz Szurgot - C++ vs C the embedded perspective 



Monday, 23 April 2018

This week 2/2018 - JavaFX

Long time I was looking for some solution to create simple desktop application. My previous choice was SWT and JFace but I was not satisfied because of its OS dependence and different presentation depending of OS. There were some other problems with windows resizing and tree view updating.
This time when I developed something for desktop, I was looking for something what is supported by all most famous IDE and is OS independent.

I've tried JavaFX and I think it was good choice. Even a few small problems which I list in the end of article.

JavaFX  it has to be successor of Swing library. It was initialized in the end of 2008 as external library. It was included to JDK only since JDK7 update 6. Since JDK8 is a standard part of JDK/JRE and uses the same version numbering. Most common Java IDEs include scene builder GUI. The output of this tool is a fxml file which is more less an equivalent of programmatic scene creation and is updated when fxml is updated. My experience with this GUI in IntelliJ on Linux was not ideal because sometimes of rendering problems but it is helpful tool for beginner and to arrange elements on scene.

The JavaFX thread needs to be run from class extending Application class. Then creation of stage, scene have to be in JavaFX thread. The same is with every action which changes view. To make change from other thread it is required to call async method:
Platform.runLater(Runnable runnable);

Stage (representing a window) and its elements (scene nodes) can be loaded from fxml file and coded in Java as well. Fxml file is a xml file loaded during stage building.
JavaFX allows defining css styles of formulas which can be used in fxml file and java code as well.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.CheckBox?>
<?import javafx.scene.control.Spinner?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.control.TreeView?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.Pane?>
<AnchorPane prefHeight="400.0" prefWidth="380.0" xmlns="http://javafx.com/javafx/8.0.121" xmlns:fx="http://javafx.com/fxml/1"
            fx:controller="example.TaskListController">
    <children>
        <TreeView fx:id="taskTree" layoutX="6.0" prefHeight="334.0" prefWidth="374.0" AnchorPane.bottomAnchor="65.0"
                  AnchorPane.leftAnchor="5.0" AnchorPane.rightAnchor="5.0" AnchorPane.topAnchor="5.0"/>
        <Pane layoutY="338.0" prefHeight="65.0" prefWidth="470.0" AnchorPane.bottomAnchor="0.0">
            <children>
                 <TextField fx:id="taskNameInput" layoutX="70.0" layoutY="1.0" prefHeight="26.0" prefWidth="392.0"
   style="-fx-padding: 0px; -fx-border-insets: 0px; -fx-background-insets: 0px; -fx-control-inner-background:#BBB; -fx-font-size: 10px;"/>
                <CheckBox fx:id="autoClose" selected="true" layoutX="7.0" layoutY="35.0" mnemonicParsing="false" text="auto close"/>
                <Button fx:id="updateButton" layoutX="294.0" layoutY="31.0" mnemonicParsing="false" onAction="#onTaskUpdate" text="update"/>
                <Spinner fx:id="positionSpinner" amountToStepBy="1" max="1000" min="0" prefHeight="26.0"  prefWidth="104.0"/>
                <CheckBox fx:id="moveCheck" layoutX="205.0" layoutY="35.0" mnemonicParsing="false" text="move" onAction="#onMove"/>
            </children>
        </Pane>
    </children>
</AnchorPane>

I don't remember how it was in Swing but JavaFX on every user action creates an event. This is handled by hierarchy of registered by programmer event handlers. Each event has source of event, target and type. Some events can be triggered by other event, ex they change state of observed element.

Another problem was, how to test it? Hopefully there is a TestFX. It resemble a little Selenium - it is possible to find element by xpath query and execute some action. I did only a few such tests and I know that this tool has some problems with dual-screens on linux. I have to turn off one monitor to resolve problem.


Below a few problems which I met:
1. I could set only one icon for all stages.
2. CheckboxTreeItem - chain of calls, I don't know who triggered event (user/previous element in chain)
3. On linux I can't play mp3. I found out that I must install some libraries and after that it doesn't work as well.



Sunday, 28 January 2018

This week 1/2018 - IntelliJ plugin

Hi Fellows,
this time I started year from creating a tool to automate my work. I always meet with problem of creating builder, mappers and some test data filling dto/vo for test purpose.
At the beginning I started from some simple examples of such plug-ins. Then I was looking for tutorial "how to start", what is concept and what are main interfaces, files, classes required to create plug-in. Unfortunately I didn't find any good for me tutorial with diagrams and main steps. Finally I had to experiment and iteratively find the solution. Now I know the main steps and I described them below in nutshell.


1. IntelliJ project - it is easy to create new plugin project, isn't it ?

2. Plug-in information stored in path META-INF/plugin.xml.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<idea-plugin>
    <id>example</id>
    <name>Builder plugin</name>
    <version>1.0</version>
    <actions>
        <action id="builderCreator" class="intellij.BuilderAction" text="Builder creator">
            <add-to-group group-id="GenerateGroup" anchor="last"/>
        </action>
    </actions>
</idea-plugin>

The most important part is to define action, where class is extension of AnAction abstract class.


2. Dependencies - we need at least a IntelliJ IDEA SDK - define it in project structure.

3. Class hierarchy - as I wrote above, in my case the main class of plugin is AnAction. Because of error connected with startTransaction problem I found some example where was used other class BaseCodeInsightAction. As I checked its parent class overwrite startInTransaction method. Anyway this extension add a few other function. I'd like to have list of classes with sublists of class fields. This works fine with MemberChooser class.
Panels and other elements are good know from Swing and AWT.

4. Artefacts - to create module jar, you just need to execute Build -> Prepare All Plugins Modules For Deployment.

5. Import project  - when I'd like to import my sources to new IntelliJ project I had  to in a hacky way change my project iml file. Type of module from JAVA

<module type="JAVA_MODULE" version="4">

to PLUGIN

<module type="PLUGIN_MODULE" version="4">

and check path to my plugin.xml

Project Structure -> Modules -> Plugin Deployment -> Path to META-INF/plugin.xml
 
I didn't make this project as maven project. I had some problems with maven dependencies and I didn't spend much time to resolve it.

Sunday, 3 December 2017

This week 14/2017 - Jollyday

Jollyday is a small library to get dates of holidays. 
When you open project documentation page, you can think that this project is dead. The sourceforge page wasn't updated for last 2 years. However when you check GitHub repository, it is still developed since 2010. When I write this blog the most fresh version for JDK8 is 0.5.2.

Jollyday handles fixed, related to day of month and religious holidays. To be more advanced, it handles additional rules to define moving free days related to holidays, ex when holiday is on Saturday, next Monday will be holiday as well.

Below there is piece US configuration file. The Jollyday jar file includes default configuration for 64 countries. Some of them include holidays changes in time in the past. Polish configuration doesn't.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
..
14
15
16
17
18
19
20
<tns:Configuration hierarchy="us" description="United States"
                   xmlns:tns="http://www.example.org/Holiday" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                   xsi:schemaLocation="http://www.example.org/Holiday/Holiday.xsd">
    <tns:Holidays>
        <tns:Fixed month="JANUARY" day="1" descriptionPropertiesKey="NEW_YEAR"/>
        <tns:Fixed month="JULY" day="4" validFrom="1776" descriptionPropertiesKey="INDEPENDENCE"/>
        <tns:Fixed month="NOVEMBER" day="11" validFrom="1938" descriptionPropertiesKey="VETERANS"/>
        <tns:Fixed month="DECEMBER" day="25" descriptionPropertiesKey="CHRISTMAS"/>
        <tns:Fixed month="MAY" day="30" validFrom="1869" validTo="1967" descriptionPropertiesKey="MEMORIAL"/>
        <tns:FixedWeekday which="LAST" weekday="MONDAY" month="MAY" validFrom="1968" descriptionPropertiesKey="MEMORIAL"/>
        <tns:FixedWeekday which="FIRST" weekday="MONDAY" month="SEPTEMBER" validFrom="1895" descriptionPropertiesKey="LABOUR_DAY"/>
        <tns:FixedWeekday which="FOURTH" weekday="THURSDAY" month="NOVEMBER" validFrom="1863" descriptionPropertiesKey="THANKSGIVING"/>
    </tns:Holidays>
....
    <tns:SubConfigurations hierarchy="la" description="Louisiana">
        <tns:Holidays>
            <tns:FixedWeekday which="THIRD" weekday="MONDAY" month="JANUARY" validFrom="1986" descriptionPropertiesKey="MARTIN_LUTHER_KING"/>
            <tns:ChristianHoliday type="GOOD_FRIDAY"/>
            <tns:ChristianHoliday type="MARDI_GRAS"/>
        </tns:Holidays>
    </tns:SubConfigurations>

The HolidayManager is main interface of Jollyday library. Below there is a piece of code which create HolidayManager instance for US using default configuration.

1
2
ManagerParameter params = ManagerParameters.create(Locale.US));
HolidayManager holidayManager = HolidayManager.getInstance(params);

If we'd like to get holidays for US we need to execute code as below.

1
holidayManager.getHolidays(2017)


If we'd like to get holidays for Louisiana in US we need to call code as below


1
holidayManager.getHolidays(2017, "la")

It is possible to create deeper hierarchy of calendar. You must only create sub-configuration for this node and call get Holidays with additional code - code of sub-configuration.

To use custom configuration, you need create ManagerParameters from URL where is configuration file available, ex


1
2
3
URL url = ClassLoader.getSystemResource("Holidays_pl.xml");
ManagerParameter params = ManagerParameters.create(url);
HolidayManager m = HolidayManager.getInstance(params);

Below I added a few example of most common usage of HolidayManager.

1
2
3
4
5
m.getHolidays(2017)
m.getHolidays(LocalDate.now(), LocalDate.now().plusYears(5))
m.isHoliday(LocalDate.now())
m.isHoliday(LocalDate.now(), "an")
m.isHoliday(LocalDate.now(), HolidayType.UNOFFICIAL_HOLIDAY)

For more demanding, it is possible to implement:
  • country specific HolidayManager
  • configuration data source
  • change implementation of parsers
Then you need create your own properties as below (default properties file)


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
manager.impl=de.jollyday.impl.DefaultHolidayManager
# Holiday manager for Japan implements some specific Japanese holiday rule.
manager.impl.jp=de.jollyday.impl.JapaneseHolidayManager
# Implementation class for holiday configurations
configuration.datasource.impl=de.jollyday.datasource.impl.XmlFileDataSource

# Configure the parsers to be used for each individual configuration type
parser.impl.de.jollyday.config.Fixed=de.jollyday.parser.impl.FixedParser
parser.impl.de.jollyday.config.FixedWeekdayInMonth=de.jollyday.parser.impl.FixedWeekdayInMonthParser
parser.impl.de.jollyday.config.IslamicHoliday=de.jollyday.parser.impl.IslamicHolidayParser
parser.impl.de.jollyday.config.ChristianHoliday=de.jollyday.parser.impl.ChristianHolidayParser
parser.impl.de.jollyday.config.RelativeToFixed=de.jollyday.parser.impl.RelativeToFixedParser
parser.impl.de.jollyday.config.RelativeToWeekdayInMonth=de.jollyday.parser.impl.RelativeToWeekdayInMonthParser
parser.impl.de.jollyday.config.FixedWeekdayBetweenFixed=de.jollyday.parser.impl.FixedWeekdayBetweenFixedParser
parser.impl.de.jollyday.config.FixedWeekdayRelativeToFixed=de.jollyday.parser.impl.FixedWeekdayRelativeToFixedParser
parser.impl.de.jollyday.config.EthiopianOrthodoxHoliday=de.jollyday.parser.impl.EthiopianOrthodoxHolidayParser
parser.impl.de.jollyday.config.RelativeToEasterSunday=de.jollyday.parser.impl.RelativeToEasterSundayParser

and setting VM options:

1
-Dde.jollyday.config.urls=file:/some/path/new.properties,http://myserver/some/path/further.properties,jar:file:myLibrary.jar!/my.properties  

I didn't find out if data source or parsers can be country specific and how to create your own parser.

Resources:
  1. jollyday.sourceforge.net
  2. github repository


Monday, 7 August 2017

This week 13/2017 (Hibernate)

I will write about few details connected with hibernate which are not commonly known.
  1. *Any
  2. Lazy loading - not working in all cases as expected
  3. Eager loading -  list collections
  4. @MapsId
  5. FetchMode and graphs
  6. Default constructor
  7. Final attributes


Ad 1. 
It is rarely to find @Any or @ManyToAny relation in code. However it is useful when it is need to create relation with many class's types. Table referring to many types should have additional column which defines a related type. 

1
2
3
4
5
6
@AnyMetaDef(name= "Vehicle", metaType = "string", idType = "int",
    metaValues = {
            @MetaValue(value = "C", targetEntity = Car.class),
            @MetaValue(value = "M", targetEntity = Motor.class)
    }
)

In this case in additional column are archived C and M - value of meta. Vehicle which is a interface for this two classes Car and Motor is used as a type in related entity. Principle of operation is similar to hardly typed relations.

Ad 2.
Lazy loading for relations @*ToOne not always works as it could be expected. Everything is connected with assumption that it is needed to know if relation with current entity is empty or not. When the key of relation is situated in coupled table, it is required to call additional query to check if that relation exists or not. If there is a relation hibernate creates proxy if not, it leaves null value. If we assume that entity has always related object it is possible to set attribute optional to false. In this case hibernate always creates proxy.
Other solution for this problem is to change table for relation key or manipulate with LazyToOne annotation and doesn't create proxy, what is not required.

Ad 3.
It is not common but sometimes I meet in entities that to keep collection some people use List. It is not recommended because some queries can receive multiplied instance of one row, especially it is common when it is used eager fetch mode.
In case when one entity has more then one eager list collection, we get javax.persistence.PersistenceException during start-up.


Ad 4.
@MapsId is an annotation which makes relation key of as primary key. It looks better in db, especially when entity has embedded key.

Ad 5.
JPA 2.1 introduce new feature - entity graph. This feature allows to change featch mode in runtime. One what is required, it is needed to define some path of connections between entities and use this definition in Query as a hint. This feature was available before JPA 2.1 but it wasn't standardized, so each implementation resolved it in other way.
Bellow some example.  

1
2
3
4
5
6
@NamedEntityGraphs({
        @NamedEntityGraph(name = "graph.Index.countrySymbols",
                attributeNodes = {@NamedAttributeNode(value = "country"), @NamedAttributeNode(value = "symbols")}),
        @NamedEntityGraph(name = "graph.Index.country",
                attributeNodes = {@NamedAttributeNode(value = "country")})
})

This part of code is added to class and then used by @Hint("graph.Index.countrySymbols") annotation.
You can find more [ref. 3]

Ad 6.
Hibernate requires default constructor (even private). Even using spring 4+ and Hibernate 5.2 I've got exception:
Caused by: org.hibernate.InstantiationException: No default constructor for entity: entity.Bill. 
It is a little strange for me because problem with instance creation, which was common for cglib, was resolved in Spring 4+ so I expected it should involve jpa entities as well.

Ad 7.
Hibernate ignores final type of variable in entity, especially it is noticeable when entity has defined some collection, initialised by the way of declaration. Chosen in declaration HashSet is replaced by hibernate implementation PersistentSet.

Resources:

  1. https://stackoverflow.com/questions/37282850/hibernate-org-hibernate-loader-multiplebagfetchexception-cannot-simultaneousl
  2. https://stackoverflow.com/questions/13334831/multiplebagfetchexception-thrown
  3. https://www.thoughts-on-java.org/jpa-21-entity-graph-part-1-named-entity/
  4. https://martinsdeveloperworld.wordpress.com/2014/07/02/using-namedentitygraph-to-load-jpa-entities-more-selectively-in-n1-scenarios/
  5. https://stackoverflow.com/questions/17987638/hibernate-one-to-one-lazy-loading-optional-false
  6. https://vladmihalcea.com/2016/07/26/the-best-way-to-map-a-onetoone-relationship-with-jpa-and-hibernate/