@Override public void handleItemList(IItemListHandler handler, long syncTime) throws IOException, ReaderException { // http://www.google.com/reader/api/0/stream/contents/user%2F-%2Fstate%2Fcom.google%2Fread?client=newsplus&output=json&ck=1276066665822&n=20&r=n Reader in = null; try { long startTime = handler.startTime(); in = readStreamContents(syncTime, startTime, handler, null); String continuation = parseItemList(in, handler); int limit = handler.limit(); int max = limit > SYNC_MAX_ITEMS ? SYNC_MAX_ITEMS : limit; int count = 1; // continuation count while ((limit == 0 || limit > max * count) && handler.continuation() && continuation != null && continuation.length() > 0) { in.close(); in = readStreamContents(syncTime, startTime, handler, continuation); continuation = parseItemList(in, handler); count++; } } catch (JsonParseException e) { e.printStackTrace(); throw new ReaderException("data parse error", e); } catch (RemoteException e) { e.printStackTrace(); throw new ReaderException("remote connection error", e); } finally { if (in != null) in.close(); // ensure resources get cleaned up timely } }
List<String> flattenTheory(String uri) { String result = sendMessage( String.format( "<related><literal uri='%s'/> <sequence><transitive><toobject relation='Includes'/></transitive><toobject relation='Declares'/></sequence></related>", uri)); ResultListWrapper res = null; try { res = xmlMapper.readValue(result, ResultListWrapper.class); } catch (JsonParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JsonMappingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } List<String> results = new ArrayList<String>(); for (ResultInstance ri : res.getResult()) { results.add(ri.getPath()); } return results; }
/** @param bioID */ private boolean setBioID(String bioID) { boolean toRet = false; try { JsonFactory factory = new JsonFactory(); JsonParser jparser = factory.createParser(bioID); String key = ""; // Get StartObject for JSON, after first { jparser.nextToken(); while (jparser.nextToken() != JsonToken.END_OBJECT) { key = jparser.getText(); if (key.equals("id")) { key = jparser.nextTextValue(); // Set bioID in Experiment selExp.setBioID(key); toRet = true; } else { jparser.skipChildren(); } } jparser.close(); } catch (JsonParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return toRet; }
private Map<Long, Map<Long, String>> parseBloodTestResults(String bloodTestingResults) { ObjectMapper mapper = new ObjectMapper(); System.out.println(bloodTestingResults); Map<Long, Map<Long, String>> bloodTestResultsMap = new HashMap<Long, Map<Long, String>>(); try { @SuppressWarnings("unchecked") Map<String, Map<String, String>> generatedMap = mapper.readValue(bloodTestingResults, HashMap.class); for (String collectionId : generatedMap.keySet()) { Map<Long, String> testResults = new HashMap<Long, String>(); bloodTestResultsMap.put(Long.parseLong(collectionId), testResults); for (String testId : generatedMap.get(collectionId).keySet()) { if (StringUtils.isBlank(testId)) continue; testResults.put(Long.parseLong(testId), generatedMap.get(collectionId).get(testId)); } } } catch (JsonParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JsonMappingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(bloodTestResultsMap); return bloodTestResultsMap; }
@RequestMapping(value = "saveNewBloodTypingRule", method = RequestMethod.POST) public @ResponseBody Map<String, Object> saveNewBloodTypingRule( HttpServletRequest request, HttpServletResponse response, @RequestParam("newBloodTypingRule") String newBloodTypingRuleAsJsonStr) { Map<String, Object> m = new HashMap<String, Object>(); ObjectMapper mapper = new ObjectMapper(); boolean success = false; try { Map<String, Object> newBloodTypingRuleAsMap; newBloodTypingRuleAsMap = mapper.readValue(newBloodTypingRuleAsJsonStr, HashMap.class); bloodTestingRepository.saveNewBloodTypingRule(newBloodTypingRuleAsMap); success = true; } catch (JsonParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JsonMappingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (!success) response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return m; }
@Override public Object read(Type type, Class<?> contextClass, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { try { TumblrResponse tumblrResponse = objectMapper.readValue(inputMessage.getBody(), TumblrResponse.class); checkResponse(tumblrResponse); Object result; if (TumblrResponse.class.equals(type)) { // don't parse the response json, callee is going to process is manually result = tumblrResponse; } else { // parse the response json into an instance of the given class JavaType javaType = getJavaType(type, contextClass); String response = tumblrResponse.getResponseJson(); result = objectMapper.readValue(response, javaType); } return result; } catch (JsonParseException ex) { throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex); } catch (EOFException ex) { throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex); } catch (Exception e) { e.printStackTrace(); throw new IOException(e); } }
@Override public void handleReaderList( ITagListHandler tagHandler, ISubscriptionListHandler subHandler, long syncTime) throws IOException, ReaderException { Reader in = null; try { in = readTagList(syncTime); parseTagList(in, tagHandler); } catch (JsonParseException e) { e.printStackTrace(); throw new ReaderException("data parse error", e); } catch (RemoteException e) { e.printStackTrace(); throw new ReaderException("remote connection error", e); } finally { if (in != null) in.close(); } try { in = readSubList(syncTime); // parseSubList(in, subHandler, getUnreadList(syncTime)); parseSubList(in, subHandler, null); } catch (JsonParseException e) { e.printStackTrace(); throw new ReaderException("data parse error", e); } catch (RemoteException e) { e.printStackTrace(); throw new ReaderException("remote connection error", e); } finally { if (in != null) in.close(); } }
private static TaoBaoIpData resolveIP(String ip) { Map<String, String> params = Maps.newHashMap(); params.put("ip", ip); String data = HttpClientUtils.doGet(IP_RESOLVING_URL, params); log.info("ip = {}, data = {}", ip, data); TaoBaoIpData tbData = null; try { tbData = JacksonUtil.str2Obj(data, TaoBaoIpData.class); } catch (JsonParseException e) { e.printStackTrace(); log.info("e = {}", e); } catch (JsonMappingException e) { e.printStackTrace(); log.info("e = {}", e); } catch (IOException e) { e.printStackTrace(); log.info("e = {}", e); } catch (Throwable e) { log.warn("e = {}", e.toString()); } return tbData; }
// Update and return given train line with the Jackson parser // AG public static <T> TrainLine updateLine(T address, TrainLine line) { try { Object trainData = new Object(); if (address instanceof URL) { // Get train data from web trainData = mapper.readValue((URL) address, Object.class); } else if (address instanceof File) { // Get train data locally trainData = mapper.readValue((File) address, Object.class); } // System.out.println(trainData.toString()); // Go inside the wrapper Object tripListObj = getFromMap(trainData, TRIP_LIST_KEY); line = new TrainLine(tripListObj); } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return line; }
// 初始化list数据函数 public void InitListDataForHistory(String url, JSONObject json, AjaxStatus status) { if (status.getCode() == AjaxStatus.NETWORK_ERROR && app.GetServiceData("user_Histories") == null) { aq.id(R.id.ProgressText).gone(); app.MyToast(aq.getContext(), getResources().getString(R.string.networknotwork)); return; } ObjectMapper mapper = new ObjectMapper(); try { if (isLastisNext == 1) { m_ReturnUserPlayHistories = mapper.readValue(json.toString(), ReturnUserPlayHistories.class); app.SaveServiceData("user_Histories", json.toString()); } else if (isLastisNext > 1) { m_ReturnUserPlayHistories = null; m_ReturnUserPlayHistories = mapper.readValue(json.toString(), ReturnUserPlayHistories.class); } // 创建数据源对象 GetVideoMovies(); } catch (JsonParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JsonMappingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
/* * 从本地缓存取数据,然后从服务器抓数据下来 */ private void CheckSaveData() { String SaveData = null; ObjectMapper mapper = new ObjectMapper(); SaveData = app.GetServiceData("user_Histories"); if (SaveData == null) { isLastisNext = 1; GetServiceData(isLastisNext); } else { try { m_ReturnUserPlayHistories = mapper.readValue(SaveData, ReturnUserPlayHistories.class); // 创建数据源对象 GetVideoMovies(); isLastisNext = 1; GetServiceData(isLastisNext); } catch (JsonParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JsonMappingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
/** * 用户接受客户端发来的消息,在有客户端消息到达时触发 * * @author lihzh * @alia OneCoder */ @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { System.out.println("messageReceived"); ChannelBuffer buffer = (ChannelBuffer) e.getMessage(); System.out.println(buffer.toString(Charset.defaultCharset())); System.out.println( "MessageServerHandler::messageReceived buffer:: " + buffer.toString(Charset.defaultCharset())); ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally ClientInfoBean bean = null; try { bean = mapper.readValue(buffer.toString(Charset.defaultCharset()), ClientInfoBean.class); System.out.println(bean.getClientId()); } catch (JsonParseException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (JsonMappingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } System.out.println(buffer.toString(Charset.defaultCharset())); }
/** 2、将json字符串转换成List<Map>集合 */ @Test public void readJson2List() { String json = "[{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"}," + "{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}]"; try { List<LinkedHashMap<String, Object>> list = objectMapper.readValue(json, List.class); System.out.println(list.size()); for (LinkedHashMap<String, Object> aList : list) { Map<String, Object> map = aList; Set<String> set = map.keySet(); for (String key : set) { System.out.println(key + ":" + map.get(key)); } } } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
/** * 用户取消订单 * * @param userBaseAndSessionDomainStr * @return */ @RequestMapping(value = "/deleteorder", method = RequestMethod.POST) public @ResponseBody RestResponse deleteUserOrder( @RequestBody String userBaseAndSessionDomainStr) { logger.info("开始删除用户订单,传入参数是:" + userBaseAndSessionDomainStr); RestResponse response = new RestResponse(); ResponseHeader header = new ResponseHeader(); response.setResponseHeader(header); UserBaseAndSessionDomain userBaseAndSessionDomain = null; try { userBaseAndSessionDomain = (UserBaseAndSessionDomain) Json2Object.deserializeObject( userBaseAndSessionDomainStr, UserBaseAndSessionDomain.class); boolean isLogin = false; // 判断用户是否登录 if (null != userBaseAndSessionDomain && null != userBaseAndSessionDomain.getSessionId() && !"".equals(userBaseAndSessionDomain.getSessionId())) { isLogin = this.userService.isLogin(userBaseAndSessionDomain.getSessionId()); } if (isLogin) { CustomerOrderBase customerOrderBase = userBaseAndSessionDomain.getCustomerOrderBase(); if (null == customerOrderBase) { response.getResponseHeader().setMessage("传入参数不能为空"); response.getResponseHeader().setErrorCode(ErrorCode.PARAMS_ERROR); logger.info("传入参数不能为空"); } else if (null == customerOrderBase.getId()) { response.getResponseHeader().setMessage("请选择要删除的订单"); response.getResponseHeader().setErrorCode(ErrorCode.PARAMS_ERROR); logger.info("请选择要删除的订单"); } else { response = this.customerOrderService.deleteUserOrder(customerOrderBase); } } else { logger.info("用户未登录,请先登录"); response.getResponseHeader().setMessage("用户未登录,请先登录"); response.getResponseHeader().setErrorCode(ErrorCode.USER_NOT_LOGIN); } } catch (JsonParseException e) { logger.error("生成用户订单失败,失败原因是:" + e.getLocalizedMessage(), e); response.getResponseHeader().setMessage("生成用户订单失败,原因为传入参数解析有误"); response.getResponseHeader().setErrorCode(ErrorCode.INSERT_EXCEPTION); e.printStackTrace(); } catch (JsonMappingException e) { logger.error("生成用户订单失败,失败原因是:" + e.getLocalizedMessage(), e); response.getResponseHeader().setMessage("生成用户订单失败,原因为传入参数解析有误"); response.getResponseHeader().setErrorCode(ErrorCode.INSERT_EXCEPTION); e.printStackTrace(); } catch (Exception e) { logger.error("生成用户订单失败,失败原因是:" + e.getLocalizedMessage(), e); response.getResponseHeader().setMessage("生成用户订单失败"); response.getResponseHeader().setErrorCode(ErrorCode.INSERT_EXCEPTION); e.printStackTrace(); } return response; }
@Test public void testEndObject() throws Exception { JacksonParserWrapper parser = new JacksonParserWrapper(jsonFactory.createJsonParser("{}")); parser.startObject(); parser.endObject(); try { parser.endObject(); fail("Where is the Exception"); } catch (JsonParseException e) { assertThat(e.getMessage()).startsWith("Invalid token. Expected <END_OBJECT> but got <null>"); } }
/** * Return the data stored in the cursor at the given index and given position (ie the given row * which the cursor is currently on) as null OR whatever data type it is. * * <p>This does not actually convert data types from one type to the other. Instead, it safely * preserves null values and returns boxed data values. If you specify ArrayList or HashMap, it * JSON deserializes the value into one of those. * * @param c * @param clazz * @param i * @return */ @SuppressWarnings("unchecked") public static final <T> T getIndexAsType(Cursor c, Class<T> clazz, int i) { // If you add additional return types here be sure to modify the javadoc. try { if (i == -1) return null; if (c.isNull(i)) { return null; } if (clazz == Long.class) { Long l = c.getLong(i); return (T) l; } else if (clazz == Integer.class) { Integer l = c.getInt(i); return (T) l; } else if (clazz == Double.class) { Double d = c.getDouble(i); return (T) d; } else if (clazz == String.class) { String str = c.getString(i); return (T) str; } else if (clazz == Boolean.class) { // stored as integers Integer l = c.getInt(i); return (T) Boolean.valueOf(l != 0); } else if (clazz == ArrayList.class) { // json deserialization of an array String str = c.getString(i); return (T) ODKFileUtils.mapper.readValue(str, ArrayList.class); } else if (clazz == HashMap.class) { // json deserialization of an object String str = c.getString(i); return (T) ODKFileUtils.mapper.readValue(str, HashMap.class); } else { throw new IllegalStateException("Unexpected data type in SQLite table"); } } catch (ClassCastException e) { e.printStackTrace(); throw new IllegalStateException( "Unexpected data type conversion failure " + e.toString() + " in SQLite table "); } catch (JsonParseException e) { e.printStackTrace(); throw new IllegalStateException( "Unexpected data type conversion failure " + e.toString() + " on SQLite table"); } catch (JsonMappingException e) { e.printStackTrace(); throw new IllegalStateException( "Unexpected data type conversion failure " + e.toString() + " on SQLite table"); } catch (IOException e) { e.printStackTrace(); throw new IllegalStateException( "Unexpected data type conversion failure " + e.toString() + " on SQLite table"); } }
public void getResult(String jsonStr) { try { MapJsonString value = mapper.readValue(jsonStr, MapJsonString.class); System.out.println(value.toString()); } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
public static Manifest readManifest(File file) throws IOException { String errorMessage = ""; try { return mMapper.readValue(file, Manifest.class); } catch (JsonParseException jpe) { errorMessage = jpe.getMessage(); } catch (JsonMappingException jme) { errorMessage = jme.getMessage(); } LoggerFactory.getLogger("Bootloader") .error("Error while parsing manifest " + file.getName() + ": " + errorMessage); return null; }
public Object json2obj(String json, Class<?> clz) { try { mapper = getMapper(); return mapper.readValue(json, clz); } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
public JSONArray validateFields(MultivaluedMap<String, String> parameters) { JSONArray validationErrors = new JSONArray(); // Dataset Validation --------------------------------------------- String datasetMetadata = parameters.get("meta").get(0); if (datasetMetadata != null) { datasetMetadata = URLDecoder.decode(datasetMetadata); try { if ((!datasetMetadata.equals("")) && (!datasetMetadata.equals("[]"))) { JSONObject metadataObject = JSONUtils.toJSONObject(datasetMetadata); JSONArray columnsMetadataArray = metadataObject.getJSONArray("columns"); for (int j = 0; j < columnsMetadataArray.length(); j++) { JSONObject columnJsonObject = columnsMetadataArray.getJSONObject(j); String columnName = columnJsonObject.getString("column"); if (columnJsonObject.getString("pname").equalsIgnoreCase("type")) { if (columnName == null) { validationErrors.put( new JSONObject("{message: 'Validation error: Column name cannot be null'}")); } /* else if(Pattern.compile("\\s").matcher(columnName).find()){ validationErrors.put(new JSONObject("{message: 'Validation error: Space character not allowed for column name "+ columnName + "'}")); }else if(Pattern.compile("[ÀÈÌÒÙàèìòùÁÉÍÓÚÝáéíóúýÂÊÎÔÛâêîôûÃÑÕãñõÄËÏÖÜŸäëïöüŸ¡¿çÇŒœßØøÅåÆæÞþÐðÐð'.,&#@:?!()$\\/]").matcher(columnName).find()){ validationErrors.put(new JSONObject("{message: 'Validation error: Special characters not allowed for column name "+ columnName + "'}")); } */ } String propertyName = columnJsonObject.getString("pname"); if (propertyName == null) { validationErrors.put( new JSONObject("{message: 'Validation error: Property name cannot be null'}")); } /* else if( Pattern.compile("\\s").matcher(propertyName).find()){ validationErrors.put(new JSONObject("{message: 'Validation error: Space character not allowed for Property name "+ propertyName + "'}")); }else if( Pattern.compile("[ÀÈÌÒÙàèìòùÁÉÍÓÚÝáéíóúýÂÊÎÔÛâêîôûÃÑÕãñõÄËÏÖÜŸäëïöüŸ¡¿çÇŒœßØøÅåÆæÞþÐðÐð'.,&#@:?!()$\\/]").matcher(propertyName).find()){ validationErrors.put(new JSONObject("{message: 'Validation error: Special characters not allowed for Property name "+ propertyName + "'}")); } */ String propertyValue = columnJsonObject.getString("pvalue"); } } } catch (JsonMappingException e1) { logger.error(e1.getMessage()); } catch (JsonParseException e1) { logger.error(e1.getMessage()); } catch (JSONException e1) { logger.error(e1.getMessage()); } catch (IOException e1) { logger.error(e1.getMessage()); } } return validationErrors; }
public RequestMaker(String jsonString) { if (jsonString == null) return; try { request = mapper.readValue(jsonString, Request.class); } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
public <T> T transform( String url, Class<T> type, String encoding, byte[] data, AjaxStatus status) { try { Log.i("info", new String(data, "utf-8")); return new ObjectMapper().readValue(data, new TypeReference<List<Map<String, Object>>>() {}); } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
public static ArrayList<?> str2list(String json, Class<?> clazz) { ObjectMapper mapper = getObjectMapper(); JavaType javaType = getCollectionType(ArrayList.class, clazz); ArrayList<?> lst = null; try { lst = (ArrayList<?>) mapper.readValue(json, javaType); } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return lst; }
@Override public List<JiveActivity> getActivites() { String jsonString = jiveRestClient.getActivities(); ObjectMapper mapper = new ObjectMapper(); List<JiveActivity> activities = null; try { activities = mapper.readValue(jsonString, new TypeReference<List<JiveActivity>>() {}); } catch (JsonParseException e) { log.error(e.getMessage()); } catch (JsonMappingException e) { log.error(e.getMessage()); } catch (IOException e) { log.error(e.getMessage()); } return activities; }
private KafkaConfig deserializeKafkaSchemalDesc(StreamingRequest streamingRequest) { KafkaConfig desc = null; try { logger.debug("Saving KafkaConfig " + streamingRequest.getKafkaConfig()); desc = JsonUtil.readValue(streamingRequest.getKafkaConfig(), KafkaConfig.class); } catch (JsonParseException e) { logger.error("The KafkaConfig definition is invalid.", e); updateRequest(streamingRequest, false, e.getMessage()); } catch (JsonMappingException e) { logger.error("The data KafkaConfig definition is invalid.", e); updateRequest(streamingRequest, false, e.getMessage()); } catch (IOException e) { logger.error("Failed to deal with the request.", e); throw new InternalErrorException("Failed to deal with the request:" + e.getMessage(), e); } return desc; }
private static FormularioCompra criarOuObterDTOCompraSessao() { FormularioCompra dto = new FormularioCompra(); try { ObjectMapper mapper = new ObjectMapper(); String stringJson = session("compra"); if (stringJson != null) { dto = mapper.readValue(stringJson, FormularioCompra.class); } } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return dto; }
/** 1、 将json字符串转换成JavaBean对象 */ @Test public void readJson2Entity() { String json = "{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}"; try { AccountBean acc = objectMapper.readValue(json, AccountBean.class); System.out.println("name : " + acc.getName()); System.out.println(acc); } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
@Override protected String doInBackground(Void... params) { // TODO Auto-generated method stub String n = null; try { parseJSON(); // parseWithSimpleJSON(); } catch (JsonParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } Log.i("TAG", "doInBackGround-Finish"); return n; }
@Override public void handleItemIdList(IItemIdListHandler handler, long syncTime) throws IOException, ReaderException { // http://www.google.com/reader/api/0/stream/contents/user%2F-%2Fstate%2Fcom.google%2Fread?client=newsplus&output=json&ck=1276066665822&n=20&r=n Reader in = null; try { in = readStreamItemIds(syncTime, handler); parseItemIdList(in, handler); } catch (JsonParseException e) { e.printStackTrace(); throw new ReaderException("data parse error", e); } catch (RemoteException e) { e.printStackTrace(); throw new ReaderException("remote connection error", e); } finally { if (in != null) in.close(); } }
public Urllib login() throws LoginException, BankException { urlopen = new Urllib(CertificateReader.getCertificates(context, R.raw.cert_avanza)); urlopen.addHeader("ctag", "1122334455"); urlopen.setUserAgent("Avanza Bank 131 (iPhone; iPhone OS 6.1.4; sv_SE)"); urlopen.addHeader( "Authorization", "Basic " + Base64.encodeToString( new String(username + ":" + password).getBytes(), Base64.NO_WRAP)); try { HttpResponse httpResponse = urlopen.openAsHttpResponse(API_URL + "account/overview/all", null, false); if (httpResponse.getStatusLine().getStatusCode() == 401) { throw new LoginException(context.getText(R.string.invalid_username_password).toString()); } ObjectMapper vObjectMapper = new ObjectMapper(); AccountOverview r = vObjectMapper.readValue(httpResponse.getEntity().getContent(), AccountOverview.class); for (com.liato.bankdroid.banking.banks.avanza.model.Account account : r.getAccounts()) { Account a = new Account( account.getAccountName(), new BigDecimal(account.getBalance()), account.getAccountId()); if (!account.getCurrencyAccounts().isEmpty()) { a.setCurrency(account.getCurrencyAccounts().get(0).getCurrency()); } accounts.add(a); } } catch (JsonParseException e) { e.printStackTrace(); throw new BankException(e.getMessage()); } catch (ClientProtocolException e) { e.printStackTrace(); throw new BankException(e.getMessage()); } catch (IOException e) { e.printStackTrace(); throw new BankException(e.getMessage()); } return urlopen; }