Hot questions for Using GlassFish in xml

Question:

I'm trying to start glassfish from eclipse luna but I have this error

Unable to start server due following issues:
java.io.FileNotFoundException: null/config/domain.xml (file or directory does not exist)

Glassfish works correctly if I start it with command

sudo ./asadmin start-domain domain1

from the shell.

How can I achieve the same result without going always through the terminal?


Answer:

I faced exactly this problem today. The domain path is missing in GlassFish configuration. This can happen when you add GlassFish 4.x server in all hassle without completing the entire Add Server wizard. The domain path is set during 3rd step which would be skipped when you finish the wizard already during 1st or 2nd step.

You can put it back in server's properties. Rightclick GlassFish entry in Servers view, choose Properties, open GlassFish and set the Domain path accordingly (it would be blank when you faced this problem).

No need to reinstall the whole IDE and server as suggested in other answer. That's way too drastic.

Question:

I have a Spring/Glassfish project created using a NetBeans wizard at the start of the year (so I don't remember the exact settings used to create it).

The strange thing though is that there is no glassfish-web.xml file inside the project whereas a different project created at the same time does have one.

Why would a project not have a glassfish-web.xml file?

I've been investigating a character encoding issue and some responses suggest adding to glassfish-web.xml:

 <sun-web-app>
      <parameter-encoding default-charset="UTF-8" />
 </sun-web-app>

However I can't do that as I don't have a glassfish-web.xml!

Is it possible to add one? If so what do I need to do in order to make sure it is read?


Answer:

If the file is included after project creation depends on the archetype (means the project template you have chosen) which is used. Some archetypes already contain a glassfish-web.xml, most of them don't.

You can easily create one by right-clicking on the folder WEB-INF, then choose New and GlassFish Descriptor. If this option is not available you may have to add the JSF facet to your project (right-click the project and add JSF in the frameworks tab).

You can also create the file manually, just create a new xml file in the WEB-INF folder, give the appropriate name and paste the desired content into the file.

See also:

  • glassfish-web.xml vs sun-web.xml vs web.xml

Question:

I've got a GlassFish 3.1.2 app server and I've started using JSP pages so I'm interested in configuring the encoding correctly for UTF-8.

My original working web.xml file started with

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" 
   "http://java.sun.com/dtd/web-app_2_3.dtd"> 

but then I added the following to it to force UTF-8 encoding

<jsp-config>
   <jsp-property-group>
       <url-pattern>*.jsp</url-pattern>
       <page-encoding>UTF-8</page-encoding>
   </jsp-property-group> 
</jsp-config>

and my GlassFish 3.1.2 server log file reported

Element type <jsp-config> must be declared web.xml

In an attempt to fix the error, I changed the start of my web.xml file to be

<?xml version="1.0" encoding="UTF-8"?>  
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
 version="2.4" >

and now I'm getting a GlassFish server error

Invalid Deployment Descriptors in Deployment descriptor file WEB-INF/web.xml ...
One of '{"http://java.sun.com/xml/ns/j2ee":servlet-class, 
         "http://java.sun.com/xml/ns/j2ee":jsp-file}' is expected.

Is my syntax off? How to get <jsp-config> working with header in xml.web file for version 2.3?

UPDATE 1

If I start the web.xml file as

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_3.xsd"
    version="2.3">

<display-name>myApp</display-name>
<description>My Application</description>

<listener>
    <listener-class>...</listener-class>
</listener>

<servlet>
    <servlet-name>MessageBrokerServlet</servlet-name>
    <display-name>MessageBrokerServlet</display-name>
    <servlet-class>...</servlet-class>
    <init-param>
        <param-name>...</param-name>
        <param-value>...</param-value>
   </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet>
  <servlet-name>Reg</servlet-name>
  <servlet-class>com.mydomain.servlet.Reg</servlet-class>
</servlet>

<servlet-mapping>
   <servlet-name>Reg</servlet-name>
   <url-pattern>/reg</url-pattern>
</servlet-mapping>

<welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
</welcome-file-list>

