Apache camel Rest service with undertow and nordic letters - apache-camel

I have a rest service that use undertow componenet. I use wildfly and wildfly patch 4.7.0 (apache camel 2.19)
I have problem to reply with nordic letters from my Rest service. Tested with postman.
The code is:
#Override
public void configure() throws Exception {
restConfiguration().component("undertow");
rest("/hello").post("/{name}").consumes("application/json").to("direct:testpost");
from("direct:testpost")
.routeId("testpost")
.log("${body}")
.transform().jsonpath("test");
}
And when I send:
POST /hello/Anton HTTP/1.1 Host: 192.168.56.103:8080 Content-Type:
application/json ; charset=UTF-8 Cache-Control: no-cache
Postman-Token: c7ed9034-8b58-d104-9804-a1ff60a26f65
{"test": "test with Å"}
I get the error:
2017-06-07 07:06:16,253 INFO [testput] (default task-5) {"test":
"test with Å"}
2017-06-07 07:06:16,258 ERROR [io.undertow.request] (default task-5)
UT005071: Undertow request failed HttpServerExchange{ POST
/hello/Anton request {Accept=[*/*],
Postman-Token=[a3f9c986-e6d1-1f41-e4f8-54f3e38678c3],
Accept-Language=[sv-SE,sv;q=0.8,en-US;q=0.6,en;q=0.4],
Cache-Control=[no-cache], Accept-Encoding=[gzip, deflate],
Origin=[chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop],
User-Agent=[Mozilla/5.0 (Windows NT 6.1; Win64; x64)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86
Safari/537.36], Connection=[keep-alive], Content-Length=[24],
Content-Type=[application/json ; charset=UTF-8],
Host=[192.168.56.103:8080]} response {Accept=[*/*],
Postman-Token=[a3f9c986-e6d1-1f41-e4f8-54f3e38678c3],
Accept-Language=[sv-SE,sv;q=0.8,en-US;q=0.6,en;q=0.4], name=[Anton],
X-Powered-By=[Undertow/1], Accept-Encoding=[gzip, deflate],
breadcrumbId=[ID-localhost-39384-1496833334654-11-5],
Server=[WildFly/10],
Origin=[chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop],
User-Agent=[Mozilla/5.0 (Windows NT 6.1; Win64; x64)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86
Safari/537.36], Content-Type=[application/json ; charset=UTF-8]}}:
org.apache.camel.TypeConversionException: Error during type conversion
from type: java.lang.String to the required type: java.nio.ByteBuffer
with value test with Å due java.nio.BufferOverflowException
at org.apache.camel.impl.converter.BaseTypeConverterRegistry.createTypeConversionException(BaseTypeConverterRegistry.java:629)
at org.apache.camel.impl.converter.BaseTypeConverterRegistry.convertTo(BaseTypeConverterRegistry.java:150)
at org.apache.camel.impl.converter.BaseTypeConverterRegistry.convertTo(BaseTypeConverterRegistry.java:121)
at org.apache.camel.component.undertow.UndertowConsumer.handleRequest(UndertowConsumer.java:135)
at io.undertow.server.Connectors.executeRootHandler(Connectors.java:202)
at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:805)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:748) Caused by: org.apache.camel.RuntimeCamelException:
java.nio.BufferOverflowException
at org.apache.camel.util.ObjectHelper.wrapRuntimeCamelException(ObjectHelper.java:1756)
at org.apache.camel.util.ObjectHelper.invokeMethod(ObjectHelper.java:1355)
at org.apache.camel.impl.converter.StaticMethodTypeConverter.convertTo(StaticMethodTypeConverter.java:59)
at org.apache.camel.impl.converter.BaseTypeConverterRegistry.doConvertTo(BaseTypeConverterRegistry.java:306)
at org.apache.camel.impl.converter.BaseTypeConverterRegistry.convertTo(BaseTypeConverterRegistry.java:133)
... 7 more Caused by: java.nio.BufferOverflowException
at java.nio.HeapByteBuffer.put(HeapByteBuffer.java:189)
at java.nio.ByteBuffer.put(ByteBuffer.java:859)
at org.apache.camel.converter.NIOConverter.toByteBuffer(NIOConverter.java:102)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.camel.util.ObjectHelper.invokeMethod(ObjectHelper.java:1351)
... 10 more
undertow configuration:
<subsystem xmlns="urn:jboss:domain:undertow:3.1">
<buffer-cache name="default"/>
<server name="default-server">
<http-listener name="default" socket-binding="http" redirect-socket="https" enable-http2="true"/>
<https-listener name="https" socket-binding="https" security-realm="ApplicationRealm" enable-http2="true"/>
<host name="default-host" alias="localhost">
<location name="/" handler="welcome-content"/>
<filter-ref name="server-header"/>
<filter-ref name="x-powered-by-header"/>
</host>
</server>
<servlet-container name="default">
<jsp-config/>
<websockets/>
</servlet-container>
<handlers>
<file name="welcome-content" path="${jboss.home.dir}/welcome-content"/>
</handlers>
<filters>
<response-header name="server-header" header-name="Server" header-value="WildFly/10"/>
<response-header name="x-powered-by-header" header-name="X-Powered-By" header-value="Undertow/1"/>
</filters>
</subsystem>
So have anyone any ideas how I can fix this? All help is appreciated!

