WebSocket through Apache and Tomcat 500 Error : java.lang.UnsupportedOperationException: HTTP upgrade is not supported by this protocol

I was implementing Web Socket using JavaScript on the client and Java/Tomcat on the server. It works very fine on localhost but when I deploy on my remote host it fails. Checking the console, I get 500 error on the Web socket request. Hence i check the server error log to view the error and find -

I was implementing Web Socket using JavaScript on the client and Java/Tomcat on the server. It works very fine on localhost but when I deploy on my remote host it fails. Checking the console, I get 500 error on the Web socket request. Hence i check the server error log to view the error and find -

java.lang.UnsupportedOperationException: HTTP upgrade is not supported by this protocol
    at org.apache.coyote.AbstractProcessor.doHttpUpgrade(AbstractProcessor.java:712) ~[tomcat-coyote.jar:8.5.20]
    at org.apache.coyote.AbstractProcessor.action(AbstractProcessor.java:478) ~[tomcat-coyote.jar:8.5.20]
    at org.apache.coyote.Request.action(Request.java:433) ~[tomcat-coyote.jar:8.5.20]
    at org.apache.catalina.connector.Request.upgrade(Request.java:2022) ~[catalina.jar:8.5.20]
    at org.apache.catalina.connector.RequestFacade.upgrade(RequestFacade.java:1115) ~[catalina.jar:8.5.20]
    at org.apache.tomcat.websocket.server.UpgradeUtil.doUpgrade(UpgradeUtil.java:234) ~[tomcat-websocket-8.5.20.jar:8.5.20]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:77) ~[tomcat-websocket-8.5.20.jar:8.5.20]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[catalina.jar:8.5.20]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[catalina.jar:8.5.20]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) [catalina.jar:8.5.20]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [catalina.jar:8.5.20]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478) [catalina.jar:8.5.20]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [catalina.jar:8.5.20]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80) [catalina.jar:8.5.20]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [catalina.jar:8.5.20]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [catalina.jar:8.5.20]
    at org.apache.coyote.ajp.AjpProcessor.service(AjpProcessor.java:486) [tomcat-coyote.jar:8.5.20]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-coyote.jar:8.5.20]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) [tomcat-coyote.jar:8.5.20]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1457) [tomcat-coyote.jar:8.5.20]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-coyote.jar:8.5.20]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [?:1.8.0_11]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [?:1.8.0_11]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-util.jar:8.5.20]
    at java.lang.Thread.run(Thread.java:745) [?:1.8.0_11]

I did some research and stumbled on someone who had a similar problem and asked in this question WebSockets through Apache and Tomcat: HTTP upgrade is not supported by the AJP protocol but am running a private tomcat instance on a shared hosting server so the solutions provided in that answer cannot be achieved by me hence i contact my host and they respond with

'While investigating your query, we could see that making changes in the tomcat and HTTP settings as per the steps mentioned in your email will affect the AJP connection configuration of another shared tomcat instance and the applications hosted by the shared tomcat instance will not work. For re-compiling, the connector settings also need a server-wide update and this cannot be done in a shared server environment. We request you to try our VPS plans by visiting the below link.'

I think purchasing a vps plan should be a last resort. Is there anyone here with a more conducive solution to the problem.

Java vs JavaScript: Difference between Java and JavaScript

Java vs JavaScript: Difference between Java and JavaScript

The video on Java vs JavaScript provides you with a short and crisp description of the two programming languages. You will also see the head to head comparison between the two on various aspects and learn the similarities and differences between them.

Java vs JavaScript: Difference between Java and JavaScript 

The video on Java vs JavaScript provides you with a short and crisp description of the two programming languages. You will also see the head to head comparison between the two on various aspects and learn the similarities and differences between them.

Thanks for reading

If you liked this post, please do share/like it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

The Complete JavaScript Course 2019: Build Real Projects!

Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)

JavaScript Bootcamp - Build Real World Applications

The Web Developer Bootcamp

JavaScript Programming Tutorial - Full JavaScript Course for Beginners

New ES2019 Features Every JavaScript Developer Should Know

Best JavaScript Frameworks, Libraries and Tools to Use in 2019

Java Programming Masterclass for Software Developers

Selenium WebDriver with Java -Basics to Advanced+Frameworks

Java In-Depth: Become a Complete Java Engineer!

Top 4 Spring Annotations for Java Developer in 2019

Java Tutorial for Absolute Beginners

100+ Java Interview Questions and Answers In 2019

JavaScript != Java

Lately I've been doing a lot of work with Java and JavaScript through JavaScript Engine and every time I come to a question about the two someone feels the need to answer the question with,&nbsp;<em>"Java and JavaScript are two different languages. They have nothing in common!"</em>&nbsp;or&nbsp;<em>"Just because the word Java is in JavaScript doesn't mean its Java"</em>&nbsp;or&nbsp;<em>"Java != JavaScript"</em>.

Lately I've been doing a lot of work with Java and JavaScript through JavaScript Engine and every time I come to a question about the two someone feels the need to answer the question with, "Java and JavaScript are two different languages. They have nothing in common!" or "Just because the word Java is in JavaScript doesn't mean its Java" or "Java != JavaScript".