<jsp-config>
  <jsp-property-group>
      <url-pattern>*.jsp</url-pattern>
      <page-encoding>UTF-8</page-encoding>
  </jsp-property-group>
</jsp-config>

</web-app>

I see this error:

[#|2014-11-06T13:03:59.779-0800|SEVERE|glassfish3.1.2|javax.enterprise.system.tools.deployment.org.glassfish.deployment.common|_ThreadID=1;_ThreadName=Thread-2;|DPL8015:

Invalid Deployment Descriptors in Deployment descriptor file WEB-INF/web.xml in archive [myapp]. Line 7 Column 41 -- s4s-elt-character: Non-whitespace characters are not allowed in schema elements other than 'xs:appinfo' and 'xs:documentation'. Saw 'var _U = "undefined"; var g_HttpRelativeWebRoot = "/ocom/";'.|#]

[#|2014-11-06T13:03:59.779-0800|SEVERE|glassfish3.1.2|javax.enterprise.system.tools.deployment.org.glassfish.deployment.common|_ThreadID=1;_ThreadName=Thread-2;|DPL8005: Deployment Descriptor parsing failure : s4s-elt-character: Non-whitespace characters are not allowed in schema elements other than 'xs:appinfo' and 'xs:documentation'. Saw 'var _U = "undefined"; var g_HttpRelativeWebRoot = "/ocom/";'.|#]

UPDATE 2

Alternatively, I also have a glassfish-web.xml file in WEB-INF directory. If I revert the web.xml file back to original and place the <jsp-config> section in glassfish-web.xml instead of web.xml, the server starts fine. Which file is <jsp-config> supposed to go in, or does it matter?


Answer:

To configure JSP with UTF-8 you need to use, at the first line of the jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> 

You should use this but with your version:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">

An example of my web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
    <display-name>base</display-name>
    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                /WEB-INF/spring/spring-mvc-dispatcher.xml
            </param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/spring/spring-database.xml,
            /WEB-INF/spring/spring-security.xml
        </param-value>
    </context-param>
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

Question:

I am developing a Java EE application and I intend to run it on an Java EE Application Server (I have chosen Glassfish).

I know Glassfish is a reference implementation (RI) of the Java EE platform and it implements/contains individual reference implementations of the Java EE specifications. Correct me if i'm wrong but this leads me to understand that the binaries of Glassfish will contain all the relevant RIs jars inside it.

I am using Maven as my build/project management system and I will build/package my application up in a WAR file (because my application is a Java EE web application). Then I will deploy this WAR onto my Application Server - Glassfish and then it runs.

My question is, do I need to specify the Java EE dependencies in my Maven pom.xml file?

I'm using Eclipse as my IDE and at the moment I need to include those dependencies otherwise Eclipse will not recognise the Java EE sources - it will complain with compile time errors.

But if I do include in my pom.xml then does that not mean I'm duplicating the external dependencies (Java EE RI jars) in my application (in the WAR file) whereas an Application Server like Glassfish already provides it? because Maven downloads those jars and put into your code base - right?

for.eg (just using JMS as an example):

<dependency>
    <groupId>javax.jms</groupId>
    <artifactId>javax.jms-api</artifactId>
    <version>2.0.1</version>
</dependency>

do I need above? I know I definitely do if I were developing against Tomcat because it is a Servlet container and doesn't have the other full Java EE specifications.

  • this is the part where I'm a bit confused about and I hope someone will shed a light on this.

Answer:

GlassFish already has the Java EE jars, but you will need it for compilation purpose so you have to add a dependency for those jars but provide the scope as "provided" so these jars will not be bundled in your war or ear file. please see below example

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

Question:

I am getting a show-stopping error trying to obtain JSON output from a basic JAX-RS setup. I am trying Netbeans' Web Services wizards which has generated this default 'service' code:

package service;

import entities.Manufacturer;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;


@Stateless
@Path("entities.manufacturer")
public class ManufacturerFacadeREST extends AbstractFacade<Manufacturer> {

    @PersistenceContext(unitName = "RestDemoPU")
    private EntityManager em;

    public ManufacturerFacadeREST() {
        super(Manufacturer.class);
    }

    @POST
    @Override
    @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public void create(Manufacturer entity) {
        super.create(entity);
    }

    @PUT
    @Path("{id}")
    @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public void edit(@PathParam("id") Integer id, Manufacturer entity) {
        super.edit(entity);
    }

    @DELETE
    @Path("{id}")
    public void remove(@PathParam("id") Integer id) {
        super.remove(super.find(id));
    }

    @GET
    @Path("{id}")
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public Manufacturer find(@PathParam("id") Integer id) {
        return super.find(id);
    }

    @GET
    @Override
    @Produces({MediaType.APPLICATION_JSON})
    public List<Manufacturer> findAll() {
        return super.findAll();
    }

    @GET
    @Path("{from}/{to}")
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public List<Manufacturer> findRange(@PathParam("from") Integer from, @PathParam("to") Integer to) {
        return super.findRange(new int[]{from, to});
    }

    @GET
    @Path("count")
    @Produces(MediaType.TEXT_PLAIN)
    public String countREST() {
        return String.valueOf(super.count());
    }

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

}

The error is showing up when I remove the @Produces annotation for MediaType.APPLICATION_XML in the findAll() method to leave MediaType.APPLICATION_JSON (I only want JSON output).

XML is fine - the JSON-only annotation raises a HTTP Status 500 - Internal Server Error with Java exception: javax.servlet.ServletException: org.glassfish.jersey.server.ContainerException: java.lang.NoClassDefFoundError: org/xml/sax/helpers/DefaultHandler error.

Using GlassFish 4.1.1. Server log is:

Info:   EclipseLink, version: Eclipse Persistence Services - 2.6.1.v20150605-31e8258
Info:   /file:/home/lemon/code/java/Netbeans/RestDemo/build/web/WEB-INF/classes/_RestDemoPU login successful
Warning:   StandardWrapperValve[service.ApplicationConfig]: Servlet.service() for servlet service.ApplicationConfig threw exception
java.lang.ClassNotFoundException: org.xml.sax.helpers.DefaultHandler not found by org.eclipse.persistence.moxy [6]
    at org.apache.felix.framework.BundleWiringImpl.findClassOrResourceByDelegation(BundleWiringImpl.java:1532)
    at org.apache.felix.framework.BundleWiringImpl.access$400(BundleWiringImpl.java:75)
    at org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.loadClass(BundleWiringImpl.java:1955)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at org.eclipse.persistence.jaxb.BeanValidationHelper.<clinit>(BeanValidationHelper.java:53)
    at org.eclipse.persistence.jaxb.JAXBBeanValidator.isConstrainedObject(JAXBBeanValidator.java:257)
    at org.eclipse.persistence.jaxb.JAXBBeanValidator.shouldValidate(JAXBBeanValidator.java:208)
    at org.eclipse.persistence.jaxb.JAXBMarshaller.validateAndTransformIfNeeded(JAXBMarshaller.java:587)
    at org.eclipse.persistence.jaxb.JAXBMarshaller.marshal(JAXBMarshaller.java:481)
    at org.eclipse.persistence.jaxb.rs.MOXyJsonProvider.writeTo(MOXyJsonProvider.java:949)
    at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.invokeWriteTo(WriterInterceptorExecutor.java:265)
    at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteTo(WriterInterceptorExecutor.java:250)
    at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
    at org.glassfish.jersey.server.internal.JsonWithPaddingInterceptor.aroundWriteTo(JsonWithPaddingInterceptor.java:106)
    at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
    at org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor.aroundWriteTo(MappableExceptionWrapperInterceptor.java:86)
    at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
    at org.glassfish.jersey.message.internal.MessageBodyFactory.writeTo(MessageBodyFactory.java:1130)
    at org.glassfish.jersey.server.ServerRuntime$Responder.writeResponse(ServerRuntime.java:683)
    at org.glassfish.jersey.server.ServerRuntime$Responder.processResponse(ServerRuntime.java:424)
    at org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:414)
    at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:312)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
    at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:292)
    at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1139)
    at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:460)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:386)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:334)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
    at java.lang.Thread.run(Thread.java:745)

