Env for project: -
Eclipse 3.6 (Eclipse-jee-helios) + HTML5 + JavaScript + Websocket + (grizzly) Glassfish 3.1.1
I have deployed sample project and able to run using GF.
When i try to connect websocket it always call onClose.
I tried: -
asadmin set configs.config.server-config.network-config.protocols.protocol.http-listener-1.http.websockets-support-enabled=true
GF 3.1.1 supports web socket (Downloaded from http://glassfish.java.net/downloads/3.1.1-final.html)
Browser like safari and Google Chrome supports websocket (i am using latest browser and checked with http://websocket.org/echo.html URL)
Java Script:-
var webSocket;
$(document).ready(
function() {
**var URL = "ws://localhost:8080/SampleGF/WebSocketChatServlet";**
//Tried using and lot of combination of URLS
var URL = "ws://localhost:8080/";
var URL = "ws://localhost:8080/SampleGF";
var URL = "ws://localhost:8080/SampleGF/WebSocketChatServlet";
webSocket = new WebSocket(URL);
//alert("WebSockets are " + (window.WebSocket ? "" : "not ") + "supported");
webSocket.onopen = function(event) {
alert("OPEN")
}
webSocket.onmessage = function(event) {
var $textarea = $('#messages');
$textarea.val($textarea.val() + event.data + "\n");
$textarea.animate({
scrollTop : $textarea.height()
}, 1000);
}
webSocket.onclose = function(event) {
alert("CLOSE")
}
});
function sendMessage() {
var message = $('#username').val() + ":" + $('#message').val();
webSocket.send(message);
$('#message').val('');
}
i have used ChatSocket.java, WebSocketChatServlet.java, ChatApplication.java as it is from below link: -
http://java.dzone.com/articles/creating-websocket-chat
i have added servlet-api.jar in my project library.
Ref. Link: - http://tech.amikelive.com/node-269/eclipse-quick-tip-resolving-error-the-import-javaxservlet-cannot-be-resolved/
Web.xml: -
I have added servlet and servlet-mapping as below:
servlet
description WebSocketChatServlet description
servlet-name WebSocketChatServlet servlet-name
servlet-class org.trivadis.websocket.servlet.WebSocketChatServlet servlet-class
servlet
servlet-mapping
servlet-name WebSocketChatServlet servlet-name
url-pattern /WebSocketChatServlet url-pattern
servlet-mapping
I am not sure what i am doing wrong....
How can i check URL i am using is correct or not for websocket.
GF location is D:\glassfish3\glassfish for my project.
Project location D:\workspace\SampleGF
Another reason: -
Even I tried WAR sample from below link: -
http://jarvana.com/jarvana/search?search_type=project&project=grizzly-websockets-chat
WAR File Name: -grizzly-websockets-chat-1.9.45.war
I have imported above war file in Eclipse and deployed it on glassfish 3.1.1 server. After running it application always call onclose event.
I have executed below command: -
asadmin set configs.config.server-config.network-config.protocols.protocol.http-listener-1.http.websockets-support-enabled=true
and I am using browser like safari and Google Chrome supports websocket (i have tested it with below link http://websocket.org/echo.html URL)
Can anyone help me out…..
It's been months since I tried to run published sample-code against grizzly. I may be out of date, but it didn't work when I tried it. The guy who published the sample eventually admitted problems in the discussion posts below his article. Since I haven't tried it since, I don't know whether it's been fixed yet; i.e. I don't have confirmation that grizzly works yet. (If someone knows of a working sample, I'm as interested as you are.)
In the mean time, you can try this alternative for running your client code. You can even check what you're doing against the free downloadable JavaScript code if you wish.
http://highlevellogic.blogspot.com/2011/09/websocket-server-demonstration_26.html
If you get your code to work against this server, then try again with grizzly. I'll be interested in the results.
Related
I have a Spring Boot project, built using Maven, where I intend to use embedded mongo db. I am using Eclipse on Windows 7.
I am behind a proxy that uses automatic configuration script, as I have observed in the Connection tab of Internet Options.
I am getting the following exception when I try to run the application.
java.io.IOException: Could not open inputStream for https://downloads.mongodb.org/win32/mongodb-win32-i386-3.2.2.zip
at de.flapdoodle.embed.process.store.Downloader.downloadInputStream(Downloader.java:131) ~[de.flapdoodle.embed.process-2.0.1.jar:na]
at de.flapdoodle.embed.process.store.Downloader.download(Downloader.java:69) ~[de.flapdoodle.embed.process-2.0.1.jar:na]
....
MongoDB gets downloaded just fine, when I hit the following URL in my web browser:
https://downloads.mongodb.org/win32/mongodb-win32-i386-3.2.2.zip
This leads me to believe that probably I'm missing some configuration in my Eclipse or may be the maven project itself.
Please help me to find the right configuration.
What worked for me on a windows machine:
Download the zip file (https://downloads.mongodb.org/win32/mongodb-win32-i386-3.2.2.zip)
manually and put it (not unpack) into this folder:
C:\Users\<Username>\.embedmongo\win32\
Indeed the problem is about your proxy (a corporate one I guess).
If the proxy do not require authentication, you can solve your problem easily just by adding the appropriate -Dhttp.proxyHost=... and -Dhttp.proxyPort=... (or/and the same with "https.[...]") as JVM arguments in your eclipse junit Runner, as suggested here : https://github.com/learning-spring-boot/learning-spring-boot-2nd-edition-code/issues/2
One solution to your problem is to do the following.
Download MongoDB and place it on a ftp server which is inside your corporate network (for which you would not need proxy).
Then write a configuration in your project like this
#Bean
#ConditionalOnProperty("mongo.proxy")
public IRuntimeConfig embeddedMongoRuntimeConfig() {
final Command command = Command.MongoD;
final IRuntimeConfig runtimeConfig = new RuntimeConfigBuilder()
.defaults(command)
.artifactStore(new ExtractedArtifactStoreBuilder()
.defaults(command)
.download(new DownloadConfigBuilder()
.defaultsForCommand(command)
.downloadPath("your-ftp-path")
.build())
.build())
.build();
return runtimeConfig;
}
With the property mongo.proxy you can control whether Spring Boot downloads MongoDB from your ftp server or from outside. If it is set to true then it downloads from the ftp server. If not then it tries to download from the internet.
The easiest way seems to me to customize the default configuration:
#Bean
DownloadConfigBuilderCustomizer mongoProxyCustomizer() {
return configBuilder -> {
configBuilder.proxyFactory(new HttpProxyFactory(host, port));
};
}
Got the same issue (with Spring Boot 2.6.1 the spring.mongodb.embedded.version property is mandatory).
To configure the proxy, I've added the configuration bean by myself:
#Value("${spring.mongodb.embedded.proxy.domain}")
private String proxyDomain;
#Value("${spring.mongodb.embedded.proxy.port}")
private Integer proxyPort;
#Bean
RuntimeConfig embeddedMongoRuntimeConfig(ObjectProvider<DownloadConfigBuilderCustomizer> downloadConfigBuilderCustomizers) {
Logger logger = LoggerFactory.getLogger(this.getClass().getPackage().getName() + ".EmbeddedMongo");
ProcessOutput processOutput = new ProcessOutput(Processors.logTo(logger, Slf4jLevel.INFO), Processors.logTo(logger, Slf4jLevel.ERROR), Processors.named("[console>]", Processors.logTo(logger, Slf4jLevel.DEBUG)));
return Defaults.runtimeConfigFor(Command.MongoD, logger).processOutput(processOutput).artifactStore(this.getArtifactStore(logger, downloadConfigBuilderCustomizers.orderedStream())).isDaemonProcess(false).build();
}
private ExtractedArtifactStore getArtifactStore(Logger logger, Stream<DownloadConfigBuilderCustomizer> downloadConfigBuilderCustomizers) {
de.flapdoodle.embed.process.config.store.ImmutableDownloadConfig.Builder downloadConfigBuilder = Defaults.downloadConfigFor(Command.MongoD);
downloadConfigBuilder.progressListener(new Slf4jProgressListener(logger));
downloadConfigBuilderCustomizers.forEach((customizer) -> {
customizer.customize(downloadConfigBuilder);
});
DownloadConfig downloadConfig = downloadConfigBuilder
.proxyFactory(new HttpProxyFactory(proxyDomain, proxyPort)) // <--- HERE
.build();
return Defaults.extractedArtifactStoreFor(Command.MongoD).withDownloadConfig(downloadConfig);
}
In my case, I had to add the HTTPS corporate proxy to Intellij Run Configuration.
Https because it was trying to download:
https://downloads.mongodb.org/win32/mongodb-win32-x86_64-4.0.2.zip
application.properties:
spring.data.mongodb.database=test
spring.data.mongodb.port=27017
spring.mongodb.embedded.version=4.0.2
Please keep in mind this is a (DEV) setup.
I want to test my Rest Application that uses SpringBoot to test with Arquillian but none of the online examples work i am not able to test a GET call and facing difficulties deploying to Jboss EAP-6.4. Can anyone guide me on how to achieve this. Any simple Examples ???
I think that here there are a lot of things to check, so I would say 1) have you tried to deploy the spring boot app to EAP 6.4 to check that it works (not using Arquillian)? and 2) is it possible to share a simple github project so we can check?
This link helped me to solve the issue : Adding all Maven dependencies to Arquillian.
The code that works :
#Deployment
public static Archive<?> createTestArchive() {
File[] files = Maven.resolver()
.loadPomFromFile("pom.xml")
.importRuntimeDependencies()
.resolve().withTransitivity()
.asFile();
return ShrinkWrap.create(WebArchive.class, "FileUploadIssue.war")
.addPackages(true,"com.example")
.addAsLibraries(files);
}
#Test
#RunAsClient
public void shouldGetFileContents() {
String result = restTemplate.getForObject(contextPath + "upload/sayhello", String.class);
System.out.println( "Test : " + result);
}
Is there any way to refactor this code even more ??
I am building a rest API with Web API2, Owin 3 and NInject Owinhost for my DI.
Using the example provided by NInject, by which I create an "HttpConfiguration" object and call the NInject extension methods in startup.cs, I get an error:
Error activating HttpConfiguration
More than one matching bindings are available.
Matching bindings:
1) binding from HttpConfiguration to method
2) self-binding of HttpConfiguration
3) binding from HttpConfiguration to constant value
Activation path:
1) Request for HttpConfiguration
Suggestions:
1) Ensure that you have defined a binding for HttpConfiguration only once.
My code is as follow in Startup.cs:
public void Configuration(IAppBuilder app)
{
Logger.Info("Entering Startup");
config = new HttpConfiguration();
ConfigureOAuth(app);
// Web API configuration and services
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter("Bearer"));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new {id = RouteParameter.Optional}
);
var appXmlType =
config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(
t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
app.UseNinjectMiddleware(CreateKernel);
app.UseNinjectWebApi(config);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
Logger.Info("Exiting Startup");
}
public static StandardKernel CreateKernel()
{
kernel = new StandardKernel();
kernel.Load(Assembly.GetExecutingAssembly());
kernel.Bind<HttpConfiguration>().ToSelf().Named("TestHttpConfiguration");
return kernel;
}
The strange thing is when I refresh the page in the browser, the error goes, which leads me to believe that this happens at application startup only.
So I'm confused with this. Has anyone faced the same issue with it?
Thanks
Vincent
I had this same error, as for some reason I had installed both Ninject.Web.WebApi.WebHost and Ninject.Web.WebApi.OwinHost.
If you look in source for OwinWebApiModule.cs and WebApiWebHostModule.cs, both Ninject modules have a binding for HttpConfiguration.
I removed the one I didn't need and things worked.
UPDATE
After trying everything, I managed to get it to work by... Starting a new project from scratch. I had the luxury of doing this because it is a new proof of concept for me.
The main difference here is I installed the packages required (owin 3, ninject) using the Package Manager console rather than the UI. I followed this link here to install those packages.
I then noticed an error message on one of the package as it was looking for Owin 2 dependencies and could not find any. I forced it to install using -DependencyVersion Highest as parameter and it was working fine from the outset.
Unless I missed it I didn't see this error when I installed the packages using the UI. Is it possible the package didn't install properly previously on my other project? Not sure.
Hope this helps someone.
When using the SC.get() function of the Soundcloud API instead of a result I receive a "HTTP Error: 0". The same codes is working under Android and in the browser (with same origin policy disabled).
This is the part of the code:
SC.initialize({client_id : "[myclientID]" ,redirect_uri:"[myURI]"});
SC.get('/resolve', {url : '[myURL]'}, function(track, error) {
if (error) alert('Error: ' + error.message);
trackImg[l] = track.artwork_url;
trackID[l] = track.id;
...
});
The URLs are white-listed as external hosts within the projects .plist and the Cordova.plist (the project is still running under phonegap 1.7.0). There is no warning in the Xcode console about blocked URLs..
Strangely enough the app was working fine a couple of weeks ago. The only thing I found changed was that the callback.html for the redirect URI got deleted but I created a new one.
Heroku recently began supporting Java apps. Looking through the docs, it seems to resemble the Java Servlet Standard. Does anyone know of an instance where a GWT app has been successfully deployed on Heroku? If so, are there any limitations?
Yes, I've got a successful deployment using the getting started with Java instructions here:
http://devcenter.heroku.com/articles/java
I use the Maven project with appassembler plugin approach but added gwt-maven-plugin to compile a GWT app during the build.
When you push to heroku you see the GWT compile process running, on one thread only so quite slow but it works fine.
The embedded Jetty instance is configured to serve up static resources at /static from src/main/resources/static and I copy the compiled GWT app to this location during the build and then reference the .nocache.js as normal.
What else do you want to know?
You've got a choice, either build the Javascript representation of your GWT app locally into your Maven project, commit it and the read it from your app, or to generate it inside Heroku via the gwt-maven-plugin as I mentioned.
The code to serve up files from a static location inside your jar via embedded Jetty is something like this inside a Guice ServletModule:
(See my other answer below for a simpler and less Guice-driven way to do this.)
protected void configureServlets() {
bind(DefaultServlet.class).in(Singleton.class);
Map<String, String> initParams = new HashMap<String, String>();
initParams.put("pathInfoOnly", "true");
initParams.put("resourceBase", staticResourceBase());
serve("/static/*").with(DefaultServlet.class, initParams);
}
private String staticResourceBase() {
try {
return WebServletModule.class.getResource("/static").toURI().toString();
}
catch (URISyntaxException e) {
e.printStackTrace();
return "couldn't resolve real path to static/";
}
}
There's a few other tricks to getting embedded Jetty working with guice-servlet, let me know if this isn't enough.
My first answer to this turned out to have problems when GWT tried to read its serialization policy. In the end I went for a simpler approach that was less Guice-based. I had to step through the Jetty code to understand why setBaseResource() was the way to go - it's not immediately obvious from the Javadoc.
Here's my server class - the one with the main() method that you point Heroku at via your app-assembler plugin as per the Heroku docs.
public class MyServer {
public static void main(String[] args) throws Exception {
if (args.length > 0) {
new MyServer().start(Integer.valueOf(args[0]));
}
else {
new MyServer().start(Integer.valueOf(System.getenv("PORT")));
}
}
public void start(int port) throws Exception {
Server server = new Server(port);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setBaseResource(createResourceForStatics());
context.setContextPath("/");
context.addEventListener(new AppConfig());
context.addFilter(GuiceFilter.class, "/*", null);
context.addServlet(DefaultServlet.class, "/");
server.setHandler(context);
server.start();
server.join();
}
private Resource createResourceForStatics() throws MalformedURLException, IOException {
String staticDir = getClass().getClassLoader().getResource("static/").toExternalForm();
Resource staticResource = Resource.newResource(staticDir);
return staticResource;
}
}
AppConfig.java is a GuiceServletContextListener.
You then put your static resources under src/main/resources/static/.
In theory, one should be able to run GWT using the embedded versions of Jetty or Tomcat, and bootstrap the server in main as described in the Heroku Java docs.