This is my code,
package com.mywicketapp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormSubmitBehavior;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.model.Model;
import org.apache.wicket.util.string.Strings;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.extensions.ajax.markup
.html.autocomplete.AutoCompleteTextField;
public class HomePage extends WebPage
{
public HomePage()
{
Form form = new Form("form");
add(form);
final AutoCompleteTextField field =
new AutoCompleteTextField("auto", new Model(""))
{
protected Iterator getChoices(String input)
{
if (Strings.isEmpty(input))
{
return Collections.EMPTY_LIST.iterator();
}
List choices = new ArrayList(10);
Locale[] locales = Locale.getAvailableLocales();
for (int i = 0; i < locales.length; i++)
{
final Locale locale = locales[i];
final String country = locale.getDisplayCountry();
if (country.toUpperCase().startsWith(input.toUpperCase()))
{
choices.add(country);
if (choices.size() == 10)
{
break;
}
}
}
return choices.iterator();
}
};
form.add(field);
final Label label = new
Label("selectedValue", field.getModel());
label.setOutputMarkupId(true);
form.add(label);
field.add(new AjaxFormSubmitBehavior(form, "onchange")
{
protected void onSubmit(AjaxRequestTarget target)
{
target.addComponent(label);
}
#Override
protected void onError(AjaxRequestTarget target)
{
}
});
}
}
This is my application code:
package com.mywicketapp;
import org.apache.wicket.protocol.http.WebApplication;
/**
* Application object for your web application. If you want to run this application without deploying, run the Start class.
*
* #see com.mywicketapp.Start#main(String[])
*/
public class WicketApplication extends WebApplication
{
/**
* Constructor
*/
public WicketApplication()
{
}
/**
* #see org.apache.wicket.Application#getHomePage()
*/
public Class<HomePage> getHomePage(){
return HomePage.class;
}
}
Some html:
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
The textfield below will autocomplete country names
<br><hr>
<form wicket:id="form">
Selected value is: <span wicket:id="selectedValue"></span>
<br/>
Country: <input type="text" wicket:id="auto" size="20"/>
</form>
</body>
</html>
And the error:
- log - Logging to org.slf4j.impl.Log4jLoggerAdapter(org.mortbay.log) via org.mortbay.log.Slf4jLog
>>> STARTING EMBEDDED JETTY SERVER, PRESS ANY KEY TO STOP
INFO - log - jetty-6.1.25
INFO - log - NO JSP Support for /, did not find org.apache.jasper.servlet.JspServlet
WARN - log - failed wicket.mywicketapp: java.lang.ClassCastException: wicket.extensions.Initializer cannot be cast to org.apache.wicket.IInitializer
ERROR - log - Failed startup of context org.mortbay.jetty.webapp.WebAppContext#66e7b3f2{/,src/main/webapp}
java.lang.ClassCastException: wicket.extensions.Initializer cannot be cast to org.apache.wicket.IInitializer
at org.apache.wicket.Application.addInitializer(Application.java:864)
at org.apache.wicket.Application.load(Application.java:938)
at org.apache.wicket.Application.initializeComponents(Application.java:715)
at org.apache.wicket.protocol.http.WicketFilter.init(WicketFilter.java:732)
at org.mortbay.jetty.servlet.FilterHolder.doStart(FilterHolder.java:97)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at org.mortbay.jetty.servlet.ServletHandler.initialize(ServletHandler.java:662)
at org.mortbay.jetty.servlet.Context.startContext(Context.java:140)
at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1272)
at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:517)
at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:489)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130)
at org.mortbay.jetty.Server.doStart(Server.java:224)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at com.mywicketapp.Start.main(Start.java:43)
INFO - log - Started SelectChannelConnector#0.0.0.0:8080
Looks to me like you have a version incompatibility problem... Check to make sure that the version of wicket-extensions that you're using is compatible with your wicket version. The wicket.extensions.Initializer that's getting loaded and causing the exception is surely getting loaded up by your AutoCompleteTextField.
Related
I am having this little problem, I see that it is impossible to load picture in my console, I don't know how to solve the problem.
I am getting my image name from database as a String in my controller, just the name, something like that ' image.jpg' and it is stored in my folder 'images'.
Here is my jsp file :
<c:if test="${ !(post.cover == 'empty')}">
<div class="imgPub">
<img src="Assets/images/${post.cover }">
</div>
</c:if>
In my inspector i can see the whole src written exactly, but a message next to it saying impossible to load image.
Any help would be much appreciated.
HttpServlet will do the job.
use:
youraddress.xxx/images/filename.png
this is important #WebServlet("/images/*")
It will automatically leads to folder defined in PATH and retrieve the image based on the name.
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 java.io.File;
import java.io.IOException;
import java.nio.file.Files;
#WebServlet("/images/*")
public class ImageServlet extends HttpServlet {
public static final String PATH = "C:/"
/*
linux
public static final String PATH = "/home/images/"
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String filename = request.getPathInfo().substring(1);
File file = new File(PATH,filename);
response.setHeader("Content-Type", getServletContext().getMimeType(filename));
response.setHeader("Content-Length",String.valueOf(file.length()));
response.setHeader("Content-Disposition","inline; filename=\""+filename +"\"");
Files.copy(file.toPath(),response.getOutputStream());
}
}
I must to test this web app, but when I try to deploy on JBoss 7 EAP this is the error, maybe I forgot something?
This is the exception that the application throws:
Cannot upload deployment: {"WFLYCTL0080: Failed services" => {"jboss.deployment.unit.\"WebAppGuestbooks.war\".INSTALL" =>
"org.jboss.msc.service.StartException in service jboss.deployment.unit.\"WebAppGuestbooks.war\".INSTALL: WFLYSRV0153:
Failed to process phase INSTALL of deployment \"WebAppGuestbooks.war\" Caused by:
org.jboss.as.server.deployment.DeploymentUnitProcessingException: WFLYEE0041: Component class it.matteo.nesea.ejb.GuestDao for
component GuestDao has errors:
WFLYJPA0033: Can't find a persistence unit named null in deployment
\"WebAppGuestbooks.war\""},"WFLYCTL0180: Services with missing/unavailable dependencies" =>
["jboss.deployment.unit.\"WebAppGuestbooks.war\".weld.weldClassIntrospector is missing
[jboss.deployment.unit.\"WebAppGuestbooks.war\".beanmanager]","jboss.deployment.unit.\"WebAppGuestbooks.war\".batch.environment
is missing [jboss.deployment.unit.\"WebAppGuestbooks.war\".beanmanager]"]}
This is my persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="GuestbookPU" transaction-type="JTA">
<class>it.matteo.nesea.dao.jpa</class>
<properties>
<property name="javax.persistence.jdbc.url" value="$objectdb/db/guests.odb"/>
<property name="javax.persistence.jdbc.user" value="admin"/>
<property name="javax.persistence.jdbc.password" value="admin"/>
</properties>
</persistence-unit>
</persistence>
this is the Ejb GuestDAO:
package it.matteo.nesea.ejb;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import it.matteo.nesea.dao.jpa.Guest;
#Stateless
public class GuestDao {
// Injected database connection:
#PersistenceContext private EntityManager em;
// Stores a new guest:
public void persist(Guest guest) {
em.persist(guest);
}
// Retrieves all the guests:
public List<Guest> getAllGuests() {
TypedQuery<Guest> query = em.createQuery(
"SELECT g FROM Guest g ORDER BY g.id", Guest.class);
return query.getResultList();
}
}
this is Jpa POJO Class Guest:
package it.matteo.nesea.dao.jpa;
import java.io.Serializable;
import java.sql.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class Guest implements Serializable {
private static final long serialVersionUID = 1L;
// Persistent Fields:
#Id
#GeneratedValue
Long id;
private String name;
private Date signingDate;
// Constructors:
public Guest() {
}
public Guest(String name) {
this.name = name;
this.signingDate = new Date(System.currentTimeMillis());
}
// String Representation:
#Override
public String toString() {
return name + " (signed on " + signingDate + ")";
}
}
This is a Servlet GuestServlet:
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import it.matteo.nesea.dao.jpa.Guest;
import it.matteo.nesea.ejb.GuestDao;
#WebServlet(name="GuestServlet", urlPatterns={"/guest"})
public class GuestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
// Injected DAO EJB:
#EJB GuestDao guestDao;
#Override
protected void doGet(
HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Display the list of guests:
request.setAttribute("guests", guestDao.getAllGuests());
request.getRequestDispatcher("/guest.jsp").forward(request, response);
}
#Override
protected void doPost(
HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Handle a new guest:
String name = request.getParameter("name");
if (name != null)
guestDao.persist(new Guest(name));
// Display the list of guests:
doGet(request, response);
}
}
This is a JSP Page:
<%#page contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%#page import="java.util.*,it.matteo.nesea.dao.jpa.Guest"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>JPA Guest Book Web Application</title>
</head>
<body>
<form method="POST" action="guest">
Name: <input type="text" name="name" />
<input type="submit" value="Add" />
</form>
<hr><ol> <%
#SuppressWarnings("unchecked")
List<Guest> guests = (List<Guest>)request.getAttribute("guests");
if (guests != null) {
for (Guest guest : guests) { %>
<li> <%= guest %> </li> <%
}
} %>
</ol></hr>
</body>
This is the path of Project
Your persistence.xml file is in the wrong place. The JPA uses a convention to find your persistence.xml so you have put the file in the right place.
According to the Oracle docs:
The JAR file or directory whose META-INF directory contains persistence.xml is called the root of the persistence unit.
If you package the persistent unit as a set of classes in an EJB JAR file, persistence.xml should be put in the EJB JAR’s META-INF directory.
If you package the persistence unit as a set of classes in a WAR file, persistence.xml should be located in the WAR file’s WEB-INF/classes/META-INF directory.
In your case when the persistence.xml file is in src/META-INF/ (if you use MAVEN the path is src/resources/META-INF) its going to be packaged in your war in the WEB-INF/classes/META-INF folder, funcioning as the root of the persistence unit.
Edit: Working with Angular2 -
I'm trying to implement OAuth2 to make users log in using Facebook/Github.
When I'm at localhost:4200/login I simply click "log in with facebook" and it tries to redirect to localhost:4200/login/facebook BUT then it gives me the error:
ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'login/facebook'
Error: Cannot match any routes. URL Segment: 'login/facebook'
What could be wrong? I've spent hours trying to figure it out but with no luck. Am I missing anything?
In my OAuth2Index.ts file I have the following:
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'OAuth2Index',
templateUrl: './auth-server/src/main/resources/static/index.html',
// styleUrls: ['./navbar.component.css']
})
export class OAuth2IndexComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
It displays the index.html file, which has:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Demo</title>
<meta name="description" content="" />
<meta name="viewport" content="width=device-width" />
<base href="/" />
<link rel="stylesheet" type="text/css"
href="/webjars/bootstrap/css/bootstrap.min.css" />
<script type="text/javascript" src="/webjars/jquery/jquery.min.js"></scr>
<script type="text/javascript"
src="/webjars/bootstrap/js/bootstrap.min.js"></script>
</head>
<body ng-app="app" ng-controller="home as home">
<h1>Login</h1>
<div class="container" ng-show="!home.authenticated">
<div>
With Facebook: click here
</div>
<div>
With Github: click here
</div>
</div>
<div class="container" ng-show="home.authenticated">
Logged in as: <span ng-bind="home.user"></span>
<div>
<button ng-click="home.logout()" class="btn btn-primary">Logout</button>
</div>
</div>
<script type="text/javascript" src="/webjars/angularjs/angular.min.js"></script>
<script type="text/javascript">
angular
.module("app", [])
.config(
function($httpProvider) {
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
}).controller("home", function($http, $location) {
var self = this;
$http.get("/user").success(function(data) {
if (data.name) {
self.user = data.name;
self.authenticated = true;
} else {
self.user = "N/A";
self.authenticated = false;
}
}).error(function() {
self.user = "N/A";
self.authenticated = false;
});
self.logout = function() {
$http.post('logout', {}).success(function() {
self.authenticated = false;
$location.path("/");
}).error(function(data) {
console.log("Logout failed")
self.authenticated = false;
});
};
});
</script>
Please notice the: "With Facebook: click here
xxxx"
I have some beans in my SocialApplication.java file that should handle the action when user clicks login with facebook (i.e. /login/facebook).
/*
* Copyright 2012-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example;
import java.security.Principal;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.Filter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties;
import org.springframework.boot.autoconfigure.security.oauth2.resource.UserInfoTokenServices;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.client.OAuth2ClientContext;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.filter.OAuth2ClientAuthenticationProcessingFilter;
import org.springframework.security.oauth2.client.filter.OAuth2ClientContextFilter;
import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.filter.CompositeFilter;
#SpringBootApplication
#RestController
#EnableOAuth2Client
#EnableAuthorizationServer
#Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class SocialApplication extends WebSecurityConfigurerAdapter {
#Autowired
OAuth2ClientContext oauth2ClientContext;
#RequestMapping({ "/user", "/me" })
public Map<String, String> user(Principal principal) {
Map<String, String> map = new LinkedHashMap<>();
map.put("name", principal.getName());
return map;
}
#Override
protected void configure(HttpSecurity http) throws Exception {
// #formatter:off
http.antMatcher("/**").authorizeRequests().antMatchers("/", "/login**", "/webjars/**").permitAll().anyRequest()
.authenticated().and().exceptionHandling()
.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/")).and().logout()
.logoutSuccessUrl("/").permitAll().and().csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()).and()
.addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class);
// #formatter:on
}
#Configuration
#EnableResourceServer
protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
#Override
public void configure(HttpSecurity http) throws Exception {
// #formatter:off
http.antMatcher("/me").authorizeRequests().anyRequest().authenticated();
// #formatter:on
}
}
public static void main(String[] args) {
SpringApplication.run(SocialApplication.class, args);
}
#Bean
public FilterRegistrationBean oauth2ClientFilterRegistration(OAuth2ClientContextFilter filter) {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(filter);
registration.setOrder(-100);
return registration;
}
#Bean
#ConfigurationProperties("github")
public ClientResources github() {
return new ClientResources();
}
#Bean
#ConfigurationProperties("facebook")
public ClientResources facebook() {
return new ClientResources();
}
private Filter ssoFilter() {
CompositeFilter filter = new CompositeFilter();
List<Filter> filters = new ArrayList<>();
filters.add(ssoFilter(facebook(), "/login/facebook"));
filters.add(ssoFilter(github(), "/login/github"));
filter.setFilters(filters);
return filter;
}
private Filter ssoFilter(ClientResources client, String path) {
OAuth2ClientAuthenticationProcessingFilter filter = new OAuth2ClientAuthenticationProcessingFilter(
path);
OAuth2RestTemplate template = new OAuth2RestTemplate(client.getClient(), oauth2ClientContext);
filter.setRestTemplate(template);
UserInfoTokenServices tokenServices = new UserInfoTokenServices(
client.getResource().getUserInfoUri(), client.getClient().getClientId());
tokenServices.setRestTemplate(template);
filter.setTokenServices(tokenServices);
return filter;
}
}
class ClientResources {
#NestedConfigurationProperty
private AuthorizationCodeResourceDetails client = new AuthorizationCodeResourceDetails();
#NestedConfigurationProperty
private ResourceServerProperties resource = new ResourceServerProperties();
public AuthorizationCodeResourceDetails getClient() {
return client;
}
public ResourceServerProperties getResource() {
return resource;
}
}
I'm my app-routing.module.ts I have:
const routes: Routes = [
// {path: 'index.html ', data: {title: 'Login'}, component: LoginComponent},
// {path: 'login', data: {title: 'Login'}, component: LoginComponent},
// {path: 'index ', data: {title: 'Login'}, component: OAuthIndexComponent},
{path: 'login', data: {title: 'Login'}, component: OAuth2IndexComponent},
{path: 'signup', data: {title: 'Login'}, component: UserRegistrationComponent},
{path: '', pathMatch: 'full', redirectTo: '/login'},
{
path:'',component: AppWrap,
children:[
{path: 'cars', data: {title: 'Car'}, component: ProductsComponent},
{path: 'cars/:id', data: {title: 'Car'}, compoent: ProductSingleDetailComponent},
// {path: 'login/facebook', data: {title: 'facebookLogin'}, component: OAuth2IndexComponent}
]
}
];
In my app.module.ts I have remembered to declare OAuth2IndexComponent.
in my Icefaces 3 application i have a drop down menu. I would like to populate it dynamicaly. In my ManagedBean i have a methode which define the menuItem. it get the label and actionMethod, and valued them on the MenuItem. When i launch my application, the item of drop down menu are always empty.
ManagedBean :
package com.omb.view;
import java.io.Serializable;
import javax.el.MethodExpression;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.icesoft.faces.component.menubar.MenuItem;
#Controller
#Scope("session")
public class MyBean implements Serializable {
private static final Log logger = LogFactory.getLog(MyBean.class);
private MenuItem menuItem1;
public String initMyBean() {
try {
initMenuItem();
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
private void initMenuItem() {
menuItem1 = new MenuItem();
menuItem1.setValue("Menu 1");
MethodExpression actionExpression = FacesUtils.createAction("#{menu1Bean.display}", String.class);
menuItem1.setActionExpression(actionExpression);
}
public MenuItem getMenuItem1() {
return this.menuItem1;
}
public void setMenuItem1(MenuItem menuItem1) {
this.menuItem1 = menuItem1;
}
}
FaceUtils
package com.omb.view;
import javax.el.MethodExpression;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.MethodExpressionActionListener;
/**
* JSF utilities.
*/
public class FacesUtils {
public static MethodExpression createAction(String actionExpression, Class<?> returnType) {
FacesContext context = FacesContext.getCurrentInstance();
return context.getApplication().getExpressionFactory()
.createMethodExpression(context.getELContext(), actionExpression, returnType, new Class[0]);
}
public static MethodExpressionActionListener createActionListener(String actionListenerExpression) {
FacesContext context = FacesContext.getCurrentInstance();
return new MethodExpressionActionListener(context
.getApplication()
.getExpressionFactory()
.createMethodExpression(context.getELContext(), actionListenerExpression, null,
new Class[] {ActionEvent.class}));
}
}
screen.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets">
<body>
<ui:composition>
<ice:form id="headerForm" xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ice="http://www.icesoft.com/icefaces/component"
xmlns:ace="http://www.icefaces.org/icefaces/components"
xmlns:c="http://java.sun.com/jstl/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
<div class="menu">
<ace:menuButton id="menuButton" effect="slide" effectDuration="200" value="Menu Button">
<ace:menuItem binding="#{myBean.menuItem1}"/>
</ace:menuButton>
</div>
</ice:form>
</ui:composition>
</body>
</html>
I finally use a the standard solution :
<ace:menuButton id="menuButton" effect="slide" effectDuration="200" value="Menu Button">
<ace:menuItem value="Menu 1" action="#{myBean.display}"/>
</ace:menuButton>
I have downloaded dukeetf2 tutorial of oracle but it does not work (when I run it nothing happens although it is supposed to update the page every second). It seems the browser is sending the requests but does not update the page as I have the following results in console.
SEVERE: in init
INFO: Initializing EJB.
INFO: JTS5014: Recoverable JTS instance, serverId = [100]
INFO: WEB0671: Loading application [org.glassfish.javaeetutorial_dukeetf2_war_7.0.4-SNAPSHOT] at [/dukeetf2]
INFO: CORE10010: Loading application org.glassfish.javaeetutorial_dukeetf2_war_7.0.4-SNAPSHOT done in 6,908 ms
INFO: GlassFish Server Open Source Edition 3.1.2.2 (5) startup time : Felix (2,692ms), startup services(117,706ms), total(120,398ms)
INFO: JMX005: JMXStartupService had Started JMXConnector on JMXService URL service:jmx:rmi://Workstation9:8686/jndi/rmi://Workstation9:8686/jmxrmi
SEVERE: in timeout
SEVERE: in send
SEVERE: in timeout
SEVERE: in send
INFO: WEB0169: Created HTTP listener [http-listener-1] on host/port [0.0.0.0:8080]
INFO: Grizzly Framework 1.9.50 started in: 2ms - bound to [0.0.0.0:8080]
INFO: [2] timers deleted for id: 90756774797901824
INFO: EJB5181:Portable JNDI names for EJB PriceVolumeBean: [java:global/org.glassfish.javaeetutorial_dukeetf2_war_7.0.4-SNAPSHOT/PriceVolumeBean, java:global/org.glassfish.javaeetutorial_dukeetf2_war_7.0.4-SNAPSHOT/PriceVolumeBean!javaeetutorial.web.dukeetf2.PriceVolumeBean]
SEVERE: in init
INFO: Initializing EJB.
INFO: WEB0671: Loading application [org.glassfish.javaeetutorial_dukeetf2_war_7.0.4-SNAPSHOT] at [/dukeetf2]
INFO: org.glassfish.javaeetutorial_dukeetf2_war_7.0.4-SNAPSHOT was successfully deployed in 348 milliseconds.
INFO: WEB0169: Created HTTP listener [http-listener-2] on host/port [0.0.0.0:8181]
INFO: Grizzly Framework 1.9.50 started in: 3ms - bound to [0.0.0.0:8181]
SEVERE: in timeout
SEVERE: in send
SEVERE: in timeout
SEVERE: in send
SEVERE: in timeout
SEVERE: in send
SEVERE: in timeout
SEVERE: in send
SEVERE: in timeout
SEVERE: in send
SEVERE: in timeout
.....
I have downloaded the dependencies and currently have, javaee-api-7.0.jar, activation-1.1.jar and javax.mail-1.5.0.jar in my dependencies directory.
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>websocket</artifactId>
<groupId>org.glassfish.javaeetutorial</groupId>
<version>7.0.4-SNAPSHOT</version>
</parent>
<groupId>org.glassfish.javaeetutorial</groupId>
<artifactId>dukeetf2</artifactId>
<packaging>war</packaging>
<name>dukeetf2</name>
</project>
index.html
<!DOCTYPE html>
<html>
<head>
<title>Duke's WebSocket ETF</title>
<link rel="stylesheet" type="text/css" href="resources/css/default.css" />
<script type="text/javascript">
var wsocket;
function connect() {
wsocket = new WebSocket("ws://localhost:8080/dukeetf2/dukeetf");
wsocket.onmessage = onMessage;
}
function onMessage(evt) {
var arraypv = evt.data.split(",");
document.getElementById("price").innerHTML = arraypv[0];
document.getElementById("volume").innerHTML = arraypv[1];
}
window.addEventListener("load", connect, false);
</script>
</head>
<body>
<h1>Duke's WebSocket ETF</h1>
<table>
<tr>
<td width="100">Ticker</td>
<td align="center">Price</td>
<td id="price" style="font-size:24pt;font-weight:bold;">--.--</td>
</tr>
<tr>
<td style="font-size:18pt;font-weight:bold;" width="100">DKEJ</td>
<td align="center">Volume</td>
<td id="volume" align="right">--</td>
</tr>
</table>
</body>
</html>
ETFEndpoint.java
package javaeetutorial.web.dukeetf2;
import java.io.IOException;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
/* WebSocket version of the dukeetf example */
#ServerEndpoint("/dukeetf")
public class ETFEndpoint {
private static final Logger logger = Logger.getLogger("ETFEndpoint");
/* Queue for all open WebSocket sessions */
static Queue<Session> queue = new ConcurrentLinkedQueue<>();
/* PriceVolumeBean calls this method to send updates */
public static void send(double price, int volume) {
System.err.println("in send");
String msg = String.format("%.2f, %d", price, volume);
try {
/* Send updates to all open WebSocket sessions */
for (Session session : queue) {
session.getBasicRemote().sendText(msg);
logger.log(Level.INFO, "Sent: {0}", msg);
}
} catch (IOException e) {
logger.log(Level.INFO, e.toString());
}
}
#OnOpen
public void openConnection(Session session) {
System.err.println("in open connection");
/* Register this connection in the queue */
queue.add(session);
logger.log(Level.INFO, "Connection opened.");
}
#OnClose
public void closedConnection(Session session) {
System.err.println("in closed connection");
/* Remove this connection from the queue */
queue.remove(session);
logger.log(Level.INFO, "Connection closed.");
}
#OnError
public void error(Session session, Throwable t) {
System.err.println("in error");
/* Remove this connection from the queue */
queue.remove(session);
logger.log(Level.INFO, t.toString());
logger.log(Level.INFO, "Connection error.");
}
}
PriceVolumeBean.java
package javaeetutorial.web.dukeetf2;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.Timeout;
import javax.ejb.TimerConfig;
import javax.ejb.TimerService;
/* Updates price and volume information every second */
#Startup
#Singleton
public class PriceVolumeBean {
/* Use the container's timer service */
#Resource TimerService tservice;
private Random random;
private volatile double price = 100.0;
private volatile int volume = 300000;
private static final Logger logger = Logger.getLogger("PriceVolumeBean");
#PostConstruct
public void init() {
/* Intialize the EJB and create a timer */
System.err.println("in init");
logger.log(Level.INFO, "Initializing EJB.");
random = new Random();
tservice.createIntervalTimer(1000, 1000, new TimerConfig());
}
#Timeout
public void timeout() {
System.err.println("in timeout");
/* Adjust price and volume and send updates */
price += 1.0*(random.nextInt(100)-50)/100.0;
volume += random.nextInt(5000) - 2500;
ETFEndpoint.send(price, volume);
}
}
For those who wants to know how I've downloaded it, I used this address and "svn export" command.
As you mentioned, you used Glassfish Server 3.1 that is not compatible with Java EE 7. You should use Glassfish 4.0 server to run above WebSocket example. WebSocket has introduced with Java EE 7.
To know how to run this example. Go to this tutorial.