Monday, December 8, 2014

Strings in switch Statements - available from Java 7 on

Good to know - Java 7 supports String type in switch statement.

Note 1: String are compared via equals() method - note, not via equalsIgnoreCase! and not via  ==.
Note 2: switch argument must not be null - else  NullPointerException is thrown.

Example code:
        String color = "#0000FF";
        color = color.toLowerCase();
        switch (color) {
          case "#0000ff":
              System.out.println("BLUE");
          break;
          case "#ff0000":
              System.out.println("RED");
          break;
          default:
              System.out.println("INVALID COLOR CODE");
        }

More: Oracle info on the topic.

Thursday, October 30, 2014

JPA orphanRemoval=true VS CascadeType.REMOVE

A short comparison of  orphanRemoval and CascadeType.REMOVE properties.

CascadeType.REMOVE

CascadeType.REMOVE (and also CascadeType.ALL as a private case) tells the DB to delete all child records when the parent is deleted. That is if I delete the INVOICE, then delete all of the ITEMS on that INVOICE.

orphanRemoval=true

orphanRemoval=true tells the ORM that if I remove an Item object from the collection of Items that belong to an Invoice object (in memory operation), and then "save" the Invoice, the removed Item should be deleted from the underlying DB. In private case, the "collection" could be @OneToOne relationship, not just @OneToMany.


Source: some (not top rated ones!) of the comments in this stackoverflow thread.

Tuesday, October 14, 2014

Hibernate: Executing an update/delete query exception solved

If you get this exception:
nested exception is javax.persistence.TransactionRequiredException: Executing an update/delete query

It may be because you do not have @Transaction annotation in your repository class (interface). I tried adding @Transaction annotation to calling service or calling controller, but it did not solve the exception. If this do not help you, check step-by-step solution described in this stackoverflow thread.

Monday, October 13, 2014

Hibernate - delete query example

Delete query by parent. Annotation approach used and this code is placed in repository class (interface):
    @Modifying
    @Query("DELETE FROM Child WHERE parent = :parent")
    public void deleteAllForParent( @Param("parent") Parent parent );

Child class has field named parent.

Wednesday, September 24, 2014

SEO optimization joke

An SEO expert walks into a bar, bars, beer garden, hangout, lounge, night club, mini bar, bar stool, tavern, pub, beer, wine, whiskey.

QA Engineer walks into a bar. Orders a beer. Orders 0 beers. Orders 999999999 beers. Orders a lizard. Orders -1 beers. Orders a sfdeljkn

There is a set of Bulgarian jokes you may like here.

Tuesday, September 2, 2014

Startup folder location in Windows 8

Startup folder location: Open Windows Explorer and paste this in address bar:
%APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup



Monday, August 25, 2014

Mantis bugtracker mail configuration

I paste successful configuration for Mantis Bugtracker for sending mails (registering users, notifications, etc).

Enter (and replace with your data) this lines in config_inc.php:

$g_administrator_email = 'sender-email@mail.bg';
$g_from_email = 'sender-email@mail.bg';
$g_webmaster_email = 'sender-email@mail.bg';
$g_return_path_email = 'sender-email@mail.bg';
$g_phpMailer_method = PHPMAILER_METHOD_SMTP;
$g_smtp_host = 'smtp.mail.bg';
$g_smtp_username = 'sender-email@mail.bg';
$g_smtp_password = 'sender-email-password';
$g_smtp_connection_mode = 'ssl';
$g_smtp_port = 465;
$g_email_send_using_cronjob = OFF;
$g_log_level = LOG_EMAIL;



Mantis default administrator password after install

Mantis bugtracker default admin credentials after install:

Username: administrator
Password: root

Friday, August 15, 2014

Embedded Tomcat in Eclipse could not start after mvn clean - solved

Web server could not start in Eclipse (or Spring Tool Suite, STS) after doing mvn clean on your project.