It's a bug in org.apache.camel.converter.NIOConverter (2.18.4)
public static ByteBuffer toByteBuffer(String value, Exchange exchange) {
ByteBuffer buf = ByteBuffer.allocate(value.length());
byte[] bytes = null;
if (exchange != null) {
String charsetName = exchange.getProperty(Exchange.CHARSET_NAME, String.class);
if (charsetName != null) {
try {
bytes = value.getBytes(charsetName);
} catch (UnsupportedEncodingException e) {
LOG.warn("Cannot convert the byte to String with the charset " + charsetName, e);
}
}
}
if (bytes == null) {
bytes = value.getBytes();
}
buf.put(bytes);
buf.flip();
return buf;
}
The ByteBuffer is allocated with String.length() ignoring the fact that it might contain double byte characters.
I'm working around this bug by replacing the converter in the registry using an eventlistener.
void onContextStarting(#Observes CamelContextStartingEvent event) {
def context = event.getContext();
def registry = context.getTypeConverterRegistry();
registry.setTypeConverterExistsLoggingLevel(LoggingLevel.INFO)
registry.setTypeConverterExists(TypeConverterExists.Override)
registry.addTypeConverter(ByteBuffer.class,String.class, new StringToByteBufferConverter());
registry.setTypeConverterExists(TypeConverterExists.Ignore)
}
The converter I replaced it with uses the byte.length to allocate the ByteBuffer so the buffer matches the actualy byte count for the string:
import org.apache.camel.Exchange;
import org.apache.camel.support.TypeConverterSupport;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
public class StringToByteBufferConverter extends TypeConverterSupport {
public <T> T convertTo(Class<T> type, Exchange exchange, Object object) {
String value = (String)object;
byte[] bytes = null;
if (exchange != null) {
String charsetName = exchange.getProperty(Exchange.CHARSET_NAME, String.class);
if (charsetName != null) {
try {
bytes = value.getBytes(charsetName);
} catch (UnsupportedEncodingException e) {
throw new UnsupportedOperationException(e);
}
}
}
if (bytes == null) {
bytes = value.getBytes();
}
ByteBuffer buf = ByteBuffer.allocate(bytes.length);
buf.put(bytes);
buf.flip();
return (T)buf;
}
}
You can also work around this bug by converting the body to a type other than String to circumvent the bad converter:
#Override
public void configure() throws Exception {
restConfiguration().component("undertow");
rest("/hello").post("/{name}").consumes("application/json").to("direct:testpost");
from("direct:testpost")
.routeId("testpost")
.log("${body}")
.transform().jsonpath("test")
.convertBodyTo(byte[].class);
}

Related

Unable to find element on closed window.server didn't provide stacktrace information

