Showing posts with label Error. Show all posts
Showing posts with label Error. Show all posts

Monday, 14 October 2013

Creating An OpenShift Web/Spring Application From The Command Line

OpenShift offers online functionalities to create applications, but this can also be achieved from command line with the RHC Client Tool. For windows, you will first need to install RubyGems and Git. The procedure is straightforward.

Git SSL Communication 

OpenShift requires SSL communication between local Git repositories and the corresponding server repositories. Generating SSH Keys for TortoiseGit on windows can be tricky, but this post tells you how to achieve this.

Maintenance

From time to time, run the following commands for RubyGems and RHC updates:

> gem update --system
> gem update rhc

Creating the Spring application

Under Windows, open a cmd windows and go to the directory where you want to create the application. Assuming you want to call it mySpringApp, run the following command:

> rhc app create mySpringApp jbosseap-6

The application will be automatically created and the corresponding Git repository will be cloned locally in your directory.

'Unable to clone your repository.'

If you encounter the above error, you will need to clone the Git repository manually. Assuming that TortoiseGit for Windows has been installed properly and that you have generated your SSL keys for Git properly, right-click on the directory where you want to clone the Git repository:

OpenShift git cloning manually

Enter the SSL URL in the first field (you can find itL under 'My Applications' in OpenShift). Make sure you check Load Putty Key and that the directory points at you .ppk file.

This solution has been made available on StackOverflow too.

Making it a Spring Application

To transform the above application into a Spring application, follow instructions available here.

If you cannot execute Git from the command line, it is most probably not in the classpath. You will need to add it and open a new command line window.

That's it, you are ready to go. Open the application in your favorite IDE. Don't forget to (Git) push the application to make it accessible from its OpenShift URL.

Wednesday, 20 March 2013

'package javax.servlet.http does not exist' Solution

This is a common error which occurs when trying to compile a web project. This package is usually provided by the container. However, it is not (always) available at compile time and one should not include it in the final .war too.

If you are using Maven, the solution is simple. Add the following dependency with the provided scope:
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>2.5</version>
    <scope>provided</scope>
</dependency>
Your IDE will be able to compile your project and won't include the library in your .war.

You can also use the following dependency:
<dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-api</artifactId>
    <version>6.0</version>
    <type>jar</type>
    <scope>provided</scope>
</dependency>

Wednesday, 7 November 2012

Failed to execute goal org.apache.maven.plugins:maven-install-plugin:... (Access is denied)

This is the backporting of a question I asked on StackOverflow. I also provided the solution/workaround to it.

Issue

I was getting the following error when compiling a maven project with NetBeans:
[ERROR] Failed to execute goal
org.apache.maven.plugins:maven-install-plugin:2.3.1:install
(default-install) on project Plasma:
Failed to install artifact
net.dwst:Plasma:jar:1.0.0:
C:\...\.m2\repository\net\dwst\Plasma\1.0.0\Plasma-1.0.0.jar
(Access is denied) -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException:
Failed to execute goal
org.apache.maven.plugins:maven-install-plugin:2.3.1:install
(default-install) on project Plasma:
Failed to install artifact
net.dwst:Plasma:jar:1.0.0:
C:\...\.m2\repository\net\dwst\Plasma\1.0.0\Plasma-1.0.0.jar
(Access is denied)
  at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:203)
  at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:148)
  at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:140)
  at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
  at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
  at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
  at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
  at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:316)
  at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:153)
  at org.apache.maven.cli.MavenCli.execute(MavenCli.java:451)
  at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:188)
  at org.apache.maven.cli.MavenCli.main(MavenCli.java:134)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
  at java.lang.reflect.Method.invoke(Method.java:597)
  at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290)
  at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230)
  at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409)
  at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)
Caused by:
org.apache.maven.plugin.MojoExecutionException:
Failed to install artifact
net.dwst:Plasma:jar:1.0.0:
C:\...\.m2\repository\net\dwst\Plasma\1.0.0\Plasma-1.0.0.jar
(Access is denied)
  at org.apache.maven.plugin.install.InstallMojo.execute(InstallMojo.java:139)
  at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:107)
  at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:195)
