Saturday, June 22, 2013

Java 7 - Autocloseable and Suppressed Exception



Summary

- The new interface AutoCloseable becomes the superinterface of Closeable.
- The try-with-resources statement is a try statement that declares one or more resources.
- A resource is an object that must be closed after the program is finished with it.
- The try-with-resources statement ensures that each resource is closed at the end of the statement.
- Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

From: http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

See also:
http://www.slideshare.net/alsdias/savedfiles?s_title=new-features-of-jdk-7&user_login=denizoguz



Example

Follow the comments on the code below, a full example to show the suppressed exception.

 


package exception.java7;

import java.io.Closeable;
import java.io.IOException;

/**
 * exception.java7.Autocloseable_main.java<br>
 * project: javaLab<br>
 * <br>
 * target: java 7 AutoCloseable example with suppressed exception. <br>
 */
public class Autocloseable_main {

    public Autocloseable_main() {
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        //event1();
        event2();
    }

    /**
     * <pre>
     * Event1's output:
     *
     * [INFO]: opening a resource
     * [INFO]: event1(): doing something
     * [INFO]: closing a resource
     * exception.java7.AppException: [WARN]: application failure.
     *     at exception.java7.Autocloseable_main.event1(Autocloseable_main.java:40)
     *     at exception.java7.Autocloseable_main.main(Autocloseable_main.java:31)
     *     Suppressed: exception.java7.AException: [ERROR]: resource failure.
     *         at exception.java7.AResource.close(Autocloseable_main.java:77)
     *         at exception.java7.Autocloseable_main.event1(Autocloseable_main.java:41)
     *         ... 1 more
     *
     * </pre>
     */
    public static void event1() {
        try (AResource resource = new AResource(false);) {
            System.out.println("[INFO]: event1(): doing something");
            if(!resource.success) throw new AppException("[WARN]: application failure.");
        } catch (AException | AppException e) {
            e.printStackTrace();
        }
    }
  
    /**
     * <pre>
     * Event2's output:
     *
     * [INFO]: opening a resource
     * [INFO]: event2(): doing something
     * [INFO]: closing a resource
     * exception.java7.AException: [ERROR]: resource failure.
     *     at exception.java7.AResource.close(Autocloseable_main.java:91)
     *     at exception.java7.Autocloseable_main.event2(Autocloseable_main.java:66)
     *     at exception.java7.Autocloseable_main.main(Autocloseable_main.java:32)
     *
     * </pre>
     */
    public static void event2() {
        try (AResource resource = new AResource(false);) {
            System.out.println("[INFO]: event2(): doing something");
            if(resource.success) throw new AppException("[ERROR]: application failure.");
        } catch (AException | AppException e) {
            e.printStackTrace();
        }
    }
  
}

class AResource implements Closeable {
  
    boolean success = false;
  
    public AResource() {
        System.out.println("[INFO]: opening a resource");
    }

    public AResource(boolean success) {
        System.out.println("[INFO]: opening a resource");
        this.success = success;
    }
  
    @Override
    public void close() throws AException {
        System.out.println("[INFO]: closing a resource");
        boolean notdone = true;
        if (notdone) {
            throw new AException("[ERROR]: resource failure.");
        }
    }
}

class AException extends IOException {

    private static final long serialVersionUID = 1L;
  
    public AException(String msg) {
        super(msg);
    }
}


class AppException extends Exception {

    private static final long serialVersionUID = 1L;

    public AppException(String msg) {
        super(msg);
    }
}

Tuesday, June 18, 2013

Exception in thread "main" java.lang.IllegalStateException: A JTA EntityManager cannot use getTransaction()

Problem:

Exception in thread "main" java.lang.IllegalStateException: A JTA EntityManager cannot use getTransaction()
    at org.hibernate.ejb.AbstractEntityManagerImpl.getTransaction(AbstractEntityManagerImpl.java:324)
    at br.com.adr.model.persistence.pojos.EmployeeTest.main(EmployeeTest.java:36)




Solution:

Switch the attribute on the persistence configuration:




To:



Eclipse faq: view-handler references to com.sun.facelets.faceletviewhandler that does not implement interface javax.faces.application.viewhandler