I written my code for a selenium program using java language. When I run the code getting below issue. I used xpath & linktext for identifying the elements. Program code also exactly matches with the code in youtube. But still application is throwing an error message like below.
Started InternetExplorerDriver server (64-bit)
3.4.0.0
Listening on port 15205
Only local connections are allowed
Aug 05, 2017 3:20:01 AM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS
Exception in thread "main" org.openqa.selenium.NoSuchWindowException: Unable to find element on closed window (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 29 milliseconds
Build info: version: 'unknown', revision: 'unknown', time: 'unknown'
System info: host: 'LAPTOP-5KIPBQVM', ip: '192.168.0.3', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_131'
Driver info: org.openqa.selenium.ie.InternetExplorerDriver
Capabilities [{se:ieOptions={browserAttachTimeout=0.0, ie.enableFullPageScreenshot=true, enablePersistentHover=true, ie.forceCreateProcessApi=false, ie.forceShellWindowsApi=false, ignoreZoomSetting=false, ie.fileUploadDialogTimeout=3000.0, ie.useLegacyFileUploadDialogHandling=false, nativeEvents=true, ie.ensureCleanSession=false, elementScrollBehavior=0.0, ie.browserCommandLineSwitches=, requireWindowFocus=false, initialBrowserUrl=http://localhost:15205/, ignoreProtectedModeSettings=false, enableElementCacheCleanup=true}, browserName=internet explorer, pageLoadStrategy=normal, javascriptEnabled=true, version=11, platform=WINDOWS, unexpectedAlertBehaviour=dismiss}]
Session ID: 7d81aaf4-8640-4c8a-829b-22efc698cb87
*** Element info: {Using=xpath, value=.//*[#id='adminAppMenu']/div[1]/ul/li[1]/a}
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:215)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:167)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:671)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:410)
at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:509)
at org.openqa.selenium.By$ByXPath.findElement(By.java:361)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:402)
at AdminInterface.main(AdminInterface.java:40)
My code:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class AdminInterface {
public static WebDriver driver;
public void launchApplication()
{
System.setProperty("webdriver.ie.driver", "C:\\Users\\rprem\\Downloads\\IEDriverServer_x64_3.4.0\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
driver.get("http://www.gcrit.com/build3/admin/login.php?osCAdminID=es8t35f3gvo51onj3q1omnef00");
}
public void loginApplication(String Username, String Password) throws InterruptedException
{
driver.findElement(By.name("username")).sendKeys(Username);
driver.findElement(By.name("password")).sendKeys(Password);
driver.findElement(By.id("tdb1")).click();
Thread.sleep(1000);
}
public void closeBrowser()
{
driver.close();
}
public static void main(String[] args) throws InterruptedException
{
AdminInterface obj = new AdminInterface();
obj.launchApplication();
obj.loginApplication("admin", "admin#123");
boolean Aol = driver.findElement(By.xpath(".//*[#id='adminAppMenu']/div[1]/ul/li[1]/a")).isDisplayed();
Thread.sleep(1000);
boolean Bol = driver.findElement(By.xpath(".//*[#id='adminAppMenu']/div[1]/ul/li[2]/a")).isDisplayed();
Thread.sleep(1000);
boolean Col = driver.findElement(By.xpath(".//*[#id='adminAppMenu']/div[1]/ul/li[3]/a")).isDisplayed();
Thread.sleep(1000);
if (Aol == true && Bol == true && Col == true)
{
System.out.println("TestCase 3: + All required links are present");
}
obj.closeBrowser();
}
}
Here is the sample code block to validate if all the 3 links i.e. Categories/Products, Manufacturers and Reviews Links are displayed or not:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class Q45519546_find_element
{
public static WebDriver driver;
public void launchApplication()
{
System.setProperty("webdriver.ie.driver", "C:\\Utility\\BrowserDrivers\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
driver.get("http://www.gcrit.com/build3/admin/login.php?osCAdminID=es8t35f3gvo51onj3q1omnef00");
}
public void loginApplication(String Username, String Password) throws InterruptedException
{
driver.findElement(By.name("username")).sendKeys(Username);
driver.findElement(By.name("password")).sendKeys(Password);
driver.findElement(By.id("tdb1")).click();
Thread.sleep(1000);
}
public void closeBrowser()
{
driver.close();
}
public static void main(String[] args) throws InterruptedException
{
Q45519546_find_element obj = new Q45519546_find_element();
obj.launchApplication();
obj.loginApplication("admin", "admin#123");
boolean Aol = driver.findElement(By.xpath("//div[#id='adminAppMenu']//a[contains(.,'Categories/Products')]")).isDisplayed();
Thread.sleep(1000);
boolean Bol = driver.findElement(By.xpath("//div[#id='adminAppMenu']//a[contains(.,'Manufacturers')]")).isDisplayed();
Thread.sleep(1000);
boolean Col = driver.findElement(By.xpath("//div[#id='adminAppMenu']//a[contains(.,'Reviews')]")).isDisplayed();
Thread.sleep(1000);
if (Aol == true && Bol == true && Col == true)
{
System.out.println("TestCase 3: + All required links are present");
}
obj.closeBrowser();
}
}
Let me know if this Answers your Question.

Selenium Grid running tests in parallel

Currently, I have a Selenium grid setup, with 1 local hub and 2 local nodes. The hub is capable of distributing the tests to run in parallel and distribute it over to the nodes. I am running the tests in parallel.
The following is the base test
public abstract class BaseTest
{
String testFolder;
String testName;
protected String envName;
protected Configuration config;
protected String host;
protected RemoteWebDriver driver;
protected String proxy;
protected SomeData someData;
protected SomeController someController;
public BaseTest() {
}
public BaseTest( String testFolder, String testName)
{
this.testFolder = testFolder;
this.testName = testName;
this.envName = System.getProperty("config");
this.proxy = System.getProperty("proxy");
config = this.envName;
}
#BeforeMethod
public void startTest(Method testMethod) {
LOG.info("Starting test: " + testMethod.getName());
try {
this.someData = new SomeData();
this.driver = WebDriverSetup.getDriver();
this.someController = new someController(this.driver, this.someData);
driver.navigate().to("https://" + this.host);
} catch (MalformedURLException e) {
System.out.println("MalformedURLException");
}
}
#AfterMethod
public void closeWindow() {
driver.close();
driver.quit();
}
}
The following is the class to get the RemoteWebDriver:
public class WebDriverSetup {
public static RemoteWebDriver getDriver() throws MalformedURLException{
String SELENIUM_HUB_URL = "http://localhost:4444/wd/hub";
ThreadLocal<RemoteWebDriver> remoteWebDriver = null;
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
String proxy = System.getProperty("proxy");
if (proxy != null && !proxy.isEmpty()) {
System.out.println("Using proxy: " + proxy);
capabilities.setCapability(CapabilityType.PROXY, proxy);
}
try {
remoteWebDriver = new ThreadLocal<RemoteWebDriver>();
remoteWebDriver.set(new RemoteWebDriver(new URL(SELENIUM_HUB_URL),
capabilities));
} catch (MalformedURLException e) {
System.out.println("Tackle Issue with RemoteDriverSetup");
}
remoteWebDriver.get().manage().window()
.setSize(new Dimension(2880, 1524));
remoteWebDriver.get().manage().timeouts()
.pageLoadTimeout(10, TimeUnit.SECONDS);
remoteWebDriver.get().manage().timeouts()
.implicitlyWait(10, TimeUnit.SECONDS);
return remoteWebDriver.get();
}
}
My test suite is like :
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="Multiple Tests Suite" verbose="1" parallel="methods">
<test name="Test1">
<classes>
<class name="com.itesteverything.qa.Tests"></class>
</classes>
</test>
</suite>
Tests are like :
public class Tests extends BaseTest {
#Parameters({"testName", "env" })
public Tests( #Optional String testName, #Optional String env ) {
super( null, testName, null, env );
}
#BeforeMethod
public void setup() throws Exception {
//setSomeData
}
public void test1() throws Exception {
use driver from super
use someData from super
use someController is using the driver from super
}
public void test2() throws Exception {
use driver from super
use someData from super
use someController is using the driver from super
}
While running these tests, I get the following errors
Build info: version: '2.44.0', revision: '76d78cf323ce037c5f92db6c1bba601c2ac43ad8', time: '2014-10-23 13:11:40'
Driver info: driver.version: RemoteWebDriver
org.openqa.selenium.remote.SessionNotFoundException: Session ID is null. Using WebDriver after calling quit()?
Build info: version: '2.44.0', revision: '76d78cf323ce037c5f92db6c1bba601c2ac43ad8', time: '2014-10-23 13:11:40'
Driver info: driver.version: RemoteWebDriver
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:572)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:352)
at org.openqa.selenium.remote.RemoteWebDriver.findElementById(RemoteWebDriver.java:393)
at org.openqa.selenium.By$ById.findElement(By.java:214)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:344)
at org.openqa.selenium.support.pagefactory.DefaultElementLocator.findElement(DefaultElementLocator.java:59)
at com.sun.proxy.$Proxy25.sendKeys(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:80)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:673)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:842)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1166)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
TEST FAILED: test2
FAILED REASON: Session ID is null. Using WebDriver after calling quit()?
Is it something anyone aware of?
Thanks in advance!
Do not set driver in the base class, do not have driver property at all. The same instance is being overridden by different threadlocal drivers.
Any time you want to run your test, refer to WebDriverSetup.getDriver() in your test method itself and in your after/before methods.
#AfterMethod
Is running after each method.
And U run's only one setup. So after first method U close and it is closed as shows stack trace.

