/** * 强制重新获取资源 * * @return * @throws Exception */ public synchronized T reAcquireRes() throws Exception { releaseRes(); res.acquireRes(); isAcquired = true; this.lastActiveTime = NetUtil.getTimeInSecs(); return res; }
public static String getUrlCache(Context context, String url) { if (TextUtils.isEmpty(url)) { return null; } int netState = NetUtil.getNetworkState(context); File file = new File(getCacheDir(context) + File.separator + replaceUrlWithPlus(url)); if (file.exists() && file.isFile()) { long expiredTime = System.currentTimeMillis() - file.lastModified(); Log.i("liweiping", url + ": expiredTime=" + expiredTime / 1000); // 1. in case the system time is incorrect (the time is turn back // long ago) // 2. when the network is invalid, you can only read the cache if (netState != NetUtil.NETWORN_NONE && expiredTime < 0) { return null; } // 如果是wifi网络,则30分钟过期 if (netState == NetUtil.NETWORN_WIFI && expiredTime > CONFIG_CACHE_WIFI_TIMEOUT) { return null; // 如果是手机网络,则2个小时过期 } else if (netState == NetUtil.NETWORN_MOBILE && expiredTime > CONFIG_CACHE_MOBILE_TIMEOUT) { return null; } try { String result = FileUtils.readTextFile(file); return result; } catch (IOException e) { e.printStackTrace(); } } return null; }
/** * 获取没有过期的资源 * * @return * @throws Exception */ public synchronized T getRes() throws Exception { // 没有获取资源或者资源已经过期时候重新获取 if (isResExpired()) { if (isAcquired) { res.releaseRes(); } res.acquireRes(); isAcquired = true; } this.lastActiveTime = NetUtil.getTimeInSecs(); return res; }
@Override protected void setUp() throws Exception { super.setUp(); String dataPath = new File("target/test-harness/elasticsearch-data").getAbsolutePath(); Map<ElasticsearchPort, Integer> esPorts = NetUtil.findOpenPortsForElasticsearch(); int httpPort = esPorts.get(ElasticsearchPort.HTTP); int tcpPort = esPorts.get(ElasticsearchPort.TCP); elasticsearchNode = ElasticsearchNode.start(dataPath, httpPort, tcpPort); // Configure mojo with context File testPom = new File(getBasedir(), "src/test/resources/goals/stop/pom.xml"); mojo = (StopElasticsearchNodeMojo) lookupMojo("stop", testPom); mojo.setPluginContext(new HashMap()); mojo.getPluginContext().put("test", elasticsearchNode); }
@Override public IMessage onMessage(final TagUpdateMessage message, final MessageContext ctx) { NetUtil.addScheduledTask( ctx, new Runnable() { @Override public void run() { // FIXME debug System.out.println(message.toString()); Entity entity = NetUtil.getSidedEntity(message.uuid, ctx); // if the entity no longer exists, return if (entity == null) { System.out.println("entity: " + message.uuid + " not found!"); return; } // merge living entity attributes, if present if (message.tags.hasKey("Attributes") && entity instanceof EntityLivingBase) { SharedMonsterAttributes.setAttributeModifiers( ((EntityLivingBase) entity).getAttributeMap(), message.tags.getTagList("Attributes", 10)); } // check for auras message if (message.tags.hasKey(SpellBase.AURAS_TAG)) { // currently, the message is a full update, so remove prior to merge entity.getEntityData().removeTag(SpellBase.AURAS_TAG); } // update entity's tags entity.getEntityData().merge(message.tags); } }); return null; }
/** * 创建HTTP的网络连接 * * @param flag * @return */ public static DefaultHttpClient createNetworkClient(boolean flag) { DefaultHttpClient defaulthttpclient; if (NetUtil.netState == 8) defaulthttpclient = null; else if (!NetUtil.isNetStateWap() && !flag) { logger.v("createNetworkClient() ---> !WlanUtils.isNetStateWap() && !isHttpReqIfWlan"); if (NetUtil.netState != 1 && NetUtil.netState != 6) { logger.d("Wlan has been closed."); defaulthttpclient = null; return defaulthttpclient; } else { if (mHttpsClient == null) mHttpsClient = createHttpsClient(); defaulthttpclient = mHttpsClient; } } else { MobileMusicApplication mobilemusicapplication = MobileMusicApplication.getInstance(); if (NetUtil.netState != 3 && NetUtil.netState != 5 && !SystemControllerImpl.getInstance(mobilemusicapplication).checkWapStatus()) { logger.d("WAP has been closed."); defaulthttpclient = null; return defaulthttpclient; } else { if (mHttpClient == null) mHttpClient = createHttpClient(); defaulthttpclient = mHttpClient; if (NetUtil.netState == 3) { HttpHost httphost = new HttpHost( MusicBusinessDefine_WAP.CMCC_WAP_PROXY_HOST, MusicBusinessDefine_WAP.CMCC_WAP_PROXY_PORT); if (defaulthttpclient == null) defaulthttpclient = createHttpsClient(); defaulthttpclient.getParams().setParameter("http.route.default-proxy", httphost); } } } logger.v("createNetworkClient() ---> Exit"); return defaulthttpclient; }
/** * 资源是否存在,或者资源是否过期。 资源没有获取或则已经超过过期时间都是过期的 过期的资源会重新获取 * * @return true表示需要重新获取资源 */ public synchronized boolean isResExpired() { return !res.hasResource() || !isAcquired || (this.lastActiveTime + this.expiredPeriod < NetUtil.getTimeInSecs()); }
public static void remove(SocketChannel sc, Event e) throws IOException { NetUtil.writeLine(sc, "REMOVE " + e.getType().name() + " " + e.getX() + " " + e.getY()); }
public static void sendInfo(SocketChannel sc, Event e) throws IOException { NetUtil.writeLine(sc, "INFO " + e.getType().name() + " " + e.getX() + " " + e.getY()); }
public static void sendInfos(SocketChannel sc, ArrayList<Event> list) throws IOException { NetUtil.writeLine(sc, "INFOS " + list.size()); for (Event e : list) { sendInfo(sc, e); } }
// onHandleIntent tourne dans un autre thread.... @Override public void onHandleIntent(Intent intent) { Log.d(TAG, "onHandle!"); if (!NetUtil.networkOK(this.getApplicationContext())) { mHandler.post( new Runnable() { @Override public void run() { Toast.makeText(ServiceMiseAJour.this, "Pas d'accès au réseau", Toast.LENGTH_LONG) .show(); } }); return; } // commence par demander un "busy" si l'app ecoute ce signal... Intent in = new Intent("com.seboid.udem.BUSY"); in.putExtra("busy", true); sendBroadcast(in); // extract period info.. long now = System.currentTimeMillis(); long start = intent.getLongExtra("start", now); long stop = intent.getLongExtra("stop", now + 6 * 24 * 3600 * 1000); String startDay = TempsUtil.aujourdhui(start, 0); String stopDay = TempsUtil.aujourdhui(stop, 0); NotificationManager mNM; mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ServiceMiseAJour.this); // long past = (long)(System.currentTimeMillis()/1000 - // Long.parseLong(preferences.getString("savetime","365"))*24*3600); // // load all event summaries // EventsAPI events = new EventsAPI("evenements", null, startDay, stopDay); if (events == null || events.erreur != null) { Log.d(TAG, "events null"); // enlever le BUSY in = new Intent("com.seboid.udem.BUSY"); in.putExtra("busy", false); sendBroadcast(in); return; } DBHelper dbH = new DBHelper(this); SQLiteDatabase db = dbH.getWritableDatabase(); int nb = 0; HashMap<String, String> hm; ContentValues val = new ContentValues(); for (int i = 0; i < events.hmList.size(); i++) { hm = events.hmList.get(i); // passer en determinate in = new Intent("com.seboid.udem.BUSY"); in.putExtra("progress", (i * 10000) / (events.hmList.size() - 1)); sendBroadcast(in); // if( (Integer)hm.get("time") < past ) { } int id = Integer.parseInt(hm.get("id")); long modif = Long.parseLong(hm.get("epoch_modif")); // ajouter a la base de donnee val.clear(); val.put(DBHelper.C_ID, id); val.put(DBHelper.C_TITRE, hm.get("titre")); val.put(DBHelper.C_DESCRIPTION, hm.get("description")); val.put(DBHelper.C_CONTACT_NOM, hm.get("contact_nom")); val.put(DBHelper.C_CONTACT_COURRIEL, hm.get("contact_courriel")); val.put(DBHelper.C_CONTACT_TEL, hm.get("contact_tel")); val.put(DBHelper.C_CONTACT_URL, hm.get("contact_url")); val.put(DBHelper.C_SERIE, hm.get("serie")); val.put(DBHelper.C_COUT, hm.get("cout")); val.put(DBHelper.C_DATE, hm.get("date")); val.put(DBHelper.C_HEURE_DEBUT, hm.get("heure_debut")); val.put(DBHelper.C_HEURE_FIN, hm.get("heure_fin")); val.put(DBHelper.C_DATE_MODIF, hm.get("date_modif")); val.put(DBHelper.C_TYPE_HORAIRE, hm.get("type_horaire")); val.put(DBHelper.C_VIGNETTE, hm.get("vignette")); val.put(DBHelper.C_IMAGE, hm.get("image")); val.put(DBHelper.C_EPOCH_DEBUT, Long.parseLong(hm.get("epoch_debut"))); val.put(DBHelper.C_EPOCH_FIN, Long.parseLong(hm.get("epoch_fin"))); val.put(DBHelper.C_EPOCH_MODIF, modif); val.put(DBHelper.C_IDS_LIEUX, hm.get("ids_lieux")); val.put(DBHelper.C_IDS_GROUPES, hm.get("ids_groupes")); val.put(DBHelper.C_IDS_CATEGORIES, hm.get("ids_categories")); val.put(DBHelper.C_IDS_SOUSCATEGORIES, hm.get("ids_souscategories")); // try { // Uri u=getContentResolver().insert(UdeMContentProvider.CONTENT_URI, val); // if( u!=null ) nb++; // } catch( SQLiteConstraintException e ) { // Log.d(TAG,"already inserted"); // } try { db.insertOrThrow(DBHelper.TABLE_E, null, val); nb++; } catch (SQLException e) { // deja dans la base de donnee... // on va verifier le epoch_modif de la bd et comparer au notre... // si ce cursor est vide, c'est que la date de modif n'a pas changee Cursor c = db.query( DBHelper.TABLE_E, new String[] {DBHelper.C_ID, DBHelper.C_EPOCH_MODIF}, "_id=" + id + " and " + DBHelper.C_EPOCH_MODIF + "<" + modif, null, null, null, null); if (c == null) continue; int count = c.getCount(); c.close(); if (count == 0) continue; // on a trouve quelque chose... on doit donc faire un update sur cet event. } // // va chercher chaque event individuel... // EventAPI event = new EventAPI(id); if (events == null || events.erreur != null) { Log.d(TAG, "event " + id + " not loaded"); continue; } // update a partir de l'evenement complet hm = event.base; // ajouter a la base de donnee val.clear(); val.put(DBHelper.C_ID, id); val.put(DBHelper.C_TITRE, hm.get("titre")); val.put(DBHelper.C_DESCRIPTION, hm.get("description")); val.put(DBHelper.C_CONTACT_NOM, hm.get("contact_nom")); val.put(DBHelper.C_CONTACT_COURRIEL, hm.get("contact_courriel")); val.put(DBHelper.C_CONTACT_TEL, hm.get("contact_tel")); val.put(DBHelper.C_CONTACT_URL, hm.get("contact_url")); val.put(DBHelper.C_SERIE, hm.get("serie")); val.put(DBHelper.C_COUT, hm.get("cout")); val.put(DBHelper.C_DATE, hm.get("date")); val.put(DBHelper.C_HEURE_DEBUT, hm.get("heure_debut")); val.put(DBHelper.C_HEURE_FIN, hm.get("heure_fin")); val.put(DBHelper.C_DATE_MODIF, hm.get("date_modif")); val.put(DBHelper.C_TYPE_HORAIRE, hm.get("type_horaire")); val.put(DBHelper.C_VIGNETTE, hm.get("vignette")); val.put(DBHelper.C_IMAGE, hm.get("image")); val.put(DBHelper.C_EPOCH_DEBUT, Long.parseLong(hm.get("epoch_debut"))); val.put(DBHelper.C_EPOCH_FIN, Long.parseLong(hm.get("epoch_fin"))); val.put(DBHelper.C_EPOCH_MODIF, Long.parseLong(hm.get("epoch_modif"))); val.put(DBHelper.C_IDS_LIEUX, hm.get("ids_lieux")); val.put(DBHelper.C_IDS_GROUPES, hm.get("ids_groupes")); val.put(DBHelper.C_IDS_CATEGORIES, hm.get("ids_categories")); val.put(DBHelper.C_IDS_SOUSCATEGORIES, hm.get("ids_souscategories")); try { db.update(DBHelper.TABLE_E, val, "_id=" + id, null); nb++; } catch (SQLException e) { } // categories for (i = 0; i < event.catList.size(); i++) { hm = event.catList.get(i); val.clear(); val.put(DBHelper.C_C_ID, hm.get("id_categorie")); val.put(DBHelper.C_C_DESC, hm.get("categorie_nom")); try { db.insertOrThrow(DBHelper.TABLE_C, null, val); } catch (SQLException e) { } } // souscategories for (i = 0; i < event.souscatList.size(); i++) { hm = event.souscatList.get(i); val.clear(); val.put(DBHelper.C_SC_ID, hm.get("id_categorie")); val.put(DBHelper.C_SC_DESC, hm.get("categorie_nom")); try { db.insertOrThrow(DBHelper.TABLE_SC, null, val); } catch (SQLException e) { } } // groupes for (i = 0; i < event.groupeList.size(); i++) { hm = event.groupeList.get(i); val.clear(); val.put(DBHelper.C_SC_ID, hm.get("id_groupe")); val.put(DBHelper.C_SC_DESC, hm.get("groupe_nom")); try { db.insertOrThrow(DBHelper.TABLE_G, null, val); } catch (SQLException e) { } } // lieux for (i = 0; i < event.lieuList.size(); i++) { hm = event.lieuList.get(i); val.clear(); val.put(DBHelper.C_SC_ID, hm.get("id_lieu")); val.put(DBHelper.C_SC_DESC, hm.get("lieu_nom")); val.put(DBHelper.C_L_SALLE, hm.get("salle")); val.put(DBHelper.C_L_ADRESSE, hm.get("adresse")); val.put(DBHelper.C_L_ADRESSE2, hm.get("adresse2")); val.put(DBHelper.C_L_VILLE, hm.get("ville")); val.put(DBHelper.C_L_PROVINCE, hm.get("province")); val.put(DBHelper.C_L_PAYS, hm.get("pays")); val.put(DBHelper.C_L_CODEPOSTAL, hm.get("code_postal")); try { val.put(DBHelper.C_L_LATITUDE, Double.parseDouble(hm.get("latitude"))); val.put(DBHelper.C_L_LONGITUDE, Double.parseDouble(hm.get("longitude"))); } catch (NumberFormatException e) { } ; // un null probablement try { db.insertOrThrow(DBHelper.TABLE_L, null, val); } catch (SQLException e) { } } } Log.d(TAG, "added " + nb + " events"); // try { // db.update(DBHelper.TABLE, val, DBHelper.C_ID+"="+id , null); // } catch ( SQLException e ) { // Log.d("service","probleme de update dans la DB :-("); // } //// now remove everything that is too old... // int k=getContentResolver().delete(UdeMContentProvider.CONTENT_URI, DBHelper.C_TIME+" < // "+past, null); // efface tout ce qui est trop vieux (dans le passe, par exemple // int k=db.delete(DBHelper.TABLE, DBHelper.C_TIME+" < "+past, null); // Log.d(TAG,"removed "+k+" old messages"); // libere la memoire events = null; db.close(); String info; if (nb == 0) info = "Aucun nouvel évenement."; else info = nb + (nb > 1 ? " nouveaux évenements." : " nouvel évenement."); // // termine en enlevant le "busy" si l'app ecoute ce signal... in = new Intent("com.seboid.udem.BUSY"); in.putExtra("busy", false); sendBroadcast(in); // // Verifions si le broadcastreceiver BUSY est disponible. // Si c'est le cas, on va faire un toast plutot qu'une notification // showNotification(mNM, info); // scheduleNextUpdate(); }