0303提交

dev
lixiangrong 2016-03-03 15:11:03 +08:00
parent cc3facc058
commit 18e4dfdaa7
10 changed files with 837 additions and 72 deletions

20
pom.xml
View File

@ -12,6 +12,7 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>4.2.4.RELEASE</spring.version>
<servlet.version>2.5</servlet.version>
</properties>
<dependencies>
@ -88,12 +89,29 @@
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>com.caucho</groupId>
<artifactId>hessian</artifactId>
<version>4.0.38</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<!-- servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>useful-code</finalName>

View File

@ -0,0 +1,44 @@
package osc.git.eh3.redis;
import java.io.InputStream;
import java.util.Properties;
public class JRedisPoolConfig {
public static String REDIS_IP;
public static int REDIS_PORT;
public static String REDIS_PASSWORD;
public static int MAX_ACTIVE;
public static int MAX_IDLE;
public static long MAX_WAIT;
public static boolean TEST_ON_BORROW;
public static boolean TEST_ON_RETURN;
static {
init();
}
public static void init() {
try {
InputStream propFile = JRedisPoolConfig.class.getResourceAsStream("redis.properties");
if(propFile != null){
Properties p = new Properties();
p.load(propFile);
REDIS_IP = p.getProperty("redis.ip");
REDIS_PORT = Integer.parseInt(p.getProperty("redis.port"));
REDIS_PASSWORD = p.getProperty("redis.password");
MAX_ACTIVE = Integer.parseInt(p.getProperty("redis.pool.maxActive"));
MAX_IDLE = Integer.parseInt(p.getProperty("redis.pool.maxIdle"));
MAX_WAIT = Integer.parseInt(p.getProperty("redis.pool.maxWait"));
TEST_ON_BORROW = Boolean.parseBoolean(p.getProperty("redis.pool.testOnBorrow"));
TEST_ON_RETURN = Boolean.parseBoolean(p.getProperty("redis.pool.testOnReturn"));
propFile.close();
propFile=null;
}else{
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,380 @@
package osc.git.eh3.redis;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class JedisUtil {
private static JedisPool jedisPool = null;
/** 缓存生存时间 */
private final static int expire = 60000;
private final static String PUBLISH_CHANNEL = "dsp_news";
private static final int DEFAULT_SINGLE_EXPIRE_TIME = 3;
private static final String CONST_STR = "_storm";
static {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(JRedisPoolConfig.MAX_ACTIVE);
config.setMaxIdle(JRedisPoolConfig.MAX_IDLE);
config.setMaxWaitMillis(JRedisPoolConfig.MAX_WAIT);
config.setTestOnBorrow(JRedisPoolConfig.TEST_ON_BORROW);
config.setTestOnReturn(JRedisPoolConfig.TEST_ON_RETURN);
// redis如果设置了密码
if (StringUtils.isEmpty(JRedisPoolConfig.REDIS_PASSWORD)) {
jedisPool = new JedisPool(config, JRedisPoolConfig.REDIS_IP,
JRedisPoolConfig.REDIS_PORT, 10000);
} else {
jedisPool = new JedisPool(config, JRedisPoolConfig.REDIS_IP,
JRedisPoolConfig.REDIS_PORT, 10000,
JRedisPoolConfig.REDIS_PASSWORD);
}
}
public static JedisPool getPool() {
return jedisPool;
}
/**
* jedisjedis
*/
public static Jedis getJedis() {
return jedisPool.getResource();
}
/**
* jedis
*/
public static void returnJedis(Jedis jedis) {
if (jedis != null)
jedisPool.returnResource(jedis);
}
/**
*
*/
public static void expire(String key, int seconds) {
if (seconds <= 0) {
return;
}
Jedis jedis = getJedis();
jedis.expire(key, seconds);
returnJedis(jedis);
}
/**
*
*/
public static void expire(String key) {
expire(key, expire);
}
public static void set(String key, String value) {
if (isBlank(key))
return;
Jedis jedis = getJedis();
jedis.set(key, value);
returnJedis(jedis);
}
public static void set(String key, Object value) {
if (isBlank(key))
return;
Jedis jedis = getJedis();
jedis.set(key.getBytes(), SerializeUtil.serialize(value));
returnJedis(jedis);
}
public static void set(String key, int value) {
if (isBlank(key))
return;
set(key, String.valueOf(value));
}
public static void set(String key, long value) {
if (isBlank(key))
return;
set(key, String.valueOf(value));
}
public static void set(String key, float value) {
if (isBlank(key))
return;
set(key, String.valueOf(value));
}
public static void set(String key, double value) {
if (isBlank(key))
return;
set(key, String.valueOf(value));
}
public static Float getFloat(String key) {
if (isBlank(key))
return null;
return Float.valueOf(getStr(key));
}
public static Double getDouble(String key) {
if (isBlank(key))
return null;
return Double.valueOf(getStr(key));
}
public static Long getLong(String key) {
if (isBlank(key))
return null;
return Long.valueOf(getStr(key));
}
public static Integer getInt(String key) {
if (isBlank(key))
return null;
return Integer.valueOf(getStr(key));
}
public static String getStr(String key) {
if (isBlank(key))
return null;
Jedis jedis = getJedis();
String value = jedis.get(key);
returnJedis(jedis);
return value;
}
public static Object getObj(String key) {
if (isBlank(key))
return null;
Jedis jedis = getJedis();
if(jedis.get(key.getBytes()) == null) {
return null;
}
byte[] bits = jedis.get(key.getBytes());
Object obj = SerializeUtil.unserialize(bits);
returnJedis(jedis);
return obj;
}
public static void delete(String key) {
Jedis jedis = getJedis();
if (jedis.get(key) != null) {
jedis.del(key);
}
returnJedis(jedis);
}
public static String[] getKeys(String pattern) {
if(isBlank(pattern)) {
return null;
}
Jedis jedis = getJedis();
Set<String> keySet = jedis.keys(pattern);
String[] keys = new String[keySet.size()];
int index = 0;
for(String key : keySet) {
keys[index] = key;
index ++;
}
returnJedis(jedis);
return keys;
}
public static void deleteByPattern(String pattern) {
Jedis jedis = getJedis();
String[] keys = getKeys(pattern);
if(keys != null && keys.length != 0) {
if(keys.length == 1) {
jedis.del(keys[0]);
}else {
jedis.del(keys);
}
}
returnJedis(jedis);
}
public static Set<String> sget(String key) {
Jedis jedis = getJedis();
returnJedis(jedis);
return jedis.smembers(key);
}
public static void sset(String key, String... members) {
Jedis jedis = getJedis();
jedis.sadd(key, members);
returnJedis(jedis);
}
public static boolean sismember(String key, String member) {
Jedis jedis = getJedis();
boolean res = jedis.sismember(key, member);
returnJedis(jedis);
return res;
}
public static void sdelete(String key, String... members) {
Jedis jedis = getJedis();
jedis.srem(key, members);
returnJedis(jedis);
}
public static void hset(String key, Map<String, String> value) {
Jedis jedis = getJedis();
jedis.hmset(key, value);
returnJedis(jedis);
}
public static void hdelete(String key) {
Jedis jedis = getJedis();
if (jedis.hgetAll(key) != null) {
jedis.del(key);
}
returnJedis(jedis);
}
public static boolean isBlank(String str) {
return str == null || "".equals(str.trim());
}
public static boolean exists(String key) {
Jedis jedis = getJedis();
boolean isexist = jedis.exists(key);
returnJedis(jedis);
return isexist;
}
public static void publishNews(String str){
Jedis jedis = getJedis();
jedis.publish(PUBLISH_CHANNEL, str);
returnJedis(jedis);
}
/**
* true false
* @param key
* @param timeout
* @param unit
* @return
*/
@SuppressWarnings("resource")
private static boolean trylock(String key) {
Jedis jedis = null;
try {
jedis = getJedis();
do {
Long i = jedis.setnx(key + CONST_STR, key);
if (i == 1) {
jedis.expire(key + CONST_STR, DEFAULT_SINGLE_EXPIRE_TIME);
return Boolean.TRUE;
}
Thread.sleep(100);
} while (true);
} catch (RuntimeException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
returnJedis(jedis);
}
return Boolean.FALSE;
}
/**
*
* @param key
*/
public static void unlock(String key) {
delete(key + CONST_STR);
}
public static void setWithLock(String key, String value) {
Jedis jedis = null;
try {
jedis = getJedis();
jedis.set(key, value);
if (jedis.get(key + CONST_STR) != null) {
unlock(key);
}
} catch (RuntimeException e) {
e.printStackTrace();
} finally {
returnJedis(jedis);
}
}
public static String getStrWithLock(String key) {
String value = null;
Jedis jedis = null;
try {
jedis = getJedis();
if (jedis.get(key) != null && trylock(key)) {
value = jedis.get(key);
if (value == null) {
unlock(key);
}
}
} catch (RuntimeException e) {
e.printStackTrace();
} finally {
returnJedis(jedis);
}
return value;
}
public static void main(String[] args) {
}
public static void lpush(String key, String value) {
if (isBlank(key))
return;
Jedis jedis = getJedis();
jedis.lpush(key, value);
returnJedis(jedis);
}
public static String[] hkeys(String key){
if (isBlank(key))
return null;
Jedis jedis = getJedis();
Set<String> keySet = jedis.hkeys(key);
List<String> keys = new ArrayList<String>();
for(String hkey : keySet) {
keys.add(hkey);
}
returnJedis(jedis);
return keys.toArray(new String[keys.size()]);
}
public static String hget(String key, String hkey) {
if (isBlank(key)||isBlank(hkey))
return "";
Jedis jedis = getJedis();
String value = jedis.hget(key, hkey);
returnJedis(jedis);
return value;
}
public static List<String> hmget(String key, String[] hkey) {
if (isBlank(key))
return null;
Jedis jedis = getJedis();
List<String> value = jedis.hmget(key, hkey);
returnJedis(jedis);
return value;
}
}

View File

@ -0,0 +1,49 @@
package osc.git.eh3.redis;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class SerializeUtil {
/**
*
*
* @param object
* @return
*/
public static byte[] serialize(Object object) {
ObjectOutputStream oos = null;
ByteArrayOutputStream baos = null;
try {
// 序列化
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
byte[] bytes = baos.toByteArray();
return bytes;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
*
*
* @param bytes
* @return
*/
public static Object unserialize(byte[] bytes) {
ByteArrayInputStream bais = null;
try {
// 反序列化
bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
return ois.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}

View File

@ -0,0 +1,9 @@
redis.pool.maxActive=1024
redis.pool.maxIdle=200
redis.pool.maxWait=1000
redis.pool.testOnBorrow=true
redis.pool.testOnReturn=true
redis.ip=192.168.3.140
#redis.ip=pxene12
redis.port=7389
redis.password=

View File

@ -4,12 +4,7 @@ import java.io.File;
import java.io.FilenameFilter;
public class DirList {
/**
* @param args
* The file pattern that need to be matched.
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
File path = new File("D://");
String arg = "dsp_impclk_15";
String[] list;
@ -25,13 +20,11 @@ public class DirList {
class DirFilter implements FilenameFilter {
String afn;
DirFilter(String afn) {
this.afn = afn;
}
public boolean accept(File dir, String name) {
// Strip path information.
String f = new File(name).getName();
return f.indexOf(afn) != -1;
}

View File

@ -1,6 +1,8 @@
package osc.git.eh3.test;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
@ -31,14 +33,14 @@ public class TestCode {
// Map<String, Object> resultMap = new HashMap<String, Object>();
// System.out.println((String)resultMap.get("dd"));
// try {
// String str = null;
// str.equals("");
// } catch (Exception e) {
// System.out.println(e.getMessage());
// e.printStackTrace();
// }
// System.out.println("fffff");
// try {
// String str = null;
// str.equals("");
// } catch (Exception e) {
// System.out.println(e.getMessage());
// e.printStackTrace();
// }
// System.out.println("fffff");
// String[] s = {"111","eee"};
// System.out.println(Arrays.toString(s));
@ -51,67 +53,83 @@ public class TestCode {
//
// System.out.println(list.toString());
// JSONArray areaTarget = new JSONArray();
// areaTarget.add("3");
// areaTarget.add("5");
// areaTarget.add("4");
// areaTarget.add("7");
// System.out.println(JSONArray.toList(areaTarget));
// String whiteStr = "2,4,5,8,3";
// System.out.println(JSONArray.fromObject(whiteStr.split(",")));
// for (int i = 0;i<2;i++) {
//
// if ("1".equals("1")) {
// if ("1".equals("1")) {
// System.out.println("111111111111111");
// continue;
// }
// System.out.println("2222222222222222");
// }
// System.out.println("3333333333333333333333");
// }
// String str = "http://www.test.com";
// System.out.println(str.replace("http://www.", "").replace("www.", ""));
// SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
// SimpleDateFormat sdf = new SimpleDateFormat("HH");
// String str = "23:59:59";
// System.out.println(sdf.format(formatter.parse(str)));
// JSONArray areaTarget = new JSONArray();
// areaTarget.add("3");
// areaTarget.add("5");
// areaTarget.add("4");
// areaTarget.add("7");
// System.out.println(JSONArray.toList(areaTarget));
// String whiteStr = "2,4,5,8,3";
// System.out.println(JSONArray.fromObject(whiteStr.split(",")));
// for (int i = 0;i<2;i++) {
//
// if ("1".equals("1")) {
// if ("1".equals("1")) {
// System.out.println("111111111111111");
// continue;
// }
// System.out.println("2222222222222222");
// }
// System.out.println("3333333333333333333333");
// }
// String str = "http://www.test.com";
// System.out.println(str.replace("http://www.", "").replace("www.",
// ""));
// SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
// SimpleDateFormat sdf = new SimpleDateFormat("HH");
// String str = "23:59:59";
// System.out.println(sdf.format(formatter.parse(str)));
// Spring Hessian代理Servelet
// String url = "http://localhost:8080/sync-logs/remote/readlogs";
// HessianProxyFactory factory = new HessianProxyFactory();
//
// IReadLogs readLogs = (IReadLogs) factory.create(IReadLogs.class, url);
// JSONArray result = JSONArray.fromObject(readLogs.readFile("2016-02-22 15:00:00", "00000000000000"));
// System.out.println(result);
// String url = "http://localhost:8080/sync-logs/remote/readlogs";
// HessianProxyFactory factory = new HessianProxyFactory();
//
// IReadLogs readLogs = (IReadLogs) factory.create(IReadLogs.class,
// url);
// JSONArray result = JSONArray.fromObject(readLogs.readFile("2016-02-22
// 15:00:00", "00000000000000"));
// System.out.println(result);
// JSONArray jonsArr = new JSONArray();
// JSONArray arr = new JSONArray();
// jonsArr = JSONArray.fromObject("[ { 'category': 2, 'clks': 4, 'cost':
// 13, 'createtime': null, 'creativeid':
// 'cf0714f4-8b92-41f2-a843-19c94fe3af74', 'downloads': 0, 'flag': 0,
// 'imprs': 5, 'regists': 0, 'time': null } ]");
// arr.addAll(JSONArray.toCollection(jonsArr));
// System.out.println(arr);
// String str =
// "20160222,18:59:50.523,DBG,ip:36.100.240.103,adx:3,bid:08a2d93b-0153-1000-fd75-3f89c5394190,mapid:62367312-d881-426d-81b4-fe635d1db989,deviceid:726e14bf3ba615e5387c256059e9f24a94721f76,deviceidtype:97,mtype:m";
// for(String dd : str.split(",")){
//
// System.out.println(dd);
// }
// BigDecimal dd = new BigDecimal("1111.10");
// JSONObject jj = new JSONObject();
// jj.put("test", dd);
// System.out.println(jj.optDouble("test"));
// JSONObject jj = new JSONObject();
// System.out.println(jj.optString("pring"));
// JSONArray jonsArr = new JSONArray();
// JSONArray arr = new JSONArray();
// jonsArr = JSONArray.fromObject("[ { 'category': 2, 'clks': 4, 'cost': 13, 'createtime': null, 'creativeid': 'cf0714f4-8b92-41f2-a843-19c94fe3af74', 'downloads': 0, 'flag': 0, 'imprs': 5, 'regists': 0, 'time': null } ]");
// arr.addAll(JSONArray.toCollection(jonsArr));
// System.out.println(arr);
// String str = "20160222,18:59:50.523,DBG,ip:36.100.240.103,adx:3,bid:08a2d93b-0153-1000-fd75-3f89c5394190,mapid:62367312-d881-426d-81b4-fe635d1db989,deviceid:726e14bf3ba615e5387c256059e9f24a94721f76,deviceidtype:97,mtype:m";
// for(String dd : str.split(",")){
//
// System.out.println(dd);
// }
// BigDecimal dd = new BigDecimal("1111.10");
// JSONObject jj = new JSONObject();
// jj.put("test", dd);
// System.out.println(jj.optDouble("test"));
JSONObject jj = new JSONObject();
System.out.println(jj.optString("pring"));
// 根据网卡取本机配置的IP
InetAddress inet = null;
try {
inet = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
String ipAddress = inet.getHostAddress();
System.out.println(ipAddress);
}
public static Long parseDate(String s) {

View File

@ -0,0 +1,131 @@
package osc.git.eh3.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONObject;
import osc.git.eh3.redis.JedisUtil;
public class TestJdbc {
private static Connection getConn() {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://192.168.3.166:3306/wins-dsp-new?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&connectTimeout=60000&socketTimeout=60000";
String username = "root";
String password = "pxene";
Connection conn = null;
try {
Class.forName(driver); // classLoader,加载对应驱动
conn = (Connection) DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
private static Integer getAll() {
Connection conn = getConn();
String sql = "SELECT v.* FROM dsp_v_app_motionclick_day_count v WHERE v.time BETWEEN 1433088000000 AND 1453046400000 ";
// String sql = "SELECT * FROM dsp_t_ad_group_adx_creative WHERE groupid
// = 'd092c630-abfd-45a1-92f3-d0530c1caee8' LIMIT 1,3;";
PreparedStatement pstmt;
try {
pstmt = (PreparedStatement) conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
ResultSetMetaData metaData = rs.getMetaData();
while (rs.next()) {
JSONObject jsonObject = new JSONObject();
String time = "";
String mapid = "";
String appid = "";
String adxtype = "";
for (int i = 1; i <= metaData.getColumnCount(); i++) {
String columnName = metaData.getColumnName(i);
if ("time".equals(columnName)) {
time = rs.getString(i);
}
if ("mapid".equals(columnName)) {
mapid = rs.getString(i);
}
if ("appid".equals(columnName)) {
appid = rs.getString(i);
}
if ("adxtype".equals(columnName)) {
adxtype = rs.getString(i);
}
jsonObject.put(columnName, rs.getString(i));
}
Map<String, String> map = new HashMap<>();
map.put(time + "_" + appid + "_" + adxtype, jsonObject.toString());
JedisUtil.hset("HistoryAPPData_" + mapid, map);
// JedisUtil.lpush("HistoryAPPData_"+mapid+"_"+time,
// jsonObject.toString());
System.out.println("HistoryAPPData_" + mapid);
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
// getAll();
JedisUtil.deleteByPattern("HistoryAPPData_*");
/*
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date start = new Date();
List<String> mapids = getMapid();
// String[] keys = JedisUtil.getKeys("HistoryAPPData_*");
List<String> alldata = new ArrayList<String>();
for (String mapid : mapids) {
String key = "HistoryAPPData_" + mapid;
String[] hkeys = JedisUtil.hkeys(key);
// for (String hkey : hkeys) {
// System.out.println(JedisUtil.hget(key, hkey));
// }
if(hkeys.length>0){
List<String> hmget = JedisUtil.hmget(key, hkeys);
alldata.addAll(hmget);
}
}
System.out.println(alldata.size());
Date end = new Date();
System.out.println(sdf.format(start));
System.out.println(sdf.format(end));
*/
}
private static List<String> getMapid() {
List<String> mapids = new ArrayList<String>();
Connection conn = getConn();
String sql = "SELECT t2.id AS mapid FROM dsp_t_ad_group_creative t2 LEFT JOIN dsp_t_ad_group t3 ON t2.groupid = t3.id LEFT JOIN dsp_t_campaign t4 ON t3.campaignid = t4.id LEFT JOIN dsp_t_advertiser_account t5 ON t4.accountid = t5.id LEFT JOIN dsp_t_advertiser t6 ON t5.advertiserid = t6.id WHERE ( t4.accountid IN ( SELECT id FROM dsp_t_advertiser_account t6 WHERE t6.advertiserid IN ( SELECT id FROM dsp_t_advertiser t7 WHERE t7.parentid = 'dfecbd8a-2d7e-4941-bd89-e39c576c5ee5' ) ) OR t4.accountid = 'dfecbd8a-2d7e-4941-bd89-e39c576c5ee5' )";
// String sql = "SELECT * FROM dsp_t_ad_group_adx_creative WHERE groupid
// = 'd092c630-abfd-45a1-92f3-d0530c1caee8' LIMIT 1,3;";
PreparedStatement pstmt;
try {
pstmt = (PreparedStatement) conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
ResultSetMetaData metaData = rs.getMetaData();
while (rs.next()) {
for (int i = 1; i <= metaData.getColumnCount(); i++) {
mapids.add(rs.getString(i));
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return mapids;
}
}

View File

@ -0,0 +1,83 @@
package osc.git.eh3.test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TestReadFile {
public static void readFile() {
File file = new File("C:/Users/lixiangrong/Desktop/IPB.txt");
BufferedReader reader = null;
Map<String, Object> resultMap = null;
List<Long> startList = null;
List<Long> endList = null;
try {
resultMap = new HashMap<String, Object>();
startList = new ArrayList<Long>();
endList = new ArrayList<Long>();
reader = new BufferedReader(new FileReader(file));
String tempString = null;
while ((tempString = reader.readLine()) != null) {
String[] tempArr = tempString.split(" ");
resultMap.put(tempArr[0], tempArr);
startList.add(Long.parseLong(tempArr[0]));
endList.add(Long.parseLong(tempArr[1]));
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
long des = 17301504l;
long key = binarySearch(startList.toArray(new Long[startList.size()]), des);
String[] tempArr = (String[]) resultMap.get(key);
for (int i = 0; i < tempArr.length; i++) {
System.out.println(tempArr[i]);
}
}
public static void main(String[] args) {
readFile();
}
/**
* * * *
*
* @param srcArray
* *
* @param des
* *
* @return des-1
*/
public static long binarySearch(Long[] srcArray, long des) {
int low = 0;
int high = srcArray.length - 1;
while (low <= high) {
int middle = (low + high) / 2;
if (des == srcArray[middle]) {
return middle;
} else if (des < srcArray[middle]) {
high = middle - 1;
} else {
low = middle + 1;
}
}
return -1;
}
}

View File

@ -2,11 +2,15 @@ package osc.git.eh3.utils;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
public class CommonUtils {
/**
*
@ -99,4 +103,40 @@ public class CommonUtils {
}
return dataBean;
}
/**
* ip
*
* @param request
* @return
*/
public static String getIpAddr(HttpServletRequest request) {
String ipAddress = request.getHeader("x-forwarded-for");
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
// 根据网卡取本机配置的IP
InetAddress inet = null;
try {
inet = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
ipAddress = inet.getHostAddress();
}
}
// 对于通过多个代理的情况第一个IP为客户端真实IP,多个IP按照','分割
if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()=15
if (ipAddress.indexOf(",") > 0) {
ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
}
}
return ipAddress;
}
}