I want to specify the location of a queue (queue manager & queue name) in my server configuration.
I have an MDB working with only the following;
the MDB:
#MessageDriven(name = "smis2/DelmeMDB"
, activationConfig = {
#ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
#ActivationConfigProperty(propertyName = "destination", propertyValue = "java:/jms/queue/CLQ"),
#ActivationConfigProperty(propertyName = "useJNDI", propertyValue = "true"),
#ActivationConfigProperty(propertyName = "transportType", propertyValue = "BINDINGS"),
#ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge")
}
, mappedName="java:/jms/queue/A"
)
#ResourceAdapter("wmq.jmsra.rar")
#TransactionAttribute(TransactionAttributeType.REQUIRED)
public class DelmeMDB implements MessageListener {
public DelmeMDB() {
}
#Override
public synchronized void onMessage(Message message) {
String msgStr = null;
try {
if (message instanceof BytesMessage) {
BytesMessage bm = (BytesMessage) message;
byte[] buf = new byte[(int)bm.getBodyLength()];
bm.readBytes(buf);
msgStr = new String(buf, "utf8");
} else if (message instanceof TextMessage) {
TextMessage txtMsg = (TextMessage) message;
msgStr = txtMsg.getText();
} else {
throw new EJBException("Unrecognized message type");
}
if (msgStr != null) {
System.out.printf("Got a message! %s%n", msgStr);
}
} catch (Exception e) {
throw new EJBException(e);
} finally {
}
}
}
And in my server config:
<subsystem xmlns="urn:jboss:domain:resource-adapters:1.0">
<resource-adapters>
<resource-adapter>
<archive>
wmq.jmsra.rar
</archive>
<transaction-support>XATransaction</transaction-support>
<connection-definitions>
<connection-definition class-name="com.ibm.mq.connector.outbound.ManagedConnectionFactoryImpl" jndi-name="java:/WMQCF" enabled="true" use-java-context="true" pool-name="WMQCF" use-ccm="true">
<config-property name="transportType">
${pnp.mq.transportType:BINDINGS}
</config-property>
<config-property name="queueManager">
${pnp.mq.queueManager:MB8QMGR}
</config-property>
<xa-pool>
<min-pool-size>1</min-pool-size>
<max-pool-size>5</max-pool-size>
<prefill>true</prefill>
<use-strict-min>true</use-strict-min>
<flush-strategy>FailingConnectionOnly</flush-strategy>
</xa-pool>
<validation>
<background-validation>false</background-validation>
<use-fast-fail>false</use-fast-fail>
</validation>
</connection-definition>
</connection-definitions>
<admin-objects>
<admin-object class-name="com.ibm.mq.connector.outbound.MQQueueProxy" jndi-name="java:/jms/queue/CLQ" enabled="true" use-java-context="false" pool-name="java:/jms/queue/CLQ">
<config-property name="baseQueueManagerName">
${pnp.mq.queueManager:MB8QMGR}
</config-property>
<config-property name="baseQueueName">
CLQ
</config-property>
</admin-object>
</admin-objects>
</resource-adapter>
</resource-adapters>
</subsystem>
Now this works as long as the queue manager I'm connecting to is the default queue manager on the system. I tried switching to a different local queue manager (not the default one) and it would not work even when the admin object was updated appropriately. At any rate, I'd prefer not to rely on a system-wide default and explicitly state the queue manager.
Alternatively, I can set useJNDI=false, and supply this in a jboss-ejb3.xml:
<message-driven>
<ejb-name>smis2/DelmeMDB</ejb-name>
<ejb-class>pnp.smis2.ejb.DelmeMDB</ejb-class>
<activation-config>
<activation-config-property>
<activation-config-property-name>transportType</activation-config-property-name>
<activation-config-property-value>${pnp.mq.transportType}</activation-config-property-value>
</activation-config-property>
<activation-config-property>
<activation-config-property-name>queueManager</activation-config-property-name>
<activation-config-property-value>${pnp.mq.queueManager}</activation-config-property-value>
</activation-config-property>
</activation-config>
</message-driven>
</enterprise-beans>
This works well, plus I can specify the full complement of activation spec options by using system property replacement. However it is difficult (impossible?) to use this scheme if I require structural changes to the jboss-ejb3.xml to deploy to my local, dev, qa & production environments.
How can I eliminate the jboss-ejb3.xml, and provide configuration by mixing node-specific items in standalone.xml (or domain.xml) and more generic options as #ActivationConfigProperys ?
Related
I have installed WMQ JMS resource adapter (9.0.4) to my JBOSS EAP 7 standalone-full.xml & created connection factory and admin object to it.
/subsystem=resource-adapters/resource-adapter=ibm-mq-resource-adapter:add(archive=wmq.jmsra-9.0.4.0.rar, transaction-support=NoTransaction)
/subsystem=resource-adapters/resource-adapter=ibm-mq-resource-adapter/admin-objects=queue-ao1:add(class-name=com.ibm.mq.connector.outbound.MQQueueProxy, jndi-name=java:jboss/outbound)
/subsystem=resource-adapters/resource-adapter=ibm-mq-resource-adapter/admin-objects=queue-ao1/config-properties=baseQueueName:add(value=TEST1)
/subsystem=resource-adapters/resource-adapter=ibm-mq-resource-adapter/admin-objects=queue-ao1/config-properties=baseQueueManagerName:add(value=TESTMANAGER)
Connection definition:
<connection-definition class-name="com.ibm.mq.connector.outbound.ManagedConnectionFactoryImpl" jndi-name="java:jboss/mqSeriesJMSFactoryoutbound" tracking="false" pool-name="mq-cd">
<config-property name="channel">
SYSTEM.DEF.XXX
</config-property>
<config-property name="hostName">
XX-XXX
</config-property>
<config-property name="transportType">
CLIENT
</config-property>
<config-property name="queueManager">
TESTMANAGER
</config-property>
<config-property name="port">
1414
</config-property>
</connection-definition>
In my understanding, If I post a message to the outbound queue from the connection factory mqSeriesJMSFactoryoutbound, I should be able to reach IBM MQ. I tried with below code to look up connection factory but I am getting naming notfound exception. Please help
public class TestQueueConnection {
// Set up all the default values
private static final String DEFAULT_MESSAGE = "Hello, World! successfull";
private static final String DEFAULT_CONNECTION_FACTORY = "java:jboss/mqSeriesJMSFactoryoutbound";
private static final String DEFAULT_DESTINATION = "java:jboss/outbound";
private static final String DEFAULT_MESSAGE_COUNT = "1";
private static final String DEFAULT_USERNAME = "jmsuser";
private static final String DEFAULT_PASSWORD = "jmsuser123";
private static final String INITIAL_CONTEXT_FACTORY = "org.jboss.naming.remote.client.InitialContextFactory";
private static final String PROVIDER_URL = "http-remoting://127.0.0.1:8070";
public static void main(String[] args) throws JMSException {
Context namingContext = null;
try {
String userName = System.getProperty("username", DEFAULT_USERNAME);
String password = System.getProperty("password", DEFAULT_PASSWORD);
// Set up the namingContext for the JNDI lookup
final Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
env.put(Context.PROVIDER_URL, System.getProperty(Context.PROVIDER_URL, PROVIDER_URL));
namingContext = new InitialContext(env);
// Perform the JNDI lookups
String connectionFactoryString = System.getProperty("connection.factory", DEFAULT_CONNECTION_FACTORY);
namingContext.lookup(connectionFactoryString);
QueueConnectionFactory connectionFactory = (QueueConnectionFactory)
JMSContext jmsContext = connectionFactory.createContext(DEFAULT_USERNAME, DEFAULT_PASSWORD);
Queue destination = (Queue) namingContext.lookup(DEFAULT_DESTINATION);
jmsContext.createProducer().send(destination, DEFAULT_MESSAGE);
System.out.println("><><><><><><>< MESSAGE POSTED <><><><><><><>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" );
} catch (NamingException e) {
e.printStackTrace();
} finally {
if (namingContext != null) {
try {
namingContext.close();
} catch (NamingException e) {
}
}
}
}
Made couple of changes to the above.
In connection-definition, instead of com.ibm.mq.connector.outbound.ManagedConnectionFactoryImpl, used ManagedQueueConnectionFactoryImpl to avoid class cast exception at runtime.
Connection factories created by RA are not accessible outside of its JVM. Written a servlet to access these connection factory. I am able to connect with below piece of code.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
Context namingContext = null;
String connectionFactoryString = "mqSeriesJMSFactoryoutbound";
String queueName = "outbound";
MessageProducer producer = null;
Session session = null;
Connection conn =null;
try {
namingContext = new InitialContext();
QueueConnectionFactory connectionFactory = (QueueConnectionFactory) namingContext.lookup(connectionFactoryString);
Queue destination = (Queue) namingContext.lookup(queueName);
conn = connectionFactory.createConnection();
session = conn.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
producer = session.createProducer(destination);
TextMessage message = session.createTextMessage();
message.setText(msg);
producer.send(message,
Message.DEFAULT_DELIVERY_MODE,
Message.DEFAULT_PRIORITY,
Message.DEFAULT_TIME_TO_LIVE);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
// Close the message producer
try {
if (producer != null) producer.close();
}
catch (JMSException e) {
System.err.println("Failed to close message producer: " + e);
}
// Close the session
try {
if (session != null) session.close();
}
catch (JMSException e) {
System.err.println("Failed to close session: " + e);
}
// Close the connection
try {
if(conn != null)
conn.close();
}
catch (JMSException e) {
System.err.println("Failed to close connection: " + e);
}
}
}
I am having trouble while sending the request to a rest service. The service works fine on my desktop, but getting the following error when i host on the IIS.
HTTP/1.1 400 Bad Request when i use https
HTTP/1.1 404 Not Found when i use http
Here is my web.config
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="webBinding">
<security mode="Transport">
</security>
</binding>
</webHttpBinding>
</bindings>
<services>
<service
behaviorConfiguration="CoreService.DialService.DialServiceBehavior"
name="CoreService.DialService.TelephonyService">
<endpoint behaviorConfiguration="webBehavior" binding="webHttpBinding"
bindingConfiguration="webBinding"
contract="CoreService.DialService.ITelephonyService"/>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="webBehavior">
<webHttp helpEnabled="true"/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="CoreService.DialService.DialServiceBehavior">
<serviceMetadata httpsGetEnabled="true" httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="webHttpBinding" scheme="http"/>
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true"/>
<diagnostics>
<messageLogging logEntireMessage="true" logMalformedMessages="true"
logMessagesAtServiceLevel="true" logMessagesAtTransportLevel="true"
maxMessagesToLog="3000" maxSizeOfMessageToLog="2000"/>
</diagnostics>
</system.serviceModel>
Service Contract
[WebInvoke(UriTemplate = "/Dial", Method = "POST", RequestFormat =
WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
[OperationContract]
Objects.Response.Telephony.DialResponse
Dial(Objects.Request.Telephony.DialRequest request);
Here is the client
DialRequest DialRequest = new DialRequest();
DialResponse DialResponse = new DialResponse();
DialRequest.ProjectID = "AMS0103300";
DialRequest.DialFromExtension = "1234";
DialRequest.OutDialCode = "51";
DialRequest.RequestBy = "HC User";
DialRequest.DialToPhoneNumber = "1234567890";
DialRequest.RequestDate = DateTime.Now;
DialRequest.ApplicationID = Guid.Parse("F5EE534B-B5ED-4ADD-B671-
CCF7C05057A7");
DataContractJsonSerializer ser =
new
DataContractJsonSerializer(typeof(Objects.Request.Telephony.DialRequest));
MemoryStream mem = new MemoryStream();
ser.WriteObject(mem, DialRequest);
string data =
Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);
WebClient webClient = new WebClient();
webClient.Headers["Content-type"] = "application/json";
webClient.Encoding = Encoding.UTF8;
var result = webClient.UploadString("https://test.xxxx.com/DialService/TelephonyService.svc/Dial","POST", data);
I have tried with different values in protocolMapping, but the results are same. Any help will be appreciated.
It seems to me that there are no errors in you project. Besides protocol mapping is the new feature in Net4.5, which could help us simplify settings.
https://learn.microsoft.com/en-us/dotnet/framework/wcf/simplified-configuration
How to make WCF Service Use HTTPS protocol
There might be some small problems during the process of hosting the service on the IIS.
Could you access the WSDL page successfully?
Like the following form.
We might need to enable the WCF feature in the control panel.
I have made an example, wish it is useful to you.
Server-side (WCF service application).
IService1
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebGet]
string GetData(int value);
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
[OperationContract]
[WebInvoke(UriTemplate ="/MyTest",Method ="POST",RequestFormat =WebMessageFormat.Json,ResponseFormat =WebMessageFormat.Json)]
string Test(CompositeType compositeType);
}
[DataContract]
public class CompositeType
{
bool boolValue = true;
string stringValue = "Hello ";
[DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}
[DataMember]
public string StringValue
{
get { return stringValue; }
set { stringValue = value; }
}
public override string ToString()
{
return $"The BoolValue is {boolValue}, StringValue is {stringValue}";
}
}
Service1.svc.cs
public class Service1 : IService1
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite == null)
{
throw new ArgumentNullException("composite");
}
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
public string Test(CompositeType compositeType)
{
return compositeType.ToString();
}
}
Web.config
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior>
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<webHttpBinding>
<binding name="mybinding">
<security mode="Transport">
<transport clientCredentialType="None"></transport>
</security>
</binding>
</webHttpBinding>
</bindings>
<protocolMapping>
<add binding="webHttpBinding" scheme="http"/>
<add binding="webHttpBinding" scheme="https" bindingConfiguration="mybinding"/>
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
IIS(new website)
Client(generate the data contract by adding service reference)
static void Main(string[] args)
{
//for validating the self-signed certificated.
ServicePointManager.ServerCertificateValidationCallback += delegate
{
return true;
};
ServiceReference1.CompositeType composite = new ServiceReference1.CompositeType()
{
StringValue = "Hello",
BoolValue = true
};
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ServiceReference1.CompositeType));
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, composite);
string data = Encoding.UTF8.GetString(ms.ToArray(), 0, (int)ms.Length);
WebClient webclient = new WebClient();
webclient.Headers["Content-type"] = "application/json";
webclient.Encoding = Encoding.UTF8;
var result = webclient.UploadString("https://localhost:8734/service1.svc/MyTest", "POST", data);
Console.WriteLine(result);
WebClient webclient2 = new WebClient();
webclient2.Headers["Content-type"] = "application/json";
webclient2.Encoding = Encoding.UTF8;
var result2 = webclient2.UploadString("http://localhost:8733/service1.svc/MyTest", "POST", data);
Console.WriteLine(result2);
}
Result.
Besides, PostMan is good choice to test Rest style service.
Feel free to let me know if the problem still exists.
I am using JBOSS eap-6.1 ,wmq with spring.when I am rolling back the messages , its not going to backout and even its not staying inqueue.But its working with ActiveMq.Below are my configuration files,Please help me if I am doing anything wrong.
jboss/standalone.xml configuration is
<subsystem xmlns="urn:jboss:domain:resource-adapters:1.1">
<resource-adapters>
<resource-adapter id="wmq.jmsra.rar">
<archive>
wmq.jmsra.rar
</archive>
<transaction-support>XATransaction</transaction-support>
<connection-definitions>
<connection-definition class-name="com.ibm.mq.connector.outbound.ManagedConnectionFactoryImpl" jndi-name="java:jboss/MQ.CONNECTIONFACTORY.NAME" pool-name="MQ.CONNECTIONFACTORY.NAME">
<config-property name="port">
${queue.port}
</config-property>
<config-property name="hostName">
${queue.host}
</config-property>
<config-property name="UserName">
${queue.server.username}
</config-property>
<config-property name="channel">
${queue.server.channel}
</config-property>
<config-property name="transportType">
${queue.transporttype}
</config-property>
<config-property name="queueManager">
${queue.manager}
</config-property>
</connection-definition>
</connection-definitions>
<admin-objects>
<admin-object class-name="com.ibm.mq.connector.outbound.MQQueueProxy" jndi-name="java:jboss/MQ.QUEUE.NAME.IN" pool-name="MQ.QUEUE.NAME.IN">
<config-property name="baseQueueName">
${queue.name.in}
</config-property>
</admin-object>
<admin-object class-name="com.ibm.mq.connector.outbound.MQQueueProxy" jndi-name="java:jboss/MQ.QUEUE.NAME.BACKOUT" pool-name="MQ.QUEUE.NAME.BACKOUT">
<config-property name="baseQueueName">
${queue.name.backout}
</config-property>
</admin-object>
</admin-objects>
</resource-adapter>
</resource-adapters>
Spring configuration file jms.xml is
<jee:jndi-lookup id="AVTConnectionFactory"
jndi-name="java:jboss/MQ.CONNECTIONFACTORY.NAME" />
<jee:jndi-lookup id="AVTMessageQueue" jndi-name="java:jboss/MQ.QUEUE.NAME.IN" />
<jee:jndi-lookup id="driverIdRequestQueue" jndi-name="java:jboss/MQ.QUEUE.NAME.OUT" />
<jee:jndi-lookup id="backOutQueue" jndi-name="java:jboss/MQ.QUEUE.NAME.BACKOUT" />
<bean id="vehiclePositionReplyListener"
class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="AVTConnectionFactory" />
<property name="destination" ref="AVTMessageQueue" />
<property name="messageListener" ref="vehicleReplyMdp" />
<property name="sessionTransacted" value="true" />
</bean>
listener file is
#Named("vehicleReplyMdp")
#TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public class VCGListenerMDP implements VCGListenerMDPService {
#Override
public void onMessage(Message message, Session session) throws JMSException {
LOG.debug("----------------- QueueIN Listener--------------");
try {
if (message instanceof TextMessage) {
boolean val=processInComingMessage(message, session);
if(!val){
throw new JMSException("JMSException");
}
}
} catch (JMSException e) {
LOG.error("Exception processing mesage: {}", e.toString());
throw new RuntimeException(e);
} catch (NamingException e) {
e.printStackTrace();
}
}
public boolean processInComingMessage(Message message, Session session)
throws JMSException, NamingException {
InitialContext ctx = new InitialContext();
NamingEnumeration<NameClassPair> list = ctx.list("");
boolean isActiveMQFlg = false;
while (list.hasMore()) {
NameClassPair next = list.next();
if (next.getName().contains(ACTIVE_MQ_JNDI_REF)) {
isActiveMQFlg = true;
break;
}
}
try {
// Checking database connectivity
jurisdictionService.getJurisdictionCount();
} catch (Exception ex) {
if (isActiveMQFlg) {
session.rollback();
} else {
ex.printStackTrace();
}
return false;
}
when I am using session.rollback its working for activemq,for WMQ when I am throwing an exception its not rolling back and event trigger for backout threshold is not working.The threshold is 3 times,it triggers only for the first time.
I have generated a web service client using wsimport command line (JAX-WS) and generated Java objects using JAXB and separate XSD files.
But when I try to request, it gives following error from server side.
SAXException, cause: The markup in the document following the root element must be well-formed.
So I checked my soap request with a sample working soap message. Then I realized that there is a different between these two messages.
1. Sample working message.
<m:getMyDetail xmlns:m="http://axis.frontend.hi.example.net">
<MyDetailRQ xmlns="http://www.example.net/schemas/1005/06/messages"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.example.net/1005/06/messages ../xsd/MyDetailRQ.xsd"
version="2013/12">
2. Web service client generated soap message.
<ns3:getMyDetail xmlns:ns3="http://axis.frontend.hi.example.net" xmlns="http://www.
example.net/schemas/1005/06/messages" xmlns:ns2="http://www. example.net/wsdl/1005/06"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="MyDetailRQ">
As you can see, above expected MyDetailRQ wrapper tag element is missing but it generated as xsi:type="MyDetailRQ" attribute.
I’m not sure why this happen and how to fix this through my client project configurations.
Appreciate your help and advice.
Thanks
- Relevant WSDL part
<wsdl:types>
<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://axis.frontend.h1.example.com">
<element name="getMyDetail" type="xsd:anyType"/>
</schema>
<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.example.com/wsdl/2005/06">
<element name="getMyDetailReturn" type="xsd:anyType"/>
</schema>
</wsdl:types>
<wsdl:message name="getMyDetailRequest">
<wsdl:part element="tns1:getMyDetail" name="part"/>
</wsdl:message>
<wsdl:message name="getMyDetailResponse">
<wsdl:part element="impl:getMyDetailReturn" name="getMyDetailReturn"/>
</wsdl:message>
<wsdl:portType name="MyService">
<wsdl:operation name="getMyDetail">
<wsdl:input message="impl:getMyDetailRequest" name="getMyDetailRequest"/>
<wsdl:output message="impl:getMyDetailResponse" name="getMyDetailResponse"/>
</wsdl:operation>
</wsdl:portType>
<wsdl:binding name="MyServiceSoapBinding" type="impl:MyService">
<wsdl:operation name="getMyDetail">
<wsdlsoap:operation soapAction=""/>
<wsdl:input name="getMyDetailRequest">
<wsdlsoap:body use="literal"/>
</wsdl:input>
<wsdl:output name="getMyDetailResponse">
<wsdlsoap:body use="literal"/>
</wsdl:output>
</wsdl:operation>
</wsdl:binding>
<wsdl:service name="MyServiceService">
<wsdl:port binding="impl:MyServiceSoapBinding" name="MyService">
<wsdlsoap:address location="http://interface.example.com/xmls/ws/MyService"/>
</wsdl:port>
</wsdl:service>
- Relevant XSD part
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns="http://www.example.net/schemas/1005/06/messages" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.example.net/schemas/1005/06/messages" elementFormDefault="qualified" attributeFormDefault="unqualified">
<xs:include schemaLocation="MyCommonTypes.xsd"/>
<xs:element name="MyDetailRQ">
- Relevant Java Object
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "MyDetailRQ", propOrder = {
"myCode"
})
#XmlRootElement(name = "MyDetailRQ")
public class MyDetailRQ
extends MainRequest
{
}
- web service client - service interface (Updated on 17-Oct-2014)
#WebService(name = "MyService", targetNamespace = "http://www.example.net/wsdl/1005/06")
#SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
#XmlSeeAlso({
com.myp.hi.frontend.axis.ObjectFactory.class,
com.myp.ObjectFactory.class
})
public interface MyService {
/**
*
* #param part
* #return
* returns java.lang.Object
*/
#WebMethod
#WebResult(name = "getMyDetailReturn", targetNamespace = "http://www.example.net/wsdl/1005/06", partName = "getMyDetailReturn")
public Object getMyDetail(
#WebParam(name = "getMyDetail", targetNamespace = "http://axis.frontend.hi.example.net", partName = "part")
Object part);
}
- ObjectFactory class (Updated on 17-Oct-2014)
#XmlRegistry
public class ObjectFactory {
private final static QName _GetMyDetail_QNAME = new QName("http://axis.frontend.hi.example.net", "getMyDetail");
public ObjectFactory() {
}
#XmlElementDecl(namespace = "http://axis.frontend.hi.example.net", name = "getMyDetail")
public JAXBElement<Object> createGetMyDetail(Object value) {
return new JAXBElement<Object>(_GetMyDetail_QNAME, Object.class, null, value);
}
}
-MyServiceService class (Updated on 17-Oct-2014)
#WebServiceClient(name = "MyServiceService", targetNamespace = "http://www.example.net/wsdl/1005/06", wsdlLocation = "http://interface.example.com/xmls/ws/MyService?wsdl")
#GZIP
public class MyServiceService
extends Service
{
private final static URL MYSERVICESERVICE_WSDL_LOCATION;
private final static WebServiceException MYSERVICESERVICE_EXCEPTION;
private final static QName MYSERVICESERVICE_QNAME = new QName("http://www.example.net/wsdl/1005/06", "MyServiceService");
static {
URL url = null;
WebServiceException e = null;
try {
url = new URL("http://interface.example.com/xmls/ws/MyService?wsdl");
} catch (MalformedURLException ex) {
e = new WebServiceException(ex);
}
MYSERVICESERVICE_WSDL_LOCATION = url;
MYSERVICESERVICE_EXCEPTION = e;
}
#WebEndpoint(name = "MyService")
public MyService getMyService() {
MyService port = super.getPort(new QName("http://www.example.net/wsdl/1005/06", "MyService"), MyService.class);
return port;
}
private static URL __getWsdlLocation() {
if (MYSERVICESERVICE_EXCEPTION!= null) {
throw MYSERVICESERVICE_EXCEPTION;
}
return MYSERVICESERVICE_WSDL_LOCATION;
}
}
- My Test class (Updated on 17-Oct-2014)
MyService myService = new MyServiceService().getMyService();
MyDetailRQ myDetailRQ = new MyDetailRQ();
myDetailRQ.setCredentials(credentials);
myDetailRQ.setLanguage("ENG");
myDetailRQ.setMyCode("52319");
MyDetailRS myDetailRS = (MyDetailRS) myService.getMyDetail(myService);
I have found a solution, but not sure whether perfect one.
What I have done is; pass a XML String to service and get response as a String from service.
Then manually do marshalling and un- marshalling.
See the example below.
MyService myService = new MyServiceService().getMyService();
MyDetailRQ myDetailRQ = new MyDetailRQ();
myDetailRQ.setCredentials(credentials);
myDetailRQ.setLanguage("ENG");
myDetailRQ.setMyCode("52319");
String requestStr = getStringFromJaxb(myDetailRQ.class, myDetailRQ);
String responseStr = (String) myService.getMyDetail(requestStr);
MyDetailRS myDetailRS = (MyDetailRS) getJaxbFromString(MyDetailRS.class, responseStr);
private static Object getJaxbFromString(Class<?> clazz, String xmlString) {
StringReader input = null;
Object o = null;
try {
input = new StringReader(xmlString);
JAXBContext context = JAXBContext.newInstance(clazz);
Unmarshaller um = context.createUnmarshaller();
o = um.unmarshal(input);
if (o instanceof JAXBElement)
o = ((JAXBElement<?>) o).getValue();
} catch (JAXBException e) {
e.printStackTrace();
} finally {
if (input != null)
input.close();
}
return o;
}
/**
* Helper method to get xml string from JAXB Object.
* #param clazz
* #param o
* #return
*/
private static String getStringFromJaxb(Class<?> clazz, Object o) {
String theXML = "";
try {
StringWriter writer = new StringWriter();
JAXBContext context = JAXBContext.newInstance(clazz);
Marshaller m = context.createMarshaller();
m.setProperty("com.sun.xml.bind.xmlDeclaration", Boolean.FALSE);
m.marshal(o, writer);
// output string to console
theXML = writer.toString();
} catch (Exception e) {
e.printStackTrace();
}
return theXML;
}
I am writing an ASP.NET MVC 2 application and don't want to use ASP.NET Membership. I do want to use the Authorize attribute on the Controllers. What I have done so far is ...
Web.config
<roleManager enabled="true" />
<authentication mode="Forms">
<forms loginUrl="~/Authentication/Login" timeout="2880"/>
</authentication>
<authorization>
<allow users="*" /> /* This is for testing */
</authorization>
In my Global.asax
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
var cookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie == null) return;
var decryptedCookie = FormsAuthentication.Decrypt(cookie.Value);
var roles = decryptedCookie.UserData.Split('|');
var tcmIdentity = new TcmIdentity(decryptedCookie.Name);
var tcmPrincipal = new GenericPrincipal(tcmIdentity, roles);
Context.User = tcmPrincipal;
}
I am using a custom IIdentity so that I can add some custom properties in the future. To test this in my Controller action I did this ...
var testPrincipal = User;
I can see the custom Identity with all of the user information but there are no roles on principal object. Any help with what i have missed would be great. Thanks.
I believe you need a role provider. Much like how a Membership provider handles the membership of users, create, delete, validate, edit, in order to use roles, you need to use a RoleProvider (ASP.NET Implementing a Role Provider).
Which also requires enabling roles in the web.config, for example:
<roleManager enabled="enabled" defaultProvider="AspNetSqlRoleProvider">
<providers>
<clear/>
<add name="AspNetSqlRoleProvider"
type="System.Web.Security.SqlRoleProvider"
connectionStringName="ApplicationServices"
applicationName="/" />
<add name="AspNetWindowsTokenRoleProvider"
type="System.Web.Security.WindowsTokenRoleProvider"
applicationName="/" />
</providers>
</roleManager>
This might be useful:
SO asp-net-mvc-roles-without-database-and-without-role-provider
As Might be:
ASP.NET 2.0, Custom Role assignment without a 'Role Provider'
UPDATE:
In the end I got this working by changing
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
var cookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie == null) return;
var decryptedCookie = FormsAuthentication.Decrypt(cookie.Value);
var roles = decryptedCookie.UserData.Split('|');
var tcmIdentity = new TcmIdentity(decryptedCookie.Name);
var tcmPrincipal = new GenericPrincipal(tcmIdentity, roles);
Context.User = tcmPrincipal;
}
to
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
var cookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie == null) return;
var decryptedCookie = FormsAuthentication.Decrypt(cookie.Value);
var roles = decryptedCookie.UserData.Split('|');
var tcmIdentity = new TcmIdentity(decryptedCookie.Name);
var tcmPrincipal = new GenericPrincipal(tcmIdentity, roles);
Thread.CurrentPrincipal = Context.User = tcmPrincipal;
}