On a jsf 2.0 project, using eclipse, I got this warning on the faces-config.xml file at:
<view-handler>com.sun.facelets.FaceletViewHandler</view-handler>

The message was:

view-handler references to "com.sun.facelets.FaceletViewHandler" that does not implement interface javax.faces.application.ViewHandler


Solution
Problem solved configuring "roject faces" JPA.
Follow the picture:










Installing vmwaretool on linux and handling an odd failure


To install vmwaretools on debian 7 (wheezy):


- First install the dependencies as root:
  apt-get install gcc make binutils linux-headers-$(uname -r)
  or just: apt-get install gcc make linux-headers-$(uname -r)



After extract to a temporary folder the vmware-tools-distrib.tar.gz file or whatever named.
  su
  chmod -R 777 vmware-tools-distrib
  cd vmware-tools-distrib
 ./vmware-install.pl

 

Then answer yes/no or just type enter accepting all questions.

See:
http://www.linkovitch.me.uk/blog/?p=732


Eventually, I got the error message thrown by the vmwaretool installer:


/tmp/vmware-root/modules/vmhgfs-only/fsutil.c: In function 'HgfsChangeFileAttributes':
/tmp/vmware-root/modules/vmhgfs-only/fsutil.c:610:4: error: assignment of read-only member 'i_nlink'
/tmp/vmware-root/modules/vmhgfs-only/file.c:128:4: warning: initialization from incompatible pointer type [enabled by default]make[4]: ***
[/tmp/vmware-root/modules/vmhgfs-only/fsutil.o] Error 1make[4]: *** Waiting for unfinished jobs....

/tmp/vmware-root/modules/vmhgfs-only/file.c:128:4: warning: (near initialization for 'HgfsFileFileOperations.fsync') [enabled by default]
/tmp/vmware-root/modules/vmhgfs-only/tcp.c:53:30: error: expected ')' before numeric constant
/tmp/vmware-root/modules/vmhgfs-only/tcp.c:56:25: error: expected ')' before 'int'
/tmp/vmware-root/modules/vmhgfs-only/tcp.c:59:33: error: expected ')' before 'int'
make[4]: *** [/tmp/vmware-root/modules/vmhgfs-only/tcp.o] Error 1
make[3]: *** [_module_/tmp/vmware-root/modules/vmhgfs-only] Error 2
make[2]: *** [sub-make] Error 2
make[1]: *** [all] Error 2
make[1]: Leaving directory `/usr/src/linux-headers-3.2.0-4-686-pae'
make: *** [vmhgfs.ko] Error 2
make: Leaving directory `/tmp/vmware-root/modules/vmhgfs-only'

Checking the output, at first sight, it seems like some version incompatibility, but ...



Solution:

The windows 7 was reinstalled, and the vmware workstation application was updated to the latest release (8.06).

Problem over!

05/31/2013 12:41:07 PM

grub fails returning "stage1 not read correctly"


grub stage1 not read correctly
/boot/grub/stage1 was not read correctly
 
This message is usually obtained during procedures that grub requires to read its configuration files but it was not able to parse them adequately although they are found.

There are many possible reasons.
First check your grub version.

Partition of ext4 type requires grub2 and it will cause this message.

For instance, Debian 7 (wheezy) installation uses grub2 and if you trying to reinstall grub using prior version the parsing incompatibility will cause the message. Other Debian based distributions will certainly run that way.
So, try the procedures below, but without warranty at all.
They work pretty well for me, and are frequently used.



Installing grub2

Follow the procedure as root.

1. Check if the environement already has a previous grub command.

grub --version
if it returns a message, probably is grub1, which returns something like ... 0.97.
grub1 which does not work with ext4 .


To check grub2, do:

grub-install --version
$grub-install (GRUB) 1.99-27+deb7u1


2. Remove the old version if installed:

sudo apt-get purge grub


3. Install the grub2 version:

sudo apt-get install grub2
apt-get install grub2


4. Test the installation:

grub-install --version
$grub-install (GRUB) 1.99-27+deb7u1


Restoring boot