... 19 more Caused by:
  org.apache.maven.artifact.installer.ArtifactInstallationException:
Failed to install artifact
net.dwst:Plasma:jar:1.0.0:
C:\...\.m2\repository\net\dwst\Plasma\1.0.0\Plasma-1.0.0.jar
(Access is denied)
  at org.apache.maven.artifact.installer.DefaultArtifactInstaller.install(DefaultArtifactInstaller.java:110)
  at org.apache.maven.plugin.install.InstallMojo.execute(InstallMojo.java:103)
... 21 more Caused by:
  org.sonatype.aether.installation.InstallationException:
Failed to install artifact
net.dwst:Plasma:jar:1.0.0:
C:\...\.m2\repository\net\dwst\Plasma\1.0.0\Plasma-1.0.0.jar
(Access is denied)
  at org.sonatype.aether.impl.internal.DefaultInstaller.install(DefaultInstaller.java:279)
  at org.sonatype.aether.impl.internal.DefaultInstaller.install(DefaultInstaller.java:190)
  at org.sonatype.aether.impl.internal.DefaultRepositorySystem.install(DefaultRepositorySystem.java:322)
  at org.apache.maven.artifact.installer.DefaultArtifactInstaller.install(DefaultArtifactInstaller.java:106)
... 22 more Caused by:
  java.io.FileNotFoundException:
