Converting assertion to string in OpenSAML 4 - java

I am trying to follow this example: How to create a valid SAML 2.0 Assertion with OpenSAML library in Java and trying to create a SAML response. The code shown is for an older version of OpenSAML. I am using OpenSAML 4.1.1. Apparently XMLHelper is no longer in v.4. I have searched high and low and not found a solution, at least one that makes sense where I can convert the assertion into a string.
Below is the code I have right out of the sample:
SAMLInputContainer input = new SAMLInputContainer();
input.strIssuer = "http://synesty.com";
input.strNameID = "UserJohnSmith";
input.strNameQualifier = "My Website";
input.sessionId = "abcdedf1234567";
Map<String,String> customAttributes = new HashMap<String, String>();
customAttributes.put("FirstName", "John");
customAttributes.put("LastName", "Smith");
customAttributes.put("Email", "john.smith#yahoo.com");
customAttributes.put("PhoneNumber", "76373898998");
customAttributes.put("Locality", "USA");
customAttributes.put("Username", "John.Smith");
input.attributes = customAttributes;
Assertion assertion = GenSAMLAssertion.buildDefaultAssertion(input);
AssertionMarshaller marshaller = new AssertionMarshaller();
assert assertion != null;
Element plaintextElement = marshaller.marshall(assertion);
String originalAssertionString = XMLHelper.nodeToString(plaintextElement);
System.out.println("Assertion String: " + originalAssertionString);

The SerializeSupport class is now used to print XML in OpenSAML.
String originalAssertionString = SerializeSupport.prettyPrintXML(plaintextElement)
As for more current sample code for OpenSAML 4 I have a ongoing series on my blog. As well as accompanying source samples on my Github
A few years ago I also wrote a book on OpenSAML 3. It has not been updated but there are very few changes between 3 and 4.

Related

Aspose word for Java - acceptAllRevisions() method is not working as expected

I am trying to compare 2 word documents, it is not working for some word documents and working fine for others.
Below is the complete code we are using.
com.aspose.words.Document wordDoc1 = new com.aspose.words.Document(oldDocStream);
com.aspose.words.Document wordDoc2 = new com.aspose.words.Document(newDocStream);
wordDoc1.acceptAllRevisions();
wordDoc2.acceptAllRevisions();
if(!wordDoc1.hasRevisions() && !wordDoc2.hasRevisions()){
wordDoc1.compare(wordDoc2, "Aspose Word API", new Date());
}else{
logger.info("Aspose Limitation: Unable to compare docs, it contains unaccepted revisions");
}
Below code block is executed successfully without any exception, So I assume accepting revision is success.
wordDoc1.acceptAllRevisions();
wordDoc2.acceptAllRevisions();
But, wordDoc1.hasRevisions() returns true which means accepting revision is failed.
As a result below message is printed in console.
"Aspose Limitation: Unable to compare docs, it contains unaccepted revisions"
Could anyone can help on this? I raised the same in official forum as well.
Try this:
com.aspose.words.Document wordDoc1 = new com.aspose.words.Document(oldDocStream);
com.aspose.words.Document wordDoc2 = new com.aspose.words.Document(newDocStream);
wordDoc1.acceptAllRevisions();
wordDoc2.acceptAllRevisions();
file.save(newDocStream);
file.save(oldDocStream);
com.aspose.words.Document wordDoc1Accepted = new com.aspose.words.Document(oldDocStream);
com.aspose.words.Document wordDoc2Accepted = new com.aspose.words.Document(newDocStream);
if(!wordDoc1Accepted.hasRevisions() && !wordDoc2Accepted.hasRevisions())
{
wordDoc1Accepted.compare(wordDoc2Accepted, "Aspose Word API", new Date());
}
else{
logger.info("Aspose Limitation: Unable to compare docs, it contains unaccepted revisions");
}

testing OpenNLP classifier model

