I want to check whether the email id entered by user is unique or not so for that initially I have my variable Boolean valid = false;. On clicking a button i am taking the email id entered and checking it for valid email id expression using regular expression and then i am using an asyntask to check its uniqueness. Code in my onclicklistner is
if (emailid.matches(regexp) && emailid.length() > 0) {
new Validate().execute();
Toast.makeText(getApplicationContext(), valid.toString(), Toast.LENGTH_LONG).show();
if (valid) {
data.putString("eid", eid);
data.putString("firstname", firstname);
data.putString("lastname", lastname);
data.putString("emailid", emailid);
Intent i = new Intent(getApplicationContext(), GamesFragment.class);
startActivity(i);
} else {
Toast.makeText(getApplicationContext(), "Email Address Already Exist", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getApplicationContext(), "Check Your Email Address", Toast.LENGTH_LONG).show();
}
Here what problem i am facing is, for first time when i am entering an email which is unique and clicks the button, the Validate() asynctask checks and sets the valid variable to true, but it doesn't goes to next activity GamesFragment because i have declared valid = false initially. Now when i again click the button, then it goes to next activity as the valid variable is set to true because of previous click.
Now My Validate() asynctask is
private class Validate extends AsyncTask<Void, Void, Void> {
#Override
protected Boolean doInBackground(Void... params) {
ArrayList<NameValuePair> emailId = new ArrayList<NameValuePair>();
emailId.add(new BasicNameValuePair("email", emailid));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("url/validate.php");
httppost.setEntity(new UrlEncodedFormEntity(emailId));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
iss = entity.getContent();
} catch(Exception e) {
Log.e("pass 1", "Connection Error");
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader
(new InputStreamReader(iss,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
sb.append(line + "\n");
iss.close();
result = sb.toString();
} catch(Exception e) {
e.printStackTrace();
}
try {
JSONObject json_data = new JSONObject(result);
code=(json_data.getInt("code"));
if(code == 1)
valid = true;
else
valid = false;
Log.e("pass 3", "valid "+valid);
} catch(Exception e) {
e.printStackTrace();
}
return null;
}
}
Please help i am not getting why this is happening.
Create function to check validation.
private boolean function validate(String emailid){
if (emailid.matches(regexp) && emailid.length() > 0) {
return true;
}
return false;
}
use that function to decide event
if(validate(emailid)){ // if function return true then email is valid and good to go.
new Validate().execute();
}
For second condition you have to check it in your async task onPostExecute() that is Validate();
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
if(code == 1){
// check if response is valid than
Intent i = new Intent(getApplicationContext(), GamesFragment.class);
startActivity(i);
}
}
Related
I am running into an issue with signing up a user into Parse-Server while using Facebook.
When the user clicks on the Sign up with facebook icon this code will run..
ParseFacebookUtils.logInWithReadPermissionsInBackground(LoginRegister.this, permissions, new LogInCallback() {
#Override
public void done(ParseUser user, ParseException err) {
if (user == null) {
MethodContants.showLog(TAG, "Uh oh. The user cancelled the Facebook login.", true);
} else if (user.isNew()) {
MethodContants.showLog(TAG, "User logged in through Facebook", false);
getUserDetailsFromFacebook();
} else {
MethodContants.showLog(TAG, "User logged in through Facebook", false);
Intent intent = new Intent(LoginRegister.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
}
}
});
My getUserDetailsFromFacebook() method looks like this
private void getUserDetailsFromFacebook() {
GraphRequest graphRequest = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject jsonObject, GraphResponse response) {
try {
facebookUser = jsonObject.getString("name");
MethodContants.showLog(TAG, "json name object: " + jsonObject.getString("name"), false);
} catch (JSONException e) {
MethodContants.showLog(TAG, "Error when getting facebook name: " + e.getMessage(), true);
showToast("Error saving Facebook user.");
}
try {
facebookEmail = jsonObject.getString("email");
MethodContants.showLog(TAG, "json email object: " + jsonObject.getString("email"), false);
} catch (JSONException e) {
MethodContants.showLog(TAG, "Error when getting facebook email: " + e.getMessage(), true);
showToast("Error saving Facebook email.");
}
saveNewFacebookUser();
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "name,email");
graphRequest.setParameters(parameters);
graphRequest.executeAsync();
}
my saveNewFacebookUser() looks like this...
private void saveNewFacebookUser() {
final ParseUser newFacebookUser = new ParseUser();
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.profile_picture);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] image = stream.toByteArray();
ParseFile file = new ParseFile(AppConstants.PARSEUSER_IMAGE_FILE_NAME, image);
newFacebookUser.setUsername(facebookUser);
newFacebookUser.setEmail(facebookEmail);
newFacebookUser.put(AppConstants.PARSEUSER_FULLNAME, facebookUser);
newFacebookUser.put(AppConstants.PARSEUSER_FIRST_TIME_LOGGED_IN, "true");
newFacebookUser.put(AppConstants.PARSEUSER_PROFILE_IMAGE, file);
file.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
newFacebookUser.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
// USER CREATED!
// TODO SEND AN EMAIL TO THE USER WITH USERNAME AND PASSWORD
Intent intent = new Intent(LoginRegister.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
} else {
MethodContants.showLog(TAG, "Facebook Error:" + e.getMessage(), true);
showToast("Facebook Error: " + e.getMessage());
}
}
});
} else {
MethodContants.showLog(TAG, "Facebook Error:" + e.getMessage(), true);
showToast("Facebook Error: " + e.getMessage());
}
}
});
}
The error is telling me that I have to use signUpInBackground and not saveInBackground. However, when I do that, I get another error that says I need to save a password for the user -> which defeats the whole purpose of the facebook login.
Any help would be much appreciated!
I found the issue.
in the saveNewFacebookUser() method, I was setting it as a brand new user.
ParseUser new = new ParseUser();
This should have been
ParseUser new = ParseUser.getCurrentUser();
I will leave this up in case anyone has issues.
I am making an android app with login via facebook and custom signup. I am using AWS dynamodb to store the user data.
I am able to store the data from facebook and custom signup but unable to scan that data. Actually I want whenever a user come back to login with his/her credentials either custom or facebook, the app should check whether the entered fields present in the table or not. If it is unavailable then app will ask user to signup first.
MainActivity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "MainActivity";
Button login;
TextView signup;
TextView help;
EditText etUsername;
EditText etPassword;
String email;
String pass;
String email1;
String pass1;
private CognitoCachingCredentialsProvider credentialsProvider;
private CallbackManager callbackManager;
private LoginButton loginButton;
private ImageButton btnLoginFb;
private ProgressDialog progressDialog;
User user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
login = (Button) findViewById(R.id.loginbutton);
signup = (TextView) findViewById(R.id.textViewsignup);
help = (TextView) findViewById(R.id.textViewHelp);
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
login.setOnClickListener(this);
signup.setOnClickListener(this);
help.setOnClickListener(this);
Context mContext = this.getApplicationContext();
credentialsProvider = new CognitoCachingCredentialsProvider(
mContext, // get the context for the current activity
"us-east-1:*******************************",
Regions.US_EAST_1
);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.loginbutton:
email = etUsername.getText().toString();
pass = etPassword.getText().toString();
AmazonDynamoDBClient ddbClient = new AmazonDynamoDBClient(credentialsProvider);
DynamoDBMapper mapper = new DynamoDBMapper(ddbClient);
if (email != null && pass != null) {
Intent slideactivity = new Intent(MainActivity.this, Welcome.class);
Bundle bndlanimation =
ActivityOptions.makeCustomAnimation(getApplicationContext(), R.anim.animation, R.anim.animation2).toBundle();
startActivity(slideactivity, bndlanimation);
return;
}
else {
AlertDialog alertDialog = new AlertDialog.Builder(
MainActivity.this).create();
// Setting Dialog Title
alertDialog.setTitle("Oops");
// Setting Dialog Message
alertDialog.setMessage("No data found. You have to signup first!!!");
// Setting Icon to Dialog
//alertDialog.setIcon(R.drawable.tick);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
startActivity(new Intent(MainActivity.this, SignUp.class));
}
});
// Showing Alert Message
alertDialog.show();
}
break;
case R.id.textViewsignup:
Intent slideactivity = new Intent(MainActivity.this, SignUp.class);
Bundle bndlanimation =
ActivityOptions.makeCustomAnimation(getApplicationContext(), R.anim.animation, R.anim.animation2).toBundle();
startActivity(slideactivity, bndlanimation);
break;
case R.id.textViewHelp:
Intent slideactivity1 = new Intent(MainActivity.this, LoginHelp.class);
Bundle bndlanimation1 =
ActivityOptions.makeCustomAnimation(getApplicationContext(), R.anim.animation, R.anim.animation2).toBundle();
startActivity(slideactivity1, bndlanimation1);
break;
}
}
#Override
protected void onResume() {
super.onResume();
callbackManager = CallbackManager.Factory.create();
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions("public_profile", "email", "user_friends");
btnLoginFb = (ImageButton) findViewById(R.id.btnLoginFb);
btnLoginFb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
loginButton.performClick();
loginButton.setPressed(true);
loginButton.invalidate();
loginButton.registerCallback(callbackManager, mCallBack);
loginButton.setPressed(false);
loginButton.invalidate();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
private FacebookCallback<LoginResult> mCallBack = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
progressDialog.dismiss();
// App code
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
Log.e("response: ", response + "");
try {
user = new User();
user.facebookID = object.getString("id").toString();
pass = user.facebookID;
Log.e(pass, "id");
user.email = object.getString("email").toString();
email = user.email;
Log.e(email, "email");
user.name = object.getString("name").toString();
user.gender = object.getString("gender").toString();
PrefUtils.setCurrentUser(user, MainActivity.this);
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(MainActivity.this, "welcome " + user.name, Toast.LENGTH_LONG).show();
Intent intent = new Intent(MainActivity.this, Welcome.class);
startActivity(intent);
finish();
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender, birthday");
request.setParameters(parameters);
request.executeAsync();
new db().execute("");
}
#Override
public void onCancel() {
progressDialog.dismiss();
}
#Override
public void onError(FacebookException e) {
progressDialog.dismiss();
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class db extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
AmazonDynamoDBClient ddbClient = new AmazonDynamoDBClient(credentialsProvider);
DynamoDBMapper mapper = new DynamoDBMapper(ddbClient);
Item item = new Item();
mapper.load(Item.class, email, pass);
if(item==null)
{
startActivity(new Intent(MainActivity.this,SignUp.class));
}
else{
item.setEmail(email);
item.setPass(pass);
mapper.save(item);
startActivity(new Intent(MainActivity.this,Welcome.class));
}
mapper.load(Item.class, email,pass);
if(item==null) {
startActivity(new Intent(MainActivity.this,SignUp.class));
}
else{
startActivity(new Intent(MainActivity.this,Welcome.class));
}
return "Executed";
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
Logcat:-
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMappingException: Null key found for public java.lang.String com.ediode.graphics3d.Item.getEmail()
at com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper.getKey(DynamoDBMapper.java:434)
at com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper.load(DynamoDBMapper.java:387)
at com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper.load(DynamoDBMapper.java:466)
at com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper.load(DynamoDBMapper.java:350)
at com.ediode.graphics3d.MainActivity$db.doInBackground(MainActivity.java:339)
at com.ediode.graphics3d.MainActivity$db.doInBackground(MainActivity.java:333)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
I am stuck on this from 4,5 hours. It would be awesome if anyone can help me this stuff.
Thanks
What does your mapper class look like for item? I'm going to assume you have the email as a hash key with no range key because the login username should be unique. You only need the hash key of the object to load it using the load method. This is assuming that there is no range key.
Try using this.
AmazonDynamoDBClient ddbClient = new AmazonDynamoDBClient(credentialsProvider);
DynamoDBMapper mapper = new DynamoDBMapper(ddbClient);
// Use the password as the third parameter if it is a range key.
Item item = mapper.load(Item.class, email1);
if(item == null){
// That email is not in the database
}
else{
// Does exist in database, now compare password.
}
I'm trying to unit test my exception filter code. I can validate the exception, but I can't seem to find the exception message to validate in the unit test. Here is my code...
public class ExceptionHandlingAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
if (context.Exception is TimeoutException)
{
context.Response = context.Request.CreateErrorResponse(HttpStatusCode.RequestTimeout, context.Exception.Message);
return;
}
if (context.Exception is UnauthorizedAccessException)
{
context.Response = context.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, context.Exception.Message);
return;
}
context.Response = context.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to process your request.");
}
}
Unit Test Code
[Theory, MemberData("ExceptionData")]
public void OnExceptionTests(Exception ex, HttpStatusCode statusCode)
{
var request = new HttpRequestMessage();
var actionContext = InitializeActionContext(request);
var httpActionExectuedContext = new HttpActionExecutedContext(actionContext, ex);
var exceptionHandlingAttribute = new ExceptionHandlingAttribute();
exceptionHandlingAttribute.OnException(httpActionExectuedContext);
Assert.Equal(actionContext.Response.StatusCode, statusCode);
Assert.Equal(actionContext.Response.ReasonPhrase, ex.Message);
}
public static IEnumerable<object[]> ExceptionData
{
get
{
return new[]
{
new object[] { new TimeoutException("My timeout message."), HttpStatusCode.RequestTimeout }
};
}
}
My problem is : Assert.Equal(actionContext.Response.ReasonPhrase, ex.Message);
When I try to look at it in the watch window, I can't seem to find "My Timeout message" in the response.
UPDATE:
actionContext.Response.ReasonPhrase = "Request Timeout"
ex.Message = "My timeout message"
The message portion of the CreateErrorResponse isn't a property, you have to read the content to get the value. Here's what I did...
var responseContent = await actionContext.Response.Content.ReadAsStringAsync();
After reading, responseContent now had:
{ "message" : "My timeout message." }
I am quite new at Android.
So I am a bit confused of working with fragments.
I have found a very great tutorial.
So I have working code. But it is the layout oft a normal activity.
Then I tried to include it into a navigation drawer.
So the list view with data will only be shown when the menu item has been selected.
On the fragment View there is a never ending loading Dialog.
While debugging I have figured out that the code loads still the data and inserts it into feedItems.
So feedItems is filled correctly.
Now after listAdapter.notifyDataSetChanged() there happens nothing.
So here that is my code:
public class FragmentNews extends ListFragment {
private static final String TAG = FragmentNews.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
private String URL_FEED = "http://address.com";
public FragmentNews(){}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
loadDataForNews();
}
private void loadDataForNews(){
listView = this.getListView();
feedItems = new ArrayList<FeedItem>();
listAdapter = new FeedListAdapter(getActivity(), feedItems);
listView.setAdapter(listAdapter);
// We first check for cached request
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(URL_FEED);
if (entry != null) {
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONObject(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
URL_FEED, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
}
// List View Feed
private void parseJsonFeed(JSONObject response) {
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
// notify data changes to list adapater
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Can the problem be that the inflater of listAdapter is null?
Thanks for help!
Sometimes listAdapter.notifyDataSetChanged() does not work properly.
Try removing
listAdapter = new FeedListAdapter(getActivity(), feedItems);
listView.setAdapter(listAdapter);
from loadDataForNews() and adding in
place of listAdapter.notifyDataSetChanged();
I am trying to hit a url(login screen), get the jsessionid(J2EEJSESSIONID) and add it in the cookie store and in turn in to the context and hit the same url with credentials. I am expecting a login successful screen.
However i am bounced with the login screen again.
And, i printed the response header for both the hits. I am expecting both the response with the same J2EESESSIONID to maintain the session. Instead both the session ids are different. Pls help.
Pls find the code below:
HttpEntity entity = null;
DefaultHttpClient httpClient = new DefaultHttpClient();
try{
// Initialization
HttpPost httpPost = new HttpPost("https://yyyyy.xxx.com/enl");
HttpClientExample httpClientExample = new HttpClientExample();
CookieStore cookieStore = new BasicCookieStore();
HttpContext httpContext = new BasicHttpContext();
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpGet httpGet = new HttpGet("https://yyyyy.xxx.com/enl");
// Execute Get
HttpResponse httpResponse = httpClient.execute(httpGet, httpContext);
// Print the header for 1st url
org.apache.http.Header[] headers = httpResponse.getAllHeaders();
System.out.println("##### Header length::"+headers.length);
for(int i=0;i<headers.length; i++)
{
System.out.println("Header Name::"+headers[i].getName());
System.out.println("Header Val::"+headers[i].getValue());
}
// update Cookie for the next hit
org.apache.http.Header[] cookieHeaders = httpResponse.getHeaders("Set-Cookie");
String html = EntityUtils.toString(httpResponse.getEntity());
cookieStore = httpClientExample.updateCookieStore(cookieHeaders, cookieStore);
httpClient.setCookieStore(cookieStore);
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
// Setting the redirects since i received 302 error
httpClient.setRedirectStrategy(new DefaultRedirectStrategy() {
public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) {
boolean isRedirect=false;
try {
isRedirect = super.isRedirected(request, response, context);
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (!isRedirect) {
int responseCode = response.getStatusLine().getStatusCode();
if (responseCode == 301 || responseCode == 302) {
return true;
}
}
return false;
}
});
// Added because i received Circular redirect error
httpClient.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
// Execute Post with credentials
httpClient.getCredentialsProvider().setCredentials(
new AuthScope("http://yyyyy.xxx.com", 443),
new UsernamePasswordCredentials("usr", "pswd"));
httpPost.setHeader("Cookie", "JSESSIONID="+ getSessionId(cookieHeaders));
HttpResponse response = httpClient.execute(httpPost, httpContext);
// Print the response
entity = response.getEntity();
InputStream content1 = (InputStream)entity.getContent();
System.out.println("############### 2nd #####################"+response.getStatusLine().getStatusCode());
BufferedReader in1 =
new BufferedReader (new InputStreamReader (content1));
String line1;
while ((line1 = in1.readLine()) != null) {
System.out.println(line1);
}
// Print the header for 2nd url
org.apache.http.Header[] headers1 = response.getAllHeaders();
System.out.println("##### Header length 2 ::"+headers1.length);
for(int i=0;i<headers1.length; i++)
{
System.out.println("Header Name 2 ::"+headers1[i].getName());
System.out.println("Header Val 2 ::"+headers1[i].getValue());
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally{
try {
EntityUtils.consume(entity);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
httpClient.getConnectionManager().shutdown();
}
}
private static String getSessionId(org.apache.http.Header[] headers) {
// TODO Auto-generated method stub
for(int i=0;i<headers.length; i++)
{
String str = headers[i].getValue();
String[] strArray = str.split("=");
String[] cookieValueArray = strArray[1].split(";");
System.out.println(strArray[0]+"|"+cookieValueArray[0]);
if(strArray[0].startsWith("J2EEJSESSION"))
{
System.out.println("cookieValueArray[0]:"+cookieValueArray[0]);
return cookieValueArray[0];
}
}
return null;
}
protected CookieStore updateCookieStore(org.apache.http.Header[] headers, CookieStore cookieStore)
{
for(int i=0;i<headers.length; i++)
{
String str = headers[i].getValue();
String[] strArray = str.split("=");
String[] cookieValueArray = strArray[1].split(";");
System.out.println(strArray[0]+"|"+cookieValueArray[0]);
BasicClientCookie cookie = new BasicClientCookie(strArray[0], "A"+cookieValueArray[0]);
/*if(strArray[0].startsWith("J2EEJSESSION"))
{
cookie.setDomain("yyyyy.xxx.com");
}
else
{
cookie.setDomain(".xxx.com");
}*/
cookie.setDomain(".xxx.com");
cookie.setPath("/");
cookieStore.addCookie(cookie);
if(strArray[0].startsWith("J2EEJSESSION"))
{
BasicClientCookie cookie1 = new BasicClientCookie("JSESSIONID", "A"+cookieValueArray[0]);
cookie1.setDomain(".xxx.com");
cookie1.setPath("/");
cookieStore.addCookie(cookie1);
}
}
return cookieStore;
}
Another observation:
When i remove the "A" concat from the below snippet, i am not getting the J2EESESSIONID in the 2nd hit:
BasicClientCookie cookie = new BasicClientCookie(strArray[0], "A"+cookieValueArray[0]);
Found the answer on the same day I posted this question.. thought of sharing..
The answer is very simple.. For some reasons the authentication wasn't successful, hence the new jsessionId was created. Replaced "httpClient.getCredentialsProvider().setCredentials()" with "BasicNameValuePair" and it worked :)