Answer:

Downgraded to Glassfish 4.1 from 4.1.1 solved the problem.

Question:

I have a web services app developed using CXF 2.7.13. When I deploy on my local Tomcat instance, everything works, but when switching to a glassfish 4 instance, I get the following exception:

java.lang.RuntimeException: Cannot create a secure XMLInputFactory
    at org.apache.cxf.staxutils.StaxUtils.createXMLInputFactory(StaxUtils.java:315)
    at org.apache.cxf.staxutils.StaxUtils.getXMLInputFactory(StaxUtils.java:265)
    at org.apache.cxf.staxutils.StaxUtils.createXMLStreamReader(StaxUtils.java:1701)
    at org.apache.cxf.interceptor.StaxInInterceptor.handleMessage(StaxInInterceptor.java:123)
    at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:272)
    at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
    at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:241)
    at org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:248)
    at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:222)
    at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:153)
    at org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:171)
    at org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:286)
    at org.apache.cxf.transport.servlet.AbstractHTTPServlet.doPost(AbstractHTTPServlet.java:206)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
    at org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:262)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
    at java.lang.Thread.run(Thread.java:722)]]

From what I've read, it seems Woodstox api (woodstox-core-asl.jar) dependency from CXF is conflicting with glassfish's own version of the library. CXF uses Woodstox 4.4.1 while my glassfish 4 instance, I've checked, uses 4.1.2.