Solution is in 2 steps:
1. Change Server path / Deploy path as described here: http://stackoverflow.com/questions/16340711/tomcat-http-status-404
Key moments on this step:
1.1. server has to be stopped
1.2. to ensure full stop, just restart Eclipse
1.3. you have to mark Tomcat Installation

2. Ensure Eclipse uses JDK, not JRE. I dont know why by default Eclipse ignore JAVA_HOME and uses JRE. Solution is described here: http://stackoverflow.com/questions/13259866/why-does-maven-want-to-use-jre7-instead-of-jdk-against-all-adjustments
In short:
2.1. Window -> Preferences
2.2. Java -> Installed JREs
2.3. add base path of JDK (with includes files src.xip and foldersbin, db...)
2.4. deactivate old and activate new one


Thursday, August 7, 2014

SVN create repository

How-to for creating SVN repo:

sudo svnadmin create /path/to/repo
chmod -R 775 /path/to/repo
chown -Rv www-data /path/to/repo

Tuesday, July 29, 2014

Wednesday, June 25, 2014

Trigger Jenkins build on SVN commit with push notification

The continuous integration server Hudson knows several ways to trigger a build. If you’d like Hudson to build your project when the source-base changes and you don’t want to let him poll your Subversion periodically let Subversion trigger the build upon commit. To do that, you need to execute few steps

Jenkins / Hudson configuration

Configure your job in Hudson (Job -> Configure -> Build Triggers) with “Trigger builds remotely (e.g., from scripts)” (”uDoo” is the job name, so replace it with your job name):


hudson_build_trigger

Configure a post-commit hook in your Subversion repository

In the repository directory of your Subversion-server, a directory hook exists. In this directory you may already have a file post-commit with 744 permissions. If not, a file post-commit.tmpl exists. In that case, copy the file and change the permissions:
$ cd path/to/your/repository/hook
$ cp post-commit.tmpl post-commit
$ chmod 744 post-commit
To trigger the build via Subversion, just put the following line at the end of the post-commit file.
wget -b http://HUDSON_URL/job/JOB_NAME/build?token=my_automated_build > /dev/null
That’s it.


This is cached version of this.
To trigger build with password-protected jenkins, you could check this great article.

Friday, June 13, 2014

"Thread stuck in device driver" for Dell with Windows 8.1 - solved

You get "THREAD STUCK IN DEVICE DRIVER" after every sleep / hibernate in Dell Inspiron 15R notebook after upgrading Windows 8 to Windows 8.1. Restoring previous state before sleep was not possible and a restart os Windows was forced. I give the solution, which helped me (copy-past-ed):

I have been reading through many, many forums to have this annoying message disappear. For 3 month I was pulling my hair because of this silly message! I also have a Dell Inspiron 15R and when I turn it on, it showed this blue message saying THREAD STUCK IN DEVICE DRIVER, it then reboots itself followed by 5-10seconds of black screen. This issue only began after I updated from Windows 8 to Windows 8.1. I kept records of what I read through many forums to fix this and hopefully this will work for you.

1. I went to the Dell website and re-installed the BIOS. I believe after upgrading from Win 8 to Win 8.1, the BIOS does get a little messed up. Find out your BIOS version by pressing the Windows key + R, and type msinfo32 then and go to Dell website then reinstall it. In my case, I went to the Dell UK website and reinstalled it.
2. I went to the Intel website and installed the Intel Update Tool below. http://supportkb.intel.com/wireless/wireless-display/templates/selfservice/intelwidi/#portal/1026/article/16168.
3. I uninstalled the AMD drivers which were currently installed via Control Panel, then I restarted the laptop.
4. After logging in, I downloaded the AMD Clean Install Utility from the AMD website below.
http://support.amd.com/en-us/kb-articles/Pages/AMD-Clean-Uninstall-Utility.aspx
5. I then installed the latest AMD Catalyst Suite from the AMD website below. In my case, it’s the 64bit AMD.
http://support.amd.com/en-us/download/desktop?os=Windows+7+-+64
6. Finally from the AMD website, I installed the AMD Auto Driver Detector from the below.
http://support.amd.com/en-us/download/auto-detect-tool
7. Back to the Intel website, I clicked on the “Check Your System For Updates” link. This detected all the Intel Drivers and showed me which ones needed updating. In my case, it detected that I needed to download 3 separate drivers.
http://www.intel.com/p/en_US/support/detect
Finally, I restarted my laptop. I did them all in this order and this worked for me like a charm.

