Sunday, July 28, 2013

openJPA, Eclipse: ... an api incompatibility was encountered while executing org.codehaus.mojo:openjpa-maven-plugin ..



Problem

The openJPA's enhancer plugin throws an error message:

... an api incompatibility was encountered while executing org.codehaus.mojo:openjpa-maven-plugin ..

For instance:

Description Resource Path Location Type
Execution enhancer of goal org.codehaus.mojo:openjpa-maven-plugin:1.2:enhance failed: An API incompatibility was encountered while executing 
org.codehaus.mojo:openjpa-maven-plugin:1.2:enhance: java.lang.VerifyError: Expecting a stackmap frame at branch target 36 in method 
br.com.adr.simplest.entities.Category.<clinit()V at offset 27
...


The enhancer execution from "openjpa-maven-plugin" of "org.codehaus.mojo" is declared in pom.xml file at:

<groupIdorg.codehaus.mojo</groupId
<artifactIdopenjpa-maven-plugin</artifactId
...
<executions
<execution
<idenhancer</id


On eclipse, you can see on "Markers" panel:




Solution

It's due libraries's incompatibilities.
In this case, the openjpa version is not compatible with the java's version used by the compiler, defined at "maven-compiler-plugin".
Follow by the example below, in order to fix the problem.

Before
...
<dependency
<groupIdorg.apache.openjpa</groupId
<artifactIdopenjpa-all</artifactId
<version2.1.1</version
</dependency
...
<plugin
<groupIdorg.apache.maven.plugins</groupId
<artifactIdmaven-compiler-plugin</artifactId
<version2.3.2</version
<configuration
<source1.6</source
<target1.6</target
</configuration
</plugin
...
<plugin
<groupIdorg.codehaus.mojo</groupId
<artifactIdopenjpa-maven-plugin</artifactId
<version1.2</version
<configuration
<includesbr/com/adr/*/entities/*/*.class</includes
<includesbr/com/adr/*/entities/*.class</includes
<addDefaultConstructortrue</addDefaultConstructor
<enforcePropertyRestrictionstrue</enforcePropertyRestrictions
</configuration
<executions
<execution
<idenhancer</id
<phaseprocess-classes</phase
<goals
<goaltest-enhance</goal
<goalenhance</goal
</goals
</execution
</executions
<dependencies
<dependency
<groupIdorg.apache.openjpa</groupId
<artifactIdopenjpa</artifactId
<!-- set the version to be the same as the level in your runtime --
<version2.1.1</version
</dependency
</dependencies
</plugin
...


-----------------------------------------------------------------------

After:
...
<dependency
<groupIdorg.apache.openjpa</groupId
<artifactIdopenjpa-all</artifactId
<version2.2.2</version
</dependency
...
<plugin
<groupIdorg.apache.maven.plugins</groupId
<artifactIdmaven-compiler-plugin</artifactId
<version3.1</version
<configuration
<source1.7</source
<target1.7</target
</configuration
</plugin
...

<plugin
<groupIdorg.codehaus.mojo</groupId
<artifactIdopenjpa-maven-plugin</artifactId
<version1.2</version
<configuration
<includesbr/com/adr/*/entities/*/*.class</includes
<includesbr/com/adr/*/entities/*.class</includes
<addDefaultConstructortrue</addDefaultConstructor
<enforcePropertyRestrictionstrue</enforcePropertyRestrictions
</configuration
<executions
<execution
<idenhancer</id
<phaseprocess-classes</phase
<goals
<goaltest-enhance</goal
<goalenhance</goal
</goals
</execution
</executions
<dependencies
<dependency
<groupIdorg.apache.openjpa</groupId
<artifactIdopenjpa</artifactId
<!-- set the version to be the same as the level in your runtime --
<version2.2.2</version
</dependency
</dependencies
</plugin
..





-----------------------------------------------------

NOTE:

Use properties to reference the versions.
They make things easier.
For instance:

    <properties
    <openjpa.version2.2.2</openjpa.version
    </properties
    ...
    <dependency
    <groupIdorg.apache.openjpa</groupId
    <artifactIdopenjpa-all</artifactId
    <version${openjpa.version}</version
    </dependency

    ...
    <!--
    The enhancer pluging:
    -->
    ...

<executions
<execution
<idenhancer</id
<phaseprocess-classes</phase
<goals
<goaltest-enhance</goal
<goalenhance</goal
</goals
</execution
</executions
<dependencies
<dependency
<groupIdorg.apache.openjpa</groupId
<artifactIdopenjpa</artifactId
<!-- set the version to be the same as the level in your runtime --
<version${openjpa.version}</version
</dependency
</dependencies

exception in thread main java.lang.classformaterror: absent code attribute in method that is not native or abstract in class file javax/persistence/persistence


Problem

Maven project to run JPA stuff, using:

<dependency>
   <groupId>javax</groupId>
   <artifactId>javaee-api</artifactId>
   <version>6.0</version>
</dependency>


 Or:

<dependency>
   <groupId>javax</groupId>
   <artifactId>javaee-web-api</artifactId>
   <version>6.0</version>
</dependency>



Causes the following exception:

  Exception in thread "main" java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/persistence/Persistence


Solution

Use an implementation jar, because the jars above are just compilation jars.
Instead see example below.

Why?

 This dependency provides you with the Java EE APIs, not the implementations.
 While this dependency works for compiling, it cannot be used for executing code (that includes tests).

See more at:
https://community.jboss.org/wiki/WhatsTheCauseOfThisExceptionJavalangClassFormatErrorAbsentCode


Example


HSQLDB: org.apache.openjpa.persistence.PersistenceException: There were errors initializing your configuration: java.lang.NoSuchMethodError: org.hsqldb.DatabaseURL.parseURL(Ljava/lang/String;ZZ)Lorg/hsqldb/persist/HsqlProperties;



Problem

Running HSQLDB and openJPA (or whatever JPA implementation) you get the following message:

- short message:
org.apache.openjpa.persistence.PersistenceException: There were errors initializing your configuration: java.lang.NoSuchMethodError: org.hsqldb.DatabaseURL.parseURL(Ljava/lang/String;ZZ)Lorg/hsqldb/persist/HsqlProperties;

- full message:
<openjpa-2.1.1-r422266:1148538 nonfatal general error org.apache.openjpa.persistence.PersistenceException: There were errors initializing your
configuration: java.lang.NoSuchMethodError: org.hsqldb.DatabaseURL.parseURL(Ljava/lang/String;ZZ)Lorg/hsqldb/persist/HsqlProperties;



Solution

The HSQLDB's url must be fixed.
Go to persistence.xml or whatever, and check it.
The org.hsqldb.DatabaseURL.parseURL() method rejected it.
In the code of org.hsqldb.DatabaseURL class, you get some examples of HSQLDB's urls:

parseURL:
JDBC:hsqldb:hsql://myhost:1777/mydb;filepath=c:/myfile/database/db",true);
parseURL("JDBC:hsqldb:../data/mydb.db", true);
parseURL("JDBC:hsqldb:../data/mydb.db;ifexists=true", true);
parseURL("JDBC:hsqldb:HSQL://localhost:9000/mydb", true);
parseURL(JDBC:hsqldb:Http://localhost:8080/servlet/org.hsqldb.Servlet/mydb;ifexists=true",true);
parseURL("JDBC:hsqldb:Http://localhost/servlet/org.hsqldb.Servlet/",true);
parseURL("JDBC:hsqldb:hsql://myhost", true);

HSQLDB, openJPA, org.apache.openjpa.persistence.PersistenceException: There were errors initializing your configuration ... A connection could not be obtained for driver class "org.hsqldb.jdbcDriver" and URL ...




Problem

Running HSQLDB and openJPA, the program throws the following message:

- short message:
org.apache.openjpa.persistence.PersistenceException: There were errors initializing your configuration ... A connection could not be obtained for driver class "org.hsqldb.jdbcDriver" and URL ...

- full message:
org.apache.openjpa.persistence.PersistenceException: There were errors initializing your
configuration: org.apache.openjpa.util.UserException: A connection could not be obtained for driver
class "org.hsqldb.jdbcDriver" and URL "jdbc:hsqldb:HSQL://localhost:9001/testone".
You may have specified an invalid URL.


Solution

Check you database log, for instance you get a message like this:
[Server@7e5e5f92]: [Thread[HSQLDB Connection @519f8603,5,HSQLDB Connections @7e5e5f92]]: database alias=testone does not exist

So, create the database on HSQLDB.

HSQLDB, openJPA, .. nonfatal general error ... org.apache.openjpa.persistence.PersistenceException: invalid schema name



Problem

- short message:
nonfatal general error ... org.apache.openjpa.persistence.PersistenceException: invalid schema name

- full message:
[CREATE TABLE testone.eshop_categories (category_id BIGINT NOT NULL, category_name VARCHAR(70), PRIMARY KEY (category_id))] {stmnt 1548490201 CREATE
TABLE testone.eshop_categories (category_id BIGINT NOT NULL, category_name VARCHAR(70), PRIMARY KEY (category_id))} [code=-4850, state=3F000]



Solution

Depending on the database and how you access it, for instance HSQLDB, the schema shall not be declared.
For instance, change:

@Entity
@Table(name="eshop_categories", schema="testone")
public class Category {

To

@Entity
@Table(name="eshop_categories")
public class Category {

Thursday, July 25, 2013

maven and log4j - log4j:WARN No appenders could be found for logger


Problem

When running a test you get the following warning message:

log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.



Solution

To get rid of that warning message,  just set log4's configuration file under the right folder.
Example:






An example of log4.xml configuration file:

<?xml version="1.0" encoding="UTF-8" ?>
<!-- <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> -->
<!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/xml/doc-files/log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

    <appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern"
                value="[temp01] %p [%t] %c{1}.%M(%L) | %m%n"/>
        </layout>
    </appender>

    <logger name="net.sf.ehcache">
        <level value="ERROR"/>
    </logger>

    <!-- Suppress success logging from InteractiveAuthenticationSuccessEvent -->
    <logger name="org.acegisecurity">
        <level value="ERROR"/>
    </logger>

    <logger name="org.apache">
        <level value="WARN"/>
    </logger>

    <logger name="org.hibernate">
        <level value="WARN"/>
    </logger>
 
    <!--logger name="org.hibernate.SQL">
        <level value="DEBUG"/>
    </logger-->

    <logger name="org.springframework">
        <level value="WARN"/>
    </logger>

    <!-- Suppress warnings from Commons Validator -->
    <logger name="org.apache.commons.validator.ValidatorResources">
        <level value="ERROR"/>
    </logger>

    <logger name="org.appfuse">
        <level value="INFO"/>
    </logger>
   
    <logger name="br.com.adr">
        <level value="DEBUG"/>
    </logger>

    <root>
        <level value="WARN"/>
        <appender-ref ref="CONSOLE"/>
    </root>

</log4j:configuration>




----------------------------------------------------------------------------------

 An example of WRONG place:





---------------------------------------------------------------------------------------------------
EXTRA


Why do I see a warning about "No appenders found for logger" and "Please configure log4j properly"? 
This occurs when the default configuration files log4j.properties and log4j.xml can not be found and the application performs no explicit
configuration.
log4j uses Thread.getContextClassLoader().getResource() to locate the default configuration files and does not directly check the file system.
Knowing the appropriate location to place log4j.properties or log4j.xml requires understanding the search strategy of the class loader in use.
log4j does not provide a default configuration since output to the console or to the file system may be prohibited in some environments.
Also see FAQ: Why can't log4j find my properties in a J2EE or WAR application?.

Why can't log4j find my properties file in a J2EE or WAR application?

The short answer: the log4j classes and the properties file are not within the scope of the same classloader.
The long answer (and what to do about it): J2EE or Servlet containers utilize Java's class loading system.
Sun changed the way classloading works with the release of Java 2.
In Java 2, classloaders are arranged in a hierarchial parent-child relationship.
When a child classloader needs to find a class or a resource, it first delegates the request to the parent.
Log4j only uses the default Class.forName() mechanism for loading classes.
Resources are handled similarly.
See the documentation for java.lang.ClassLoader for more details.
So, if you're having problems, try loading the class or resource yourself.
If you can't find it, neither will log4j.


FROM:

http://logging.apache.org/log4j/1.2/faq.html



Wednesday, July 24, 2013

maven exception: Unsupported major.minor version 51.0



Problem

Tests fail.

Example:

mvn install
or
mvn install -U

Causes:

Caused by: java.lang.UnsupportedClassVersionError: br/com/adr/AppTest : Unsupported major.minor version 51.0






Solution

Check the project's java version and plugins, setting the compatible version in pom.xml file.
Follow by the example below.

--------------------------
Before:

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>


--------------------------
After:

<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<jvm>${env.JAVA_HOME7}/bin/java</jvm>
<!-- <jvm>D:/portables_d/jdk-7u25-windows-x64/bin/java</jvm> -->
</configuration>
</plugin>

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>


Now, tests section is working.




Additional Tips

Suppose that jvm element is not correctly configured. For instance, using an absolute path, the "java" was missed:

      <jvm>D:/portables_d/jdk-7u25-windows-x64/bin</jvm>

So, the plugin can not find the path, and it throws a message like this:

'D:\portables_d\jdk-7u25-windows-x64\bin' is not recognized as an internal or external command, an operable program or a batch file.



Or like this:

           The system could not find the specified path.



More at:

http://sampreshan.svashishtha.com/2012/04/01/quicktip-maven-surefire-plugin-unsupported-major-minor-version-51-0/

https://coderwall.com/p/y8yg8w


Tuesday, July 23, 2013

Failed while installing JPA 2.0. org.osgi.service.prefs.BackingStoreException: Resource ... /.settings' does not exist.



The "eclipse-jee-juno-SR1-win32-x86_64" installation was generating the following error message:

Failed while installing JPA 2.0. org.osgi.service.prefs.BackingStoreException: Resource ...
'$RELATIVE_PROJECT_PATH/.settings' does not exist.








This error may have many causes.
Here I gonna show two methods to fix it, and certainly there are many others.

All eclipse configuration is saved under "$WORKSPACE/.metadata" and "$ECLIPSE_INSTALL " folders.

The error may be caused by:


- Plugins incompatibilities,
   or
- Some configuration that became corrupted.


Fixing Plugins incompatibilities



It was installed the following plugins from marketplace - follow by the pictures.



                  Maven Integration for Eclipse WTP (Juno)
  


                  and JBoss Tools:









Inspecting the installation details (menu, help, About Eclipse, Installation Details), I noticed that JBoss also installed maven stuff, and probably would be conflicting with WTP's installation.





The solution was to uninstall one of them.
So, I've decided to uninstall "Maven WTP".
Pressing the button unistall, the procedure begins...






Restarted Eclipse, the problem was gone.



---------------------------------------------------------







Fixing configuration that became corrupted

In this case, you may try to reinstall the plugin.
Uninstall it and install again.

I also got an alternative solution using the workaround described as follows.

Trying to fix the problem, I extracted a new virgin installation and installed just "Maven Integration for Eclipse (Juno and newer)" from marketplace (menu, help, Eclipse Marketplace).

Then I started it using the same workspace when I got the problem.
After, I imported the project which had thrown the error message, but this time the import was successful.
The new installation was closed.

I returned to the previous installation,  where I was getting the JPA error messages,  restarting it, using always the same workspace.
The problem had gone.

So, the new installation had overwritten some improper configuration under $WORKSPACE_PATH/.metadata folder.
Remember that eclipse configuration is saved there.

I always keep a backup file of workspace's .metadata folder.For each expressive change, a new backup is done.
In this case, I had not generated a backup yet since it was the first installation in progress and test.

When a backup is not available, or the old one has problems, it is possible to generate a new workspace from scratch. Go to menu, file, switch workspace and set a new path, of course different from the prior one and press enter to proceed.
The Eclipse is restarted with a new configuration. The old one is gone.

This alternative is useful when it is ineffective an attempt using the usual procedures through the project's properties. When metadata is defective, it usually rejects the configuration adjusted or it causes some malfunction.


Saturday, July 20, 2013

Eclipse Maven Import error: An internal error occurred during: Importing Maven projects. Unsupported IClasspathEntry kind=4



Problem
After using the command mvn eclipse:eclipse, the project is imported by Eclipse using the "Existing Maven Projects", which throws the error message:
An internal error occurred during: Importing Maven projects. Unsupported IClasspathEntry kind=4

Solution
Do not use the "mvn eclipse:eclipse" command.
Do a straight import by Eclipse using the "Existing Maven Projects".
An incompatibility is commented here.

TIP
About compatibilities between command line vs. Eclipse's maven plugin, when the "Run Maven Build" option (Shift+Alt+X M) doesn't work properly, use the command line as follows:

cd project_root (where pom.xml is)
mvn install -U

Return to Eclipse and refresh the project (F5 over project).

Wednesday, July 10, 2013

OpenOffice - Importing from text files



To opens a dialog for import setup, there are at least two options:

1. Simple Copy/Paste

Copy the text using Ctrl+C and paste it using Ctrl+V.

or

2. Using a file having a .csv extension.

Rename the original file (or copy it), adding a .csv  extension.
For instance, if you have a file using .diff extension (myfile.diff), without the .cvs suffix, OpenOffice doesn't recognize it as an import, and it doesn't open the import dialog.
This is the trick and certainly there are other extensions that may be used instead .cvs. Test it, renaming the file with another extension and repeating the procedure. If the dialog is opened, that extension is another alternative.

*** NOTE:
Use the F1 to find out other informations about. The help is good.

Saturday, July 6, 2013

Windows 7 slow startup - very long boot



There are two basic stages when a computer starts using Windows.

The first one is the BIOS setup, which shows a screen defined by the BIOS vendor.

The second, and the last, is the Windows startup screen.

The Windows screen has the Windows' logo and the "Windows starting" message.
So, again, the screen that comes before this screen is the BIOS setup.

If your machine freezes on the first screen, the BIOS screen, your problem is about the BIOS boot.
Sometimes, if you reset the BIOS to the default values may solve.
Do not forget to take note of your current values before changing them.
Other times may require other procedures.

This post is about the second screen, when the computer freezes during Windows startup.

Keep in mind that many reasons may lead to this problem, for instance, hardware malfunction.

A simple hardware check may be done using a live CD of another operating system (O.S.), for instance Ubuntu.
You don't have to install the other O.S., since a live CD runs the new O.S. from the CD itself.
That way, if you may run the new O.S. from the live CD as usual, accessing all drives and etc., probably your hardware is working properly.

So, supposing that hardware is Ok, we shall test if Windows is not running chckdsk without previous notice.
This is a bug, which requires a hot fix.

Note: "chckdsk is a check disk utility, a windows native program used for maintenance.



But how can you fix something without having access?
Remember, you do have access, but it takes a long time.

Two choices:
1. wait for the long startup to enable you access and then apply the hot fix, or
2. try to reboot the computer to execute the chckdsk command manually and restart the computer again.

I prefer the first one, because the second may not solve the problem for sure.
If you're a luck guy which have a small problem, it may work.
After all, any choice is a matter of time... : (

To apply the hot fix, go to Microsoft's page at http://support.microsoft.com/kb/975778 and follow the directions, or manually run chckdsk (summary bellow).

CHKDSK /F at Startup

1.Reboot your computer.
2.Press the "F8" key and hold it as the computer boots up.
3. Choose "Safe Mode with Command Prompt" by moving the up and down arrows to highlight the option and pressing "Enter."
4. Type "Chkdsk /f" at the command prompt and press "Enter."

More details at:
http://www.ehow.com/how_6905134_perform-chkdsk-_f-startup.html

http://searchenterprisedesktop.techtarget.com/tip/How-to-run-the-chkdsk-utility-in-Windows-7



Note:

Google search or other search machine returns for searching strings like "windows 7 slow boot/startup" many results pointing to fake solutions that lead us to unreliable sites registered on "virus lists".
I've discovered the problem by myself, and after that I've switched the searching string to "windows 7 starts checkdisk silently", when eventually I've found the Microsoft's page.

How did I discover that?
After I've formatted the boot and system partitions.
After reinstalling windows again, the checdsk tool came back as usual, but the data partitions marked to be checked were still there active, but at this time the operations were shown ostensibly.


The detail is that formatting partitions are not a problem at all if you have at least two things:

1. backup (partition images) which enables to restore the full system in short time.

2. system and data have their own different partitions. One for system, different the other for data.

Good luck!  : )

Friday, July 5, 2013

MySQL - ERROR 1005 (HY000): Can't create table './MyDB/#sql-e4a_c715.frm' (errno: 121)


The following statement

ALTER TABLE testone.lgn_permission ADD CONSTRAINT fk_lgn_permission_r FOREIGN KEY ( role_fk ) REFERENCES testone.lgn_role( id ) ON DELETE NO ACTION ON UPDATE NO ACTION;

was causing this error:

ERROR 1005 (HY000): Can't create table './MyDB/#sql-e4a_c715.frm' (errno: 121)


Below, it's shown part of the script responsible for the error:


CREATE TABLE testone.lgn_role (
    id                   BIGINT  NOT NULL  AUTO_INCREMENT,
    title                VARCHAR(100)  NOT NULL  ,
    code                 INT UNSIGNED NOT NULL  ,
    profile_fk           BIGINT    ,
    CONSTRAINT pk_lgn_role PRIMARY KEY ( id )
 );

CREATE INDEX idx_lgn_role ON testone.lgn_role ( profile_fk );

CREATE TABLE testone.lgn_permission (
    role_fk              BIGINT  NOT NULL  ,
    login_fk             BIGINT  NOT NULL  ,
    resource_fk          BIGINT  NOT NULL 
    -- CONSTRAINT pk_lgn_permission UNIQUE ( login_fk, role_fk )
 ) ENGINE=InnoDB ;

ALTER TABLE testone.lgn_permission ADD CONSTRAINT fk_lgn_permission_role FOREIGN KEY ( role_fk ) REFERENCES testone.lgn_role( id ) ON DELETE NO ACTION ON UPDATE NO ACTION;

ALTER TABLE testone.lgn_permission ADD CONSTRAINT fk_lgn_permission_login FOREIGN KEY ( login_fk ) REFERENCES testone.lgn_login( id ) ON DELETE NO ACTION ON UPDATE NO ACTION;

Solution

One table was declared as InnoDB, the other not.


CREATE TABLE testone.lgn_role (
...
);


CREATE TABLE testone.lgn_permission (
...
 ) ENGINE=InnoDB ;


Note:

Every time you get such error (1005), check your table declarations.
Something wrong you'll certainly find there.
May be difficult because if the database has a huge script there will be much stuff to be checked.

A good strategy is to create a check list.
For instance:
1. Check all table constraints first.
2. Check key types, if they all have the appropriate type.
etc.

 There are also some useful commands:

1. Checking innoDB status

mysql> Show innoDB status;


On the example above, the result of this command shows that there is a pendant issue.

------------------------
LATEST FOREIGN KEY ERROR
------------------------
130705 18:41:47 Error in foreign key constraint of table testone/#sql-d65_ca:
 FOREIGN KEY ( role_fk ) REFERENCES testone.lgn_role( id ) ON DELETE NO ACTION ON UPDATE NO ACTION:
Cannot resolve table name close to:
( id ) ON DELETE NO ACTION ON UPDATE NO ACTION
------------




2. Checking Schema Informations

Useful to find out the existent constraints, etc.

mysql>USE information_schema;
mysql>desc KEY_COLUMN_USAGE;


For instance:

select * from key_column_usage where constraint_name='fk_lgn_permission_resource';



Thursday, July 4, 2013

VMWare suspended machine fails to restart



Problem

Suppose that suspended your vm and when you try to restart it, if fails, freezing the application, including the host, a Windows O.S..

An error message may come telling us that some log was written to disk that shall be reported to the support.

 
Solution

Restart Windows by some way.
Check if the log reported on the error message was really saved.
Sometimes it is not, but if there is one, and this workaround doesn't work to you, maybe the log comes useful to the support.

When the VM is suspended, its state is saved into files under the VM's installl directory, like this:

VM_NAME-A_CODE.vmem
VM_NAME-A_CODE.vmss

For instance:

vmvd5-db61c31a.vmem
vmvd5-db61c31a.vmss


Delete both files.
Pay attention to not delete any other file, except those mentioned above.
Also, delete the lock file or folder, if existent.

 
*** NOTE

If you have a recent VM backup of your working VM, stored as a suspended machine, you can take the advantage of restoring the working VM using the backup's state.
Just copy the .vmem and .vmss files to the working VM and restart it as usual.

 
****** IMPORTANT

Important to note that the state is tied by the system's environment.
You can't switch states among different environments.

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.



Tuesday, January 15, 2013

The Possible New Future for Mobiles



some topics stand out:

Recently (and ironically) Microsoft bought all of Netscape’s patents from AOL for $1 billion. These include such foundational patents of the web as Secure Socket Layer (SSL), cookies and JavaScript.
One motivation for Microsoft’s acquisition of Netscape’s patents could be to use them in a patent war with Google to stop the Chrome browser’s ascendance in its tracks. The mobile version of Chrome will be a major competitor to Apple’s Safari as well as Mozilla’s new Firefox OS.

The Mozilla entry is not only a browser, but a full-on operating system that can run mobile devices.

The Netscape technology bought by Microsoft, possibly trying to stuck Chrome, and the Firefox OS, supplying support for resources which were before just supplied by the operating system, lead us to a future completely different from the present.
The operating system will no more define the mobile market, split into Android, Apple and Microsoft.

You will buy connectivity considering cost/benefit (ROI – return on investiment) and the O.S. will become a secondary subject, or even optional.

The new Market will fight offering the best final resources under the users’ point of views, where the way to achieve them is no more relevant.

The new rules will change the IT scenarios as a consequence in just few years like a Tsunami, considering that a new embedded O.S. may offer some concepts inherited from the virtual machines were additional O.S. compliances and services may be available to the applications, turning the native O.S. transparent and no more decisive.

Better considering such possibility when planning at long term.

Friday, January 11, 2013

Thunderbird - Inbox is full

If you get the message that your Inbox is full when you start thunderbird, check the following:

1. Open thunderbird as usual, ignore the warning and check all the inbox folders for those accounts that are pop and not imap type. To discover the type, go to  menu, tools, account settings, and point an account,
then "Server Settings" and check on the right the "Server Type" on the top, close to the tittle.

Let all pop accounts' input folders empty, moving their contents to another folder or deleting it.
Once the pop inbox folders are empty, close thunderbird.

2. If desired, check your server's inbox using a web email through your browser or use an imap account version in thunderbird. In such cases,  probably you'll find find the emails that were not downloaded to your machine because the local input folder was considered full, but they are still there, on the server, waiting to be downloaded.

Note: An imap account differs from pop because the former access you email on the server and latter downloads the server content to your machine, saving on the local repository.

3. Go to your local repository, the place where you save your emails in your machine.

Note: If you don't know this place, you can find it clicking on menu, tools, account settings, on the left panel point to local folders then on the right you get your local repository path into the local directory input box.

There you're gonna find two files and one folder:

Inbox.mozmsgs (folder)
Inbox
Inbox.msf

Delete the Inbox and the Inbox.msf files, and start thunderbird again but at this time the warning shall have gone.

Note: thunderbird will recreate those files automatically when restarted, fixing the problem.


IMPORTANT:

If you have any important email that you can't find in you inbox, check it first on the server's input box.
If you still didn't find it, than instead of performing the procedure above, create a new local repository,
switching the path (see note on the 3rd step and just set a new temporary path).
Restart thunderbird and check again. If found, you can return to the original path, execute the procedure above and then you manually move the files downloaded to the temporary repository, created before, to your usual local repository.



Wednesday, January 2, 2013

Value Object vs. DTO


This subject is a controversial issue.
Check different sources below.

Reading the different definitions, I think that :

- Value Object are simple objects passed by value.

- DTO are tranfer objects, so serializable.

- Depending on the context, both may have same meaning, as referred by the J2EE documentation below, when a Transfer Object is passed by value or treated like so, but they do not represent the same concept.
 
- Summarizing:

  A DTO is linked to the concept of its pattern.
 
  A Transfer Object is an object that servers the purpose of a wrapped data transport object.
  So, it can be used in DTO pattern or anywhere else.
 
  A Value Object is a small simple object not based on identity, but on its values' equality.
   
    Depending on the context, things can assume the same role, so they seam similar on its purpose but not on their natures.


----------------------------------------------------------------------------------------------------------------------------------------------

Entity beans aren’t serializable.
We find that we must define additional data transfer objects (DTOs, also called value objects) when we need to transport data to a remote
client tier.
The use of fine-grained method calls (multiple method calls) from the client to a remote entity bean instance is not scalable.
DTOs provide a way of batching remote data access.
The DTO pattern results in the growth of parallel class hierarchies, where each entity of the domain model is represented as both an
entity bean and a DTO.

Use a Transfer Object to encapsulate the business data.
A single method call is used to send and retrieve the Transfer Object.
When the client requests the enterprise bean for the business data, the enterprise bean can construct the Transfer Object, populate it with
its attribute values, and pass it by value to the client.

Clients usually require more than one value from an enterprise bean.
To reduce the number of remote calls and to avoid the associated overhead, it is best to use Transfer Objects to transport the data from
the enterprise bean to its client.

When an enterprise bean uses a Transfer Object, the client makes a single remote method invocation to the enterprise bean to
request the Transfer Object instead of numerous remote method calls to get individual attribute values.
The enterprise bean then constructs a new Transfer Object instance, copies values into the object and returns it to the client.
The client receives the Transfer Object and can then invoke accessor (or getter) methods on the Transfer Object to get the individual
attribute values from the Transfer Object.
Or, the implementation of the Transfer Object may be such that it makes all attributes public.
Because the Transfer Object is passed by value to the client, all calls to the Transfer Object instance are local calls instead of remote
method invocations.


FROM:
http://java.sun.com/blueprints/corej2eepatterns/Pattern/TransferObject.html


  My Note: 
Within this context, it makes sense to assume Value Object as synonym to Transfer Object , because the Transfer Object is passed by value to the client.
Outside this context, a "Transfer Object" is not necessarily a "Value Object" cause instead of being passed by value it may contains references or representations.

Setback
If the Transfer Object comes like a big ship navigating up and down, other problems are raised - throughput (network traffic) and memory usages.
See Adam's comment, below on his blog.

----------------------------------------------------------------------------------------------------------------------------------------------
Data transfer object (DTO) is a design pattern used to transfer data between software application subsystems.
DTOs are often used in conjunction with data access objects to retrieve data from a database.

The difference between data transfer objects and business objects or data access objects is that a DTO does not have any behavior except  for
storage and retrieval of its own data (accessors and mutators).

In a traditional EJB (Enterprise JavaBeans) architecture, DTOs serve dual purposes:

First, they work around the problem that entity beans  pre-ejb 3.0 are not serializable;

Second, they implicitly define an assembly phase where all data to be used by the view are fetched and  marshalled into the
DTOs before returning control to the presentation tier.

A third reason of using DTOs could be that  certain layers of the
application should not be able to access the underlying data access objects, and hence change the data.

A value object is a small simple object, like money or a date range, whose equality isn't based on identity.

FROM:
http://en.wikipedia.org/wiki/Data_transfer_object
http://en.wikipedia.org/wiki/Value_object

----------------------------------------------------------------------------------------------------------------------------------------------


A value object is a small simple object, like money or a date range, whose equality isn't based on identity.

FROM:  Wikipeadia


----------------------------------------------------------------------------------------------------------------------------------------------


The pattern which is known today as Data Transfer Object was mistakenly (see this definition) called Value Object in the first version of the Core
J2EE Patterns.
 

The name was corrected in the second edition of the Core J2EE Patterns book, but the name alue Objectbecame very popular and is still used as an
alias for the actual DTOs.
 

There is, however, a real difference between both patterns: A Data Transfer Object (DTO) is just as stupid data container which is used to transport
data between layers and tiers.
It mainly contains of attributes.
 

Actually you can even use public attributes without any getters / setters, but this will probably cause too much meetings and discussions :-).
 

DTOs are anemic in general and do not contain any business logic.
DTOs are often java.io.Serializable - its only needed if you are going to transfer the data across JVMs.
 

A Value Object [1,2] represents itself a fix set of data and is similar to a Java enum.
A Value Object doesn't have any identity, it is entirely identified by its value and is immutable.
A real world example would be Color.RED, Color.BLUE, SEX.FEMALE etc.

@FROM:
Adam's blog


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...