C:\...\.m2\repository\net\dwst\Plasma\1.0.0\Plasma-1.0.0.jar
(Access is denied)
  at java.io.FileOutputStream.open(Native Method)
  at java.io.FileOutputStream.<init>(FileOutputStream.java:179
  at java.io.FileOutputStream.<init>(FileOutputStream.java:131)
  at org.sonatype.aether.impl.internal.DefaultFileProcessor.copy(DefaultFileProcessor.java:120)
  at org.sonatype.aether.impl.internal.DefaultInstaller.install(DefaultInstaller.java:255)
... 25 more [ERROR]  [ERROR]  [ERROR]
For more information about the errors and possible solutions, please read
the following articles: [ERROR] [Help 1]
http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
A workaround was to delete the .m2 content, but the issue would come back from time to time.

Solution

To solve the issue once for all, one has to delete the content of .m2 and re-install NetBeans from scratch.

Tuesday, 6 November 2012

Spring MVC Error Handling

This post describes the different techniques to perform error handling in Spring MVC 3. The code is available on GitHub in the Spring-MVC-Error-Handling directory. It is based on the Spring MVC With Annotations examples.

Handling Exceptions Before Spring 3

Before Spring 3, exceptions were handled with HandlerExceptionResolvers. This interface defines a single method:
ModelAndView resolveException(
  HttpServletRequest request,
  HttpServletResponse response,
  Object handler,
  Exception ex)
Notice it returns a ModelAndView object. Therefore, encountering an error meant being forwarded to a special page. However, this method is not suited for REST Ajax calls to JSONs (for example). In this case, we do not want to return a page, and we may want to return a specific HTTP status code. A solution, described further, is available.

For the sake of this example, two fake CustomizedException1 and CustomizedException2 exceptions have been created. To map customized exceptions to views, one could (and can still) use a SimpleMappingExceptionResolver:
SimpleMappingExceptionResolver getSimpleMappingExceptionResolver() {

    SimpleMappingExceptionResolver result
        = new SimpleMappingExceptionResolver();

    // Setting customized exception mappings
    Properties p = new Properties();
    p.put(CustomizedException1.class.getName(), "Errors/Exception1");
    result.setExceptionMappings(p);

    // Unmapped exceptions will be directed there
    result.setDefaultErrorView("Errors/Default");

    // Setting a default HTTP status code
    result.setDefaultStatusCode(HttpStatus.BAD_REQUEST.value());

    return result;

}
We map CustomizedException1 to the Errors/Exception1 JSP page (view). We also set a default error view for unmapped exception, namely CustomizedException2 in this example. We also set a default HTTP status code.

Here is the Exception1 JSP page, the default page is similar:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!doctype html>
<html lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html;" charset=UTF-8">
  <title>Welcome To Exception I !!!</title>
</head>
<body>
    <h1>Welcome To Exception I !!!</h1>
    Exception special message:<
    ${exception.specialMsg}
    <a href="<c:url value='/'/>">Home</a>
</body>
</html>
We also create a dummy error controller to help triggering these exceptions:
@Controller
public class TriggeringErrorsController {

    @RequestMapping(value = "/throwCustomizedException1")
    public ModelAndView throwCustomizedException1(
        HttpServletRequest request,HttpServletResponse response)
            throws CustomizedException1 {

        throw new CustomizedException1(
            "Houston, we have a problem!");
    }

    @RequestMapping(value = "/throwCustomizedException2")
    public ModelAndView throwCustomizedException2(
        HttpServletRequest request,HttpServletResponse response)
            throws CustomizedException2 {

        throw new CustomizedException2(
            "Something happened on the way to heaven!");
    }

    ...

}
Before Spring 3, one would declare a SimpleMappingExceptionResolver as a @Bean in web.xml. However, we will use a HandlerExceptionResolverComposite which we will describe later.

We also configure a target page for HTTP status codes in web.xml, which is an other way to deal with issues:
<error-page>
    <error-code>404</error-code>
    <location>/WEB-INF/pages/Errors/My404.jsp</location>
</error-page>

What Is New Since Spring 3.X?

The @ResponseStatus annotation is a new mean to set a Http status code when a method is invoked. These are handled by the ResponseStatusExceptionResolver. The @ExceptionHandler annotation facilitates the handling of exceptions in Spring. Such annotations are processed by the AnnotationMethodHandlerExceptionResolver.

The following illustrates how these annotations can be used to set an HTTP status code to the response when our customized exception is triggered. The message is returned in the response's body:
@Controller
public class TriggeringErrorsController {

    ...

    @ExceptionHandler(Customized4ExceptionHandler.class)
    @ResponseStatus(value=HttpStatus.BAD_REQUEST)
    @ResponseBody
    public String handleCustomized4Exception(
        Customized4ExceptionHandler ex) {

        return ex.getSpecialMsg();

    }

    @RequestMapping(value = "/throwCustomized4ExceptionHandler")
    public ModelAndView throwCustomized4ExceptionHandler(

        HttpServletRequest request,HttpServletResponse response)
            throws Customized4ExceptionHandler {

        throw new Customized4ExceptionHandler("S.O.S !!!!");

    }

}
On the user side, if one uses an Ajax call, the error can be retrieved with the following (we are using JQuery):
$.ajax({
    type: 'GET',
    url:  prefix + "/throwCustomized4ExceptionHandler",
    async: true,
    success: function(result) {
        alert('Unexpected success !!!');
    },
    error: function(jqXHR, textStatus, errorThrown) {
        alert(jqXHR.status + " " + jqXHR.responseText);
    }
});
Some people using Ajax like to return a JSON with the error code and some message to handle exceptions. I find it overkill. A simple error number with a message keeps it simple.

Since we are using several resolvers, we need a composite resolver (as mentioned earlier):
@Configuration
public class ErrorHandling {

    ...

    @Bean
    HandlerExceptionResolverComposite getHandlerExceptionResolverComposite() {

        HandlerExceptionResolverComposite result
            = new HandlerExceptionResolverComposite();

        List<HandlerExceptionResolver> l
            = new ArrayList<HandlerExceptionResolver>();

        l.add(new AnnotationMethodHandlerExceptionResolver());
        l.add(new ResponseStatusExceptionResolver());
        l.add(getSimpleMappingExceptionResolver());
        l.add(new DefaultHandlerExceptionResolver());

        result.setExceptionResolvers(l);

        return result;

}
The DefaultHandlerExceptionResolver resolves standard Spring exceptions and translates them to corresponding HTTP status codes.

Running The Example

Once compiled, the example can be run with mvn tomcat:run. Then, browse:

  http://localhost:8585/spring-mvc-error-handling/

The main page will look like this:

Spring MVC Error Handling

If you click on the Exception 1 link, the following page will display:

Spring MVC Exception Handling

If you click on the Exception 2 link, the following page will display:


If you click on the Exception Handler button, a pop-up will be displayed:

Spring MVC Exception Handling Pop-Up

These techniques are enough to cover error handling in Spring.

More Spring related posts here.

Tuesday, 21 August 2012

Hibernate/JPA Create-Drop Known Issue

Often, running Hibernate/JPA in create drop mode:

  <property name="hibernate.hbm2ddl.auto" value="create-drop"/>

generates multiple errors like this:

  Unsuccessful: alter table XXX drop constraint YYY

Thanks to feedback from Mikko Maunu on StackOverflow, the following issue can be explained by the fact that Hibernate does not check whether an object exists when it deletes it. The underlying database often triggers an error.

Since the create-drop mode drops many objects, these errors happen frequently, but can be ignored.

Friday, 19 November 2010

Timestamps in Cassandra

A couple of weeks ago, I had several splitting hair moments trying to understand timestamps in Cassandra.

Of course, I did my best to come with a clear mind, but like many, I was already polluted with SQL. Cassandra has nothing to do with SQL. You'll be wise to lock that monster in the basement before getting into Cassandra...
 
I did my best to avoid traps. I pulled my best analytic attitude. I proceeded methodically, step-by-step. I thought nothing could happen to me. Boy... did I confuse being anal with being accurate? I sure did! I made my own assumptions and found nothing to invalidate them in the documentation. This threw me into orbit faster than Superman on steroids. I started a lengthy discussion on the Cassandra mailing list. Yeah, the Ground control to Major Tom kind.
 
Let this post save you some time.
 
I am not going to cover Cassandra concepts here, as this has already been done very well by Ronald Mathies. I will only use reminders.
 
Error #1: A timestamp would be a column in SQL
 
Timestamps are part of the column triplet: name, value, timestamp. Cassandra columns are often described as triplets, but this can be misleading.

Timestamps are often used in SQL tables to keep track of a record status. For example, they can be used to monitor the status of a user in an application:
 
   USERID   TIMESTAMP  STATUS
   003341   001000506  REGISTERED 
   003341   001214566  CONFIRMED
   003341   001394230  LOGGED_IN 
   003341   002004447  LOGGED_OUT
   ... 

In the above SQL-like table, the timestamp is a SQL-like column. In Cassandra, there is no such thing as SQL-like columns for timestamps. A timestamp in Cassandra is a validity information for the Cassandra (name, value) pair.

A Cassandra name can be considered as the equivalent of a SQL-like column. For each row, a corresponding value and timestamp is defined and registered. Cassandra timestamps are not defined in SQL. There is no corresponding concept. Do not plan to use Cassandra timestamps as data in your application.

If you need to implement a SQL-like timestamp in your application, you will need to implement a Cassandra column like this:
 
   NAME  = 'MyTimeStamp'
   VALUE = 001000506, 001214566... // Row values
 
For each SQL-like timestamp row entry, one would set a Cassandra timestamp value too.

Error #2: Multiple Cassandra column value instances with different timestamps result in multiple entries
 
No. Just plain no. In the above example, multiple instances of a Cassandra column triplet with different Cassandra timestamp values would look like this:
 
   NAME           VALUE      TIMESTAMP
   'MyTimeStamp'  001000506  001000500 
   'MyTimeStamp'  001000506  001000503
   'MyTimeStamp'  001000506  001000510 
   'MyTimeStamp'  001000506  001000521
   ...
 
In this case, Cassandra does not register 4 entries, but only one. The one with the highest timestamp value: 001000521.

Error #3: I can use any type of value for Cassandra timestamps
 
In theory, yes you can. In practice, no it is not a good idea. Cassandra implements timestamps to facilitate idempotency. An operation is idempotent if applying it multiple times does not impact the final result. For example, I can add zero as many time as I want to a number, the result will always be that number.

In Cassandra, setting a column row value multiple times with the same timestamp does not change the final row value. Most application will use now() for their timestamp value, but it is not mandatory. For the sake of integrity, any type of value use for timestamp should enforce the idempotent property.

The motivation behind this is that, from time to time, Cassandra needs to re-submit a set of batch mutations on a node. The final result should be the same as if it was applied once. This also applies for your own batch mutations that you would like to re-apply at your application level.

Error #4: Cassandra secretly registers some kind of history about each columns entries
 
No. The only historical information stored by Cassandra during a write is the value of the timestamp of the corresponding column value. Any previous column value (i.e., Cassandra value-timestamp pair) is simply overwritten if its timestamp is older. The content is lost forever. No safety net. No second chance. No resurrection.
 
This is not to be confused with 'tombstoning', which happens when users explicitly delete previously created 'records'. Instead of performing the wipe out immediately, Cassandra flags the 'record' as 'to be deleted later'. It remains in a limbo state for some time, before being removed forever. However, the record content is lost as soon as it is flagged for delete. No safety net. No second chance. No resurrection.
 
You could say that Cassandra stores data on a big heap, but you only have access to the crust. And, every write with a higher Cassandra timestamp value results in an extra layer on the heap. Cassandra automatically deletes whatever is below the crust, synchronously or asynchronously.

Error #5: Concurrent writing operations in Cassandra are deterministic
 
No they are not, only reads are. Let's imagine a system with 11 Cassandra nodes operating with quorum. The quorum value is 11 DIV 2 + 1 = 6. Let's imagine two nodes A and B willing to perform a write on the same column at the same time:
 
   'MyColumn'  'MyValueA'  001000500
   'MyColumn'  'MyValueB'  001000500 
 
Who is going to win? The first that manages to perform writes on 6 nodes? No. You will notice a tie in the timestamps. In this case, 'value breaks timestamps ties'. If alphabetic order is set to sort column values, node B will win, because 'MyValueB' is greater than 'MyValueA', even if A manages to perform 6 writes before node B, for a given timestamp.
 
We could play semantics around the word 'deterministic'. What I mean here is that you have no guarantee that what a node writes is going to be the new crust of the heap for a given timestamp (I am not talking about different timestamps). Even a re-read would not help verifying this. You never know what write, with the same given timestamp, could happen in between.

Hence, concurrent writing is not 'locally' deterministic in Cassandra. You can't rely on what you just wrote to guess anything about the status of Cassandra content.
 
Concurrent readings are deterministic (assuming quorum mode). Why? Because Cassandra needs at least 6 coherent reads before returning a value to the user, for a given timestamp value (again, I am not talking about a different timestamp value situations). One way or the other, any potential timestamps tie will always have been resolved the same way on at least 6 nodes, before a column instance value is returned to the user. This is nothing more than an expression of determinism.
 
Error #6: Cassandra takes the current system clock value to automatically fabricate timestamps
 
No. The end user always has to provide the Cassandra column timestamp value when performing a write. It can be the current value of the system clock or any other value. The latter is not recommended though. A library facilitating the use of Cassandra can eventually do this for you automatically.

Keep in mind the idempotent property requirement described earlier in this post. 
 
Error #7: Cassandra manages timestamp ties on SuperColumn writes atomically
 
No.That's a tricky one. If two nodes perform a write on a SuperColumn (for example) using the same timestamp value, it can result in a write being a mix of the column values provided by both node A and node B. Some columns of B can beat A, and some columns of A can beat B. In other word, the crust can be a composite of A's values and B's values.
 
However, one does not need to delete columns one by one in SuperColumns. One can delete a whole SuperColumn (or rows) at once. This operation will happen atomically.
 
Error #8: Column inserts in SuperColums is atomic/deterministic for a given timestamp

No. Let's imagine two nodes willing to add columns in a super column. Node A wants to add column CA1. Node B wants to add column CB1 and CB2. CB2 will always be there, but you can't be sure who is going to win between CA1 and CB1.

So what is the solution?

If you are going to have concurrent writes, you will need a lock/synchronization system to tackle the issues described in this post.

Lamport's Bakery algorithm has been suggested. Another suggestion is to have nodes register update requests in a queue using (UUID, timestamp) unique pairs and have a unique 'thread' sort these and process them one-by-one.

A big thanks to Peter Schuller for clarifying these issues. This post is written when Cassandra 0.7.0 beta 3 just came out.