This is solution from J.King Jr which helped me. It is posted here in Microsoft's forum.

The key was to Update BIOS, and after that to make a clean install of ATI driver. I tried to skip some steps of provided how-to, but the issue continue to persist.

Wednesday, June 11, 2014

Windows 8: Start menu location & Startup folder location

There is no direct way of accessing Start menu location & Startup folder location, so you have to open them manually in Windows Explorer. The locations are:

Start menu

C:\Users\<username>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs
C:\ProgramData\Microsoft\Windows\Start Menu\Programs

Startup folder

C:\Users\<username>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp

Utility software

This program provides access to all Windows special folders in an easy way:

Saturday, June 7, 2014

Developers' jokes

Some people, when confronted with a problem, think, 'I know, I'll use threads' - and then two they hav erpoblesms.

A programmer is told to "go to hell", he finds the worst part of that statement is the "go to"

"It should be noted that no ethically-trained software engineer would ever consent to write a DestroyBaghdad procedure. Basic professional ethics would instead require him to write a DestroyCity procedure, to which Baghdad could be given as a parameter." - Nathaniel Borenstein

"I've got a really good UDP joke to tell you, but I absolutely don't care, whether you'll get it"

"What's the best part about TCP jokes? I get to keep telling them until you get them."

A SEO expert walks into a bar, pub, public house, inn, restaurant, club.

How many SEO engineers does it take to change a light bulb, lightbulb, globe, lamp, sex, xxx

99 little bugs in the code
99 bugs in the code
patch one down, compile it around
117 bugs in the code

A group of computer science geeks were listening to a lecture about Java programming at a university.
After the lecture, one of the men leaned over and grabbed a woman’s breast.
Woman: Hey! That’s private OK ?
The man hesitated for a second looking confused.
Man: But I thought we were in the same class.

In order to understand recursion you must first understand recursion.

A man flying in a hot air balloon suddenly realizes he’s lost. He reduces height and spots a man down below. He lowers the balloon further and shouts to get directions, "Excuse me, can you tell me where I am?"
The man below says: "Yes. You're in a hot air balloon, hovering 30 feet above this field."
"You must work in Information Technology," says the balloonist.
"I do" replies the man. "How did you know?"
"Well," says the balloonist, "everything you have told me is technically correct, but It's of no use to anyone."
The man below replies, "You must work in management."
"I do," replies the balloonist, "But how'd you know?"*
"Well", says the man, "you don’t know where you are or where you’re going, but you expect me to be able to help. You’re in the same position you were before we met, but now it’s my fault."

Programming is like sex. Make one mistake and you end up supporting it for the rest of your life.


Why do programmers confuse halloween and christmas? Because Oct 31 = Dec 25.

Source - reddit.com

Thursday, June 5, 2014

Catching low-level controller exceptions in Jackson

This is useful code, that could be used in controllers to catch exception while parsing json data by jackson.

    @ExceptionHandler({org.springframework.http.converter.HttpMessageNotReadableException.class})
    @ResponseBody
    public String resolveException(Exception e) throws Exception{
        throw e;
    }

It catches all exception thrown by this class members.

Examples of join and other queries for Hibernate (HQL)

Examples of usage of Hibernate query language. Could be used in repositories with @Query annotation.

Join:
1. select night.id nid, night.night_duration, night.night_date, area.id aid, night.area_id, area.name from Night night, Area area where night.area_id = area.id

2. from Bid bid left join fetch bid.item left join fetch bid.bidder where bid.amount > 100

3. from Book book inner join book.chapters chapter where chapter.title like '%hibernate%'

4. from com.package.Venue venue inner join venue.name.translations t WHERE t.string = :name
Double join table

