Cannot use com.sun.net.httpserver - Java 8 - java

I am trying to create a simple server program to handle http requests. So with minimum search, I stumbled upon the oracle documentation for the httpserver class, inside the com.sun.net package. I'm relatively new to Java, so I thought that a class "sponsored" by Oracle itself would be included in the default libraries.
Unfortunately, that was not the case. After a lot of trials for possible syntax-import errors (various kinds of error arouse) and having installed the Oracle JDK 8 correctly on my Ubuntu machine, the compiler said that the package did not exist. What do I have to do to get the package to work?

I did finally make it work. Mostly, it was a misunderstanding from my place, since I only imported up to a point that was wrong - that is,I only imported com.sun.net.httpserver, thinking the latter part was the actual class I wanted, but it was merely the package name. So then I proceeded to import com.sun.net.httpserver.HttpServer, then the rest of my classes. Finally a com.sun.net.httpserver.* would work perfectly fine. It seems stupid now that I figured it out, but I think I will leave it here just in case anyone has the same misunderstanding - I already see 1 favourite on the question. And of course, as others have pointed out, the package is not part of the standard java libraries, but I used Oracle Java specifically for that.
P.S. The class is really useful, unlike what the other answer implies, but now I have stumbled upon another problem regarding reading the request body right, something that might have to do with the locale of the client-server, and I will now procced to search that.. Just a warning for anyone thinking of using the package.

Firstly try to avoid com.sun.xxx package, as those are internalls of Oracle/Sun java implementation.
Secondly, why not use libraries from apache ? See https://hc.apache.org/
EDITED:
You can also look on http://sparkjava.com/ , not tested but examples looks promising and they are using Java 8 nice features.

Related

Java: Parse JavaScript & Flag Errors

