DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Curious about the future of data-driven systems? Join our Data Engineering roundtable and learn how to build scalable data platforms.

Data Engineering: The industry has come a long way from organizing unstructured data to adopting today's modern data pipelines. See how.

Threat Detection: Learn core practices for managing security risks and vulnerabilities in your organization — don't regret those threats!

Managing API integrations: Assess your use case and needs — plus learn patterns for the design, build, and maintenance of your integrations.

Avatar

Michal Jastak

Software Developer at AIS.PL

Torun, PL

Joined Jun 2008

About

More than 10 years of experience in Enterprise Applications development, and Project Management (since June 2001). Specialties: Enterprise Applications, J2EE, J2SE, Spring Framework, Spring Security, Spring Webflow, JPA and JDBC, JMX, JAXB, JUnit; XML, XSLT and XSL-FO; HTML/CSS, Javascript, JSON, jQuery/jQuery UI; RDBMS (Oracle, SQL Server, MySQL), PL/SQL; UML; Mobile Applications, mostly in Objective-C targeted iPhone/iPad

Stats

Reputation: 76
Pageviews: 308.1K
Articles: 8
Comments: 7
  • Articles
  • Comments

Articles

article thumbnail
Spring MVC: HTTP Message Converter
Learn more about Spring MVC and the HTTP message converter.
October 18, 2019
· 16,812 Views · 3 Likes
article thumbnail
JDBC: Emulating a Sequence
See how to emulate a sequence.
August 21, 2019
· 9,775 Views · 1 Like
article thumbnail
Serialization Proxy Pattern Example
There are books, which change your life immensely. One of such books is "Effective Java" by Joshua Bloch. Below you may find small experiment, which was inspired by Chapter 11 of this book - "Serialization". Suppose that we have a class designed for inheritance, which is not Serializable itself, and has no parameterless constructor, like in this example: public class CumbersomePoint { private String name; private double x; private double y; protected CumbersomePoint(double x, double y, String name) { this.x = x; this.y = y; this.name = name; } public String getName() { return name; } public double getX() { return x; } public double getY() { return y; } ... } Now when we extend this class, for example in following way: public class ConvenientPoint extends CumbersomePoint implements Serializable { public ConvenientPoint(double x, double y, String name) { super(x, y, name); } ... } and try to serialize and then deserialize any of ConvenientPoint instances, we'll quickly encounter beautifulInvalidClassException, complaining that there is no valid constructor. Situation looks kinda hopeless, until you apply technique known as Serialization Proxy Pattern. We will start by adding to the ConvenientPoint class following inner class: private static class SerializationProxy implements Serializable { private String name; private double x; private double y; public SerializationProxy(ConvenientPoint point) { this.name = point.getName(); this.x = point.getX(); this.y = point.getY(); } private Object readResolve() { return new ConvenientPoint(x, y, name); } } The SerializationProxy class will represent the logical state of enclosing class instance. We will have to add also following method to ConvenientPoint class: private Object writeReplace() { return new SerializationProxy(this); } Now when the ConvenientPoint instance will be serialized, it will nominate its replacement, thanks to writeReplacemethod - SerializationProxy instance will be serialized instead of ConvenientPoint. From the other side, when SerializationProxy will be deserialized, readResolve method usage will nominate its replacement, being ConvenientPoint instance. As you see, we've made ConvenientPoint serializable, regardless of missing parameterless constructor of non-serializable parent class. One more remark, at the end of this post - if you want to protect against breaking class invariants, enforced by the constructor, you may add following method to class using Serialization Proxy Pattern (ConvenientPoint in our example): private void readObject(ObjectInputStream stream) throws InvalidObjectException { throw new InvalidObjectException("Use Serialization Proxy instead."); } It will prevent deserialization of the enclosing class.
June 17, 2014
· 17,141 Views
article thumbnail
@OneToOne With Shared Primary Key, Revisited
Take another look at @OneToOne with a shared primary key.
May 6, 2014
· 31,655 Views · 3 Likes
article thumbnail
JPA - Querydsl Projections
In my last post: JPA - Basic Projections - I've mentioned about two basic possibilities of building JPA Projections. This post brings you more examples, this time based on Querydsl framework. Note, that I'm referring Querydslversion 3.1.1 here. Reinvented constructor expressions Take a look at the following code:... import static com.blogspot.vardlokkur.domain.QEmployee.employee; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.beans.factory.annotation.Autowired; import com.blogspot.vardlokkur.domain.EmployeeNameProjection; import com.mysema.query.jpa.JPQLTemplates; import com.mysema.query.jpa.impl.JPAQuery; import com.mysema.query.types.ConstructorExpression; ... public class ConstructorExpressionExample { ... @PersistenceContext private EntityManager entityManager; @Autowired private JPQLTemplates jpqlTemplates; public void someMethod() { ... final List projections = new JPAQuery(entityManager, jpqlTemplates) .from(employee) .orderBy(employee.name.asc()) .list(ConstructorExpression.create(EmployeeNameProjection.class, employee.employeeId, employee.name)); ... } ... } The above Querydsl construction means: create new JPQL query [1][2], using employee as the data source, order the data using employee name [3], and return the list of EmployeeNameProjection, built using the 2-arg constructor called with employee ID and name [4]. This is very similar to the constructor expressions example from my previous post (JPA - Basic Projections), and leads to the following SQL query: select EMPLOYEE_ID, EMPLOYEE_NAME from EMPLOYEE order by EMPLOYEE_NAME asc As you see above, the main advantage comparing to the JPA constructor expressions is using Java class, instead of its name hard-coded in JPQL query. Even more reinvented constructor expressions Querydsl documentation [4] describes another way of using constructor expressions, requiring @QueryProjectionannotation and Query Type [1] usage for projection, see example below. Let's start with the projection class modification - note that I added @QueryProjection annotation on the class constructor. package com.blogspot.vardlokkur.domain; import java.io.Serializable; import javax.annotation.concurrent.Immutable; import com.mysema.query.annotations.QueryProjection; @Immutable public class EmployeeNameProjection implements Serializable { private final Long employeeId; private final String name; @QueryProjection public EmployeeNameProjection(Long employeeId, String name) { super(); this.employeeId = employeeId; this.name = name; } public Long getEmployeeId() { return employeeId; } public String getName() { return name; } } Now we may use modified projection class (and corresponding Query Type [1] ) in following way: ... import static com.blogspot.vardlokkur.domain.QEmployee.employee; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.beans.factory.annotation.Autowired; import com.blogspot.vardlokkur.domain.EmployeeNameProjection; import com.blogspot.vardlokkur.domain.QEmployeeNameProjection; import com.mysema.query.jpa.JPQLTemplates; import com.mysema.query.jpa.impl.JPAQuery; ... public class ConstructorExpressionExample { ... @PersistenceContext private EntityManager entityManager; @Autowired private JPQLTemplates jpqlTemplates; public void someMethod() { ... final List projections = new JPAQuery(entityManager, jpqlTemplates) .from(employee) .orderBy(employee.name.asc()) .list(new QEmployeeNameProjection(employee.employeeId, employee.name)); ... } ... } Which leads to SQL query: select EMPLOYEE_ID, EMPLOYEE_NAME from EMPLOYEE order by EMPLOYEE_NAME asc In fact, when you take a closer look at the Query Type [1] generated for EmployeeNameProjection(QEmployeeNameProjection), you will see it is some kind of "shortcut" for creating constructor expression the way described in first section of this post. Mapping projection Querydsl provides another way of building projections, using factories based on MappingProjection. package com.blogspot.vardlokkur.domain; import static com.blogspot.vardlokkur.domain.QEmployee.employee; import com.mysema.query.Tuple; import com.mysema.query.types.MappingProjection; public class EmployeeNameProjectionFactory extends MappingProjection { public EmployeeNameProjectionFactory() { super(EmployeeNameProjection.class, employee.employeeId, employee.name); } @Override protected EmployeeNameProjection map(Tuple row) { return new EmployeeNameProjection(row.get(employee.employeeId), row.get(employee.name)); } } The above class is a simple factory creating EmployeeNameProjection instances using employee ID and name. Note that the factory constructor defines which employee properties will be used for building the projection, and mapmethod defines how the instances will be created. Below you may find an example of using the factory: ... import static com.blogspot.vardlokkur.domain.QEmployee.employee; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.beans.factory.annotation.Autowired; import com.blogspot.vardlokkur.domain.EmployeeNameProjection; import com.blogspot.vardlokkur.domain.EmployeeNameProjectionFactory import com.mysema.query.jpa.JPQLTemplates; import com.mysema.query.jpa.impl.JPAQuery; ... public class MappingProjectionExample { ... @PersistenceContext private EntityManager entityManager; @Autowired private JPQLTemplates jpqlTemplates; public void someMethod() { ... final List projections = new JPAQuery(entityManager, jpqlTemplates) .from(employee) .orderBy(employee.name.asc()) .list(new EmployeeNameProjectionFactory()); .... } ... } As you see, the one and only difference here, comparing to constructor expression examples, is the list method call. Above example leads again to the very simple SQL query: select EMPLOYEE_ID, EMPLOYEE_NAME from EMPLOYEE order by EMPLOYEE_NAME asc Building projections this way is much more powerful, and doesn't require existence of n-arg projection constructor. QBean based projection (JavaBeans strike again) There is at least one more possibility of creating projection with Querydsl - QBean based - in this case we build the result list using: ... .list(Projections.bean(EmployeeNameProjection.class, employee.employeeId, employee.name)) This way requires EmployeeNameProjection class to follow JavaBean conventions, which is not always desired in application. Use it if you want, but you have been warned ;) Few links for the dessert Using Query Types Querying Ordering Constructor projections
May 15, 2013
· 38,095 Views · 3 Likes
article thumbnail
FindBugs and JSR-305
Suppose that group of developers work in parallel on parts of big project - some developers are working on service implementation, while others are working on code using this service. Both groups agreed on service API, and started working separately, having in mind the API assumptions... Do you think this story will have happy end? Well, ... - maybe :) - there are tools which can help achieve it :) - one of them is FindBugs, supported with JSR-305 (annotations for software defect detection). Let's take a look at the service API contract: package com.blogspot.vardlokkur.services; import java.util.List; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import com.blogspot.vardlokkur.entities.domain.Employer; /** * Defines the API contract for the employer service. * * @author Warlock * @since 1.0 */ public interface EmployerService { /** * @param identifier the employer's identifier * @return the employer having specified {@code identifier}, {@code null} if not found */ @CheckForNull Employer withId(@Nonnull Long identifier); /** * @param specification defines which employers should be returned * @return the list of employers matching specification */ @Nonnull List thatAre(@Nonnull Specification specification); } As you see there are annotations like @Nonnull or @CheckForNull added to the service method signatures. The purpose of their usage is to define the requirements for the method parameters (ex. identifier parameter cannot be null), and the expectations for the values returned by methods (ex. service method result can be null and you should check it in your code). So what? - you may ask - should I check them in the code by myself or trust the co-workers that they will use the guidelines defined by those annotations? Of course not :) - trust no one, use the tools which will verify the API assumptions, like FindBugs. Suppose that we have following service API usage: package com.blogspot.vardlokkur.test; import org.junit.Before; import org.junit.Test; import com.blogspot.vardlokkur.services.EmployerService; import com.blogspot.vardlokkur.services.impl.DefaultEmployerService; /** * Employer service test. * * @author Warlock * @since 1.0 */ public class EmployerServiceTest { private EmployerService employers; @Before public void before() { employers = new DefaultEmployerService(); } @Test public void test01() { Long identifier = null; employers.withId(identifier); } @Test public void test02() { employers.withId(Long.valueOf(1L)).getBusinessName(); } @Test public void test03() { employers.thatAre(null); } } Let's try to verify the code against the service API assumptions: FindBugs will analyze your code, and switch to the FindBugs perspective showing potential problems: Null passed for nonnull parameter Possible null pointer dereference Similar way, guys writing the service code may verify their work against defined API assumptions, for ex. if you run FindBugs for the very early version of service implementation: package com.blogspot.vardlokkur.services.impl; import java.util.List; import com.blogspot.vardlokkur.entities.domain.Employer; import com.blogspot.vardlokkur.services.EmployerService; import com.blogspot.vardlokkur.services.Specification; /** * Default implementation of {@link EmployerService}. * * @author Warlock * @since 1.0 */ public class DefaultEmployerService implements EmployerService { /** * {@inheritDoc} */ public Employer withId(Long identifier) { return null; } /** * {@inheritDoc} */ public List thatAre(Specification specification) { return null; } } Following error will be found: As you see, nothing can hide from the FindBugs and his ally - JSR-305 ;) Few links for the dessert: JSR-305: Annotations for Software Defect Detection JSR 305: a silver bullet or not a bullet at all?
August 30, 2012
· 19,985 Views
article thumbnail
Suppressing FindBugs Warnings
A few days ago I spoke with my friend, Tomek, about suppressing FindBugs warnings. Here is brief summary of our conversation, which may be interesting for you. There is one simple method for suppressing the FindBugs warnings - usage of edu.umd.cs.findbugs.annotations.SuppressWarnings annotation. Just add it in the place where FindBugs reported problem, and use the appropriate bug code. You should start by adding com.google.code.findbugs:annotations:2.0.0 jar to the project dependencies. Then open the bug reported by FindBugs, and find its code, like in this example: Finally add something like this to the method holding the code marked by FindBugs: That's all, clear the FindBugs markers, and run it again, the problem will not be reported in this place again. Nice! Isn't it? - No, it isn't :( - Why you may ask? - Because there is another annotation in java.lang package with exactly the same name (!), used for suppressing different kind of warnings. Shouldn't it be used instead? - Well ... Another question is if we want to add another jar to the project dependencies just for suppressing FindBugs warnings - thank God the FindBugs authors marked this annotation with retention policy 'CLASS', which means the jar will not be required when running the project (ex. in web application container).
March 24, 2012
· 30,872 Views
article thumbnail
Spring MVC - Flash Attributes
The latest incarnation of the Spring Framework (3.1) brought an interesting feature called Flash Attributes. It is a remedy for the problem mentioned a long time ago, in one of my posts: Spring MVC - Session Attributes handling. This problem can be described in few words: if we want to pass the attributes via redirect between two controllers, we cannot use request attributes (they will not survive the redirect), and we cannot use Spring's @SessionAttributes (because of the way Spring handles it), only an ordinary HttpSession can be used, which is not very convenient. Below you will find an example of Flash Attributes usage, before you start reviewing it, read Using flash attributes section of Spring documentation. Suppose that we have two controllers: AController and BController, first one will prepare some data and pass to the second using Flash Attributes after the form submission. On the AController we will have something like this: @RequestMapping(method = RequestMethod.POST) public String handleFormSubmission(..., final RedirectAttributes redirectAttrs) { ... redirectAttrs.addFlashAttribute("AttributeName", value); return "redirect:to_some_url_handled_by_BController"; } When the form will be submitted, attribute value will be stored as Flash Attribute named "AttributeName", and thanks to the Spring, will be passed to BController, where it can be used for example in following way: @Controller ... @SessionAttributes("AttributeName") public class SearchCriteriaHandler { ... @RequestMapping(method = RequestMethod.GET) public void handleGetRequest(@ModelAttribute("AttributeName") final SomeType value) { ... } ... } Before your handler method will be called, Spring Framework will populate the Model with the available Flash Attributes - at this point value passed from AController will become a model attribute for the BController. Note, that because we also defined this attribute as the Session Attribute, it will be automatically stored for future usage within this controller, after the GET request handling. Let me say that I was waiting for this feature for the long time, ;)
March 22, 2012
· 52,662 Views · 2 Likes