5. select cont from Continent cont join fetch cont.countries where cont.name = 'Europe'



Basic:
1. select p from Plane p

2. select n from Night n where n.date >= :date


Docs:
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html#queryhql-joins Join queries in HQL

Friday, May 16, 2014

Hibernate relationship templates

Here is a list with one-to-many, one-to-one and many-to-many relations templates.

One-to-many:
@Entity(name = "parent")
@Access(AccessType.FIELD)
public class Parent {

    @OneToMany(fetch = FetchType.LAZY, mappedBy="childVarName", orphanRemoval=true)
    protected Set<Child> parentVarName;
}

@Entity(name = "child")
@Access(AccessType.FIELD)
public class Child {
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "child", nullable = false)
    protected Parent childVarName;
}

One-to-one:
public class VirtualParent {
    @OneToOne(mappedBy = "virtualParentVar")
    protected VirtualChild virtualChildVar;
    // ...
}

public class VirtualChild {
    @OneToOne
    @JoinColumn(name = "frn_virtual_parent_id")
    protected VirtualParent virtualParentVar;
    // ...
}

Many-to-many:

Wednesday, May 14, 2014

Setting transactional Spring components manually

There is an issue while setting @Transactional Spring components, because of proxies used to generate them. Here is an solution for that:

Setter:        
ReflectionTestUtils.setField( 
    TestUtils.unwrapTransactionalServiceSafe(serviceWithAutowiredComponents), 
    "externalService", newExternalServiceInstance );


Utils:
    public static Object unwrapTransactionalService( Object transactionalService ) throws Exception {
      if(AopUtils.isAopProxy(transactionalService) && transactionalService instanceof Advised) {
          Object target = ((Advised) transactionalService).getTargetSource().getTarget();
          return target;
      }
      return null;
    }
    public static Object unwrapTransactionalServiceSafe( Object transactionalService ){
        try {
            return unwrapTransactionalService( transactionalService );
        } catch (Exception ex) {
            throw new RuntimeException( ex );
        }
    }



Tuesday, May 13, 2014

Spring: setting properties externally

        ReflectionTestUtils.setField( mobileController, "externalService", externalService );

Tuesday, April 22, 2014

Ways of Inheritance in Hibernate

Here is a great article for hibernate inheritance.

An example  of each of them is added. Advantages and disadvantages also are mentioned.

Using Subversion in Netbeans - solutions for all issues

Some mandatory steps needed after Netbeans installation to get SVN working.

0. Start position: svn functionality is not working. Item "Show annotations" in Team menu is deactivated.

1. Your subversion client version must match requirements by Netbeans. They are different for every Netbeans version. So check link - http://wiki.netbeans.org/FaqSubversionClients

2. Show annotations menu item in Team menu is active now.

3. Navigate menus: Tools > Options > Team -> Versioning > Subversion . Select "Path to the SVN executable file". It is placed in folder C:\Program Files\TortoiseSVN\bin by default. If executable could not be selected, may not be installed in SVN installation. Ensure "command line utils" checkbox is selected in the reinstallation.

4. Update or any SVN action could cause "sslprotocolexception: handshake alert:  unrecognized_name" in Netbeans. This is caused by missing configuration in Netbeans.
Solution:
Copy folders named: svn.ssl.client-passphrase, svn.ssl.server, svn.username
from folder: C:\Documents and Settings\<username>\Application Data\Subversion\auth
to folder: C:\Documents and Settings\<username>\AppData\Roaming\NetBeans\8.0\config\svn\config\auth

5. Finally solved! So enjoy your SVN client.

Spring repositories with native queries - Supported keywords inside findBy method names



