Hot questions for Using GlassFish in http

Question:

I am implementing a basic client server architecture using REST services for the first time. This time I making it more complicated with including some more classes and services with sharing class objects as parameters between client and server. I am running server on ApacheTomcat7. It is getting executed successfully. When I am running my client it is giving me error: javax.ws.rs.InternalServerErrorException: HTTP 500 Internal Server Error I tried debugging my code, it seems like I am not properly receiving/sending response. I know its not wise idea to share all classes here but I has no choice since it has wasted my time a lot. Any help will be appreciated. Thanks in advance.

Following is my ImageProgress class. This class is present at both server and client.

@XmlRootElement
public class ImageProgress{
    private String name;

    public ImageProgress( String image_name){
        this.name = image_name;
    }

    public String getName() {
        return name;
    }

    public void setName( String name ){
        this.name = name;
    }
}

HPCResponse is the class whose object will be returned to client as the server response. HPCResponse will basically return the ImageProgress object which will give me the intended result.

@XmlRootElement
public class HPCResponse
{
    private ImageProgress imgProgress;

    public ImageProgress getImgProgress() {
        return imgProgress;
    }

    public void setImgProgress(ImageProgress imgProgress) {
        this.imgProgress = imgProgress;
    }
}

Following is the service class from server named HpcService which will return the HPCResponse's object as response. As you can see the method startAnalysing accepts object of HPCInfo. Description of HPCInfo is also given below.

@Path( "/hpc" )
@Consumes( MediaType.APPLICATION_XML )
@Produces( MediaType.APPLICATION_XML )
public class HpcService{

    public HPCInfo hpcInfo;
    public HPCResponse hpcResponse;

    @POST
    @Path( "/analyze" )
    public HPCResponse startAnalysing(HPCInfo _hpcInfo){

        System.out.println( "Started Analyzing..." );

        hpcInfo = _hpcInfo;
        hpcInfo.getImagePath();        

        hpcResponse = new HPCResponse();
        ImageProgress iProg = new ImageProgress(hpcInfo.getImagePath());
        hpcResponse.setImgProgress(iProg);

        System.out.println("Returning response...");
        return hpcResponse;
    }
}

HPCInfo class is also at both client and server. HPCInfo class:

    @XmlRootElement
    public class HPCInfo
    {
        private String imagePath = "";

        public String getImagePath(){
            return imagePath;
        }

        public void setImagePath( String imagePath ){
            this.imagePath = imagePath;
        }
    }

And finally its my client calling for the HPCService.

public class TestClient {
    private static String webServiceURI = "http://localhost:8080/TestServer123";
    public static void main(String[] args) {
        String input = "ABNKidney.scn";
        ClientConfig clientConfig = new ClientConfig();
        Client client = ClientBuilder.newClient(clientConfig);
        URI serviceURI = UriBuilder.fromUri(webServiceURI).build();

        WebTarget webTarget = client.target(serviceURI);

        HPCInfo info = new HPCInfo();
        info.setImagePath(input);

        webTarget = webTarget.path("test").path("hpc").path("analyze");

        HPCResponse hResponse = webTarget.request().accept(MediaType.APPLICATION_XML).post(Entity.entity(info, MediaType.APPLICATION_XML), HPCResponse.class);
    }
}

This is the full error description I am getting:

javax.ws.rs.InternalServerErrorException: HTTP 500 Internal Server Error
    at org.glassfish.jersey.client.JerseyInvocation.convertToException(JerseyInvocation.java:968)
    at org.glassfish.jersey.client.JerseyInvocation.translate(JerseyInvocation.java:795)
    at org.glassfish.jersey.client.JerseyInvocation.access$500(JerseyInvocation.java:91)
    at org.glassfish.jersey.client.JerseyInvocation$2.call(JerseyInvocation.java:683)
    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:228)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:424)
    at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:679)
    at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:435)
    at org.glassfish.jersey.client.JerseyInvocation$Builder.post(JerseyInvocation.java:338)
    at com.TestClient.main(TestClient.java:34)

Answer:

One way to debug things like this is to create a simple ExceptionMapper to catch exceptions that are not mapped. When there is no mapper, often the exception will bubble up to the container level, which just gives us generic 500 server error (which most of the time is of little help).

@Provider
public class DebugExceptionMapper implements ExceptionMapper<Exception> {

    @Override
    public Response toResponse(Exception exception) {
        exception.printStackTrace();
        return Response.serverError().entity(exception.getMessage()).build();
    } 
}

Then just register the mapper. When running a simple test with your ImageProgress class, when the exception is thrown, the stacktrace gets printed, and you can see the exception message

...ImageProgress does not have a no-arg default constructor

So just add a default (no-arg constructor) to the ImageProgress class. This is a requirement with JAXB models.

Question:

Please see the attached images, Please help me to understand the relationship between thread pool(max and min thread pool size), acceptor threads and its max connection count and HTTP max connection count.

Thread Pool :

HTTP:

Transport TCP:


Answer:

First I'll give you some official documentation

Thread Pool

The thread pool is the max number of simultaneous requests the server can handle. The server has a queue of connections awaiting to be processed by a thread.

Keep in mind that a thread will be a long the request life. That is, not only when reading HTTP request from socket, or when writing HTTP response to client, but all time it is dealing with business logic, awaiting DB to finish, writing to a log file, sending/receiving WS mehtods, ...

Read: https://docs.oracle.com/cd/E18930_01/html/821-2431/abehk.html

HTTP Max Connections

HTTP Server is listening to clients requests, and every client has an associated connection queue where requests are queuing to be processed by a thread from the Thread Pool.

Here is where live the threads waiting to serve queued requests.

Read: https://docs.oracle.com/cd/E18930_01/html/821-2431/abegk.html

Transport acceptor threads

Is the number that states how many threads can hold your server in accept mode for every listen socket at any time. Oracles documentation recommends to have this number below of number of the numbers of CPU's.

That is, this is the number of sockets that are reading/writing simultaneously. You can think of a direct relation with thread pool, but remember a thread is not only to read/write from/to client, but for processing request too.

Read: http://docs.oracle.com/cd/E18930_01/html/821-2431/gkxjt.html

My Explanation

So, your server will have a queue for every client (listen socket) where there can be no more than Max Connections. This connections will be processed by a Thread Pool and at the same time it can not be more than Acceptor Threads processing/accepted sockets.

If a client request is awaiting more thant Time out it will be rejected. Min Thread Pool ensures you to have a minimun of threads, ready to processing. And Max Connection Count limits the total of listen sockets you can have waiting. If this last limit is exceed, new connections will be rejected.

Hope it helps.

Question:

I have an instance of glassfish 4.1.1 running and I added my own certificate to my applications, until then everything is Ok..

But, when I tried to access the glassfish admin(DAS) the connection was unstrusted and the button to add exception disappears.

Then I found some interesting links talking about that, like :

  • Right way to configure Glassfish SSL certificate nickname?

I tried this:

asadmin enable-secure-admin --adminalias=myNewAlias --instancealias myNewAlias
asadmin restart-domain domain1

This way the untrusted connection message disappears and the certicate properly appears, but when I try the authentication throw an error:

According to the comments of the answer from the link, it is very similar what that guy had but I could not solve it doing:

  • Removing the s1as certificate from ~.gfclient/truststore
  • Restart the domain with my new alias cert

How could I change the s1as certificate properly? In order to my DAS works...

I'am using Ubuntu 14 with java-1.8.0-openjdk-amd64.

Step 1:

Step 2:

The server log showing these lines:

[2016-10-18T10:38:12.565+0200] [glassfish 4.1] [SEVERE] [] [org.glassfish.admingui] [tid: _ThreadID=51 _ThreadName=admin-listener(2)] [timeMillis: 1476779892565] [levelValue: 1000] [[ javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target; javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target; restRequest: endpoint=https://localhost:4848/management/domain/anonymous-user-enabled attrs={} method=GET]]


Answer:

I finally solved it, why it was happening? Using the @Mike explanation:

That is because there is both a keystore and a truststore for GlassFish, and the Admin console effectively uses 2-way SSL authentication for the initial login. If you change the s1as certificate, you will also need to change the glassfish-instance certificate

In my case I was trying to use my own certificate but I did not delete the oldest certificates properly on cacerts.jks and keystore.jks files.

I was running the code bellow without firstly remove the s1as and glassfish-instance from files, that was my wrong step...

asadmin enable-secure-admin --adminalias=myNewAlias --instancealias myNewAlias

To your Domain Administration Server (DAS) on Glassfish 4.1.1 run with your own certificate you must follow these steps:

1) Insert your own certificate into cacerts.jks and keystore.jks files:

In my case I am using certificate pkcs12:

keytool -importkeystore -deststorepass changeit -destkeypass changeit -destkeystore keystore.jks -srckeystore myOwnCert.p12 -srcstoretype PKCS12 -srcstorepass changeit -alias myOwnAlias

keytool -importkeystore -deststorepass changeit -destkeypass changeit -destkeystore cacerts.jks -srckeystore myOwnCert.p12 -srcstoretype PKCS12 -srcstorepass changeit -alias myOwnAlias

If you have another kind of certificate you must search how to insert inside this two files your certificate type:

$GLASSFISH_HOME/domains/domain1/config/cacerts.jks - truststore - holding all the public keys $GLASSFISH_HOME/domains/domain1/config/keystore.jks - keystore - holding all the private keys

References:

Session 6. Security configuration before first startup: https://www.nabisoft.com/tutorials/glassfish/installing-glassfish-41-on-ubuntu

http://peter-butkovic.blogspot.com.es/2013/02/glassfish-default-keystore-and.html

https://www.sslshopper.com/article-most-common-java-keytool-keystore-commands.html?jn9ed3e997=3

https://glassfish.java.net/docs/4.0/security-guide.pdf

2) Delete the oldest self-signed certificates:

By default, when you run the command enabled-secur-admin the certificate assigned to this instance is s1as and the public is glassfish-instance, as explained by @Mike into another stack-overflow question the certificates remains even if you force to run with another certificate. Delete both using these commands:

#Restart your domain without secure-admin
$GLASSFISH_HOME/bin/asadmin disable-secure-admin


#Go to your domain config folder to remove the certificates:
cd $GLASSFISH_HOME/domains/domain1/config/
keytool -delete -alias s1as -keystore keystore.jks -storepass changeit
keytool -delete -alias glassfish-instance -keystore keystore.jks -storepass changeit
keytool -delete -alias glassfish-instance -keystore cacerts.jks -storepass changeit
keytool -delete -alias s1as -keystore cacerts.jks -storepass changeit

References:

Thanks @Mike: Right way to configure Glassfish SSL certificate nickname?

https://glassfish.java.net/docs/4.0/security-guide.pdf (page ~80)

3) Restart the security-admin with your own alias set on the first step

$GLASSFISH_HOME/bin/asadmin enable-secure-admin --adminalias=myOwnAlias --instancealias myOwnAlias

$GLASSFISH_HOME/bin/asadmin restart-domain

In theory, it is done, You'll be able to access the DAS with your own certificate... ;)

Question:

I've gone through the steps to add an SSL certificate into glassfish v4. I've verified that it works via browsers and via my java swing client (i'm using apache's http client libraries on the client side)

what doesn't work is the admin console! Since successful import of the SSL, I can no longer connect to the admin console, http://www.myhost.com:4848, I still get the login screen, the admin username/password combo that always worked has ceased to work. I've also noticed issues when trying to deploy a web app from netbeans, but i haven't researched things enough to know if it's the same problem.

Following are the steps I took to add the ssl cert. These are directly lifted from the glassfish v4 security guide, p1-26 through p1-29. I did add a step to change the master password, but I should have done that earlier, but I'm including it here. I also omitted or changed certain folder names in the steps below for my privacy, but other than that, I've copied all this out of the terminal application.

Does anyone know what went wrong with the admin? One thing to note - following the admin and security guides for glassfish said that I could ovrwrite the s1as alias. you'll notice that i used that alias when working with the cert in the steps below

thanks in advance for your help!

step 1 - stop the server

/usr/home/myhost                                                                                                                                                                                                                                           
110 % glassfish4/bin/asadmin stop-domain domain1
Waiting for the domain to stop .
Command stop-domain executed successfully.

step 2 - update master password

/usr/home/myhost
110 % glassfish4/bin/asadmin
Use "exit" to exit and "help" for online help.
asadmin> change-master-password domain1
Enter the current master password>
Enter the new master password>
Enter the new master password again>
Command change-master-password executed successfully.
asadmin> exit
Command multimode executed successfully.

step 3 - change to directory of keyfile

/usr/home/myhost
111 % cd glassfish4/glassfish/domains/domain1/config/

step 4 - remove s1as from keystore

/usr/home/myhost/glassfish4/glassfish/domains/domain1/config
113 % keytool -delete -alias s1as -keystore keystore.jks
Enter keystore password:

step 5 - Generate a new key pair

/usr/home/myhost/glassfish4/glassfish/domains/domain1/config
114 % keytool -genkey -alias s1as -keyalg RSA -keystore keystore.jks -keysize 2048
Enter keystore password:
What is your first and last name?
[Unknown]:  www.myhost-dev.com
What is the name of your organizational unit?
[Unknown]:  development
What is the name of your organization?
[Unknown]:  myhost, inc
What is the name of your City or Locality?
[Unknown]:  mycity
What is the name of your State or Province?
[Unknown]:  mystate
What is the two-letter country code for this unit?
[Unknown]:  us
Is CN=www.myhost-dev.com, OU=development, O="myhost, inc", L=mycity, ST=mystate, C=us correct?
Enter key password for <s1as>
(RETURN if same as keystore password): 

Step 6 - Generate a Certificate Signing Request (CSR)

/usr/home/myhost/glassfish4/glassfish/domains/domain1/config
115 % keytool -certreq -alias s1as -file toSymantec02.csr -keystore keystore.jks
Enter keystore password: 

Step 7 - submit CSR to symantec

step 8 - copy intermediate and ssl cert from symantec into config directory

step 9 - import intermediate cert

/usr/home/myhost/glassfish4/glassfish/domains/domain1/config
115 % keytool -import -trustcacerts -alias Intermediate -keystore keystore.jks -file IntermediateCA.crt
Enter keystore password:
Certificate was added to keystore

step 10 - import ssl cert

/usr/home/myhost/glassfish4/glassfish/domains/domain1/config
116 % keytool -import -trustcacerts -alias s1as -keystore keystore.jks -file ssl_certificate.crt
Enter keystore password:
Certificate reply was installed in keystore

step 11 - restart the server

/usr/home/myhost
118 % glassfish4/bin/asadmin start-domain domain1
Enter master password (3) attempt(s) remain)>
Waiting for domain1 to start ...............................
Successfully started the domain : domain1
domain  Location: /usr/home/myhost/glassfish4/glassfish/domains/domain1
Log File:/usr/home/myhost/glassfish4/glassfish/domains/domain1/logs/server.log
Admin Port: 4848
Command start-domain executed successfully.

Answer:

The problem is almost certainly that the distinguished name (DN) of the s1as certificate has changed, but the secure admin principal has not been updated.

There is an asadmin command (enable-secure-admin-principal) which allows you to manually update this, but you can also just run enable-secure-admin again (even though secure admin is already enabled). This command will call the same code as the previous one and replace the secure admin principals with the correct ones from whatever the admin certificate alias is (s1as).

You will then need to restart GlassFish for the change to take effect, but you will then be able to log in to the admin console.

The root cause is that the admin console is essentially doing 2-way SSL along with your login, so your username and password is verified for you, the admin user, then the admin console itself is verified with the DN as a user ID and the s1as key as a password. This is because the admin console communicates with the DAS over REST and needs to identify itself as a trusted client.


Hope all that background helps, but the TL;DR is as follows:

  1. Run enable-secure-admin once more
  2. Restart the domain

Question:

Problem

When I try to use GrizzlyHttpServerFactory.createHttpServer I get a "WARNING: Unknown HK2 failure detected:" followed by two errors inside a "MultiException":

  • "java.lang.NoSuchFieldError: WADL"
  • "Unable to perform operation: create on org.glassfish.jersey.server.wadl.processor.WadlModelProcessor"
I've Tried

I am not knowledgeable in Jersey, but I have:

  • Read this similar, unsolved question from seven months ago, and this one from two years ago.
  • Learned that the ResourceConfig is meant to replace/simplify a web.xml, but this project has no existing (and thus, no conflicting) web.xmls.
  • Removed the underscores and changed the port number in the URI (http://127.0.0.1:8086/the_uri/). Didn't work.
In-depth
ResourceConfig I'm using:
public class MyResourceConfig extends ResourceConfig {

    public MyResourceConfig(){
        register(CORSResponseFilter.class);

        register(MyAPIPoint.class);
    }
}

Contains two classes being registered and nothing else.

Truncated Error Stack Trace:
WARNING: The following warnings have been detected: WARNING: Unknown HK2 failure detected:
MultiException stack 1 of 2
java.lang.NoSuchFieldError: WADL
    at org.glassfish.jersey.server.wadl.processor.WadlModelProcessor.<init>(WadlModelProcessor.java:96)
    ...
    at org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpContainer.<init>(GrizzlyHttpContainer.java:331)
    at org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory.createHttpServer(GrizzlyHttpServerFactory.java:116)
MultiException stack 2 of 2
java.lang.IllegalStateException: Unable to perform operation: create on org.glassfish.jersey.server.wadl.processor.WadlModelProcessor
    at org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:395)
    ...
    at org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpContainer.<init>(GrizzlyHttpContainer.java:331)
    at org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory.createHttpServer(GrizzlyHttpServerFactory.java:116)

Answer:

(It's OK to Ask and Answer Your Own Questions)

After reading this question and this issue thread it seems that I might have a conflict in my dependencies.

Relevant dependencies: I'm using jersey 2.11 and tyrus-container-grizzly-server 1.13.

Edit: Updated the jersey version to 2.25 in the pom and the error disappeared.

If someone wants to try and give a better solution or explanation I can give more information about the setup of the project. I won't accept this answer as it is not complete.

Question:

I'm trying to debug some Rest service in Glassfish 4 and I want to see exactly what is being sent over the wire (HTTP connection). Is there a way to make Glassfish print that out?

My project uses Apache HTTP Client and I know is it possible to configure it there, but I couldn't get it to work with our logging framework(java.util.logging).

EDIT: Alternatively is there a way to debug Jersey that will make it printout this info?


Answer:

You don't specify if you have control over the client/front end or not, or if this is just over the backend.

A few immediate thoughts come to mind:

  1. Use a packet sniffer/analyzer like WireShark (as already suggested). Works great, the only problem is that will probably generate significantly more data than you really want to see/analyze.

  2. Use a proxy like Charles or Fiddler. These can be configured to show/log exactly what data you want/need. The disadvantage is that they are proxies (ie: have to be in the middle of your connection) and this can cause configuration difficulties if you are putting it in front of your server. Usually much easier to configure on the client end, and just push your client traffic through it. Fiddler is free, but only Windows based (alpha version available for Mac and Linux). Charles has a trial version, or otherwise is 50$ (if memory serves). I also do not know if Fiddler and/or Charles will run in headless mode.

  3. Set up your own Http Proxy server and log everything through there. Not truly an ideal solution, but an option none the less.

  4. Add a filter to your application to log all HTTP data coming in/out, but that gets tricky/messy as well as incoming Http request bodies are single read, so they need to be cached for multiple reads/accesses (see Http Servlet request lose params from POST body after read it once and https://stackoverflow.com/a/17129256/827480 for a good proposed solution to this issue)

Question:

I would like to know if its possible for me to expose server.log over http, like i would like to see my logs on the Internet browser. like how the Team City build work, the Build output are shown on the browser; can I tail -f /path/to/glassfish/domains/YOURDOMAIN/logs/server.log and specify the port and URL to access via a browser like tail -f /path/to/glassfish/domains/YOURDOMAIN/logs/server.log -host localhost -port 9090 -path /glassfish/logs


Answer:

You can access you log through the following address:

https://www.yourservername.com:4848/management/domain/view-log

Question:

I've met a really strange case:

Before migrating to Payara 5.182, I use Payara 4.1.181, and the http/https requests are all very fast. Things go strange when I migrate to Payara 5.182, http requests are working just fine, but the https requests are extremely slow.

Here's the information:

  • the application that deployed to Payara 5.182 / Payara 4.1.181 is the same version
  • configure the keystore.jks and cacerts.jks in Payara 5.182 just the same way as Payara 4.1.181:
    • keytool -importkeystore -destkeystore keystore.jks -srckeystore 3MEdu.p12 -srcstoretype PKCS12 -alias 3medu_cert
    • keytool -importkeystore -destkeystore cacerts.jks -srckeystore 3MEdu.p12 -srcstoretype PKCS12 -alias 3medu_cert
  • the 3MEdu.p12 is the same file as used in Payara 4.1.181
  • use 80 port for http request and 443 port for https request
  • JDK version: Oracle JDK 8u161
  • OS verison: Ubuntu 16.04.4 LTS

Answer:

One difference between Payara 4 and 5 is that HTTP/2 is enabled by default in Payara 5. Try disabling HTTP2 as described in the documentation: https://docs.payara.fish/documentation/payara-server/server-configuration/http/protocols.html

Question:

I've configured a Glassfish 5.0 instance with an AJP connector that would work as load balancer even though at the moment I have only one glassfish.

In domain.xml I have the followin:

<http-service>
    <access-log></access-log>
    <virtual-server network-listeners="http-listener-1,http-listener-2,jk-connector" id="server"></virtual-server>
    <virtual-server network-listeners="admin-listener" id="__asadmin"></virtual-server>
</http-service>

where jk-connector is the one I use from the load balancer.

 <network-config>
     ...
      <protocols>
          <protocol name="jk-connector">
            <http default-virtual-server="server">
              <file-cache></file-cache>
            </http>
          </protocol>
        </protocols>
    </network-config>

then there is the listener

    <network-listeners>
      <network-listener protocol="jk-connector" jk-enabled="true" port="8009" name="jk-connector" thread-pool="http-thread-pool" transport="tcp"></network-listener>
    </network-listeners>

My Apache http.conf is as follows:

LoadModule headers_module modules/mod_headers.so
LoadModule jk_module modules/mod_jk.so

# Where to find workers.properties
JkWorkersFile conf/workers.properties
JkOptions +ForwardKeySize +ForwardURICompat -ForwardDirectories
JkRequestLogFormat "%w %V %T"

<IfModule mod_rewrite.c>
        Options +Indexes
        Options +FollowSymlinks
        RewriteEngine on
        RewriteMap  uc int:toupper

        #rewrite per compatibilita' con vecchie URL dei servizi 
        RewriteRule ^/services/(.)(.*)$   /api/${uc:$1}$2Services?%{QUERY_STRING}  [PT]
        #RewriteRule ^/services/(.)(.*)$  http://%{HTTP_HOST}/api/${uc:$1}$2Services?%{QUERY_STRING}  [R=301,L]

        #solo nel caso di un GET
        RewriteCond  %{REQUEST_METHOD}  GET
        ReWriteRule ^(.*)/login.jsf;jsessionid=[A-Za-z0-9\.]+(.*)$ $1/login.jsf$2 [L,R=301]
</IfModule>

The exception is:

  GRIZZLY0013: Exception during FilterChain execution
java.lang.NullPointerException
    at org.glassfish.grizzly.http.ajp.AjpHandlerFilter.encodeHttpPacket(AjpHandlerFilter.java:282)
    at org.glassfish.grizzly.http.ajp.AjpHandlerFilter.handleWrite(AjpHandlerFilter.java:245)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$8.execute(ExecutorResolver.java:111)
    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.filterchain.FilterChainContext.write(FilterChainContext.java:890)
    at org.glassfish.grizzly.filterchain.FilterChainContext.write(FilterChainContext.java:858)
    at org.glassfish.grizzly.http.io.OutputBuffer.flushBuffer(OutputBuffer.java:1092)
    at org.glassfish.grizzly.http.io.OutputBuffer.flushBinaryBuffers(OutputBuffer.java:1066)
    at org.glassfish.grizzly.http.io.OutputBuffer.flushAllBuffers(OutputBuffer.java:1036)
    at org.glassfish.grizzly.http.io.OutputBuffer.close(OutputBuffer.java:754)
    at org.apache.catalina.connector.OutputBuffer.close(OutputBuffer.java:244)
    at org.apache.catalina.connector.CoyoteOutputStream.close(CoyoteOutputStream.java:179)
    at java.nio.channels.Channels$WritableByteChannelImpl.implCloseChannel(Channels.java:469)
    at java.nio.channels.spi.AbstractInterruptibleChannel.close(AbstractInterruptibleChannel.java:115)
    at com.sun.faces.application.resource.ResourceHandlerImpl.handleResourceRequest(ResourceHandlerImpl.java:365)
    at javax.faces.application.ResourceHandlerWrapper.handleResourceRequest(ResourceHandlerWrapper.java:178)
    at org.primefaces.application.resource.PrimeResourceHandler.handleResourceRequest(PrimeResourceHandler.java:87)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:667)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1580)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:338)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:100)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:250)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at com.ocpsoft.pretty.PrettyFilter.doFilter(PrettyFilter.java:145)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:250)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.logging.log4j.web.Log4jServletFilter.doFilter(Log4jServletFilter.java:71)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:250)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:256)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:652)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:591)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:371)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:238)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:463)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:168)
    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:242)
    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:539)
    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:593)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:573)
    at java.lang.Thread.run(Thread.java:748)

Using JDK 1.8.0_131, Glassfish 5.0, Apache 2.4.2


Answer:

Seems like you are facing this Glassfish bug (and this one).

You can try the latest Glassfish 5 build which is available here: http://download.oracle.com/glassfish/5.0.1/nightly

Unfortunately it looks like there is currently no solution besides manually fixing the grizzly JAR file.

You can try the following:

  1. Download the grizzly 2.4 sources (https://github.com/javaee/grizzly/archive/2.4.x.zip) and extract them
  2. Open the project grizzly-http-ajp and build it, if the build fails due to missing dependencies, change the project version to 2.4.3 in pom.xml
  3. If it compiles without problems, open the class AjpHandlerFilter
  4. Do the following change near line 276 so the code looks like this:

        if (contentBuffer.hasRemaining()) {
            return AjpMessageUtils.appendContentAndTrim(memoryManager,
                    encodedBuffer, contentBuffer);
        } else if (encodedBuffer == null) {
            encodedBuffer = Buffers.EMPTY_BUFFER;
        }
    
  5. Save and compile the project

  6. Go to /grizzly-2.4.x/modules/http-ajp/target/classes/org/glassfish/grizzly/http/ajp/ and copy the the generated .class file for AjpHandlerFilter
  7. Update the AjpHandlerFilter.class in the glassfish-grizzly-extras-all.jar (inside glassfish/glassfish/modules) of your Glassfish installation. You can do this with jar uf ${jar-file} ${class-file}. You need to make sure that the path is correct and you that you replace the old .class file in the JAR

Alternativly you can try to find the sources of the project glassfish-grizzly-extras-all, fix the problem there and build a new glassfish-grizzly-extras-all.jar.

Question:

I build java web application,and I try to login with cookies... So I insert user and password values, user is gerardo password 12345.. When I insert it, JSP respond my request but I get an issue...anyone can help me? I upload code here:

https://mega.nz/#F!s0V2WaZb!Q5zoZFm11VP2IJ_lc6Wolw

Note**: Im using NETBEANS IDE and GLASSFISH server


Answer:

Give full path of index.html like http://domain_name/direcorry/index.html as index.html may not be present in same location of jsp file.

Question:

When I try to run my Web Application (a basic CRUD) using JSP, the GlassFish server returns the follow message:

HTTP Status 500 - Internal Server Error

type Exception report

message Internal Server Error

description The server encountered an internal error that prevented it from fulfilling this request.

exception

java.lang.NullPointerException

note The full stack traces of the exception and its root causes are available in the GlassFish Server Open Source Edition 4.1 logs.

And I don't knhow what to do. I think the error is in connection with my DB. I'm using PostgreSQL, running in a Windows.

My NetBeans project is in GitHub Crisfa Project


Answer:

An HTTP 500 error is meaningless. It is only telling you that something went wrong, although you can see that whatever it was was down to a null pointer error. You need to look in the server logs to see what caused the null pointer error.

This StackOverflow question has a few good answers on how to find the server logs, either manually through the file system, or with NetBeans. Location of GlassFish Server Logs

Question:

Is it possible to create a HTTPS connection to a java-servlet with a static name (like https://.../logonServlet) so that only clients who already own the public key/certificate can access the servlet? I would like to prevent the server from delivering public certificates and refusing all other clients?

To my knowledge: I read about the java keytool and the different stores (keystore (certs and private keys) and truststore (client side, public keys)). I am currently reading the book "Glassfish Security" by Masoud Kalali to learn about user groups and different security realms and stuff like different xml options for server configuration but I feel like I start mixing everything in my head so I would like to ask if you could help me with my desire from above. A big question that is still open to me is "Why do we need certificates?". Shouldn't be a private key which will be kept secret enough and a public key for the clients?

@Edit

What you may want to check is SSL/TLS with client authentication. In this setup, the clients need a certificate and a private key as well. The server will refuse connections if they are not from a client with a trusted certificate. This means that server and client need both a keystore and a truststore.

Seems like you are correct, that is what I am looking for.


Answer:

Asymetric cryptography works with two elements by design:

  • Public key: Shared with everybody, so they can know it's you who send the messages. Also to cipher messages that only can be read with the private key.
  • Private key: Only known to you, so you can guarantee that you are who send the messages. Also to read messages sent to you ciphered using your public key.

In a typical HTTPS setup, the server has the certificate (with a public key) and the private key, but the public part is shared with anyone who connects (you can see the certificate of any HTTPS site in the browser). This is because usually, the client needs to know who the server is, but the server doesn't need to know who the user is (and if it does, other ways like passwords are cheaper and more convenient for the average user). Sharing the server's public certificate is necessary for SSL/TLS to work, so there is no way to hide those keys and completing the handshake at the same time.

So no, the server's public key cannot be used to authenticate the clients, as it is assumed by design that everybody can get it.

What you may want to check is SSL/TLS with client authentication. In this setup, the clients need a certificate and a private key as well. The server will refuse connections if they are not from a client with a trusted certificate. This means that server and client need both a keystore and a truststore.

Note that keystore and truststore are conceptual terms. A single file (.jks, for example) can act as both, as it can contain private keys and public certificates at the same time. That said, they tend to be in different files.

Question:

I've looked in 4 (yes, four) tutorials already and still don't get how to get this working.

After setting a second HTTP listener configured for HTTPS in my Glassfish 4.1.1 server, I'm trying to create a certificate, so I don't get security errors in my browser. The problem is, that I just don't get keytool working proper; it just messes up and throws strange errors whatever I do. Per example, it doesn't find some of the commands that many guides recommend.

I can guess that the tool changed in Java 8 or something else, I don't really know.

Thing is: I want to create a certificate, export it to my Glassfish server, and have HTTPS correctly implemented and working for testing purposes. What should I do for this?

EDIT: Seriously, I'm in a trouble because of this. I just can't do anything: cacerts password isn't the typical "changeit", I can't get my keys outside the keystore, and therefore I can't do anything with certificates.


Answer:

If all you need to do is create a pair of self-signed certificates... I may be able to help.

On a Microsoft Windows Machine:

  • Create an empty directory and save the below script there (GenTestCerts.ps1).
  • Edit the script and change the Alias values (and other variables) to whatever you need.
  • Execute the script.

Copy the server (tomcat.server.net.p12) cert to wherever your server expects it to be.

Copy the Trust Store (truststore.p12) to wherever your server expects it to be.

Install the admin (tomcat-admin.p12) cert in your Windows Key Store accepting the Root into your Trusted Root Certification Authorities section.

<#
    This sample Windows PowerShell script will:
        1.) Create a Certificate Authority
        2.) Create a Server Certificate signed by the Certificate Authority
        3.) Create a Client Certificate signed by the Certificate Authority
        4.) Create a TrustStore containing the public Certificate Authority key

    The first section defines variables
    The second section does the work

    All Key Stores are PKCS12

    The Server Certificate includes a Subject Alternative Name
        The command below uses the serverAlias as the serverDNS value, but may be changed to whatever you need

    You just have Java 7 (or higher) installed and keytool in your path
#>

<# Your Organizational Information #>
$organizationalUnit="USN"
$organization="NRL"
$locality="Washington"
$state="DC"
$country="USA"

<# Certificate Alias #>
$authorityAlias="tomcat-root"
$serverAlias="tomcat.server.net"
$clientAlias="tomcat-admin"

<# Subject Alternative Name #>
$serverDNS="$serverAlias"

<# Extensions #>
$certAuthExtension="BasicConstraints:critical=ca:true,pathlen:10000"
$altNameExtension="san=dns:$serverDNS"

<# Trust Store #>
$trustCertName="truststore"

<# Key size and effective period #>
$keySize="4096"
$validity="365"

<# Key and Store Password #>
$certPassword="changeit"

<# ------------------------------------------------------------------------------------------ #>
<# ------------------  Use caution if you change anything below this line  ------------------ #>
<# ------------------------------------------------------------------------------------------ #>

$authorityDN="CN=$authorityAlias,OU=$organizationalUnit,O=$organization,L=$locality,ST=$state,C=$country"
$serverDN="CN=$serverAlias,OU=$organizationalUnit,O=$organization,L=$locality,ST=$state,C=$country"
$clientDN="CN=$clientAlias,OU=$organizationalUnit,O=$organization,L=$locality,ST=$state,C=$country"

rm "$authorityAlias.*"
rm "$serverAlias.*"
rm "$clientAlias.*"
rm "$trustCertName.*"

echo ""
echo "Generating the Root Authority Certificate..."
keytool -genkeypair -alias "$authorityAlias" -keyalg RSA -dname "$authorityDN" -ext "$certAuthExtension" `
    -validity "$validity" -keysize "$keySize" -keystore "$authorityAlias.p12" -keypass "$certPassword" `
    -storepass "$certPassword" -deststoretype pkcs12
echo "- Exporting Root Authority Certificate Public Key..."
keytool -exportcert -rfc -alias "$authorityAlias" -file "$authorityAlias.cer" -keypass "$certPassword" `
    -keystore "$authorityAlias.p12" -storepass "$certPassword"

echo ""
echo "Generating the Server Certificate..."
echo "- Creating Key Pair"
keytool -genkey -validity "$validity" -keysize "$keySize" -alias "$serverAlias" -keyalg RSA -dname "$serverDN" `
    -ext "$altNameExtension" -keystore "$serverAlias.p12" -keypass "$certPassword" -storepass "$certPassword" `
    -deststoretype pkcs12
echo "- Creating Certificate Signing Request"
keytool -certreq -alias "$serverAlias" -ext "$altNameExtension" -keystore "$serverAlias.p12" -file "$serverAlias.csr" `
    -keypass "$certPassword" -storepass "$certPassword"
echo "- Signing Certificate"
keytool -gencert -infile "$serverAlias.csr" -keystore "$authorityAlias.p12" -storepass "$certPassword" `
    -alias "$authorityAlias" -ext "$altNameExtension" -outfile "$serverAlias.pem"
echo "- Adding Certificate Authority Certificate to Keystore"
keytool -import -trustcacerts -alias "$authorityAlias" -file "$authorityAlias.cer" -keystore "$serverAlias.p12" `
    -storepass "$certPassword" -noprompt
echo "- Adding Certificate to Keystore"
keytool -import -keystore "$serverAlias.p12" -file "$serverAlias.pem" -alias "$serverAlias" -keypass "$certPassword" `
    -storepass "$certPassword" -noprompt
rm "$serverAlias.csr"
rm "$serverAlias.pem"

echo ""
echo "Generating the Client Certificate..."
echo "- Creating Key Pair"
keytool -genkey -validity "$validity" -keysize "$keySize" -alias "$clientAlias" -keyalg RSA -dname "$clientDN" `
    -keystore "$clientAlias.p12" -keypass "$certPassword" -storepass "$certPassword" -deststoretype pkcs12
echo "- Creating Certificate Signing Request"
keytool -certreq -alias "$clientAlias" -keystore "$clientAlias.p12" -file "$clientAlias.csr" -keypass "$certPassword" `
    -storepass "$certPassword"
echo "- Signing Certificate"
keytool -gencert -infile "$clientAlias.csr" -keystore "$authorityAlias.p12" -storepass "$certPassword" `
    -alias "$authorityAlias" -outfile "$clientAlias.pem"
echo "- Adding Certificate Authority Certificate to Keystore"
keytool -import -trustcacerts -alias "$authorityAlias" -file "$authorityAlias.cer" -keystore "$clientAlias.p12" `
    -storepass "$certPassword" -noprompt
echo "- Adding Certificate to Keystore"
keytool -import -keystore "$clientAlias.p12" -file "$clientAlias.pem" -alias "$clientAlias" -keypass "$certPassword" `
    -storepass "$certPassword" -noprompt
rm "$clientAlias.csr"
rm "$clientAlias.pem"

