I'm really stuck configuring Apache camel https4 for self signed server certificates that does not match the hostname.
[Do. 2020 16 Juli 13:13:19] [DEBUG] org.apache.camel.processor.Pipeline () - Message exchange has failed: so breaking out of pipeline for exchange: Exchange[ID-lvm-cdbservice-01ct-1594888044674-0-15551] Exception: javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
That's why I created a custom HttpClientConfigurer as stated in the apache camel http configuration. But this configurer does not seem to be used for my route?! Does anybody know why?
The configureHttpClient method is used at some point
[Do. 2020 16 Juli 10:27:25] [INFO ] com.test.SelfSignedHttpClientConfigurer () - Using SelfSignedHttpClientConfigurer...
[Do. 2020 16 Juli 10:27:25] [INFO ] com.test.SelfSignedHttpClientConfigurer () - ... HttpClient configured!
But the protocols didn't change. That's why I guess it is not used for my route.
available protocols [[TLSv1.3, TLSv1.2, TLSv1.1, TLSv1]],
currently enabled protocols [[TLSv1.3, TLSv1.2, TLSv1.1, TLSv1]],
and default protocol patterns [Patterns [includes=[.*], excludes=[SSL.*]]].
Resulting enabled protocols are [[TLSv1.3, TLSv1.2, TLSv1.1, TLSv1]].
pom.xml
<properties>
<camel.version>2.24.3</camel.version>
</properties>
<dependencies>
<!-- camel -->
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-core</artifactId>
<version>${camel.version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-spring</artifactId>
<version>${camel.version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-http4</artifactId>
<version>${camel.version}</version>
</dependency>
</dependencies>
applicationContext.xml
<!-- Apache Camel -->
<camelContext
xmlns="http://camel.apache.org/schema/spring">
<!-- HTTP myTime -->
<route id="myTimeRoute">
<from uri="file:///tmp/test?consumer.delay=10000" />
<setHeader headerName="CamelHttpMethod">
<constant>POST</constant>
</setHeader>
<setHeader headerName="Content-Type">
<constant>application/json</constant>
</setHeader>
<to uri="https4://test.de/test?delay=60000&connectTimeout=20000&httpClientConfigurer=#selfSignedHttpClientConfigurer&sslContextParameters=#mySSLContextParameters&throwExceptionOnFailure=false" />
</route>
</camelContext>
<bean id="selfSignedHttpClientConfigurer"
class="com.test.SelfSignedHttpClientConfigurer" />
I tried it with and without # (httpClientConfigurer=#selfSignedHttpClientConfigurer and httpClientConfigurer=selfSignedHttpClientConfigurer)
SelfSignedHttpClientConfigurer.class
package com.test;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.SSLContext;
import org.apache.camel.component.http4.HttpClientConfigurer;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.ssl.SSLContexts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SelfSignedHttpClientConfigurer implements HttpClientConfigurer {
/** the logger. */
private static final Logger LOG = LoggerFactory.getLogger(SelfSignedHttpClientConfigurer.class);
#Override
public void configureHttpClient(HttpClientBuilder clientBuilder) {
try {
LOG.info("Using SelfSignedHttpClientConfigurer...");
SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
// Allow TLSv1.2 protocol only
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1.2" },
null, NoopHostnameVerifier.INSTANCE);
clientBuilder.setSSLSocketFactory(sslsf);
LOG.info("... HttpClient configured!");
} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
e.printStackTrace();
}
}
}
I tried with .build() and without.
I finally found a solution. All the tutorials and documentations are "deprecated", because the Apache HTTP API has changed with version 4.5. You will not get any errors in your code, but it is simply not working.
This post really helped me: https://stackoverflow.com/a/38509015
SelfSignedHttpClientConfigurer.class
package com.test;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.SSLContext;
import org.apache.camel.component.http4.HttpClientConfigurer;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SelfSignedHttpClientConfigurer implements HttpClientConfigurer {
/** the logger. */
private static final Logger LOG = LoggerFactory.getLogger(SelfSignedHttpClientConfigurer.class);
#Override
public void configureHttpClient(HttpClientBuilder clientBuilder) {
try {
LOG.info("Using SelfSignedHttpClientConfigurer...");
final SSLContext sslContext = new SSLContextBuilder()
.loadTrustMaterial(null, (x509CertChain, authType) -> true).build();
clientBuilder.setSSLContext(sslContext)
.setConnectionManager(new PoolingHttpClientConnectionManager(RegistryBuilder
.<ConnectionSocketFactory> create().register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https",
new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE))
.build()));
LOG.info("... HttpClient configured!");
} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
e.printStackTrace();
}
}
}
applicationContext.xml
<!-- Apache Camel -->
<camelContext
xmlns="http://camel.apache.org/schema/spring">
<!-- HTTP myTime -->
<route id="myTimeRoute">
<from uri="file:///tmp/test?consumer.delay=10000" />
<setHeader headerName="CamelHttpMethod">
<constant>POST</constant>
</setHeader>
<setHeader headerName="Content-Type">
<constant>application/json</constant>
</setHeader>
<to uri="https4://test.de/test?httpClientConfigurer=#selfSignedHttpClientConfigurer" />
</route>
</camelContext>
<bean id="selfSignedHttpClientConfigurer"
class="com.test.SelfSignedHttpClientConfigurer" />
Related
Since the httpClient 3 has been outdated, I need a replacement for the code:
SSLProtocolSocketFactory.setSSL(trustStore, keyStore, pasw);
ProtocolSocketFactory factory = new SSLProtocolSocketFactory();
Protocol.registerProtocol("https", new Protocol("https", factory, 443));
Please share if anyone has tried it.
In the java code, I'm tring to call the webservice using OperationClient object
operationClientObject.execute(true);
Thanks in advance..
The axis2 httpclient4 migration is not so easy, as it appears from the "documentation".
During the process, I use the latest Axis 2 version 1.7.8.
The axis 2 1.7.0 release notes contains a one liner, for HttpClient v4 integration:
Axis2 1.7.0 supports Apache HttpClient 4.x in addition to the no longer maintained Commons HttpClient 3.x. To enable the support for HttpClient 4.x, use org.apache.axis2.transport.http.impl.httpclient4.HTTPClient4TransportSender instead of org.apache.axis2.transport.http.CommonsHTTPTransportSender in axis2.xml. Please note that the code was written for HttpClient 4.2.x and should work with 4.3.x and 4.4.x, but is incompatible with 4.5.x.
Watch out the last words. Axis 2 1.7.8 pom file, and the binary distribution contains the httpclient-4.5.3.jar, but doesn't work with it. So use httpclient 4.4.1 instead.
Enable logging
Before the upgrade, I suppose you already have a working axis 2 project. I recommend to enable axis 2 debug logging, to see what happens. To enable logging define a custom log4j propery file with jvm argument:
-Dlog4j.configuration=file:/c:/work/sources/debug_log4j.properties
The content of the debug_log4j.properties file is:
log4j.rootCategory=DEBUG, CONSOLE
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=[%p] %m%n
Axis2 + Httpclient4
If you doesn't have axis2.xml, you can found it in axis2 binary package (contains all the dependencies and example configs)
Based on the release notes, you need to change the transport senders from CommonsHTTPTransportSender to HTTPClient4TransportSender.
If you look (or debug) axis2 configurator, you see, the xml must contain specific parts otherwise axis2 doesn't read it.
So my axis2.xml content after configured to use HttpClient4 (and removed unused parts, but keep essential ones):
<axisconfig name="AxisJava2.0">
<!-- ================================================= -->
<!-- Transport Outs -->
<!-- ================================================= -->
<parameter name="hotdeployment">true</parameter>
<parameter name="hotupdate">false</parameter>
<parameter name="enableMTOM">false</parameter>
<parameter name="enableSwA">false</parameter>
<transportSender name="local"
class="org.apache.axis2.transport.local.LocalTransportSender"/>
<transportSender name="http"
class="org.apache.axis2.transport.http.impl.httpclient4.HTTPClient4TransportSender">
<parameter name="PROTOCOL">HTTP/1.1</parameter>
<parameter name="Transfer-Encoding">chunked</parameter>
<!-- If following is set to 'true', optional action part of the Content-Type will not be added to the SOAP 1.2 messages -->
<!-- <parameter name="OmitSOAP12Action">true</parameter> -->
</transportSender>
<transportSender name="https"
class="org.apache.axis2.transport.http.impl.httpclient4.HTTPClient4TransportSender">
<parameter name="PROTOCOL">HTTP/1.1</parameter>
<parameter name="Transfer-Encoding">chunked</parameter>
</transportSender>
<!-- ================================================= -->
<!-- Phases -->
<!-- ================================================= -->
<phaseOrder type="InFlow">
<!-- System predefined phases -->
<phase name="Transport">
<handler name="RequestURIBasedDispatcher"
class="org.apache.axis2.dispatchers.RequestURIBasedDispatcher">
<order phase="Transport"/>
</handler>
<handler name="SOAPActionBasedDispatcher"
class="org.apache.axis2.dispatchers.SOAPActionBasedDispatcher">
<order phase="Transport"/>
</handler>
</phase>
<phase name="Addressing">
<handler name="AddressingBasedDispatcher"
class="org.apache.axis2.dispatchers.AddressingBasedDispatcher">
<order phase="Addressing"/>
</handler>
</phase>
<phase name="Security"/>
<phase name="PreDispatch"/>
<phase name="Dispatch" class="org.apache.axis2.engine.DispatchPhase">
<handler name="RequestURIBasedDispatcher"
class="org.apache.axis2.dispatchers.RequestURIBasedDispatcher"/>
<handler name="SOAPActionBasedDispatcher"
class="org.apache.axis2.dispatchers.SOAPActionBasedDispatcher"/>
<handler name="RequestURIOperationDispatcher"
class="org.apache.axis2.dispatchers.RequestURIOperationDispatcher"/>
<handler name="SOAPMessageBodyBasedDispatcher"
class="org.apache.axis2.dispatchers.SOAPMessageBodyBasedDispatcher"/>
<handler name="HTTPLocationBasedDispatcher"
class="org.apache.axis2.dispatchers.HTTPLocationBasedDispatcher"/>
<handler name="GenericProviderDispatcher"
class="org.apache.axis2.jaxws.dispatchers.GenericProviderDispatcher"/>
<handler name="MustUnderstandValidationDispatcher"
class="org.apache.axis2.jaxws.dispatchers.MustUnderstandValidationDispatcher"/>
</phase>
<phase name="RMPhase"/>
<!-- System predefined phases -->
<!-- After Postdispatch phase module author or service author can add any phase he want -->
<phase name="OperationInPhase">
<handler name="MustUnderstandChecker"
class="org.apache.axis2.jaxws.dispatchers.MustUnderstandChecker">
<order phase="OperationInPhase"/>
</handler>
</phase>
<phase name="soapmonitorPhase"/>
</phaseOrder>
<phaseOrder type="OutFlow">
<!-- user can add his own phases to this area -->
<phase name="soapmonitorPhase"/>
<phase name="OperationOutPhase"/>
<!--system predefined phase-->
<!--these phase will run irrespective of the service-->
<phase name="RMPhase"/>
<phase name="PolicyDetermination"/>
<phase name="MessageOut"/>
<phase name="Security"/>
</phaseOrder>
<phaseOrder type="InFaultFlow">
<phase name="Addressing">
<handler name="AddressingBasedDispatcher"
class="org.apache.axis2.dispatchers.AddressingBasedDispatcher">
<order phase="Addressing"/>
</handler>
</phase>
<phase name="Security"/>
<phase name="PreDispatch"/>
<phase name="Dispatch" class="org.apache.axis2.engine.DispatchPhase">
<handler name="RequestURIBasedDispatcher"
class="org.apache.axis2.dispatchers.RequestURIBasedDispatcher"/>
<handler name="SOAPActionBasedDispatcher"
class="org.apache.axis2.dispatchers.SOAPActionBasedDispatcher"/>
<handler name="RequestURIOperationDispatcher"
class="org.apache.axis2.dispatchers.RequestURIOperationDispatcher"/>
<handler name="SOAPMessageBodyBasedDispatcher"
class="org.apache.axis2.dispatchers.SOAPMessageBodyBasedDispatcher"/>
<handler name="HTTPLocationBasedDispatcher"
class="org.apache.axis2.dispatchers.HTTPLocationBasedDispatcher"/>
<handler name="GenericProviderDispatcher"
class="org.apache.axis2.jaxws.dispatchers.GenericProviderDispatcher"/>
<handler name="MustUnderstandValidationDispatcher"
class="org.apache.axis2.jaxws.dispatchers.MustUnderstandValidationDispatcher"/>
</phase>
<phase name="RMPhase"/>
<!-- user can add his own phases to this area -->
<phase name="OperationInFaultPhase"/>
<phase name="soapmonitorPhase"/>
</phaseOrder>
<phaseOrder type="OutFaultFlow">
<!-- user can add his own phases to this area -->
<phase name="soapmonitorPhase"/>
<phase name="OperationOutFaultPhase"/>
<phase name="RMPhase"/>
<phase name="PolicyDetermination"/>
<phase name="MessageOut"/>
<phase name="Security"/>
</phaseOrder>
</axisconfig>
In the java side, you need to create a custom axis2 configuration context, to use our custom axis2.xml. Axis2 offer multiple configurator, i prefer the file based one:
final ConfigurationContext ctx = ConfigurationContextFactory.createConfigurationContextFromFileSystem(
"c:\\work\\sources\\axis2conf",
"c:\\work\\sources\\axis2conf\\axis2.xml");
You can assign the configuration context to the client stub during the constructor:
FileNet_UploadDocumentWSStub stub = new FileNet_UploadDocumentWSStub(ctx, "https://testserver/test.asp");
So, if you doesn't want to use custom ssl settings, your upgrade is done.
Axis2 + Httpclient4 + SSL
After you upgraded to httpclient4, the implementation doesn't use the custom protocol handler property (HTTPConstants.CUSTOM_PROTOCOL_HANDLER) anymore.
The old implementation in org/apache/axis2/transport/http/impl/httpclient3/HTTPSenderImpl.java:524:
// one might need to set his own socket factory. Let's allow that case
// as well.
Protocol protocolHandler = (Protocol) msgCtx.getOptions().getProperty(
HTTPConstants.CUSTOM_PROTOCOL_HANDLER);
The new implementation org/apache/axis2/transport/http/impl/httpclient4/HTTPSenderImpl.java:583:
// TODO : one might need to set his own socket factory. We have to allow that case as well.
You need to setup ssl context in httpclient4 side. It's not a problem, because axis allow you to define httpclient for a ws call with HTTPConstants.CACHED_HTTP_CLIENT property:
options.setProperty(HTTPConstants.CACHED_HTTP_CLIENT, httpClient);
But if you create a httpclient4 for a standard way:
...
HttpClientBuilder builder = HttpClientBuilder.create();
...
and assign it to axis2 client stub, you got a ClassCastException, because all new httpclient Builder, factory, etc. methods create the "modern" implementation of httpclient, based on ClosableHttpClient. But axis2 implementation depends on deprecated AbstractHttpClient. So you need to create old version of httpclient.
The complete example:
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.Security;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;
import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.commons.httpclient.contrib.ssl.AuthSSLProtocolSocketFactory;
import org.apache.http.client.HttpClient;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.BasicClientConnectionManager;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.ssl.SSLContexts;
public class SslTest {
public SslTest() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) throws Exception {
File keyFile = new File("c:\\work\\sources\\ConsoleApp25\\avp-pc.jks");
final ConfigurationContext ctx = ConfigurationContextFactory.createConfigurationContextFromFileSystem(
"c:\\work\\sources\\axis2conf",
"c:\\work\\sources\\axis2conf\\axis2.xml");
FileNet_UploadocumentWSStub stub = new FileNet_UploadDocumentWSStub(ctx, "https://testserver/test.asp");
FileNet_UploadDocument wsMethodReq = new FileNet_UploadDocument();
ServiceClient serviceClient = stub._getServiceClient();
Options options = serviceClient.getOptions();
//keystore types: https://docs.oracle.com/javase/9/docs/specs/security/standard-names.html#keystore-types
KeyStore keyStore = KeyStore.getInstance("jks");
InputStream in = null;
try {
in = new FileInputStream(keyFile);
keyStore.load(in, "changeit".toCharArray());
} finally {
if (in != null) {
in.close();
}
}
//Factory instance types: https://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html#T5
//on IBM servers use IbmX509 instead of SunX509
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
keyManagerFactory.init(keyStore, "changeit".toCharArray());
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
trustManagerFactory.init(keyStore);
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
SSLSocketFactory sf = new SSLSocketFactory(sslContext);
Scheme httpsScheme = new Scheme("https", 443, sf);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(httpsScheme);
ClientConnectionManager cm = new SingleClientConnManager(schemeRegistry);
HttpClient httpClient = new DefaultHttpClient(cm);
options.setProperty(HTTPConstants.CACHED_HTTP_CLIENT, httpClient);
stub.fileNet_UploadDocument(wsMethodReq);
System.out.println("done");
}
I use 5.0.0-rc4 as izpack version and izpack-installer artifact exists as a dependency in my pom.xml.
<dependency>
<groupId>org.codehaus.izpack</groupId>
<artifactId>izpack-installer</artifactId>
<version>${izpack.version}</version>
</dependency>
I have defined a custom action DeletePreviousInstallationAction for InstallPanel.
InstallPanel definition is included in install.xml as below.
<panels>
<panel classname="TargetPanel"/>
<panel classname="UserInputPanel" id="panelUserInput"/>
<panel classname="InstallPanel">
<actions>
<action stage="preconstruct" classname="com.x.y.z.w.DeletePreviousInstallationAction" />
</actions>
</panel>
<panel classname="ProcessPanel"/>
<panel classname="SimpleFinishPanel"/>
</panels>
DeletePreviousInstallationAction code:
package com.x.y.z.w;
import com.izforge.izpack.api.data.InstallData;
import com.izforge.izpack.api.data.PanelActionConfiguration;
import com.izforge.izpack.api.handler.AbstractUIHandler;
import com.izforge.izpack.data.PanelAction;
public class DeletePreviousInstallationAction implements PanelAction {
#Override
public void executeAction(InstallData id, AbstractUIHandler auih) {
System.out.println("Intall path: " + id.getInstallPath());
}
#Override
public void initialize(PanelActionConfiguration pac) {
}
}
When I try to build setup project, I get Failure: Class 'com.x.y.z.w.DeletePreviousInstallationAction' not found. Why does this happen?
You are most likely missing it during compilation, it has to be added in "jar" section to install xml of izpack e.g.:
<jar src="#{jmx4ant:jmx4ant:jar}" stage="both" />
Hi i have a Red5 Application Server running and a NetConnection using Air to IOS to connect to the Red5 Application Server.
But the problem is that i get an error like:
2014-07-01 04:43:04,475 [NioProcessor-6] ERROR o.r.server.service.ServiceInvoker - Method addSomething with parameters [2, 3] not found in org.red5.server.CoreHandler#ebf5a1
I understand that the Method is not being called for some reason but can understand why, can anyone help please?
CODE
SERVERSIDE
package com;
import java.util.HashMap;
import org.red5.server.adapter.ApplicationAdapter;
import org.red5.server.api.IConnection;
import org.red5.server.api.Red5;
import org.red5.server.api.scope.IScope;
import org.red5.server.api.service.*;
import static java.lang.System.*;
import java.util.Stack;
public class Application extends ApplicationAdapter{
//private static final Log log = LogFactory.getLog( Application.class );
public boolean appStart(IScope scope){
out.println("Adding: ");
return true;
}
public void appStop(){
out.println("Adding: ");
// This function fires when the app is closing
}
public double addSomething(double a, double b){
// This is a method we will call from our flash client
out.println("Adding: "+a+" + "+b);
return a+b;
}
public boolean connect(IConnection conn, IScope scope, Object[] params) {
// This is the master connection method called every time someone connects
// to the server.
out.println("Adding: ");
//ServiceUtils.invokeOnAllConnections(scope, "joinuser", null);
return true;
}
/*
* (non-Javadoc)
* #see org.red5.server.adapter.ApplicationAdapter#disconnect(org.red5.server.api.IConnection, org.red5.server.api.IScope)
* disconnect an user form the chat and notify all others users
*/
public void disconnect(IConnection conn, IScope scope) {
// Function called every time someone disconnects from the server.
//ServiceUtils.invokeOnAllConnections(scope, "removeuser",null );
super.disconnect(conn, scope);
}
}
CLIENT
------
import flash.display.Sprite;
import flash.display.MovieClip;
import flash.events.NetStatusEvent;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.media.Camera;
import flash.media.Microphone;
import flash.media.Video;
import flash.net.Responder;
var nc:NetConnection;
var good:Boolean;
var netOut:NetStream;
var netIn:NetStream;
var cam:Camera;
var mic:Microphone;
var responder:Responder;
var r:Responder;
var vidOut:Video;
var vidIn:Video;
var outStream:String;
var inStream:String;
trace("hello");
var rtmpNow:String="rtmp://localhost/Test1";
nc=new NetConnection;
nc.client = this;
nc.connect(rtmpNow,"trik");
nc.addEventListener(NetStatusEvent.NET_STATUS,getStream);
function getStream(e:NetStatusEvent):void
{
good=e.info.code == "NetConnection.Connect.Success";
if(good)
{
trace("hello");
// Here we call functions in our Java Application
//responder=new Responder(streamNow);
r = new Responder(adder);
nc.call("addSomething",r,2,3);
//nc.call("streamer",responder,"test");
}
}
function adder (obj:Object):void{
trace("Total = ",obj.toString());
}
function streamNow(streamSelect:Object):void
{
setCam();
setMic();
setVid();
trace("We've got our object",streamSelect.toString());
switch(streamSelect.toString())
{
case "left" :
outStream="left";
inStream="right";
break;
case "right" :
outStream="right";
inStream="left";
break;
}
//Publish local video
netOut=new NetStream(nc);
netOut.attachAudio(mic);
netOut.attachCamera(cam);
vidOut.attachCamera(cam);
netOut.publish(outStream, "live");
//Play streamed video
netIn=new NetStream(nc);
vidIn.attachNetStream(netIn);
netIn.play(inStream);
}
function setCam():void
{
cam=Camera.getCamera();
cam.setMode(240,180,15);
cam.setQuality(0,85);
}
function setMic():void
{
mic=Microphone.getMicrophone();
mic.rate=11;
mic.setSilenceLevel(12,2000);
}
function setVid():void
{
vidOut=new Video(240,180);
addChild(vidOut);
vidOut.x=25;
vidOut.y=110;
vidIn=new Video(240,180);
addChild(vidIn);
vidIn.x=vidOut.x+260;
vidIn.y=110;
}
RED5 PROPERTIES FILE
--------------------
webapp.contextPath=/Test1
webapp.virtualHosts=localhost, localhost:5080
RED5 WEB XML FILE
-----------------
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:lang="http://www.springframework.org/schema/lang"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.0.xsd">
<bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="/WEB-INF/red5-web.properties" />
</bean>
<bean id="web.context" class="org.red5.server.Context" autowire="byType" />
<bean id="web.handler" class="com.Application" />
<bean id="web.scope" class="org.red5.server.scope.WebScope" init-method="register">
<property name="server" ref="red5.server" />
<property name="parent" ref="global.scope" />
<property name="context" ref="web.context" />
<property name="handler" ref="global.handler" />
<property name="contextPath" value="${webapp.contextPath}" />
<property name="virtualHosts" value="${webapp.virtualHosts}" />
</bean>
</beans>
RED5 WEB XML FILE
-----------------
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns
/j2ee/web-app_2_4.xsd"
version="2.4">
<display-name>Test1</display-name>
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>/Test1</param-value>
</context-param>
<listener>
<listener-class>org.red5.logging.ContextLoggingListener</listener-class>
</listener>
<filter>
<filter-name>LoggerContextFilter</filter-name>
<filter-class>org.red5.logging.LoggerContextFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>LoggerContextFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<security-constraint>
<web-resource-collection>
<web-resource-name>Forbidden</web-resource-name>
<url-pattern>/streams/*</url-pattern>
</web-resource-collection>
<auth-constraint/>
</security-constraint>
</web-app>
The issues is that the "numbers" are not coming to the server as the expected type of "double". There are several solutions to this:
Change the parameter type on your addSomething method to int.
Send your parameters from the client with a decimal point (2.0 vs 2)
Following is my test file :
package test;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
public class TestWatcherTest
{
#Rule
public TestWatcher testWatcher = new TestWatcher()
{
protected void failed(Throwable e, Description description)
{
System.out.println("in failed()");
}
};
#Test
public void shouldFail()
{
Assert.assertTrue("Test failed", false);
}
}
Output is :
<failure message="Test failed" type="junit.framework.AssertionFailedError">junit.framework.AssertionFailedError: Test failed at test.TestWatcherTest.shouldFail(TestWatcherTest.java:24)
</failure>
It seems failed() is not being executed. I read many posts but nothing seems to work for me. What am I doing wrong?
The issue was with ant configuration. From http://testautomationusingjunit.blogspot.com/2013/08/applying-rules-to-junit-tests-running.html, the target needs to be edited to contain JUnitCore in the classpath.
<target name="junit" depends="build">
<java classname="org.junit.runner.JUnitCore">
<classpath>
<path location="selenium_server/selenium-server-standalone-xxx.xx.jar"/>
</classpath>
</java>
<junit fork="no" haltonfailure="no" printsummary="true" failureProperty="test.failed" dir=".">
<test name="src.SampleTest" todir="./report" />
</junit>
</target>
I am studying spring framework and trying to use it in my project. But I have came across the following problem with spring data repository and #Transactional annotation used in my service. The problem is that there are no exceptions on the spring start up. Later on when I try to access spring data repository I get NullPointerException. Maybe you have some thoughts that could help me.
I am using spring data repository define as following:
package net.question.data.repository;
import net.question.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
}
Then I have a service defined which contains autowired repository:
package net.question.data.service;
import net.question.data.repository.UserRepository;
import net.question.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
#Service
#Transactional
public class UserService {
#Autowired
public UserRepository userRepository;
public void doStuff(User usr) {
// login will be here
}
}
here is the test to show my problem:
package net.question.spring;
import static org.junit.Assert.assertNotNull;
import net.question.data.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration("/app-context.xml")
public class InjectionTestSuite {
#Autowired
UserService userService;
#Test
public void testRepositoryInjection() {
assertNotNull(userService);
assertNotNull(userService.userRepository);
}
}
The test fails on the follwowing line:
assertNotNull(userService.userRepository);
If I remove the #Transactional annotation on the service then the test passes.
here is my app-context.xml file:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd ">
<jpa:repositories base-package="net.question.data.repository" />
<!-- For discovering entity services -->
<context:component-scan base-package="net.question.data.service" />
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="hibernate_mysql" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven />
</beans>
Maybe you have some ideas, how to find the error?