KeywordSampleJPQL snippet
AndfindByLastnameAndFirstname… where x.lastname = ?1 and x.firstname = ?2
OrfindByLastnameOrFirstname… where x.lastname = ?1 or x.firstname = ?2
BetweenfindByStartDateBetween… where x.startDate between 1? and ?2
LessThanfindByAgeLessThan… where x.age < ?1
GreaterThanfindByAgeGreaterThan… where x.age > ?1
After
findByStartDateAfter… where x.startDate > ?1
Before
findByStartDateBefore… where x.startDate < ?1
IsNullfindByAgeIsNull… where x.age is null
IsNotNull,NotNullfindByAge(Is)NotNull… where x.age not null
LikefindByFirstnameLike… where x.firstname like ?1
NotLikefindByFirstnameNotLike… where x.firstname not like ?1
StartingWithfindByFirstnameStartingWith… where x.firstname like ?1 (parameter bound with appended %)
EndingWithfindByFirstnameEndingWith… where x.firstname like ?1 (parameter bound with prepended %)
ContainingfindByFirstnameContaining… where x.firstname like ?1 (parameter bound wrapped in %)
OrderByfindByAgeOrderByLastnameDesc… where x.age = ?1 order by x.lastname desc
NotfindByLastnameNot… where x.lastname <> ?1
InfindByAgeIn(Collection<Age> ages)… where x.age in ?1
NotInfindByAgeNotIn(Collection<Age> age)… where x.age not in ?1
TruefindByActiveTrue()… where x.active = true
FalsefindByActiveFalse()… where x.active = false


Source: http://docs.spring.io/spring-data/jpa/docs/1.4.3.RELEASE/reference/html/jpa.repositories.html

Wednesday, April 16, 2014

java syntax for catching multiple exceptions

New java syntax for catching multiple exceptions in a single section:

    try {
        // do something
    } catch (ImageProcessingException | IOException ex) {
        log.error("Unable to get orientation from file " + imagePath.toString(), ex);
    }




Friday, April 4, 2014

Skipping constraint checks in MySQL

Error
Cannot delete or update a parent row: a foreign key constraint fails

Issue:
mysql> update User SET id=6 where id = 8;

ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`database_name`.`table_name`, CONSTRAINT `FK_35jtu0049tkg8m9twhc03ii9` FOREIGN KEY (`customer`) REFERENCES `user` (`id`))

Solution:
SET foreign_key_checks = 1;
; execute code with constraint restrictions here
SET foreign_key_checks = 0;


Hibernate: setting foreigh key without getting foreign object

A nice solution from stackoverflow:
http://stackoverflow.com/questions/21012293/hibernate-add-entity-with-child-entity-id

Tuesday, March 25, 2014

Java IO Tutorial - file read / write

Commonly Used Methods for Small Files

Reading All Bytes or Lines from a File

If you have a small-ish file and you would like to read its entire contents in one pass, you can use the readAllBytes(Path) or readAllLines(Path, Charset) method. These methods take care of most of the work for you, such as opening and closing the stream, but are not intended for handling large files. The following code shows how to use the readAllBytes method:

Path file = ...;
byte[] fileArray;
fileArray = Files.readAllBytes(file);

Writing All Bytes or Lines to a File

The following code snippet shows how to use a write method.

Path file = ...;
byte[] buf = ...;
Files.write(file, buf);


Original tutorial is locate here: http://docs.oracle.com/javase/tutorial/essential/io/file.html

Thursday, March 20, 2014

Getting last element in Hibernate's repository by annotations

Getting last element in hibernate is useful for integration testing, where you have to ensure some object is stored in database, for example.

Using Hibernate SQL.

Code:
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.jpa.repository.Query;

public interface MyObjectRepository extends CrudRepository<MyObject, Long> {
 
  @Query("FROM com.yourcompany.zzz.MyObject c WHERE (c.id) IN (select max(id) from com.yourcompany.zzz.MyObject)")
  MyObject getLastOne();   
 
}



It returns null, when there are no elements in table (do not throw an exception).

Wednesday, March 5, 2014

Jackson deserialization in controller

Here is an example for deserialize JSON data from string placed in the body of the request.

Here are clear (not-working) and work-around.

