List of usage examples for org.apache.http.client ClientProtocolException getLocalizedMessage
public String getLocalizedMessage()
From source file:com.nononsenseapps.notepad.sync.SyncAdapter.java
@SuppressWarnings("unchecked") @Override/*ww w.ja va 2s . c o m*/ public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) { final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mContext); // Only sync if it has been enabled by the user, and account is selected // Issue on reinstall where account approval is remembered by system if (settings.getBoolean(SyncPrefs.KEY_SYNC_ENABLE, false) && !settings.getString(SyncPrefs.KEY_ACCOUNT, "").isEmpty() && account.name.equals(settings.getString(SyncPrefs.KEY_ACCOUNT, ""))) { if (SYNC_DEBUG_PRINTS) Log.d(TAG, "onPerformSync"); Intent i = new Intent(SYNC_STARTED); mContext.sendBroadcast(i); // For later Intent doneIntent = new Intent(SYNC_FINISHED); doneIntent.putExtra(SYNC_RESULT, ERROR); // Initialize necessary stuff GoogleDBTalker dbTalker = new GoogleDBTalker(account.name, provider); GoogleAPITalker apiTalker = new GoogleAPITalker(); try { boolean connected = apiTalker.initialize(accountManager, account, AUTH_TOKEN_TYPE, NOTIFY_AUTH_FAILURE); if (connected) { if (SYNC_DEBUG_PRINTS) Log.d(TAG, "We got an authToken atleast"); try { // FIrst of all, we need the latest updated time later. // So // save // that for now. // This is the latest time we synced String lastUpdate = dbTalker.getLastUpdated(account.name); //String lastUpdate = settings.getString(PREFS_LAST_SYNC_DATE, null); // Get the latest hash value we saw on the server String localEtag = settings.getString(PREFS_LAST_SYNC_ETAG, ""); // Prepare lists for items ArrayList<GoogleTaskList> listsToSaveToDB = new ArrayList<GoogleTaskList>(); HashMap<GoogleTaskList, ArrayList<GoogleTask>> tasksInListToSaveToDB = new HashMap<GoogleTaskList, ArrayList<GoogleTask>>(); HashMap<Long, ArrayList<GoogleTask>> tasksInListToUpload = new HashMap<Long, ArrayList<GoogleTask>>(); HashMap<Long, ArrayList<GoogleTask>> allTasksInList = new HashMap<Long, ArrayList<GoogleTask>>(); // gets all tasks in one query ArrayList<GoogleTask> allTasks = dbTalker.getAllTasks(allTasksInList, tasksInListToUpload); ArrayList<GoogleTaskList> listsToUpload = new ArrayList<GoogleTaskList>(); ArrayList<GoogleTaskList> allLocalLists = new ArrayList<GoogleTaskList>(); // gets all lists in one query dbTalker.getAllLists(allLocalLists, listsToUpload); // Get the current hash value on the server and all // remote // lists if upload is not true String serverEtag = apiTalker.getModifiedLists(localEtag, allLocalLists, listsToSaveToDB); // IF the tags match, then nothing has changed on // server. if (localEtag.equals(serverEtag)) { if (SYNC_DEBUG_PRINTS) Log.d(TAG, "Etags match, nothing to download"); } else { if (SYNC_DEBUG_PRINTS) Log.d(TAG, "Etags dont match, downloading new tasks"); // Download tasks which have been updated since last // time for (GoogleTaskList list : listsToSaveToDB) { if (list.id != null && !list.id.isEmpty()) { if (SYNC_DEBUG_PRINTS) Log.d(TAG, "Saving remote modified tasks for: " + list.id); tasksInListToSaveToDB.put(list, list.downloadModifiedTasks(apiTalker, allTasks, lastUpdate)); } } } if (SYNC_DEBUG_PRINTS) Log.d(TAG, "Getting stuff we want to upload"); // Get stuff we would like to upload to server // In case of lists, locally modified versions always // wins // in // conflict, so nothing more to do for (GoogleTaskList list : allLocalLists) { ArrayList<GoogleTask> moddedTasks = tasksInListToUpload.get(list.dbId); if (moddedTasks != null && !moddedTasks.isEmpty()) { // There are some tasks here which we want to // upload if (SYNC_DEBUG_PRINTS) Log.d(TAG, "List id " + list.dbId + ", Locally modified tasks found: " + moddedTasks.size()); // Now we need to handle possible conflicts in // the // tasks. But this has already been sorted when // we // downloaded them // For any task which exists in stuffToSaveToDB, // we // should not upload it // Iterate over a clone to avoid concurrency // problems since we will be modifying // the list during iteration for (GoogleTask moddedTask : (ArrayList<GoogleTask>) moddedTasks.clone()) { ArrayList<GoogleTask> tasksToBeSaved = tasksInListToSaveToDB.get(list); if (tasksToBeSaved != null && tasksToBeSaved.contains(moddedTask)) { if (SYNC_DEBUG_PRINTS) Log.d(TAG, "This modified task was newer on server, removing from upload list: " + moddedTask.title); moddedTasks.remove(moddedTask); } // In the case that a task has been deleted // before it was synced the first time // We should definitely not sync it. Only // delete // it later if (moddedTask.deleted == 1 && (moddedTask.id == null || moddedTask.id.isEmpty())) { moddedTasks.remove(moddedTask); } } } } if (SYNC_DEBUG_PRINTS) Log.d(TAG, "Uploading lists"); // First thing we want to do is upload stuff, because // some // values are updated then boolean uploadedStuff = false; // Start with lists for (GoogleTaskList list : listsToUpload) { GoogleTaskList result = apiTalker.uploadList(list); uploadedStuff = true; if (result != null) { // Make sure that local version is the same as // server's for (GoogleTaskList localList : allLocalLists) { if (result.equals(localList)) { localList.title = result.title; localList.id = result.id; result.dbId = localList.dbId; break; } } listsToSaveToDB.add(result); } } if (SYNC_DEBUG_PRINTS) Log.d(TAG, "Uploading tasks"); // Right, now upload tasks for (GoogleTaskList list : allLocalLists) { ArrayList<GoogleTask> tasksToUpload = tasksInListToUpload.get(list.dbId); if (tasksToUpload != null) { for (GoogleTask task : tasksToUpload) { GoogleTask result = apiTalker.uploadTask(task, list); uploadedStuff = true; // Task now has relevant fields set. Add to // DB-list if (tasksInListToSaveToDB.get(list) == null) tasksInListToSaveToDB.put(list, new ArrayList<GoogleTask>()); tasksInListToSaveToDB.get(list).add(result); } } } // Finally, get the updated etag from the server and // save. // Only worth doing if we actually uploaded anything // Also, only do this if we are doing a full sync String currentEtag = serverEtag; if (uploadedStuff) { currentEtag = apiTalker.getEtag(); //lastUpdate = dbTalker.getLastUpdated(account.name); } settings.edit().putString(PREFS_LAST_SYNC_ETAG, currentEtag) //.putString(PREFS_LAST_SYNC_DATE, lastUpdate) .commit(); // Now, set sorting values. for (GoogleTaskList list : tasksInListToSaveToDB.keySet()) { if (SYNC_DEBUG_PRINTS) Log.d(TAG, "Setting position values in: " + list.id); ArrayList<GoogleTask> tasks = tasksInListToSaveToDB.get(list); if (tasks != null) { if (SYNC_DEBUG_PRINTS) Log.d(TAG, "Setting position values for #tasks: " + tasks.size()); ArrayList<GoogleTask> allListTasks = allTasksInList.get(list.dbId); list.setSortingValues(tasks, allListTasks); } } // Save to database in a single transaction if (SYNC_DEBUG_PRINTS) Log.d(TAG, "Save stuff to DB"); dbTalker.SaveToDatabase(listsToSaveToDB, tasksInListToSaveToDB); // Commit it ContentProviderResult[] result = dbTalker.apply(); if (SYNC_DEBUG_PRINTS) Log.d(TAG, "Sync Complete!"); doneIntent.putExtra(SYNC_RESULT, SUCCESS); } catch (ClientProtocolException e) { if (SYNC_DEBUG_PRINTS) Log.d(TAG, "ClientProtocolException: " + e.getLocalizedMessage()); } catch (JSONException e) { if (SYNC_DEBUG_PRINTS) Log.d(TAG, "JSONException: " + e.getLocalizedMessage()); } catch (IOException e) { syncResult.stats.numIoExceptions++; if (SYNC_DEBUG_PRINTS) Log.d(TAG, "IOException: " + e.getLocalizedMessage()); } catch (RemoteException e) { if (SYNC_DEBUG_PRINTS) Log.d(TAG, "RemoteException: " + e.getLocalizedMessage()); } catch (OperationApplicationException e) { Log.d(TAG, "Joined operation failed: " + e.getLocalizedMessage()); } catch (ClassCastException e) { // GetListofLists will cast this if it returns a string. It should not return a string // but it did... Log.d(TAG, "ClassCastException: " + e.getLocalizedMessage()); } } else { // return real failure if (SYNC_DEBUG_PRINTS) Log.d(TAG, "Could not get authToken. Reporting authException"); syncResult.stats.numAuthExceptions++; doneIntent.putExtra(SYNC_RESULT, LOGIN_FAIL); } } finally { // This must always be called or we will leak resources if (apiTalker != null) { apiTalker.closeClient(); } mContext.sendBroadcast(doneIntent); if (SYNC_DEBUG_PRINTS) Log.d(TAG, "SyncResult: " + syncResult.toDebugString()); } } }
From source file:com.evolveum.polygon.scim.StandardScimHandlingStrategy.java
@Override public void delete(Uid uid, String resourceEndPoint, ScimConnectorConfiguration conf) { ServiceAccessManager accessManager = new ServiceAccessManager(conf); Header authHeader = accessManager.getAuthHeader(); String scimBaseUri = accessManager.getBaseUri(); if (authHeader == null || scimBaseUri.isEmpty()) { throw new ConnectorException( "The data needed for authorization of request to the provider was not found."); }/*from w ww . j a v a2 s . c o m*/ HttpClient httpClient = initHttpClient(conf); String uri = new StringBuilder(scimBaseUri).append(SLASH).append(resourceEndPoint).append(SLASH) .append(uid.getUidValue()).toString(); LOGGER.info("The uri for the delete request: {0}", uri); HttpDelete httpDelete = buildHttpDelete(uri, authHeader); try (CloseableHttpResponse response = (CloseableHttpResponse) httpClient.execute(httpDelete)) { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 204 || statusCode == 200) { LOGGER.info("Deletion of resource was succesfull"); } else { String responseString; HttpEntity entity = response.getEntity(); if (entity != null) { responseString = EntityUtils.toString(entity); } else { responseString = ""; } handleInvalidStatus("while deleting resource. ", responseString, "deleting object", statusCode); } } catch (ClientProtocolException e) { LOGGER.error( "An protocol exception has occurred while in the process of deleting a resource object. Possible mismatch in the interpretation of the HTTP specification: {0}", e.getLocalizedMessage()); LOGGER.info( "An protocol exception has occurred while in the process of deleting a resource object. Possible mismatch in the interpretation of the HTTP specification: {0}", e); throw new ConnectionFailedException( "An protocol exception has occurred while in the process of deleting a resource object. Possible mismatch in the interpretation of the HTTP specification.", e); } catch (IOException e) { StringBuilder errorBuilder = new StringBuilder( "An error has occurred while processing the http response. Occurrence in the process of deleting a resource object with the Uid: "); errorBuilder.append(uid.toString()); if ((e instanceof SocketTimeoutException || e instanceof NoRouteToHostException)) { errorBuilder.insert(0, "Connection timed out. "); throw new OperationTimeoutException(errorBuilder.toString(), e); } else { LOGGER.error( "An error has occurred while processing the http response. Occurrence in the process of deleting a resource object: : {0}", e.getLocalizedMessage()); LOGGER.info( "An error has occurred while processing the http response. Occurrence in the process of deleting a resource object: : {0}", e); throw new ConnectorIOException(errorBuilder.toString(), e); } } }
From source file:com.evolveum.polygon.scim.StandardScimHandlingStrategy.java
@Override public Uid create(String resourceEndPoint, ObjectTranslator objectTranslator, Set<Attribute> attributes, Set<Attribute> injectedAttributeSet, ScimConnectorConfiguration conf) { ServiceAccessManager accessManager = new ServiceAccessManager(conf); Header authHeader = accessManager.getAuthHeader(); String scimBaseUri = accessManager.getBaseUri(); if (authHeader == null || scimBaseUri.isEmpty()) { throw new ConnectorException( "The data needed for authorization of request to the provider was not found."); }//from w w w .j a v a2s . c om injectedAttributeSet = attributeInjection(injectedAttributeSet, accessManager.getLoginJson()); JSONObject jsonObject = new JSONObject(); jsonObject = objectTranslator.translateSetToJson(attributes, injectedAttributeSet, resourceEndPoint); HttpClient httpClient = initHttpClient(conf); String uri = new StringBuilder(scimBaseUri).append(SLASH).append(resourceEndPoint).append(SLASH).toString(); LOGGER.info("Query url: {0}", uri); try { // LOGGER.info("Json object to be send: {0}", // jsonObject.toString(1)); HttpPost httpPost = buildHttpPost(uri, authHeader, jsonObject); String responseString = null; try (CloseableHttpResponse response = (CloseableHttpResponse) httpClient.execute(httpPost)) { HttpEntity entity = response.getEntity(); if (entity != null) { responseString = EntityUtils.toString(entity); } else { responseString = ""; } int statusCode = response.getStatusLine().getStatusCode(); LOGGER.info("Status code: {0}", statusCode); if (statusCode == 201) { // LOGGER.info("Creation of resource was successful"); if (!responseString.isEmpty()) { JSONObject json = new JSONObject(responseString); Uid uid = new Uid(json.getString(ID)); // LOGGER.info("Json response: {0}", json.toString(1)); return uid; } else { return null; } } else { handleInvalidStatus(" while resource creation, please check if credentials are valid. ", responseString, "creating a new object", statusCode); } } catch (ClientProtocolException e) { LOGGER.error( "An protocol exception has occurred while in the process of creating a new resource object. Possible mismatch in interpretation of the HTTP specification: {0}", e.getLocalizedMessage()); LOGGER.info( "An protocol exception has occurred while in the process of creating a new resource object. Possible mismatch in interpretation of the HTTP specification: {0}", e); throw new ConnectionFailedException( "An protocol exception has occurred while in the process of creating a new resource object. Possible mismatch in interpretation of the HTTP specification: {0}", e); } catch (IOException e) { if ((e instanceof SocketTimeoutException || e instanceof NoRouteToHostException)) { throw new OperationTimeoutException( "The connection timed out. Occurrence in the process of creating a new resource object", e); } else { LOGGER.error( "An error has occurred while processing the http response. Occurrence in the process of creating a new resource object: {0}", e.getLocalizedMessage()); LOGGER.info( "An error has occurred while processing the http response. Occurrence in the process of creating a new resource object: {0}", e); throw new ConnectorIOException( "An error has occurred while processing the http response. Occurrence in the process of creating a new resource object", e); } } } catch (JSONException e) { LOGGER.error( "An exception has occurred while processing an json object. Occurrence in the process of creating a new resource object: {0}", e.getLocalizedMessage()); LOGGER.info( "An exception has occurred while processing an json object. Occurrence in the process of creating a new resource object: {0}", e); throw new ConnectorException( "An exception has occurred while processing an json object. Occurrence in the process of creating a new resource objec", e); } catch (UnsupportedEncodingException e) { LOGGER.error("Unsupported encoding: {0}. Occurrence in the process of creating a new resource object ", e.getLocalizedMessage()); LOGGER.info("Unsupported encoding: {0}. Occurrence in the process of creating a new resource object ", e); throw new ConnectorException( "Unsupported encoding, Occurrence in the process of creating a new resource object ", e); } return null; }
From source file:com.evolveum.polygon.scim.StandardScimHandlingStrategy.java
@Override public ParserSchemaScim querySchemas(String providerName, String resourceEndPoint, ScimConnectorConfiguration conf) { List<String> excludedAttrs = new ArrayList<String>(); ServiceAccessManager accessManager = new ServiceAccessManager(conf); Header authHeader = accessManager.getAuthHeader(); String scimBaseUri = accessManager.getBaseUri(); if (authHeader == null || scimBaseUri.isEmpty()) { throw new ConnectorException( "The data needed for authorization of request to the provider was not found."); }/*from ww w.j av a 2 s. c o m*/ HttpClient httpClient = initHttpClient(conf); String uri = new StringBuilder(scimBaseUri).append(SLASH).append(resourceEndPoint).toString(); LOGGER.info("Qeury url: {0}", uri); HttpGet httpGet = buildHttpGet(uri, authHeader); try (CloseableHttpResponse response = (CloseableHttpResponse) httpClient.execute(httpGet)) { HttpEntity entity = response.getEntity(); String responseString; if (entity != null) { responseString = EntityUtils.toString(entity); } else { responseString = ""; } int statusCode = response.getStatusLine().getStatusCode(); LOGGER.info("Schema query status code: {0} ", statusCode); if (statusCode == 200) { if (!responseString.isEmpty()) { //LOGGER.warn("The returned response string for the \"schemas/\" endpoint"); JSONObject jsonObject = new JSONObject(responseString); ParserSchemaScim schemaParser = processSchemaResponse(jsonObject); excludedAttrs = excludeFromAssembly(excludedAttrs); for (String attr : excludedAttrs) { LOGGER.info("The attribute \"{0}\" will be omitted from the connId object build.", attr); } return schemaParser; } else { LOGGER.warn("Response string for the \"schemas/\" endpoint returned empty "); String resources[] = { USERS, GROUPS }; JSONObject responseObject = new JSONObject(); JSONArray responseArray = new JSONArray(); for (String resourceName : resources) { uri = new StringBuilder(scimBaseUri).append(SLASH).append(resourceEndPoint) .append(resourceName).toString(); LOGGER.info("Additional query url: {0}", uri); httpGet = buildHttpGet(uri, authHeader); try (CloseableHttpResponse secondaryResponse = (CloseableHttpResponse) httpClient .execute(httpGet)) { statusCode = secondaryResponse.getStatusLine().getStatusCode(); responseString = EntityUtils.toString(secondaryResponse.getEntity()); if (statusCode == 200) { JSONObject jsonObject = new JSONObject(responseString); jsonObject = injectMissingSchemaAttributes(resourceName, jsonObject); responseArray.put(jsonObject); } else { LOGGER.warn( "No definition for provided shcemas was found, the connector will switch to default core schema configuration!"); return null; } } responseObject.put(RESOURCES, responseArray); } if (responseObject == JSONObject.NULL) { return null; } else { excludedAttrs = excludeFromAssembly(excludedAttrs); for (String attr : excludedAttrs) { LOGGER.info("The attribute \"{0}\" will be omitted from the connId object build.", attr); } return processSchemaResponse(responseObject); } } } else { handleInvalidStatus("while querying for schema. ", responseString, "schema", statusCode); } } catch (ClientProtocolException e) { LOGGER.error( "An protocol exception has occurred while in the process of querying the provider Schemas resource object. Possible mismatch in interpretation of the HTTP specification: {0}", e.getLocalizedMessage()); LOGGER.info( "An protocol exception has occurred while in the process of querying the provider Schemas resource object. Possible mismatch in interpretation of the HTTP specification: {0}", e); throw new ConnectorException( "An protocol exception has occurred while in the process of querying the provider Schemas resource object. Possible mismatch in interpretation of the HTTP specification", e); } catch (IOException e) { StringBuilder errorBuilder = new StringBuilder( "An error has occurred while processing the http response. Occurrence in the process of querying the provider Schemas resource object"); if ((e instanceof SocketTimeoutException || e instanceof NoRouteToHostException)) { errorBuilder.insert(0, "The connection timed out. "); throw new OperationTimeoutException(errorBuilder.toString(), e); } else { LOGGER.error( "An error has occurred while processing the http response. Occurrence in the process of querying the provider Schemas resource object: {0}", e.getLocalizedMessage()); LOGGER.info( "An error has occurred while processing the http response. Occurrence in the process of querying the provider Schemas resource object: {0}", e); throw new ConnectorIOException(errorBuilder.toString(), e); } } return null; }