So my first attempt was to try and exclude CXF's dependency and declare my own Woodstox 4.1.2 dependency on my POM in order for everyone to use the same version. But this didn't solve the problem.

I also tried straight up removing this dependency from my POM and checked it's not included in the WAR before deploying, also to no avail (same exception).

I've only managed to deploy on glassfish by removing the .jar from the modules dir of the server, but this is somehting I cannot do on my production servers, by requirement.

Is there anything else I can try?


Answer:

It was so easy and I am ashamed I've spent 5 hours trying to solve with maven while it was on the official documentation page (http://cxf.apache.org/docs/application-server-specific-configuration-guide.html):

CXF Interceptors will not work in Glassfish without this sun-web.xml file to configure the classloader. By default, Glassfish will use Metro for JAX-WS services so the classloader needs to be configured to allow CXF libraries to provide JAX-WS services. The following sun-web.xml xml source was added to /WEB-INF to resolve this issue:

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE sun-web-app PUBLIC
'-//Sun Microsystems, Inc.//DTD Application Server 9.0 Servlet
 2.5//EN' 'http://www.sun.com/software/appserver/dtds/sun-web-app_2_5-0.dtd>
 <sun-web-app> <class-loader delegate="false"/> </sun-web-app>

Question:

I have this project name in my eclipse 'abc-work' and when I run it on localhost the url is

http://localhost:8080/abc-work

The default file or page that opens is (as per web.xml below)

<display-name>abc-work</display-name>
  <welcome-file-list>
    <welcome-file>account/login.xhtml</welcome-file>
  </welcome-file-list>

I successfully deployed this application on a cloud and linked it to my domain.

The URL now is:

http://www.abcwork.in/abc-work/

Now, the problem is - I need to remove the last /abc-work/ from this link, login page should directly open with the link http://www.abcwork.in/

My project is in Glassfish 3.1.2

I need to make this change, maybe by URL rewriting in web.xml, but I have no clue how to achieve it.

I have tried changing context root from Eclipse project properties, tried changing glassfish-web.xml's context root too - did not work for me.

Any help shall be highly appreciated. Thanks.


Answer:

Option 1: You can set one of your webapps as default. This can be done with the admin console:

Configuration --> Virtual Servers --> server

Then select your default web application from the drop-down menu. If your webserver port is 8080, you can start your application now by:

http://hostname:8080