Workaround:


    @RequestMapping(
        value = "/add_venue_raw",
//        method = RequestMethod.POST, // if you like
        produces="application/json",
        consumes={"application/json"}
    )
    @ResponseBody
    public String addVenueRaw( @RequestBody String body ) throws IOException {
        log.info( "received body: " + body );


        ObjectMapper mapper = new ObjectMapper();
        Venue x = mapper.readValue( body, Venue.class );
        log.info( "obj.toString() = " + x.toString() );


        return "{\"status\":\"no warnings
\"}";
    }


Clear but not working way

    @RequestMapping(
        value = "/add_venue_buggy",
        method = RequestMethod.POST,
        consumes={"application/json"},
//        produces="application/json;charset=utf-8"
        produces="application/json"
    )
    @ResponseBody
    public String addVenue( @RequestBody VenuePhoto venue ) {
// this DO NOT works!!!!!!!!!!!!!!!!!!!!
        return "{}";
    }

   


Deserialize as map

Deserialize body data as map and return the same body (useful for tests):
    @RequestMapping(
        value = "/add_venue_raw",
//        method = RequestMethod.POST,
        produces="application/json",
        consumes={"application/json"}
    )
    @ResponseBody
    public String addVenueRaw( @RequestBody String body ) throws IOException {

        log.info( "received body: " + body );
       
        Map<String, String> map = new HashMap<String, String>();
        ObjectMapper mapper = new ObjectMapper();

        try {
            //convert JSON string to Map
            map = mapper.readValue(body,
                new TypeReference<HashMap<String, String>>() {
                });


            System.out.println(map);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return map.toString();
    }


Blank template JavaScript application for JSON requests

Blank template application for JSON requests with and without body:

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>My Blank JS / jQuery app - jsFiddle demo by jorooo</title>
 
  <script type='text/javascript' src='http://code.jquery.com/jquery-latest.js'></script>
  <!--link rel="stylesheet" type="text/css" href="/css/result-light.css"-->
  <script type='text/javascript' src="http://code.jquery.com/mobile/latest/jquery.mobile.min.js"></script>
  <link rel="stylesheet" type="text/css" href="http://code.jquery.com/mobile/latest/jquery.mobile.min.css">
     
  <style type='text/css'>
   
  </style>
</head>
<body>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
    $("#alert").bind("click", function(event) {
        alert('alert called');
    }); 

    $("#call_json_with_body").bind("click", function(event) {
        $.ajax({
            success: function( data ){
                alert("success");
                alert('success, data received is ' + JSON.stringify(data));
            },
            error: function( jqXHR, textStatus, errorThrown ){
                alert( "error  while making ajax call. Error parameters are, " +
                    "\ntextStatus: " + textStatus +
                    ";\n errorThrown: " + errorThrown +
                    ";\n jqXHR: " + JSON.stringify(jqXHR) );
            },
            beforeSend: function(req) {
                req.setRequestHeader("Accept", "application/json");
                req.setRequestHeader("Content-Type","application/json");
            },       
            dataType: 'json',
            data: JSON.stringify( {"zzz":"222"} ),
            type: 'POST',
            cache: false,
            url: "http://localhost:8080/add_venue_raw",
          }
        );   
    }); 
    $("#call_json_without_body").bind("click", function(event) {
        $.ajax({
            success: function( data ){
                alert("x");
                alert('success, data received is ' + JSON.stringify(data) );
            },
            error: function( jqXHR, textStatus, errorThrown ){
                alert( "error  while making ajax call. Error parameters are, " +
                    "\ntextStatus: " + textStatus +
                    ";\n errorThrown: " + errorThrown +
                    ";\n jqXHR: " + JSON.stringify(jqXHR) );
            },
            type: 'GET',
            cache: false,
            url: "http://localhost:8080/user/1",
          }
        );   
    }); 
});//]]> 

</script>

  <div data-role="page" id="p1">
    <div  data-role="header"><h1>Header</h1></div>
   
    <div  data-role="content">
        <h5>If the script is running from a file:/// URL you could experience some issues. It's best not to do AJAX requests from file URLs, because they are treated inconsistently. Chrome, for example, entirely disallows them. Firefox also.</h5>
        <a href="#" id="call_json_without_body" data-role="button">JSON request without body</a><br/>
        <a href="#" id="call_json_with_body" data-role="button">JSON request with body</a><br/>
        <a href="#" id="alert" data-role="button">Show alert</a>
    </div>
   
    <div  data-role="footer"><h4>Footer</h4></div>