I've been having terrible luck trying to get this to work, so I'm hopeful someone can help here.
In Java, I need to be able to take an HTML page with JavaScript within it and detect any JavaScript errors without, preferably without executing the JavaScript code.
I found this article:
Javascript parser for Java
And I've attempted to figure out how I'm supposed to use Caja to do this, but I'm having a difficult time finding any documentation with working examples of anything close to what I'm doing.
As a result I took a look at Nashorn also referenced in that article. I found a few examples which show how to execute JavaScript code from Java, but this doesn't process the whole HTML page. Even then, the execution doesn't seem to include the ability to validate common JavaScript functions (e.g. It hadn't heard of "alert").
Can anyone recommend something that might be able to do what I want, and point me in the right direction for their documentation or give me an example?
jshint as a standalone product seems to be a good fit for this:
it can run in java inside rhino (see https://github.com/jshint/jshint/)
a nodejs package exists (see https://www.npmjs.com/package/jshint)
it works with nashorn but it's quite tricky
I will only cover the technical difficulties around 3rd solution as I finally managed to make it work too...
Spoiler alert: "alert()" is not detected yet... Solution nb 2 will help there...
You first need to grab this specific release of jshint: https://github.com/jshint/jshint/releases/tag/2.4.4
Anything later than v2.7.0 will fail for now and I personally gave up patching intensively prototypes and namespaces... Releases from v2.4.4 until v2.6.3 work without modification but are limited in functionalities.
In the release notes, it's specifically written that "support for the Nashorn JavaScript engine" is working on this release. I'm using JDK8 nashorn 1.8.0_45 for this test.
Next step is to extract from this release this single file jshint-2.4.4/dist/jshint-rhino.js
Now you need to run nashorn/jjs in scripting mode and you need to be specific about the single file you wish to verify. In solution 2 (nodejs based) you can do multiple files or a complete hierarchy below a folder...
Create a simple file file.js:
function(){}
Now run the following command (please note the presence of -- ):
jjs -scripting jshint-rhino.js -- file.js
This will give you the following output:
Missing name in function declaration. (file.js:1:9)
> function(){}
So this covers the how to run jshint in a simple manner with nashorn... With the 3rd solution, at least you can find missing semicolons and several typical errors. But it's not a silver bullet and to me it's not a real alternative.
My personal preference would be to stick to solution 2 only. If you've the possibility to install either nodejs or iojs on your dev platform, go and grab https://www.npmjs.com/package/jshint. Not only will you be able to do more than the 3rd solution, you'll also be able to configure a jshintrc file as described at http://jshint.com/docs/

Java environment variables, CLASSPATH vs. CLASS_PATH?

Of course the CLASSPATH form (non underscore version) is what people use now.
But I thought it used to also accept CLASS_PATH, maybe way back in the early 2000's?
I've Google'd around but haven't seen this answered. Google has trouble with this type of search, given the abundance of classpath, class and path in relation to Java. There are some older posts showing it as CLASS_PATH, and the one person who actually asked about the two versions didn't get a real answer on that board.
I was also wondering if maybe it was specific to one old JVM variant, or maybe to an early DOS / Windows port?
Obviously not a high priority, but was curious if anybody else remembered this, and whether there was ever any "official" support (or withdrawal) for it.
Thanks, Mark
You got me curious too - I found one reference googling "CLASS_PATH Gosling", the java faq in version 0.9.7. I can faintly remember (or I´m imagining) using it...
http://journals.ecs.soton.ac.uk/java/javafaq.html#xtocid558364
Searching on Google with quotes around CLASS_PATH ("CLASS_PATH") will certainly help your searches for this. That said, I've never seen this - except in some batch files used to start programs which passed this to java's command line argument.

Java type list is ambiguous?

I am a programming enthusiast with a basic programming background, but I'm completely new to the Java programming language.
I want to learn how a simple web crawler is built and I'm using this site to compile the source to see how it works and see it in action!
http://java.sun.com/developer/technicalArticles/ThirdParty/WebCrawler/#demo
The source provided by the website is here:
http://java.sun.com/developer/technicalArticles/ThirdParty/WebCrawler/WebCrawler.java
I am running eclipse 3.2 and using the sun-java-6 JRE to compile applets. I am running on Crunchbang, a Ubuntu distro.
There is some part of the library that I am unfamiliar with and do not know how to fix.
List listmatches;
The error says that "The type List is ambiguous".
I have the package java.utils.*; but the error still persist.
Is there something wrong with my syntax or is there a new syntax for List?
Add import java.awt.List; to your import statements. This should work fine then.
This is mainly because there is a java.util.List and a java.awt.List. Since you are importing both of them using wildcards, the compiler doesn't know which one you actually want to.
The reason that you get the "ambiguous" message is because there is a List class in both "java.awt." and the "java.util." packages that are at the top of the import list.
To solve this issue you should pick one of them that most likely is being used in the application (I would guess java.awt.List.
In eclipse if you do a "CTRL + SHIFT + o" (that's an o not a zero), it will refactor your imports. From there you can select the java.awt.List.
To avoid such ambiguous message, we have to import either "java.util.List" or "java.awt.List" specifically based on your need. If you use both, then the confusion may arise such problem.
To see example program using this, please visit http://www.cjavaprogramsprojects.com/java-final-year-mini-project-file-loader

Is there any program like LINQPad for Java?

I've found LINQPad to be extremely useful when answering StackOverflow questions for C# or VB.NET. It allows me to write up some quick code, run it, and (if I want) see a nicely-formatted dump of the results. That way I can be sure that the code I post actually runs. Thus far I haven't seen anything that I can use to achieve the same result with Java. Is there anything like that out there?
I am not looking for something to query data sources; I just want a light-weight IDE. These are the features I'm particularly interested in:
The ability to write and run short snippets of code without establishing a whole project or file structure.
Reporting of compiler and runtime errors in the code when it is run.
The ability to add references to a particular editor instance.
Syntax highlighting and Autocomplete/Intellisense would be a plus.
JPad - A java scratchpad for running snippets
Since I also couldn't find one I've decided to write one. Currently it can:
Run java snippets (no class / imports / public blah... needed).
Contains drivers for MS/MySQL/Postgres.
Output results as HTML tables
It's very rough but I will add to it over time. Feedback is definitely welcome.
This may help : http://www.browxy.com:9000/codeRunner
EDIT: Url seems to have changed to http://www.browxy.com
You can use the Groovy web console ; it's possible to speak java in groovy land.
Java Snippet Runner:
Does something similar to Linqpad (jar file, not just for macs)
http://mac.softpedia.com/get/Development/Java/Java-Snippet-Runner.shtml
Code Runner (Commercial):
for Mac's only, it'll run code snippets in Java, and lots of other languages too (e.g. Objective C)
http://krillapps.com/coderunner/
http://ideone.com is an online service that has the features you want.
I've been using JEdit for a long time, which is a very powerful cross-platform editor, NOT an IDE. It does have plugins to execute Java code right in the editor, and even uses BSH for macros.
I was looking for a "Java LinqPad" also, and i came across :
this
I've been using IntelliJ IDEA and it works really well as a Groovy scratchpad. The Community Edition is free too.
You need to create a new project, but then can add Groovy scripts to it and run them on the fly. Not had any luck with the actual Scratch File functionality though.
Being a Jetbrains editor it's pretty slick too. (Unlike some of the other options)
Nothing beats LinqPad though.

Sun Java HTTPServer has a bug, how to fix it?

I'm using com.sun.net.httpserver.HttpServer in my project. However, it seems that the server leaks connections when it gets invalid data from the HTTP connection. The bug is this one:
http://bugs.sun.com/view_bug.do;jsessionid=dfe841c3152d878571573bafceb8?bug_id=6946825
Now, this is reported to be fixed in version "7(b94)" - however, we are still using Java 1.6 and it is unlikely that we would want switch Java versions at this point.
So, I am looking for ways to fix this situation. I don't have a lot of time, so I'd prefer quick solutions that work for now, over reimplementing a lot of things for later.
I have a few ideas on how to go about this:
Update to a more recent Java - this is something I don't want to do.
Find a jar which only contains a more recent version of com.sun.net.httpserver and make sure that jar loads before the system jars.
Find a drop-in replacement for com.sun.net.httpserver - I'm open to pointers here.
Modify code to work with another embedded HTTP server, hopefully one that isn't too different from the current one. I can rewrite the server setup code, somewhat, but most of the interfaces should stay the same.
Decompile the com.sun.net.httpserver.ServerImpl class, fix the offending places, and recompile that single class to a jar of it's own
But, I'm open to good suggestions!
Thank you in advance.
Fix is now implemented and works. I will paste here the relevant bits if anyone else needs these:
final Field httpserverimpl_server = Class.forName("sun.net.httpserver.HttpServerImpl").getDeclaredField("server");
final Field httpsserverimpl_server = Class.forName("sun.net.httpserver.HttpsServerImpl").getDeclaredField("server");
final Field serverimpl_allconnections = Class.forName("sun.net.httpserver.ServerImpl").getDeclaredField("allConnections");
final Field httpconnection_closed = Class.forName("sun.net.httpserver.HttpConnection").getDeclaredField("closed");
httpserverimpl_server.setAccessible(true);
httpsserverimpl_server.setAccessible(true);
serverimpl_allconnections.setAccessible(true);
httpconnection_closed.setAccessible(true);
Object serverimpl = httpserverimpl_server.get(server);
Set allconnections = (Set)serverimpl_allconnections.get(serverimpl);
LinkedList<Object> toRemove = new LinkedList<Object>();
for (Object conn : allconnections) {
if (httpconnection_closed.getBoolean(conn)) {
toRemove.add(conn);
}
}
for (Object conn : toRemove) {
allconnections.remove(conn);
}
Could you put a reverse proxy infront of the HTTP server, to make sure you only allow known good requests to come through? Varnish or Squid or Apache?
Or knock something up in Jetty so that it acts as a reverse proxy?
Another approach would be to grab the source code of the fixed version, rename the class and package so that it fits into your project, make the class public, and then use that implementation instead.
I can understand your reluctance to upgrade to a pre-release build of Java 7.
Here are my suggestions:
Get a Java support contract from Oracle and get them to provide you with a patch for Java 6 that fixes the bug.
Download the Java 6 sources for the release you are currently using, backport the bug fix from the Java 7 sources and build. Maybe you only need to do a build of certain JAR files.
Look at the code and see if you could develop a workaround. For example, you might be able to use reflection to dig out the "list of HttpConnection instances" that the bug report talks about, and periodically remove entries that look like they are dead. (I'd treat this as a last resort.)
(Updated: 2012-05-15)
And, now that Java 7 is well and truly released (we are now at 1.7u4):
upgrade to Java 7, and
get rid of the nasty reflective hacks that you used as a TEMPORARY workaround.
Do you have access to 7(b94)? Then you can compare the sources and see whether you can fix it by overriding or providing different accessors.

Categories