Comments

Fortress - programming for supercomputers

Apr 02, 2012 · ldz

Fabrizio,

I'm glad that someone has left such a valuable comment on my modest post :). You are right that, marking SuppressWarnings annotation with SOURCE retention is something unbelievable :(, and harming potential tools like FindBugs. Anyway, don't you think that using by FindBugs annotation having exactly the same short name as the one already existing in JDK is something misleading? Imagine, that one day I introduce String class in my own Java library, having different meaning than the original one (coming from JDK) ... I know that we will probably not be able to avoid all such cases, but maybe it's worth trying ;)

It's interesting that tools like PMD, can work with the original SuppressWarnings annotation, even if it has this unfortunate retention type, but PMD works probably in a little different way than FindBugs.

You are right that even RUNTIME retention doesn't require the jar itself, as long as the classes coming from it are not referenced directly, ex. if you have class A annotated with annotation B coming from some jar, and you don't include this jar in runtime classpath, using A.class.getAnnotation(B.class) will cause an error as expected (because class B is not available on classpath), while A.class.getAnnotations() will silently ignore B in this case

We do learn our whole life :) - and thanks to your comment I'm a little more experienced developer now, thank you

Regards

Suppressing FindBugs Warnings

Apr 02, 2012 · James Sugrue

Fabrizio,

