Skip to content

Instantly share code, notes, and snippets.

@shijinkui
Created May 30, 2014 02:40
Show Gist options
  • Select an option

  • Save shijinkui/8abe9a66d9f74f4a6aba to your computer and use it in GitHub Desktop.

Select an option

Save shijinkui/8abe9a66d9f74f4a6aba to your computer and use it in GitHub Desktop.
import com.google.common.base.*;
import com.google.common.cache.*;
import com.google.common.collect.*;
import com.google.common.hash.*;
import com.google.common.hash.Hashing;
import com.google.common.io.Files;
import com.google.common.io.LineProcessor;
import org.junit.Assert;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
/**
* @author 玄畅
* @date 5/23/14 23:28
*/
public class GuavaTest {
@Test
public void testOptional() {
Optional<Long> possible = Optional.of(5l);
Assert.assertTrue(possible.isPresent());
Assert.assertEquals(possible.get().longValue(), 5l);
String str = null;
Optional<String> os = Optional.fromNullable(str);
Assert.assertNull(os.orNull());
Assert.assertEquals(os.or("aa"), "aa");
System.out.println(os.or("lasdfjlasdjf"));
// 返回两个中前面不为null的字符串
String s = Objects.firstNonNull(null, "ss");
Assert.assertEquals(s, "ss");
System.out.println(s);
}
@Test
public void testNullEmpty() {
// null --> ""
String s = Strings.nullToEmpty(null);
Assert.assertEquals(s, "");
// "" --> null
String s2 = Strings.emptyToNull("");
Assert.assertNull(s2);
}
@Test
public void testPreconditions() {
Preconditions.checkArgument(true); // IllegalArgumentException
Preconditions.checkNotNull(null);
}
@Test
public void testFunction() {
// 把一个字符串列表,转化成只包含大写的字符串长度集合
final Set<String> list = ImmutableSet.of("a", "LJSLDJF", "B", "asadfSDFas");
Multiset<Integer> lengths = HashMultiset.create(
FluentIterable.from(list)
.filter(new Predicate<String>() {
public boolean apply(String string) {
// 检查条件,true检查通过
return CharMatcher.JAVA_UPPER_CASE.matchesAllOf(string);
}
})
.transform(
new Function<String, Integer>() {
public Integer apply(String string) {
// 改变单个Item,返回新值
return string.length();
}
}));
// 得到转化的结果
for (int len : lengths) {
System.out.println(len);
}
}
@Test
public void testJoiner() {
String baseUrl = "http://www.taobao.com/m?";
ImmutableMap<String, String> map = ImmutableMap.of("a", "va", "b", "vb", "c", "vc");
// 字符串拼接
String r1 = Joiner.on("&").withKeyValueSeparator("=").join(map);
System.out.println(baseUrl + r1);
String r2 = Joiner.on("-").skipNulls().join("asdf", "", null, "2323");
System.out.println(r2);
}
@Test
public void testSplitter() {
String url = "http://tiaoshi.taobao.com/?spm=1.7274553.1997517397.2.FAQPAH&acm=20140506001.1003.2.70913&ad_id=&cm_id=&pm_id=&am_id=130109847509e8c34b1b&uuid=79KoSnlA&scm=1003.2.20140506001.OTHER_1402811863232_70913&pos=0";
Map<String, String> ret = Splitter.on("&").withKeyValueSeparator("=").split(url);
for (Map.Entry<String, String> entry : ret.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
}
@Test
public void testIO() throws IOException {
File f = new File("/Users/shijinkui/tmp/ssltest.py");
String ret = Files.readLines(f, Charset.defaultCharset(), new LineProcessor<String>() {
StringBuffer sf = new StringBuffer();
@Override
public boolean processLine(String line) throws IOException {
if (line.length() > 0) {
sf.append(line).append("\n");
}
return true;
}
@Override
public String getResult() {
return sf.toString();
}
});
System.out.println(ret);
}
@Test
public void testHash() {
// 支持的hash
// md5() murmur3_128() murmur3_32() sha1()
// sha256() sha512() goodFastHash(int bits)
HashFunction hf = Hashing.md5();
HashCode hc = hf.newHasher()
.putLong(System.currentTimeMillis())
.putString("sjk", Charsets.UTF_8)
.hash();
System.out.println(hc.toString());
}
@Test
public void testBloomFilter() {
BloomFilter<Long> friends = BloomFilter.create(Funnels.longFunnel(), 500, 0.01);
ImmutableList<Long> list = ImmutableList.of(1l, 2l, 2489234l, 1l);
for (long friend : list) {
friends.put(friend);
}
System.out.println(friends.mightContain(1l));
System.out.println(friends.mightContain(2l));
System.out.println(friends.mightContain(2489234l));
System.out.println(friends.mightContain(1232l));
}
@Test
public void testCache() throws ExecutionException, InterruptedException {
LoadingCache<String, String> cache = CacheBuilder.newBuilder().softValues()
.maximumSize(1000)
.expireAfterWrite(2, TimeUnit.SECONDS)
.recordStats()
.removalListener(
new RemovalListener<String, String>() {
@Override
public void onRemoval(RemovalNotification notify) {
System.out.println("remove notify: " + notify.getKey() + "||"
+ notify.getValue() + "||" + notify.getCause().toString());
}
})
.build(new CacheLoader<String, String>() {
public String load(String key) throws Exception {
System.out.println("--->> reload:" + key);
return key + "--" + System.currentTimeMillis();
}
});
cache.put("1", "111");
cache.put("2", "32323");
cache.put("3", "asfasf");
System.out.println(cache.get("1"));
System.out.println(cache.getIfPresent("122"));
Thread.sleep(3000);
System.out.println(cache.get("1"));
System.out.println(cache.stats().toString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment