Login to adfs through openam using java application - adfs2.0

I have configured adfs as identity provider and openam as service provider but how to test whether login is working fine with adfs throght openam.
Can anyone help me to do login to adfs server through openam using java application.
Thanks,

Refer OpenAM and ADFS2 configuration.
The article covers all your questions.
Update:
The way I normally do this is to use the OpenSSO / OpenAM Java Fedlet.
Refer Using Fedlets in Java Web Applications (Chapter 8).
The code (as per the fedlet) to display the contents of the token looks like:
Response samlResp = (Response) map.get(SAML2Constants.RESPONSE);
Assertion assertion = (Assertion) map.get(SAML2Constants.ASSERTION);
Subject subject = (Subject) map.get(SAML2Constants.SUBJECT);
String entityID = (String) map.get(SAML2Constants.IDPENTITYID);
String spEntityID = (String) map.get(SAML2Constants.SPENTITYID);
NameID nameId = (NameID) map.get(SAML2Constants.NAMEID);
String value = nameId.getValue();
String format = nameId.getFormat();
out.println("<br><br><b>Single Sign-On successful with IDP "
+ entityID + ".</b>");
out.println("<br><br>");
out.println("<table border=0>");
if (format != null) {
out.println("<tr>");
out.println("<td valign=top><b>Name ID format: </b></td>");
out.println("<td>" + format + "</td>");
out.println("</tr>");
}
if (value != null) {
out.println("<tr>");
out.println("<td valign=top><b>Name ID value: </b></td>");
out.println("<td>" + value + "</td>");
out.println("</tr>");
}
String sessionIndex = (String) map.get(SAML2Constants.SESSION_INDEX);
if (sessionIndex != null) {
out.println("<tr>");
out.println("<td valign=top><b>SessionIndex: </b></td>");
out.println("<td>" + sessionIndex + "</td>");
out.println("</tr>");
}
Map attrs = (Map) map.get(SAML2Constants.ATTRIBUTE_MAP);
if (attrs != null) {
out.println("<tr>");
out.println("<td valign=top><b>Attributes: </b></td>");
Iterator iter = attrs.keySet().iterator();
out.println("<td>");
while (iter.hasNext()) {
String attrName = (String) iter.next();
Set attrVals = (HashSet) attrs.get(attrName);
if ((attrVals != null) && !attrVals.isEmpty()) {
Iterator it = attrVals.iterator();
while (it.hasNext()) {
out.println(attrName + "=" + it.next() + "<br>");
}
}
}
out.println("</td>");
out.println("</tr>");
}
out.println("</table>");

Related

How to avoid to fetch a list of followers of the same Twitter user that was displayed before