</div>

 
</body>
</html>





static root folder for maven projects

Static files could be copied here:
<maven-project-root>\src\main\webapp\resources

They are accessed on server on URL:
<server_address>/resources

Example:
<maven-project-root>\src\main\webapp\resources\x.txt
could be accessed on
http://localhost:8080/resources/x.txt

In come cases, the content changes are actualized without server restart. For example with:
mvn jetty:run

Tuesday, February 25, 2014

Avoiding CORS security issues

CORS is security policy, according which a page could not be iframe-d from page from another site.

ajax requests are implemented via iframe, so if we want to do ajax requests to another site, we encounter CORS error.

How to enable this?

Solution is to tell server to allow the page/JSON/webservice to be iframed. This is done this way:
    public String getUserById(@PathVariable("id") Long id, HttpServletResponse httpResponse) throws JsonProcessingException {
        httpResponse.addHeader("Access-Control-Allow-Origin", "*");
        // do real work

    }

Access-Control-Allow-Origin is the header that allows this. Check wikipedia for other solutions.

solved: Spring + Hibernate used with JPA and EntityManager => HibernateException: collection is not associated with any session

When I started using lazy loading in Spring + Hibernate project, I encounter this error.

What does NOT solve my issue:
  • @Transactional annotation
  • OpenSessionInViewInterceptor


The error message was:

HTTP ERROR 500

Problem accessing /user/1. Reason:
    Server Error

Caused by:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.HibernateException: collection is not associated with any session
 at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894)


Solution for Spring with JPA approach and EntityManager, is to use OpenEntityManagerInViewFilter. Register it in web.xml this way:
<filter>
    <filter-name>
        OpenEntityManagerInViewFilter
    </filter-name>
    <filter-class>
        org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter
    </filter-class>
    <init-param>
        <param-name>singleSession</param-name>
        <param-value>true</param-value>
    </init-param>
    <init-param>
        <param-name>flushMode</param-name>
        <param-value>AUTO</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>OpenEntityManagerInViewFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>


Sources:
http://stackoverflow.com/questions/9304020/lazy-initialisation-with-openentitymanagerinviewfilter - not the selected answer, but this from Jhonathan

Monday, February 24, 2014

How to serialize only the ID of a child with Jackson?

Solution from stackoverflow.com

public class Parent {
   @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id")
   @JsonIdentityReference(alwaysAsId=true) // otherwise first ref as POJO, others as id
   public Child child; // or use for getter or setter

   // if using 'PropertyGenerator', need to have id as property -- not the only choice
   public int id;
}

Friday, February 21, 2014

Jackson + Spring + Maven = http error 406 - workarounded

I get this error in Spring project with Jackson, with annotations:

HTTP ERROR 406

Problem accessing /xxx/4. Reason:
    Not Acceptable

Powered by Jetty://

I have tested it with Jackson 2.3.1, 2.2.3 and 2.1.3 - same. Spring 3.1.1 and 3.1.0 - same. Application server jetty and tomcat - same, but in Tomcat dies with no error/log text.

So my conclusion is:

Jackson sucks!

And this is not for its error (there are no errors in controller method, it passes fine), but in dieing with no single line of message.

I will revert to jackson 1, where this error is not absolute blocker to me (i get it only on one page in version 1).

P.S. No answer on stackoverflow uptill 2014.2 helped me :(


Edit: the solution.
Holly *hit, I finally overcome the issue in very simple way!

Clean, not working way:
    @RequestMapping(value="/t")
    @ResponseBody
    public Dummy getT() {
        Dummy t = new Dummy();
        t.setId(1L);
        t.setUrl("sdfsaf");
        System.out.println( "hello from t" );
        return t;
    }


Workaround:
    @RequestMapping(value = "/manualDummy", method = RequestMethod.GET)
    @ResponseBody
    public String manualDummy(/*HttpServletRequest request, ModelMap model*/) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper(); // com.fasterxml.jackson.databind.ObjectMapper
        Dummy t = new Dummy();
        t.setId(1L);
        t.setUrl("sdfsaf");
        return mapper.writeValueAsString(t);
    }