I'm glad that someone has left such a valuable comment on my modest post :). You are right that, marking SuppressWarnings annotation with SOURCE retention is something unbelievable :(, and harming potential tools like FindBugs. Anyway, don't you think that using by FindBugs annotation having exactly the same short name as the one already existing in JDK is something misleading? Imagine, that one day I introduce String class in my own Java library, having different meaning than the original one (coming from JDK) ... I know that we will probably not be able to avoid all such cases, but maybe it's worth trying ;)

It's interesting that tools like PMD, can work with the original SuppressWarnings annotation, even if it has this unfortunate retention type, but PMD works probably in a little different way than FindBugs.

You are right that even RUNTIME retention doesn't require the jar itself, as long as the classes coming from it are not referenced directly, ex. if you have class A annotated with annotation B coming from some jar, and you don't include this jar in runtime classpath, using A.class.getAnnotation(B.class) will cause an error as expected (because class B is not available on classpath), while A.class.getAnnotations() will silently ignore B in this case

We do learn our whole life :) - and thanks to your comment I'm a little more experienced developer now, thank you

Regards

Suppressing FindBugs Warnings

Apr 02, 2012 · James Sugrue

Fabrizio,

I'm glad that someone has left such a valuable comment on my modest post :). You are right that, marking SuppressWarnings annotation with SOURCE retention is something unbelievable :(, and harming potential tools like FindBugs. Anyway, don't you think that using by FindBugs annotation having exactly the same short name as the one already existing in JDK is something misleading? Imagine, that one day I introduce String class in my own Java library, having different meaning than the original one (coming from JDK) ... I know that we will probably not be able to avoid all such cases, but maybe it's worth trying ;)