instead of http://hostname:8080/webapp

Notice that "server" is the name of Glassfish's default virtual server. If you configured a different virtual server for your webapp you need to change it accordingly.

Furthermore regarding this source, there might be some problems with JDBCRealms.

Option 2: You could also deploy your default webapp to "/" instead of "/webapp" but I think the first option is more flexible.

Question:

When I run my project on IntelliJ, it gives me a java.io.IOException: org.xml.sax.SAXParseException error.

I can't find the problem. Can someone help me with this error?

web.xml

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

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
         http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
</web-app>

Persistence.xml

<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
             http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
             version="2.1">

    <persistence-unit name="aquadinePU" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/aquadine?autoReconnect=true&amp;useSSL=false&amp;allowPublicKeyRetrieval=true" />
            <property name="hibernate.hbm2ddl.auto" value="update"/>
            <property name="javax.persistence.jdbc.user" value="root" />
            <property name="javax.persistence.jdbc.password" value="ruta" />
            <property name="hibernate.show_sql" value="true"/>
        </properties>
    </persistence-unit>

</persistence>

The error for web.xml is as follows:

java.io.IOException: org.xml.sax.SAXParseExceptionpublicId: http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd; lineNumber: 1; columnNumber: 1; Deployment descriptor file WEB-INF/web.xml in archive [aquadine-jee].  Premature end of file.

The error for persistence.xml is as follows:

java.io.IOException: org.xml.sax.SAXParseExceptionpublicId: http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd; lineNumber: 1; columnNumber: 1; Deployment descriptor file META-INF/persistence.xml in archive [classes].  Premature end of file.

Answer:

We also started getting this Error since a few days. The uri:

 http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd 

returns a status code 301 which the SAX Parser cant handle.

Our hotfix was to change the schema location in the web.xml to the new file:

xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://www.oracle.com/webfolder/technetwork/jsc/xml/ns/javaee/web-app_3_1.xsd

Question:

I have a Netbeans project, from which I build a .war file. I now deploy two instances of that war file on my glassfish server, each with a different context root, e.g. mydomain.com/abc and mydomain.com/def

This works fine but they are still operating on the same database, since I declare the persistence unit in the persistence.xml and the glassfish-resources.xml.

My glassfish-resources.xml file:

...
<jdbc-resource  enabled="true"
                jndi-name="jdbc/abc"
                object-type="user"
                pool-name="abcPool">
    <description/>
</jdbc-resource>

<jdbc-connection-pool
    ...
    name="abcPool"
    ...
    <property name="URL" value="jdbc:mysql://localhost:3306/abc"/>
    ...
</jdbc-connection-pool>

My persistence.xml file:

...
<persistence-unit name="abcPU" transaction-type="JTA">
    <jta-data-source>jdbc/abc</jta-data-source>
    ...
</persistence-unit>
...

Does anybody have a solution on how to have two instances of one war file, operating on two different databases?

Is there maybe a way to upload a different glassfish-resources.xml and persistence.xml to each application, overwriting the packaged one?

It would be acceptable to change the module descriptors in the glassfish domain admin console once the application is deployed, if that is possible.

If screenshots from the glassfish domain admin console are needed, please write in the comments, I will add them.

Thank you in advance!


Answer:

Easiest approach in my opinion would be to have two different builds.

Basically you may create two different .war files. Each one with a different persistence.xml file in it. One pointing to the JDBC resource ABC and the other one pointing to the JDBS resource DEF.

Build tools like gradle+Jenkins may support you with this.

You will find lots of information about similar tasks, if you search for how to create builds with a different configuration for testing vs. productive system. This is a very common task.

Here might be a starting point for what you are looking for: Create multiple .WAR files with different dependencies in Gradle

Question:

Trying to setup glassfish server for netbeans. I started the server and ran the project(default web project) and it gives this error:

In-place deployment at C:\Users\Michael\Desktop\WebApplication2\build\web

GlassFish Server, deploy, null, false

C:\Users\Michael\Desktop\WebApplication2\nbproject\build-impl.xml:1045: 

