Red5 Live Streaming using Air to IOS client - air

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)

Related

JAX-RS writer interceptor works for every response even with NameBinding

I need to intercept a response from the server that was generated for a specific API call and change it.
I used the JAX-RS 'WriterInterceptor' for this and I have created a NameBinding as well. But the server is intercepting every response out from the server. What am I doing wrong here?
Shown below is the code I have tried. Why is the name binding does not work? (I have verified that when calling other API resources the particular method that I have use name binding is not called.)
Name Binding.
package com.example.common.cm.endpoint;
#Target({ElementType.TYPE, ElementType.METHOD})
#NameBinding
#Retention(RetentionPolicy.RUNTIME)
public #interface JSONtoJWT {}
The Interceptor.
package com.example.common.cm.endpoint;
#Provider
#JSONtoJWT
public class TestInterceptor implements WriterInterceptor {
private static final Log log = LogFactory.getLog(TestInterceptor.class);
#Override
public void aroundWriteTo(WriterInterceptorContext writerInterceptorContext) throws IOException, WebApplicationException {
log.info("interceptor invoked");
OutputStream outputStream = writerInterceptorContext.getOutputStream();
outputStream.write(("{\"message\": \"Message added in the writer interceptor in the server side\"}").getBytes());
writerInterceptorContext.setOutputStream(outputStream);
writerInterceptorContext.proceed();
log.info("Proceeded");
}
}
API Resource.
package com.example.cm.endpoint.u3.acc;
#Path("/u3/some-validation")
#Consumes({ "application/json; charset=utf-8" })
#Produces({ "application/json; charset=utf-8" })
public class SomeValidationApi {
#POST
#Path("/")
#JSONtoJWT
#Consumes({ "application/json; charset=utf-8" })
#Produces({ "application/json; charset=utf-8" })
public Response someValidationPost(#ApiParam(value = "validations post" ,required=true ) SomeValidationRequestDTO someValidationConsent)
{
return delegate.someValidationPost(someValidationConsent);
}
}
beans.xml
<?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:jaxrs="http://cxf.apache.org/jaxrs" 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.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
<import resource="classpath:META-INF/cxf/cxf.xml"/>
<context:property-placeholder/>
<context:annotation-config/>
<bean class="org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer"/>
<bean class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer"/>
<jaxrs:server id="services" address="/">
<jaxrs:serviceBeans>
***Some other beans here***
<bean class="com.example.cm.endpoint.u3.acc.SomeValidationApi/>
</jaxrs:serviceBeans>
<jaxrs:providers>
<bean class="com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider"/>
<bean class="com.example.common.cm.endpoint.TestInterceptor"/>
</jaxrs:providers>
</jaxrs:server>
</beans>
When I use the above every response from the server is intercepted and the message is added. But I want only the particular resource to invoke the Interceptor.
Also, Other than JAX-RS interceptor with writerInterceptor, are there any other good alternative to achieve this?

Arquillian - How to debug managed Wildfly container

I am using Arquillian to write black box tests for my RESTful application. I am actually capable of debug the test classes, but unable to debug my application classes. I would like to know exactly how to do that.
My arquillian.xml:
<arquillian xmlns="http://jboss.org/schema/arquillian"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://jboss.org/schema/arquillian
http://jboss.org/schema/arquillian/arquillian_1_0.xsd">
<container qualifier="jbossas-managed" default="true">
<configuration>
<property name="jbossHome">D:\desenv\arquivos\servidores\wildfly-9.0.1.Final-test</property>
<property name="allowConnectingToRunningServer">true</property>
<property name="javaVmArguments">-Dorg.apache.deltaspike.ProjectStage=IntegrationTest</property>
</configuration>
</container>
One of my test classes:
#RunAsClient
#RunWith(Arquillian.class)
public class AuthenticationBlackBoxTest extends AbstractBlackBoxTest {
#Test
public void testInvalidCredentials(#ArquillianResource URL baseURI) {
Client client = ClientBuilder.newClient();
WebTarget target = client.target(baseURI.toString()).path("api/v1/auth");
Response response = target.request(MediaType.APPLICATION_JSON)
.post(Entity.entity(new Credentials("invalid", "invalid"), MediaType.APPLICATION_JSON));
Assert.assertEquals(401, response.getStatus());
response.close();
client.close();
}
#Test
public void testValidCredentials(#ArquillianResource URL baseURI) {
Client client = ClientBuilder.newClient();
WebTarget target = client.target(baseURI.toString()).path("api/v1/auth");
Entity<Credentials> credentialsEntity = Entity.entity(new Credentials("adm#adm.com", "123"), MediaType.APPLICATION_JSON);
Response response = target.request(MediaType.APPLICATION_JSON)
.post(credentialsEntity);
Assert.assertEquals(200, response.getStatus());
response.close();
client.close();
}
}
Inside arquillian.xml for javaVmArguments element add -Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=y.
Then in your favourite IDE you have to define a new Remote Debug configuration where you specify the host(localhost), port(8787). Place your break point, then run your test and finally start the remote debug. Official doc here.

Creating a Junit test that tests conection to SQL Server

I am having a great deal of difficulty in either understanding what I am doing wrong or missing something fundamental. I have searched for my problem for a day or so and not understanding what I am missing.
So what I am trying to do is Create a JUnit test that connects to my SQL server and does a query to get the current time. My connection to the server works and I have tested my SQL code in the Query on the server and works perfectly. For some reason the test isn't sending my code and getting anything returned.. Not sure what Ive done wrong an if this is too extensive for this form(little new to this)
#Override
public Timestamp PCNow() throws PCSQLException {
//SQL Server uses GETDATAE
String strSQL = "SELECT GETDATE()";;
try {
//Get a result set with the timestamp field
Timestamp datTs = (Timestamp)jdbcTemplate.queryForObject( strSQL, Timestamp.class );
//Make sure there is a result
if ( datTs == null )
//Throw an exception indicating the server could not give a time
throw new PCSQLException( "UNABLE_SERVER_TIME" );
return datTs;
}
catch (Exception e) {
throw new PCSQLException( "This didn't work PCNow", e );
}
}
This is my Test class
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = {"classpath:applicationContext-sql.xml"} )
//instantiate TestExecutionListener class
#TestExecutionListeners
public class ConnectionAdapterSQLTest {
#Autowired
ConnectionAdapterImpl connectionAdapterPC;
private final Log log = LogFactory.getLog( getClass() );
#Before
public void setUp() throws Exception {
}
/**
* #throws java.lang.Exception
*/
#After
public void tearDown() throws Exception {
}
#Test
public final void testPCNow() {
log.info("testPCNow()");
//fail("Not yet implemented");
}
applicationContext-sql.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- connection to Sql Server using JDBC sqljdbc4.2 -->
<bean id="dataSourcePC" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
<property name="url" value="jdbc:sqlserver://******;databaseName=******" />
<property name="username" value="******" />
<property name="password" value="******" />
</bean>
<bean id="connectionAdapterPC"
class="com.*******.*******.connections.ConnectionAdapterSQL">
<property name="dataSource" ref="dataSourcePC" />
<property name="useConnectionPool" value="false" />
</bean>
<bean id="dxDateTimeFormatter" class="com.*******.*******.data.format.DateTimeFormatter">
<property name="dateFormat" value="dd-MMM-yyyy" />
</bean>
</beans>
Matt, you are logging the String "testPCNow()" not invoking the method PCNow().
So replace the test method:
#Test
public void testPCNow() {
log.info(new TheClassThatContainsTestPCNowMethod().PCNow());
}
Remember replacing TheClassThatContainsTestPCNowMethod with a valid constructor of the class that contains the method PCNow().

Optional Resources in Spring.Net

How to include Spring configuration files optionally? I think about something simular to this:
<spring>
<context>
<resource uri="file:///Objects/RequiredObjects.xml" />
<resource uri="file:///Objects/OptionalObjects.xml" required="false" />
</context>
This way I could provide developers the possibility to override some configuration parts (e.g. for a local speed improvement or automatism during app startup) without affecting the app.config and the problem that a developer could checkin his modified file when it is not really his intent to change the config for all.
Not as simple as in AutoFac (because there is already a builtin way) but possible to achieve something similar with a little coding:
using System.IO;
using System.Xml;
using Spring.Core.IO;
public class OptionalFileSystemResource : FileSystemResource
{
public OptionalFileSystemResource(string uri)
: base(uri)
{
}
public override Stream InputStream
{
get
{
if (System.IO.File.Exists(this.Uri.LocalPath))
{
return base.InputStream;
}
return CreateEmptyStream();
}
}
private static Stream CreateEmptyStream()
{
var xml = new XmlDocument();
xml.LoadXml("<objects />");
var stream = new MemoryStream();
xml.Save(stream);
stream.Position = 0;
return stream;
}
}
Register a section handler:
<sectionGroup name="spring">
...
<section name="resourceHandlers" type="Spring.Context.Support.ResourceHandlersSectionHandler, Spring.Core"/>
...
</sectionGroup>
...
<spring>
<resourceHandlers>
<handler protocol="optionalfile" type="MyCoolStuff.OptionalFileSystemResource, MyCoolStuff" />
</resourceHandlers>
...
<context>
<resource uri="file://Config/MyMandatoryFile.xml" />
<resource uri="optionalfile://Config/MyOptionalFile.xml" />
...
You'll find more information about resources and resource handlers in the Spring.Net documentation.

How to Define Prototype Interceptors with DefaultAdvisorAutoProxyCreator in Spring.NET

I am new to Spring.NET and am just playing around trying different things out. As part of my testing, I created a simple object:
public interface ICommand {
void Execute(object context);
}
with one implementation:
public class ServiceCommand : ICommand {
public ServiceCommand() {
Console.WriteLine("########## {0} ##########", GetType().Name);
}
public void Execute(object context) {
Console.WriteLine("Service implementation: {0}.{1}", GetType().Name, MethodBase.GetCurrentMethod().Name);
}
}
Finally, I've a simple before advice as follows:
public class ConsoleLoggingBeforeAdvice : IMethodBeforeAdvice {
public ConsoleLoggingBeforeAdvice() {
Console.WriteLine("########## {0} ##########", GetType().Name);
}
public void Before(MethodInfo method, object[] args, object target) {
Console.WriteLine("Intercepted call to this method: {0}", method.Name);
Console.WriteLine(" The target is : {0}", target);
Console.WriteLine(" The arguments are : ");
if (args != null) {
foreach (object arg in args) {
Console.WriteLine("\t: {0}", arg);
}
}
}
}
As you can see, much of this stuff is from the Spring.NET quick start samples.
So, I configured the ServiceCommand to be wrapped in a ConsoleLoggingBeforeAdvice via ProxyFactoryObject and marked both the objects as prototype (see config below). This works as expected: each time we request a ServiceCommand, a new instance of both the object and associated interceptor is created:
<?xml version="1.0" encoding="utf-8"?>
<objects xmlns="http://www.springframework.net">
<object id="ConsoleLoggingBeforeAdvice" type="Spring.Aop.Support.DefaultPointcutAdvisor" singleton="false">
<property name="Advice">
<object type="Spring.Examples.AopQuickStart.ConsoleLoggingBeforeAdvice"/>
</property>
</object>
<object id="ServiceCommandTarget" type="Spring.Examples.AopQuickStart.ServiceCommand" singleton="false"/>
<object id="ServiceCommand" type ="Spring.Aop.Framework.ProxyFactoryObject">
<property name="IsSingleton" value="false"/>
<property name="TargetName" value="ServiceCommandTarget"/>
<property name="InterceptorNames">
<list>
<value>ConsoleLoggingBeforeAdvice</value>
</list>
</property>
</object>
</objects>
However, when I try to achieve the same results via DefaultAdvisorAutoProxyCreator, everything works except that the interceptor is always created as Singleton (even though it's configured as singleton="false"). The config is as follows:
<?xml version="1.0" encoding="utf-8"?>
<objects xmlns="http://www.springframework.net">
<object id="ConsoleLoggingBeforeAdvice" type="Spring.Aop.Support.DefaultPointcutAdvisor" singleton="false">
<property name="Advice">
<object type="Spring.Examples.AopQuickStart.ConsoleLoggingBeforeAdvice"/>
</property>
</object>
<object id="ServiceCommand" type="Spring.Examples.AopQuickStart.ServiceCommand" singleton="false"/>
<object type="Spring.Aop.Framework.AutoProxy.DefaultAdvisorAutoProxyCreator"/>
</objects>
Now, how can I ensure that both the object and associated interceptor are treated as prototypes by DefaultAdvisorAutoProxyCreator?
OK, I've figured out that setting InterceptorNames on DefaultAdvisorAutoProxyCreator will correctly instantiate interceptors as prototypes (if they're configured so). But this somehow feels incorrect as the DefaultAdvisorAutoProxyCreator should be able to pick interceptors from advisors and honor their configuration settings.
I am still not 100% clear on how to create prototype interceptors under different scenrarios. For example, all my attempts to create thread-scoped interceptors while using DefaultAdvisorAutoProxyCreator have failed.
Anyways, here's the xml config that works for me:
<?xml version="1.0" encoding="utf-8"?>
<objects xmlns="http://www.springframework.net" default-autowire="constructor">
<object id="ConsoleLoggingBeforeAdvice" type="Spring.Aop.Support.DefaultPointcutAdvisor" singleton="false">
<property name="Advice">
<object type="Spring.Examples.AopQuickStart.ConsoleLoggingBeforeAdvice"/>
</property>
</object>
<object id="ServiceCommand" type="Spring.Examples.AopQuickStart.ServiceCommand" singleton="false"/>
<object type="Spring.Aop.Framework.AutoProxy.DefaultAdvisorAutoProxyCreator">
<property name="InterceptorNames" value="ConsoleLoggingBeforeAdvice"/>
</object>
</objects>
I am totally confused with the idea of creating prototype interceptors. Are interceptors supposed to be or recommended to be prototypes at all or should they always be singletons?