understanding AMFChannel in flex and message broker - apache-flex

I need to use AMFChannel in order to connect to RemoteObject in flex tried searching a lot but couldn;t get source to understand the two parameters being passed to the constructor ... I am using spring framework as a backend for my GUI created using flex .... canm some one explain me this integration of flex with spring or guide me to a proper resource to understand it... through which I can understand the overall scenerio... or atleast understand how this call is being made using message broker . PLEASE SOME ONE HELP ME BY TELLING ME WHAT IS THE MEANING OF URL WE ARE PASSING TO THE AMF CHANNEL CONSTRUCTOR

This link might help some one.
The MessageBroker transparently handles the process of serialization and deserialization between the Flex AMF data format and Java.
This link explains everything with help of example which was exactly what I was looking for
some important setup information is as follows
Server side has following files
* testdrive/src/main/webapp/WEB-INF/spring/app-config.xml
* testdrive/src/main/webapp/WEB-INF/flex-servlet.xml
* testdrive/src/main/java/flex/spring/samples/product/ProductDAO.java
Client side has one file which looks like this
Step1) Initialize a messagebroker in flex-servlet.xml
<flex:message-broker>
<flex:message-service
default-channels="my-streaming-amf,my-longpolling-amf,my-polling-amf" />
<flex:secured />
</flex:message-broker>
Step2) In the same flex-servlet.xml specify one tag
<flex:remoting-destination ref="productService" />
Step 3) In app-config.xml
<bean id="contactService" class="org.springframework.flex.samples.product.ProductDAO">
<constructor-arg ref="dataSource" />
</bean>
Step 4) ProductDAO.java is the class which will exposed for the remoting
Client side can call the remote object as follows
Step 5)
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<!-- "productService" is defined in Spring's configuration file WEB-INF/config/web-application-config.xml
and provides remote access to the org.springframework.flex.samples.product.ProductDAO class -->
<mx:RemoteObject id="ro" destination="productService"/>
<mx:DataGrid dataProvider="{ro.findAll.lastResult}" width="100%" height="100%"/>
<!-- the findAll() method is defined in org.springframework.flex.samples.product.ProductDAO -->
<mx:Button label="Get Data" click="ro.findAll()"/>
</mx:Application>

Related

WSO2AM Mediator with conditional properties

We are trying to add an API to WSO2AM which has the problem, that we need to add (invisible for users) an Authorization Key.
We are able to add it using Mediator with that configuration:
<sequence xmlns="http://ws.apache.org/ns/synapse" name="Add_Fahrplan_AuthKey">
<property name="REST_URL_POSTFIX"
expression="fn:concat(get-property('axis2','REST_URL_POSTFIX'),
'&authKey=**HERE_IS_THE_SECRET**')"
scope="axis2"
type="STRING"/>
</sequence>
We have 4 get methods
/location
/departure
/arrival
/journeyDetails <-- needs an different AuthKey
But for the fourth get method journeyDetails we need to add the AuthKey in a different way with different characters.
Is it possible to do that in a Mediator configuration? And in case of yes, how can we do it?
Please keep in mind that we are not very familiar with synapse configuration syntax. We tried
value="/location"
but it resulted in an AM-error while invoking the API and we tried
<filter> with <then> and <else>
which resulted again in an AM error.
Thanks for any help

How to use WAS standard persistence provider with Spring