I'm currently training a model for a classifier. yesterday I found out that it will be more accurate if you also test the created classify model. I tried searching on the internet how to test a model : testing openNLP model. But I cant get it to work. I think the reason is because i'm using OpenNLP version 1.83 instead of 1.5. Could anyone explain me how to properly test my model in this version of OpenNLP?
Thanks in advance.
Below is the way im training my model:
public static DoccatModel trainClassifier() throws IOException
{
// read the training data
final int iterations = 100;
InputStreamFactory dataIn = new MarkableFileInputStreamFactory(new File("src/main/resources/trainingSets/trainingssetTest.txt"));
ObjectStream<String> lineStream = new PlainTextByLineStream(dataIn, "UTF-8");
ObjectStream<DocumentSample> sampleStream = new DocumentSampleStream(lineStream);
// define the training parameters
TrainingParameters params = new TrainingParameters();
params.put(TrainingParameters.ITERATIONS_PARAM, iterations+"");
params.put(TrainingParameters.CUTOFF_PARAM, 0+"");
params.put(AbstractTrainer.ALGORITHM_PARAM, NaiveBayesTrainer.NAIVE_BAYES_VALUE);
// create a model from traning data
DoccatModel model = DocumentCategorizerME.train("NL", sampleStream, params, new DoccatFactory());
return model;
}
I can think of two ways to test your model. Either way, you will need to have annotated documents (an by annotated I really mean expert-classified).
The first way involves using the opennlp DocCatEvaluator. The syntax would be something akin to
opennlp DoccatEvaluator -model model -data sampleData
The format of your sampleData should be
OUTCOME <document text....>
documents are separated by the new line character.
The second way involves creating an DocumentCategorizer. Something like:
(the model is the DocCat model from your question)
DocumentCategorizer categorizer = new DocumentCategorizerME(model);
// could also use: Tokenizer tokenizer = new TokenizerME(tokenizerModel)
Tokenizer tokenizer = WhitespaceTokenizer.INSTANCE();
// linesample is like in your question...
for(String sample=linesample.read(); sample != null; sample=linesample.read()){
String[] tokens = tokenizer.tokenize(sample);
double[] outcomeProb = categorizer.categorize(tokens);
String sampleOutcome = categorizer.getBestCategory(outcomeProb);
// check if the outcome is right...
// keep track of # right and wrong...
}
// calculate agreement metric of your choice
Since I typed the code here there may be a syntax error or two (either I or the SO community can fix), but the idea for running through your data, tokenizing, running it through the document categorizer and keeping track of the results is how you want to evaluate your model.
Hope it helps...

Paypal SetExpressCheckout Soap