Transport error in WebSocketServerSockJsSession - Cannot load platform configurator on a Spring Stomp websocket

I'm trying to add web sockets to my AngularJS application.
I set up the web socket using Spring 4 on the server and Stomp SockJS on the client.
I access the page at http://localhost:9000/#/project/1/bts after a grunt serve command.
But I get a 500 response when doing the web socket handshake:
WebSocket connection to 'ws://localhost:8080/nitro-project-rest/api/socket/bts/405/bmtcztq4/websocket' failed: Error during WebSocket handshake: Unexpected response code: 500
The server has this to say upon each failed websocket request:
SEVERE: Servlet.service() for servlet [NITRo] in context with path [/nitro-project-rest] threw exception [Request processing failed; nested exception is org.springframework.web.socket.sockjs.SockJsException: Uncaught failure in SockJS request, uri=http://localhost:8080/nitro-project-rest/api/socket/bts/970/2xoe6kls/websocket; nested exception is org.springframework.web.socket.sockjs.SockJsTransportFailureException: WebSocket handshake failure; nested exception is java.lang.RuntimeException: Cannot load platform configurator] with root cause
java.lang.RuntimeException: Cannot load platform configurator
More on the error:
2017-02-06 10:36:04,241 DEBUG [http-bio-8080-exec-10] o.s.w.s.h.LoggingWebSocketHandlerDecorator Transport error in WebSocketServerSockJsSession[id=nqj286ob]
java.lang.RuntimeException: Cannot load platform configurator
at javax.websocket.server.ServerEndpointConfig$Configurator.fetchContainerDefaultConfigurator(ServerEndpointConfig.java:123)
at javax.websocket.server.ServerEndpointConfig$Configurator.getContainerDefaultConfigurator(ServerEndpointConfig.java:128)
at javax.websocket.server.ServerEndpointConfig$Configurator.checkOrigin(ServerEndpointConfig.java:192)
The funny thing is the push notification works fine. I can see the webpage being updated live when the expected event occurs. So my websocket works fine, in spite of this exception. This exception occurs at page load time.
When I manually type the url:
http://localhost:8080/nitro-project-rest/api/socket/bts
in the Chromium web browser it displays: Welcome to SockJS!
Here is my web socket connection service:
function StompService(endpoint) {
this.stompClient = Stomp.client(ENV.NITRO_PROJECT_WS_URL + '/socket/' + endpoint);
}
StompService.prototype.connect = function(onConnect, onError) {
this.stompClient.connect({}, function(frame) {
$rootScope.$apply(function() {
onConnect.apply(stompClient, frame);
});
}, function(frame) {
$rootScope.$apply(function() {
onError.apply(stompClient, frame);
});
}, '/');
};
And the controller:
var stomp = new SocketService(BTS_WS_ENDPOINT);
stomp.connect(function() {
$scope.client.subscribe('status', function(message) {
$scope.messages.push(message.body);
});
}, function() {
});
With the server side configuration and controller:
#Configuration
#EnableWebSocketMessageBroker
#ComponentScan(basePackages = "com.nsn.nitro.project.rest.socket")
public class WebSocketConfiguration extends AbstractWebSocketMessageBrokerConfigurer {
#Override
public void configureMessageBroker(MessageBrokerRegistry config) {
// Prefix for destinations towards the server
config.setApplicationDestinationPrefixes("/app");
// Prefix for destinations towards the client
config.enableSimpleBroker("/topic");
}
#Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
// All controllers need to be added to the endpoint registry
registry.addEndpoint("/socket/bts").withSockJS();
}
#Override
public void configureClientInboundChannel(ChannelRegistration registration) {
}
#Override
public void configureClientOutboundChannel(ChannelRegistration registration) {
registration.taskExecutor().corePoolSize(4).maxPoolSize(10);
}
}
#Controller
public class BTSSocketController {
private static Logger logger = LoggerFactory.getLogger(BTSSocketController.class);
#MessageMapping("/socket/bts")
#SendTo("/topic/status")
public BTSMessage status(BTSMessage message) throws Exception {
logger.debug("==========>> Received the message " + message.getBtsId());
message.setStatus(BTSStatus.ONAIR);
return message;
}
}
I'm running Spring Security with Basic Authentication and the following configuration:
#Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(simpleCORSFilter, ChannelProcessingFilter.class);
http
.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().httpBasic().authenticationEntryPoint(restAuthenticationEntryPoint)
.and().authorizeRequests().antMatchers("/socket/**").permitAll()
.and().authorizeRequests().antMatchers("/resources/**").permitAll()
.and().authorizeRequests().antMatchers(RESTConstants.SLASH + RESTConstants.ADMINS + RESTConstants.SLASH + RESTConstants.LOGIN).permitAll()
.and().authorizeRequests().antMatchers("/**").hasRole("ADMIN").anyRequest().authenticated();
}
#Component
public class SimpleCORSFilter implements Filter {
private static final String ORIGIN = "Origin";
private static final String OPTIONS = "OPTIONS";
private static final String OK = "OK";
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
if (httpServletRequest.getHeader(ORIGIN) != null) {
String origin = httpServletRequest.getHeader(ORIGIN);
httpServletResponse.setHeader("Access-Control-Allow-Origin", origin);
httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
httpServletResponse.setHeader("Access-Control-Allow-Headers", "Accept-Language,Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization,X-Filename,Content-Disposition,Content-Length");
// Allow more than the 6 default headers to be returned, as the content length is required for a download file request to get the file size
httpServletResponse.setHeader("Access-Control-Expose-Headers", "Accept-Language,Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization,X-Filename,Content-Disposition,Content-Length");
}
if (httpServletRequest.getMethod().equals(OPTIONS)) {
try {
httpServletResponse.getWriter().print(OK);
httpServletResponse.getWriter().flush();
} catch (IOException e) {
e.printStackTrace();
}
} else {
filterChain.doFilter(servletRequest, servletResponse);
}
}
public void init(FilterConfig filterConfig) {
}
public void destroy() {
}
}
My Java dependencies are:
[INFO] +- javax.websocket:javax.websocket-api:jar:1.1:provided
[INFO] +- org.springframework:spring-web:jar:4.3.6.RELEASE:compile
[INFO] +- org.springframework:spring-webmvc:jar:4.3.6.RELEASE:compile
[INFO] +- org.springframework:spring-test:jar:4.3.6.RELEASE:compile
[INFO] +- org.springframework:spring-messaging:jar:4.3.6.RELEASE:compile
[INFO] +- org.springframework:spring-websocket:jar:4.3.6.RELEASE:compile
My Js dependencies are:
"sockjs": "~0.3.4",
"stomp-websocket": "~2.3.4",
To help anyone else who stumbles across this while searching for the "Welcome to SockJS" error: if you are trying to connect to a SockJS address using a regular websocket connection, add /websocket to the end of your url.