I'm developing a portlet which runs in WebSphere Application Server ( - I accept the same problem to appear if it was a servlet instead of a portlet). At the moment it depends on Hibernate. As WAS provides a JPA implementation itself, which is a modified version of OpenJPA 2.0, I want to get rid of Hibernate.
This is my setup. persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
>
<persistence-unit name="default" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/myDb</jta-data-source>
<properties>
<property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.WebSphereExtendedJtaPlatform" />
<property name="hibernate.dialect" value="org.hibernate.dialect.DB2Dialect" />
</properties>
</persistence-unit>
</persistence>
myPortlet-portlet.xml
<!-- ... -->
<tx:jta-transaction-manager />
<jee:jndi-lookup jndi-name="jdbc/myDb" cache="true" id="dataSource" expected-type="javax.sql.DataSource" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="default" />
</bean>
In my DAO-classes I access the entityManager by using annotations:
#PersistenceContext(unitName = "default")
private EntityManager entityManager;
Everything works fine using Hibernate.
According to WebSphere Application Server docs, the default persistence provider is used if you don't specify it by using the <provider/>-tag in persistence.xml. But after commenting out the provider specification, Spring throws an exception due not being able to find the provider-class:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in PortletContext resource [/WEB-INF/myPortlet-portlet.xml]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: No PersistenceProvider specified in EntityManagerFactory configuration, and chosen PersistenceUnitInfo does not specify a provider class name either
How can I use the provided JPA implementation together with Spring (Portlet) MVC?
Short answer
You cannot use WebSphere's default provider by omitting the provider, if you want to use LocalContainerEntityManagerFactoryBean.
Long answer
Normally an entity manager is created by an entity manager factory provided by the container. You retrieve it by doing a context loopkup (EntityManager em = (EntityManager) ctx.lookup(...)) manually or use Springs jndi-lookup capability:
<beans>
<jee:jndi-lookup id="myEmf" jndi-name="persistence/myPersistenceUnit"/>
</beans>
In the question, a different approach is used, a LocalContainerEntityManagerFactoryBean, which creates an entity manager factory itself. This entity manager factory is a proxy that implements all the interfaces of the native entity manager factory. For creating such a proxy, Spring must know the class of the native entity manager factory. Spring uses three different ways to determine the class:
Detect it by the <provider/>-entry in persistence.xml
Asking a jpaVendorAdapter (specified in the equally named property of the factory bean)
Using the entityManagerFactoryInterface-property of the factory bean
And that's why you cannot completely omit the specification of your provider.
This is most likely happening because the Spring JAR(s) that you include with your application contains a different implementation of the Persistence class, or other JPA classes, used to "bootstrap" JPA.
If you'd like to use WebSphere's default provider (or, more precisely, to use whichever JPA provide configured through WebSphere's administration screens), then you must ensure that the JPA "bootstrapping" code being called during runtime is WebSphere's, not yours.
You should look for a Spring distribution JAR that doesn't mess with JPA.

Can't create CSRF token with Spring Security

I am using Spring Security 3.2.3 in my Spring MVC application and getting some unexpected behavior.
According to the documentation here, it should be possible to use ${_csrf.token} in the meta tags of my html:
<meta name="_csrf" content="${_csrf.token}" />
<!-- default header name is X-CSRF-TOKEN -->
<meta name="_csrf_header" content="${_csrf.headerName}" />
From where I extract the value of "content" using JQuery and place it into the Request Header using AJAX.
For some reason though, Spring Security doesn't "convert" this into an actual token, it just gets sent into the header as a literal string "${_csrf.token}".
Trying the alternate route of using ${_csrf.token} in a hidden input according to the documentation, I then tried to check what the token evaluates to by checking the input's value, but it's still just plain text "${_csrf.token}".
Since it seems that Spring Security isn't in effect, am I missing some kind of configuration? I am currently using a barebones Spring Security Java configuration (as opposed to xml) as shown here:
import org.springframework.context.annotation.*;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.*;
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf();
}
}
I know configure is getting called since I put a debug statement in it, so I assume that CSRF protection is indeed enabled since it should be by default.
I realize that the syntax "${}" is JSP Expression Language, and I am currently successfully using it to evaluate the context into an object with Thymeleaf, for example:
th:object="${context}"
So I tried adding "th:" in front of the meta tag's "content" like so:
<meta name="_csrf" th:content="${_csrf.token}"/>
But it results in an exception that this cannot be evaluated:
Exception evaluating SpringEL expression: "_csrf.token"
I think the key here may be figuring out how to get the expression to evaluate properly in my view.
I finally solved this problem, but it basically required rewriting Spring Security. Here it is in all its glory.
First, I followed the suggestions in Eyal Lupu's great blog post here, but I had to tweak it to my situation because of my AJAX requirement.
As for the Thymeleaf situation, the key tidbit is hidden away in the archives of the Thymeleaf forums - Infamous Issue 7.
https://github.com/thymeleaf/thymeleaf-spring/issues/7#issuecomment-27643488
The last comment by the creator of Thymeleaf himself says that:
th:action ... detects when this attribute is being applied on a
tag --which should be the only place, anyway--, and in such case
calls RequestDataValueProcessor.getExtraHiddenFields(... ) and adds the
returned hidden fields just before the closing tag.
That was the key phrase I needed to get the token to work. Unfortunately it's completely not obvious why th:action would also kick off getExtraHiddenFields, but at any rate it does, and that's what matters.
So for anyone struggling with Thymeleaf + Spring Security CSRF + AJAX POST, here are my steps (this is paring it down quite a bit but these are the high-level concepts to solve it):
Implement the Spring interface RequestDataValueProcessor and register it in Spring Security's XML config so you can override the method getExtraHiddenFields, which allows you to insert a hidden input field into the HTML (with the token of course). The token itself is generated with a Java.Util UUID.
With JQuery, read the value from that hidden field and set the Request Header's "X-CSRF-Token" attribute so that it gets sent over HTTP. It's not possible to simply leave the token in the hidden input field because we are not doing a form Submit, instead we use AJAX POST to call methods on the server side.
Extend Spring's HandlerInterceptorAdapter and register it as an interceptor so that every time a POST method is done, the "preHandle" method on the server side is called so it can compare the request token (extracted from the HTTP header in the previous step) to the session's token (should be the same!). After it does this check, it can either allow the request to go through or return an error.
I started with the same source article as you, I think, and the same "you should be able to" add answers as you did. I fought it a different way. I made Thymeleaf give me the answer I wanted.
<meta name="_csrf" th:content="${_csrf.token}"/>
<!-- default header name is X-CSRF-TOKEN -->
<meta name="_csrf_header" th:content="${_csrf.headerName}"/>
Thymeleaf put the attribute "content" with the requested Spring EL contents. I then used the provided JavaScript/JQuery to extract the info from the meta tags straight into the CSRF header.
Before adding the thymeleaf-extras-springsecurity namespace and its dependency into my project, I had similar problems. I never did get the meta tags to work, even with thymeleaf-extras-springsecurity. But I did successfully retrieve Spring Security's csrf token using the hidden input. I have instructions below that work for me:
In the html tag, add:
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"
In your pom.xml (if you're using Maven) you'll need to add the dependency: thymeleaf-extras-springsecurity4.
Then add the hidden input inside your page's body to retrieve the csrf token.
<input type="hidden" id= "csrf-token" th:name="${_csrf.parameterName}" th:content="${_csrf.token}" />
and then use that within your javascript/jquery as follows:
function f1() {
var token1 = $('input#csrf-token').attr("content");
...
$.ajax({
...
type: "POST",
beforeSend: function (request)
{
request.setRequestHeader("X-CSRF-TOKEN", token1);
},
...
This all assumes that you have spring security enabled, and that you have NOT turned off csrf protection.
You have incorrect configuration for springSecurityFilterChain in your web.xml. Correct definition is:
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
Spring Security uses set of servlet filters to provide the functionality it is offering (including CSRF protection). These filters are defined as Spring beans (i.e. they are instantiated and managed by Spring application context). DelegatingFilterProxy is a special type of servlet filter, which finds root application context on the registered servlet context and delegates every call to the same named bean.
Your issue is a different one, just stumbled across this one as well and it took me several hours to figure out the cause. The cause for the issue described by you is that you did not enable csrf support within your spring-security.xml
This little snippet needs to go into your security-config.xml:
<!-- Static resources such as CSS and JS files are ignored by Spring Security -->
<security:http pattern="/static/**" security="none" />
<security:http use-expressions="true">
<!-- Enables Spring Security CSRF protection -->
<security:csrf/>
<!-- Configures the form login -->
<security:form-login
login-page="/login"
login-processing-url="/login/authenticate"
authentication-failure-url="/login?error=bad_credentials"
username-parameter="username"
password-parameter="password"/>
<!-- Configures the logout function -->
<security:logout
logout-url="/logout"
logout-success-url="/login"
delete-cookies="JESSIONID"/>
<!-- Anyone can access these urls -->
<security:intercept-url pattern="/auth/**" access="permitAll"/>
<security:intercept-url pattern="/login" access="permitAll"/>
<security:intercept-url pattern="/signin/**" access="permitAll"/>
<security:intercept-url pattern="/signup/**" access="permitAll"/>
<security:intercept-url pattern="/user/register/**" access="permitAll"/>
<!-- The rest of our application is protected. -->
<security:intercept-url pattern="/**" access="hasRole('ROLE_USER')"/>
<!-- Adds social authentication filter to the Spring Security filter chain. -->
<security:custom-filter ref="socialAuthenticationFilter" before="PRE_AUTH_FILTER" />
</security:http>
....
...
..
.
Save time by configuring this correctly...
Cheerio,
Flo!
In case you don't need to use Thymeleaf, I'd suggest the following:
Add this to the top of your page:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
Add this to your login form:
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
Add these dependencies to your pom.xml:
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
After struggling a lot, that worked for me.

how to call java method from actionscript

I've just now started working on Flex. May be its basic question but I’m not aware of it – how can I call a java method from actionscript. I want to call some java method on double click of a event. Can you please let me know how to proceed on this?
In Flash Builder, under the Data menu, there are data service wizards:
These wizards auto-generate code and are convenient for connecting to WSDL:
Or HTTP Services:
Accessing data services overview has example implementations, such as this example calling a restaurant web service with responder returning value objects from service.
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/halo"
xmlns:employeesservice="services.employeesservice.*"
xmlns:valueObjects="valueObjects.*">
<fx:Declarations>
<s:WebService id="RestaurantSvc"
wsdl="http://examples.adobe.com/flex3app/restaurant_ws/RestaurantWS.xml?wsdl" />
<s:CallResponder id="getRestaurantsResult"
result="restaurants = getRestaurantsResult.lastResult as Restaurant" />
</fx:Declarations>
<fx:Script>
<![CDATA[
import mx.controls.Alert;
protected function b1_clickHandler(event:MouseEvent):void
{
getRestaurantsResult.token = RestaurantWS.getRestaurants();
}
]]>
</fx:Script>
<s:Button id="b1"
label="GetRestaurants"
click="button_clickHandler(event)" />
</s:Application>
References:
Accessing data services overview
Building data-centric applications with Flash Builder
Use the Data Services wizard to connect to a service

ASP.Net Web Service - What is the correct way to add a detail element to a SOAP fault response that works for both SOAP 1.1 and SOAP 1.2?

ASP.Net 2.0 Web Services automatically create both SOAP 1.1 and SOAP 1.2 bindings. Our web service, however, has SOAP extensions and custom exception handling that make the assumption that only the SOAP 1.1 binding is used (for example, the SOAP extension uses the HTTP SOAPAction header to control behavior).
I am looking to correct the code that makes these assumptions and make it work with either SOAP 1.1 or SOAP 1.2 properly. I am running into a bit of a problem in the generation of elements for our SOAP faults.
Consider the following web method implementation:
[WebMethod]
public void
ThrowsSoapException()
{
throw new SoapException("This is a SOAP exception.", SoapException.ServerFaultCode);
}
Invoking this via SOAP 1.1 yields the following result:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<soap:Fault>
<faultcode>soap:Server</faultcode>
<faultstring>This is a SOAP exception.</faultstring>
<detail/>
</soap:Fault>
</soap:Body>
</soap:Envelope>
Invoking via SOAP 1.2 yields the following result:
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<soap:Fault>
<soap:Code>
<soap:Value>soap:Receiver</soap:Value>
</soap:Code>
<soap:Reason>
<soap:Text xml:lang="en">This is a SOAP exception.</soap:Text>
</soap:Reason>
<soap:Detail/>
</soap:Fault>
</soap:Body>
</soap:Envelope>
In both these cases there is an empty detail element as a child of the <soap:Fault> element, but it has a different qualified name, either <detail> or <soap:Detail>.
Now consider the following code that tries to create a SOAPException with a detail element.
[WebMethod]
public void
ThrowsSoapExceptionWithDetail()
{
XmlDocument doc = new XmlDocument();
XmlNode detail =
doc.CreateNode(XmlNodeType.Element, SoapException.DetailElementName.Name, SoapException.DetailElementName.Namespace);
XmlNode custom =
doc.CreateNode(XmlNodeType.Element, "custom", "http://example.com/xml/namespace/blah");
custom.InnerXml = "Detail value";
detail.AppendChild(custom);
throw new SoapException("This is a SOAP exception with a detail element.", SoapException.ServerFaultCode, Context.Request.Url.AbsoluteUri, detail);
}
The SOAP 1.1 response is:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<soap:Fault>
<faultcode>soap:Server</faultcode>
<faultstring>This is a SOAP exception with a detail element.</faultstring>
<faultactor>http://localhost/simplewebservice/service1.asmx</faultactor>
<detail>
<custom xmlns="http://example.com/xml/namespace/blah">Detail value</custom>
</detail>
</soap:Fault>
</soap:Body>
</soap:Envelope>
and the SOAP 1.2 response is:
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<soap:Fault>
<soap:Code>
<soap:Value>soap:Receiver</soap:Value>
</soap:Code>
<soap:Reason>
<soap:Text xml:lang="en">This is a SOAP exception with a detail element.</soap:Text>
</soap:Reason>
<soap:Node>http://localhost/simplewebservice/service1.asmx</soap:Node>
<detail>
<custom xmlns="http://example.com/xml/namespace/blah">Detail value</custom>
</detail>
</soap:Fault>
</soap:Body>
</soap:Envelope>
The SOAP 1.2 response now has the wrong qualified name for the detail element. It should be <soap:Detail>, but instead is merely <detail>, same as the SOAP 1.1 response.
It seems that the ASP.Net 2.0 framework has done quite a bit to transform a SOAPException into the appropriate form for the SOAP version, but neglected to properly handle the detail element. Additionally, they don't seem to have exposed the correct SOAP 1.2 qualified name for the detail element as was done with the SoapException.DetailElementName property.
So, what is the correct way to add a detail element to a SOAP fault response that works for both SOAP 1.1 and SOAP 1.2? Do I need to detect the SOAP version myself and hard-code the SOAP 1.2 qualified name for the detail element?
No idea about the coding part of your question, sorry, but a workaround wound be to disable the soap1.2 in your web.config, if you haven't already look that way.
....
<webServices>
<protocols>
<remove name="HttpSoap12"/>
</protocols>
</webServices>
The following is not meant to be snide:
The fix to this problem is to use WCF.
This looks like a bug in ASMX web services handling of the detail element in a SOAP 1.2 fault. It obviously makes no sense for the qualified name of the element to change based on whether or not the element has a value.
You could report this error on Connect, but since only critical ASMX bugs are being fixed, that's unlikely to help you.
I doubt that WCF has this problem, since it fully supports SOAP Faults.
This is a late answer, but since I've ran into the issue myself I thought I might as well put my solution here, which is essentially to pass along the version of the SOAP protocol to the method that builds the detail section of the fault message.
The WebService class from which an ASMX web service class is derived exposes the SoapVersion property, which contains the version of the SOAP protocol used to make the current SOAP request.
A detail section appropriate for the current SOAP version can then be built easily.
using System.Xml.Linq;
XNamespace detailElementNamespace;
string detailElementName;
if (soapVersion == SoapProtocolVersion.Soap12)
{
detailElementNamespace = "http://www.w3.org/2003/05/soap-envelope";
detailElementName = "Detail";
}
else
{
detailElementNamespace = "";
detailElementName = "detail";
}
var document = new XmlDocument();
document.LoadXml(
new XElement(detailElementNamespace + detailElementName,
new XElement("MySection",
new XElement("MyCode", "..."),
new XElement("MyDescription", "...")
)).ToString());
throw new SoapException(
"MESSAGE",
SoapException.ClientFaultCode,
"ACTOR",
document.DocumentElement);

Resources