echo ""
echo "Generating the Trust Store and put the Client Certificate in it..."
keytool -importcert -alias "$authorityAlias" -file "$authorityAlias.cer" -keystore "$trustCertName.p12" `
    -storepass "$certPassword" -noprompt

echo ""
echo "Removing Public Key Files..."
rm "$authorityAlias.cer"

Hope this helps.

Best, Ace

Question:

I did a migration of my Client WebApp. Previously, it was running on Glassfish 2.1 and JDK 1.6. Now, it's on Glassfish 4.1 and jdk 1.8.

When I try to send an email from my WebApp, the same ".war" packaged in JDK 1.6 (Project facets 1.6) works perfectly on Glassfish 2.1 and doesn't work on Glassfish 4.0. The two Glassfish are running on local.

The exception is :

    13917 [http-listener-1(4)] ERROR com.myClient.web.action.myAction- Failed to send email
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: ismtp.corp.capgemini.com, 25; timeout -1;
  nested exception is:
    java.net.SocketException: Network is unreachable: connect
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2053)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:697)
    at javax.mail.Service.connect(Service.java:364)
    at javax.mail.Service.connect(Service.java:245)
    at javax.mail.Service.connect(Service.java:194)
    at javax.mail.Transport.send0(Transport.java:253)
    at javax.mail.Transport.send(Transport.java:124)
    at com.labco.web.action.ValiderOubliMdpAction.sendMail(ValiderOubliMdpAction.java:296)

I tried to send email from the cmd.exe with telnet and it works. So I think the matter is in the tuning of Glassfish 4.1. problably on the http-listeners.

Do you have some recommandations or any ideas about my problem?

Thanks,


Answer:

On glassfish Instead of "Default-configuration" add Djava.net.preferIPv4Stack=true to server-config. I think it can fix your problem

Question:

I'm trying to use HTTPS in Java EE, for my own login directives and transfering information via a secure protocol. This should be trivial, but I'm having trouble finding a tutorial/guide to do it.

Currently, I'm using Netbeans for all my J2EE work, which uses Glassfish 4.1.1, along with JDK and JRE at the 1.8 version.

I'm basically looking for a comprehensive guide or a quick resume on how to implement HTTPS on a Servlet, so when I access to that servlet (mydomain/#/myServlet) the protocol gets set to HTTPS, uses my own created certificate (I also need help with that), so it encrypts the GET/POST requests, in order to make it unable to read the info (or at least make it a non-trivial thing).

Knowing a list of TO-DO things could be enough; if I know what I have to do, I can look for the information in a proper way. But now, I really don't find anything easy to understand.

Anyone can help? Thank you!


Answer:

Your server will have a port for HTTP communication and other for HTTPS communication. So if you will communicate on HTTPS port the communication will be on HTTPS. So see your server configuration and check the HTTPS port and use that port in the URL.

Question:

I am trying to develop a JavaEE 7.0 web application using NetBeans (IDE), GlassFish 4.1.0 (web server) and MySql 5.7.11 (Database server). My Operating System is Windows 8.1.

I would like to set up a very basic authentication system. The user enters a username and a password already inserted in the database and if it is correct, he will be able to access a webpage called index.jsp. Therefore, I proceeded in the following way in order to develop this authentication system:

1- In the GlassFish admin console, I went to the "security/Realms/file" window and add a username: "john" and a password:"azerty". The group list to which "john" belongs is called "cemsAdmin":

2- In the "security" general window, I enabled the Default Principal To Role Mapping option:

3- In my NetBeans web app project I wrote the following code in the web.xml document:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"   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">
<context-param>
    <param-name>javax.faces.PROJECT_STAGE</param-name>
    <param-value>Development</param-value>
</context-param>
<servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>/faces/*</url-pattern>
</servlet-mapping>

<session-config>
    <session-timeout>
        30
    </session-timeout>
</session-config>
<welcome-file-list>
    <welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>

<jsp-config>
    <jsp-property-group>
        <description>JSP configuration for the admin console</description>
        <url-pattern>/admin/index.jsp</url-pattern>
    </jsp-property-group>

    <jsp-property-group>
        <description>JSP configuration for the store front</description>
        <url-pattern>/index.jsp</url-pattern>
        <url-pattern>/WEB-INF/view/*</url-pattern>
    </jsp-property-group>
</jsp-config>

<login-config>
    <auth-method>FORM</auth-method>
    <realm-name>file</realm-name>
    <form-login-config>
        <form-login-page>/admin/login.jsp</form-login-page>
        <form-error-page>/admin/error.jsp</form-error-page>
    </form-login-config>
</login-config>
<resource-ref>
    <description>Connect to the cems database</description>
    <res-ref-name>jdbc/cems</res-ref-name>
    <res-type>javax.sql.ConnectionPoolDataSource</res-type>
    <res-auth>Container</res-auth>
    <res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>

3- In my NetBeans web app project I wrote the following code in the AdminServlet file:

@WebServlet(name = "AdminServlet", urlPatterns = {"/admin/","/admin/logout"})

@ServletSecurity( @HttpConstraint(rolesAllowed = {"cemsAdmin"}) )
public class AdminServlet extends HttpServlet {

private String userPath;

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    userPath = request.getServletPath();

    System.out.println("The user path is:"+userPath);
    HttpSession session = request.getSession(true);

    // use RequestDispatcher to forward request internally
    userPath = "/admin/index.jsp";
    try {
        request.getRequestDispatcher(userPath).forward(request, response);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

When I run all the code I obtain the following webpage:

Therefore, I enter the username "john" and the password "azerty" and I have the following HTTP error:

I really do not know what is going on. Could you help me please ?

Thank you so much for your help.


Answer:

You need to add a security constraint in your web.xml. Something like this:

<security-constraint>
    <display-name>Constraint1</display-name>
    <web-resource-collection>
        <web-resource-name>rr</web-resource-name>
        <description/>
        <url-pattern>/admin/*</url-pattern>
    </web-resource-collection>
    <auth-constraint>
        <description/>
        <role-name>RoleOne</role-name>
    </auth-constraint>
</security-constraint>
<security-role>
    <description/>
    <role-name>RoleOne</role-name>
</security-role>

You also are missing security-role definition.

Question:

I have a Java Client on Glassfish that has to consume a soap web service from a third party but I can't get around the error:

"error":    {
      "code": "ClientTransportException",
      "description": "HTTP transport error: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target"
}

I have the third party certificates in the JVM keystore and cacert but still no luck.

This is the (summarised) ssl messaging:

Info:   Using SSLEngineImpl.
Info:   Allow unsafe renegotiation: false
Allow legacy hello messages: true
Is initial handshake: true
Is secure renegotiation: false
Info:   http-listener-2(5), READ: TLSv1 Handshake, length = 181
Info:   *** ClientHello, TLSv1
Info:   RandomCookie:
...
Info:   ***
Info:   %% Resuming [Session-5, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA]
Info:   *** ServerHello, TLSv1
Info:   RandomCookie:
Info:   bytes = {
Info:   10
Info:   ,
...
Info:   ,
Info:   218
Info:   }
Info:   Session ID:
Info:   Cipher Suite: TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
Info:   Compression Method: 0
Info:   Extension renegotiation_info, renegotiated_connection: <empty>
Info:   ***
Info:   Cipher suite:  TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
Info:   CONNECTION KEYGEN:
Info:   Client Nonce:
Info:   0000:
Info:   55
Info:   /
Info:   http-listener-2(5), WRITE: TLSv1 Handshake, length = 81
Info:   http-listener-2(5), WRITE: TLSv1 Change Cipher Spec, length = 1
Info:   *** Finished
Info:   verify_data:  {
Info:   95
Info:   ,
...
Info:   ,
Info:   7
Info:   }
Info:   ***
Info:   http-listener-2(5), WRITE: TLSv1 Handshake, length = 48
Info:   http-listener-2(2), READ: TLSv1 Change Cipher Spec, length = 1
Info:   http-listener-2(2), READ: TLSv1 Handshake, length = 48
Info:   *** Finished
Info:   verify_data:  {
Info:   241
Info:   ,
...
Info:   ,
Info:   206
Info:   }
Info:   ***
Info:   Finalizer, called close()
Info:   Finalizer, called closeInternal(true)
Info:   Allow unsafe renegotiation: false
Allow legacy hello messages: true
Is initial handshake: true
Is secure renegotiation: false
Info:   http-listener-2(2), setSoTimeout(0) called
Info:   %% No cached client session
Info:   *** ClientHello, TLSv1.2
Info:   RandomCookie:
Info:   GMT: 1431349301
Info:   bytes = {
Info:   98
Info:   ,
...
Info:   Extension server_name, server_name: [type=host_name (0), value=*****]
Info:   ***
Info:   http-listener-2(2), WRITE: TLSv1.2 Handshake, length = 244
Info:   http-listener-2(2), READ: TLSv1.2 Handshake, length = 81
Info:   *** ServerHello, TLSv1.2
Info:   RandomCookie:
Info:   GMT: 305071236
Info:   bytes = {
Info:   16
Info:   ,
...
Info:   ,
Info:   157
Info:   }
Info:   Session ID:
Info:   Cipher Suite: SSL_RSA_WITH_RC4_128_SHA
Info:   Compression Method: 0
Info:   Extension renegotiation_info, renegotiated_connection: <empty>
Info:   ***
Info:   %% Initialized:  [Session-7, SSL_RSA_WITH_RC4_128_SHA]
Info:   ** SSL_RSA_WITH_RC4_128_SHA
Info:   http-listener-2(2), READ: TLSv1.2 Handshake, length = 2084
Info:   *** Certificate chain
<b>Info:   chain [0] = [</b>
[
Version: V3
Subject: CN=*****, OU=*****, O=*****, L=*****, ST=*****, C=*****
Signature Algorithm: SHA1withRSA, OID = 1.2.840.113549.1.1.5
Key:  Sun RSA public key, 2048 bits
modulus: *****
public exponent: *****
Validity: [From: Tue Apr 30 11:50:28 BST 2013,
           To: Mon Dec 25 10:50:28 GMT 2017]
Issuer: EMAILADDRESS=*****, CN=*****, OU=*****K, O=*****, L=*****,     ST=*****, C=*****
SerialNumber: [*****]
Certificate Extensions: 2
[1]: ObjectId: 2.5.29.19 Criticality=false
BasicConstraints:[
CA:false
PathLen: undefined
]
[2]: ObjectId: 2.5.29.15 Criticality=false
KeyUsage [
DigitalSignature
Non_repudiation
Key_Encipherment
]
]
Algorithm: [SHA1withRSA]
Signature:
0000: 52 52 A2 33 8F 48 81 85   F9 CD 8E A8 90 1B D0 01  RR.3.H..........
0010: 3E 09 FF EC F5 23 E0 6F   77 2B 5E 20 B2 BC FF CE  >....#.ow+^ ....
...
00D0: 26 70 A9 5C 6D 80 9E 72   B0 F0 75 1D F3 E4 93 41  &p.\m..r..u....A
00E0: 6E 11 43 CB 6E 6D 1E C3   BB C7 A2 6F 65 A6 B6 58  n.C.nm.....oe..X
00F0: 53 98 4D CA 0A EC 18 6A   D4 80 BE 19 43 AD 7D F7  S.M....j....C...
]
**Info:   chain [1] = [**
[
Version: V3
Subject: EMAILADDRESS=*****, CN=*****, OU=*****, O=*****, L=*****,  ST=*****, C=*****
Signature Algorithm: SHA1withRSA, OID = *****
Key:  Sun RSA public key, 2048 bits
modulus: *****
public exponent: *****
Validity: [From: Thu May 06 11:35:16 BST 2010,
           To: Sun May 03 11:35:16 BST 2020]
Issuer: EMAILADDRESS=*****, CN=*****, OU=*****, O=*****, L=*****,      ST=*****, C=*****
SerialNumber: [*****]
Certificate Extensions: 3
[1]: ObjectId: 2.5.29.35 Criticality=false
AuthorityKeyIdentifier [
KeyIdentifier [
0000: A0 C0 66 47 F2 E2 D7 6F   44 6F 3C E9 44 77 32 1B  ..fG...oDo<.Dw2.
0010: 00 3A B3 B6                                        .:..
]
]
[2]: ObjectId: 2.5.29.19 Criticality=false
BasicConstraints:[
CA:true
PathLen:2147483647
]
[3]: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifier [
0000: A0 C0 66 47 F2 E2 D7 6F   44 6F 3C E9 44 77 32 1B  ..fG...oDo<.Dw2.
0010: 00 3A B3 B6                                        .:..
Algorithm: [SHA1withRSA]
Signature:
0000: C0 FC 52 0F 9F 43 A4 64   B4 F2 61 79 50 37 90 28  ..R..C.d..ayP7.(
0010: 0B F7 ED 2E C8 28 01 66   25 AD DC E6 9D 3E 30 ED  .....(.f%....>0.
...
00E0: A6 19 A7 71 7A 55 BE 4F   54 FA 4E DE DE BF FD 29  ...qzU.OT.N....)
00F0: 12 29 D0 48 B8 BA BB CC   57 11 24 7A A4 F5 0B 03  .).H....W.$z....
]
Info:   ***
**Info:   %% Invalidated:  [Session-7, SSL_RSA_WITH_RC4_128_SHA]**
Info:   http-listener-2(2)
Info:   , SEND TLSv1.2 ALERT:
Info:   fatal,
**Info:   description = certificate_unknown**
Info:   http-listener-2(2), WRITE: TLSv1.2 Alert, length = 2
Info:   http-listener-2(2), called closeSocket()
**Info:   http-listener-2(2), handling exception:  javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target**
Info:   http-listener-2(2), called close()
Info:   http-listener-2(2), called closeInternal(true)
Info:   http-listener-2(2), WRITE: TLSv1 Application Data, length = 637
Info:   http-listener-2(2), WRITE: TLSv1 Application Data, length = 1
Info:   http-listener-2(2), WRITE: TLSv1 Application Data, length = 4

Am I doing something wrong?


Answer:

Finally got it working. I had to explicitly tell Glassfish about the cacerts to be used even with those certificates being available in the /jdk/jr, /jre and the glassfish domain config cacerts...

asadmin> create-jvm-options -Djavax.net.ssl.trustStore="/Program Files/Java/jre7/lib/security/cacerts"

Question:

As a beginner to Jsp and Java , I'm building a simple web application that displays data from data base to web page

When i run the below code i'm getting the following error HTTP Status 500 - Internal Server Error

Building web application in net beans and web server is Glass fish

Don't know what went wrong .Still searching Google but no luck yet

type Exception report

messageInternal Server Error

descriptionThe server encountered an internal error that prevented it from fulfilling this request.

exception

org.apache.jasper.JasperException: java.lang.NullPointerException
root cause

java.lang.NullPointerException

Update1:

Warning:   StandardWrapperValve[jsp]: Servlet.service() for servlet jsp threw exception
java.lang.NullPointerException
    at org.apache.jsp.nextPage_jsp._jspService(nextPage_jsp.java:111)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:111)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:411)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:473)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:377)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    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:415)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:282)
    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:745)

Index.jsp

<%-- 
    Document   : index
    Created on : Jan 1, 2015, 7:36:04 PM
    Author     : ksathis
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Inside</title>
    </head>
    <body>
        <h1>Inside</h1>
        <form name="mainForm" action="nextPage.jsp" method="POST">
            <table border="0">
                <tbody>
                    <tr>
                        <td>DateRange</td>
                        <td><input type="radio" name="radioS" id="dateRadio" value="1" /></td>
                        <td><input type="date" name="date1" value="0" size="10" /></td>
                        <td><input type="date" name="date2" value="0" size="10" /></td>
                    </tr>
                    <tr>
                        <td>WeekNum</td>
                        <td><input type="radio" name="radioS" id="weekRadio" value="1" /></td>
                        <td><input type="text" name="weeknum1" id="weeknum1" value="0" size="10" /></td>
                    </tr>
                    <tr>
                        <td>MonthNum</td>
                        <td><input type="radio" name="radioS"  id="monthRadio" value="1" /></td>
                        <td><input type="text" name="monthnum1" value="0" size="10" /></td>
                    </tr>
                    <tr>
                        <td></td>
                        <td></td>
                        <td><input type="reset" value="Clear" name="Clear" size="10"/><input type="submit" value="submit" name="Clear" size="10"/></td>
                    </tr>
                </tbody>
            </table>
        </form>
    </body>
</html>

Nextpage.jsp

<%-- 
    Document   : nextPage
    Created on : Jan 1, 2015, 7:55:59 PM
    Author     : ksathis
--%>

<%@page import="java.sql.*" %>
<% Class.forName("com.mysql.jdbc.Driver"); %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Result</title>
    </head>
    <body>
        <h1>DIS SLA RESULT FOR THE WEEK !</h1>
        <%!
            public class imaging {

                String URL = "jdbc:mysql://localhost:3306/database1";
                String USERNAME = "root";
                String PASSWORD = "password";

                Connection connection = null;
                PreparedStatement selectRetouch = null;
                ResultSet resultSet = null;

                public imaging() {
                    try {
                        connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
                        selectRetouch = connection.prepareStatement("select * from retouch limit 1 , ?");

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

                }

                public ResultSet imaging_Result(String limitone) {
                    try {
                        selectRetouch.setString(1, limitone);
                        resultSet = selectRetouch.executeQuery();

                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                    return resultSet;
                }
            }
        %>
        <%
            String str = new String();
            str = request.getParameter("weeknum1");
            imaging image = new imaging();
            ResultSet images = image.imaging_Result(str);
        %>
        <table border="1">
            <tbody>
                <tr>
                    <td>Retail_sku</td>
                    <td>Region</td>
                </tr>
                <% while (images.next()) {%>

                <tr>
                    <td><%= images.getString("retail_sku")%></td>
                    <td><%= images.getString("region")%></td>
                </tr>
                <% }%>
            </tbody>
        </table> 
    </body>
</html>

Answer:

Please try first by rearranging your imports and declarations followed by driver loading later on as a scriptlet :

<%@ page import="java.sql.*" %>
<%@ page contentType="text/html" pageEncoding="UTF-8"%>
<% Class.forName("com.mysql.jdbc.Driver"); %>

Next the class renaming is not okay. First letter of your class should be capital. So rename it to Imaging. It is better to define this class in your source package rather than declare inside JSP page and using it.

The problem area is your PreparedStatement:

selectRetouch.setString(1, limitone);

Since you are setting a limit value, the driver is expecting an Integer value and not a String. To get over this problem here is a workaround:

 selectRetouch.setInt(1, Integer.parseInt(limitone));

To test this through URL you directly hit the link and pass the request parameter like this for example:

http://localhost:8080/yourappname/yourpage.jsp?weeknum1=12

Question:

I'm using Glassfish 3.1.2.2. Is it possible to determine http port number (http-listener-1) from java (EJB) code? I don't have any connections or requests, so reading ServletRequest is not an option.


Answer:

Yes, this is possible. You can use the Glassfish Admin REST API to retrieve nearly every property of the server.

For the properties of the http-listener-1 use the following url: http://localhost:4848/management/domain/configs/config/server-config/network-config/network-listeners/network-listener/http-listener-1

A normal GET request will give you a HTML response, set the Accept header to application/json to retrieve the response in JSON.

In your EJB you just have to issue an HTTP request to the url from above with the right header. Here is an example:

String url = "http://localhost:4848/management/domain/configs/config/server-config/network-config/network-listeners/network-listener/http-listener-1";

URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();

con.setRequestProperty("Accept", "application/json");

BufferedReader in = new BufferedReader(
        new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
}
in.close();

System.out.println(response.toString());

This will give you a result similar to this:

{
    "message": "",
    "command": "http-listener-1",
    "exit_code": "SUCCESS",
    "extraProperties": {
        "commands": [
            {
                "path": "create-ssl",
                "method": "POST",
                "command": "create-ssl"
            }
        ],
        "methods": [
            {
                "name": "GET"
            },
            {},
            {
                "messageParameters": {
                    "address": {
                        "defaultValue": "0.0.0.0",
                        "optional": "true",
                        "type": "string",
                        "key": "false"
                    },
                    "enabled": {
                        "defaultValue": "true",
                        "optional": "true",
                        "type": "boolean",
                        "key": "false"
                    },
                    "jkConfigurationFile": {
                        "defaultValue": "${com.sun.aas.instanceRoot}/config/glassfish-jk.properties",
                        "optional": "true",
                        "type": "string",
                        "key": "false"
                    },
                    "jkEnabled": {
                        "defaultValue": "false",
                        "optional": "true",
                        "type": "boolean",
                        "key": "false"
                    },
                    "name": {
                        "optional": "false",
                        "type": "string",
                        "key": "true"
                    },
                    "port": {
                        "optional": "false",
                        "type": "int",
                        "key": "false"
                    },
                    "protocol": {
                        "optional": "false",
                        "type": "string",
                        "key": "false"
                    },
                    "threadPool": {
                        "optional": "true",
                        "type": "string",
                        "key": "false"
                    },
                    "transport": {
                        "optional": "false",
                        "type": "string",
                        "key": "false"
                    }
                },
                "name": "POST"
            },
            {
                "messageParameters": {
                    "target": {
                        "acceptableValues": "",
                        "defaultValue": "server",
                        "optional": "true",
                        "type": "string"
                    }
                },
                "name": "DELETE"
            }
        ],
        "entity": {
            "address": "0.0.0.0",
            "enabled": "true",
            "jkConfigurationFile": "${com.sun.aas.instanceRoot}/config/glassfish-jk.properties",
            "jkEnabled": "false",
            "name": "http-listener-1",
            "port": "8080",
            "protocol": "http-listener-1",
            "threadPool": "http-thread-pool",
            "transport": "tcp"
        },
        "childResources": {
            "find-http-protocol": "http://localhost:4848/management/domain/configs/config/server-config/network-config/network-listeners/network-listener/http-listener-1/find-http-protocol",
            "property": "http://localhost:4848/management/domain/configs/config/server-config/network-config/network-listeners/network-listener/http-listener-1/property"
        }
    }
}

As you can see the result contains the port (8080 in this case).

You can either parse the value manually from the response string or use some JSON library to convert the response to an JSON object from which you can easily retrieve the property.

This procedure should work if your Glassfish Admin interface is unprotected, if you have enabled secure administration you may have to send authorization parameters with your HTTP request.

See also:

Question:

I am learning java with netbeans . I build web application for insert, update and delete operation. but when i run the application its always returns error 404 not found .

Here is the HTML Code that i want to run .

<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
    <head>
        <title>Add New</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <h1>Add New</h1>
        <div style="width: 900px; margin-left: auto; margin-right: auto">
            <form action="JSP/ManagerAddNew.jsp" method="post">
                Title:<br>
                <input type="text" name="title" style="width: 200px"><br>
                Description:<br>
                <input type="text" name="description" style="width: 200px"><br>
                Detail:<br>
                <textarea name="detail" style="width: 400px; height: 200px"></textarea><br>
                Category: 
                <select name="category">
                    <option value="World">World</option>
                    <option value="Tech">Tech</option>
                    <option value="Sport">Sport</option>
                </select><br>
                Image:<br>
                <input type="text" name="image" style="width: 200px"><br>
                <input type="submit" value="Submit">
            </form>
            <!--Complete Interface Addnew.-->
        </div>

    </body>
</html>

Here is the screen shot of the error message .

Here is my project structure .

Here is the screen of the server and the application has been deployed .


Answer:

i don't know about GlassFish Server,but tomcat. A JSP file under WEB-INF folder can't be visit by URL directly,you can visit it like this:

request.getRequestDispatcher("/WEB-INF/xxx.jsp").forward(request,response);

I'm not sure this way can solve the question under GlassFish,hope it can help you.

Question:

I am having HTTP Status 404 - Not Found.

I am using Netbeans IDE and Glassfish sever and MySql as database. I am unable to understand why I am having the error. Here are my codes.I am a beginner.

Thanks!

This is my JSP file:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>User Application Registration</title>
</head>
<body>
    <h1>Registration Page</h1>
    <form action="ServletRegister" method="post">
        Name: <input type="text" name="name"><br/>
        Password: <input type="password" name="password"><br/>
        Email: <input type="text" name="email"><br/>
        Language: <select name="language">
            <option>Hindi</option>
            <option>English</option>
            <option>Bengali</option>
        </select><br/>
        <input type="submit" value="Submit"/>
    </form>
</body>

This is my Servlet file:

package RegisterPackage;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletRegister extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {



    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    String n = request.getParameter("name");
    String p = request.getParameter("password");
    String e  = request.getParameter("email");
    String l = request.getParameter("language");

    try {
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/demo", "root", "root");
        PreparedStatement ps = con.prepareStatement("insert into userdetails values(?,?,?,?)");

        ps.setString(1, n);
        ps.setString(2, p);
        ps.setString(3, e);
        ps.setString(4, l);

        int i = ps.executeUpdate();
        if (i > 0)
            out.print("You are successfully registered!");
    } 
    catch (Exception e2) {
        System.out.println(e2);
    }
    out.close();  
}

}

This is web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" 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">
    <servlet>
        <servlet-name>ServletRegister</servlet-name>
        <servlet-class>RegisterPackage.ServletRegister</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ServletRegister</servlet-name>
        <url-pattern>/ServletRegister</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>

Directory structure in NetBeans:

My Output:


Answer:

There is nothing in your web app which handles a request to the context root http://localhost:8080/UserApplication therefore the servlet container returns a 404 not found error:

  • Your servlet listens only to http://localhost:8080/UserApplication/ServletRegister
  • Your JSP page isn't visible since you have put it into WEB-INF

You could move the JSP page to directory Web Pages, correct the name (register.jsp) and then call http://localhost:8080/UserApplication/register.jsp

Question:

I have deployed a web app including an EJB (RESTFul web service) from Netbwans 8 into Glassfish 4. This includes a cross origin resource sharing filter. I am getting the "HTTP Status 500 - Internal Server Error" error in the browser when i try to view the output of the web service (directly from the web service path, not from a client per se). I saw in a forum that i might try un-checking a Jersey option in my project properties in Netbeans but i see no such option. The only thing I've found in the logs is:

Info:   WELD-000900 2.0.0 (SP1)
Warning:   Class 'javax.ejb.PostActivate' not found, interception based on it is not enabled
Warning:   Class 'javax.ejb.PrePassivate' not found, interception based on it is not enabled
Info:   Registering the Jersey servlet application, named com.mycompany.enterprisesample.service.ApplicationConfig, at the servlet mapping /webresources/*, with the Application class of the same name.


Aug 21, 2014 11:31:10 AM com.sun.enterprise.glassfish.bootstrap.osgi.BundleProvisioner$DefaultCustomizer getLocations
WARNING: Skipping entry  because it is not an absolute URI.
Aug 21, 2014 11:31:10 AM com.sun.enterprise.glassfish.bootstrap.osgi.BundleProvisioner$DefaultCustomizer getLocations
WARNING: Skipping entry  because it is not an absolute URI.
Registered com.sun.enterprise.glassfish.bootstrap.osgi.EmbeddedOSGiGlassFishRuntime@5c8edb94 in service registry.

Answer:

Add

<jvm-options>-Djavax.xml.accessExternalSchema=all</jvm-options> 

line of code in the domain.xml file at glassfish4\glassfish\domains\domain1\config\domain.xml folder

inside <java-config> </java-config> tag as :-

<java-config>
.
.
<jvm-options>-Djavax.xml.accessExternalSchema=all</jvm-options>
</java-config>

Note:- add the above line of code at the last of the –D..... code of the domain.xml file. Adding it at random position may not gurantee that this will work.

Question:

I have tried putting the following on my web.conf

<security-constraint>
    <web-resource-collection>
        <web-resource-name>SecureResource</web-resource-name>
        <url-pattern>/*</url-pattern>
    </web-resource-collection>
    <user-data-constraint>
        <transport-guarantee>CONFIDENTIAL</transport-guarantee>
    </user-data-constraint>
</security-constraint>

But when I publish I get a "Too many redirects" on chrome.


Answer:

I assume you are running Glassfish behind a load balancer on AWS, and SSL termination is happening at the load balancer.

You need to configure Glassfish to check the x-forwarded-proto header to determine if the client is connecting via HTTP or HTTPS. You can do this via the scheme-mapping parameter in your domain.xml file:

<http default-virtual-server="server"
      max-connections="100"
      scheme-mapping="X-Forwarded-Proto">

Alternatively, you can run this command on the server to set the scheme-mapping value:

asadmin set server.network-config.protocols.protocol.http-listener-1.http.scheme-mapping=X-Forwarded-Proto

Question:

I am developing an XML based Web Service, but firstly i wanted to see wether a java class would be executed on a server. The server of my choosing was GlassFish 5. After a ride with all the setting i got it runing, now as you can see i stumbled upon this kind of Error

My Code ExampleWs:

package ws;

import javax.jws.WebService;

@WebService
    public class ExampleWs {

        public String getText() {
            return "Some Text";
        }

    }

Now i want to know what can be done in order to solve this Error. I also tried another way of deploying ExampleWs.java -> directly through asadmin with Command Prompt, but there is this error:


Answer:

To my knowledge you cannot deploy just a class file. You need to create some kind of archive that contains your classes along with some other information (e.g. deployment descriptor that tells the application server what to do with the contained classes).

If you want to create a web application then the kind of archive will most likely be a WAR (web archive).

If you are using Eclipse IDE for JEE Developers you should be able to right-click on your project and from there export it as a WAR.

How to make war file in Eclipse

Question:

I successfully deployed a Java servlet on glassfish5 in my Raspberry PI3. Now I wanted to use another servlet for a Telegram bot, but in this case I need to use HTTPS.

I tried to define a new servlet with in the web.xml, but when I try to reach the servlet via https connection from a browser the result is an ERR_CONNECTION_REFUSED.

My servlet

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;

@WebServlet("/telegramUpdate")

public class TelegramUpdate extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public TelegramUpdate() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        System.out.println("doGet");

    }

    protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        System.out.println("doPost");

    }

}

And 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>Smarthome</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <security-constraint>
    <web-resource-collection>
      <web-resource-name>telegram webhook</web-resource-name>
      <url-pattern>/telegramMessage</url-pattern>
    </web-resource-collection>
    <user-data-constraint>
        <transport-guarantee>CONFIDENTIAL</transport-guarantee>
    </user-data-constraint>
  </security-constraint>
</web-app>

In case it be a raspberry config problem, this is the result of netcat -lptn

pi@raspberrypi:~/glassfish5/glassfish/domains/domain1/logs$ netstat -lptn
(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 127.0.0.1:5939          0.0.0.0:*               LISTEN      -               
tcp        0      0 0.0.0.0:53              0.0.0.0:*               LISTEN      -               
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      -               
tcp        0      0 0.0.0.0:1883            0.0.0.0:*               LISTEN      -               
tcp6       0      0 :::8686                 :::*                    LISTEN      -               
tcp6       0      0 :::80                   :::*                    LISTEN      -               
tcp6       0      0 :::4848                 :::*                    LISTEN      -               
tcp6       0      0 :::8080                 :::*                    LISTEN      -               
tcp6       0      0 :::3700                 :::*                    LISTEN      -               
tcp6       0      0 :::8181                 :::*                    LISTEN      -               
tcp6       0      0 :::53                   :::*                    LISTEN      -               
tcp6       0      0 :::22                   :::*                    LISTEN      -               
tcp6       0      0 :::1527                 :::*                    LISTEN      -               
tcp6       0      0 :::1883                 :::*                    LISTEN      -

443 port is not mentioned, but in case it is closed I don't know how to open it


Answer:

Please try with port 8181 which is the default port for secured communication on Payara and Glassfish. Please also see here: https://blog.payara.fish/securing-payara-server-with-custom-ssl-certificate

Question:

If I send my server an GET-request with params, I'm getting a 405 - Method not allowed.

 package pkgService;

 import com.fasterxml.jackson.databind.ObjectMapper;
 import pkgData.pkgEmployee.User;
 import pkgServer.pkgUser.UserManagement;

 import javax.ws.rs.*;
 import javax.ws.rs.core.Response;

@Path("/user")
public class UserRouter {

     private UserManagement userManagement;
     private ObjectMapper objMap;

     public UserRouter() {
         this.userManagement = new UserManagement();
         objMap = new ObjectMapper();

         //TODO delete test data
         userManagement.addUser(new User(1,"lukad", "luki"));
         userManagement.addUser(new User(2,"meli", "malal"));
     }

     @GET
     @Path("{userId}")
     public Response getBook(@PathParam("userId") String id) {
         Response.ResponseBuilder response = Response.status(Response.Status.OK);
         try {
             response.entity(objMap.writeValueAsString(userManagement.getUser(id)));
         } catch (Exception e) {
             response.status(Response.Status.BAD_REQUEST);
             response.entity("[ERROR] " + e.getMessage());
         }
         return response.build();
     } }

I expect to get the user with the id 1 (lukad,luki), but I received a 405.

My postman request Url: http://localhost:8080/Server_war_exploded/user?userId=1

Did I forget something in the code ?


Answer:

Change function as by adding '/' before user id

@GET
@Path("/{userId}")
     public Response getBook(@PathParam("userId") String id) {
}

Also if you are using PathParam then you need to change url also as

 http://localhost:8080/Server_war_exploded/user/1

where 1 is user id

But if you want to use

 http://localhost:8080/Server_war_exploded/user?userId=1

Then you need to use QueryParams and change your code as follow

 @GET
 public Response getBook(@QueryParam("userId") String id) {
    }

Question:

When I rename the name of a dynamic web project with JSF v2.2 as configuration created by itself Eclipse 2019.03 then I redeploy it on glassfish v5.1 with Eclipse, gets HTTP Status 404 - Not Found... While it was working well before renaming project name.

web.xml file:

<?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" 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>test1</display-name>
  <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>/faces/*</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.xhtml</welcome-file>
  </welcome-file-list>
</web-app>  

There is a simple index.xhtml in /WebContent


Answer:

I noticed when a new dynamic web project with JSF as configuration has been created by itself Eclipse, if you use Glassfish as server, there will be an additional file named glassfish-web.xml in /WebContent/WEB-INFO directory. When the name of a dynamic web project is renamed, the line below of glassfissh-web.xml file should be modified manually to new name of the project:

<context-root>/testProject</context-root>

Question:

I am supporting another vendors legacy application.

This is a J2EE application that runs on Glassfish v3.1.2.2. It has a REST API implemented using JAX-RS. I have limited visibility to the application and source.

The symptoms are:

  • make an HTTP request to a REST API
  • application has its own auditing system, this shows a successful request
  • no errors in GF logs
  • GF access log notes the request
  • 0 bytes are returned from the request to the caller

This happens for both remote calls as well as from calls made using curl on localhost.

If we make the same requests to a different port over HTTPS they succeed. We are reluctant to move the calls to that other port without knowing a root cause. These failed intermittently last night and now fail constantly today.

A packet capture of the request shows: - TCP overhead/handshake - A GET request - A single ACK from the application back to the caller - then nothing after that

What would cause Glassfish v3 to successfully handle and process an HTTP request but return no data?

Is there a mechanism in Glassfish v3 to flush or reset an HTTP listener and its associated thread pool?

Since this happens on a curl request on the same server to localhost I think I can rule out the network being the issue.

The ports being used communicate directly with Glassfish. There is no proxy (like Apache or Nginx) between the caller and the app server.

Are there logging or monitoring settings I should be enabling in Glassfish to observe what the HTTP listener is doing relative to the application and the network stack?

I have obfuscated some examples that show the symptoms:

Glassfish Access log:

"0:0:0:0:0:0:0:1" "NULL-AUTH-USER" "25/Oct/2018:11:21:02 -0500" "GET /api/obfuscated/by/me HTTP/1.1" 200 9002 

Curl response for that same call:

*   Trying OFBBFUSCATED
* Connected to hostname.local (OFBBFUSCATED) port 11080 (#0)
> GET /api/obfuscated/by/me HTTP/1.1
> Host: hostname.local:11080
> User-Agent: curl/7.43.0
> Accept: */*
> Authorization: Basic asdfdsfsdfdsfsdafsdafsdafw==
>
* Empty reply from server
* Connection #0 to host hostname.local left intact

UPDATE I changed a timeout setting for the HTTP network listener. I bumped it from 30 to 35 seconds because I was seeing a packet capture where the app was sending a FIN after 30 seconds. After making this change it started to work again.

It is not clear if this somehow flushed or reset something or if I had some kind of race condition.


Answer:

The apparent root cause was high I/O on the system running these services. The applications normally used 50MB/sec, a new process drove that usage to 250MB/sec. Once the I/O problem was resolved all of the HTTP errors went away and haven't come back.

Question:

I have an httpClient that send a json object and a set of file in the body The REST WS is a glassfish (payara) server When the file are little (not beyond 1k) it's working well When I send a request with a file larger than the others (I tried with ~130k and ~50k file) it throws an error at multipartStream.readBodyData(os); of the following function

public static String parseMultipart(InputStream stream, List<UploadedFile> uploadedFiles) throws IOException {

    String msgInfo = null;

    MultipartStream multipartStream = new MultipartStream(stream, "".getBytes());
    boolean nextPart = multipartStream.skipPreamble();

    if (nextPart) {

        // Information
        multipartStream.readHeaders();

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        multipartStream.readBodyData(os);
       //json part
        msgInfo = new String(os.toByteArray(), java.nio.charset.StandardCharsets.UTF_8);

        nextPart = multipartStream.readBoundary();
    }

    // Files
    while (nextPart) {

        String header = multipartStream.readHeaders();
        String fileName = null;

        int fileNameStart = header.indexOf("filename=\"");
        int fileNameEnd = -1;
        if (fileNameStart != -1) {

            fileNameEnd = header.indexOf("\"", fileNameStart + 10);
            if (fileNameEnd != -1) {
                fileName = header.substring(fileNameStart + 10, fileNameEnd);
            }
        }

        if (fileName != null) {

            // Reads the body - Actual file data
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            multipartStream.readBodyData(os);

            if (os.size() > 0) {
                UploadedFile uploadedFile = new ByteArrayUploadedFile(os.toByteArray(), fileName, "");
                uploadedFiles.add(uploadedFile);
            } else {

                return null;
            }

        } else {
            return null;
        }

        nextPart = multipartStream.readBoundary();
    }

    return msgInfo;

The error is

Warning:   StandardWrapperValve[webServices.ApplicationConfig]: Servlet.service() for servlet webServices.ApplicationConfig threw exception
java.util.concurrent.TimeoutException
    at org.glassfish.grizzly.nio.tmpselectors.TemporarySelectorReader.read(TemporarySelectorReader.java:126)
    at org.glassfish.grizzly.nio.tmpselectors.TemporarySelectorReader.read(TemporarySelectorReader.java:75)
    at org.glassfish.grizzly.AbstractReader.read(AbstractReader.java:72)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransportFilter.handleRead(TCPNIOTransportFilter.java:77)
    at org.glassfish.grizzly.filterchain.TransportFilter.handleRead(TransportFilter.java:173)
    at org.glassfish.grizzly.ssl.SSLBaseFilter$SSLTransportFilterWrapper.handleRead(SSLBaseFilter.java:1132)
    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.read(DefaultFilterChain.java:352)
    at org.glassfish.grizzly.filterchain.FilterChainContext.read(FilterChainContext.java:736)
    at org.glassfish.grizzly.http.io.InputBuffer.blockingRead(InputBuffer.java:1103)
    at org.glassfish.grizzly.http.server.io.ServerInputBuffer.blockingRead(ServerInputBuffer.java:95)
    at org.glassfish.grizzly.http.io.InputBuffer.fill(InputBuffer.java:1127)
    at org.glassfish.grizzly.http.io.InputBuffer.read(InputBuffer.java:348)
    at org.apache.catalina.connector.InputBuffer.read(InputBuffer.java:273)
    at org.apache.catalina.connector.CoyoteInputStream.read(CoyoteInputStream.java:270)
    at org.glassfish.jersey.message.internal.EntityInputStream.read(EntityInputStream.java:102)
    at myapp.webServices.MultipartStream.readBodyData(MultipartStream.java:333)
    ...

The client part is with apache httpClient, the relevant part is

    request = new HttpPost(baseUrl + wsName);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addTextBody("info", restBag.getAsJsonObject().toString(), ContentType.APPLICATION_JSON);

    for (File file : restBag.getFileMap().values()) {
        builder.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM, file.getName());
    }
    HttpEntity multipart = builder.build();
    request.setEntity(multipart);
response = httpClient.execute(request, localContext);

UPDATE

I've tried to change the REST method, using apache commons, but the result is the same

@POST
@Path("/send")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed({"WS_Crea_Messaggio"})
public ReturnMessage sendMessage1(@Context HttpServletRequest httpRequest) throws IOException, JAXBException
{

    LOG.log(Level.FINEST, "User {0} called sendMessage", new Object[]{user});

    ReturnMessage ret = new ReturnMessage();
    String info = null;
    List<UploadedFile> uploadedFiles = new ArrayList<>();
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request
    Iterator /* FileItem */ items;
    try {
        items = upload.parseRequest(httpRequest).iterator();
while (items.hasNext()) {
    FileItem thisItem = (FileItem) items.next();
        if (thisItem.getFieldName().equals("info")) {
            info = thisItem.getString();
            // Do something with the value
    } else if (thisItem.getFieldName().equals("file")) {
        uploadedFiles.add(new ByteArrayUploadedFile(thisItem.get(), thisItem.getName(), thisItem.getContentType()));
    }

}
    }
    catch (FileUploadException ex) {
        LOG.log(Level.INFO, "Erroro uploading messages", ex);
        ret.setStatus(ReturnStatusEnum.ERROR);
        ret.setErrorCode(ReturnErrorCodeEnum.FILE_NOT_UPLOADED);
        return ret;
    }
....
}

No luck, again stop items = upload.parseRequest(httpRequest).iterator(); waiting for timeout

org.apache.commons.fileupload.FileUploadBase$IOFileUploadException: Processing of multipart/form-data request failed. java.util.concurrent.TimeoutException
at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:371)
at org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:126)
at myapp.webServices.MessagesWebService.sendMessage1(MessagesWebService.java:331)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1081)
at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1153)
at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4762)
at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:656)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:834)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:64)
at org.jboss.weld.ejb.SessionBeanInterceptor.aroundInvoke(SessionBeanInterceptor.java:52)
at sun.reflect.GeneratedMethodAccessor147.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:895)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:834)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:140)
at sun.reflect.GeneratedMethodAccessor149.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:895)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:834)
at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:374)
at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4734)
at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4722)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
at com.sun.proxy.$Proxy450.sendMessage1(Unknown Source)
at myapp.webServices.__EJB31_Generated__MessagesWebService__Intf____Bean__.sendMessage1(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161)
at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$TypeOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:205)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102)
at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:326)
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:305)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)
at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:473)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1693)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161)
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:466)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:169)
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: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:526)
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:593)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:573)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.IOException: java.util.concurrent.TimeoutException
at org.glassfish.grizzly.nio.transport.TCPNIOTransportFilter.handleRead(TCPNIOTransportFilter.java:90)
at org.glassfish.grizzly.filterchain.TransportFilter.handleRead(TransportFilter.java:173)
at org.glassfish.grizzly.ssl.SSLBaseFilter$SSLTransportFilterWrapper.handleRead(SSLBaseFilter.java:1132)
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.read(DefaultFilterChain.java:352)
at org.glassfish.grizzly.filterchain.FilterChainContext.read(FilterChainContext.java:736)
at org.glassfish.grizzly.http.io.InputBuffer.blockingRead(InputBuffer.java:1103)
at org.glassfish.grizzly.http.server.io.ServerInputBuffer.blockingRead(ServerInputBuffer.java:95)
at org.glassfish.grizzly.http.io.InputBuffer.fill(InputBuffer.java:1127)
at org.glassfish.grizzly.http.io.InputBuffer.read(InputBuffer.java:348)
at org.apache.catalina.connector.InputBuffer.read(InputBuffer.java:273)
at org.apache.catalina.connector.CoyoteInputStream.read(CoyoteInputStream.java:270)
at org.apache.commons.fileupload.MultipartStream$ItemInputStream.makeAvailable(MultipartStream.java:976)
at org.apache.commons.fileupload.MultipartStream$ItemInputStream.read(MultipartStream.java:886)
at java.io.InputStream.read(InputStream.java:101)
at org.apache.commons.fileupload.util.Streams.copy(Streams.java:96)
at org.apache.commons.fileupload.util.Streams.copy(Streams.java:66)
at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:366)
... 88 more
Caused by: java.util.concurrent.TimeoutException
at org.glassfish.grizzly.nio.tmpselectors.TemporarySelectorReader.read(TemporarySelectorReader.java:126)
at org.glassfish.grizzly.nio.tmpselectors.TemporarySelectorReader.read(TemporarySelectorReader.java:75)
at org.glassfish.grizzly.AbstractReader.read(AbstractReader.java:72)
at org.glassfish.grizzly.nio.transport.TCPNIOTransportFilter.handleRead(TCPNIOTransportFilter.java:77)
... 107 more

I've tested it using both client and server on the same machine, but I have also tried with a remote client on the same subnet


Answer:

The timeout you are getting is because the NIO (non-blocking) layer at the bottom reading the message body doesn't receive a new chunk of data within a timeout, which is by default 1 second. It means that the server processes anything that comes and if nothing more comes within 1 second, it throws the Timeout exception.

You can increase the timeout to more than 1 second to handle the bigger requests. You can do it in the Admin console, in Network Config -> Transports -> tcp -> Selector Poll Timeout. By default, it is 1000 milliseconds.

The reason might be that the connection is slow, much slower than the server is capable of reading the data. For smaller requests, I guess that whole 1k requests fits one or small number of TCP packets and comes as a single piece of data. For bigger requests, the number of packets is bigger and they come after a big delay, probably caused by a slow connection or by HTTP client sending the data slowly.

Question:

I am developing a RESTful web service application in IntelliJ idea. I am deploying it to GlassFish with a war exploded artifact. The application simply works sometimes, and doesn't other times. I can launch it, it runs fine, then stop the application, launch it again, and I get 404. Here are a list of things that seems to temporarily fix the issues (until a consequent run with the same configuration and I get another 404).

  • Rebuilding the project
  • Removing and re-adding the war exploded artifact
  • Removing or adding libraries or dependencies
  • Unchecking or checking export on dependencies
  • Redeploying the application (but not restarting the server)
  • Reloading the application from the admin console

GlassFish log prints out the following

[2017-02-14T21:38:37.212-0700] [Payara 4.1] [WARNING] [] [org.glassfish.jersey.servlet.init.JerseyServletContainerInitializer] [tid: _ThreadID=63 _ThreadName=admin-thread-pool(2)] [timeMillis: 1487133517212] [levelValue: 900] [[ Mapping conflict. A Servlet registration exists with same mapping as the Jersey servlet application, named launcher.MyApplication, at the servlet mapping, /*.]]

But it does this when it runs successfully and when it fails, it doesn't seem to be related. I will research it more but have found little information on this message (perhaps because its a warning of little importance?)

I have been banging my head against this issue for a while now. I am a absolute beginner to deploying applications to servers (especially in IntelliJ), but any help or tips would be appreciated.

Thank you

EDIT: I have not gotten to the point where if I restart the server or redeploy enough times it works again. Anywhere from 2-5 tries and it works again with for no reason. (Seems to work more frequently when I redeploy)


Answer:

Well it seems like I have finally found the issue. I was missing a servlet mapping in the web.xml to the class in my project that subclasses Application and uses the @ApplicationPath annotation to identify the base URI for all of the JAX-RS REST resources.

...
    <servlet>
        <servlet-name>services.MyApplication</servlet-name>
    </servlet>
    <servlet-mapping>
        <servlet-name>services.MyApplication</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
...

Still unsure as to how it worked occasionally without this mapping specified, very weird. Anyway now it seems to function correctly every time.

Question:

I have a Glassfish server and I expect it to be rather loaded. For example, I have RESTful services and I want to make a request to Google API in the one of the methods. Should I create a new Thread to do such a work?


Answer:

No, you should avoid managing anything with threads manually inside the Java EE world. This work is should be provided by the container (Glassfish in this case), especially for a HTTP response.

Inside of EJBs it is even prohibited:

The enterprise bean must not attempt to manage threads. The enterprise bean must not attempt to start, stop, suspend, or resume a thread, or to change a thread’s priority or name. The enterprise bean must not attempt to manage thread groups.

(EJB 3.1 spec, page 599)

There are some exceptions where you may need to do something manually in a web application, but in general it should be avoided.

See also:

  • Thread creation in JavaEE EJB/Web containers
  • Java EE specification and multi threading

Question:

I have a little problem with the development of an https request with in an ManagedBean. The problem is that I'm getting following exception:

javax.net.ssl.SSLPeerUnverifiedException: Host name 'bitpay.com' does not match the certificate subject provided by the peer (CN=bitpay.com, O="BitPay, Inc.", L=Atlanta, ST=Georgia, C=US, SERIALNUMBER=5163966, OID.2.5.4.15=Private Organization, OID.1.3.6.1.4.1.311.60.2.1.2=Delaware, OID.1.3.6.1.4.1.311.60.2.1.3=US)

But if I try the code in a pure java client it works perfectly fine. Does anyone know where my failure is?

I've used the code from this repository.

My own code is following:

import model.BitPay;
import model.Invoice;
import javax.inject.Named;
import javax.enterprise.context.Dependent;


@Named(value = "bitPayMBean")
@Dependent
public class BitPayMBean {

    private static final String API_KEY = "";

    @Named(value = "returnUrl")
    private String returnUrl = "URL";

    public void setReturnUrl(String returnUrl) {
        this.returnUrl = returnUrl;
    }

    public String getReturnUrl() {
        return returnUrl;
    }

    public BitPayMBean() {
        System.setProperty("javax.net.ssl.trustStore", "cacerts.jks");
        System.setProperty("javax.net.ssl.trustStorePassword", "changeit");

    }

    public void transaction(double value) {
        BitPay bitpay = new BitPay(API_KEY, "USD");
        Invoice invoice = bitpay.createInvoice(value);
        setReturnUrl(invoice.getUrl());
    }

}

Cheers and thanks for your advise


Answer:

So i've solved my problem. The problem was that in my cert file of JDK version 8 hasn't all cetificates intetegrated which where in my cert file of the JDK version 6. So i've integrated the missing certs of the jdk6 in my jdk8 cert file. That solved my problem

Question:

Iam working on a webapplication using java 8, maven and a glassfish-server.

Iam trying to convert a Part object to a File object with following Code to use it for the javaMail attachment.

First of all My Application Folder looks Like This

And My Code:

public  void copyPartToFile() throws IOException{
    InputStream inputStream = part.getInputStream();
    String contentType = part.getContentType();
    String pathname = "GradePlus/Attachment/tmpFile."+ contentType.substring(contentType.lastIndexOf('/') +1);
    File copy = new File(pathname);
    OutputStream outputStream = new FileOutputStream(copy);
    try {
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, length);
        }
    } finally {
        inputStream.close();
        outputStream.close();
    }
}

The Stacktrace is saying, that there was no such file or directory.

 #{fileBean.copyPartToFile}: java.io.FileNotFoundException:GradePlus/Attachment/tmpFile.csv (No such file or directory)
javax.faces.FacesException: #{fileBean.copyPartToFile}: java.io.FileNotFoundException: GradePlus/Attachment/tmpFile.csv (No such file or directory)
	at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
	at javax.faces.component.UICommand.broadcast(UICommand.java:315)
	at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
	at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
	at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
	at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
	at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
	at javax.faces.webapp.FacesServlet.service(FacesServlet.java:658)
	at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1692)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:258)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
	at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:654)
	at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:593)
	at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:159)
	at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:371)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:238)
	at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:483)
	at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:180)
	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: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:539)
	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:593)
	at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:573)
	at java.lang.Thread.run(Thread.java:745)
Caused by: javax.faces.el.EvaluationException: java.io.FileNotFoundException: GradePlus/Attachment/tmpFile.csv (No such file or directory)
	at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
	at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
	... 35 more
Caused by: java.io.FileNotFoundException:GradePlus/Attachment/tmpFile.csv (No such file or directory)
	at java.io.FileOutputStream.open0(Native Method)
	at java.io.FileOutputStream.open(FileOutputStream.java:270)
	at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
	at java.io.FileOutputStream.<init>(FileOutputStream.java:162)
	at controller.FileBean.copyPartToFile(FileBean.java:132)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at com.sun.el.parser.AstValue.invoke(AstValue.java:289)
	at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
	at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
	at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
	at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
	at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
	... 36 more
]]

[2018-03-02T20:08:55.497+0100] [Payara 4.1] [WARNUNG] [] [javax.enterprise.web] [tid: _ThreadID=28 _ThreadName=http-thread-pool::http-listener-1(4)] [timeMillis: 1520017735497] [levelValue: 900] [[
  StandardWrapperValve[Faces Servlet]: Servlet.service() for servlet Faces Servlet threw exception
java.io.FileNotFoundException: /Users/arbnor/Documents/Repositories/Software_Projekt2/GradePlus/GradePlus/Attachment/tmpFile.csv (No such file or directory)
	at java.io.FileOutputStream.open0(Native Method)
	at java.io.FileOutputStream.open(FileOutputStream.java:270)
	at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
	at java.io.FileOutputStream.<init>(FileOutputStream.java:162)
	at controller.FileBean.copyPartToFile(FileBean.java:132)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at com.sun.el.parser.AstValue.invoke(AstValue.java:289)
	at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
	at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
	at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
	at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
	at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
	at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
	at javax.faces.component.UICommand.broadcast(UICommand.java:315)
	at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
	at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
	at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
	at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
	at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
	at javax.faces.webapp.FacesServlet.service(FacesServlet.java:658)
	at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1692)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:258)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
	at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:654)
	at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:593)
	at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:159)
	at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:371)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:238)
	at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:483)
	at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:180)
	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: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:539)
	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:593)
	at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:573)
	at java.lang.Thread.run(Thread.java:745)

Answer:

You're using a relative path name. That name is relative to the directory where the GlassFish server was started. The GradePlus/Attachment directory probably doesn't exist there. It would be much better to use an absolute path name so you know exactly where the file will end up.

Since this is just a temporary file, consider using the File.createTempFile method.

Also, note that you can simplify your code using the MimeBodyPart.saveFile method.