The module has not been deployed.

See the server log for details.

BUILD FAILED (total time: 0 seconds)

edit: server log: https://justpaste.it/u702


Answer:

Become owner of the Tomcat directory.. On Linux or BSD do this:

chown -R username /usr/local/apache-tomcat-8.0/

To show how's use the command ls-l He was root now will show your username.

*check in which path to the directory's Tomcat on your distro.

Question:

I have a restful web service created on netbeans and connected to a database. when I start and deploy the web Service, it works great and returns the right information, but if I do any update in the database the xml content don't update, it just still returning xml with the old content. To return the updated content I need to redeploy the web service. Anyone knows how to solve the problem?


Answer:

Fist of all, isolate if the data on the DB gets updated by running a query. If it fails you might need to make sure that you're committing the data properly.

If the data is properly stored, you might have cache issues. Please post some sample code of your application so that we can provide deeper insights (controller and service layer).

Question:

I've got an Java EE Web app. I am using this to manage users in a database, so they can login. The thing is the the productowner wants a option to login without using the DB, I have already made that. But I am having a problem deploying this to glassfish now, since when deploying glassfish checks the connection, but I want to be able to configure that e.g. this build I don't want to use a database connection, but I also want to be easily enable it again.

Does anyone know a solution for this?

This is the persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
  <persistence-unit name="WebApp_PerformancePU" transaction-type="JTA">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <jta-data-source>jdbc/myWebApp</jta-data-source>
    <class>db.entities.User</class>
    <properties>
        <property name="eclipselink.ddl-generation" value="create-or-extend-tables"/>
    </properties>
  </persistence-unit>
</persistence>

This the glassfish-resource.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE resources PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Resource Definitions//EN" "http://glassfish.org/dtds/glassfish-resources_1_5.dtd">
<resources>
  <jdbc-resource enabled="true" jndi-name="jdbc/myWebApp" object-type="user" pool-name="webAppPool">
    <description/>
  </jdbc-resource>
  <jdbc-connection-pool allow-non-component-callers="false" associate-with-thread="false" connection-creation-retry-attempts="0" connection-creation-retry-interval-in-seconds="10" connection-leak-reclaim="false" connection-leak-timeout-in-seconds="0" connection-validation-method="auto-commit" datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" fail-all-connections="false" idle-timeout-in-seconds="300" is-connection-validation-required="false" is-isolation-level-guaranteed="true" lazy-connection-association="false" lazy-connection-enlistment="false" match-connections="false" max-connection-usage-count="0" max-pool-size="32" max-wait-time-in-millis="60000" name="webAppPool" non-transactional-connections="false" pool-resize-quantity="2" res-type="javax.sql.ConnectionPoolDataSource" statement-timeout-in-seconds="-1" steady-pool-size="8" validate-atmost-once-period-in-seconds="0" wrap-jdbc-objects="false">
    <property name="URL" value="jdbc:mysql://localhost:3306/webapp?zeroDateTimeBehavior=convertToNull"/>
    <property name="User" value="root"/>
    <property name="Password" value=""/>
  </jdbc-connection-pool>
</resources>

When deploying on glassfish, glassfish says this:

Error occurred during deployment: Exception while deploying the app [WebApp] : Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException Internal Exception: java.sql.SQLException: Error in allocating a connection. Cause: Connection could not be allocated because: Communications link failure The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server. Error Code: 0. Please see server.log for more details.

Answer:

I've managed to do this, by setting "jbdc-resouce" enabled on false in the " glassfish-resources.xml". And in the "persistence.xml" commenting the "jta-data-source" line.

Question:

I've ported an application from JEE6 to JEE7 (glassfish 3.1.2.2 to 4.1),

I've upgraded the META-INF/validation.xml with latest version (as stated here): http://antoniogoncalves.org/2013/06/04/java-ee-7-deployment-descriptors/):

