List of usage examples for org.apache.http.auth AuthenticationException AuthenticationException
public AuthenticationException()
From source file:com.bearstech.android.myownsync.client.NetworkUtilities.java
/** * Fetches status messages for the user's friends from the server * //from w w w . j a va 2 s .c o m * @param account The account being synced. * @param authtoken The authtoken stored in the AccountManager for the * account * @return list The list of status messages received from the server. */ public static List<User.Status> fetchFriendStatuses(Account account, String authtoken) throws JSONException, ParseException, IOException, AuthenticationException { Log.d(TAG, "fetchFriendStatuses"); final ArrayList<User.Status> statusList = new ArrayList<User.Status>(); final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(PARAM_USERNAME, account.name)); params.add(new BasicNameValuePair(PARAM_PASSWORD, authtoken)); HttpEntity entity = null; entity = new UrlEncodedFormEntity(params); final HttpPost post = new HttpPost(base_url + FETCH_STATUS_URI); post.addHeader(entity.getContentType()); post.setEntity(entity); maybeCreateHttpClient(); final HttpResponse resp = mHttpClient.execute(post); final String response = EntityUtils.toString(resp.getEntity()); if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // Succesfully connected to the samplesyncadapter server and // authenticated. // Extract friends data in json format. final JSONArray statuses = new JSONArray(response); for (int i = 0; i < statuses.length(); i++) { statusList.add(User.Status.valueOf(statuses.getJSONObject(i))); } } else { if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { Log.e(TAG, "Authentication exception in fetching friend status list"); throw new AuthenticationException(); } else { Log.e(TAG, "Server error in fetching friend status list"); throw new IOException(); } } return statusList; }
From source file:com.senechaux.rutino.utils.NetworkUtilities.java
/** * Fetches the list of entities from the server * /*from w w w.java2 s.co m*/ * @param account * The account being synced. * @param authtoken * The authtoken stored in AccountManager for this account * @param lastUpdated * The last time that sync was performed * @return list The list of updates received from the server. */ public static List<BaseEntity> fetchEntityUpdates(Context ctxt, Account account, String authtoken, Date lastUpdated, String url, Class<?> myClass) throws JSONException, ParseException, IOException, AuthenticationException { final ArrayList<BaseEntity> entityList = new ArrayList<BaseEntity>(); final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); // params.add(new BasicNameValuePair(PARAM_USERNAME, account.name)); // params.add(new BasicNameValuePair(PARAM_PASSWORD, authtoken)); // if (lastUpdated != null) { // final SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm"); // formatter.setTimeZone(TimeZone.getTimeZone("UTC")); // params.add(new BasicNameValuePair(PARAM_UPDATED, formatter.format(lastUpdated))); // } Log.i(TAG, params.toString()); Log.v(TAG, "authtoken: " + authtoken); HttpEntity entity = null; entity = new UrlEncodedFormEntity(params); url = url + "?user_id=" + authtoken; Log.v(TAG, "url: " + url); final HttpGet get = new HttpGet(url); get.addHeader(entity.getContentType()); maybeCreateHttpClient(); final HttpResponse resp = mHttpClient.execute(get); final String response = EntityUtils.toString(resp.getEntity()); if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // Succesfully connected to the samplesyncadapter server and // authenticated. // Extract wallets data in json format. final JSONArray entities = new JSONArray(response); Log.d(TAG, response); for (int i = 0; i < entities.length(); i++) { if (myClass == Wallet.class) { entityList.add(Wallet.valueOf(ctxt, entities.getJSONObject(i))); } else if (myClass == Report.class) { entityList.add(Report.valueOf(ctxt, entities.getJSONObject(i))); } else if (myClass == AccountType.class) { entityList.add(AccountType.valueOf(ctxt, entities.getJSONObject(i))); } else if (myClass == Currency.class) { entityList.add(Currency.valueOf(ctxt, entities.getJSONObject(i))); } else if (myClass == AccountEntity.class) { entityList.add(AccountEntity.valueOf(ctxt, entities.getJSONObject(i))); } else if (myClass == Transaction.class) { entityList.add(Transaction.valueOf(ctxt, entities.getJSONObject(i))); } else if (myClass == PeriodicTransaction.class) { entityList.add(PeriodicTransaction.valueOf(ctxt, entities.getJSONObject(i))); } } } else { if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { Log.e(TAG, "Authentication exception in fetching remote data"); throw new AuthenticationException(); } else { Log.e(TAG, "Server error in fetching remote data: " + resp.getStatusLine()); throw new IOException(); } } return entityList; }
From source file:nl.hardijzer.bitonsync.client.NetworkUtilities.java
/** * Fetches the list of friend data updates from the server * // w ww . j av a 2 s .c o m * @param account The account being synced. * @param authtoken The authtoken stored in AccountManager for this account * @param lastUpdated The last time that sync was performed * @return list The list of updates received from the server. */ public static List<User> fetchFriendUpdates(Account account, String authtoken) throws ParseException, IOException, AuthenticationException { ArrayList<User> friendList = new ArrayList<User>(); final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(PARAM_USERNAME, account.name)); params.add(new BasicNameValuePair(PARAM_PASSWORD, authtoken)); params.add(new BasicNameValuePair(PARAM_METHOD, DATA_METHOD)); Log.i(TAG, params.toString()); HttpEntity entity = null; entity = new UrlEncodedFormEntity(params); final HttpPost post = new HttpPost(SYNC_URI);//FETCH_FRIEND_UPDATES_URI post.addHeader(entity.getContentType()); post.setEntity(entity); maybeCreateHttpClient(); final HttpResponse resp = mHttpClient.execute(post); //final HttpResponse resp = mHttpClient.execute(new HttpGet(FETCH_FRIEND_UPDATES_URI)); if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // Succesfully connected to the samplesyncadapter server and // authenticated. // Extract friends data in json format. final String response = EntityUtils.toString(resp.getEntity()); boolean loggedin = response.startsWith("OK "); if (loggedin) { String data = response.substring(3); GsonBuilder bld = new GsonBuilder(); bld.registerTypeAdapter(User.class, User.deserializer); Gson gson = bld.create(); friendList = gson.fromJson(data, new TypeToken<ArrayList<User>>() { }.getType()); /* String[] parts=response.split("<td class=''>"); for (int i=1; i<parts.length; i++) { int end=parts[i].indexOf("</td>"); if (end>=0) parts[i]=parts[i].substring(0,end); parts[i]=unhtmlify(parts[i]); } for (int i=1; i+6<=parts.length; i+=6) { Matcher naammatcher=Pattern.compile("(^.+) \\((.+?)\\) (.+$)").matcher(parts[i]); String naam,voornaam,achternaam; if (naammatcher.find()) { voornaam=parts[i].substring(naammatcher.start(2),naammatcher.end(2)); naam=parts[i].substring(naammatcher.start(1),naammatcher.end(1)); achternaam=parts[i].substring(naammatcher.start(3),naammatcher.end(3)); } else { voornaam=parts[i]; achternaam=""; int split=voornaam.indexOf(" "); if (split>=0) { achternaam=voornaam.substring(split+1); voornaam=voornaam.substring(0,split); } naam=voornaam; } String telefoon=parts[i+1]; String mobiel=parts[i+2]; if (telefoon.startsWith("0")) { telefoon="+31"+telefoon.substring(1); } if (mobiel.startsWith("0")) { mobiel="+31"+mobiel.substring(1); } String geboorte=parts[i+5]; String[] geboorte_parts=geboorte.split(" "); if (geboorte_parts.length==3) { String dag=geboorte_parts[0]; String jaar=geboorte_parts[2]; String maand=geboorte_parts[1]; if (dag.length()<2) dag="00".substring(dag.length())+dag; if (jaar.length()==2) jaar="19"+jaar; //januari 1 ja //februari 2 f //maart 3 ma //april 4 ap //mei 5 me //juni 6 jun //juli 7 jul //aug 8 au //sep 9 s //okt 12 o //nov 11 n //dec 12 d if (maand.startsWith("ja")) geboorte=jaar+"-01-"+dag; else if (maand.startsWith("f")) geboorte=jaar+"-02-"+dag; else if (maand.startsWith("ma")) geboorte=jaar+"-03-"+dag; else if (maand.startsWith("ap")) geboorte=jaar+"-04-"+dag; else if (maand.startsWith("me")) geboorte=jaar+"-05-"+dag; else if (maand.startsWith("jun")) geboorte=jaar+"-06-"+dag; else if (maand.startsWith("jul")) geboorte=jaar+"-07-"+dag; else if (maand.startsWith("au")) geboorte=jaar+"-08-"+dag; else if (maand.startsWith("s")) geboorte=jaar+"-09-"+dag; else if (maand.startsWith("o")) geboorte=jaar+"-10-"+dag; else if (maand.startsWith("n")) geboorte=jaar+"-11-"+dag; else if (maand.startsWith("d")) geboorte=jaar+"-12-"+dag; } friendList.add(new User(naam, voornaam, achternaam, telefoon, mobiel, parts[i+3], parts[i+4], geboorte)); }*/ } else { Log.e(TAG, "Authentication exception in fetching remote contacts (content)"); throw new AuthenticationException(); } } else { if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { Log.e(TAG, "Authentication exception in fetching remote contacts"); throw new AuthenticationException(); } else { Log.e(TAG, "Server error in fetching remote contacts: " + resp.getStatusLine()); throw new IOException(); } } if (friendList.isEmpty()) { Log.e(TAG, "No friends found, auth error?: " + resp.getStatusLine()); throw new AuthenticationException(); } return friendList; }
From source file:com.deliciousdroid.client.DeliciousApi.java
/** * Performs an api call to Delicious's http based api methods. * //from www. j ava 2 s . c o m * @param url URL of the api method to call. * @param params Extra parameters included in the api call, as specified by different methods. * @param account The account being synced. * @param context The current application context. * @return A String containing the response from the server. * @throws IOException If a server error was encountered. * @throws AuthenticationException If an authentication error was encountered. */ private static InputStream DeliciousApiCall(String url, TreeMap<String, String> params, Account account, Context context) throws IOException, AuthenticationException { final AccountManager am = AccountManager.get(context); if (account == null) throw new AuthenticationException(); final String username = account.name; String authtoken = null; try { authtoken = am.blockingGetAuthToken(account, Constants.AUTHTOKEN_TYPE, false); } catch (OperationCanceledException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (AuthenticatorException e) { // TODO Auto-generated catch block e.printStackTrace(); } Uri.Builder builder = new Uri.Builder(); builder.scheme(SCHEME); builder.authority(DELICIOUS_AUTHORITY); builder.appendEncodedPath(url); for (String key : params.keySet()) { builder.appendQueryParameter(key, params.get(key)); } String apiCallUrl = builder.build().toString(); Log.d("apiCallUrl", apiCallUrl); final HttpGet post = new HttpGet(apiCallUrl); post.setHeader("User-Agent", "DeliciousDroid"); post.setHeader("Accept-Encoding", "gzip"); DefaultHttpClient client = (DefaultHttpClient) HttpClientFactory.getThreadSafeClient(); CredentialsProvider provider = client.getCredentialsProvider(); Credentials credentials = new UsernamePasswordCredentials(username, authtoken); provider.setCredentials(SCOPE, credentials); client.addRequestInterceptor(new PreemptiveAuthInterceptor(), 0); final HttpResponse resp = client.execute(post); final int statusCode = resp.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { final HttpEntity entity = resp.getEntity(); InputStream instream = entity.getContent(); final Header encoding = entity.getContentEncoding(); if (encoding != null && encoding.getValue().equalsIgnoreCase("gzip")) { instream = new GZIPInputStream(instream); } return instream; } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) { throw new AuthenticationException(); } else { throw new IOException(); } }
From source file:com.roadwarrior.vtiger.client.NetworkUtilities.java
/** * Fetches the list of friend data updates from the server * // w ww . j a v a2 s.c o m * @param account The account being synced. * @param authtoken The authtoken stored in AccountManager for this account * @param lastUpdated The last time that sync was performed * @return list The list of updates received from the server. */ public static List<User> fetchFriendUpdates(Account account, String auth_url, String authtoken, long serverSyncState/*Date lastUpdated*/, String type_contact) throws JSONException, ParseException, IOException, AuthenticationException { ArrayList<User> friendList = new ArrayList<User>(); ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(PARAM_OPERATION, "sync")); params.add(new BasicNameValuePair(PARAM_SESSIONNAME, sessionName)); if (serverSyncState == 0) params.add(new BasicNameValuePair("modifiedTime", "878925701")); // il y a 14 ans.... else params.add(new BasicNameValuePair("modifiedTime", String.valueOf(serverSyncState))); params.add(new BasicNameValuePair("elementType", type_contact)); // "Accounts,Leads , Contacts... Log.d(TAG, "fetchFriendUpdates"); // params.add(new BasicNameValuePair(PARAM_QUERY, "select firstname,lastname,mobile,email,homephone,phone from Contacts;")); // if (lastUpdated != null) { // final SimpleDateFormat formatter = // new SimpleDateFormat("yyyy/MM/dd HH:mm"); // formatter.setTimeZone(TimeZone.getTimeZone("UTC")); // params.add(new BasicNameValuePair(PARAM_UPDATED, formatter // .format(lastUpdated))); // } // HTTP GET REQUEST URL url = new URL(auth_url + "/webservice.php?" + URLEncodedUtils.format(params, "utf-8")); HttpURLConnection con; con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("Content-length", "0"); con.setRequestProperty("accept", "application/json"); con.setUseCaches(false); con.setAllowUserInteraction(false); int timeout = 10000; // si tiemout pas assez important la connection echouait =>IOEXception con.setConnectTimeout(timeout); con.setReadTimeout(timeout); con.connect(); int status = con.getResponseCode(); LastFetchOperationStatus = true; if (status == HttpURLConnection.HTTP_OK) { // Succesfully connected to the samplesyncadapter server and // authenticated. // Extract friends data in json format. BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); String response = sb.toString(); Log.i(TAG, "--response--"); // <Hack> to bypass vtiger 5.4 webservice bug: int idx = response.indexOf("{\"success"); response = response.substring(idx); Log.i(TAG, response); // </Hack> Log.i(TAG, "--response end--"); JSONObject result = new JSONObject(response); String success = result.getString("success"); Log.i(TAG, "success is" + success); if (success == "true") { Log.i(TAG, result.getString("result")); final JSONObject data = new JSONObject(result.getString("result")); final JSONArray friends = new JSONArray(data.getString("updated")); // == VTiger updated contacts == for (int i = 0; i < friends.length(); i++) { friendList.add(User.valueOf(friends.getJSONObject(i))); } // == Vtiger contacts deleted === String deleted_contacts = data.getString("deleted"); Log.d(TAG, deleted_contacts); Log.d(TAG, deleted_contacts.substring(deleted_contacts.indexOf("["))); List<String> items = Arrays.asList( deleted_contacts.substring(deleted_contacts.indexOf("[") + 1, deleted_contacts.indexOf("]")) .split("\\s*,\\s*")); for (int ii = 0; ii < items.size(); ii++) { Log.d(TAG, items.get(ii)); if (items.get(ii).startsWith("\"4x")) // this is a contact { //Log.d(TAG,"{\"id\":"+items.get(ii)+",\"d\":true,\"contact_no\":1}"); JSONObject item = new JSONObject( "{\"id\":" + items.get(ii) + ",\"d\":true,\"contact_no\":\"CON1\"}"); friendList.add(User.valueOf(item)); } if (items.get(ii).startsWith("\"3x")) // this is an account { //Log.d(TAG,"{\"id\":"+items.get(ii)+",\"d\":true,\"contact_no\":1}"); JSONObject item = new JSONObject( "{\"id\":" + items.get(ii) + ",\"d\":true,\"account_no\":\"ACC1\"}"); friendList.add(User.valueOf(item)); } if (items.get(ii).startsWith("\"2x")) // this is a lead { //Log.d(TAG,"{\"id\":"+items.get(ii)+",\"d\":true,\"contact_no\":1}"); JSONObject item = new JSONObject( "{\"id\":" + items.get(ii) + ",\"d\":true,\"lead_no\":\"LEA1\"}"); friendList.add(User.valueOf(item)); } } } else { LastFetchOperationStatus = false; // FIXME: else false... // possible error code : //{"success":false,"error":{"code":"AUTHENTICATION_REQUIRED","message":"Authencation required"}} // throw new AuthenticationException(); } } else { if (status == HttpURLConnection.HTTP_UNAUTHORIZED) { LastFetchOperationStatus = false; Log.e(TAG, "Authentication exception in fetching remote contacts"); throw new AuthenticationException(); } else { LastFetchOperationStatus = false; Log.e(TAG, "Server error in fetching remote contacts: "); throw new IOException(); } } return friendList; }
From source file:com.talk.demo.util.NetworkUtilities.java
/** * Perform 2-way sync with the server-side contacts. We send a request that * includes all the locally-dirty contacts so that the server can process * those changes, and we receive (and return) a list of contacts that were * updated on the server-side that need to be updated locally. * * @param account The account being synced * @param authtoken The authtoken stored in the AccountManager for this * account//w ww.j av a 2 s . co m * @param serverSyncState A token returned from the server on the last sync * @param dirtyContacts A list of the contacts to send to the server * @return A list of contacts that we need to update locally */ public static List<RawRecord> syncRecords(Account account, String authtoken, long serverSyncState, List<RawRecord> dirtyRecords) throws JSONException, ParseException, IOException, AuthenticationException { // Convert our list of User objects into a list of JSONObject List<JSONObject> jsonRecords = new ArrayList<JSONObject>(); for (RawRecord rawRecord : dirtyRecords) { jsonRecords.add(rawRecord.toJSONObject()); } // Create a special JSONArray of our JSON contacts JSONArray buffer = new JSONArray(jsonRecords); // Create an array that will hold the server-side records // that have been changed (returned by the server). final ArrayList<RawRecord> serverDirtyList = new ArrayList<RawRecord>(); // Prepare our POST data final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(PARAM_USERNAME, account.name)); //params.add(new BasicNameValuePair(PARAM_AUTH_TOKEN, authtoken)); params.add(new BasicNameValuePair(PARAM_RECORDS_DATA, buffer.toString())); String tempBuffer = null; if (authtoken.split(";").length > 1) { tempBuffer = authtoken.split(";")[1]; } if (tempBuffer.length() > 10) { params.add(new BasicNameValuePair("csrfmiddlewaretoken", tempBuffer.substring(10))); } Log.d(TAG, "auth toke: " + authtoken); if (serverSyncState > 0) { params.add(new BasicNameValuePair(PARAM_SYNC_STATE, Long.toString(serverSyncState))); } Log.i(TAG, params.toString()); HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8); // Send the updated friends data to the server Log.i(TAG, "Syncing to: " + SYNC_RECORDS_URI); final HttpPost post = new HttpPost(SYNC_RECORDS_URI); post.addHeader(entity.getContentType()); post.addHeader("Cookie", authtoken); post.setEntity(entity); final HttpResponse resp = getHttpClient().execute(post); final String response = EntityUtils.toString(resp.getEntity()); if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // Our request to the server was successful - so we assume // that they accepted all the changes we sent up, and // that the response includes the contacts that we need // to update on our side... final JSONArray serverRecords = new JSONArray(response); Log.d(TAG, serverRecords.toString()); for (int i = 0; i < serverRecords.length(); i++) { RawRecord rawRecord = RawRecord.valueOf(serverRecords.getJSONObject(i)); if (rawRecord != null) { serverDirtyList.add(rawRecord); } } } else { if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { Log.e(TAG, "Authentication exception in sending dirty contacts"); throw new AuthenticationException(); } else { Log.e(TAG, "Server error in sending dirty contacts: " + resp.getStatusLine()); throw new IOException(); } } return serverDirtyList; }
From source file:com.pindroid.client.PinboardApi.java
/** * Performs an api call to Pinboard's http based api methods. * //from w w w .j a va2 s.c o m * @param url URL of the api method to call. * @param params Extra parameters included in the api call, as specified by different methods. * @param account The account being synced. * @param context The current application context. * @return A String containing the response from the server. * @throws IOException If a server error was encountered. * @throws AuthenticationException If an authentication error was encountered. * @throws TooManyRequestsException * @throws PinboardException */ private static InputStream PinboardApiCall(String url, TreeMap<String, String> params, Account account, Context context) throws IOException, AuthenticationException, TooManyRequestsException, PinboardException { final AccountManager am = AccountManager.get(context); if (account == null) throw new AuthenticationException(); final String username = account.name; String authtoken = "00000000000000000000"; // need to provide a sane default value, since a token that is too short causes a 500 error instead of 401 try { String tempAuthtoken = am.blockingGetAuthToken(account, Constants.AUTHTOKEN_TYPE, true); if (tempAuthtoken != null) authtoken = tempAuthtoken; } catch (Exception e) { e.printStackTrace(); throw new AuthenticationException("Error getting auth token"); } params.put("auth_token", username + ":" + authtoken); final Uri.Builder builder = new Uri.Builder(); builder.scheme(SCHEME); builder.authority(PINBOARD_AUTHORITY); builder.appendEncodedPath(url); for (String key : params.keySet()) { builder.appendQueryParameter(key, params.get(key)); } String apiCallUrl = builder.build().toString(); Log.d("apiCallUrl", apiCallUrl); final HttpGet post = new HttpGet(apiCallUrl); post.setHeader("User-Agent", "PinDroid"); post.setHeader("Accept-Encoding", "gzip"); final DefaultHttpClient client = (DefaultHttpClient) HttpClientFactory.getThreadSafeClient(); final HttpResponse resp = client.execute(post); final int statusCode = resp.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { final HttpEntity entity = resp.getEntity(); InputStream instream = entity.getContent(); final Header encoding = entity.getContentEncoding(); if (encoding != null && encoding.getValue().equalsIgnoreCase("gzip")) { instream = new GZIPInputStream(instream); } return instream; } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) { am.invalidateAuthToken(Constants.AUTHTOKEN_TYPE, authtoken); try { authtoken = am.blockingGetAuthToken(account, Constants.AUTHTOKEN_TYPE, true); } catch (Exception e) { e.printStackTrace(); throw new AuthenticationException("Invalid auth token"); } throw new AuthenticationException(); } else if (statusCode == Constants.HTTP_STATUS_TOO_MANY_REQUESTS) { throw new TooManyRequestsException(300); } else if (statusCode == HttpStatus.SC_REQUEST_URI_TOO_LONG) { throw new PinboardException(); } else { throw new IOException(); } }
From source file:com.talk.demo.util.NetworkUtilities.java
public static List<RawFriend> syncFriends(Account account, String authtoken, long serverSyncState, List<RawFriend> dirtyFriends) throws JSONException, ParseException, IOException, AuthenticationException { // Convert our list of User objects into a list of JSONObject List<JSONObject> jsonRecords = new ArrayList<JSONObject>(); for (RawFriend rawFriend : dirtyFriends) { jsonRecords.add(rawFriend.toJSONObject()); }/*from w w w . ja v a 2 s .c o m*/ // Create a special JSONArray of our JSON contacts JSONArray buffer = new JSONArray(jsonRecords); // Create an array that will hold the server-side records // that have been changed (returned by the server). final ArrayList<RawFriend> serverDirtyList = new ArrayList<RawFriend>(); // Prepare our POST data final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(PARAM_USERNAME, account.name)); //params.add(new BasicNameValuePair(PARAM_AUTH_TOKEN, authtoken)); params.add(new BasicNameValuePair(PARAM_RECORDS_DATA, buffer.toString())); String tempBuffer = null; if (authtoken.split(";").length > 1) { tempBuffer = authtoken.split(";")[1]; } if (tempBuffer.length() > 10) { params.add(new BasicNameValuePair("csrfmiddlewaretoken", tempBuffer.substring(10))); } Log.d(TAG, "auth toke: " + authtoken); if (serverSyncState > 0) { params.add(new BasicNameValuePair(PARAM_SYNC_STATE, Long.toString(serverSyncState))); } Log.i(TAG, params.toString()); HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8); // Send the updated friends data to the server Log.i(TAG, "Syncing to: " + SYNC_FRIENDS_URI); final HttpPost post = new HttpPost(SYNC_FRIENDS_URI); post.addHeader(entity.getContentType()); post.addHeader("Cookie", authtoken); post.setEntity(entity); final HttpResponse resp = getHttpClient().execute(post); final String response = EntityUtils.toString(resp.getEntity()); if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // Our request to the server was successful - so we assume // that they accepted all the changes we sent up, and // that the response includes the contacts that we need // to update on our side... final JSONArray serverRecords = new JSONArray(response); Log.d(TAG, serverRecords.toString()); for (int i = 0; i < serverRecords.length(); i++) { RawFriend rawRecord = RawFriend.valueOf(serverRecords.getJSONObject(i)); if (rawRecord != null) { serverDirtyList.add(rawRecord); } } } else { if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { Log.e(TAG, "Authentication exception in sending dirty contacts"); throw new AuthenticationException(); } else { Log.e(TAG, "Server error in sending dirty friends: " + resp.getStatusLine()); throw new IOException(); } } return serverDirtyList; }
From source file:org.gege.caldavsyncadapter.caldav.CaldavFacade.java
private void checkStatus(HttpResponse response) throws AuthenticationException, FileNotFoundException, ClientProtocolException { final int statusCode = response.getStatusLine().getStatusCode(); lastStatusCode = statusCode;//from w w w.j ava2 s. c om if (response.containsHeader("ETag")) lastETag = response.getFirstHeader("ETag").getValue(); else lastETag = ""; if (response.containsHeader("DAV")) lastDav = response.getFirstHeader("DAV").getValue(); else lastDav = ""; switch (statusCode) { case 401: throw new AuthenticationException(); case 404: throw new FileNotFoundException(); case 409: //Conflict case 412: case 200: case 201: case 204: case 207: return; default: throw new ClientProtocolException("StatusCode: " + statusCode); } }
From source file:com.ibm.sbt.services.client.ClientService.java
/** * Process the specified response/*from ww w. j ava2s . c om*/ * * @param httpClient * @param httpRequestBase * @param httpResponse * @param args * @return * @throws ClientServicesException */ protected Response processResponse(HttpClient httpClient, HttpRequestBase httpRequestBase, HttpResponse httpResponse, Args args) throws ClientServicesException { if (logger.isLoggable(Level.FINEST)) { logger.entering(sourceClass, "processResponse", new Object[] { httpRequestBase.getURI(), httpResponse.getStatusLine() }); } int statusCode = httpResponse.getStatusLine().getStatusCode(); String reasonPhrase = httpResponse.getStatusLine().getReasonPhrase(); if (!checkStatus(statusCode)) { if (SbtCoreLogger.SBT.isErrorEnabled()) { // Do not throw an exception here as some of the non OK responses are not error cases. String msg = "Client service request to: {0} did not return OK status. Status returned: {1}, reason: {2}, expected: {3}"; msg = StringUtil.format(msg, httpRequestBase.getURI(), statusCode, reasonPhrase, HttpStatus.SC_OK); SbtCoreLogger.SBT.traceDebugp(this, "processResponse", msg); } } if (isResponseRequireAuthentication(httpResponse)) { forceAuthentication(args); throw new ClientServicesException(new AuthenticationException()); } Handler format = findHandler(httpRequestBase, httpResponse, args.handler); Response response = new Response(httpClient, httpResponse, httpRequestBase, args, format); if (logger.isLoggable(Level.FINEST)) { logger.exiting(sourceClass, "processResponse", response); } return response; }