Showing posts with label Java. Show all posts
If you would like to figure out week number in the month of your business date by using JodaTime in Java, please check below code snippet
Examples
- Week number in the month for business date of 2020-10-07 is 2
- Week number in the month for business date of 2020-10-21 is 4
LocalDate firstDayOfTheMonth = businessDate.dayOfMonth().withMinimumValue(); int weekOfMonth = Weeks.weeksBetween(firstDayOfTheMonth, businessDate.dayOfWeek().withMaximumValue().plusDays(1)).getWeeks();
New platform with IntelliJ Live Templates has been released! You can find it here IntelliJ Live Templates
CREATE TABLE MY_TABLE (
ID NUMERIC(19,0) NOT NULL,
STATUS NVARCHAR2(20) NOT NULL CHECK (STATUS IN ('OPEN', 'CLOSED'));
);
ALTER TABLE MY_TABLE ADD CONSTRAINT STATUS_VALIDATION CHECK (STATUS IN ('OPEN', 'CLOSED'));
Link to a ticket - https://youtrack.jetbrains.com/issue/DBE-10549
@Builder(builderMethodName = "mandatoryBuilder")
@ToString
public class MyClass {
private String name;
private String identifier;
public String getName() {
return name;
}
public String getIdentifier() {
return identifier;
}
public static MyClassBuilder builder(String identifier) {
return mandatoryBuilder().identifier(identifier);
}
}
Inside your .idea folder, change workspace.xml file add below property
<property name="dynamic.classpath" value="true" />
to
<component name="PropertiesComponent">
Last time I was working on migration of some code from Python into Java and I was trying to find a corresponding code in Java for a function called rstrip in Python. So, below you can see a code written in Python and solution written in Java produced of course using Guava.
icb_code.rstrip("0")
CharMatcher trailingZeroMatcher = CharMatcher.is('0'); String trimmedInput = trailingZeroMatcher.trimTrailingFrom(input);
I needed recently to create a case-insensitive map in Java to query it with keys which might be uppercase or lowercase. I thought that it should be somewhere some kind of solution already available for developers. I found a class called CaseInsensitiveMap in Apache Commons Collections package (https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/map/CaseInsensitiveMap.html) but unfortunately, I found later on that it does not support generics which was needed in my case, that's why I decided to go with a custom solution for that problem which might be found below.
Map<String, String> record = getRecord(); TreeMap<String, String> caseInsensitiveMap = new TreeMap<>getCaseInsensitiveComparator()); caseInsensitiveMap.putAll(record); protected Comparator<String> getCaseInsensitiveComparator() { return Comparator.nullsFirst(String.CASE_INSENSITIVE_ORDER); }
Last time I had a problem with how to split the incoming list of a type File, to get a map of list of files by FileType, which is a property of File class. The easiest way to achieve it? Reduce.
Input -> List<File> listOfFiles
Output -> Map<FileType, List<File>>
public Map<FileType, List<File>> splitFilesByFileType(List<File> listOfFiles) { return listOfFiles.stream() .reduce(new HashMap<>(), (filesByFileType, file) -> { FileType fileType = file.getFileType(); if (filesByFileType.containsKey(fileType)) { filesByFileType.get(fileType).add(file); } else { filesByFileType.putIfAbsent(fileType, Lists.newArrayList(file)); } return filesByFileType; }, (acc1, acc2) -> { acc1.putAll(acc2); return acc1; }); }
Last time I was thinking about one small feature which might be added into IntelliJ IDEA, that's why I created a task on their ticketing system, so hopefully, all of us might use it one day in the future.
It's just an idea of a new feature which is basically an additional safety check. So, when a developer runs SQL script in IntelliJ IDEA like 'DELETE FROM tableName', it might show up confirmation if a developer is really sure about dropping data from a database. This dialog box might show up eventually the amount of data to be deleted and environment which is going to be affected. I hope that this feature might save a lot of developer's lives.
Link to ticket https://youtrack.jetbrains.com/issue/DBE-6408
Do you still write those special if statements for enums like myEnum.equals(myEnum.TEST) ? If yes, I might be able to share with you a small tip how to avoid it! It will be very beneficial for you because of your code might express itself without a word! Moreover, you might avoid those imports of your enum fields in every class where the comparison is going to be defined by if statement. It will say you a lot of time in case of changing name of enum field.
For instance, for the example defined below, only what you need to do in your code is -> if (operation.isCount()) {...} instead of if (operations.equals(Operation.COUNTA)) {...}
Check this post on Medium.com -> Use enum utility methods in Java ! Avoid equals at all costs!
import org.apache.commons.lang3.EnumUtils; public enum Operation { COUNTA, SUM,
NA; public static Operation parse(String input) { Operation operation = EnumUtils.getEnum(Operation.class, input); if (operation == null) { return NA; } return operation; } public boolean isCount() { return this == COUNTA; } public boolean isSum() { return this == SUM; } public boolean isCountOrSum() { return this == COUNTA || this == SUM; } }
Last time I was looking for an explanation what this "Non-Blocking IO" means. It was hard to understand what it's not blocking and what exactly it does or does not. Moreover, I was trying to find information how this correlates with reactive programming in overall... and I found it! Please check article listed in References. Thanks Adam!
In an old approach called threaded blocking IO, we bound every new connection to a new socket and create a new thread to process the data. This means that there is a single open connection which is managed by the single thread. When a client requests a connection from the server socket it sends back a new socket to communicate with. Now multiple connections can be handled until the limit of the maximum number of threads is reached. Each thread requires memory allocation, so while the concurrent connection goes up, the performance of the server goes down.
Instead of binding the thread to a connection, a notification is sent when the data is ready to read from a buffer. NIO uses buffers instead of streams to read/write data because data is processed when it's already there, not when it's actually being received. With this mechanism, multiple connections can be handled by one thread. That's how finally no threads are blocked while waiting on the IO.
The thread is only responsible for reading the buffers when it's notified about the arrival of any new data. This mechanism is called the 'event loop'. Following that logic, lots of concurrent connections can be handled with just a couple of threads. That's why NIO-based servers are so awesome and serve as our first building blocks.
Reactive programming is about using asynchronous, non-blocking building blocks with a functional style of coding.
[1] Kotlindevelopment.com - Developers guide to Webflux
Would you like to compare properties of two, not related beans? Are you tired of using Comparable interface from Java ? You might use a class called DiffBuilder which is a part of Apache Commons !
Reference : [1] DiffBuilder - Apache Commons
How to remove duplicates in Java 8 using field or property ? We might use reduce!
List<MyClass> distinctByField = myList.stream().reduce(new ArrayList<>(), (List<MyClass> accumulator, MyClass myClass) -> { if (accumulator.stream().noneMatch(item -> item.getField().equals(myClass.getField()))) { accumulator.add(MyClass); } return accumulator; }, (acc1, acc2) -> { acc1.addAll(acc2); return acc1; });
Recently I was creating small distributed application called ClientBackend just for interview purpose. Solution consists of thee microservices :
- Client (received request from API Gateway and sends it to Backend)
- Backend (performs operation defined in request)
- Discovery (Spring Eureka)
- API Gateway (Spring Zuul)
- Java 8
- Spring Boot
- Hystrix
- Eureka
- Feign
- Zuul
- TypeOf
Sometimes asserting custom exception is difficult. Sometimes it's not, for instance when you are using AssertJ, it's very quite easy to achieve. In this post I would like to highlight how to achieve that using Hamcrest matcher.
Below you might find a BaseExceptionMatcher which can be easily extended for our needs. Let's assume that we have an exception with four properties like errorType, errorCode, status and description.
import com.my.package.ErrorCode; import com.my.package.ErrorType; import com.my.package.base.BaseException; import com.my.package.MessageType; import org.hamcrest.Description; import org.hamcrest.TypeSafeMatcher; import javax.ws.rs.core.Response; public abstract class BaseExceptionMatcher extends TypeSafeMatcher<BaseException> { protected ErrorType expectedErrorType; protected ErrorCode expectedErrorCode; protected Response.Status expectedStatus; protected String expectedDescription; public BaseExceptionMatcher(ErrorCode expectedErrorCode, Response.Status expectedStatus, ErrorType expectedErrorType, String expectedDescription) { this.expectedErrorCode = expectedErrorCode; this.expectedStatus = expectedStatus; this.expectedErrorType = expectedErrorType; this.expectedDescription = expectedDescription; } @Override protected boolean matchesSafely(BaseException item) { return item.getStatus().equals(expectedStatus) && item.getError().stream().allMatch(p -> p.getType().equals(expectedErrorType.name()) && p.getCode().equals(expectedErrorCode.name())) && item.getError().stream().allMatch(p -> p.getDescription().contains(expectedDescription)); } @Override public void describeTo(Description description) { description.appendText("Response status : ") .appendValue(expectedStatus.getReasonPhrase() + " (" + expectedStatus.getStatusCode() + ")") .appendText(" | ErrorType : ").appendValue(expectedErrorType.name()) .appendText(" | ErrorCode : ").appendValue(expectedErrorCode.name()) .appendText(" | Description : ").appendValue(expectedDescription); } @Override protected void describeMismatchSafely(BaseException item, Description mismatchDescription) { mismatchDescription.appendText("Exception contains response status : ") .appendValue(item.getStatus().getReasonPhrase() + "(" + item.getStatus().getStatusCode() + ")") .appendText(" | ErrorType : ").appendValue(getMessageType(item).getType()) .appendText(" | ErrorCode : ").appendValue(getMessageType(item).getCode()) .appendText(" | Description : ").appendValue(getMessageType(item).getDescription()); } private MessageType getMessageType(BaseException item) { return item.getError().stream().findFirst().orElseGet(() -> { MessageType messageType = new MessageType(); messageType.setType(ErrorType.APPLICATION.name()); messageType.setCode(ErrorCode.INTERNAL_SERVER_ERROR.name()); messageType.setDescription("Matcher Error"); return messageType; }); } }
import my.package.ErrorCode; import my.package.ErrorType; import my.package.BaseExceptionMatcher; import javax.ws.rs.core.Response; public class MyExceptionMatcher extends BaseExceptionMatcher { public MyExceptionMatcher(ErrorType expectedErrorType, ErrorCode expectedErrorCode, Response.Status expectedStatus, String expectedDescription) { super(expectedErrorCode, expectedStatus, expectedErrorType, expectedDescription); } }
@Rule public ExpectedException expectedException = ExpectedException.none();
public void testFailure() throws MyException { expectedException.expect(new MyExceptionMatcher(ErrorType.APPLICATION, ErrorCode.DOCUMENT_NOT_FOUND, Response.Status.NOT_FOUND, "Document not found")); //do smth to fail }
Last time I was describing how to enable Tomcat for projects maintained by Gradle in post with title called "IntelliJ with Tomcat and Gradle using Gretty plugin". The thing that I found recently even a better way to achieve that! Moreover this way is less invasive in terms of that you do not need to append any configuration to your gradle scripts! This better way is known as a Smart Tomcat! It is a plugin for IntelliJ which allow you to configure literally everything around your app if it should be run on Tomcat.
Smart Tomcat - IntelliJ IDEA Plugins
Last time I was looking for a way to convert a Map into a Map of List. In otherwise direction, I mean backward from value up to key. Below you might find an solution for that problem using of course main Java 8 components like stream, filter, grouping and mapping.
Map<String, String> input = new HashMap<>(); input.put("SHARK", null); input.put("DOG", "HOME"); input.put("CAT", "HOME"); input.put("TURTLE", "HOME"); input.put("RABBIT", "HOME"); input.put("LION", "NOT_HOME"); input.put("HIPPO", "NOT_HOME"); input.put("TIGER", "NOT_HOME"); input.put("ZEBRA", "NOT_HOME"); Map<String, List<String>> result = input.entrySet().stream() .filter(i -> i.getValue() != null) .collect(Collectors.groupingBy(i -> i.getValue(), Collectors.mapping(i -> i.getKey(), Collectors.toList())));
Results
Key : HOME with List of DOG, CAT, TURTLE and RABBIT
Key : NOT_HOME with List of LION, HIPPO, TIGER, ZEBRA
This time I would like to describe briefly how to enable Tomcat in debug & class reload mode on IntelliJ when project is built using Gradle using this time Gretty plugin [1].
1) Add below line to build.gradle after applied war plugin
apply from: 'https://raw.github.com/akhikhl/gretty/master/pluginScripts/gretty.plugin'
2) At the end of build.gradle add also below statement which allows us to reload classes in container in the fly after change made by you in IntelliJ
gretty {
managedClassReload = true
}
3) Add Remote item in IntelliJ [3]
4) Run project using below command line
gradle tomcatStartDebug --info
5) Pickup Remote item in IntelliJ and run it in debug mode
6) Place breakpoints and run the code to catch them
Reference :
[1] https://github.com/akhikhl/gretty
[2] Hot deployment in Gretty
[3] Adding Remote item in IntelliJ
As you can see Spring Integration posts are going to be continued! This time I would like to share with you small hint of code which will help you to route your message based on existing or not key Signature in your headers.
<int:router id="headerRouter" expression="headers.containsKey('Signature')" default-output-channel="processFurther"> <int:mapping value="false" channel="drop"/> <int:mapping value="true" channel="processFurther"/> </int:router>
References : [1] Spring Docs - Message Routing