Partition resizing or another operation may invalidate the boot.
In this case it is necessary to restore the grub configuration.

Two alternatives:
- using command line.
- using the Debian's recue interface.
  

Method #1 - using command line.

Boot the machine from "Debian's Installation CD or DVD".
It doesn't matter if from .iso file, virtual machines,  CD or DVD.
Go to:

Advanced options, Rescue mode
Device to use as root file: /dev/sda5
Execute a shell in /dev/sda5


After you get access to the prompt, issue the following commands:


su
mount /dev/sda1 /boot
grub-install /dev/sda


Shall return a success message.

To exit, type exit twice.
Restart machine.


Method #2 - using the Debian's recue interface

Boot the machine from "Debian's Installation CD or DVD".
It doesn't matter if from .iso file, virtual machines,  CD or DVD.
Go to:

Advanced options, Rescue mode
Device to use as root file: /dev/sda5
Execute a shell in /dev/sda5

After you get access to the prompt, type exit.
It's gonna appear a dialog to reinstall grub.
Use it.
Restart machine.


More about grub

Additional information like grub's notation, the documentation of prior version (grub1) is still usefull.





Saturday, June 15, 2013

How to use Yahoo web services for any country


 Suppose you desire to get the weather for the Rio Janeiro city, in Rio Janeiro state, in Brazil.
 The Yahoo's weather web services requires the WOEID.

 To discover the WOEID, do:

 1. Point your browser to:
http://weather.yahoo.com/brazil/
 or
http://weather.yahooapis.com/forecastrss?w=455825


 In the "search box" type the text below and press 'Go':

Rio de Janeiro, RJ, Brazil




After the page is redirected, the WOEID is shown in its URL as a number at the end:
http://weather.yahoo.com/brazil/rio-de-janeiro/rio-de-janeiro-455825/

 


Use this number to call the web service as follow:
http://weather.yahooapis.com/forecastrss?w=455825

You can use the URL directly on the browser or programatically.



If desired to get the temperature in Celsius degrees, append to the end of the url the following:
&u=c


org.codehaus.plexus.util.xml.XmlStreamReader error message on maven's pom.xml using Eclipse



In a maven project, if you get the error message:

 org.codehaus.plexus.util.xml.XmlStreamReader

on the pom.xml file, means that the "XmlStreamReader" class found errors when parsing it.

If a new project, so without compilation, go to its root directory (where the pom.xml file is placed) and run "mvn install". After, refresh you project.

If not a new project, try running "mvn install -U", also under the root directory. After, refresh you project.

If the problem persists and can not be identified visually, probably it's an "encoding" issue or phantom characters.


Solution #1 - Fixing Encoding

If you are using UTF-8, check the header of the pom.xml file.
Add the following at the first line:

<?xml version="1.0" encoding="UTF-8"?>

If not using UTF-8, discover your enconding.

Most used:
Brazil = ISO-8859-1
Windows-1252
UTF-16
us-ascii


More information at:
http://en.wikipedia.org/wiki/Character_encoding



Solution #2 - Phantom Characters


Phantom chars (not printable characters) are generating the errors during parsing. Do the following:

1. Copy the content using Ctrl+C, Ctrl+V to another temporary place.
2. Delete the original file and create a new one using the content from the temporary place.

If the problem persists, use an editor that trims not printable chars, for instance Notepad++ (windows) or gedit(linux).


Before:



After:







Solution #3 -  Eclipse's bug due to memory

Check if your memory is low, less than 200KB.
If *nix, use "free -h" command.
If windows, you can use a widget or the command "perfom /res".
With slow level of system's memory, Iclipse begins to behavior slightly different, small malfunctions up to a full freezing.
Save your files and stop Eclipse's server, if using one, then restart it.
Check memory again, and you'll see that the level is highly increased.
For this reason, due to mysterious project's malfunctions, I track the system memory and once in while I restart Eclipse if it
was working under low level memory, even though no problems happened yet in order to avoid the mysterious malfunctions.



eclipse: java: SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder" or Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder

  >PROBLEM Using Eclipse, you try to run a simple logging test using "org.slf4j.Logger" like the sample below: package Test; im...