Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Friday, June 28, 2019

Building Java Applications with Gradle

Gradle wrapper:

  • In order to make sure you build the project with the same version of gradle as other developers (which can make a big difference), build the application using the wrapper: ./gradlew
    It will start with downloading the right gradle version, unless it's already there.
  • Watch out for running old gradlew for a version like 2.3 with a new java like version 11.  It quits silently without doing anything.

Useful commands:

  • gradle build -x test  -- run build but skip tests

Friday, June 7, 2019

Querying for Data in a Java Spring App - Alternatives


  1. Create a method with a name including all attributes you want to query by in your PersonRepository interface that implements CrudRepository<> (or PagingAndSortingRepository<>)
  2. Create a Specification object and use Spring findAll to find all records matching the Specification.
  3. Use @Query in the PersonRepository and define the query using JQL
  4. Use GraphQL (see for example https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#core.extensions.querydsl)

Monday, May 20, 2019

Java Optional - Good Practice



  • orElseThrow: if personService.getAll() returns an Optional, then:
    return personService.getAll().map(converter::toResource).orElseThrow(
           () -> new NoResourceFound(...)
    );
  • orElse: if personService.getByLastName() returns an optional:
    return personService.getByLastName(lName).orElse(null);

Tuesday, April 30, 2019

Java Streams

Null elements in the stream

I thought, I saw a statement that Java streams filters out the null elements in the stream but the information must have been wrong.  So, if nulls are expected, or just in case, do:

... .filter(Objects::nonNull). ....

Monday, September 21, 2015

IntelliJ IDEA - Keyboard Shortcuts And More for An Ex-Eclipse User

Since, couple years ago, JetBrains made available its IntelliJ IDEA to users for free (yes, only its Community Edition), it became an interesting alternative to Eclipse IDE.  While Eclipse is a great IDE, people looking for something more (even if just a little more), may be tempted to switch to IDEA, so here's something for them from another developer tempted to switch as well.

I have bolded out the actions I tend to use all the time in Eclipse.


Basic Shortcuts:

  • C-N - open class
  • C-S-N - open any file
  • A-F7 - find all usages of the object in the workspace
  • C-Q - quick doco (info) about the object under cursor
  • C-click - go to definition/implementation
  • C-F12 - show quick outline of the class
  • C-Space - auto complete
  • C-S-Space - power auto complete (Tan and Enter - both select, but differently)
  • A-Insert - code generate
  • C-/ - comments with //
  • C-S-/ - comments with /*...*/
  • C-D - duplicates the selection
  • C-S-BckSpc - move back in change-history locations
  • C-S-F7 - highlight an identifier; F3 and S-F3 move to next/prev usage; Esc - de-highlight
  • Code | Optimize Imports - from menu
  • C-E - recent files list
  • call tree of the current method: C-A-H
  • locate the current file in the project tree: there is an icon in the project viewer
  • move selected statements up or down the file: C-S-up and down
  • go to declaration of the object: C-B 
  • go back in the browsing history (as opposed to change history):
    C-A-left and right or C-[
  • synchronize a file or a project against the SVN repo: see Version Control tool
Legend: C means Control, S - Shift and A - Alt

Advanced Shortcuts:

  • S-F6 - refactor: rename
  • Esc - in a tool window - moves focus to editor (S-Esc - also hides the tool window)
  • F12 - opposite to Esc
  • C-A-T - surround it
  • C-W - extend the selection
  • C-A-V - refactor: extract variable
  • Tab - live templates (np. itar Tab)
  • Local History | Show History - from file or directory shows and lets  revert to any version all changes in this file or directory

Create a New Project from Sources in IntelliJ: 

  • Open from sources or from SVN/GIT
  • Open Project Structure dialog (Ctrl+Shift+Alt+S) and specify which are source folders using the Module item from the left-hand panel

Tuesday, June 9, 2015

Java - Pass Object by Reference

Facts:
  • Java passes everything by value.
  • References to objects-as well.
  • As long as you use or modify the object whose reference you've got in a parm, you're good.
  • When you want to assign a new object to replace the one that was passed-in, you're for a bad surprise.  Doesn't work
  • The above case can be hidden:
private MainReturnObject getThatObject(BigDecimal extraValue) {
  ...
  extraValue = extraValue.add(BigDecimal.valueOf(7));
  ...
}
...
BigDecimal objectExtraValue;
anObject = getThatObject(objectExtraValue);

After your program exits from getThatObject(), you'll find that extraValue = 0.0.  The method has modified the getThatObject's copy of the reference to objectExtraValue.

Tuesday, September 18, 2012

Eclipse Quirks

Here's a garden variety of Eclipse quirks and gotschas:

  • I frequently use Ctrl-, and Ctrl-. to move between next and previous usage of the current variable. It suddenly stopped working recently and to my surprise I, found that this functionality requires the two following settings to be set correctly:
    • the Next Annotation needs to have Occurances checked (it can be accesses from the standard toolbar under a button with an arrow and a dot), and
    • the Toggle Marke Occurances needs to be on (button with a highlighter)
  • A maven project got stuck with an old set of dependencies and Maven plugin Update Project Configuration doesn't help, even if repeated 7 times.
    Answer: When you do the Update Project Dependencies, check the Force Update of Snapshots/Releases.
    Background: May be, for maven gurus, it should have been obvious what I was missing, but that just means I'm not one of them.  It's true, that only SNAPSHOT and RELEASE dependencies were stuck, and yet it took me almost two hours of tearing my hair off.

Friday, December 16, 2011

Java Project Layout - Best Practices

Simple Project
  • project-name
    • trunk
      • src...
      • pom.xml
    • branches
      • branch-abc
        • src...
        • pom.xml
    • tags...

 Multi-Module Project
  • project-name 
    • project-name-parent
      • pom.xml - defines all modules that are part of the project
    • module 1 
      • trunk
        • src...
        • pom.xml - points to the parent pom.xml
      • branches
      • tags
    • module 2
      • trunk
        • src...
        • pom.xml - points to the parent pom.xml
      • branches
      • tags
    • module ...
 The key point is that the parent folder doesn't define the parent project, but is just a container for the parent and the children-modules.

Advantages:
  • Nicely groups the modules under one folder.
  • Allows to build the whole project by calling "mvn clean install" from parent's folder.
  • Keeps the SVN (and/or Git) operations simple, unlike the layout where the project-name-parent is the parent folder.

    Wednesday, May 12, 2010

    Options for Java Middle-Tier of an RIA Application

    Choice of Standard/Framework
    Here's my best option or two for each area:
    • Persistence:

      • JPA. Use implementation-specific annotations only where unavoidable, and mark them in a way that will allow you to find all of them easily.
       
    • Transaction Management: EJB 3.1
    • Dependency Injection: EJB 3.1
    • Security: EJB 3.1
    • Exposing required web services:EJB 3.1
    • AOP: EJB 3.1 if their support for AOP is sufficient for you. Otherwise: Spring
    • Other:

      • Singletons: EJB 3.1
    Providers
    • JPA: I use Hibernate, but the whole advantage of JPA is, that which provider you use is much less important than it used to be.
    • Application Server: Glassfish 3. It does support EJB 3.1.

    Tuesday, March 2, 2010

    JSON RESTfull Service Using Jersey with Hibernate Persistence on Glassfish - Part 2

    This is continuation of my blog on this topic. I'm adding the solution to the questions/issues left out in that first blog as delineated in the last part of the blog. Actually, this effort wasn't successful. I wasn't able to make it work. Although made a good progress, I had to go back to the approach presented in my previous blog. This post is just to document what I was able to achieve.

    JTA
    Switch to use JTA, instead of native JDBC transactions. All new application servers support JTA natively. With JTA, the session is bound to the transaction. If you call sessionFactory.getCurrentSession(), anytime between userTransaction.begin() and userTransaction.commit(), a session bound to this transaction is returned. User transaction is usually obtained via JNDI. So, an example of code:
    UserTransaction tx = (UserTransaction)new InitialContext()
     .lookup("java:comp/UserTransaction");
    
    SessionFactory factory = HibernateUtil.getSessionFactory();
    PersonDao dao = new PersonDao(factory);
    
    try{
     tx.begin();
     
     dao.saveOrUpdate(person);
     
        tx.commit();
    
    } catch( Exception ex) {
     tx.rollback();
    }
    
    while the only thing that the Dao needs to do is to request the session via: factory.getCurrentSession().

    The required Hibernate configuration file hibernate.cfg.xml:
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE hibernate-configuration PUBLIC
      "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
      "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
    <hibernate-configuration>
        <session-factory name="hibernate/sessionFactory">
         <property name="transaction.manager_lookup_class">org.hibernate.transaction.SunONETransactionManagerLookup</property>
         <property name="transaction.factory_class">org.hibernate.transaction.JTATransactionFactory</property>
            <property name="connection.datasource">jdbc/xaderby</property>
            <property name="dialect">org.hibernate.dialect.DerbyDialect</property>
            <property name="current_session_context_class">jta</property>
            <property name="hbm2ddl.auto">create</property>
        
         <mapping resource="olcc/entity/Person.hbm.xml"/>
        </session-factory>
    </hibernate-configuration>
    
    where jdbc/xaderby is a data source defined on Glassfish, of type javax.sql.XADataSource.

    Configuration
    Glassfish 3
    Hibernate 3.5
    JDK 6 (Derby included)

    Result
    This configuration results in the following error message:

    FINEST: saving transient instance
    FINE: surrounding JTA transaction suspended [JavaEETransactionImpl: txId=1 nonXAResource=null jtsTx=null localTxStatus=0 syncs=[org.hibernate.transaction.CacheSynchronization, org.hibernate.context.JTASessionContext$CleanupSynch@1d069e4]]
    FINE: opening JDBC connection
    INFO: JTS5014: Recoverable JTS instance, serverId = [100]
    
    FINE: select next_hi from hibernate_unique_key for read only with rs
    FINE: update hibernate_unique_key set next_hi = ? where next_hi = ?
    FINE: closing JDBC connection (open PreparedStatements: 0, globally: 0) (open ResultSets: 0, globally: 0)
    SEVERE: org.hibernate.HibernateException: unable to resume previously suspended transaction
        at org.hibernate.engine.transaction.Isolater$JtaDelegate.delegateWork(Isolater.java:179)
        at org.hibernate.engine.transaction.Isolater.doIsolatedWork(Isolater.java:64)
        at org.hibernate.engine.TransactionHelper.doWorkInNewTransaction(TransactionHelper.java:74)
        at org.hibernate.id.TableGenerator.generate(TableGenerator.java:118)
        at org.hibernate.id.TableHiLoGenerator.generate(TableHiLoGenerator.java:84)
        at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:122)
    When I tried using a plain javax.sql.DataSource instead of XADataSource, I was getting XAResource.start error.

    Remaining Questions:
    • findAllByProperty(), findByCriteria() and/or findByExample() methods. Commonly used. What is the right way to implement them?

    J2EE - Tips and Tricks

    • Sun/Oracle's J2EE 5 SDK is installed in small pieces. Unlike previous versions of J2EE, there is no j2ee.jar. And so, pieces of it are installed in glassfish\modules folder, as separate jars. For example, the JTA stuff is installed as jta.jar (the implmementation stuff, com.sun....* classes) and javax.transactions.jar, which holds the core of the JTA API.

    Tuesday, December 8, 2009

    RESTfull Webservices Using Java with Introduction to JSON

    Introduction
    What are RESTfull or Rest web services and how can they be implemented in with Java? Also what is JSON and how to make a webservice that returns a JSON object?  This is what this blog is about. Specifically, first, about installing and running a sample RESTfull application available from Jersey project.

    What are RESTfull webservices? See this article. Or any other; there are many.

    Approach 1

    This approach uses one of the samples provided by the Jersey project and uses Maven to install the libraries. It's a bit heavy approach, but it works. Approach 2 below also uses Jersey, but is way lighter and simpler.


    Server Side
    I'm using Eclipse IDE with Glassfish Application Server. The steps for this configuration are:
    • Add Jersey and Jersey Documentation and Examples components to Glassfish using its admin console. Note, use GlassFish v3 Prelude version.  When I used GlassFish v3 Promoted Build, the Examples module was not showing in its Update Tool.
    • Restart the GF server.
    • Find the Jersey samples in GF_Home/glassfish/jersey folder.  Go into helloworld-webapp folder. You should see a .pom file there, that is used by maven. From that folder, run "mvn clean package" command. Install maven if needed.
    • Maven installs many files, and for me it ended with an error saying it can't read the glassfish-embedded-all-3.0-Prelude-Embedded-b10.jar file.  I have located this file in the maven repository (Documents and Settings/user/.m2/...) and found that it was broken.  I had to download it manually from internet (search by the file name).
    • Rerun the mvn command. It finished successfully and created a war file in the target directory.
    • Open GF console, and from Web Applications do a deploy. Point to the above war file and click OK. That did it.
    • Point your browser to http://localhost:8080/helloworld-webapp/helloworld. The string "Hello World" appeared.
    Analyzing the Sample
    After I had the sample running, I have exploded and analyzed the contents of the generated war file. The file had a class file implementing the resource plus two more short config files.

    sun-web.xml:
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE sun-web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Application Server 9.0 Servlet 2.5//EN" "http://www.sun.com/software/appserver/dtds/sun-web-app_2_5-0.dtd">
    <sun-web-app error-url="">
      <context-root>/helloworld-webapp</context-root>
      <class-loader delegate="true"/>
      <jsp-config>
        <property name="keepgenerated" value="true">
          <description>Keep a copy of the generated servlet class' java code.</description>
        </property>
      </jsp-config>
    </sun-web-app> 

    web.xml:
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
        <servlet>
            <servlet-name>Jersey Web Application</servlet-name>
            <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
            <init-param>
                <param-name>com.sun.jersey.config.property.packages</param-name>
                <param-value>com.sun.jersey.samples.helloworld.resources</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>Jersey Web Application</servlet-name>
            <url-pattern>/*</url-pattern>
        </servlet-mapping>
    </web-app> 

    Approach 2
    Approach 1 worked OK, but I wasn't able to apply the sample to deploy an application of my own. And so I searched for a tutorial that uses Eclipse and possibly no Maven. I have run into this mini tutorial which worked great. I was able to drop this application into a Tomcat 6.0 and GlassFish 3 Prelude containers and it worked in both fine.
    Also, this example illustrates how the service can be implemented for different response formats, leaving to the requestor to decide which one to use.

    JSON
     JSON is simply a format, in a way an alternative to XML, that is especially useful for (de-)serializing objects, for example in order to send them over internet. The format is derived from JavaScript native format, but it became language neutral.  Here's a sample:
    {"name":"Alfred Alfredo","age":"47"}
    A nice and concise description of JSON syntax is on JSON website. To have your RESTfull webservice return a JSON object, download and add to the project jettison.jar that Jersey uses to create a JSON object. Now, for the sake of the demonstration, say that the webservice need to return a Person object:

    @XmlRootElement
    public class Person {
     public String name;
     public int age;
     
     public Person() {} // required by JAXB
     
     public Person(String name, int age) {
      this.name = name;
      this.age = age;
     }
    }

    Thanks to the annotations in this class, in order to return a JSON object we just need to define a method:

    @Path("/person")
    public class PersonResource {
      @GET  @Produces("application/json")
      public Person get() {
       return new Person("Alfred Alfredo",47);
      }
    }

    The JSON object as specified above, in the first part of this section will be returned. You can test it using a browser by pointing it to http://localhost:8080/jersey1/rest/person, where jersey1 is the context of my web app, rest is my servlet mapping and person is what I defined with @Path in my RESTful resource class.

    Thursday, October 29, 2009

    Use Eclipse to Build a Starter Java Web Application

    • Create a new eclipse project using the Dynamic Web Project
    • After it's created, you may find an error in web.xml: Cannot find the declaration of element 'web-app'. To fix it, change all occurrences of j2ee to javaee in the attributes of the web-app tag in web.xml.
    • Place all jars required by your app:
      • into yourWebApp/WEB-INF/lib folder if you want just your app to acces it
      • into tomcatHome/shared/lib folder if you want all web apps on the server to share it
      • into tomcatHome/common/lib folder if you want all application and the server to be able to use it

    Tuesday, May 12, 2009

    Developing Flex Applications with Java Middle-Tier

    Intro
    In my job we are using Flex with Java to develop web applications that support the activity of the agency I'm working for. It's my first experience with Flex and I'd say, I'm duly impressed. I had experience of developing using GWT and I must say, that Flex is an equally good tool.

    A Simple Way
    Just follow this tutorial.

    Tools Used
    We use the following toolset:

    • eclipse with FlexBuilder plugin (plugin is not free)
    • jBoss
    • Java for back-end
    • LCDS to communicate between Flex and Java (not free, but there are free alternatives: BlazeDS and the LCDS Express is also free, I think).
    • Cairngorm pattern for Flex client structure

    Tips and Gotchas

    • A great intro to Cairngorm (and Flex itself) is one by David Tucker.
    • He is using ColdFusion for the back-end, so switch to this or this for how to do it with Java.
    The Cairngorm pattern for calling a remote service is a bit complex. Here's how it goes:
    • In the main mxml file (the one where you define mx:Application): instantiate the ServiceLocator: . The id "services" is irrelevant, it seems. And instantiate the FrontController.
    • Let say, the command LOGIN is to be handled by the back-end. Dispatch the command by initiating the LoginEvent and calling dispatch() on it.
    • Each event is mapped onto a command in the FrontController. Let say, in this case, onto a LoginCommand.
    • In loginCommand, instantiate a delegate, say LoginDelegate and call the login(event)
    • In LoginDelegate, obtain the service proxy using:
      ServiceLocator.getInstance().getRemoteObject("myRemoteObject");
      and call the login(args) on it.
    • Now, two additional files need to be setup: Services.mxml and remoting-config.xml
    • In the first one, Services.mxml, define a mx:RemoteObject with id="myRemoteObject" and the destination="myRemoteClass".
    • In the second, the remoting-config.xml, define a destination with id="myRemoteClass" and the Java class package+classname in the source tag.
    • In the Flex Server properties (access through project properties), set the Root Context as the /YourProjectName.
    If you need to pass an object between client and the server, create two corresponding value objects (usually named *VO, like LoginVO), one in ActionScript in flex branch and one in Java branch:

    • The ActionScript version, needs to have an annotation above the class definition: [RemoteClass(alias=org.sjb.LoginVO)].
    • The Java version needs to be public and have public setters.
    If you want to debug not only Flex (which is done the usual "eclipse" way), stop the JBoss server and start it in Debug mode. That's all that is needed.

    Conclusion
    Altogether, using Flex with Java is very simple. Enjoy it!

    Wednesday, April 29, 2009

    How to Deploy a GWT Application to Tomcat?

    Intro
    OK, so you have tried the GWT (Google Web Toolkit), decided that it's cool, and you created your first application, precisely a module. You have tried it locally on your development machine, using the hosted mode and, may be, in the web mode by using the Compile/Browse button on the hosted-mode preview window. Now, you can either deploy it to Google App Engine, which is a way to try it online free and easily (make sure that your app doesn't become the IP of Google! I haven't looked at the terms of use myself.) or you decide yo want to go for it, and publish it for real. You purchase a Java hosting plan (google for it; you can find some within $12/mo.), and you're ready to deploy your application to your Tomcat server.

    Deploying It
    I used this re
    source to help me with. Basically, follow the steps ( is the root of your GWT application,):
    • create a staging folder (let's call it deploy)
    • copy contents of /www/com.meography.EntryScreen into /deploy
    • create /WEB-INF with folders classes and lib in it
    • create web.xml file in WEB-INF. See the above resource for how to.
    • copy contents of /bin folder to deploy/WEB-INF/classes
    • copy all needed jars into deploy/WEB-INF/lib (you don't need gwt-user.jar nor gwt-dev-windows.jar, though)
    • compress all of the conents of deploy folder into a zip file and rename the file to .war.
    • upload the file to Tomcat, which can be done via browser using Tomcat manager, which is usually already installed for you by your Java hosting vendor. Once the upload finishes, the manager will show your application with options to Start, Stop, Reload and Undeploy it. The name of the app, is the base URL for your app.
    Point your browser to the main .html file of the module (URL indicated by Tomcat manager + YourMainScreen.html). And, voila, you should be on. Well, if there are any problems, for example with your database setup, you'll find errors in the catalina.log file in the /tomcat/logs folder on your production server.

    Re-Deploying It
    To redeploy, after you have done some changes, simply repeat the steps above, but remember to preserve files you had to tweak or create for your production environment like web.xml and possibly hibernate.cfg.xml, if you happen to use Hibernate and use different database on your development machine and on your production server (Java hosting plan will usually have MySQL and PostgreSQL databases included). And, one more thing. I have found that I have to do Undeploy, upload the new .war file and then Deploy for the changes to post correctly. The reason may be, that GWT application is compiled into JavaScript cache files with random names, so the file names will be different each time you compile it, and so, just copying the new .war file over will not replace all of the old files.

    Any feedback? Feel free to let me know.