code:
#Aspect
#Order(Integer.MAX_VALUE)
public class KeySortedAspect {
#Pointcut(value = "#annotation(com.le.bigdata.convertor.KeySortedRule)")
public void pointCut(){}
#Around(value = "pointCut()")
public Object keySorted(ProceedingJoinPoint joinPoint) throws Throwable {
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Object result = joinPoint.proceed();
if(methodSignature.getMethod().isAnnotationPresent(KeySortedRule.class)){
KeySortedRule keySortedRule = methodSignature.getMethod().getAnnotation(KeySortedRule.class);
String path = keySortedRule.path();
//String rule = keySortedRule.rule();
try {
Map<String, String[]> keyMap = getRule(path);
Class<?> type = methodSignature.getMethod().getReturnType();
Object a = sortedUseKeyList(result, keyMap, type);
return a;
} catch (IOException e) {
logger.error("Key sorted Error");
logger.error("reason ", e);
}
}
return result;
}
}
spring mvc configuration mvc-dispatcher-servlet.xml:
<context:annotation-config />
<!-- controller层 内部ctrl与lebi对接的ctrl -->
<context:component-scan base-package="com.le.bigdata.controller, com.le.bigdata.api.controller"/>
<bean id="keySortedAspect" class="com.le.bigdata.convertor.KeySortedAspect"/>
<aop:aspectj-autoproxy proxy-target-class="true"/>
<mvc:default-servlet-handler/>
controller code:
#RestController
#RequestMapping("cp")
public class ContentPortraitController {
#Autowired
private IContentPortraitService service;
#RequestMapping(value = "usertop", method = RequestMethod.GET)
#ApiOperation(value = "获取默认的cv排名前10名的专辑")
private CommonResponseDTO getUserTop(#RequestParam(defaultValue = "10") int size){
List<Map<String, Object>> list = service.getDefaultPid(size);
return new CommonResponseDTO(true, list);
}
#RequestMapping(value = "/album", method = RequestMethod.GET)
#ApiOperation(value = "获取专辑画像", httpMethod = "GET")
#KeySortedRule(path="content_portrait")
public JSONObject getAlbum(#RequestParam(value="dt",required = false) String dt,
#RequestParam(value="start_dt",required = false) String start,
#RequestParam(value="end_dt",required = false) String end,
#RequestParam(value="product",required = false) List<String> product,
#RequestParam(value="pid") String pid){
JSONObject result = new JSONObject();
JSONObject data = null;
try {
if(dt != null && !dt.isEmpty()){
//
data = service.getAlbumPortrait(pid, dt, product);
} else if(start != null && end != null && !start.isEmpty() && !end.isEmpty()){
//
data = service.getAlbumPortrait(pid, start, end, product);
}
} catch (Exception e) {
return null;
}
result.put("result", data);
return result;
}
}
When I request /cp/album it works and response data.
But I request /cp/usertop it throw an exception: NullPointException
reference service is null! service could not be null, IContentPortraitService is an interface and has only one implementation. And I absolutely sure I have scan service package and use #Service annotation on it's implementation.
Debug information:
When I request /cp/usertop:
ContentProtrationController instance is ContentPortraitServiceImpl$$EnhancerBySprinigCGLIB$bdfd5678#7591 and service is null
When I request /cp/album:
ContentProtrationController instance is ContentPortraitServiceImpl#7591 and service is not null, it works.
What's wrong with my code? This problem has troubled me for many days.Who knows how to solve this problem?
Related
I would like to get the value of Result which comes with invocation.ReturnValue , if it is not async , there is no problem. If the method is async, I cannot get the Result of it
public class RedisCacheAspect: MethodInterception
{
private int _duration;
private IRedisCacheManager _redisCacheManager;
private static readonly ConcurrentDictionary<Type, MethodInfo> TypeofTaskResultMethod = new ConcurrentDictionary<Type, MethodInfo>();
public RedisCacheAspect(int duration = 60)//Default 60
{
_duration = duration;
_redisCacheManager = ServiceTool.ServiceProvider.GetService<IRedisCacheManager>();
}
public override void Intercept(IInvocation invocation)
{
var methodName = string.Format($"{invocation.Method.ReflectedType.FullName}.{invocation.Method.Name}");
var method = invocation.Method;
var arguments = invocation.Arguments.ToList();
var key = KeyGenerator.GetCacheKey(invocation.Method, invocation.Arguments,"FoodThen");
var returnType = invocation.Method.ReturnType;
var isExists = _redisCacheManager.IsAdd(key);
var isAsync = IsAsyncMethod(method);
if (isExists)
{
string cacheValue = GetCacheAsync(key);
var objValue = DeserializeCache(key, cacheValue, returnType);
invocation.ReturnValue = ResultFactory(objValue, returnType, isAsync);
return;
}
invocation.Proceed();
_redisCacheManager.Set(key, invocation.ReturnValue,TimeSpan.FromMinutes(_duration));
}
DeserializeCache Method :
private object DeserializeCache(string cacheKey, string cacheValue, Type returnType)
{
try
{
return JsonConvert.DeserializeObject(cacheValue, returnType);
}
catch (System.Exception)
{
_redisCacheManager.Remove(cacheKey);
return null;
}
}
ResultFactory Method :
private object ResultFactory(object result, Type returnType, bool isAsync)
{
if (isAsync)
{
return TypeofTaskResultMethod
.GetOrAdd(returnType, t => typeof(Task)
.GetMethods()
.First(p => p.Name == "FromResult" && p.ContainsGenericParameters)
.MakeGenericMethod(returnType))
.Invoke(null, new object[] { result });
}
else
{
return result;
}
}
This is how invocation.ReturnValue looks like and I want to get the value of Result...
Since you've debugged,have you noticed the value of returntype after var returnType = invocation.Method.ReturnType; been executed?
For Async methods ,the return type should be:
invocation.Method.ReturnType.GenericTypeArguments.First();
I have error
"Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property." when I try to retrieve my data.
What have I try is to put below code in web.config and it is still not working.
<configuration>
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000"/>
</webServices>
</scripting>
</system.web.extensions>
</configuration>
Can anyone help to advise on this?
Changing the default maxJsonLength in web config won't work when trying to return a JsonResult, because asp.net will try to serialize your object internally while completely ignoring the maxJsonLenght you set.
One simple way to fix this, is to return a string instead of a JsonResult in your method, and instance a new JavaScriptSerializer with your custom maxJsonLenght, something like this:
[HttpPost]
public string MyAjaxMethod()
{
var veryBigJson = new object();
JavaScriptSerializer s = new JavaScriptSerializer
{
MaxJsonLength = int.MaxValue
};
return s.Serialize(veryBigJson);
}
And then in your view you just parse it back into a json with JSON.parse(data)
Another way would be creating your own JsonResult class when you can actually control the maxJsonLenght, something like this:
public class LargeJsonResult : JsonResult
{
const string JsonRequest_GetNotAllowed = "This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.";
public LargeJsonResult(object data,JsonRequestBehavior jsonRequestBehavior=JsonRequestBehavior.DenyGet,int maxJsonLength=Int32.MaxValue)
{
Data = data;
JsonRequestBehavior = jsonRequestBehavior;
MaxJsonLength = maxJsonLength;
RecursionLimit = 100;
}
public new int MaxJsonLength { get; set; }
public new int RecursionLimit { get; set; }
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException(JsonRequest_GetNotAllowed);
}
HttpResponseBase response = context.HttpContext.Response;
if (!String.IsNullOrEmpty(ContentType))
{
response.ContentType = ContentType;
}
else
{
response.ContentType = "application/json";
}
if (ContentEncoding != null)
{
response.ContentEncoding = ContentEncoding;
}
if (Data != null)
{
JavaScriptSerializer serializer = new JavaScriptSerializer() { MaxJsonLength = MaxJsonLength, RecursionLimit = RecursionLimit };
response.Write(serializer.Serialize(Data));
}
}
}
And on your method you just change the type and return a new instance of the class
[HttpPost]
public LargeJsonResult MyAjaxMethod()
{
var veryBigJson = new object();
return new LargeJsonResult(veryBigJson);
}
Source: https://brianreiter.org/2011/01/03/custom-jsonresult-class-for-asp-net-mvc-to-avoid-maxjsonlength-exceeded-exception/
Can you do it like this in your code
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = Int32.MaxValue;
myObject obj = serializer.Deserialize<yourObject>(yourJsonString);
I am trying to validate an assertion signature received from an IDP. It results in a failure with following error :
Verification failed for URI "#_7e59add4-11a0-415f-85a3-6f493110d198"
Expected Digest: PgSvwq0Jn6GLMHID20j1fT40VlhvdavKxEM3PtNUfLM=
Actual Digest: mDcfPO26UwGV/tt/JM20ADDDkGGODjd2CZn7dqqR5LM=
org.opensaml.xml.signature.SignatureValidator(SignatureValidator.java:77) -
Signature did not validate against the credential's key
following is the code I am using to validate :
public class SamlTest {
public static void main(String[] args) throws Exception {
// read the file
File file = new File("d://a.xml");
BufferedReader bf = new BufferedReader(new FileReader(file));
String str = null;
String samlStr = "";
while ((str = bf.readLine()) != null) {
samlStr += str;
}
Assertion assertion = SamlTest.unmarshall(samlStr);
//Always do Profile Validation before cryptographically verify the Signature
SAMLSignatureProfileValidator profileValidator = new SAMLSignatureProfileValidator();
try {
profileValidator.validate(assertion.getSignature());
} catch (ValidationException e) {
System.out.println("ErrorString [Error in SAMLSignatureProfilValidation]");
}
Certificate certificate = SamlTest.getCertificate(assertion.getSignature());
BasicCredential verificationCredential = new BasicCredential();
verificationCredential.setPublicKey(certificate.getPublicKey());
SignatureValidator sigValidator = new SignatureValidator(verificationCredential);
try {
sigValidator.validate(assertion.getSignature());
} catch (ValidationException e) {
System.out.println("unable to validate");
}
}
private static Assertion unmarshall(String samlStr) throws Exception {
DefaultBootstrap.bootstrap();
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
DocumentBuilder docBuilder = null;
docBuilder = documentBuilderFactory.newDocumentBuilder();
ByteArrayInputStream is = new ByteArrayInputStream(samlStr.getBytes());
Document document = null;
document = docBuilder.parse(is);
Element element = document.getDocumentElement();
UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element);
return (Assertion) unmarshaller.unmarshall(element);
}
private static Certificate getCertificate(Signature signature) {
try {
X509Certificate certificate = signature.getKeyInfo().getX509Datas().get(0).getX509Certificates().get(0);
if (certificate != null) {
//Converts org.opensaml.xml.signature.X509Certificate to java.security.cert.Certificate
String lexicalXSDBase64Binary = certificate.getValue();
byte[] decoded = DatatypeConverter.parseBase64Binary(lexicalXSDBase64Binary);
try {
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(decoded));
return cert;
} catch (CertificateException e) {
//this should never happen
System.out.println("SAML Signature issue");
return null;
}
}
return null; // TODO Auto-generated method stub
} catch (NullPointerException e) {
//Null certificates
return null;
}
}}
below is the assertion xml received : `
<?xml version="1.0" encoding="UTF-8" standalone="no"?><saml2:Assertion xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" xmlns="http://docs.oasis-open.org/ws-sx/ws-trust/200512" xmlns:S="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns10="urn:oasis:names:tc:SAML:2.0:conditions:delegation" xmlns:ns2="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:ns3="http://www.rsa.com/names/2009/12/std-ext/WS-Trust1.4/advice" xmlns:ns4="urn:oasis:names:tc:SAML:2.0:assertion" xmlns:ns5="http://www.w3.org/2000/09/xmldsig#" xmlns:ns6="http://www.rsa.com/names/2009/12/std-ext/SAML2.0" xmlns:ns7="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:ns8="http://docs.oasis-open.org/ws-sx/ws-trust/200802" xmlns:ns9="http://www.w3.org/2005/08/addressing" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ID="_7e59add4-11a0-415f-85a3-6f493110d198" IssueInstant="2015-06-16T19:38:03.664Z" Version="2.0"><saml2:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">https://localhost/websso/SAML2/Metadata/vsphere.local</saml2:Issuer><ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#"><ds:SignedInfo><ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/><ds:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"/><ds:Reference URI="#_7e59add4-11a0-415f-85a3-6f493110d198"><ds:Transforms><ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/><ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"><ec:InclusiveNamespaces xmlns:ec="http://www.w3.org/2001/10/xml-exc-c14n#" PrefixList="xs xsi"/></ds:Transform></ds:Transforms><ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/><ds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rAGRwVtT2AxavMu4aUL9kDO8yyrqXT2
UF5W5B2jFEWr413h8MmV4v+F/+MqVW7UXQ6C0f6bsaBLdmQNa69b4EAj0UGvvohogObglvP9Du0n
qXwDTt3NMg2aJefHtLsyAXA6A1IR85g/AdImBezM0ZgUALpf1Jaq3XjZvR9XqRiu/VZHDEJacxep
/Csw9AuLA5D2U8bWBV8URoBIfFzyho+3dYG8zS1l9Ym5CvSP98nryWSH1LwsEBVunoZpVE+TLGsz
A4uui1/y31gO04y44DxZp1Bh/HfIT4woOIOIlBqOGd5Rz+kCAwEAAaNFMEMwHQYDVR0OBBYEFPvn
7D4SQkOFxE2ljtW0AowwwIDPMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMBAf8ECDAGAQH/AgEAMA0G
CSqGSIb3DQEBCwUAA4IBAQBcRs/wwAfkWVbwgVKkucSMnRNb7kPS7qERcUykMGA/46QXhDcDShd1
j2aXbZKx0DNLKpGYuIN4N6uGdHZu0jABaSMOtVYdXCAHdXGPYJB6vV/l3jOOVvOPULwaf8lbBrmM
AuR6F6J1DBiXH+XMuOPB6/Tp9YYSoFJkPqhxqxyns3tjjTXmCIcoEUuPqACniLk6aUzlKFzDUt2N
hp34Qzj4BdH7QepHjR/mcDkVVaMjY597d2f/kAJm0D/l01W3nyKCbDb3yq3w8f6gj1WIIB6o8w9R
HsZwm4eVFYhJWWvi9N2wci8X5PMdDi/abUxhOT7EYEQGk39dfc/VTEQoMKrE</ds:X509Certificate></ds:X509Data></ds:KeyInfo></ds:Signature><saml2:Subject><saml2:NameID Format="http://schemas.xmlsoap.org/claims/UPN">Administrator</saml2:NameID><saml2:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:holder-of-key"><saml2:NameID Format="http://schemas.xmlsoap.org/claims/UPN">vsphere-webclient-21665f80-b6c4-11e4-b9fe-005056a638d3#vsphere.local</saml2:NameID><saml2:SubjectConfirmationData xsi:type="saml2:KeyInfoConfirmationDataType"><ds:KeyInfo xmlns:ds="http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pAhnss6PniRLdQ2D7dbKgLNjgi4CIEV3SuaDXaqONV9IV
+IjAg6N+yMqGghc64MyAzDS0Rkp2R7hfNjyYUcG9lNTSpsKSZE0iNb9RWaqrPKu4RsnPvjIStx43
EytkF63Q7ktYxFCXlnB9AVeMa6nfOzFZS+SXHrd+zWs62Hp/9mBHLoHKEYYQawpJlbBnAkg8WZxq
uVE/Ky5Gv8ni3eAovM2g0Ot7gqqbfPH09Yk4L9pBUPw/lT2icBvZ6yHgWxmEnZuHBKUF5B8F0smI
TSCwNY2lUghkxxCdTEaqsthPGb9uYEB6JFJDgblgEBg=</ds:X509Certificate></ds:X509Data></ds:KeyInfo></saml2:SubjectConfirmationData></saml2:SubjectConfirmation></saml2:Subject><saml2:Conditions NotBefore="2015-06-16T19:38:51.295Z" NotOnOrAfter="2015-07-16T19:38:51.295Z"><saml2:ProxyRestriction Count="9"/><saml2:Condition xmlns:del="urn:oasis:names:tc:SAML:2.0:conditions:delegation" xsi:type="del:DelegationRestrictionType"><del:Delegate DelegationInstant="2015-06-16T19:36:37.101Z"><saml2:NameID Format="http://schemas.xmlsoap.org/claims/UPN">vsphere-webclient-21665f80-b6c4-11e4-b9fe-005056a638d3#vsphere.local</saml2:NameID></del:Delegate></saml2:Condition><saml2:Condition xmlns:rsa="http://www.rsa.com/names/2009/12/std-ext/SAML2.0" Count="9" xsi:type="rsa:RenewRestrictionType"/></saml2:Conditions><saml2:AuthnStatement AuthnInstant="2015-06-16T19:38:03.662Z"><saml2:AuthnContext><saml2:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:PreviousSession</saml2:AuthnContextClassRef></saml2:AuthnContext></saml2:AuthnStatement><saml2:AttributeStatement><saml2:Attribute FriendlyName="givenName" Name="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"><saml2:AttributeValue xsi:type="xs:string">Administrator</saml2:AttributeValue></saml2:Attribute><saml2:Attribute FriendlyName="Groups" Name="http://rsa.com/schemas/attr-names/2009/01/GroupIdentity" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"><saml2:AttributeValue xsi:type="xs:string">SophosAdministrator</saml2:AttributeValue><saml2:AttributeValue xsi:type="xs:string">Administrators</saml2:AttributeValue><saml2:AttributeValue xsi:type="xs:string">vsphere.localAdministrators</saml2:AttributeValue><saml2:AttributeValue xsi:type="xs:string">vsphere.localEveryone</saml2:AttributeValue></saml2:Attribute><saml2:Attribute FriendlyName="Subject Type" Name="http://vmware.com/schemas/attr-names/2011/07/isSolution" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"><saml2:AttributeValue xsi:type="xs:string">false</saml2:AttributeValue></saml2:Attribute><saml2:Attribute FriendlyName="surname" Name="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"><saml2:AttributeValue xsi:type="xs:string"/></saml2:Attribute></saml2:AttributeStatement></saml2:Assertion>
`could someone please help me find the issue here.
I have java SE sample client which run on desktop (code below). But I have access to WebSphere were called EJB is deployed. How to rewrite below code to work on WebSphere? (When I leave this code just like it is program works but I think this can be done more simple and clear)
Main method:
WSConn connection = new WSConn();
final Plan plan = connection.getPlanBean();
com.ibm.websphere.security.auth.WSSubject.doAs(connection.getSubject(), new java.security.PrivilegedAction<Object>() {
public Object run() {
try {
// App logic
} catch (Throwable t) {
System.err.println("PrivilegedAction - Error calling EJB: " + t);
t.printStackTrace();
}
return null;
}
}); // end doAs
WSConn class:
public class WSConn {
private static final String INITIAL_CONTEXT_FACTORY = "com.ibm.websphere.naming.WsnInitialContextFactory";
private static final String JAAS_MODULE = "WSLogin";
private static final String MODEL_EJB_NAME_LONG = "ejb/com/ibm/ModelHome";
private static final String PLAN_EJB_NAME_LONG = "ejb/com/ibm/PlanHome";
private Subject subject;
private InitialContext initialContext;
private String serverName;
private String serverPort;
private String uid;
private String pwd;
private String remoteServerName;
private Model modelBean;
private Plan planBean;
public WSConn() {
Properties props = new Properties();
try {
props.load(WSConn.class.getClassLoader().getResourceAsStream("WSConn.properties"));
} catch (IOException e) {
e.printStackTrace();
}
serverName = props.getProperty("WSConn.serverName");
serverPort = props.getProperty("WSConn.serverPort");
uid = props.getProperty("WSConn.userID");
pwd = props.getProperty("WSConn.password");
remoteServerName = props.getProperty("WSConn.remoteServerName");
}
private void init() {
if (subject == null || initialContext == null) {
subject = login();
}
}
private Subject login() {
Subject subject = null;
try {
LoginContext lc = null;
// CRATE LOGIN CONTEXT
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
env.put(Context.PROVIDER_URL, "corbaloc:iiop:" + serverName + ":" + serverPort);
initialContext = new InitialContext(env);
// Just to test the connection
initialContext.lookup("");
lc = new LoginContext(JAAS_MODULE, new WSCallbackHandlerImpl(uid, pwd));
lc.login();
subject = lc.getSubject();
} catch (javax.naming.NoPermissionException exc) {
System.err.println("[WSConn] - Login Error: " + exc);
} catch (Exception exc) {
System.err.println("[WSConn] - Error: " + exc);
}
return subject;
}
public wModel getModelBean() {
if (modelBean == null) {
init();
modelBean = (wModel) com.ibm.websphere.security.auth.WSSubject.doAs(subject,
new java.security.PrivilegedAction<wModel>() {
public wModel run() {
wModel session = null;
try {
Object o = initialContext.lookup(MODEL_EJB_NAME_LONG);
wModelHome home = (wModelHome) PortableRemoteObject.narrow(o, wModelHome.class);
if (home != null) {
session = home.create(remoteServerName);
}
} catch (Exception exc) {
System.err.println("Error getting model bean: " + exc);
}
return session;
}
}); // end doAs
}
return modelBean;
}
public wPlan getPlanBean() {
if (planBean == null) {
init();
planBean = (wPlan) com.ibm.websphere.security.auth.WSSubject.doAs(subject,
new java.security.PrivilegedAction<wPlan>() {
public wPlan run() {
wPlan session = null;
try {
Object o = initialContext.lookup(PLAN_EJB_NAME_LONG);
wPlanHome home = (wPlanHome) PortableRemoteObject.narrow(o, wPlanHome.class);
if (home != null) {
session = home.create(remoteServerName);
}
} catch (Exception exc) {
System.err.println("Error getting plan bean: " + exc);
}
return session;
}
}); // end doAs
}
return planBean;
}
public Subject getSubject() {
if (subject == null) {
init();
}
return subject;
}
}
As indicated in another answer, the classic mechanism is to lookup and narrow the home interface.
Get the initial context
final InitialContext initialContext = new InitialContext();
Lookup for the home by jndi name, specifying either the full jndi name
Object obj = initialContext.lookup("ejb/com/ibm/tws/conn/plan/ConnPlanHome");
or you can create e reference in your WAR and use java:comp/env/yourname
Then narrow the home to the home interface class
ConnPlanHome planHome = (ConnPlanHome)PortableRemoteObject.narrow(obj, ConnPlanHome.class);
and then create the EJB remote interface
ConnPlan plan = planHome.create();
The about calls should work for IBM Workload Scheduler distributed.
For IBM Workload Scheduler z/OS the JNDI name and the class names are different:
final InitialContext initialContext = new InitialContext();
String engineName = "XXXX";
Object obj = initialContext.lookup("ejb/com/ibm/tws/zconn/plan/ZConnPlanHome");
ZConnPlanHome planHome = (ZConnPlanHome)PortableRemoteObject.narrow(obj, ZConnPlanHome.class);
ZConnPlan plan = planHome.create(engineName);
User credentials are propagated from the client to the engine, the client need to be authenticated otherwise the engine will reject the request.
If you're trying to access an EJB from a POJO class, then there is nothing more simple than lookup+narrow. However, if the POJO is included in an application (EAR or WAR), then you could declare and lookup an EJB reference (java:comp/ejb/myEJB), and then the container would perform the narrow rather than your code. If you change your code to be a managed class like a servlet, another EJB, or a CDI bean, then you could use #EJB injection, and then you would not even need a lookup.
I am attempting to write some Tests for a small project of mine but they seem to fail (I am starting with 1 test 'Create_Class')
I use the repository pattern and use Constructor Dependency Injection:
public KlasController() {
db = ObjectContextPerHttpRequest.Context;
KlasRepo = new KlasRepository(db);
LesRepo = new LesRepository(db);
OpdrachtRepo = new OpdrachtRepository(db);
}
//dependency injection constructor
public KlasController(IKlasRepository KlasRepo, ILesRepository LesRepo,
IOpdrachtRepository OpdrachtRepo) {
this.KlasRepo = KlasRepo;
this.LesRepo = LesRepo;
this.OpdrachtRepo = OpdrachtRepo;
}
here is my TestClass with testinitializer (which runs before every test) and the first test
[TestClass()]
public class KlasControllerTest
{
private KlasController Controller;
private IOpdrachtRepository OpdrachtRepo;
//Use TestInitialize to run code before running each test
[TestInitialize()]
public void MyTestInitialize()
{
OpdrachtRepo = new DummyOpdrachtRepository();
Controller = new KlasController(new DummyKlasRepository(),
new DummyLesRepository(), OpdrachtRepo);
Opdracht TestOpdracht = new Opdracht
{
OpdrachtID = 1,
VakID = 1,
StamNummer = "im1"
};
Vak TestVak = new Vak { VakID = 1, VakNaam = "FOOP" };
TestOpdracht.Vak = TestVak;
OpdrachtRepo.addOpdracht(TestOpdracht);
}
/// <summary>
///A test for Index
///</summary>
[TestMethod()]
public void CreateKlasDirectsToToonKlassen()
{
Klas Klas = new Klas { KlasNaam = "2dNet" };
RedirectToRouteResult view = Controller.Create(1) as RedirectToRouteResult;
Assert.IsNotNull(view);
Assert.AreEqual("ToonKlassen", view.RouteValues["action"]);
}
}
at the moment I get a nullreferenceException on the view (assert.isNotNull fails)
and here is one of my DummyRepository's:
class DummyOpdrachtRepository : IOpdrachtRepository
{
List<Opdracht> opdrachten;
public DummyOpdrachtRepository()
{
opdrachten = new List<Opdracht>();
}
public void addOpdracht(Opdracht opdracht)
{
opdrachten.Add(opdracht);
}
public string GetDocentID(int OpdrachtID)
{
var opdracht = opdrachten.Where(o => o.OpdrachtID == OpdrachtID).FirstOrDefault();
return opdracht.StamNummer;
}
public Opdracht Find(int id)
{
return opdrachten.Where(o => o.OpdrachtID == id).FirstOrDefault();
}
}
Normally I should have written the tests Before writting the code, I know (and I am convinced off TDD, as I have used it successfully in my latest Java-project). but it just doesn't seem to work..
here is the code for KlasController.Create action
public ActionResult Create(int id) //id = opdrachtID
{
var Opdracht = OpdrachtRepo.Find(id);
Vak vak;
if(Opdracht != null)
vak = Opdracht.Vak;
else
throw new NullReferenceException("Deze opdracht werd niet gevonden");
return View(new CreateKlasModel(id,vak));
}
I know this is a lot of code, but I really want to make this work.
Thanks for helping me out in advance :)
As vladimir77 already says in his comment, the method public ActionResult Create(int id) is of type ViewResult, so either you change you method to do areturn RedirectToRoute() or you change your test to
ViewResult view = Controller.Create(1);
Assert.IsNotNull(view);
A ViewResult can not be cast as a RedirectToRouteResult.