P.S. Jackson continues to sucks...

Monday, February 17, 2014

How to Stop Netbeans: Transferring repository index

I see at status bar, that Netbeans is Transferring repository index : java.net repository. It slows down my computer very much. Very annoying.

Solution for Netbeans 7.4 (and possibly later versions, 8.0):
Tools | Options | Java | Index”, find “Index Update Frequency” and then adjust how often it should be updated (Never :).

Thursday, February 13, 2014

KendoUI Mobile: force refresh / reload / update on a ListView

Lets have a list view, initialized with data from variable employees this way:

<ul id="employeesListView" data-role="listview" data-title="Employee list title" data-source="employees" data-template="employees-template" />

If we have updated the variable employees, the listview stays the same. To force update, we have to do this:

        $("#employeesListView").kendoMobileListView({            dataSource: employees,
            template:  $("#employees-template").text(),
        });

KendoUI Mobile: catching connection errors in accesing remote datasource

    var dataSource = new kendo.data.DataSource({
        transport: {
            read: {
                url: "https://ala.bala.com:443/test/test.json2",
                timeout: 3900,
                dataType: "json",
                data: {
                    q: "javascript"
                },
            },
        },
        schema: {
            data: "results"
        },
        error: function(e) {
            console.log(JSON.stringify(e));
        }
    });

KendoUI Mobile: working example with remote json listview databinding

Source could be downloaded from this thread. Tested and working.

In the example .json file has to be placed in folder of index.html, but you could move it in any remote server and point "url" to its location.

Thursday, February 6, 2014

Using JSON web services in jQuery - simple example

Lets web-service returns this data:
{"user":{"@id":"10","firstName":"Bill","lastName":"Clinton"}}

Here is the JavaScript code:
                var ws_url = 'http://example.webservice.com:8002/xxx-ws/management/usr/10';
                $.ajax({
                  url: ws_url,
                  dataType: 'json',
                  timeout : 5000,
                }).success(function( data, textStatus, xhr ) {
                        alert( "returned user name = " + data.user.firstName + " " + data.user.lastName );
                        gdata = data;
                }).error(function(httpObj, textStatus) {       
                    alert(textStatus);
                    alert(JSON.stringify(httpObj));
                });


You will get [returned user name = Bill Clinton]

Wednesday, February 5, 2014

jetty 9 in maven. Newer jetty, older jetty

Update from jetty 6 to jetty 9 done - solved!

Fixed version Jetty 9:
        <plugin>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-maven-plugin</artifactId>
            <version>9.1.1.v20140108</version>
        </plugin>

Latest Jetty:
        <plugin>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-maven-plugin</artifactId>
        </plugin>

Older jetty 6 was with non-eclipse groupId, which cause auto version update to 7+ not to works. If you want Jetty 6, this is the pom.xml fraction you need.
        <plugin>
          <groupId>org.mortbay.jetty</groupId>
          <artifactId>maven-jetty-plugin</artifactId>
        </plugin>

Custom configuration
Some useful configuration options for Jetty:
        <plugin>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-maven-plugin</artifactId>
            <configuration>
              <scanIntervalSeconds>2</scanIntervalSeconds>
              <webApp>
                <contextPath>/my-context</contextPath><!-- default is / -->
              </webApp>
            </configuration>    
       
        </plugin>

Wednesday, January 29, 2014

Find object by id in array of javascript objects

myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'},etc.]

var result = $.grep(myArray, function(e){ return e.id == id; });
 
if (result.length == 0) {
  // not found
} else if (result.length == 1) {
  // access the foo property using result[0].foo
} else {
  // multiple items found
}
 
Source - stackoverflow.com