It's interesting that tools like PMD, can work with the original SuppressWarnings annotation, even if it has this unfortunate retention type, but PMD works probably in a little different way than FindBugs.

You are right that even RUNTIME retention doesn't require the jar itself, as long as the classes coming from it are not referenced directly, ex. if you have class A annotated with annotation B coming from some jar, and you don't include this jar in runtime classpath, using A.class.getAnnotation(B.class) will cause an error as expected (because class B is not available on classpath), while A.class.getAnnotations() will silently ignore B in this case

We do learn our whole life :) - and thanks to your comment I'm a little more experienced developer now, thank you

Regards

Fortress - programming for supercomputers

Apr 02, 2012 · ldz

Fabrizio,

I'm glad that someone has left such a valuable comment on my modest post :). You are right that, marking SuppressWarnings annotation with SOURCE retention is something unbelievable :(, and harming potential tools like FindBugs. Anyway, don't you think that using by FindBugs annotation having exactly the same short name as the one already existing in JDK is something misleading? Imagine, that one day I introduce String class in my own Java library, having different meaning than the original one (coming from JDK) ... I know that we will probably not be able to avoid all such cases, but maybe it's worth trying ;)

It's interesting that tools like PMD, can work with the original SuppressWarnings annotation, even if it has this unfortunate retention type, but PMD works probably in a little different way than FindBugs.

