private <E> E getUpdatedObject(E oldItem, E newItem) { Gson gson = new Gson(); Type type = new TypeToken<E>() { }.getType(); E item = null; if (Objects.isNull(oldItem) && Objects.nonNull(newItem)) { item = newItem; } else if (Objects.nonNull(oldItem) && Objects.isNull(newItem)) { item = oldItem; } else { try { ObjectMapper objectMapper = new ObjectMapper(); String elements = gson.toJson(newItem, type); item = objectMapper.readerForUpdating(oldItem).readValue(elements); } catch (IOException e) { LOGGER.error("error updating object: {}", e); } } return item; }
Monday, January 13, 2020
Java Generics Example
Friday, February 8, 2019
Docker remove/compose and push an image
mvn clean install -DskipTests to build the executable jar file to be dockerized.
docker-compose.yml
version: "2"
services: camunda-demo: container_name: ordermanager build: context: ./ args: JAR_FILE: target/ordermanager-0.0.1-SNAPSHOT.jar PORT: 8080 dockerfile: Dockerfile image: mschassisdial/camunda-demo:dev ports: - 8080:8080 networks: - camunda-network networks: camunda-network: driver: bridge
Dockerfile
FROM openjdk:8-jdk VOLUME /tmp ARG JAR_FILEARG PORTARG CONFIGCOPY ${JAR_FILE} app.jar COPY ${CONFIG} config.properties ENTRYPOINT ["java","-jar","/app.jar"] EXPOSE ${PORT}
docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
mschassisdial/camunda-demo dev b1a0d11f8a8d 3 minutes ago 693MB
mschassisdial/external-service dev d496ef00abfd 2 hours ago 680MB
mschassisdial/ordermanager dev a37c119aa03c 2 hours ago 693MB
mschassisdial/external-service qa b85c41a54ef6 19 hours ago 680MB
mschassisdial/external-service <none> 748115d11fb6 20 hours ago 680MB
dialcamundabpm/ordermanager latest 1052ba8d4e08 20 hours ago 693MB
mschassisdial/camunda-demo qa 1052ba8d4e08 20 hours ago 693MB
mschassisdial/camunda-demo <none> a3e6620465b0 7 days ago 695MB
chown -R admin:admin .
docker image rm mschassisdial/camunda-demo:dev
docker-compose build
docker push mschassisdial/camunda-demo:dev
Thursday, February 7, 2019
Java Multithreading - Threadsafe Counter
https://stackoverflow.com/questions/29883719/java-multithreading-threadsafe-counter
The traditional way to achieve thread synchronization in Java is by the use of synchronized keyword. While it provides a certain basic synchronization, the synchronized keyword is quite rigid in its use. For example, a thread can take a lock only once. Synchronized blocks don’t offer any mechanism of a waiting queue and after the exit of one thread, any thread can take the lock. This could lead to starvation of resources for some other thread for a very long period of time.
Reentrant Locks are provided in Java to provide synchronization with greater flexibility.
The traditional way to achieve thread synchronization in Java is by the use of synchronized keyword. While it provides a certain basic synchronization, the synchronized keyword is quite rigid in its use. For example, a thread can take a lock only once. Synchronized blocks don’t offer any mechanism of a waiting queue and after the exit of one thread, any thread can take the lock. This could lead to starvation of resources for some other thread for a very long period of time.
Reentrant Locks are provided in Java to provide synchronization with greater flexibility.
What are Reentrant Locks?
The ReentrantLock class implements the Lock interface and provides
synchronization to methods while accessing shared resources. The code
which manipulates the shared resource is surrounded by calls to lock and
unlock method. This gives a lock to the current working thread and
blocks all other threads which are trying to take a lock on the shared
resource.public class ThreadsExample implements Runnable {
static int counter = 1; // a global counter
static ReentrantLock counterLock = new ReentrantLock(true); // enable fairness policy
static void incrementCounter(){
counterLock.lock();
// Always good practice to enclose locks in a try-finally block
try{
System.out.println(Thread.currentThread().getName() + ": " + counter);
counter++;
}finally{
counterLock.unlock();
}
}
@Override
public void run() {
while(counter<1000){
incrementCounter();
}
}
public static void main(String[] args) {
ThreadsExample te = new ThreadsExample();
Thread thread1 = new Thread(te);
Thread thread2 = new Thread(te);
thread1.start();
thread2.start();
}
}
Tuesday, February 5, 2019
Setting up a Home VPN Server Using Your Raspberry Pi
https://www.sitepoint.com/setting-up-a-home-vpn-using-your-raspberry-pi/
https://www.noip.com/support/knowledgebase/install-ip-duc-onto-raspberry-pi/
https://www.noip.com/support/knowledgebase/install-ip-duc-onto-raspberry-pi/
When are connections returned to the connection pool with Spring JPA (Hibernate) Entity Manager?
https://stackoverflow.com/questions/27486104/when-are-connections-returned-to-the-connection-pool-with-spring-jpa-hibernate
https://vladmihalcea.com/a-beginners-guide-to-transaction-isolation-levels-in-enterprise-java/
https://vladmihalcea.com/the-anatomy-of-connection-pooling/
Monday, January 28, 2019
Erase and Install firmware to Ruizu X02 MP3 player from Windows 7/10 Software
Hi Everyone,
Today I faced an issue of my Ruizu X02 Mp3 player malfunctioning due to a virus. It had Hungarian words in the welcome screen and it froze on that screen. So I decided to flash the player using the official firmware.
I searched in the internet and was able to find the http://www.ruizutek.com/manuals-firmware.html
site which contained the Ruizu X02 firmware.
Then I searched a software to flash the mp3 player from my windows 10 system. It took a while because some of the software were outdated and couldn't run on windows 10 as well as some of the software link locations returned 404.
Finally I found this http://www.sweetpeatoyco.com site to download a software called Audio Product Tool 1.03_01.
Then I followed this http://www.agptek.com/forum/viewtopic.php?f=103&p=68#p68 forum to install the firmware on X02. As I have learned this agptek site is the counter part of ruizu company in Europe. Ruizu is sold mainly in China.
That blog was written nicely and I was able to troubleshoot and install the firmware in X02 successfully.
First when I connected the player to usb slot using a usb cable software didn't detect my player. So I was so frustrated and almost gave up until I saw the 4th step.
It says,
Note:
If your player failed to be recognized or updated, please connect it to your computer the way below:
① For those player designed with soft power button:
Long press the power button to turn off the player
Plug the bigger end of the USB cable into the computer interface first
Then hold down the power button and plug the other end of the USB cable into the player at the same time.
I did exactly the same and tadaahh it detected my player.
It took around 10 mins to install so be patient until it shows successful installation.
Today I faced an issue of my Ruizu X02 Mp3 player malfunctioning due to a virus. It had Hungarian words in the welcome screen and it froze on that screen. So I decided to flash the player using the official firmware.
I searched in the internet and was able to find the http://www.ruizutek.com/manuals-firmware.html
site which contained the Ruizu X02 firmware.
Then I searched a software to flash the mp3 player from my windows 10 system. It took a while because some of the software were outdated and couldn't run on windows 10 as well as some of the software link locations returned 404.
Finally I found this http://www.sweetpeatoyco.com site to download a software called Audio Product Tool 1.03_01.
Then I followed this http://www.agptek.com/forum/viewtopic.php?f=103&p=68#p68 forum to install the firmware on X02. As I have learned this agptek site is the counter part of ruizu company in Europe. Ruizu is sold mainly in China.
That blog was written nicely and I was able to troubleshoot and install the firmware in X02 successfully.
First when I connected the player to usb slot using a usb cable software didn't detect my player. So I was so frustrated and almost gave up until I saw the 4th step.
It says,
Note:
If your player failed to be recognized or updated, please connect it to your computer the way below:
① For those player designed with soft power button:
Long press the power button to turn off the player
Plug the bigger end of the USB cable into the computer interface first
Then hold down the power button and plug the other end of the USB cable into the player at the same time.
I did exactly the same and tadaahh it detected my player.
It took around 10 mins to install so be patient until it shows successful installation.
Sunday, April 24, 2016
No Time Zone in java.util.Date
We can change the time zone of the local machine by changing the default timezone of the JVM like below.
TimeZone.setDefault(TimeZone.getTimeZone("NEW_TIME_ZONE");
A java.util.Date has no time zone†. It represents UTC/GMT (no time zone offset). Very confusing because its toString method applies the JVM's default time zone when generating a String representation.
Avoid j.u.Date
For this and many other reasons, you should avoid using the built-in java.util.Date & .Calendar & java.text.SimpleDateFormat. They are notoriously troublesome.Instead use the java.time package bundled with Java 8. These new classes are inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project. For Java 6 & 7, use the back-port project, ThreeTen-Backport. For Android, the adaptation of that back-port, ThreeTenABP. See Oracle Tutorial.
java.time
The java.time classes can represent a moment on the timeline in three ways:
- UTC (Instant)
- With an offset (OffsetDateTime with ZoneOffset)
- With a time zone (ZonedDateTime with ZoneId)
Instant
In java.time, the basic building block is Instant, a moment on the time line in UTC. Use Instantobjects for much of your business logic.Instant instant = Instant.now();OffsetDateTime
Apply an offset-from-UTC to adjust into some locality’s wall-clock time.
Apply a ZoneOffset to get an OffsetDateTime.ZoneOffset zoneOffset = ZoneOffset.of( "-04:00" ); OffsetDateTime odt = OffsetDateTime.ofInstant( instant , zoneOffset );
ZonedDateTime
Better is to apply a time zone, an offset plus the rules for handling anomalies such as Daylight Saving Time (DST).
Apply a ZoneId to an Instant to get a ZonedDateTime. Always specify a proper time zone name. Never use 3-4 abbreviations such as EST or IST that are neither unique nor standardized.ZoneId zoneId = ZoneId.of( "America/Montreal" ); ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
Formatted Strings
Call the toString method on any of these three classes to generate a String representing the date-time value in standard ISO 8601 format. The ZonedDateTime class extends standard format by appending the name of the time zone in brackets.
String outputInstant = instant.toString(); // Ex: 2011-12-03T10:15:30Z
String outputOdt = odt.toString(); // Ex: 2007-12-03T10:15:30+01:00
String outputZdt = zdt.toString(); // Ex: 2007-12-03T10:15:30+01:00[Europe/Paris]
For other formats use the DateTimeFormatter class. Generally best to let that class generate localized formats using the user’s expected human language and cultural norms. Or you can specify a particular format.
Joda-Time
While Joda-Time is still actively maintained, its makers have told us to migrate to java.time as soon as is convenient. I leave this section intact as a reference, but I suggest using the java.time section above instead.
In Joda-Time, a date-time object (DateTime) truly does know its assigned time zone. That means an offset from UTC and the rules and history of that time zone’s Daylight Saving Time (DST) and other such anomalies.
String input = "2014-01-02T03:04:05";
DateTimeZone timeZone = DateTimeZone.forID( "Asia/Kolkata" );
DateTime dateTimeIndia = new DateTime( input, timeZone );
DateTime dateTimeUtcGmt = dateTimeIndia.withZone( DateTimeZone.UTC );
Call the toString method to generate a String in ISO 8601 format.String output = dateTimeIndia.toString();
Joda-Time also offers rich capabilities for generating all kinds of other String formats.
If required, you can convert from Joda-Time DateTime to a java.util.Date.Java.util.Date date = dateTimeIndia.toDate();
Search StackOverflow for "joda date" to find many more examples, some quite detailed.
Subscribe to:
Posts (Atom)