The Singapore Nationwide AWS LLM League 2024 concluded today with the grand finale at Raffle City Convention Center. The 5 finalists competed on stage for the top prizes including Amazon vouchers, Amazon Echo, and exclusive swags.
Each finalist, using their own finetuned Llama-3–8B model, answers a series of questions on Singapore culture. Their answers were then shared with a panel of 1 AI judge and a panel of 5 human judges for scoring. They were also shared with hundreds of live and virtual audiences for voting. Fan votes accounted for 20% of each answer’s final score while each AI and human panel contributed 40%.
This is a continuation from my previous article where we learned the basic of Selenium and how to program it in Python to perform UI automation testing.
Create a script that use ffmpeg to join video files then save the script and grant it necessary execute permission (on Mac and Linux). Make sure ffmpeg is on executable path, usually the $PATH or %PATH% variable
On Windows, you can use the below.
@echo off
setlocal enabledelayedexpansion
del concat.txt
rem Get the total number of parameters
set "totalParams=0"
for %%# in (%*) do set /a "totalParams += 1"
set /a "to_merge=%totalParams%-1"
echo There are a total of %to_merge% video to merge
rem Loop through all parameters except the last one
set "index=0"
set "outputfile="
for %%f in (%*) do (
set /a "index+=1"
if !index! neq %totalParams% (
set "F=%%f"
set "F=!F:\=/!"
set "F=!F:"=!"
echo file !F!
echo file !F! >> concat.txt
) else ( set "outputfile=%%f" )
)
echo output file %outputfile%
ffmpeg -safe 0 -f concat -i concat.txt -c copy %outputfile%
Assume the script is named concat.cmd, use the command concat.cmd <inputfile> <inputfile> <outputfile as the last argument> to join individual input files to a single output file. For example, to join 2 files video-1.mp4 and video-2.mp4 to a single combine.mp4, we type the following
Naive application of traditional software development methods (e.g. SADT or Structured Analysis and Design Technique), in the past, often resulted in a type of relationship where high-level modules depended on lower implementation details. This form of relationship often leads to rigidity, fragility, and immobility. These are the symptoms of bad design according to Robert C. Martin.
A naive application of top-down approaches can lead to bad design. Source: R.C.M paper
A chrome extension that automatically adds a comment while approving the request. Doing so cements the collaboration between the reviewer and the merge request’s submitter
The comment is defaulted to “LGTM” (Look Good to Me) and can be customized.
The extension works by replacing Gitlab’s “Approve” or “Approve Additionally” button with an upgraded button that adds a comment (e.g. “LGTM”) to the merge request while approving the request.
If you are going to build a house, a table, or a chair, what is your preferred option? The multiple tools on the first picture or one Swiss knife on the second?
Yep, you are right. If you want to create something useful that last for years, you need specialized tools. The same thinking applies to software development, if you want to create a serious application, you need specialized components represented by their own, purposely designed interfaces. The Interface Segregation Principle (ISP) is available to guide the creation of those interfaces.
Thailand comfortably beat Vietnam 1–0 on home soil to seal a 3–2 aggregate win and retain the crown for yet another 2 years. Theerathon Bunmathan was voted the most valuable player of the tournament.
What impressed me most about Theerathon was not his consistent and superb performance but what he said after the match. Theerathon reportedly said that he wanted VAR to be available in future AFF cups because all participating teams are neighbors and should improve their games together instead of committing faults or injuring each other.
Did you know that anyone in a Scrum team can be called a “developer”?
…developers, researchers, analysts, scientists, and other specialists do the work. We use the word “developers” in Scrum not to exclude, but to simplify. If you get value from Scrum, consider yourself included— The official Scrum Guides
We will, however, discuss this title in a more focused and traditional context in the following sections. Just bear in mind the strong association between the term “developer” and “agile” due not only to the agile movement but the nature of software development itself.
Your home for data science. A Medium publication sharing concepts, ideas and codes.
Followers: 652K (as of 17 Jan 2023)
Review: The most popular tech-oriented publication on Medium with huge followers on Medium, Twitter, and LinkedIn. If you write about data science or its related topics, this is one to apply for. Be prepared to submit your best writing as the submission guideline is comprehensive.
We started with unit testing, by developers, for their own codes. This is the easiest shift to implement, though it still takes time, effort, and patience to get it right. I recommend Pragmatic Unit Testing in Java 8 with JUnit if you want quickly level-up
You probably have heard of this popular fable before.
Mother Goat in her wisdom had carefully secured her house and her Kid before going out. She even reminded her Kid to check the password before opening the door. Her password was good. It was very long and contained non-alphabets and special characters.
As fate had it, a Wolf was nearby, he eavesdropped and learned of the mother’s password. He was so sure of filling his belly. He even mimicked the way mother Goat softly said her password
The Garuda team lost 0–2 to the Golden Dragon team on Monday, thus failing to reach the AFF Mitsubishi Electric Cup’s final. For a team from a football-crazed Indonesia, the loss was heartbreaking for many.
Some took to social media calling for the sacking of coach Shin Tae-Yong. The tag #STYOut has been trending among Indonesian fans. Some were calmer. They defended him. #STYSTAY has been trending as well. As of 11 Jan 2023, #STYSTAY appears to have an upper hand.
This is part of myFive Minimum Viable Interview Questions serieswhere I research and compile Five essential interview questions on each interview topic. All of these questions aim to assess real and practical skills expected at work
#1 — What is REST API?
This question assesses the breadth and depth of a candidate’s understanding of REST API concepts.
It was a tense match with both teams unable to score in front of about 50,000 spectators in Gelora Bung Karno Stadium. That is a huge turnout in a country severely affected by the Covid pandemic just 2 years ago.
They will meet again for the second leg on Monday at My Dinh stadium on Monday. Greeting the Indonesia team would be at least 30,000 home fans there.
Maven is the most popular build and dependency management system from the Apache Foundation.
If you plan to develop serious applications in Java or if you have just started to, you have better pick up Maven. I have just the resources for you below to learn about it and move from Beginner to Intermediate in no time.
Beginner tutorial
I often recommend Baeldung.com to my friends for beginner-level tutorials. They did it again here with this simple and easy-to-follow Maven tutorial
The title is loosely translated from a Vietnamese idiom
Bụt chùa nhà không thiêng
Literally translated, the idiom is about a Buddhist Saint (Vietnamese:bụt) prayed to in a pagoda (Vietnamese:chùa) close to or within the home (Vietnamese: nhà) being non-divine (Vietnamese:không thiêng)
Usages
The idiom has 2 common usages. One is a resignation that own advice, tool, resource, etc… was unsuccessful in helping a close friend, a loved one, or a fond organization achieves an objective. For example, when your favorite football team fails to win at home, you may say “Bụt chùa nhà không thiêng” to mean the home advantage and fan support were not successful in securing a win.
I am determined to become a writer. That does not mean forgoing my day job. Once back to work, I will be away from Medium for about 13 hours straights (8 AM to 9 PM). Writings only resume at night or during weekends.
I experienced some of that reality these past 2 weeks. I had cleared my annual leaves in early December to “avoid the crowd”, so I worked the last week of December while most colleagues were away. The work was not that heavy, but integrity forbade me from using company equipment and hours for my own side gig.
Sometimes web request fails, for whatever reason, and you need to retry it
Let’s simulate a failed request scenario in a unit test. In the below code, the webClient attempts to submit a GET request to /employee/100 (stored in constant PATH). We mocked the backend server to fail with common status codes such as BAD_REQUEST, UNAUTHORIZED and validate that the client throws WebClientResponseException upon receiving such statuses.
@ParameterizedTest@EnumSource(value=HttpStatus.class,mode=EnumSource.Mode.INCLUDE,names={"BAD_REQUEST","UNAUTHORIZED","FORBIDDEN","SERVICE_UNAVAILABLE","INTERNAL_SERVER_ERROR"})voidthrowExceptionWhenReceiveNon200Response(HttpStatusstatus)throwsInterruptedException{// request varwebClient=WebClient.builder().baseUrl(baseUrl).build();varrequest=webClient.get().uri(PATH).retrieve().bodyToMono(String.class);// response to first request with fail status mockBackEnd.enqueue(newMockResponse().setResponseCode(status.value()));// assert that exception thrown due to non-200 response varex=assertThrows(WebClientResponseException.class,()->request.block());assertEquals(status,ex.getStatusCode());// extra assert that the path is correct assertEquals(PATH,mockBackEnd.takeRequest().getPath());}
Retry unchanged
The easiest task is just retrying with the same request details.
35 years of Đổi Mới (Economic Reform) helped Vietnam from a country that had to “run for rice” (see note 1) in the early 1980s to become a middle-income country, reaching the top 20 of the world’s leading economies in terms of international trade. The Reform has turned many poor rural areas into industrial districts, farmers into city dwellers, the number of poor households has decreased sharply, the middle class has increased rapidly… But the Reform process also led to the “Reorder” among provinces and regions.
Many times when I visited Singapore, I noticed that under each apartment building, there were 2–3 red-painted drums in a straight line. These drums are modified with ventilation holes, have high legs, and have discharge doors… so that when households need to burn votive paper, they can do it here.
Incense burner (source: author’s father)
In a country where more than 70% of the population is Chinese with the tradition and custom of burning votive papers a lot every Lunar New Year, anniversaries, funerals, etc., along with propaganda, fines for violations, uniform arrangement of such burning places proved to be very effective, significantly limiting environmental pollution.
They are responsible for creating a nice visual and interactive experience such as greeting customers, arranging the tables, present the dishes — like what React or Angular codes do.
They will take your orders — like how HTML forms accept your inputs, auto-complete your sentences, or apologize that certain dishes aren’t available.
I’m a programmer by trade and write codes for a living. Then 1 month ago, I decided to become a writer. Here are the reasons why I did it and how I do it.
I’m pursuing my hobby
I never considered writing a hobby. I barely managed to pass my literature and English classes. I preferred subjects that did not require writing such as Mathematics, Chemistry, or Physics.
What is worth learning from the Lion island nation is, first of all, the strategic vision of development and the solution to turn that vision into reality.
The goal is to continuously improve people’s quality of life
From the perspective of urban development, Singapore is considered to have a very good level of urban planning and management. With an area only slightly larger than Vietnam’s Phu Quoc island, a population of 5.3 million people, most of the houses are high-rise apartment buildings… it is clear that Singapore is a case of “compression” of buildings on a narrow area.
In the physical world, a door closed is a closed door. In the software world, a closed entity may still be open for extension. And it should be so, according to the Open-closed principle (OCP).
There are 2 popular ways to apply this principle. We are going to discuss them both.
And a third option.
#1 — Inheritance
This is the original application of OCP. Bertrand Meyer, who introduced the term in his 1988 book Object-Oriented Software Construction, intended that:
It may be verbose, but you have total control over their placements, label, and format
<select><option>January</option><option>February</option><option>March</option><option>April</option><option>May</option><option>June</option><option>July</option><option>August</option><option>September</option><option>October</option><option>November</option><option>December</option></select> Month
<select><option>2021</option><option>2022</option><option>2023</option></select> Year
Option 2: use the browser’s built-in month picker
Built-in month picker
You have less control over the picker’s appearance, but the code is much cleaner. And localization support is free.
We know the saying “Jack of all trades, master of none”. We dislike it when we are at the receiving end. We dislike it too when it is said to someone we love. That should extend to things that we love too.
We developers love the codes we created. We are proud of the function we write, the class we design, the component, the system, and the microservices… we develop. We thus would not like it if they become “Jack of all trades, master of none”.
This is part of myFive Minimum Viable Interview Questions serieswhere I research and compile Five essential interview questions on each interview topic. All of these questions aim to assess real and practical skills expected at work
It is common nowadays for companies to hire for full-stack positions. A full-stack developer is typically expected to work on both frontend and backend development. That same expectation applies to interviews.
It is thus tough to interview or be interviewed for a full-stack position. There would be too many questions to ask or to prepare for. But if you are running out of time, here are five questions I think you should know.
There are 2 articles from https://vladmihalcea.com describing his analysis and solutions to Hibernate’s MultipleBagFetchException. The first one, appeared around 2020 (when I first researched this problem) or even earlier (2018?), offered an analysis of the problem and a solution using Hibernate’s EntityManager API. The second one appeared around Jun 2022, and offers a slightly different solution for JPA.
I will present below my understanding of his analysis, his solutions, and working sample codes which you can check out and validate your understanding and/or devise your own solutions.
The need for this library arose when I wanted assurance that my HTTP client was sending correctly formulated HTTP messages.
Another use of this /echo API is to capture and debug the remote calls from another service. Imagine you are providing a webhook endpoint. Before you even build one, you first need to know what incoming messages look like. Supplying an /echo API endpoint in the webhook’s registration allows you to capture and log all incoming messages
Java’s try-with-resource is a convenient syntactic shortcut. It frees developers from keeping track of closeable resources and closing in a finally block
Unit testing try-with-resource
Overview
Some of us may remember doing such boring and lengthy try-finally-if-not-null-close() A LOT!
On a typical day, we performed these steps a dozen times:
Obtained a DB connection, and execute a query within the try {...}
And then, to avoid connection leak, we must close the statement and DB connection within the finally {...} block.
Because getConnection(), prepareStatment() and executeQuery could fail, stmt and conn could be null . Hence we performed the not-null check prior to invoke close() methods.
I first learned method reference from C#, so the Java concept is familiar to me. Or that’s what I thought until I picked up the Modern Java Recipes book.
In this article, we’ll explore 3 forms of method references in Java
object::instanceMethod
Class::staticMethod
Class::instanceMethod
The last one is a bit more special, as we shall examine in detail
Source: author
object::instanceMethod
The object::instanceMethod will invoke the referenced method on the said object with compatible arguments. In the following example, the "hello " string’s concat method is invoked with arguments "a", "b", "c" resulting in "hello a", "hello b", "hello c" respectively
In all software development teams that I have been part of, we always value and encourage everyone to participate in code reviews. We see it as an effective way of learning and contributing. It has an important place in my Engineering practice.
We learn when we review other people’s codes. That’s actually an effective way of keeping up-to-date with what is happening to the code base, what sort of problems our colleagues are trying to solve, and what techniques they employed to solve them. Whether you are young or experienced, the delightful feeling of seeing creative solutions during code reviews is the same.
Since its introduction in Java 8, Stream has become more and more the preferred way of processing collection. But some of its APIs, are complicated and hard to understand, especially those of Collector and those for reduction.
I dare say that even experienced Java Stream users may still find them intimidating. Despite using it for several years and having prior experience with Stream-like operations in other programming languages, I still occasionally find some Stream-related tasks challenging.
Given a sentence comprising of one or multiple words separated by space (e.g. java, Hello World, aadsbbaba), return a sorted list of distinct characters excluding space
Solve this problem using Java Stream
Hint: Use String.split(“”)to split a string into a String[], then use String.charAt(0) to convert each single-char string to char
Discussion
This problem tests candidate’s knowledge of the following Stream methods:
Stream.of(...) or Array.stream(...) to convert an array of single-char string (e.g. from str.split("")) to Stream<String>
map(str -> str.charAt(0)) to convert String to Character. Note: while String.toCharArray can readily convert a String to an char[], turning the resulting array to a Character stream isn’t straightforward due to lack of built-in support for char type in Stream and Collection API. The Arrays.asList(str.toCharArray() or List.of(...) results in a List<char[]> instead
distinct() to keep only 1 instance of each encountered character
sorted() to sort the encountered characters in their natural order
collect(Collectors.toList()) to collect stream elements into a list
Sample Solution
A sample solution is shown below. In addition to above operations, we only utilize an extra filter(...) operation to discard spaces from getting into our response
Objective: Assess a candidate’s practical experience and knowledge
Instructions: Given the below controller, fill in Spring annotations according to instructions given in the code comments
Pay attention to:
Did the candidate notice the repetition of /friends prefix? Did he/she suggest a @RequestMapping(/friends) on the controller class instead?
How did he/she annotate the optional parameter name and id in findFriends(String name, Long id) method?
What annotation can be used to force a 204 (no content) response?
/* Assume all package, imports and dependency classes are available *//**
* A rest controller for Friend-related operations
*/publicclassFriendController{privatefinalFriendServicefriendService;publicFriendController(FriendServicefriendService){this.friendService=friendService;}/**
* Response to GET /friends/ request
* @param name (optional) filter by name
* @param id (optional) filter by id
* @return a list of friends
*/publicList<FriendDTO>findFriends(Stringname,Longid){if(id!=null){returnfriendService.findByFriendId(id);}elseif(StringUtils.hasText(name)){returnfriendService.findByName(name);}else{returnfriendService.findAll();}}/**
* Response to GET /friends/hello/{friend's name} request
* @param friend a friend's name
* @return a friendly Hello
*/publicStringhello(Stringfriend){returnString.format("Hello %s",friend);}/**
* Response to POST /friends/hello/{friend's name} request
* @param friend a friend's name which is to be saved
* @return a friendly Hello together with Id of the new friend
*/publicStringhelloAndSave(Stringfriend){FriendDTOdto=friendService.add(FriendDTO.builder().name(friend).createDt(LocalDateTime.now()).build());returnString.format("%s. Your Id is %d",hello(friend),dto.getId());}/**
* Un-friend
* Response to DELETE /friends/{friend's id} request,
* return 204 if successful
* @param friendId the id of the friend
*/publicvoiddeleteFriend(longfriendId){friendService.removeFriend(friendId);}/**
* Update friend name
* Response to <METHOD?> /friends/{friend's id}/{new name} request,
* return update friend info
* @param friendId the id of the friend
* @param newName the new name of the friend
* @return updated friend's info
*/publicFriendDTOupdateFriend(longfriendId,StringnewName){returnfriendService.updateName(friendId,newName);}}
Note 2024-08-15: An earlier version of this site ran on doks. I’m in the middle of updating it to a medium-like theme*
Introduction
You may have noticed that this website is using a powerful-yet-easy-to-use doks theme.
As I wanted to have more interaction with my readers, enabling comment is a first step.
Enable Comment in Hugo
Hugo provides built-in support for Disqus. It ships with a _internal/disqus.html template that we can simply copy & paste to wherever we want comment to appear. The steps are simple:
Default memory unit in Kubernetes is bytes, in addition to other shorter forms with one of supported suffixes: E, P, T, G, M, K, Ei, Pi, Ti, Gi, Mi, Ki.
For example: 128974848, 129e6, 129M , 123Mi
Have you ever wondered what do those suffixes mean?
If you’re using Spring or Spring Boot, then use the Spring @Transactional annotation, as it allows you to configure more attributes than the Java EE @Transactional annotation.
If you are using Java EE alone, and you deploy your application on a Java EE application server, then use the Java EE @Transactional annotation.
Sub CreateLinkToSheet()
Dim c As Range
For Each c In Selection
' MsgBox c.Value
ActiveSheet.Hyperlinks.Add Anchor:=c, Address:="", _
SubAddress:=c.Value & "!A1", TextToDisplay:=c.Value
Next c
End Sub
How to run: Select the cells to create link and run the macro
Here’s a scenario that illustrate above possibility
T1 | T2
1) setupState [A] | <- store state as a variable
| in bean instance [A]
| 2) setupState [A] <- [A] is free, so the container
| allocate it to serve T2 request
|
3) someLongRunMethod [A] | 3') aMethod [B] <- Because A is busy with T1,
another instance (B) is created
to serve T2 request. If aMethod
depends on previously setup state
it will encounter error
Prerequisite: Enable Developer tab, macro security and create “C:\mailattachment\” folder if not exists
Instruction: Select emails which have attachment to save (e.g. email containing daily report), select Developer, Macro, SaveAttachment
Sub SaveAttachment()
Dim myOlapp As Outlook.Application
Dim myNameSpace As Outlook.NameSpace
Dim myFolder As Outlook.MAPIFolder
Dim myItem As Outlook.MailItem
Dim myAttachment As Outlook.Attachment
Dim I As Long
Set myOlapp = CreateObject("Outlook.Application")
'Set myNameSpace = myOlapp.GetNamespace("MAPI")
'Set myFolder = myNameSpace.GetDefaultFolder(olFolderInbox)
'Set myFolder = myFolder.Folders("Ethsys")
'Set myFolder = myFolder.Folders("Ethsys Operation Alert")
'For Each myItem In myFolder.Items
'If myItem.Attachments.Count <> 0 Then
'For Each myAttachment In myItem.Attachments
'MsgBox myAttachment.FileName
'Next
'End If
'Next
For Each myItem In Application.ActiveExplorer.Selection
If myItem.Attachments.Count <> 0 Then
For Each myAttachment In myItem.Attachments
'MsgBox myAttachment.FileName
myAttachment.SaveAsFile ("C:\mailattachment\" & myAttachment.DisplayName)
Next
End If
Next
End Sub
#! /bin/bash
function list {
if [ -z $1 ]
then
echo list starting_dir [exclude_file_or_folder] [action_on_file]
exit 1
elif [ "$1" == "-help" ]
then
echo list starting_dir [exclude_file_or_folder] [action_on_file]
echo [exclude_file_or_folder]: use string that works with egrep e.g. ".jar|.log|.bak .jar|.log|.bak"
echo [action_on_file]: if specified, output listing will not be in ls -l format
exit 0
fi
local path=$1
if [ -z $2 ]
then
ls -al $path
else
ls -al $path | egrep -v $2
fi
for file in `ls -a $path`
do
if [ "$file" != "." ] && [ "$file" != ".." ] && [ -d "$path/$file" ]
then
file=`echo $file|grep -v $2`
if [ -z $file ]
then
echo "skipped" >> /dev/null
else
echo ============= $path/$file ================
list $path/$file $2 $3
fi
fi
done
}
list $1 $2 $3
Often, EXISTS and INNER JOIN can be used interchangeably to query data with existence in 2 or more tables. However, it is not always the case. There is an important inherent characteristics of INNER JOIN that every developer should keep in mind: INNER JOIN result may contain DUPLICATE data record. This is important for uniqueness-sensitive handling of query result (e.g. record count), or when migrating database table with unique constraints.
Below example is for Oracle DB, but adopting for other DBMS e.g. Sybase, MS SQL… should be straightforward.
select ‘both no space’ as “String comparison in Oracle” from dual where ‘a’ = ‘a’
--
union
select ‘right has single trailing space’ from dual where ‘a’ = ‘a ‘
union
select ‘right has multiple trailing space’ from dual where ‘a’ = ‘a ‘
union
select ‘right has single leading space’ from dual where ‘a’ = ‘ a’
union
select ‘right has multiple leading space’ from dual where ‘a’ = ‘ a’
--
union
select ‘left has single trailing space’ from dual where ‘a ‘ = ‘a’
union
select ‘left has multiple trailing space’ from dual where ‘a ‘ = ‘a’
union
select ‘left has single leading space’ from dual where ‘ a’ = ‘a’
union
select ‘left has multiple leading space’ from dual where ‘ a’ = ‘a’
--
union
select ‘right has single leading and trailing space’ from dual where ‘a’ = ‘ a ‘
union
select ‘right has multiple leading and trailing space’ from dual where ‘a’ = ‘ a ‘
union
select ‘left has single leading and trailing space’ from dual where ‘ a ‘ = ‘a’
union
select ‘left has multiple leading and trailing space’ from dual where ‘ a ‘ = ‘a’
—-
union
select ‘both has leading and trailing space but leading space are different’ from dual where ‘ a ‘ = ‘ a ‘
Wrong. Nowadays, many more malware infection are linked to visit to legitimate and popular websites than porn or counterfeit sites.
According to Cisco 2013 Annual Security Report, Business/Industry site category stands at 3rd position behind advertising and dynamic content categories in the top 20 dangerous website categories. Included are Shopping (8th), Travel (9th), News (13th). Porn or counterfeit products (e.g. cheap Viagra) didn’t make it to top 20.
This is a simple application of my previous post whereby you can develop your own validation rule and enforcer.
The significance of this application is the use of SelfValidate interface to enable bean to define its own validation method and validator to invoke bean’s method. Typically this constraint is apply to a type, but application on field is also possible.
Create a DAO method in which you set JDBC connection’s auto-commit property to false
dbConn.setAutoCommit(false);
Execute all your queries
stmt = dbConn.createStatement();
result = stmt.executeQuery(query);
stmt.executeUpdate(update);
Commit or rollback the transaction
dbConn.commit();
Reset auto-commit to true again for other execution
dbConn.setAutoCommit(true);
This is really simple, as it should be for something purely mechanical. The challenge for every programmer is how to write your transaction code or order your queries such that you can achieve desired result.
So far, we have learn the basic and a not-so-common nested usage of JSR 303 Bean Validation, it’s time to learn how the declarative validation rule was implemented. In another word, we will learn to create a custom constraint this this post.
Constraint Annotation
Custom constraint is a special kind of annotation that is itself annotated with @javax.validation.Constraint annotation. For example:
Following up from my previous post about JSR 303 – Bean Validation, we will see how to apply it to any nested property and how to display validation error on screen using Spring MVC’s JSP tags
1. Bean Validation on Nested Property
Recall that to validate any property, we only need to put a Constraint annotation on top of its declaration. Example of common constraints are @NotEmpty, @Pattern, @Email. One thing in common of these constraints are that the applied property has to be of type String.
JSR 303 – Bean Validation is defines a metadata model and API for JavaBean validation. The metadata is primarily in Annotation forms, with the possibility of being overridden or extended by XML descriptors. Hibernate Validator is the reference implementation of JSR 303.
The current version, as of August 2nd, 2012, of JSR303 is 1.0, and of Hibernate Validator version is 4.0.1.
1. Example
A straightforward use of Bean Validation is to document and specify validation rules on JavaBean’s properties. In the below example, it is easy to deduce that field manufacturer, licensePlate and seatCount are mandatory while note is not. In addition, licencePlate must contain at least 2 and at most 14 characters; seatCount must be equal or higher than 2.
Spring MVC’s SessionAttributes has 2 parameters: values (storing attributes’ names) and types (storing attributes’ types).
It’s pretty straightforward for values. You specify the name of your attribute and it is remembered.
It’s trickier for types. For example:
– @SessionAttributes (types= java.util.List.class) does not work!
– But @SessionAttributes (types= java.util.ArrayList.class) works (but not always)
The reason behind this peculiar behaviour is that Spring does exact matching of attribute’s type versus declared type, instead of assessing attribute object’s Is-A relationship.
But when my SAXParserFactory was correct and I still encountered XML parsing error for the sample code from Tiles’s website, it is really puzzling.
java.net.ConnectException: Tried all: '1' addresses, but could not connect over HTTP to server: 'tiles.apache.org', port: '80' at weblogic.net.http.HttpClient.openServer(HttpClient.java:312) ... at org.apache.commons.digester.Digester.createInputSourceFromURL(Digester.java:2072) at org.apache.commons.digester.Digester.resolveEntity(Digester.java:1725) at com.sun.org.apache.xerces.internal.util.EntityResolverWrapper.resolveEntity(EntityResolverWrapper.java:107) at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.resolveEntityAsPerStax(XMLEntityManager.java:1018) .. at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:107) ... at org.apache.commons.digester.Digester.parse(Digester.java:1887) at org.apache.tiles.definition.digester.DigesterDefinitionsReader.read(DigesterDefinitionsReader.java:267)
I no longer favor static over singleton as much as before. Static is convenient (sometimes very!), low memory footprint. But it does take away several Object-Orientation (OO) ’s strength. In addition, it couples your code to a specific implementation class. Singleton is less convenient (sometimes troublesome), slightly higher memory footprint, but it can deliver all OO’s strengths that static drops.
New Zealand cows are arriving by the boatload in Vietnam as part of an Israeli-led $500 million dairy farm project there.
Israeli company, SAE Afikim is helping Vietnam develop its dairy industry, in the largest project of its kind in the world.
In the largest project of its kind in the world and the biggest ever undertaken by an Israeli firm, 30,000 dairy cows are being flown to Vietnam to supply 300 million liters of milk annually as part of a $500 million dairy farm project there.
It really depends. If you hate storing object reference or passing it around, static is a excellent tool.
But remember: static method CANNOT be overridden by sub-classing, it’s only hidden. Refer to http://faq.javaranch.com/view?OverridingVsHiding for a simple explanation. (Side note: invoking a static method on a object reference only brings confusion, it’s the variable data type that determine which static method’s code will execute - remember: hidden, not overridden).
Since static method cannot be overridden, the polymorphism power of OOP is lost, and we fall back to the realm of procedural programming. Some even complain about the difficult of unit testing with static method.
“Without getting into too much detail, I can tell you some of what Sun did to create their various Java certification exams. So, in the old Sun days…
The whole process to create a new exam takes a long time. A first team of experts is assembled and for several months the team develops a new set of objectives. Once created, the new set of objectives go through all sorts of vetting / verification processes.
Framework: a set of ideas, principles, agreements, or rules that provides the basis or outline for something intended to be more fully developed at a later stage (MSN Dictionary)
Not sure if you agree, but for me, the above definition implies “consistency” as a essential effect of using a framework. In the context of software development, using a framework usually equals to following its design guideline, or implementing/extending its interfaces/base classes. Things can stuck or go wrong and time will definitely be wasted if you don’t.
The first article discusses the issues using US copyright law; the second is in the context of New Zealand. There are slight difference between the 2 laws with regard to Contractor/Customer relationship but the case of Employee/Employer is the same: without explicit agreement (contract), the Employer owns the source code.
I participated in an thread in Javaranche regarding why Arrays uses quicksort and Collections use merge sort (http://www.coderanch.com/t/520171/java/java/Why-Collections-sort-merge-sort). The thread starter claimed that quicksort is the best sort algorithm, for which I disagreed. I also replied with a link to wikipedia about merge sort performs better when the underlying datatype does not support random access (as does array). I thought that was the reason why Collections use merge sort: because a collection type such as LinkedList does not necessarily support random access.
In EJB 3, we can obtain a reference to Stateful Session Bean either either by using @EJB annotation or performing JNDI look-up. Yet these 2 methods do not offer you a way to initialize a Stateful SB as EJB 2.1 Home interface’s createMETHODs do.
StatefulSB bean = home.create (arg0, arg1, arg2);
EJB3 defines @Init annotation as a replacement for EJB 2.1 createMETHOD. But it is intended for bean written to 2.1 client view (that means you will need to define an home interface and annotate the bean class with @RemoteHome or @LocalHome annotations)
I have just wasted 1 whole day trying to debug this issues. Since I get most help from the internet, here is what I can do in return :D
I was trying to build a Spring 3.0 webapp with Tiles 2.2. Since Tiles depends on common-digester which subsequently depends on SAXParserFactory, I got stuck in a whole range of strange Weblogic behaviors.
Firstly, I got UnsupportedOperationException everytime I first access the webapp. Subsequent access is fine, but the first always encounters that exception. Hours of googling tells me that the exception is due to weblogic’s RegistrySAXParserFactory.
Tagfile is a good alternative for lazy people like me who hates doing java coding and XML configuration for simple task with lots of HTML codes.
But laziness knows no limit. Just now I ended up wasting haft a day on a recursive tagfile that would otherwise be completed within 1 hour at most. Yet it was an experience that’s worth sharing.
The tagfile is named catalogue.tag. Its purpose is to display recursively a hierarchy tree of catalogues..
That has been my challenge since yesterday. And I think I have just got it :D
Let’s see if I can reconstruct a step-by-step manual:
1. First of all, let have some understanding of the structure of a EAR file.
EAR stands for Enterprise ARchive. It’s a convenient mean to to pack and deploy components of an enterprise application. Essentially, you can pack WAR, EJB, Resource Adapter and supporting libraries inside a EAR file. Having them all in one place, as a single unit tremendously helps release management and deployment. But it does pose some challenges in the context of class-loading.
utils.CertGen: a certification generate tool provided by WLS. By default it will generate certificates from default CertGenCA.der and CertGenCAKey.der; but have not been able to generate certificate from other cert and key (probably because of the lack of original cert & key AND CertGenCA has constraint of max 1 descendant). Online renference: http://download.oracle.com/docs/cd/E13222_01/wls/docs103/admin_ref/utils.html#wp1198920
utils.ImportPrivateKey: a tool provided by WLS. Used to import certificate generated by CertGen to keystore as PrivateKey (normal keytool’s importcert store imported key as trustedCertEntry which is unsuitable for Identity & personal keystore)
Always try to optimize your program; performance is a big concern in any J2EE application.
Dont just follow what other people call best practices, they may not fit your need while being costly to implement.
J2EE application’s performance is often constraint by its interraction with database(s). Optimise your database access, data transaction management codes.