<validation-config
        xmlns="http://jboss.org/xml/ns/javax/validation/configuration"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://jboss.org/xml/ns/javax/validation/configuration validation-configuration-1.1.xsd"
        version="1.1">
    <message-interpolator>com.infomaxgroup.adaecommerce.validation.DatabaseMessageInterpolator</message-interpolator>
</validation-config>

The custom messageinterpolator is never called, so I've tried to set a name of a non existent class:

    <message-interpolator>foo.foo.foo.Bar</message-interpolator>

and tried to insert an error (xxx after the opening tag):

    <message-interpolatorxxx>foo.foo.foo.Bar</message-interpolator>

I've no exception into log, seems like that validation.xml (that my JEE6 application processes good) is not loaded at all into my ported JEE7 application...

Any idea on how to solve the issue ?

Many thanks in advance...


Answer:

Solved from myself,

the problem was that validation.xml must be placed into META-INF/validation.xml folder of the "ejb module", into my JEE6 application I had that file into WEB-INF folder of the "web module" (strangely the JEE6 application works good...), now my JEE7 application correctly load validation.xml configuration and works using the message interpolator, very good !

Question:

I try to enable my CorsFilter to allow access from my AngularClient. I have searched up on google how to do it but i can´t find anything that works for me.

When i am starting up my Server it throws an Exception that my CorsFilter can not be cast to an servlet.Filter.

My CrossOriginResourceSharingFilter class:

import java.util.logging.Filter;
import java.util.logging.LogRecord;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.Provider;

/**
 *
 * @author Struckl
 */
@Provider
public class NewCrossOriginResourceSharingFilter implements ContainerResponseFilter, Filter {

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext response) {
        response.getHeaders().putSingle("Access-Control-Allow-Origin", "*");
        response.getHeaders().putSingle("Access-Control-Allow-Methods", "OPTIONS, GET, POST, PUT, DELETE");
        response.getHeaders().putSingle("Access-Control-Allow-Headers", "Content-Type");
    }

    @Override
    public boolean isLoggable(LogRecord record) {
        throw new UnsupportedOperationException("Hast schon gedacht das des implementiert is.");
    }

}

My web.xml:

<web-app xmlns="http://java.sun.com/xml/ns/javaee" version="3.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">   

    <filter>
        <filter-name>CORSFilter</filter-name>
        <filter-class>Misc.NewCrossOriginResourceSharingFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>CORSFilter</filter-name>
        <url-pattern>/SypServer/*</url-pattern>
    </filter-mapping>

    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

My Stacktrace:

    at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:135)
    at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:5329)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:5943)
    at com.sun.enterprise.web.WebModule.start(WebModule.java:691)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:1041)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:1024)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:747)
    at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:2286)
    at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:1932)
    at com.sun.enterprise.web.WebApplication.start(WebApplication.java:139)
    at org.glassfish.internal.data.EngineRef.start(EngineRef.java:122)
    at org.glassfish.internal.data.ModuleInfo.start(ModuleInfo.java:291)
    at org.glassfish.internal.data.ApplicationInfo.start(ApplicationInfo.java:352)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:500)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:219)
    at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:491)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:539)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:535)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:360)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:534)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:565)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:557)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:360)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:556)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1464)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1300(CommandRunnerImpl.java:109)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1846)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1722)
    at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:534)
    at com.sun.enterprise.v3.admin.AdminAdapter.onMissingResource(AdminAdapter.java:224)
    at org.glassfish.grizzly.http.server.StaticHttpHandlerBase.service(StaticHttpHandlerBase.java:189)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.ClassCastException: Misc.NewCrossOriginResourceSharingFilter cannot be cast to javax.servlet.Filter
    at com.sun.enterprise.web.WebContainer.createFilterInstance(WebContainer.java:1007)
    at com.sun.enterprise.web.WebModule.createFilterInstance(WebModule.java:2143)
    at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:264)
    at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:131)
    ... 51 more

Maybe i have missed out on something very important or i have overseen a simple mistake but i can´t figure out why it won´t run.


Answer:

You are implementing java.util.logging.Filter instead of javax.servlet.Filter. Auto-import FTW. ;)