Lookup of locale EJB in a POJO class throws NameNotFoundException

I try to lookup a #Stateless bean inside a POJO which is in the same package where the bean is. The bean is not null when I use it in my #ManagedBean controller class and I can do CRUD operations.
Here is the code for lookup in ArticlesBundle.java:
public class ArticlesBundle extends ResourceBundle{
protected static final String BASE_NAME = "ArticlesLcl.findForLocale";
private Map<String,String> messages = new HashMap<>();
private Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
protected final Control DB_CONTROL = new DBControl();
public ArticlesBundle(){
setParent(ResourceBundle.getBundle(BASE_NAME, FacesContext.getCurrentInstance().getViewRoot().getLocale(), DB_CONTROL));
}
protected ArticlesBundle(Locale locale){
setParent(ResourceBundle.getBundle(BASE_NAME, locale, DB_CONTROL));
}
public ArticlesBundle(Map<String,String> messages){
this.messages = messages;
}
#Override
protected Object handleGetObject(String key){
return messages != null ? messages.get(key) : parent.getObject(key);
}
#Override
public Enumeration<String> getKeys(){
return parent.getKeys();
}
protected class DBControl extends Control{
#Override
public ResourceBundle newBundle
(String baseName, Locale locale, String format, ClassLoader loader, boolean reload)
throws IllegalAccessException, InstantiationException, IOException
{
String language = locale.getLanguage();
Map<String,String> messages = getArticless(locale);
System.out.println("getArticles("+language+") = "+getArticles(locale));
return new ArticlesBundle(messages);
}
public Map<String,String> getArticles(Locale locale){
String language = locale.getLanguage();
try {
Context ctx = new InitialContext();
ArticlesLclFacade arBean = (ArticlesLclFacade) ctx.lookup("java:gesht/ArticlesLclFacade");
List<ArticlesLcl> articles = arBean.getArticles(language);
for(Iterator<ArticlesLcl> it = articles.iterator(); it.hasNext();){
ArticlesLcl article = it.next();
messages.put(article.getArId().getArId().toString(), article.getArTitle());
}
} catch (NamingException ex) {
Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
}
return messages;
}
}
}
In ArticlesFacade:
#Stateless
public class ArticlesFacade extends AbstractFacade<ArticlesLcl> {
#PersistenceContext(unitName = "gtestPU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public ArticlesFacade() {
super(ArticlesLcl.class);
}
public List<ArticlesLcl> getArticless(String language){
Query q = em.createNamedQuery("ArticlesLcl.findForLocale", ArticlesLcl.class);
q.setParameter("lang", language);
return q.getResultList();
}
}
Faces-Config.xml
<resource-bundle>
<base-name>com.gesht.bundles.ArticlesBundle</base-name>
<var>article</var>
</resource-bundle>
It throws the following exception:
SEVERE: javax.naming.NamingException: Lookup failed for 'java:gtest/ArticlesLclFacade' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is javax.naming.NameNotFoundException: No object bound to name java:gtest/ArticlesLclFacade]
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:518)
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:455)
at javax.naming.InitialContext.lookup(InitialContext.java:411)
at javax.naming.InitialContext.lookup(InitialContext.java:411)
at java.util.ResourceBundle.loadBundle(ResourceBundle.java:1436)
at java.util.ResourceBundle.findBundle(ResourceBundle.java:1400)
at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1296)
at java.util.ResourceBundle.getBundle(ResourceBundle.java:841)
at com.gtest.bundles.test.<init>(test.java:50)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at java.lang.Class.newInstance0(Class.java:372)
at java.lang.Class.newInstance(Class.java:325)
at java.util.ResourceBundle$Control.newBundle(ResourceBundle.java:2571)
at java.util.ResourceBundle.loadBundle(ResourceBundle.java:1436)
at java.util.ResourceBundle.findBundle(ResourceBundle.java:1400)
at java.util.ResourceBundle.findBundle(ResourceBundle.java:1354)
at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1296)
at java.util.ResourceBundle.getBundle(ResourceBundle.java:1028)
at com.sun.faces.application.ApplicationResourceBundle.getResourceBundle(ApplicationResourceBundle.java:124)
at com.sun.faces.application.ApplicationAssociate.getResourceBundle(ApplicationAssociate.java:608)
at com.sun.faces.application.ApplicationImpl.getResourceBundle(ApplicationImpl.java:700)
at javax.faces.application.ApplicationWrapper.getResourceBundle(ApplicationWrapper.java:526)
at com.sun.faces.el.FacesResourceBundleELResolver.getValue(FacesResourceBundleELResolver.java:83)
at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
at com.sun.el.parser.AstIdentifier.getValue(AstIdentifier.java:103)
at com.sun.el.parser.AstValue.getValue(AstValue.java:179)
at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:224)
at org.jboss.weld.el.WeldValueExpression.getValue(WeldValueExpression.java:50)
at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)
at javax.faces.component.UIOutput.getValue(UIOutput.java:169)
at com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getValue(HtmlBasicInputRenderer.java:205)
at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getCurrentValue(HtmlBasicRenderer.java:355)
at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeEnd(HtmlBasicRenderer.java:164)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1764)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1760)
at org.primefaces.component.panelgrid.PanelGridRenderer.encodeDynamicBody(PanelGridRenderer.java:92)
at org.primefaces.component.panelgrid.PanelGridRenderer.encodeBody(PanelGridRenderer.java:60)
at org.primefaces.component.panelgrid.PanelGridRenderer.encodeEnd(PanelGridRenderer.java:49)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875)
at org.primefaces.renderkit.CoreRenderer.renderChild(CoreRenderer.java:61)
at org.primefaces.renderkit.CoreRenderer.renderChildren(CoreRenderer.java:45)
at org.primefaces.renderkit.CoreRenderer.renderChild(CoreRenderer.java:59)
at org.primefaces.renderkit.CoreRenderer.renderChildren(CoreRenderer.java:45)
at org.primefaces.component.datagrid.DataGridRenderer.encodeTable(DataGridRenderer.java:156)
at org.primefaces.component.datagrid.DataGridRenderer.encodeMarkup(DataGridRenderer.java:91)
at org.primefaces.component.datagrid.DataGridRenderer.encodeEnd(DataGridRenderer.java:53)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1764)
at javax.faces.render.Renderer.encodeChildren(Renderer.java:168)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:845)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1757)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1760)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1760)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:402)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:288)
at org.ocpsoft.rewrite.faces.RewriteViewHandler.renderView(RewriteViewHandler.java:186)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:288)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:343)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
at org.ocpsoft.rewrite.servlet.RewriteFilter.doFilter(RewriteFilter.java:191)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
at org.apache.shiro.web.servlet.AbstractShiroFilter.executeChain(AbstractShiroFilter.java:449)
at org.apache.shiro.web.servlet.AbstractShiroFilter$1.call(AbstractShiroFilter.java:365)
at org.apache.shiro.subject.support.SubjectCallable.doCall(SubjectCallable.java:90)
at org.apache.shiro.subject.support.SubjectCallable.call(SubjectCallable.java:83)
at org.apache.shiro.subject.support.DelegatingSubject.execute(DelegatingSubject.java:383)
at org.apache.shiro.web.servlet.AbstractShiroFilter.doFilterInternal(AbstractShiroFilter.java:362)
at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:722)
Caused by: javax.naming.NameNotFoundException: No object bound to name java:gtest/ArticlesLclFacade
at com.sun.enterprise.naming.impl.GlassfishNamingManagerImpl.lookup(GlassfishNamingManagerImpl.java:772)
at com.sun.enterprise.naming.impl.GlassfishNamingManagerImpl.lookup(GlassfishNamingManagerImpl.java:744)
at com.sun.enterprise.naming.impl.JavaURLContext.lookup(JavaURLContext.java:177)
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:498)
... 108 more
I use Glassfish Server 3+
#Stateless(mappedName="articlesLclFacade")
public class ArticlesLclFacade extends AbstractFacade {
then in your try clause
ArticlesLclFacade arBean = (ArticlesLclFacade)ctx.lookup("articlesLclFacadee");
Or I can guess you can also use the EJB annotation as this :
#EJB
private ArticlesLclFacade arBean;
I used syntax ArticlesLclFacade arBean = (ArticlesLclFacade) ctx.lookup("java:global/gtest/ArticlesLclFacade"); and there is no more NamingException thrown.

Error 500 when contacting webservice with cxf and guice

I'm using cfx 2.5.1 and guice 2.0.
I have this interface for the ws
#WebService(targetNamespace="http://com.example.firstapp/")
public interface IWSEchoService {
#WebMethod(operationName="echoService")
String echoService(#WebParam(name="id") String id,#WebParam(name="payload") String payload) throws SOAPFault;
#WebMethod(operationName="testAttachment")
DataHandler testAttachment(DataHandler attachment) throws SOAPFault;
}
And the implementation
#WebService(targetNamespace = "http://com.example.firstapp/")
public class WSEchoServiceImpl implements IWSEchoService {
protected Log logger = LogFactory.getLog(this.getClass());
#WebMethod(operationName = "echoService")
public String echoService(String id, String payload) throws SOAPFault {
return id + "|" + payload;
}
#WebMethod(operationName = "testAttachment")
public DataHandler testAttachment(DataHandler attachment) throws SOAPFault {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
FileUtil.copyInputStream(attachment.getInputStream(), baos);
logger.debug(baos.toString());
} catch (IOException ex) {
logger.error(ex);
}
logger.info("Attachment ok! Size: " + baos.size());
return attachment;
}
}
Also I have
public class ContextStartup implements ServletContextListener {
private Log logger = LogFactory.getLog(ContextStartup.class);
private CamelContext camelContext;
public void contextInitialized(ServletContextEvent sce) {
try {
camelContext = new GuiceCamelContext(Guice.createInjector(Stage.DEVELOPMENT, new MyModule()));
camelContext.start();
startWS();
} catch (Exception ex) {
logger.error(ex);
}
}
.....
private void startWS() {
String address = "http://localhost:8191/ws/echoService";
Endpoint.publish(address, new WSEchoServiceImpl());
}
private class MyModule extends CamelModuleWithMatchingRoutes {
#Override
protected void configure() {
super.configure();
// bind camel component
}
}
}
Finally the web.xml for tomcat
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<listener>
<description>Start and destroy CamelContext</description>
<listener-class>com.example.firstapp.ContextStartup</listener-class>
</listener>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Now when in my browser i call
http://localhost:8191/ws/echoService?wsdl
or
http://localhost:8191/ws/echoService
i have a http 500 error, but in the console or in the tomcat log i haven't any exception or error
I also used this guide http://jax-ws-commons.java.net/guice/ but i had the same result
Did you try replacing localhost by IP ?
We faced same problem and this solved the problem.

Resources