I'm very new at coding and I'm having some issues. I'd like to display the followers of followers of ..... of followers of some specific users in Twitter. I have coded this and I can set a limit for the depth. But, while running the code with a small sample, I saw that I run into the same users again and my code re-display the followers of these users. How can I avoid this and skip to the next user? You can find my code below:
By the way, while running my code, I encounter with a 401 error. In the list I'm working on, there's a private user, and when my code catches that user, it stops. Additionally, how can I deal with this issue? I'd like to skip such users and prevent my code to stop.
Thank you for your help in advance!
PS: I know that I'll encounter with a 429 error working with a large sample. After fixing these issues, I'm planning to review relevant discussions to deal with.
public class mainJava {
public static Twitter twitter = buildConfiguration.getTwitter();
public static void main(String[] args) throws Exception {
ArrayList<String> rootUserIDs = new ArrayList<String>();
Scanner s = new Scanner(new File("C:\\Users\\ecemb\\Desktop\\rootusers1.txt"));
while (s.hasNextLine()) {
rootUserIDs.add(s.nextLine());
}
s.close();
for (String rootUserID : rootUserIDs) {
User rootUser = twitter.showUser(rootUserID);
List<User> userList = getFollowers(rootUser, 0);
}
}
public static List<User> getFollowers(User parent, int depth) throws Exception {
List<User> userList = new ArrayList<User>();
if (depth == 2) {
return userList;
}
IDs followerIDs = twitter.getFollowersIDs(parent.getScreenName(), -1);
long[] ids = followerIDs.getIDs();
for (long id : ids) {
twitter4j.User child = twitter.showUser(id);
userList.add(child);
getFollowers(child, depth + 1);
System.out.println(depth + "th user: " + parent.getScreenName() + " Follower: " + child.getScreenName());
}
return userList;
}
}
I guess graph search algorithms can be implemented for this particular issue. I chose Breadth First Search algorithm because visiting root user's followers at first would be better. You can check this link to additional information about algorithm.
Here is my implementation for your problem:
public List<User> getFollowers(User parent, int startDepth, int finalDepth) {
List<User> userList = new ArrayList<User>();
Queue<Long> queue = new LinkedList<Long>();
HashMap<Long, Integer> discoveredUserId = new HashMap<Long, Integer>();
try {
queue.add(parent.getId());
discoveredUserId.put(parent.getId(), 0);
while (!queue.isEmpty()) {
long userId = queue.remove();
int discoveredDepth = discoveredUserId.get(userId);
if (discoveredDepth == finalDepth) {
continue;
}
User user = twitter.showUser(userId);
handleRateLimit(user.getRateLimitStatus());
if (user.isProtected()) {
System.out.println(user.getScreenName() + "'s account is protected. Can't access followers.");
continue;
}
IDs followerIDs = null;
followerIDs = twitter.getFollowersIDs(user.getScreenName(), -1);
handleRateLimit(followerIDs.getRateLimitStatus());
long[] ids = followerIDs.getIDs();
for (int i = 0; i < ids.length; i++) {
if (!discoveredUserId.containsKey(ids[i])) {
discoveredUserId.put(ids[i], discoveredDepth + 1);
User child = twitter.showUser(ids[i]);
handleRateLimit(child.getRateLimitStatus());
userList.add(child);
if (discoveredDepth >= startDepth && discoveredDepth < finalDepth) {
System.out.println(discoveredDepth + ". user: " + user.getScreenName() + " has " + user.getFollowersCount() + " follower(s) " + (i + 1) + ". Follower: " + child.getScreenName());
}
queue.add(ids[i]);
} else {//prints to console but does not check followers. Just for data consistency
User child = twitter.showUser(ids[i]);
handleRateLimit(child.getRateLimitStatus());
if (discoveredDepth >= startDepth && discoveredDepth < finalDepth) {
System.out.println(discoveredDepth + ". user: " + user.getScreenName() + " has " + user.getFollowersCount() + " follower(s) " + (i + 1) + ". Follower: " + child.getScreenName());
}
}
}
}
} catch (TwitterException e) {
e.printStackTrace();
}
return userList;
}
//There definitely are more methods for handling rate limits but this worked for me well
private void handleRateLimit(RateLimitStatus rateLimitStatus) {
//throws NPE here sometimes so I guess it is because rateLimitStatus can be null and add this conditional expression
if (rateLimitStatus != null) {
int remaining = rateLimitStatus.getRemaining();
int resetTime = rateLimitStatus.getSecondsUntilReset();
int sleep = 0;
if (remaining == 0) {
sleep = resetTime + 1; //adding 1 more second
} else {
sleep = (resetTime / remaining) + 1; //adding 1 more second
}
try {
Thread.sleep(sleep * 1000 > 0 ? sleep * 1000 : 0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
in this code HashMap<Long, Integer> discoveredUserId is used to prevent program checking same users repeatedly and storing in which depth we faced with this user.
and for private users, there is isProtected() method in twitter4j library.
Hope this implementation helps.

Creating multiple mandatory fields in workflow

I have a requirement for multiple fields to be set whenever an issue is created.
I tried this
rule Mandatory
when <issue created or updated> {
Swimlane.required("Must have a swimlane");
UtgmsVehicleName.required("Must be attached to a vehicle ");
Subsystem.required("Subsystem must be set");
Assignee.required("Assignee must be set");
Fix versions.required("Fix versions must be set/");
}
What happens is that it continually asks for all the fields to be set. What is the best way to fulfil the requirement.
Based on Alex's suggestion i got this
rule MandatoryFields
when !isReported() {
var assigneeSet = Assignee != null;
var subSystemSet = Subsystem != null && Subsystem != {No subsystem};
var fixedVersionSet = Fix versions != null;
var assigneeValue = Assignee.oldValue;
var messageValue = "Mandatory fields:";
if (!assigneeSet) {
messageValue = messageValue + " Assignee";
}
if (!subSystemSet) {
messageValue = messageValue + " Subsystem";
}
if (!fixedVersionSet) {
messageValue = messageValue + " FixedVersion";
}
assert (assigneeSet && subSystemSet && fixedVersionSet): messageValue;
if (assigneeSet) {
Assignee = assigneeValue;
}
}
You can have something like
var noSwimlane = Swimlane == null;
var noSubsystem = Subsystem == null;
...
var message = "You need to fill the following fields: ";
if (noSwimlane) {
message += "Swimlane";
}
...
assert !(noSwimlane || noSubsystem || ...) : message;

the process cannot access the file 'xxx.xml' because it is being used by another process

I googled a lot, but i dint get any solution for problem.
Iam trying to add a node in to a xxx.xml file, but its throwing an error
"the process cannot access the file 'xxx.xml' because it is being used by another process", below is my class
public class Registration
{
List Users;
List NewUsers;
string Userpath = string.Empty;
string NewUserpath = string.Empty;
string strUsername = string.Empty;
public bool FINDUSERNAME(string firstname, string lastname, string emailaddress, string country, string purchasedate, string username, string password)
{
//Put code to get the offers from database to Offers variable
if (ReadXML(firstname, lastname, emailaddress, country, purchasedate, username, password))
return true;
else
return false;
}
//bool ReadXML(XmlDocument xmlfile2)
bool ReadXML(string firstname, string lastname, string emailaddress, string country, string purchasedate, string username, string password)
{
try
{
XmlDocument receivedxml = new XmlDocument();
Userpath = HttpContext.Current.Server.MapPath("/SampleData/Registration.xml");
NewUserpath = HttpContext.Current.Server.MapPath("/SampleData/NewRegistration.xml");
XmlReaderSettings xrs = new XmlReaderSettings();
xrs.DtdProcessing = DtdProcessing.Ignore;
XmlReader xr = XmlReader.Create(Userpath, xrs);
if (xr != null)
{
//Setting the Root element
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "Registration";
xRoot.IsNullable = true;
XmlSerializer deserializer = new XmlSerializer(typeof(Registration), xRoot);
Registration UserDetails = (Registration)deserializer.Deserialize(xr);
Users = UserDetails.Users;
foreach (var varuser in Users)
{
if (username == varuser.Username)
{
strUsername = varuser.Username;
return true;
}
}
if (strUsername == "")
{
//here iam trying to add a node to the xml
using (StreamWriter sw = new StreamWriter(File.Create(Userpath)))
{
sw.Write("<User><Firstname>"
+ firstname + "</Firstname><Lastname>"
+ lastname + "</Lastname><Country>"
+ country + "</Country><Purchasedate>"
+ purchasedate + "</Purchasedate><Emailaddress>"
+ emailaddress + "</Emailaddress><Username>"
+ username + "</Username><Password>"
+ password + "</Password></User>");
}
return false;
}
}
return false;
}
catch (Exception)
{
return false;
}
}
}
Thanks in Advance...
It looks like you are never closing your reader, you need to call xr.Close() at some point. Or as Johan suggested, wrap it in a using statement:
using (XmlReader xr = XmlReader.Create(Userpath, xrs))
{
//Setting the Root element
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "Registration";
xRoot.IsNullable = true;
XmlSerializer deserializer = new XmlSerializer(typeof(Registration), xRoot);
Registration UserDetails = (Registration)deserializer.Deserialize(xr);
Users = UserDetails.Users;
foreach (var varuser in Users)
{
if (username == varuser.Username)
{
strUsername = varuser.Username;
return true;
}
}
if (strUsername == "")
{
//here iam trying to add a node to the xml
using (StreamWriter sw = new StreamWriter(File.Create(Userpath)))
{
sw.Write("<User><Firstname>"
+ firstname + "</Firstname><Lastname>"
+ lastname + "</Lastname><Country>"
+ country + "</Country><Purchasedate>"
+ purchasedate + "</Purchasedate><Emailaddress>"
+ emailaddress + "</Emailaddress><Username>"
+ username + "</Username><Password>"
+ password + "</Password></User>");
}
return false;
}
}
Also another note: I notice your method is named ReadXML, yet you are also writing XML in this method. This can be confusing, are you reading or writing? Part of your issue may also be that you are opening the file for reading, and then creating the file for writing?? I have not dealt with the C# Xml libs before but something doesn't seem right here. You might consider breaking this down more.

Convert cookie string to a Cookie object in C# or Java

I need to automatically access a website that requires authentication. I found cookie string of this website's http host (using fiddler). Is there a way to convert this string to a cookie object and pass it to a Webclient to pass the authentication?
Convert the Sting to a cookie object. For this you need to parse the String to get name, value, path, domain, etc.
You have to do something like this -
String[] cArray = cookieValueIs.split(";");
for (String s : cArray) {
s = s.trim();
int i1 = s.indexOf('=');
if (i1 != -1) {
String k = s.substring(0, i1).trim();
String v = s.substring(i1 + 1).trim();
if (k.equalsIgnoreCase(VERSION)) {
version = v;
} else if (k.equalsIgnoreCase(COMMENT)) {
comment = v;
} else if (k.equalsIgnoreCase(DOMAIN)) {
domain = v;
} else if (k.equalsIgnoreCase(PATH)) {
path = v;
} else if (k.equalsIgnoreCase(MAX_AGE)) {
maxAge = v;
} else if(k.equalsIgnoreCase(EXPIRES)){
continue;
}
else {
key = k;
value = v;
}
} else {
if (s.equalsIgnoreCase(SECURE)) {
secure = true;
} else if (s.equalsIgnoreCase(HTTPONLY)) {
httpOnly = true;
}
}
Once you are done with this create a cookie object-
Cookie cookie = new Cookie(key,value);
if(comment != null){
cookie.setComment(comment);
}
if(domain != null){
cookie.setDomain(domain);
}
if(path != null){
cookie.setPath(path);
}
if(version != null){
cookie.setVersion(Integer.parseInt(version));
}
if(secure){
cookie.setSecure(true);
Now your string is converted to the Cookie object --> cookie
This worked for me in c#.
public static Cookie ToCookie(this string #this)
{
String[] array = #this.Split(';');
var cookie = new Cookie();
foreach (var ss in array)
{
string key;
object value;
var s = ss.Trim();
int indexOf = s.IndexOf('=');
if (indexOf != -1) {
key = s.Substring(0, indexOf).Trim();
value = s.Substring(indexOf + 1).Trim();
} else
{
key = s.ToTitleCase();
value = true;
}
var prop = cookie.GetType().GetProperty(key.ToTitleCase());
if (prop != null)
{
var converted = Convert.ChangeType(value, prop.PropertyType);
prop.SetValue(cookie, converted, null);
}else
{
cookie.Name = key;
cookie.Value = value.ToString();
}
}
return cookie;
}

How to disable/deactivate a SalesForce User through SOAP API?

I want to disable a User programmetically by using SOAP API. How can I do that? I am using Partner API and I have Developer edition. I have manage users persmissions set. I have gone through this link. I am looking for code which can help me disable/deactivate a User.
This is my code:
import com.sforce.soap.partner.Connector;
import com.sforce.soap.partner.PartnerConnection;
import com.sforce.soap.partner.QueryResult;
import com.sforce.soap.partner.sobject.SObject;
import com.sforce.ws.ConnectionException;
import com.sforce.ws.ConnectorConfig;
public class DeactivateUser {
public static void main(String[] args) {
ConnectorConfig config = new ConnectorConfig();
config.setUsername("waprau#waprau.com");
config.setPassword("sjjhggrhgfhgffjdgj");
PartnerConnection connection = null;
try {
connection = Connector.newConnection(config);
QueryResult queryResults = connection.query("SELECT Username, IsActive from User");
if (queryResults.getSize() > 0) {
for (SObject s : queryResults.getRecords()) {
if(s.getField("Username").equals("abcd#pqrs.com")){
System.out.println("Username: " + s.getField("Username"));
s.setField("IsActive", false);
}
System.out.println("Username: " + s.getField("Username") + " IsActive: " + s.getField("IsActive"));
}
}
} catch (ConnectionException ce) {
ce.printStackTrace();
}
}
}
This is output:
Username: waprau#waprau.com IsActive: true
Username: jsmith#ymail.net IsActive: false
Username: abcd#pqrs.com
Username: abcd#pqrs.com IsActive: false
However in UI when I go to My Name > Setup > Manage Users > Users, it always show 'Active' check box for user abcd#pqrs.com selected :-(
It doesn't look like you're actually sending the update back to Salesforce - you're just setting IsActive to false locally. You will need to use a call to PartnerConnection.update(SObject[] sObjects) in order for Salesforce to reflect your changes, like so:
try {
connection = Connector.newConnection(config);
QueryResult queryResults = connection.query("SELECT Id, Username, IsActive from User");
if ( queryResults.getSize() > 0 ) {
// keep track of which records you want to update with an ArrayList
ArrayList<SObject> updateObjects = new ArrayList<SObject>();
for (SObject s : queryResults.getRecords()) {
if ( s.getField("Username").equals("abcd#pqrs.com") ){
System.out.println("Username: " + s.getField("Username"));
s.setField("Id", null);
s.setField("IsActive", false);
}
updateObjects.add(s); // if you want to update all records...if not, put this in a conditional statement
System.out.println("Username: " + s.getField("Username") + " IsActive: " + s.getField("IsActive"));
}
// make the update call to Salesforce and then process the SaveResults returned
SaveResult[] saveResults = connection.update(updateObjects.toArray(new SObject[updateObjects.size()]));
for ( int i = 0; i < saveResults.length; i++ ) {
if ( saveResults[i].isSuccess() )
System.out.println("record " + saveResults[i].getId() + " was updated successfully");
else {
// There were errors during the update call, so loop through and print them out
System.out.println("record " + saveResults[i].getId() + " failed to save");
for ( int j = 0; j < saveResults[i].getErrors().length; j++ ) {
Error err = saveResults[i].getErrors()[j];
System.out.println("error code: " + err.getStatusCode().toString());
System.out.println("error message: " + err.getMessage());
}
}
}
}
} catch (ConnectionException ce) {
ce.printStackTrace();
}
It is possible to directly work with the user record without the SOQL query if you already know the Id.
SalesforceSession session = ...;
sObject userSObject = new sObject();
userSObject.Id = "00570000001V9NA";
userSObject.type = "User";
userSObject.Any = new System.Xml.XmlElement[1];
XmlDocument xmlDocument = new XmlDocument();
XmlElement fieldXmlElement = xmlDocument.CreateElement("IsActive");
fieldXmlElement.InnerText = bool.FalseString;
userSObject.Any[0] = fieldXmlElement;
SaveResult[] result = session.Binding.update(new sObject[] { userSObject });
foreach(SaveResult sr in result)
{
System.Diagnostics.Debug.WriteLine(sr.success + " " + sr.id);
if(!sr.success)
{
foreach(Error error in sr.errors)
{
System.Diagnostics.Debug.WriteLine(error.statusCode + " " + error.message);
}
}
}