when i try to setExpressCheckout, i get ack = success but not token return.
the version of paypal api is 87.0
Here the wsdl link : https://www.sandbox.paypal.com/wsdl/PayPalSvc.wsdl
here to command i use in axis2-1.6.1 to generate java code
-uri https://www.sandbox.paypal.com/wsdl/PayPalSvc.wsd -p com.paypal.soap
here the link to the java code that generated using axis2 https://docs.google.com/open?id=0B97cB4uxjmztbGgxRER6VjBWcWc
here the code for SetExpressCheckout
PaymentDetailsType paymentDetails = new PaymentDetailsType();
BasicAmountType orderTotal = new BasicAmountType();
orderTotal.setCurrencyID(CurrencyCodeType.USD);
orderTotal.setString("10.00");
paymentDetails.setOrderTotal(orderTotal);
paymentDetails.setPaymentAction(PaymentActionCodeType.Sale);
SetExpressCheckoutRequestDetailsType requestDetailsType = new SetExpressCheckoutRequestDetailsType();
requestDetailsType.setCancelURL(buyer.getCancelUrl());
requestDetailsType.setReturnURL(buyer.getReturnUrl());
requestDetailsType.setPaymentDetails(new PaymentDetailsType[]{paymentDetails});
SetExpressCheckoutRequestType requestType = new SetExpressCheckoutRequestType();
requestType.setVersion("87.0");
requestType.setSetExpressCheckoutRequestDetails(requestDetailsType);
SetExpressCheckoutReq req = new SetExpressCheckoutReq();
req.setSetExpressCheckoutRequest(requestType);
RequesterCredentials requesterCredentials = new RequesterCredentials();
CustomSecurityHeaderType customSecurityHeaderType = new CustomSecurityHeaderType();
UserIdPasswordType userIdPasswordType = new UserIdPasswordType();
userIdPasswordType.setUsername("<username>");
userIdPasswordType.setPassword("<pass>");
userIdPasswordType.setSignature("<signature>");
customSecurityHeaderType.setCredentials(userIdPasswordType);
requesterCredentials.setRequesterCredentials(customSecurityHeaderType);
String endPoint = null;
endPoint = "https://api-3t.sandbox.paypal.com/2.0/"; //sandbox API Signature
PayPalAPIInterfaceServiceStub stub = new PayPalAPIInterfaceServiceStub(endPoint);
stub._getServiceClient().getOptions().setProperty(HTTPConstants.CHUNKED, false);
SetExpressCheckoutResponse setExpressCheckout = stub.setExpressCheckout(req, requesterCredentials);
SetExpressCheckoutResponseType checkoutResponse = setExpressCheckout.getSetExpressCheckoutResponse();
Calendar timestamp = checkoutResponse.getTimestamp();
String strdate = null;
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
if (timestamp != null) {
strdate = sdf.format(timestamp.getTime());
}
System.out.println("Date:" + strdate);
System.out.println("CorrelationID:" + checkoutResponse.getCorrelationID());
System.out.println("ack :" + checkoutResponse.getAck());
if (checkoutResponse.getErrors() != null && checkoutResponse.getErrors().length > 0) {
PayPalAPIInterfaceServiceStub.ErrorType[] errors = checkoutResponse.getErrors();
for (int i = 0; i < errors.length; i++) {
System.out.println(errors[i].getErrorCode());
System.out.println(errors[i].getLongMessage());
}
}
System.out.println("token:" + checkoutResponse.getToken());
here the result that i get
Date:17/04/2012 12:33:38
CorrelationID:a7c9fe7283bd
ack :Success
token:null
how i get ack success but token is null?
the contact person for paypal said that there is an EC token already be generated for CorrelationID:a7c9fe7283bd .
thanks in advance.
i have to use setExpressCheckoutResponse.getExtraElement().getText() to get the token. why setExpressCheckoutResponse.getToken() return null?
If you look into mentioned wsdl file, at the beginning you'll notice the following:
<wsdl:definitions
ns:version="89.0"
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns="http://schemas.xmlsoap.org/wsdl/"
... >
Meaning that the version of API which should be used is 89.0 - don't remember where it's specified in PayPal API documentation, but this was mentioned there for sure.
Let me know if you still encounter this issue, since I've managed to set up PayPal Express Checkout using SOAP in Java recently and can help with that.
I just came across this issue and found the answer (this is for C#, I am not sure if it applies to Java):
https://www.x.com/developers/paypal/forums/soap/paypal-api-aa-and-net-wcf-undeserialized-fields
Look in the generated code for the web service (Reference.cs) and find the AbstractResponseType. The last property is Any(). Change the attribute to match this (to ignore the property):
[System.Xml.Serialization.XmlIgnoreAttribute()]
public System.Xml.XmlElement Any {
get {
return this.anyField;
}
set {
this.anyField = value;
}
}
Following this, recompile and test again and you should now receive the Token property set correctly.
If you regenerate the web service code, this change will of course get replaced and you will have to re-do it unless PayPal fixes this. BTW, my WSDL Version number is 98.0 at this time.
Gary Davis

Getting all ActiveDirectory groups using OpenSSO Client SDK

I hope someone here has experience with Sun OpenSSO (now ForgeRock OpenAM).
I'm trying to get all groups in ActiveDirectory using the OpenSSO Client SDK in Java / JBoss EAP 5.0.
I tried the following by combining various samples and code snippets I could find on the web, but this fails and eventually logs "Memberships for identities other than Users is not allowed." The basic approach was to use AMIdentityRepository -> getRealmIdentity() -> getMemberships(IdType.GROUP) :
SSOTokenManager manager = SSOTokenManager.getInstance();
String tokenString = URLDecoder.decode(tokenID, "ISO-8859-1");
SSOToken token = manager.createSSOToken(tokenString);
if (manager.isValidToken(token)) {
SSOToken adminToken = (SSOToken)AccessController.
doPrivileged(AdminTokenAction.getInstance());
AMIdentityRepository rep = new AMIdentityRepository(adminToken, "/");
AMIdentity identity = rep.getRealmIdentity();
Set groups = identity.getMemberships(IdType.GROUP);
}
Note I'm not trying to determine if a user is a member of a group or to retrieve a user's groups - I'm trying to get a list of ALL groups.
Any suggestions would be appreciated - thanks!
Instead of rep.getRealmIdentity() and then calling getMemberships(IdType.GROUP), use searchIdentities and getSearchResults like:
SSOToken token = (SSOToken) AccessController.doPrivileged(AdminTokenAction.getInstance());
AMIdentityRepository ir = new AMIdentityRepository(token, "/");
IdSearchResults results = ir.searchIdentities(IdType.GROUP, "*", new IdSearchControl());
Set<AMIdentity> groups = results.getSearchResults();
for (AMIdentity group : groups) {
logger.debug("Group Name : " + group.getName());
}

ROME API to parse RSS/Atom

I'm trying to parse RSS/Atom feeds with the ROME library. I am new to Java, so I am not in tune with many of its intricacies.
Does ROME automatically use its modules to handle different feeds as it comes across them, or do I have to ask it to use them? If so, any direction on this.
How do I get to the correct 'source'? I was trying to use item.getSource(), but it is giving me fits. I guess I am using the wrong interface. Some direction would be much appreciated.
Here is the meat of what I have for collection my data.
I noted two areas where I am having problems, both revolving around getting Source Information of the feed. And by source, I want CNN, or FoxNews, or whomever, not the Author.
Judging from my reading, .getSource() is the correct method.
List<String> feedList = theFeeds.getFeeds();
List<FeedData> feedOutput = new ArrayList<FeedData>();
for (String sites : feedList ) {
URL feedUrl = new URL(sites);
SyndFeedInput input = new SyndFeedInput();
SyndFeed feed = input.build(new XmlReader(feedUrl));
List<SyndEntry> entries = feed.getEntries();
for (SyndEntry item : entries){
String title = item.getTitle();
String link = item.getUri();
Date date = item.getPublishedDate();
Problem here --> ** SyndEntry source = item.getSource();
String description;
if (item.getDescription()== null){
description = "";
} else {
description = item.getDescription().getValue();
}
String cleanDescription = description.replaceAll("\\<.*?>","").replaceAll("\\s+", " ");
FeedData feedData = new FeedData();
feedData.setTitle(title);
feedData.setLink(link);
And Here --> ** feedData.setSource(link);
feedData.setDate(date);
feedData.setDescription(cleanDescription);
String preview =createPreview(cleanDescription);
feedData.setPreview(preview);
feedOutput.add(feedData);
// lets print out my pieces.
System.out.println("Title: " + title);
System.out.println("Date: " + date);
System.out.println("Text: " + cleanDescription);
System.out.println("Preview: " + preview);
System.out.println("*****");
}
}
getSource() is definitely wrong - it returns back SyndFeed to which entry in question belongs. Perhaps what you want is getContributors()?
As far as modules go, they should be selected automatically. You can even write your own and plug it in as described here
What about trying regex the source from the URL without using the API?
That was my first thought, anyway I checked against the RSS standardized format itself to get an idea if this option is actually available at this level, and then try to trace its implementation upwards...
In RSS 2.0, I have found the source element, however it appears that it doesn't exist in previous versions of the spec- not good news for us!
[ is an optional sub-element of 1
Its value is the name of the RSS channel that the item came from, derived from its . It has one required attribute, url, which links to the XMLization of the source.

Categories

Resources