Well OK... That doesn't answer the question and it is so irrelevant because you can obviously use Java inside of JavaScript and you can use JavaScript inside of Java so just because someone is asking a question about the two doesn't mean they think they're are the same language.

So my question is how come so many people seem to get worked up over the fact someone is trying to use Java and JavaScript together and will dismiss the question with their condescending phrases instead of offering a solution?

Here is an example,

var SwingGui = JavaImporter(Packages.javax.swing,
                    Packages.javax.swing.event,
                    Packages.javax.swing.border,
                    java.awt.event,
                    java.awt.Point,
                    java.awt.Rectangle,
                    java.awt.Dimension);
...

with (SwingGui) {
var mybutton = new JButton(test);
var mypoint = new Point(10, 10);
var myframe = new JFrame();
...
}

sources:

https://developer.mozilla.org/en-US/docs/Mozilla/Projects/Rhino/Scripting_Java

http://docs.oracle.com/javase/7/docs/technotes/guides/scripting/programmer_guide/

http://www.oracle.com/technetwork/articles/javase/scripting-140262.html

How to Use TensorFlow Using Java/JavaScript

How to Use TensorFlow Using Java/JavaScript

This article will help get experienced Java/JavaScript developers use machine learning/deep learning in the TensorFlow ecosystem without any prior knowledge of Python.

Background

Nowadays, there is a great market for machine learning and deep learning enthusiasts, as it is a niche technology, but it also requires different programming skillset.

There are plenty of tools and libraries available for this like Numpy, Keras, and TensorFlow, but most of them play around R, MATLAB, and, of course, Python.

So, now the problem is reskilling the existing programmer community, which is typically trained on languages like C, C++, and Java.


You might also enjoy: Machine Learning In Node.js With TensorFlow.js


Solution

There is lots of misconception that TensorFlow is made only for Python and its allies. Don't worry, if you are an experienced Java/JS programmer and want to get your hands dirty with ML/DL, you still can!

The solution is TensorFlow for Java and TensorFlow.js.

Learn by Example

Java

To start with Java, you need to first to set up a Maven project and add the following dependency to your pom.xml.

<dependency>
	<groupId>org.tensorflow</groupId>
	<artifactId>tensorflow</artifactId>
	<version>1.7.0</version>
</dependency>

This is an enumeration of two libraries:

  • libtensorflow
  • libtensorflow_jni

This wraps the TensorFlow C++ library and JNI connector to access it through Java programs.

Additionally, you can add the following dependency to support GPU acceleration. By default, it works on CPU powers.

<dependency>
	<groupId>org.tensorflow</groupId>
	<artifactId>libtensorflow_jni_gpu</artifactId>
	<version>1.7.0</version>
</dependency>

Now, you are all set to use TensorFlow features on Java. You can use following test program to check the environment.

import org.tensorflow.Graph;
import org.tensorflow.Session;
import org.tensorflow.Tensor;
import org.tensorflow.TensorFlow;

public class HelloTF {
  public static void main(String[] args) throws Exception {
    try (Graph g = new Graph()) {
      final String value = "Hello from " + TensorFlow.version();

      // Construct the computation graph with a single operation, a constant
      // named "MyConst" with a value "value".
      try (Tensor t = Tensor.create(value.getBytes("UTF-8"))) {
        // The Java API doesn't yet include convenience functions for adding operations.
        g.opBuilder("Const", "MyConst").setAttr("dtype", t.dataType()).setAttr("value", t).build();
      }

      // Execute the "MyConst" operation in a Session.
      try (Session s = new Session(g);
           Tensor output = s.runner().fetch("MyConst").run().get(0)) {
        System.out.println(new String(output.bytesValue(), "UTF-8"));
      }
    }
  }
}

This is basically creating an operation graph with a const and assigning a value as the current version. For fetching it, you need to run it inside a session.

JavaScript

To start with JavaScript, you just need a single package available through CDN. It's available through an NPN package, as well, but it is easier to use CDN for working with a browser.

Add the below script tag to your HTML file.

<script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]"> </script>

That's it. Now, you can test TensorFlow features like training, re-training, and converting existing models into JavaScript-compatible models right into your browser.

To test, you can use following code.

// Define a model for linear regression.
    const model = tf.sequential();
    model.add(tf.layers.dense({units: 1, inputShape: [1]}));

    // Prepare the model for training: Specify the loss and the optimizer.
    model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});

    // Generate some synthetic data for training.
    const xs = tf.tensor2d([1, 2, 3, 4], [4, 1]);
    const ys = tf.tensor2d([1, 3, 5, 7], [4, 1]);

    // Train the model using the data.
    model.fit(xs, ys).then(() => {
        // Use the model to do inference on a data point the model hasn't seen before:
        result = model.predict(tf.tensor2d([5], [1, 1]));
    });

This is a basic linear regression model trained with mean square error and gradient descent.

You can have a look at a complete example on GitHub.

Originally published by Vinod Pahuja at dzone.com