You are right that even RUNTIME retention doesn't require the jar itself, as long as the classes coming from it are not referenced directly, ex. if you have class A annotated with annotation B coming from some jar, and you don't include this jar in runtime classpath, using A.class.getAnnotation(B.class) will cause an error as expected (because class B is not available on classpath), while A.class.getAnnotations() will silently ignore B in this case

We do learn our whole life :) - and thanks to your comment I'm a little more experienced developer now, thank you

Regards

@MultipartConfig : Servlet 3.0 File Upload Example

Mar 29, 2011 · Sahil Nim

agree :) - API creators - give us something portable across the containers/operating systems or drop it all ;)
@MultipartConfig : Servlet 3.0 File Upload Example

Mar 29, 2011 · Sahil Nim

Hm, suppose that you are preparing the web application which people will run in different containers, and different operating systems, specifying hard coded location is very useful in this case ;) :D - and will give you extreme level of portability between the operating systems ... I see only one possible usage of this - using some predefined constants as values, which will be implemented same way in all operating systems, where JVM is available - but current API doesn't have this possibility, unless I've missed something ... As you wrote, omitting it is the only choice here, but why it is available in the API then?
@MultipartConfig : Servlet 3.0 File Upload Example

Mar 25, 2011 · Sahil Nim

Guys, please, tell me that location="c:\\tmp" is some kind of joke in this example ...

User has been successfully modified

Failed to modify user

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: