Hot questions for Using Applets in web services

Top Java Programmings / Applets / web services

Question:

I'm currently planning on making a simple IRC style chat client and server system using Java for practice. I did some research into different ways of including the client functionality on a webpage like applets and java-web-start. I would like to have the client running on the users machine instead of the server itself. As I interpreted, out of the two, the applet pretty much does exactly that and seems way less effort to set up.

However, it turns out that applets have their own graphical implementation using "Graphics" class to render things like text, lines and shapes. Instead of going for something fancy, I would like to use a simple console interface like cmd on windows or shell on unix systems.

Is it possible to have this type of console running on a webpage as java applet or would I basically have to code the entire graphical look using the tools provided by the Graphics class? For this practice project, it would be ideal just using simple functionality provided in console windows like "nexInt()" and "system.out.print()" instead of having to add complex elements for input and output.

TL;DR: Is it possible to embed an OS console within a webpage using java and what would be the preferred method of going about it?


Answer:

Is it possible to embed an OS console within a webpage using java ..

AFAIU it is not possible to embed a console in a Swing or AWT desktop app. As far as embedding that into a web page, that would require an applet. Chrome and FF have completely removed support for applets and IE is set to follow.

Question:

I am trying to use Amazon's SDK to upload files to Amazon S3 from a Java applet. The applet sits on a web server running Spring.

The problem is that before I try to upload my file I need to initialise the Amazon S3 client. This is usually pretty simple:

AWSCredentials credentials = new BasicAWSCredentials(AWS_ACCESS_KEY, AWS_SECRET_KEY);
AmazonS3Client s3Client = new AmazonS3Client(credentials);

But when I do that, the second line triggers this error message (regardless of whether the credentials are correct or not):

java.lang.ClassFormatError: Incompatible magic value 1008813135 in class file <!DOCTYPE html>
    at java.lang.ClassLoader.defineClass1(Native Method) ~[na:1.8.0_66]
    at java.lang.ClassLoader.defineClass(Unknown Source) ~[na:1.8.0_66]
    at java.security.SecureClassLoader.defineClass(Unknown Source) ~[na:1.8.0_66]
    at sun.plugin2.applet.Applet2ClassLoader.findClass(Unknown Source) ~[na:na]
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass0(Unknown Source) ~[na:na]
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source) ~[na:na]
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source) ~[na:na]
    at java.lang.ClassLoader.loadClass(Unknown Source) ~[na:1.8.0_66]
    at org.apache.commons.logging.LogFactory.createFactory(LogFactory.java:1131) ~[upload.jar:na]
    at org.apache.commons.logging.LogFactory$2.run(LogFactory.java:1065) ~[upload.jar:na]
    at java.security.AccessController.doPrivileged(Native Method) ~[na:1.8.0_66]
    at org.apache.commons.logging.LogFactory.newFactory(LogFactory.java:1062) ~[upload.jar:na]
    at org.apache.commons.logging.LogFactory.getFactory(LogFactory.java:569) ~[upload.jar:na]
    at org.apache.commons.logging.LogFactory.getLog(LogFactory.java:685) ~[upload.jar:na]
    at com.amazonaws.AmazonWebServiceClient.<clinit>(AmazonWebServiceClient.java:56) ~[upload.jar:na]

What's happening here is the AWS library is trying to initialise its logging system, so it starts searching for the LogFactory that's going to handle any internal logging messages. The problem is it starts to search outside of the applet, by making a GET request for

http://localhost/...myUrl.../commons-logging.properties

(I found this out from the docs here: https://commons.apache.org/proper/commons-logging/apidocs/org/apache/commons/logging/package-summary.html)

Now, a quick side note: My security-app-context.xml file for Spring contains the following entry point bean to make sure non-authenticated users only see the log-in page:

<beans:bean id="loginUrlAuthenticationEntryPoint" class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
    <beans:constructor-arg value="/loginPage" />
</beans:bean>

It's at this stage that my Spring set-up is catching the GET request and redirecting it to the server log-in page. This redirect ends up sending a valid HTML page as the result of this GET request. The HTML page's first line is '', which the Logging Framework parses and tries to use that to initialise a Java class. Obviously a class called .class doesn't exist, so I get the ClassFormatError.

Is there a way to get the AWS library to play nicely with this set up? Ideally without disabling Spring's redirection policy.


Answer:

You can work around that particular error by telling the logging framework exactly where to find a LogFactory implementation by putting this line in somewhere before the new AmazonS3Client() call:

System.setProperty("org.apache.commons.logging.LogFactory", "org.apache.commons.logging.impl.LogFactoryImpl");

However, you may find the same problem appears with a different file, two of them in fact, this time a bit deeper inside Amazon's library. Again, they are searched for using GET requests (as seen in the Java console).

http://localhost/...myUrl.../com/amazonaws/services/s3/request.handlers
http://localhost/...myUrl.../com/amazonaws/services/s3/request.handler2s

So, you need a file called request.handlers and another called request.handler2s, both inside a folder structure of com/amazonaws/services/s3, with the com folder in one of your Classpath folders (Probably the root of your applet's JAR file). The files should be empty.

With the LogFactory property set to prevent searching for commons-logging.properties, and the Amazon request handler files in place the initialisation should complete successfully.

(This answer feels a bit unwieldy and I'm not completely happy with it, so alternatives are very welcome).

Question:

I'm trying to develope an application under C# wich it has some applets in Java and when I run it, I see on my Java console a mistake wich is: SAAJ0537: Invalid Content-Type. More exactly is this one:

 feb 18, 2015 12:46:10 PM com.sun.xml.internal.messaging.saaj.soap.MessageImpl identifyContentType
 GRAVE: SAAJ0537: Content-Type no válido. Podría ser un mensaje de error en lugar de un mensaje SOAP
 com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl:    com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: Invalid Content-Type:text/html. Is this an error message instead of a SOAP response?
at 
com.sun.xml.internal.messaging.saaj.client.p2p.HttpSOAPConnection.call(Unknown Source)
at paqSoap.Soap.enviar_y_obtener_string(Soap.java:273)
at paqConfiguracion.ConfiguracionMenu.<init>(ConfiguracionMenu.java:404)
at paqApplet.PruebaMenu.iniciarVariables(PruebaMenu.java:265)
at paqApplet.PruebaMenu.init(PruebaMenu.java:165)
at com.sun.deploy.uitoolkit.impl.awt.AWTAppletAdapter.init(Unknown Source)
at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

Caused by: com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: Invalid Content-Type:text/html. Is this an error message instead of a SOAP response?
at com.sun.xml.internal.messaging.saaj.soap.MessageImpl.identifyContentType(Unknown Source)
at com.sun.xml.internal.messaging.saaj.soap.MessageFactoryImpl.createMessage(Unknown Source)
at com.sun.xml.internal.messaging.saaj.client.p2p.HttpSOAPConnection.post(Unknown Source)
... 8 more

So it says something from the headers if I'm not wrong. The code where is the mistake is this one:

public String enviar_y_obtener_string()   {


            try
            {
                SOAPConnectionFactory scf = SOAPConnectionFactory.newInstance();
                SOAPConnection connection = scf.createConnection();

                //Crea el mensaje
                MessageFactory mf = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);
                SOAPMessage message = mf.createMessage();


                System.out.println("El mensaje al principio es:"+message);

                //Crea las partes del mensaje       
                SOAPPart soapPart = message.getSOAPPart();
                SOAPEnvelope envelope = soapPart.getEnvelope();
                SOAPBody body = envelope.getBody();

                System.out.println("El servidor en enviar_y_obtener_string es:"+servidor+" y el método es:"+metodo);

                Name n = envelope.createName(metodo,"","http://localhost:3624/");   
                SOAPBodyElement soapBodyElement =body.addBodyElement(n);

                for(int i=0;i<lista_nombre_parametros.size();i++)
                {


                    SOAPElement soapElement = soapBodyElement.addChildElement(lista_nombre_parametros.get(i).toString());
                    System.out.println("El nombre del parámetro es:"+lista_nombre_parametros.get(i).toString());
                    int tipo=Integer.valueOf(lista_tipo_parametro.get(i).toString()).intValue();
                    if(tipo==IdTipoCadena){

                        soapElement.addTextNode(lista_valores_parametros.get(i).toString());
                        System.out.println("El valor es:"+ lista_valores_parametros.get(i).toString());
                    }
                    else
                    {
                        SOAPFactory soapFactory = SOAPFactory.newInstance();
                        Name nodeName = envelope.createName("nodo");
                        SOAPElement soapElementint=soapElement.addChildElement(nodeName);
                        ArrayList arraydev=(ArrayList)lista_valores_parametros.get(i);
                        for(int j=0;j<arraydev.size();j++)
                        {
                            Name name3 = envelope.createName("carlos");
                            SOAPElement soapElementhijo=soapElementint.addChildElement(name3);  
                            soapElementhijo.addTextNode("p");

                        }
                    }

                }



                message.setProperty(Call.SOAPACTION_USE_PROPERTY, new Boolean( true ));
                message.setProperty(Call.SOAPACTION_URI_PROPERTY,url);

                MimeHeaders hd = message.getMimeHeaders();

                String serverURI = soapAction;
                System.out.println("ServerURI en enviar_y_obtener_string es:"+serverURI);
                hd.addHeader("SOAPAction", "http://localhost:3624/getConfig");


                url=leerPropiedades()[2];
                System.out.println("La url es dentro de enviar_y_obtener_string:"+url);
                //Establece la URL del destino
                URL endpoint = new URL(url);

                //Envía el mensaje
                System.out.println("Endpoint es:"+endpoint);

                String msg;
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                message.writeTo(baos);
                msg = baos.toString();
                System.out.println("msg es:"+message);



                SOAPMessage response = connection.call(message, endpoint);
                System.out.println("Voy a cerrar la conexión");
                //Cierra la conexión
                connection.close();

                //Obtiene los resultados
                TransformerFactory tf = TransformerFactory.newInstance();
                return response.getSOAPBody().getFirstChild().getTextContent();

            }
            catch (Exception ex) 
            {
                ex.printStackTrace();
                return "";
            }


        }

And it fails, why?. Could you help me please?. Thanks so much. The line where is the mistake is this one: SOAPMessage response = connection.call(message, endpoint);

When I put on my browser the asmx from C# I have this:

POST /web/soa/soa.asmx HTTP/1.1
Host: localhost
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://localhost:3624/getConfig"

<?xml version="1.0" encoding="utf-8"?>
 <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
 <soap:Body>
  <getConfig xmlns="http://localhost:3624/">
    <id>string</id>
  </getConfig>
 </soap:Body>

The message which my applet does it's this one:

  <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
    <SOAP-ENV:Header/>
      <SOAP-ENV:Body><getConfig xmlns="http://localhost:3624/"><id>1628</id></getConfig>
      </SOAP-ENV:Body>
   </SOAP-ENV:Envelope>

So watching this, how can I solve it?.


Answer:

I had to remove an / from the end of my endpoint. After doing it. It works.

Question:

Im newbie in java. I want make a web application (like a remote controller) for 3rd party server(via xml api).

I think to make a java applet for user gui and a service for parcing xml to (and from) 3rd party server. Whole app will run on separate server with apache.

Is it correct way in general or i need change my concept? And I need advice how to make communication between web user gui (applet) and service, that parcing xml, on same host? Through or make it in one application with different threads?


Answer:

Applet? So 1998.

Web UIs in browser speak HTTP to web services now. Applets are NOT the way to go.

IF you deploy on a Java EE app server or, better yet, Spring Boot, all that threading stuff will be taken care of for you.

It's not for newbies. By all means attempt if you want to learn; get some help if this is real.