hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
---|---|---|---|---|---|
aefbe535c611d078be026ab4949858822b69437f | 25,685 | package org.nutz.ssdb4j;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.nutz.ssdb4j.impl.BatchClient;
import org.nutz.ssdb4j.impl.DefaultObjectConv;
import org.nutz.ssdb4j.impl.SocketSSDBStream;
import org.nutz.ssdb4j.pool2.Pool2s;
import org.nutz.ssdb4j.spi.Cmd;
import org.nutz.ssdb4j.spi.KeyValue;
import org.nutz.ssdb4j.spi.ObjectConv;
import org.nutz.ssdb4j.spi.Response;
import org.nutz.ssdb4j.spi.SSDB;
import org.nutz.ssdb4j.spi.SSDBException;
import org.nutz.ssdb4j.spi.SSDBStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author wr
*
*/
public class SSDBClient {
private static final Logger LOGGER = LoggerFactory.getLogger(SSDBClient.class);
protected SSDBStream stream;
protected ObjectConv conv;
public SSDBClient(String host, int port, int timeoutSeconds, String pass) {
this.stream = Pool2s.pool(host, port, timeoutSeconds, null, isBlank(pass) ? null : pass.getBytes());
this.conv = DefaultObjectConv.me;
}
public SSDBClient(SSDBStream stream) {
this.stream = stream;
this.conv = DefaultObjectConv.me;
}
public SSDBClient(String host, int port, int timeout) {
stream = new SocketSSDBStream(host, port, timeout);
this.conv = DefaultObjectConv.me;
}
protected byte[] bytes(Object obj) {
return conv.bytes(obj);
}
protected byte[][] bytess(Object... objs) {
return conv.bytess(objs);
}
public static boolean isBlank(String str) {
int strLen;
if ((str == null) || ((strLen = str.length()) == 0))
return true;
for (int i = 0; i < strLen; ++i) {
if (!(Character.isWhitespace(str.charAt(i)))) {
return false;
}
}
return true;
}
protected Response req(Cmd cmd, byte[] first, byte[][] lots) {
byte[][] vals = new byte[lots.length + 1][];
vals[0] = first;
for (int i = 0; i < lots.length; i++) {
vals[i + 1] = lots[i];
}
try {
return req(cmd, vals);
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return null;
}
public Response req(Cmd cmd, byte[]... vals) {
return stream.req(cmd, vals);
}
public SSDB batch() {
return new BatchClient(stream, 60, TimeUnit.SECONDS);
}
public SSDB batch(int timeout, TimeUnit timeUnit) {
return new BatchClient(stream, timeout, timeUnit);
}
public List<Response> exec() {
throw new SSDBException("not batch!");
}
public void setObjectConv(ObjectConv conv) {
this.conv = conv;
}
public void changeObjectConv(ObjectConv conv) {
this.setObjectConv(conv);
}
public void setSSDBStream(SSDBStream stream) {
this.stream = stream;
}
// ----------------------------------------------------------------------------------
public String get(Object key) {
try {
return req(Cmd.get, bytes(key)).asString();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return null;
}
public int set(Object key, Object val) {
try {
return req(Cmd.set, bytes(key), bytes(val)).asInt();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return 0;
}
public int setx(Object key, Object val, int ttl) {
try {
return req(Cmd.setx, bytes(key), bytes(val), Integer.toString(ttl).getBytes()).asInt();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return 0;
}
public int del(Object key) {
try {
return req(Cmd.del, bytes(key)).asInt();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return 0;
}
public long incr(Object key, int val) {
try {
return req(Cmd.incr, bytes(key), Integer.toString(val).getBytes()).asLong();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return 0;
}
public boolean exists(Object key) {
try {
return req(Cmd.exists, bytes(key)).asInt() > 0;
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return false;
}
public List<String> keys(Object start, Object end, int limit) {
try {
return req(Cmd.keys, bytes(start), bytes(end), Integer.toString(limit).getBytes()).listString();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return null;
}
public int multiSet(Object... pairs) {
try {
return req(Cmd.multi_set, bytess(pairs)).asInt();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return 0;
}
public List<String> multiGet(Object... keys) {
try {
return req(Cmd.multi_get, bytess(keys)).listString();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return null;
}
public int multiDel(Object... keys) {
try {
return req(Cmd.multi_del, bytess(keys)).asInt();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return 0;
}
public List<KeyValue> scan(Object start, Object end, int limit) {
try {
return req(Cmd.scan, bytes(start), bytes(end), Integer.toString(limit).getBytes()).asKeyValues();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return null;
}
public List<KeyValue> rscan(Object start, Object end, int limit) {
try {
return req(Cmd.rscan, bytes(start), bytes(end), Integer.toString(limit).getBytes()).asKeyValues();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return null;
}
public int hset(Object key, Object hkey, Object hval) {
try {
return req(Cmd.hset, bytes(key), bytes(hkey), bytes(hval)).asInt();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return 0;
}
public int hdel(Object key, Object hkey) {
try {
return req(Cmd.hdel, bytes(key), bytes(hkey)).asInt();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return 0;
}
public String hget(Object key, Object hkey) {
try {
return req(Cmd.hget, bytes(key), bytes(hkey)).asString();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return null;
}
public int hsize(Object key) {
try {
return req(Cmd.hsize, bytes(key)).asInt();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return 0;
}
public List<KeyValue> hlist(Object key, Object hkey, int limit) {
try {
return req(Cmd.hlist, bytes(key), bytes(hkey), Integer.toString(limit).getBytes()).asKeyValues();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return null;
}
public long hincr(Object key, Object hkey, int val) {
try {
return req(Cmd.hincr, bytes(key), bytes(hkey), Integer.toString(val).getBytes()).asLong();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return 0;
}
public List<KeyValue> hscan(Object key, Object start, Object end, int limit) {
try {
return req(Cmd.hscan, bytes(key), bytes(start), bytes(end), Integer.toString(limit).getBytes())
.asKeyValues();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return null;
}
public List<KeyValue> hrscan(Object key, Object start, Object end, int limit) {
try {
return req(Cmd.hrscan, bytes(key), bytes(start), bytes(end), Integer.toString(limit).getBytes())
.asKeyValues();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return null;
}
public int zset(Object key, Object zkey, long score) {
try {
return req(Cmd.zset, bytes(key), bytes(zkey), Long.toString(score).getBytes()).asInt();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return 0;
}
public long zget(Object key, Object zkey) {
try {
return req(Cmd.zget, bytes(key), bytes(zkey)).asLong();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return 0;
}
public int zdel(Object key, Object zkey) {
try {
return req(Cmd.zdel, bytes(key), bytes(zkey)).asInt();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return 0;
}
public long zincr(Object key, Object zkey, int val) {
try {
return req(Cmd.zincr, bytes(key), bytes(zkey), Integer.toString(val).getBytes()).asLong();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return 0;
}
public int zsize(Object key) {
try {
return req(Cmd.zsize, bytes(key)).asInt();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return 0;
}
public List<String> zlist(Object zkey_start, Object zkey_end, int limit) {
try {
return req(Cmd.zlist, bytes(zkey_start), bytes(zkey_end), Integer.toString(limit).getBytes()).listString();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return null;
}
public int zrank(Object key, Object zkey) {
try {
return req(Cmd.zrank, bytes(key), bytes(zkey)).asInt();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return 0;
}
public int zrrank(Object key, Object zkey) {
try {
return req(Cmd.zrrank, bytes(key), bytes(zkey)).asInt();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return 0;
}
public List<KeyValue> zscan(Object key, Object zkey_start, Object score_start, Object score_end, int limit) {
try {
return req(Cmd.zscan, bytes(key), bytes(zkey_start), bytes(score_start), bytes(score_end),
Integer.toString(limit).getBytes()).asKeyScores();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return null;
}
public List<KeyValue> zrscan(Object key, Object zkey_start, Object score_start, Object score_end, int limit) {
try {
return req(Cmd.zrscan, bytes(key), bytes(zkey_start), bytes(score_start), bytes(score_end),
Integer.toString(limit).getBytes()).asKeyScores();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return null;
}
public List<KeyValue> zpopfront(Object key, int limit) {
try {
return req(Cmd.zpopfront, bytes(key), Integer.toString(limit).getBytes()).asKeyScores();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return null;
}
public List<KeyValue> zpopback(Object key, int limit) {
try {
return req(Cmd.zpopback, bytes(key), Integer.toString(limit).getBytes()).asKeyScores();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return null;
}
public int qsize(Object key) {
try {
return req(Cmd.qsize, bytes(key)).asInt();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return 0;
}
public String qfront(Object key) {
try {
return req(Cmd.qfront, bytes(key)).asString();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return null;
}
public String qback(Object key) {
try {
return req(Cmd.qback, bytes(key)).asString();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return null;
}
public int qpush(Object key, Object value) {
try {
return req(Cmd.qpush, bytes(key), bytes(value)).asInt();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return 0;
}
public List<String> qpop(Object key) {
try {
return req(Cmd.qpop, bytes(key)).listString();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return null;
}
public List<String> qlist(Object key_start, Object key_end, int limit) {
try {
return req(Cmd.qlist, bytes(key_start), bytes(key_end), Integer.toString(limit).getBytes()).listString();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return null;
}
public boolean qclear(Object key) {
try {
req(Cmd.qclear, bytes(key)).ok();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return false;
}
public List<String> hkeys(Object key, Object start, Object end, int limit) {
try {
return req(Cmd.hkeys, bytes(key), bytes(start), bytes(end), Integer.toString(limit).getBytes())
.listString();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return null;
}
public boolean hexists(Object key, Object hkey) {
try {
return req(Cmd.hexists, bytes(key), bytes(hkey)).asInt() > 0;
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return false;
}
public int hclear(Object key) {
try {
return req(Cmd.hclear, bytes(key)).asInt();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return 0;
}
public List<KeyValue> multiHget(Object key, Object... hkeys) {
try {
return req(Cmd.multi_hget, bytes(key), bytess(hkeys)).asKeyValues();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return null;
}
public boolean multiHset(Object key, Object... pairs) {
try {
return req(Cmd.multi_hset, bytes(key), bytess(pairs)).ok();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return false;
}
public int multiHdel(Object key, Object... hkeys) {
try {
return req(Cmd.multi_hdel, bytes(key), bytess(hkeys)).asInt();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return 0;
}
public boolean zexists(Object key, Object zkey) {
try {
return req(Cmd.zexists, bytes(key), bytes(zkey)).asInt() > 0;
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return false;
}
public int zclear(Object key) {
try {
return req(Cmd.zclear, bytes(key)).asInt();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return 0;
}
public List<String> zkeys(Object key, Object zkey_start, Object score_start, Object score_end, int limit) {
try {
return req(Cmd.zkeys, bytes(key), bytes(zkey_start), bytes(score_start), bytes(score_end),
Integer.toString(limit).getBytes()).listString();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return null;
}
public List<KeyValue> zrange(Object key, int offset, int limit) {
try {
return req(Cmd.zrange, bytes(key), Integer.toString(offset).getBytes(), Integer.toString(limit).getBytes())
.asKeyScores();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return null;
}
public List<KeyValue> zrrange(Object key, int offset, int limit) {
try {
return req(Cmd.zrrange, bytes(key), Integer.toString(offset).getBytes(), Integer.toString(limit).getBytes())
.asKeyScores();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return null;
}
public boolean multiZset(Object key, Object... pairs) {
try {
return req(Cmd.multi_zset, bytes(key), bytess(pairs)).ok();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return false;
}
public List<KeyValue> multiZget(Object key, Object... zkeys) {
try {
return req(Cmd.multi_zget, bytes(key), bytess(zkeys)).asKeyScores();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return null;
}
public int multiZdel(Object key, Object... zkeys) {
try {
return req(Cmd.multi_zdel, bytes(key), bytess(zkeys)).asInt();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return 0;
}
public long flushdb(String type) {
if (type == null || type.length() == 0) {
long count = 0;
count += flushdb_kv();
count += flushdb_hash();
count += flushdb_zset();
count += flushdb_list();
return count;
}
if ("kv".equals(type)) {
return flushdb_kv();
}
if ("hash".equals(type)) {
return flushdb_hash();
}
if ("zset".equals(type)) {
return flushdb_zset();
}
if ("list".equals(type)) {
return flushdb_list();
}
throw new IllegalArgumentException("not such flushdb mode=" + type);
}
protected long flushdb_kv() {
long count = 0;
while (true) {
List<String> keys = keys("", "", 1000);
if (null == keys || keys.isEmpty())
return count;
count += keys.size();
multiDel(keys.toArray());
}
}
protected long flushdb_hash() {
long count = 0;
while (true) {
List<KeyValue> keys = hlist("", "", 1000);
if (null == keys || keys.isEmpty())
return count;
count += keys.size();
for (KeyValue key : keys) {
hclear(key.getKey());
}
}
}
protected long flushdb_zset() {
long count = 0;
while (true) {
List<String> keys = zlist("", "", 1000);
if (null == keys || keys.isEmpty())
return count;
count += keys.size();
for (String key : keys) {
zclear(key);
}
}
}
protected long flushdb_list() {
long count = 0;
while (true) {
List<String> keys = qlist("", "", 1000);
if (null == keys || keys.isEmpty())
return count;
count += keys.size();
for (String key : keys) {
qclear(key);
}
}
}
public String info() {
try {
return req(Cmd.info).asBlocks('\n');
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return null;
}
// ------------------------------------------
public int setnx(Object key, Object val) {
try {
return req(Cmd.setnx, bytes(key), bytes(val)).asInt();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return 0;
}
public String getset(Object key, Object val) {
try {
return req(Cmd.getset, bytes(key), bytes(val)).asString();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return null;
}
public List<String> qslice(Object key, int start, int end) {
try {
return req(Cmd.qslice, bytes(key), Integer.toString(start).getBytes(), Integer.toString(end).getBytes())
.listString();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return null;
}
public String qget(Object key, int index) {
try {
return req(Cmd.qget, bytes(key), Integer.toString(index).getBytes()).asString();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return null;
}
public int zcount(Object key, int start, int end) {
try {
return req(Cmd.zcount, bytes(key), Integer.toString(start).getBytes(), Integer.toString(end).getBytes())
.asInt();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return 0;
}
public long zsum(Object key, int start, int end) {
try {
return req(Cmd.zsum, bytes(key), Integer.toString(start).getBytes(), Integer.toString(end).getBytes())
.asLong();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return 0;
}
public long zavg(Object key, int start, int end) {
try {
return req(Cmd.zavg, bytes(key), Integer.toString(start).getBytes(), Integer.toString(end).getBytes())
.asLong();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return 0;
}
public int ttl(Object key) {
try {
return req(Cmd.ttl, bytes(key)).asInt();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return 0;
}
public List<KeyValue> hgetall(Object key) {
try {
return req(Cmd.hgetall, bytes(key)).asKeyValues();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return null;
}
public int zremrangebyrank(Object key, Object score_start, Object score_end) {
try {
return req(Cmd.zremrangebyrank, bytes(key), bytes(score_start), bytes(score_end)).asInt();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return 0;
}
public int zremrangebyscore(Object key, Object score_start, Object score_end) {
try {
return req(Cmd.zremrangebyscore, bytes(key), bytes(score_start), bytes(score_end)).asInt();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return 0;
}
public boolean multiZexists(Object key, Object... zkeys) {
try {
return req(Cmd.zexists, bytes(key), bytess(zkeys)).asInt() > 0;
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return false;
}
public int multiZsize(Object... keys) {
try {
return req(Cmd.zsize, bytess(keys)).asInt();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return 0;
}
public int qpushBack(Object key, Object value) {
try {
return req(Cmd.qpush_back, bytes(key), bytes(value)).asInt();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return 0;
}
public int qpushFront(Object key, Object value) {
try {
return req(Cmd.qpush_front, bytes(key), bytes(value)).asInt();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return 0;
}
public int qpopBack(Object key) {
try {
return req(Cmd.qpop_back, bytes(key)).asInt();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return 0;
}
public List<String> qpopFront(Object key) {
try {
return req(Cmd.qpop_front, bytes(key)).listString();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return null;
}
public List<String> qrange(Object key, int begin, int limit) {
try {
return req(Cmd.qrange, bytes(key), Integer.toString(begin).getBytes(), Integer.toString(limit).getBytes())
.listString();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return null;
}
public int expire(Object key, int ttl) {
try {
return req(Cmd.expire, bytes(key), Integer.toString(ttl).getBytes()).asInt();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return 0;
}
public void close() throws IOException {
stream.close();
}
public int getbit(Object key, int offset) {
try {
return req(Cmd.getbit, bytes(key), Integer.toString(offset).getBytes()).asInt();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return 0;
}
public int setbit(Object key, int offset, byte on) {
try {
return req(Cmd.setbit, bytes(key), Integer.toString(offset).getBytes(),
on == 1 ? "1".getBytes() : "0".getBytes()).asInt();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return 0;
}
public int countbit(Object key, int start, int size) {
try {
return req(Cmd.countbit, bytes(key), Integer.toString(start).getBytes(), Integer.toString(size).getBytes())
.asInt();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return 0;
}
public int strlen(Object key, int start, int size) {
if (size < 0)
size = 2000000000;
try {
return req(Cmd.strlen, bytes(key), Integer.toString(start).getBytes(), Integer.toString(size).getBytes())
.asInt();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return 0;
}
public int strlen(Object key) {
try {
return req(Cmd.strlen, bytes(key)).asInt();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return 0;
}
public List<KeyValue> hrlist(Object key, Object hkey, int limit) {
try {
return req(Cmd.hrlist, bytes(key), bytes(hkey), Integer.toString(limit).getBytes()).asKeyValues();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return null;
}
public boolean zrlist(Object zkey_start, Object zkey_end, int limit) {
try {
return req(Cmd.zrlist, bytes(zkey_start), bytes(zkey_end), Integer.toString(limit).getBytes()).ok();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return false;
}
public List<String> qrlist(Object key_start, Object key_end, int limit) {
try {
return req(Cmd.qrlist, bytes(key_start), bytes(key_end), Integer.toString(limit).getBytes()).listString();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return null;
}
public boolean auth(String passwd) {
try {
return req(Cmd.auth, bytes(passwd)).ok();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return false;
}
public int qtrimBack(Object key, int size) {
try {
return req(Cmd.qtrim_back, bytes(key), Integer.toString(size).getBytes()).asInt();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return 0;
}
public int qtrimFront(Object key, int size) {
try {
return req(Cmd.qtrim_front, bytes(key), Integer.toString(size).getBytes()).asInt();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return 0;
}
// -----------------------------------
public long dbsize() {
try {
return req(Cmd.dbsize).asLong();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return 0;
}
public boolean qset(Object key, int index, Object value) {
try {
return req(Cmd.qset, bytes(key), Integer.toString(index).getBytes(), bytes(value)).ok();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return false;
}
public List<String> qpopBack(Object key, int limit) {
try {
return req(Cmd.qpop_back, bytes(key), Integer.toString(limit).getBytes()).listString();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return null;
}
public List<String> qpopFront(Object key, int limit) {
try {
return req(Cmd.qpop_front, bytes(key), Integer.toString(limit).getBytes()).listString();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return null;
}
// ------------------------
public List<String> rkeys(Object start, Object end, int limit) {
try {
return req(Cmd.rkeys, bytes(start), bytes(end), Integer.toString(limit).getBytes()).listString();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return null;
}
public String version() {
try {
return req(Cmd.version).asString();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
;
}
return null;
}
public boolean ping() {
try {
return req(Cmd.ping).ok();
} catch (Exception e) {
LOGGER.error("ssdb操作发生异常", e);
}
return false;
}
}
| 24.816425 | 112 | 0.615145 |
48a87b0f722d1143d142510706bb70a417c227f6 | 379 | /**
* Copyright (c) 2017 European Organisation for Nuclear Research (CERN), All Rights Reserved.
*/
package io.molr.gui.fx;
import io.molr.mole.remote.conf.LocalhostRestClientConfiguration;
import org.springframework.context.annotation.Import;
@Import({MolrGuiBaseConfiguration.class, LocalhostRestClientConfiguration.class})
public class LocalhostMolrGuiConfiguration {
}
| 27.071429 | 93 | 0.812665 |
c27e9bd98cf9f40deee13f1cd25f60b672e6a7c1 | 2,643 | package com.yapp.yongyong.infra.fcm;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.auth.oauth2.GoogleCredentials;
import com.yapp.yongyong.infra.fcm.FcmMessage.Message;
import com.yapp.yongyong.infra.fcm.FcmMessage.Notification;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.List;
@Slf4j
@RequiredArgsConstructor
@Service
public class FcmService {
private final String API_URL = "https://fcm.googleapis.com/v1/projects/yongyong-db0f9/messages:send";
private final ObjectMapper objectMapper;
public void sendMessageTo(String targetToken, String title, String body, String image) throws IOException {
String message = makeMessage(targetToken, title, body, image);
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = RequestBody.create(message, MediaType.get("application/json; charset=utf-8"));
Request request = new Request.Builder()
.url(API_URL)
.post(requestBody)
.addHeader(HttpHeaders.AUTHORIZATION, "Bearer " + getAccessToken())
.addHeader(HttpHeaders.CONTENT_TYPE, "application/json; UTF-8")
.build();
Response response = client.newCall(request)
.execute();
log.info("FCM 발신: ", response.body().toString());
}
private String makeMessage(String targetToken, String title, String body, String image) throws JsonProcessingException {
FcmMessage fcmMessage = FcmMessage.builder()
.message(Message.builder()
.token(targetToken)
.notification(Notification.builder().title(title).body(body).image(image).build())
.build())
.validate_only(false)
.build();
return objectMapper.writeValueAsString(fcmMessage);
}
private String getAccessToken() throws IOException {
String firebaseConfigPath = "/home/ec2-user/app/firebase-adminsdk.json";
GoogleCredentials googleCredentials = GoogleCredentials.fromStream(new ClassPathResource(firebaseConfigPath).getInputStream())
.createScoped(List.of("https://www.googleapis.com/auth/cloud-platform"));
googleCredentials.refreshIfExpired();
return googleCredentials.getAccessToken().getTokenValue();
}
}
| 40.661538 | 134 | 0.698449 |
5216c3649e298ad56e53025a6caff36c475a927a | 4,168 | /*
* Copyright 2016 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @author tags. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.keycloak.testsuite.admin.client;
import java.util.List;
import org.junit.Rule;
import org.junit.Test;
import org.keycloak.admin.client.resource.ClientResource;
import org.keycloak.events.admin.OperationType;
import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.testsuite.util.AdminEventPaths;
import org.keycloak.testsuite.util.AssertAdminEvents;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/**
*
* @author Stan Silvert [email protected] (C) 2016 Red Hat Inc.
*/
public class ClientTest extends AbstractClientTest {
public static void assertEqualClients(ClientRepresentation expected, ClientRepresentation actual) {
assertEquals(expected.getClientId(), actual.getClientId());
assertEquals(expected.getName(), actual.getName());
assertEquals(expected.getDescription(), actual.getDescription());
assertEquals(expected.getBaseUrl(), actual.getBaseUrl());
assertTrue(expected.getRedirectUris().containsAll(actual.getRedirectUris()));
assertTrue(expected.getWebOrigins().containsAll(actual.getWebOrigins()));
assertEquals(expected.getRegisteredNodes(), actual.getRegisteredNodes());
}
@Test
public void testCreateClient() {
createOidcClient("foo");
ClientRepresentation found = findClientRepresentation("foo");
assertEquals("foo", found.getName());
}
@Test
public void testDeleteClient() {
String clientDbId = createOidcClient("deleteMe");
ClientResource clientRsc = findClientResource("deleteMe");
assertNotNull(clientRsc);
clientRsc.remove();
assertNull(findClientResource("deleteMe"));
assertAdminEvents.assertEvent(getRealmId(), OperationType.DELETE, AdminEventPaths.clientResourcePath(clientDbId));
}
@Test
public void testUpdateClient() {
createOidcClient("updateMe");
ClientRepresentation clientRep = findClientRepresentation("updateMe");
assertEquals("updateMe", clientRep.getName());
clientRep.setName("iWasUpdated");
findClientResource("updateMe").update(clientRep);
ClientRepresentation updatedClient = findClientRepresentation("iWasUpdated");
assertNotNull(updatedClient);
assertEquals("updateMe", updatedClient.getClientId());
assertEquals("iWasUpdated", updatedClient.getName());
// Assert admin event
ClientRepresentation expectedClientRep = new ClientRepresentation();
expectedClientRep.setClientId("updateMe");
expectedClientRep.setName("iWasUpdated");
assertAdminEvents.assertEvent(getRealmId(), OperationType.UPDATE, AdminEventPaths.clientResourcePath(clientRep.getId()), expectedClientRep);
}
@Test
public void testGetAllClients() {
List<ClientRepresentation> allClients = testRealmResource().clients().findAll();
assertNotNull(allClients);
assertFalse(allClients.isEmpty());
}
@Test
public void getClientByIdTest() {
createOidcClient("byidclient");
ClientRepresentation rep = findClientRepresentation("byidclient");
ClientRepresentation gotById = testRealmResource().clients().get(rep.getId()).toRepresentation();
assertEqualClients(rep, gotById);
}
}
| 38.238532 | 148 | 0.731286 |
935c63f36a5b3128fc8e70e0ffe25d69d794f300 | 3,079 | /*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.execution;
import com.intellij.openapi.util.io.FileUtilRt;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import java.util.List;
public class CommandLineUtil {
private static final char SPECIAL_QUOTE = '\uEFEF';
private static final String WIN_SHELL_SPECIALS = "&<>()@^|";
public static @NotNull String specialQuote(@NotNull String parameter) {
return quote(parameter, SPECIAL_QUOTE);
}
public static @NotNull List<String> toCommandLine(@NotNull List<String> command) {
assert command.size() > 0;
return toCommandLine(command.get(0), command.subList(1, command.size()));
}
public static @NotNull List<String> toCommandLine(@NotNull String command, @NotNull List<String> parameters) {
return toCommandLine(command, parameters, Platform.current());
}
// please keep an implementation in sync with [junit-rt] ProcessBuilder.createProcess()
public static @NotNull List<String> toCommandLine(@NotNull String command, @NotNull List<String> parameters, @NotNull Platform platform) {
List<String> commandLine = ContainerUtil.newArrayListWithExpectedSize(parameters.size() + 1);
commandLine.add(FileUtilRt.toSystemDependentName(command, platform.fileSeparator));
boolean isWindows = platform == Platform.WINDOWS;
boolean winShell = isWindows &&
("cmd".equalsIgnoreCase(command) || "cmd.exe".equalsIgnoreCase(command)) &&
parameters.size() > 1 && "/c".equalsIgnoreCase(parameters.get(0));
for (String parameter : parameters) {
if (isWindows) {
if (parameter.contains("\"")) {
parameter = StringUtil.replace(parameter, "\"", "\\\"");
}
else if (parameter.length() == 0) {
parameter = "\"\"";
}
}
if (winShell && StringUtil.containsAnyChar(parameter, WIN_SHELL_SPECIALS)) {
parameter = quote(parameter, SPECIAL_QUOTE);
}
if (isQuoted(parameter, SPECIAL_QUOTE)) {
parameter = quote(parameter.substring(1, parameter.length() - 1), '"');
}
commandLine.add(parameter);
}
return commandLine;
}
private static String quote(String s, char ch) {
return !isQuoted(s, ch) ? ch + s + ch : s;
}
private static boolean isQuoted(String s, char ch) {
return s.length() >= 2 && s.charAt(0) == ch && s.charAt(s.length() - 1) == ch;
}
}
| 36.223529 | 140 | 0.686262 |
86b25ec65a9698b7bba9a6978d61e900bb9aad91 | 1,505 | package me.ningsk.mediascanlibrary.widget.cropper.nocropper;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.Rect;
public class ImageInfo {
private Matrix baseMatrix;
private Bitmap bitmap;
private int degree;
private Matrix drawMatrix;
private float mScaleFocusX;
private float mScaleFocusY;
private Matrix mSuppMatrix;
private String path;
private Rect showRect;
public ImageInfo(String path, Rect showRect, Matrix drawMatrix, Matrix suppMatrix, float scaleFocusX, float scaleFocusY, Matrix baseMatrix) {
this.path = path;
this.showRect = new Rect(showRect);
this.drawMatrix = new Matrix(drawMatrix);
this.mSuppMatrix = new Matrix(suppMatrix);
this.mScaleFocusX = scaleFocusX;
this.mScaleFocusY = scaleFocusY;
this.baseMatrix = baseMatrix;
}
public Matrix getBaseMatrix() {
return baseMatrix;
}
public int getDegree() {
return degree;
}
public Matrix getDrawMatrix() {
return drawMatrix;
}
public String getPath() {
return path;
}
public float getScaleFocusX() {
return mScaleFocusX;
}
public float getScaleFocusY() {
return mScaleFocusY;
}
public Rect getShowRect() {
return showRect;
}
public Matrix getSuppMatrix() {
return mSuppMatrix;
}
public void setDegree(int degree) {
this.degree = degree;
}
}
| 22.462687 | 145 | 0.657807 |
c93500ca9a3f74c96051f203f267c0745639de0c | 1,561 | /*
* This file is subject to the terms and conditions outlined in the file 'LICENSE' (hint: it's MIT); this file is located in the root directory near the README.md which you should also read.
*
* This file is part of the 'Adama' project which is a programming language and document store for board games; however, it can be so much more.
*
* See http://www.adama-lang.org/ for more information.
*
* (c) 2020 - 2022 by Jeffrey M. Barber (http://jeffrey.io)
*/
package org.adamalang.common;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
/** helpful toolss for Jackson JSON library */
public class Json {
public static final JsonMapper MAPPER = new JsonMapper();
public static ObjectNode newJsonObject() {
return MAPPER.createObjectNode();
}
public static ObjectNode parseJsonObject(final String json) {
try {
return parseJsonObjectThrows(json);
} catch (final Exception jpe) {
throw new RuntimeException(jpe);
}
}
public static ObjectNode parseJsonObjectThrows(final String json) throws Exception {
final var node = MAPPER.readTree(json);
if (node instanceof ObjectNode) {
return (ObjectNode) node;
}
throw new Exception("given json is not an ObjectNode at root");
}
public static String readString(ObjectNode tree, String field) {
JsonNode node = tree.get(field);
if (node == null || node.isNull()) {
return null;
}
return node.textValue();
}
}
| 32.520833 | 190 | 0.712364 |
846f874585075e0064408d29af80dd17e4165416 | 11,968 | /*
* Copyright 2017 Axway Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.axway.ats.config;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URL;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.axway.ats.config.exceptions.ConfigSourceDoesNotExistException;
import com.axway.ats.config.exceptions.ConfigurationException;
import com.axway.ats.config.exceptions.NoSuchPropertyException;
/**
* The configuration repository is a single holder for settings which are used by the ATS framework
* or user components. These settings are in the form of key-value pairs.
*
* This is a two layer repository.
* The lower layer keeps settings loaded from some configuration files, some of settings can be overridden when a new
* configuration file is loaded. It is intended to hold long living settings - usually for the span of a whole run,
* so they are called "permanent".
* The higher layer keeps settings provided by the user in the test. It is intended to hold short living
* settings - usually for the span of a single test, so they are called "temporary".
*
* ATS is using this functionality to configure its components and our users can also use it to override the default
* ATS components' settings.
*/
public class ConfigurationRepository {
//the logger instance
private static final Logger log = LogManager.getLogger(ConfigurationRepository.class);
//the singleton instance
private static final ConfigurationRepository instance;
// this is intended to be a short living resource, when we search for properties we will search here first
private ConfigurationResource tempResource;
// this is intended to be a long living resource,
// we will search here if the properties are not present in the short living resource
private ConfigurationResource permResource;
// this memory is used just to assure that the new configuration is correct
private ConfigurationResource permResourceBackup;
static {
// create the instance
instance = new ConfigurationRepository();
}
/**
* Constructor
*/
private ConfigurationRepository() {
//init the repository for the first time
initialize();
}
/**
* Get the instance of the configuration repository
*
* @return the instance of the configuration repository
*/
public static synchronized ConfigurationRepository getInstance() {
return instance;
}
/**
* Initialize the repository - clean all existing configuration resources
*/
void initialize() {
tempResource = new ConfigurationResource();
permResource = new ConfigurationResource();
permResourceBackup = new ConfigurationResource();
}
/**
* Register a regular configuration file from the classpath.
* These settings will be added to the permanent resources.
*
* @param filePath the configuration resource to add
* @param overrideExistProperties whether existing properties will be overridden
*/
void registerConfigFileFromClassPath(
String filePath,
boolean overrideExistProperties ) {
URL configFileURL = ConfigurationRepository.class.getResource(filePath);
if (configFileURL == null) {
throw new ConfigSourceDoesNotExistException(filePath);
}
InputStream fileStream = ConfigurationRepository.class.getResourceAsStream(filePath);
ConfigurationResource newPermResource = createConfigurationResourceFromStream(fileStream,
configFileURL.getFile());
assignTheNewPermResource(newPermResource, overrideExistProperties);
}
/**
* Register a regular configuration file.
* These settings will be added to the permanent resourcse.
*
* @param filePath the configuration resource to add
*/
void registerConfigFile(
String filePath ) {
File configFile = new File(filePath);
ConfigurationResource newPermResource = null;
try {
newPermResource = createConfigurationResourceFromStream(new FileInputStream(configFile),
configFile.getAbsolutePath());
} catch (FileNotFoundException e) {
throw new ConfigSourceDoesNotExistException(filePath);
}
assignTheNewPermResource(newPermResource, true);
}
private void assignTheNewPermResource(
ConfigurationResource newPermResource,
boolean overrideExistProperties ) {
// backup the current resource
copyProperties(permResource, permResourceBackup, true);
// set the new resource
copyProperties(newPermResource, permResource, overrideExistProperties);
// if exception is thrown while the new settings are loaded - we will revert back the previous assignments
}
/**
* Get a property from the repository.
* All resources will be queried according to their order and the first matching property will be returned
*
* @param name name of the property
* @return the value of the property
*/
String getProperty(
String name ) {
String value = null;
//look for the first property that matches from the temporary resources
value = tempResource.getProperty(name);
if (value != null) {
if (log.isTraceEnabled()) {
log.trace("Returning property '" + name + "' with value '" + value);
}
return value;
}
//the property is not found in the temporary resources, now look for it in the permanent resources
value = permResource.getProperty(name);
if (value != null) {
if (log.isTraceEnabled()) {
log.trace("Returning property '" + name + "' with value '" + value);
}
return value;
}
//we didn't find the property
throw new NoSuchPropertyException(name);
}
/**
* Get a property from the repository.
* If there is no such property no exception will be thrown, instead it will return the default value
*
* @param name name of the property
* @param defaultValue the default property value
* @return the value of the property
*/
String getProperty(
String name,
String defaultValue ) {
try {
return getProperty(name);
} catch (NoSuchPropertyException nspe) {
//we didn't find the property, use its default value
return defaultValue;
}
}
/**
* Get a property from the repository.
* If there is no such property no exception will be thrown, instead it will return null
*
* @param name name of the property
* @return the value of the property
*/
String getOptionalProperty(
String name ) {
try {
return getProperty(name);
} catch (NoSuchPropertyException nspe) {
return null;
}
}
/**
* Get a set of properties that match a certain prefix. All available
* configuration resources will be queried for matching properties
*
* @param prefix the prefix to look for
* @return map of all properties that match this prefix
*/
Map<String, String> getProperties(
String prefix ) {
Map<String, String> matchingTempProperties = tempResource.getProperties(prefix);
if (!matchingTempProperties.isEmpty()) {
return matchingTempProperties;
} else {
return permResource.getProperties(prefix);
}
}
/**
* Set a property in the temporary configuration resource. If this property
* already exists, it will be overridden.
*
* Usually it is call before the execution of a test or the first test in a class.
*
* @param name the name of the property
* @param value the value of the property
*/
void setTempProperty(
String name,
String value ) {
tempResource.setProperty(name, value);
}
/**
* Clear all temporary properties.
* Usually it is call after the execution of a test or the last test in a class.
*/
void clearTempResources() {
tempResource = new ConfigurationResource();
}
/**
* We call it if there is a problem while applying the new permanent configuration.
*/
void rollBackNewPermConfiguration() {
permResource = permResourceBackup;
}
private void copyProperties(
ConfigurationResource from,
ConfigurationResource to,
boolean overrideExistProperties ) {
for (Map.Entry<Object, Object> property : from.getProperties()) {
String key = (String) property.getKey();
String value = (String) property.getValue();
if (value != null) {
value = value.trim();
}
if (to.getProperty(key) != null) {
if (overrideExistProperties) {
to.setProperty(key, value);
}
} else {
to.setProperty(key, value);
}
}
}
/**
* Create a new configuration resource based on a given configuration file
*
* @param configFile the configuration file
* @return a config resource based on the file type
*/
private ConfigurationResource createConfigurationResourceFromStream(
InputStream resourceStream,
String resourceIdentifier ) {
ConfigurationResource configResource;
if (resourceIdentifier.endsWith(".xml")) {
configResource = new ConfigurationResource();
configResource.loadFromXmlFile(resourceStream, resourceIdentifier);
return configResource;
} else if (resourceIdentifier.endsWith(".properties")) {
configResource = new ConfigurationResource();
configResource.loadFromPropertiesFile(resourceStream, resourceIdentifier);
return configResource;
} else {
throw new ConfigurationException("Not supported file extension. We expect either 'xml' or 'properties': "
+ resourceIdentifier);
}
}
}
| 37.167702 | 119 | 0.603359 |
19d3184466394f0e0df03ca6263683f116f1b2ef | 5,304 | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package libcore.java.nio.file;
import junit.framework.TestCase;
import java.io.IOException;
import java.nio.file.FileSystemException;
import java.nio.file.NotLinkException;
import libcore.libcore.util.SerializationTester;
public class NotLinkExceptionTest extends TestCase {
public void test_constructor$String() {
NotLinkException exception = new NotLinkException("file");
assertEquals("file", exception.getFile());
assertNull(exception.getOtherFile());
assertNull(exception.getReason());
assertTrue(exception instanceof FileSystemException);
}
public void test_constructor$String$String$String() {
NotLinkException exception = new NotLinkException("file", "otherFile", "reason");
assertEquals("file", exception.getFile());
assertEquals("otherFile", exception.getOtherFile());
assertEquals("reason", exception.getReason());
}
public void test_serialization() throws IOException, ClassNotFoundException {
String hex = "ACED00057372001E6A6176612E6E696F2E66696C652E4E6F744C696E6B457863657074696F6EF"
+ "A9B37CB53A0387B020000787200216A6176612E6E696F2E66696C652E46696C6553797374656D457"
+ "863657074696F6ED598F27876D360FC0200024C000466696C657400124C6A6176612F6C616E672F5"
+ "37472696E673B4C00056F7468657271007E0002787200136A6176612E696F2E494F4578636570746"
+ "96F6E6C8073646525F0AB020000787200136A6176612E6C616E672E457863657074696F6ED0FD1F3"
+ "E1A3B1CC4020000787200136A6176612E6C616E672E5468726F7761626C65D5C635273977B8CB030"
+ "0044C000563617573657400154C6A6176612F6C616E672F5468726F7761626C653B4C000D6465746"
+ "1696C4D65737361676571007E00025B000A737461636B547261636574001E5B4C6A6176612F6C616"
+ "E672F537461636B5472616365456C656D656E743B4C0014737570707265737365644578636570746"
+ "96F6E737400104C6A6176612F7574696C2F4C6973743B787071007E0009740006726561736F6E757"
+ "2001E5B4C6A6176612E6C616E672E537461636B5472616365456C656D656E743B02462A3C3CFD223"
+ "90200007870000000097372001B6A6176612E6C616E672E537461636B5472616365456C656D656E7"
+ "46109C59A2636DD8502000449000A6C696E654E756D6265724C000E6465636C6172696E67436C617"
+ "37371007E00024C000866696C654E616D6571007E00024C000A6D6574686F644E616D6571007E000"
+ "278700000002C74002A6C6962636F72652E6A6176612E6E696F2E66696C652E4E6F744C696E6B457"
+ "863657074696F6E546573747400194E6F744C696E6B457863657074696F6E546573742E6A6176617"
+ "40012746573745F73657269616C697A6174696F6E7371007E000DFFFFFFFE7400186A6176612E6C6"
+ "16E672E7265666C6563742E4D6574686F6474000B4D6574686F642E6A617661740006696E766F6B6"
+ "57371007E000D000000F9740028766F6761722E7461726765742E6A756E69742E4A756E697433245"
+ "66F6761724A556E69745465737474000B4A756E6974332E6A61766174000372756E7371007E000D0"
+ "0000063740020766F6761722E7461726765742E6A756E69742E4A556E697452756E6E65722431740"
+ "0104A556E697452756E6E65722E6A61766174000463616C6C7371007E000D0000005C740020766F6"
+ "761722E7461726765742E6A756E69742E4A556E697452756E6E657224317400104A556E697452756"
+ "E6E65722E6A61766174000463616C6C7371007E000D000000ED74001F6A6176612E7574696C2E636"
+ "F6E63757272656E742E4675747572655461736B74000F4675747572655461736B2E6A61766174000"
+ "372756E7371007E000D0000046D7400276A6176612E7574696C2E636F6E63757272656E742E54687"
+ "2656164506F6F6C4578656375746F72740017546872656164506F6F6C4578656375746F722E6A617"
+ "66174000972756E576F726B65727371007E000D0000025F74002E6A6176612E7574696C2E636F6E6"
+ "3757272656E742E546872656164506F6F6C4578656375746F7224576F726B6572740017546872656"
+ "164506F6F6C4578656375746F722E6A61766174000372756E7371007E000D000002F97400106A617"
+ "6612E6C616E672E54687265616474000B5468726561642E6A61766174000372756E7372001F6A617"
+ "6612E7574696C2E436F6C6C656374696F6E7324456D7074794C6973747AB817B43CA79EDE0200007"
+ "8707874000466696C657400096F7468657246696C65";
NotLinkException exception = (NotLinkException) SerializationTester.deserializeHex(hex);
String hex1 = SerializationTester.serializeHex(exception).toString();
assertEquals(hex, hex1);
assertEquals("file", exception.getFile());
assertEquals("otherFile", exception.getOtherFile());
assertEquals("reason", exception.getReason());
}
}
| 61.674419 | 100 | 0.76678 |
abb57158177b8a506c5f70df3f2e426c3c5722ad | 1,707 | package com.infoworks.lab.rest.breaker;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
public class HttpResponse implements AutoCloseable {
private CircuitBreaker.Status status;
private Integer code;
private String payload;
@Override
public void close() throws Exception {
//TODO
}
public HttpResponse() {
this(HttpURLConnection.HTTP_NOT_FOUND);
}
public HttpResponse(Integer code) {
this.setCode(code);
}
public CircuitBreaker.Status getStatus() {
return status;
}
public void setStatus(CircuitBreaker.Status status) {
this.status = status;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
this.status = (code == HttpURLConnection.HTTP_OK) ? CircuitBreaker.Status.CLOSED : CircuitBreaker.Status.OPEN;
}
public String getPayload() {
return payload;
}
public void setPayload(String payload) {
this.payload = payload;
}
public void setPayload(InputStream payload) {
if (payload == null) return;
try (BufferedReader in = new BufferedReader(
new InputStreamReader(payload))){
//
String inputLine;
StringBuffer response = new StringBuffer();
//
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
setPayload(response.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 25.102941 | 118 | 0.616286 |
353eafc442d45c3c15d956d3f07a715563e421c8 | 5,197 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pinotdruidbenchmark;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Arrays;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
/**
* Test single query response time for Pinot.
*/
public class PinotResponseTime {
private PinotResponseTime() {
}
private static final byte[] BYTE_BUFFER = new byte[4096];
public static void main(String[] args)
throws Exception {
if (args.length != 4 && args.length != 5) {
System.err.println(
"4 or 5 arguments required: QUERY_DIR, RESOURCE_URL, WARM_UP_ROUNDS, TEST_ROUNDS, RESULT_DIR (optional).");
return;
}
File queryDir = new File(args[0]);
String resourceUrl = args[1];
int warmUpRounds = Integer.parseInt(args[2]);
int testRounds = Integer.parseInt(args[3]);
File resultDir;
if (args.length == 4) {
resultDir = null;
} else {
resultDir = new File(args[4]);
if (!resultDir.exists()) {
if (!resultDir.mkdirs()) {
throw new RuntimeException("Failed to create result directory: " + resultDir);
}
}
}
File[] queryFiles = queryDir.listFiles();
assert queryFiles != null;
Arrays.sort(queryFiles);
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost(resourceUrl);
for (File queryFile : queryFiles) {
String query = new BufferedReader(new FileReader(queryFile)).readLine();
httpPost.setEntity(new StringEntity("{\"pql\":\"" + query + "\"}"));
System.out.println("--------------------------------------------------------------------------------");
System.out.println("Running query: " + query);
System.out.println("--------------------------------------------------------------------------------");
// Warm-up Rounds
System.out.println("Run " + warmUpRounds + " times to warm up...");
for (int i = 0; i < warmUpRounds; i++) {
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
httpResponse.close();
System.out.print('*');
}
System.out.println();
// Test Rounds
System.out.println("Run " + testRounds + " times to get response time statistics...");
long[] responseTimes = new long[testRounds];
long totalResponseTime = 0L;
for (int i = 0; i < testRounds; i++) {
long startTime = System.currentTimeMillis();
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
httpResponse.close();
long responseTime = System.currentTimeMillis() - startTime;
responseTimes[i] = responseTime;
totalResponseTime += responseTime;
System.out.print(responseTime + "ms ");
}
System.out.println();
// Store result.
if (resultDir != null) {
File resultFile = new File(resultDir, queryFile.getName() + ".result");
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
try (
BufferedInputStream bufferedInputStream = new BufferedInputStream(httpResponse.getEntity().getContent());
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(resultFile))
) {
int length;
while ((length = bufferedInputStream.read(BYTE_BUFFER)) > 0) {
bufferedWriter.write(new String(BYTE_BUFFER, 0, length));
}
}
httpResponse.close();
}
// Process response times.
double averageResponseTime = (double) totalResponseTime / testRounds;
double temp = 0;
for (long responseTime : responseTimes) {
temp += (responseTime - averageResponseTime) * (responseTime - averageResponseTime);
}
double standardDeviation = Math.sqrt(temp / testRounds);
System.out.println("Average response time: " + averageResponseTime + "ms");
System.out.println("Standard deviation: " + standardDeviation);
}
}
}
}
| 38.213235 | 119 | 0.635174 |
ba6bee60067d68e7d32f42678333027fed6f809f | 184 | package codecup2022.stopcriterion;
public interface StopCriterion {
public abstract void started();
public abstract boolean shouldStop();
public abstract String name();
}
| 23 | 41 | 0.755435 |
b6e6ab9bf9b1742b6c4a02e4506b6f4561a8cd9d | 2,923 | package engine;
import conventionalsearch.Engine;
import conventionalsearch.State;
import conventionalsearch.StateProblem;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
/**
* Title: BreadthFirstEngine
* Description: Class BreadthFirstEngine implements a Breadth-first search
strategy which can be used with any instance of StateProblem.
* @author Nazareno Aguirre
*/
public class BreadthFirstEngine<S extends State, P extends StateProblem<S>> implements Engine<S,P> {
/**
* Internal representation of the StateProblem.
*/
private P sp;
/**
* path stores the path to the goal.
*/
private List<S> path;
/**
* Constructor for class BreadthFirstEngine.
* @pre. true.
* @post. Lists path is initialized as empty.
*/
public BreadthFirstEngine() {
path = new LinkedList<S>();
}
/**
* Constructor for class BreadthFirstEngine.
* @param sp is the search problem associated with the engine
being created.
* @pre. p!=null.
* @post. A reference to p is stored in field problem.
*/
public BreadthFirstEngine(P sp) {
this.sp = sp;
path = new LinkedList<S>();
}
/**
* Starts the search for successful states for problem, following a
* breadth-first strategy.
* @return true iff a successful state is found.
* @pre. problem!=null.
* @post. the search is performed, the path in list path, and true is returned iff a
successfull state is found.
*/
public S performSearch() {
Queue<S> queue = new LinkedList<S>();
queue.add(sp.initialState());
boolean found = false;
S goal = null;
while (!queue.isEmpty() && !found) {
S current = queue.poll();
if (current.isSuccess()) {
found = true;
goal = current;
} else {
List<S> succs = sp.getSuccessors(current);
for (S s: succs) {
queue.add(s);
}
}
}
if (!(goal == null)) {
S s = goal;
while (!(s == null)) {
path.add(0,s);
s = (S)s.getParent();
}
}
return goal;
}
/**
* Returns the path to a previously calculated successful state for problem.
* @return the list of nodes corresponding to the path from the root to
the successful node.
* @pre. performSearch() has been executed and finished successfully.
* @post. the path to the found goal node is returned.
*/
public List<S> getPath() {
return path;
} // end of getPath()
/**
* Reports information regarding a previously executed search.
* @pre. performSearch() has been executed and finished.
* @post. A report regarding the search is printed to standard output.
This report consists of .
*/
public void report() {
System.out.println("Length of path to state when search finished: " + path.size());
} // end of report()
}
| 26.572727 | 101 | 0.625727 |
39f8ae706fc114741364e82b441919af4852a5a6 | 1,323 | import java.util.*;
import java.io.*;
public class Euler22
{
public static void main(String args[])throws IOException
{
BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(b.readLine()),i,l,j;
int[] a = new int[n];
Arrays.fill(a,0);
String[] name = new String[n];
for(i=0;i<n;i++) name[i] = b.readLine();
Arrays.sort(name);
for(i=0;i<n;i++)
{
l=name[i].length();
for(j=0;j<l;j++)
{
a[i]+=name[i].charAt(j)-'A'+1;
}
a[i]=a[i]*(i+1);
}
int q = Integer.parseInt(b.readLine());
String que;
for(i=1;i<=q;i++)
{
que = b.readLine();
System.out.println(a[binarySearch(name, que)]);
}
}
public static int binarySearch(String[] a,String k)
{
int l=0,u=a.length-1,m=(l+u)/2,f=0;
while(l<=u)
{
m=(l+u)/2;
if(a[m].compareTo(k)>0)
u=m-1;
if(a[m].compareTo(k)<0)
l=m+1;
if(a[m].compareTo(k)==0)
{
f=1;
break;
}
}
if(f==1)
return m;
return -1;
}
} | 24.962264 | 80 | 0.417234 |
4185af18fccdf5d4abfb10b6d3648127fb4ccabf | 4,255 | package edu.mtu.reactor;
import java.util.List;
import java.util.Set;
import edu.mtu.compound.Molecule;
import edu.mtu.parser.ChemicalDto;
import edu.mtu.primitives.Entity;
import edu.mtu.primitives.Sparse3DLattice;
import edu.mtu.reaction.ReactionRegistry;
import edu.mtu.simulation.SimulationProperties;
import edu.mtu.util.FnvHash;
import net.sourceforge.sizeof.SizeOf;
import sim.util.Bag;
/**
* The reactor is the container that the experiment takes place in. As a
* simplification, the container is assumed to be square.
*
* Note that in the interest of performance, this code ignores the need
* to check state. It assumes that methods will only be called when they
* should be called.
*/
public class Reactor {
public final static double AvogadrosNumber = 6.02214085774E23;
public final static double MemoryOverhead = 0.9;
private static Reactor instance;
private int moleculeCount;
private long moleculeSize;
public final int[] dimensions;
public Sparse3DLattice grid;
/**
* Constructor.
*/
private Reactor(int[] dimensions) {
this.dimensions = dimensions;
}
/**
* Get an instance of the reactor.
*/
public static Reactor getInstance() {
return instance;
}
/**
* Calculate the dimensions (assuming cubic) of the reactor based upon the list of compounds provided.
*
* @param compounds parsed out when the experimental inputs are loaded.
* @return The dimensions a long a single axis in nanometers (nm).
*/
public static int calculateSize(List<ChemicalDto> compounds, long molecules) {
double result = Math.cbrt(molecules / (8e-5 * AvogadrosNumber)); // m
result = Math.ceil(result * Math.pow(10, 9)); // nm
return (int)result;
}
public Molecule getFirst(String formula) {
int hash = FnvHash.fnv1a32(formula);
return (Molecule)grid.getFirstEntity(hash);
}
public int[] getLocation(Molecule molecule) {
return grid.getObjectLocation(molecule);
}
/**
* Get the maximum number of molecules that can be allocated.
*/
public long getMaximumMolecules() {
return moleculeCount;
}
/**
* Returns all molecules present in the reactor.
*/
public Molecule[] getMolecules() {
Set<Entity> objects = grid.getAllObjects();
Molecule[] array = new Molecule[objects.size()];
objects.toArray(array);
return array;
}
/**
* Get the molecules at the same location as the given molecule.
*/
public Bag getMolecules(Molecule molecule) {
return grid.getColocatedObjects(molecule);
}
/**
* Return the estimated total size of a molecule, in bytes.
*/
public long getMoleculeSize() {
return moleculeSize;
}
/**
* Initialize the reactor with the given dimensions.
*
* @param compounds a list of compounds that are going to be fed into the reactor.
*/
public static void initalize(List<ChemicalDto> compounds) {
try {
// Note the size and number of initial molecules
long size = SizeOf.deepSizeOf(new Molecule("CH3COCH2OH", false)) * 3;
int count = SimulationProperties.getInstance().getInitialMolecules();
// Use the maximum molecule count to estimate a size for the reactor
int dimension = calculateSize(compounds, count);
// Create the reactor, set relevant values, and return
int[] hashes = ReactionRegistry.getInstance().getEntityHashList();
if (hashes == null) {
throw new IllegalAccessError("Entity hash table is null.");
}
instance = new Reactor(new int[] { dimension, dimension, dimension });
instance.grid = Sparse3DLattice.create3DLattice(count, hashes);
instance.moleculeCount = count;
instance.moleculeSize = size;
} catch (IllegalArgumentException ex) {
System.err.println("Fatal Error while initalizing the Reactor");
System.err.println(ex.getMessage());
System.exit(-1);
}
}
/**
* Insert the given molecule at the given location.
*/
public void insert(Molecule molecule, int[] location) {
grid.setObjectLocation(molecule, location);
}
/**
* Remove the molecule from the grid.
*/
public void remove(Molecule molecule) {
grid.remove(molecule);
}
}
| 28.366667 | 105 | 0.688602 |
26ca43339560c06ffbb4fef3df263c92db771581 | 3,442 | /*
*
* * Copyright 2014 Orient Technologies LTD (info(at)orientechnologies.com)
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
* * For more information: http://www.orientechnologies.com
*
*/
package com.orientechnologies.orient.core;
import java.util.Hashtable;
import java.util.Map.Entry;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import sun.misc.Signal;
import sun.misc.SignalHandler;
@SuppressWarnings("restriction")
public class OSignalHandler implements SignalHandler {
private Hashtable<Signal, SignalHandler> redefinedHandlers = new Hashtable(4);
public OSignalHandler() {
}
public void listenTo(final String name, final SignalHandler iListener) {
Signal signal = new Signal(name);
SignalHandler redefinedHandler = Signal.handle(signal, iListener);
if (redefinedHandler != null) {
redefinedHandlers.put(signal, redefinedHandler);
}
}
public void handle(Signal signal) {
OLogManager.instance().warn(this, "Received signal: %s", signal);
final String s = signal.toString().trim();
if (Orient.instance().isSelfManagedShutdown()
&& (s.equals("SIGKILL") || s.equals("SIGHUP") || s.equals("SIGINT") || s.equals("SIGTERM"))) {
Orient.instance().shutdown();
System.exit(1);
} else if (s.equals("SIGTRAP")) {
System.out.println();
OGlobalConfiguration.dumpConfiguration(System.out);
System.out.println();
Orient.instance().getProfiler().dump(System.out);
System.out.println();
System.out.println(Orient.instance().getProfiler().threadDump());
} else {
SignalHandler redefinedHandler = redefinedHandlers.get(signal);
if (redefinedHandler != null) {
redefinedHandler.handle(signal);
}
}
}
public void installDefaultSignals() {
installDefaultSignals(this);
}
public void installDefaultSignals(final SignalHandler iListener) {
// listenTo("HUP", iListener); // DISABLED HUB BECAUSE ON WINDOWS IT'S USED INTERNALLY AND CAUSED JVM KILL
// listenTo("KILL",iListener);
try {
listenTo("INT", iListener);
} catch (IllegalArgumentException e) {
// NOT AVAILABLE
}
try {
listenTo("TERM", iListener);
} catch (IllegalArgumentException e) {
// NOT AVAILABLE
}
try {
listenTo("TRAP", iListener);
} catch (IllegalArgumentException e) {
// NOT AVAILABLE
}
}
public void cancel() {
for (Entry<Signal, SignalHandler> entry : redefinedHandlers.entrySet()) {
try {
// re-install the original handler we replaced
Signal.handle(entry.getKey(), entry.getValue());
} catch (IllegalStateException e) {
// not expected as we were able to redefine it earlier, but just in case
}
}
redefinedHandlers.clear();
}
}
| 31.87037 | 110 | 0.676351 |
a81cb2c8d10fd478c7007ce3be373bd8029a2864 | 93 | package com.alibaba.alink.server.domain;
public enum NodeType {
SOURCE,
FUNCTION,
SINK
}
| 11.625 | 40 | 0.752688 |
416f6156e51e6a2ab790503fe5f646fe1ff2de48 | 2,303 | package ulcambridge.foundations.viewer.pdf;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.layout.element.Div;
import com.itextpdf.layout.element.Image;
import org.json.JSONObject;
import ulcambridge.foundations.viewer.model.Item;
import javax.servlet.http.HttpServletResponse;
import java.net.MalformedURLException;
public class SinglePagePdf {
private final String IIIFImageServer;
private final BasicTemplatePdf basicTemplatePdf;
/**
* This is used to generate a PDF with a large image of a single page and document metadata.
*
* These classes could be moved out to a separate service.
*/
public SinglePagePdf(String IIIFImageServer, String baseURL,
String headerText, int[] pdfColour,
String[] urlsForFontZips, String defaultFont, String cachePath) throws MalformedURLException {
this.IIIFImageServer = IIIFImageServer;
this.basicTemplatePdf = new BasicTemplatePdf(baseURL, headerText, pdfColour,
urlsForFontZips, defaultFont, cachePath);
}
public void writePdf(Item item, String pageInput, HttpServletResponse response) {
try {
int page = Integer.parseInt(pageInput);
int numPages = item.getJSON().getJSONArray("pages").length();
if (page < 1) { page = 1; }
if (page > numPages) { page = numPages; }
JSONObject pageJSON = item.getJSON().getJSONArray("pages").getJSONObject(page - 1);
String iiifImageURL = pageJSON.getString("IIIFImageURL");
String imageURL = IIIFImageServer + iiifImageURL + "/full/,1000/0/default.jpg";
if (pageJSON.getInt("imageWidth") > pageJSON.getInt("imageHeight")) {
imageURL = IIIFImageServer + iiifImageURL + "/full/1000,/0/default.jpg";
}
Image image = new Image(ImageDataFactory.create(imageURL));
Div div = new Div();
div.add(image.setMargins(10f, 0f, 30f, 0f)
.scaleToFit(PageSize.A4.getWidth() - 60f, PageSize.A4.getHeight() - 220f));
basicTemplatePdf.writePdf(item, div, response, false);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 38.383333 | 119 | 0.657838 |
ddd95e14e3f63de09090ab4d1b0a01cd68961d9b | 83 | package infrastructure.database;
public class Database implements IDatasource {
} | 16.6 | 46 | 0.831325 |
5259ab5a88df7bff9b8cc5b5ee2fe7693253ae34 | 326 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/datastore/v1/datastore.proto
package com.google.datastore.v1;
public interface RollbackResponseOrBuilder extends
// @@protoc_insertion_point(interface_extends:google.datastore.v1.RollbackResponse)
com.google.protobuf.MessageOrBuilder {
}
| 32.6 | 87 | 0.800613 |
c144f11723be9a65422496d13c82347324047845 | 11,005 | package com.holypasta.trainer.util;
import java.util.Arrays;
import java.util.List;
/**
* Created by q1bot on 17.04.2015.
*/
public class DictionaryGenerator {
private int levelId;
public DictionaryGenerator(int levelId) {
this.levelId = levelId;
}
public List<String> getDictionaryItems() {
switch (levelId) {
case 0:
return getItems1();
case 1:
return getItems2();
case 2:
return getItems3();
case 3:
return getItems4();
case 4:
return getItems5();
case 5:
return getItems6();
case 6:
return getItems7();
case 7:
return getItems8();
default:
return null;
}
}
public List<String> getItems1() {
String[] itemsArray = new String[]{
"I - я",
"you - вы, ты",
"he - он",
"she - она",
"we - мы",
"they - они",
"love - любить",
"live - жить",
"work - работать",
"open - открыть",
"close - закрыть",
"see (saw) - видеть",
"come (came) - приходить",
"go (went) - идти",
"know (knew) - знать",
"think (thought) - думать",
"start - начать",
"finish - закончить"
};
return Arrays.asList(itemsArray);
}
public List<String> getItems2() {
String[] itemsArray = new String[]{
"me - меня, мне",
"you - вас, вам",
"him - его, ему",
"her - её, ей",
"us - нас, нам",
"them - им",
"ask - просить, спрашивать",
"answer - отвечать",
"give (gave) - давать",
"take (took) - брать",
"help - помогать",
"hope - надеяться",
"speak (spoke) - говорить",
"travel - путешествовать",
"think (thought) - думать",
"work - работать",
"come (came) - приходить",
"live - жить",
"what - что? какой?",
"who - кто?",
"where - где? куда?",
"when - когда?",
"why - почему? зачем?",
"how - как?",
"in - в (внутри)",
"to - к, куда, к чему, к кому",
"from - откуда, от кого, из чего"
};
return Arrays.asList(itemsArray);
}
public List<String> getItems3() {
String[] itemsArray = new String[]{
"my - моё, мой",
"your - твоё, твой",
"his - его",
"her - её",
"our - наше, наш",
"their - их"
};
return Arrays.asList(itemsArray);
}
public List<String> getItems4() {
String[] itemsArray = new String[]{
"study - изучать",
"art history - историю искуства",
"work - работать",
"museum - музей",
"PR-manager - пиарменеджер",
"writer - писатель",
"actor - актёр, актриса",
"theater - театре",
"hello, hi - привет",
"good morning - доброе утро (до 12:00)",
"good afternoon - добрый день (до 18:00)",
"good evening - добрый вечер",
"good night - доброй ночи / спокойной ночи",
"thank you, thanks - спасибо",
"please - пожалуйста (сделай, помоги)",
"welcome - пожалуйста (в ответ)",
"nice to meet you - приятно познакомиться",
"I'm sorry - приношу извинения",
"I apologize for coming late - приношу извинение за опоздание",
"I regret - я сожалею",
"excuse me - извините (обратить внимание)",
"forgive me - простите (переспросить)",
"goodbye, bye - до свиданья"
};
return Arrays.asList(itemsArray);
}
public List<String> getItems5() {
String[] itemsArray = new String[]{
"old - старый",
"older - старше",
"oldest - старейший",
"beautiful - красивый",
"more beautiful - красивее",
"most beautiful - самый красивый",
"young - молодой",
"younger - моложе",
"youngest - самый молодой",
"short - короткий",
"shorter - короче",
"shortest - самый короткий",
"big - большой",
"bigger - больше",
"biggest - самый большой",
"good - хороший",
"better - лучше",
"best - лучший",
"bad - плахой",
"worse - хуже",
"worst - наихудший",
"yesterday - вчера",
"today - сегодня",
"tomorrow - завтра",
"now - сейчас",
"in - через",
"ago - назад",
"day - день",
"week - неделя",
"month - месяц",
"year - год",
"Norway - Норвегия",
"Moscow - Москва",
"Kiev - Киев",
"home - дом",
"at - в (время)",
"on - в (день недели)",
"in - в (месяц, время года)",
"before - до",
"after - после",
"Monday - понедельник",
"Tuesday - вторник",
"Wednesday - среда",
"Thursday - четверг",
"Friday - пятница",
"Saturday - суббота",
"Sunday - воскресенье",
"January - январь",
"February - февраль",
"March - март",
"April - апрель",
"May - май",
"June - июнь",
"July - июль",
"August - август",
"September - сентябрь",
"October - октябрь",
"November - ноябрь",
"December - декабрь",
"last - прошлый",
"this - текущий",
"next - следующий",
"winter - зима",
"spring - весна",
"summer - лето",
"autumn - осень",
"jewelry designer - ювелирный дизайнер"
};
return Arrays.asList(itemsArray);
}
public List<String> getItems6() {
String[] itemsArray = new String[]{
"time - время",
"dollar - доллар",
"rouble - рубль",
"money - деньги",
"hour - час",
"love - любовь",
"day - день",
"people - люди",
"have, has (had) - иметь (с местоимениями he, she - has)",
"much - много (нельзя посчитать)",
"many - много (можно посчитать)",
"everybody - все, всякий, каждый",
"somebody - кто-то, кто-нибудь, кое-кто",
"nobody - никто",
"everything - всё",
"something - что-нибудь, что-то, кое-что",
"nothing - ничего",
"everywhere - везде, всюду",
"somewhere - где-то, куда-то, где-нибудь",
"nowhere - нигде, никуда",
"always - всегда",
"sometimes - иногда",
"never - никогда"
};
return Arrays.asList(itemsArray);
}
public List<String> getItems7() {
String[] itemsArray = new String[]{
"try - пытаться, стараться, примерять",
"buy (bought) - покупать",
"shirt - рубашка",
"pay (paid) - платить, оплачивать",
"cash - наличные",
"credit card - кредитная карта",
"play - играть",
"film - фильм",
"change - менять, обменивать, переодеваться",
"choose (chose) - выбирать",
"dress - платье",
"car - машина, автомобиль",
"drive - ехать, водить",
"slowly - медленно",
"hurry - спешить",
"cinema - кино",
"dinner - обед",
"watch TV - смотреть телевизор",
"football - футбол",
"mail - почта",
"together - вместе",
"right now - прямо сейчас"
};
return Arrays.asList(itemsArray);
}
public List<String> getItems8() {
String[] itemsArray = new String[]{
"try - пытаться, стараться, примерять",
"buy (bought) - покупать",
"in - в (внутри)",
"to - к, в (по направлению к)",
"from - от",
"under - под",
"on - на, по (над)",
"at - у чего-то",
"over - над",
"between - между",
"with - с",
"without - без",
"for - для",
"about - о, около",
"measure - измерять",
"whim - каприз",
"sew - шить",
"woman - женщина",
"women - женщины",
"man - мужчина, человек",
"men - мужчины",
"people - люди, народ",
"human - человеческий",
"mankind - человечество",
"society - общество",
// "# дополнительные слова из предложений",
"Moscow - Москва",
"ground - земля",
"table - стол",
"school - школа",
"home - дом",
"tell - рассказывать",
"father - отец",
"minute - минута",
"meet - встретить",
"o'clock - час (время дня)",
"go up - подниматься",
"go down - спускаться",
"go back - возвращаться",
"go away - прочь, в сторону",
"go in - заходить",
"go out - выходить",
"look up - посмотреть вверх",
"look down - посмотреть вниз",
"look back - оглянуться",
"look away - отвернуться",
"look in - заглянуть",
"look out - выглянуть",
"take up - поднять",
"take down - опустить",
"take away - отобрать",
"take in - внести",
"take out - вынести",
"market - рынок",
"make (made) - делать",
"shirt - рубашка",
"hope - надеяться"
};
return Arrays.asList(itemsArray);
}
}
| 32.272727 | 79 | 0.408723 |
fec54094a0d7edbb8e9a6dda43b62ee15d23a9d3 | 509 | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2013-2014 sagyf Yang. The Four Group.
*/
package goja.lang;
import static java.lang.String.format;
@SuppressWarnings("serial")
public class InvokingException extends RuntimeException {
public InvokingException(String format, Object... args) {
super(format(format, args));
}
public InvokingException(String msg, Throwable cause) {
super(String.format(msg, cause.getMessage()), cause);
}
}
| 23.136364 | 61 | 0.701375 |
c023a75545fc5b8c11a6d03e04d5cfa90743e82b | 16,696 | package org.firstinspires.ftc.teamcode.util;
/**
* Created by tycho on 2/18/2017, but borrowed some of this from Team Fixit's VortexUtils. All hail Team Fixit!!!!!
*/
import android.graphics.Bitmap;
import android.graphics.Canvas;
//import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
//import com.vuforia.CameraCalibration; //to do revert after https://github.com/FIRST-Tech-Challenge/FtcRobotController/issues/26
import org.firstinspires.ftc.robotcore.internal.camera.calibration.CameraCalibration;
//import org.firstinspires.ftc.robotcore.internal.vuforia.
import com.vuforia.Image;
import com.vuforia.Matrix34F;
import com.vuforia.Tool;
import com.vuforia.Vec3F;
import org.firstinspires.ftc.robotcore.external.matrices.OpenGLMatrix;
import org.firstinspires.ftc.robotcore.external.matrices.VectorF;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaLocalizer;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaTrackableDefaultListener;
import org.firstinspires.ftc.teamcode.vision.colorblob.ColorBlobDetector;
import org.firstinspires.ftc.teamcode.RC;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.imgproc.Imgproc;
import org.opencv.imgproc.Moments;
import org.opencv.android.Utils;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class VisionUtils {
public final static int NOT_VISIBLE = 0;
public final static int BEACON_BLUE_RED = 1;//blue left, red right
public final static int BEACON_RED_BLUE = 2;//blue right, red left
public final static int BEACON_ALL_BLUE = 3;
public final static int BEACON_NO_BLUE = 4;
public final static int OBJECT_BLUE = 1;
public final static int OBJECT_RED = 2;
//hsv blue beacon range colours
//DON'T CHANGE THESE NUMBERS
public final static Scalar BEACON_BLUE_LOW = new Scalar(108, 0, 220);
public final static Scalar BEACON_BLUE_HIGH = new Scalar(178, 255, 255);
public final static Scalar OTHER_BLUE_LOW = new Scalar(105, 120, 110);
public final static Scalar OTHER_BLUE_HIGH = new Scalar(185, 255, 255);
public final static Scalar OTHER_RED_LOW = new Scalar(222, 101, 192);
public final static Scalar OTHER_RED_HIGH = new Scalar(47, 251, 255);
public final static Scalar RED_CRYPTO = new Scalar(47, 251, 255);
public static Mat bitmapToMat (Bitmap bit, int cvType) {
Mat newMat = new Mat(bit.getHeight(), bit.getWidth(), cvType);
Utils.bitmapToMat(bit, newMat);
return newMat;
}
public static Mat applyMask(Mat img, Scalar low, Scalar high) {
Mat mask = new Mat(img.size(), CvType.CV_8UC3);
if (high.val[0] < low.val[0]) {
Scalar lowMed = new Scalar(255, high.val[1], high.val[2]);
Scalar medHigh = new Scalar(0, low.val[1], low.val[2]);
Mat maskLow = new Mat(img.size(), CvType.CV_8UC3);
Mat maskHigh = new Mat(img.size(), CvType.CV_8UC3);
Core.inRange(img, low, lowMed, maskLow);
Core.inRange(img, medHigh, high, maskHigh);
Core.bitwise_or(maskLow, maskHigh, mask);
} else {
Core.inRange(img, low, high, mask);
}//else
return mask;
}
public static int waitForBeaconConfig(Image img, VuforiaTrackableDefaultListener beacon, CameraCalibration camCal, long timeOut) {
int config = NOT_VISIBLE;
long beginTime = System.currentTimeMillis();
while (config == NOT_VISIBLE && System.currentTimeMillis() - beginTime < timeOut && RC.l.opModeIsActive()) {
config = getJewelConfig(img, beacon, camCal);
RC.l.idle();
}//while
return config;
}
public static int getJewelConfig(Bitmap bm) {
if (bm != null) {
//turning the corner pixel coordinates into a proper bounding box
Mat image = bitmapToMat(bm, CvType.CV_8UC3);
//filtering out non-beacon-blue colours in HSV colour space
Imgproc.cvtColor(image, image, Imgproc.COLOR_RGB2HSV_FULL);
//get filtered mask
//if pixel is within acceptable blue-beacon-colour range, it's changed to white.
//Otherwise, it's turned to black
Mat mask = new Mat();
Core.inRange(image, BEACON_BLUE_LOW, BEACON_BLUE_HIGH, mask);
Moments mmnts = Imgproc.moments(mask, true);
//calculating centroid of the resulting binary mask via image moments
Log.i("CentroidX", "" + ((mmnts.get_m10() / mmnts.get_m00())));
Log.i("CentroidY", "" + ((mmnts.get_m01() / mmnts.get_m00())));
//checking if blue either takes up the majority of the image (which means the beacon is all blue)
//or if there's barely any blue in the image (which means the beacon is all red or off)
// if (mmnts.get_m00() / mask.total() > 0.8) {
// return VortexUtils.BEACON_ALL_BLUE;
// } else if (mmnts.get_m00() / mask.total() < 0.1) {
// return VortexUtils.BEACON_NO_BLUE;
// }//elseif
//Note: for some reason, we end up with a image that is rotated 90 degrees
//if centroid is in the bottom half of the image, the blue beacon is on the left
//if the centroid is in the top half, the blue beacon is on the right
if ((mmnts.get_m01() / mmnts.get_m00()) < image.rows() / 2) {
return VisionUtils.BEACON_RED_BLUE;
} else {
return VisionUtils.BEACON_BLUE_RED;
}//else
}//if
return VisionUtils.NOT_VISIBLE;
}//getJewelConfig
public static double getColumnPos(Image img, int columnId, ColorBlobDetector detector) {
Mat overlay;
overlay = new Mat();
List <BlobStats> blobStats;
//getting camera image...
Bitmap bm = Bitmap.createBitmap(img.getWidth(), img.getHeight(), Bitmap.Config.RGB_565);
bm.copyPixelsFromBuffer(img.getPixels());
Mat eye = bitmapToMat(bm, CvType.CV_8UC3);
detector.process(eye, overlay);
blobStats = detector.getBlobStats();
double largest =0;
int x = 0;
//need some magic here to group the blobs into columns and find the error to the desired column
//this is a very basic example where we find the x coordinate of the largest blob's centroid
Iterator<BlobStats> each = blobStats.iterator();
while (each.hasNext()) {
BlobStats stat = each.next();
if (stat.area > largest)
{
largest = stat.area;
x = stat.x;
}
}
return ErrorPixToDeg(x);
}
public static int getJewelConfig(Image img, VuforiaTrackableDefaultListener codex, CameraCalibration camCalVuforia) {
OpenGLMatrix pose = codex.getRawPose();
com.vuforia.CameraCalibration camCal = com.vuforia.CameraDevice.getInstance().getCameraCalibration();
if (pose != null && img != null && img.getPixels() != null) {
Matrix34F rawPose = new Matrix34F();
float[] poseData = Arrays.copyOfRange(pose.transposed().getData(), 0, 12);
rawPose.setData(poseData);
//calculating pixel coordinates of beacon corners
float[][] corners = new float[4][2];
//todo uncomment after there is a fix for issue 26 https://github.com/FIRST-Tech-Challenge/FtcRobotController/issues/26
corners[0] = Tool.projectPoint(camCal, rawPose, new Vec3F(-127, -0, 0)).getData(); //upper left of beacon
corners[1] = Tool.projectPoint(camCal, rawPose, new Vec3F(-254, -0, 0)).getData(); //upper right of beacon
corners[2] = Tool.projectPoint(camCal, rawPose, new Vec3F(-254, -254, 0)).getData(); //lower right of beacon
corners[3] = Tool.projectPoint(camCal, rawPose, new Vec3F(-127, -254, 0)).getData(); //lower left of beacon
// corners[0] = Tool.projectPoint(camCal, rawPose, new Vec3F(-127, 276, 0)).getData(); //upper left of beacon
// corners[1] = Tool.projectPoint(camCal, rawPose, new Vec3F(127, 276, 0)).getData(); //upper right of beacon
// corners[2] = Tool.projectPoint(camCal, rawPose, new Vec3F(127, -92, 0)).getData(); //lower right of beacon
// corners[3] = Tool.projectPoint(camCal, rawPose, new Vec3F(-127, -92, 0)).getData(); //lower left of beacon
//getting camera image...
Bitmap bm = Bitmap.createBitmap(img.getWidth(), img.getHeight(), Bitmap.Config.RGB_565);
bm.copyPixelsFromBuffer(img.getPixels());
//turning the corner pixel coordinates into a proper bounding box
Mat crop = bitmapToMat(bm, CvType.CV_8UC3);
float x = Math.min(Math.min(corners[1][0], corners[3][0]), Math.min(corners[0][0], corners[2][0]));
float y = Math.min(Math.min(corners[1][1], corners[3][1]), Math.min(corners[0][1], corners[2][1]));
float width = Math.max(Math.abs(corners[0][0] - corners[2][0]), Math.abs(corners[1][0] - corners[3][0]));
float height = Math.max(Math.abs(corners[0][1] - corners[2][1]), Math.abs(corners[1][1] - corners[3][1]));
//make sure our bounding box doesn't go outside of the image
//OpenCV doesn't like that...
x = Math.max(x, 0);
y = Math.max(y, 0);
width = (x + width > crop.cols())? crop.cols() - x : width;
height = (y + height > crop.rows())? crop.rows() - y : height;
//cropping bounding box out of camera image
final Mat cropped = new Mat(crop, new Rect((int) x, (int) y, (int) width, (int) height));
//filtering out non-beacon-blue colours in HSV colour space
Imgproc.cvtColor(cropped, cropped, Imgproc.COLOR_RGB2HSV_FULL);
//get filtered mask
//if pixel is within acceptable blue-beacon-colour range, it's changed to white.
//Otherwise, it's turned to black
Mat mask = new Mat();
Core.inRange(cropped, BEACON_BLUE_LOW, BEACON_BLUE_HIGH, mask);
Moments mmnts = Imgproc.moments(mask, true);
//calculating centroid of the resulting binary mask via image moments
Log.i("CentroidX", "" + ((mmnts.get_m10() / mmnts.get_m00())));
Log.i("CentroidY", "" + ((mmnts.get_m01() / mmnts.get_m00())));
//checking if blue either takes up the majority of the image (which means the beacon is all blue)
//or if there's barely any blue in the image (which means the beacon is all red or off)
// if (mmnts.get_m00() / mask.total() > 0.8) {
// return VortexUtils.BEACON_ALL_BLUE;
// } else if (mmnts.get_m00() / mask.total() < 0.1) {
// return VortexUtils.BEACON_NO_BLUE;
// }//elseif
//Note: for some reason, we end up with a image that is rotated 90 degrees
//if centroid is in the bottom half of the image, the blue beacon is on the left
//if the centroid is in the top half, the blue beacon is on the right
if ((mmnts.get_m10() / mmnts.get_m00()) < cropped.cols() / 2) {
return VisionUtils.BEACON_RED_BLUE;
} else {
return VisionUtils.BEACON_BLUE_RED;
}//else
}//if
return VisionUtils.NOT_VISIBLE;
}//getJewelConfig
Bitmap getBitmapFromView(View v)
{
Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.draw(c);
return b;
}
public static int isBlueOrRed(Image img) {
if (img != null && img.getPixels() != null) {
Bitmap bm = Bitmap.createBitmap(img.getWidth(), img.getHeight(), Bitmap.Config.RGB_565);
bm.copyPixelsFromBuffer(img.getPixels());
//turning the corner pixel coordinates into a proper bounding box
Mat analyse = bitmapToMat(bm, CvType.CV_8UC3);
Mat maskBlue = applyMask(analyse.clone(), OTHER_BLUE_LOW, OTHER_BLUE_HIGH);
Mat maskRed = applyMask(analyse.clone(), OTHER_RED_LOW, OTHER_RED_HIGH);
if (Imgproc.moments(maskBlue).get_m00() > Imgproc.moments(maskRed).get_m00()) {
return OBJECT_BLUE;
} else {
return OBJECT_RED;
}//else
}//if
return NOT_VISIBLE;
}//isBlueOrRed
//@Nullable
public static Image getImageFromFrame(VuforiaLocalizer.CloseableFrame frame, int format) {
long numImgs = frame.getNumImages();
for (int i = 0; i < numImgs; i++) {
if (frame.getImage(i).getFormat() == format) {
return frame.getImage(i);
}//if
}//for
return null;
}
/* public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame, ColorBlobDetector pipeline) {
Mat mRgba = inputFrame.rgba();
if (true) {
pipeline.process(mRgba);
List<MatOfPoint> contours = pipeline.getContours();
Log.e(TAG, "Contours count: " + contours.size());
Imgproc.drawContours(mRgba, contours, -1, CONTOUR_COLOR, 3);
//get the centroid (center of mass) and area for each contour
List<Moments> mu = new ArrayList<Moments>(contours.size());
maxContour=0;
blobWidth = 0;
blobHeight = 0;
blobBox = null;
for (int i = 0; i < contours.size(); i++) {
mu.add(i, Imgproc.moments(contours.get(i), false));
Moments p = mu.get(i);
int x = (int) (p.get_m10() / p.get_m00());
int y = (int) (p.get_m01() / p.get_m00());
//Core.circle(mRgba, new Point(x, y), 4, new Scalar(255,49,0,255));
Core.circle(mRgba, new Point(x, y), 5, CONTOUR_COLOR, -1);
double area = Imgproc.contourArea(contours.get(i));
if (area > maxContour)
{
maxContour=area;
blobx=x;
bloby=y;
blobBox=Imgproc.boundingRect(contours.get(i));
blobWidth=blobBox.width;
blobHeight = blobBox.height;
}
}
if (targetContour == -1 && maxContour > 0 )
{
targetContour = maxContour; //new target size, thus distance to object
}
Mat colorLabel = mRgba.submat(4, 68, 4, 68);
colorLabel.setTo(mBlobColorRgba);
Mat spectrumLabel = mRgba.submat(4, 4 + mSpectrum.rows(), 70, 70 + mSpectrum.cols());
mSpectrum.copyTo(spectrumLabel);
}
return mRgba;
}*/
//this assumes the horizontal axis is the y-axis since the phone is vertical
//robot angle is relative to "parallel with the beacon wall"
public static VectorF navOffWall(VectorF trans, double robotAngle, VectorF offWall){
return new VectorF(
(float) (trans.get(0) - offWall.get(0) * Math.sin(Math.toRadians(robotAngle)) - offWall.get(2) * Math.cos(Math.toRadians(robotAngle))),
trans.get(1) + offWall.get(1),
(float) (-trans.get(2) + offWall.get(0) * Math.cos(Math.toRadians(robotAngle)) - offWall.get(2) * Math.sin(Math.toRadians(robotAngle)))
);
}
public static VectorF navOffWall2(VectorF trans, double robotAngle, VectorF offWall){
double theta = Math.toDegrees(Math.atan2(offWall.get(0), offWall.get(2)));
return new VectorF(
(float) (trans.get(0) - offWall.get(0) * Math.sin(Math.toRadians(robotAngle)) - offWall.get(2) * Math.cos(Math.toRadians(robotAngle))),
trans.get(1),
(float) (-trans.get(2) + offWall.get(0) * Math.cos(Math.toRadians(robotAngle)) - offWall.get(2) * Math.sin(Math.toRadians(robotAngle)))
);
}
private static double ErrorPixToDeg(int blobx){
int ViewWidth = 800;
int ScreenCenterPix;
int ErrorPix;
double PixPerDegree;
double errorDegrees;
ScreenCenterPix = ViewWidth/2;
ErrorPix = ScreenCenterPix - blobx;
PixPerDegree = ViewWidth / 75; //FOV
errorDegrees = ErrorPix/PixPerDegree;
if (errorDegrees < 0) {
errorDegrees += 360;
}
return errorDegrees;
}
} | 40.524272 | 151 | 0.613141 |
233e6c3a744ddffef67376289fd424cebc64694b | 4,582 | package com.wu.admin.utils;
import com.wu.admin.pojo.auth.entity.MenuDO;
import com.wu.admin.pojo.auth.entity.RoleMenuDO;
import java.util.*;
/**
* Description : Created by intelliJ IDEA
* Author : wubo
* Date : 2017/10/12
* Time : 下午5:16
*/
public class MenuTreeUtil {
private List<MenuDO> nodes;
private List<RoleMenuDO> checknodes;
/**
* 创建一个新的实例 Tree.
*
* @param nodes 将树的所有节点都初始化进来。
*/
public MenuTreeUtil(List<MenuDO> nodes, List<RoleMenuDO> checknodes){
this.nodes = nodes;
this.checknodes = checknodes;
}
/**
* buildTree
* 描述: 创建树
* @return List<Map<String,Object>>
* @exception
* @since 1.0.0
*/
public List<Map<String, Object>> buildTree(){
List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
for(MenuDO node : nodes) {
//这里判断父节点,需要自己更改判断
if (Objects.equals(node.getParentId(), "0")) {
//System.out.println("node"+node.getMenuName());
Map<String, Object> map = buildTreeChildsMap(node);
list.add(map);
}
}
return list;
}
/**
* buildChilds
* 描述: 创建树下的节点。
* @param node
* @return List<Map<String,Object>>
* @exception
* @since 1.0.0
*/
private List<Map<String, Object>> buildTreeChilds(MenuDO node){
List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
List<MenuDO> childNodes = getChilds(node);
for(MenuDO childNode : childNodes){
//System.out.println("childNode"+childNode.getMenuName());
Map<String, Object> map = buildTreeChildsMap(childNode);
list.add(map);
}
return list;
}
/**
* buildChildMap
* 描述:生成Map节点
* @param childNode
* @return Map<String, Object>
*/
private Map<String, Object> buildTreeChildsMap(MenuDO childNode){
Map<String, Object> map = new HashMap<String, Object>();
Map<String, Object> stateMap = new HashMap<>();
stateMap.put("checked", false);
for(RoleMenuDO checknode : checknodes){
if(checknode.getMenuId().equals(childNode.getMenuId())){
stateMap.put("checked", true);
}
}
stateMap.put("disabled", false);
stateMap.put("expanded", false);
stateMap.put("selected", false);
map.put("id", childNode.getMenuId());
map.put("text", childNode.getMenuName());
map.put("url", childNode.getMenuUrl());
map.put("state", stateMap);
List<Map<String, Object>> childs = buildTreeChilds(childNode);
if(childs.isEmpty() || childs.size() == 0){
//map.put("state","open");
}else{
map.put("nodes", childs);
}
return map;
}
/**
* getChilds
* 描述: 获取子节点
* @param parentNode
* @return List<Resource>
* @exception
* @since 1.0.0
*/
public List<MenuDO> getChilds(MenuDO parentNode) {
List<MenuDO> childNodes = new ArrayList<MenuDO>();
for(MenuDO node : nodes){
// System.out.println(node.getParentId()+"-------"+parentNode.getMenuId());
if (Objects.equals(node.getParentId(), parentNode.getMenuId())) {
childNodes.add(node);
}
}
return childNodes;
}
/**
* buildTree
* 描述: 创建树
* @return List<Map<String,Object>>
* @exception
* @since 1.0.0
*/
public List<MenuDO> buildTreeGrid(){
List<MenuDO> list = new ArrayList<MenuDO>();
for(MenuDO node : nodes) {
//这里判断父节点,需要自己更改判断
if (Objects.equals(node.getParentId(), "0")) {
List<MenuDO> childs = buildTreeGridChilds(node);
node.setChildren(childs);
list.add(node);
}
}
return list;
}
/**
* buildChilds
* 描述: 创建树下的节点。
* @param node
* @return List<Map<String,Object>>
* @exception
* @since 1.0.0
*/
private List<MenuDO> buildTreeGridChilds(MenuDO node){
List<MenuDO> list = new ArrayList<MenuDO>();
List<MenuDO> childNodes = getChilds(node);
for(MenuDO childNode : childNodes){
//System.out.println("childNode"+childNode.getMenuName());
List<MenuDO> childs = buildTreeGridChilds(childNode);
childNode.setChildren(childs);
list.add(childNode);
}
return list;
}
}
| 27.27381 | 86 | 0.552597 |
9015517b9e8c8c9873ff06d05b5492f04161fe45 | 448 | public static void main(String[] args) {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new File("DomainModel.xml"));
Element ele = doc.getDocumentElement();
System.out.println(ele.getTagName());
} catch (Exception ex) {
ex.printStackTrace();
}
}
| 37.333333 | 78 | 0.582589 |
665574a9a661f300e66667b8209a7f1299d10ec3 | 393 | import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
public class IslandTest {
private Island island = new Island();
@Test
public void test_IslandTest() throws Exception {
int n = 4;
int[][] costs = {{0,1,1},{0,2,2},{1,2,5},{1,3,1},{2,3,8}};
int result = 4;
assertThat(island.makeBridge(n, costs)).isEqualTo(result);
}
} | 21.833333 | 66 | 0.597964 |
4e3e8442eacebc509ea9ae70fdc11219e82a3c8a | 398 | package main.utility.warframe.market.item;
public class WarframeItem {
String url_name;
String id;
String item_name;
String thumb;
public String getId() {
return id;
}
public String getUrl_name() {
return url_name;
}
public String getItem_name() {
return item_name;
}
public String getThumb() {
return thumb;
}
}
| 15.92 | 42 | 0.600503 |
ec73e0d3b449740fbed72356cb3f380af3aef4b8 | 7,284 | /**
* Copyright (c) 2009-2013, Lukas Eder, [email protected]
* Christopher Deckers, [email protected]
* All rights reserved.
*
* This software is licensed to you under the Apache License, Version 2.0
* (the "License"); You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* . Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* . Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* . Neither the name "jOOQ" nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.jooq.debug.console;
import java.awt.Color;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import org.jooq.debug.impl.Utils;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextAreaEditorKit;
import org.fife.ui.rsyntaxtextarea.RSyntaxUtilities;
import org.fife.ui.rsyntaxtextarea.Style;
import org.fife.ui.rsyntaxtextarea.SyntaxConstants;
import org.fife.ui.rsyntaxtextarea.SyntaxScheme;
import org.fife.ui.rsyntaxtextarea.Token;
/**
* @author Christopher Deckers
*/
@SuppressWarnings("serial")
public class SqlTextArea extends RSyntaxTextArea {
public SqlTextArea() {
setTabSize(2);
setTabsEmulated(true);
setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_SQL);
setMarkOccurrences(true);
setAnimateBracketMatching(false);
setAutoIndentEnabled(true);
setCurrentLineHighlightColor(new Color(232, 242, 254));
setMarkOccurrencesColor(new Color(220, 220, 220));
setMatchedBracketBGColor(null);
setMatchedBracketBorderColor(new Color(192, 192, 192));
getActionMap().put("copy", new RSyntaxTextAreaEditorKit.CopyAsRtfAction());
Font editorFont = UIManager.getFont("TextArea.font");
editorFont = new Font("Monospaced", editorFont.getStyle(), editorFont.getSize());
SyntaxScheme syntaxScheme = getSyntaxScheme();
syntaxScheme.setStyle(Token.SEPARATOR, new Style(new Color(200, 0, 0), null));
syntaxScheme.setStyle(Token.RESERVED_WORD, new Style(Color.BLUE, null, editorFont));
setFont(editorFont);
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
boolean isControlDown = e.isControlDown();
boolean isShiftDown = e.isShiftDown();
switch(e.getKeyCode()) {
case KeyEvent.VK_P:
if(isControlDown && isShiftDown) {
int position = RSyntaxUtilities.getMatchingBracketPosition(SqlTextArea.this, null).y;
if(position >= 0) {
setCaretPosition(position + 1);
}
}
break;
case KeyEvent.VK_F:
if(isControlDown && isShiftDown) {
formatSelection();
}
break;
}
}
});
}
@Override
public JPopupMenu getPopupMenu() {
boolean isEditable = isEditable();
JPopupMenu popupMenu = new JPopupMenu();
final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
JMenuItem copyClipboardMenuItem = new JMenuItem("Copy");
copyClipboardMenuItem.setEnabled(getSelectionStart() < getSelectionEnd());
copyClipboardMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
copyAsRtf();
}
});
popupMenu.add(copyClipboardMenuItem);
JMenuItem pasteClipboardMenuItem = new JMenuItem("Paste");
pasteClipboardMenuItem.setEnabled(false);
if(isEditable && clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor)) {
try {
final String data = (String)clipboard.getData(DataFlavor.stringFlavor);
if(data != null && data.length() > 0) {
pasteClipboardMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
replaceSelection(data);
}
});
pasteClipboardMenuItem.setEnabled(true);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
popupMenu.add(pasteClipboardMenuItem);
popupMenu.addSeparator();
JMenuItem formatMenuItem = new JMenuItem("Format");
formatMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, KeyEvent.CTRL_MASK | KeyEvent.SHIFT_MASK));
formatMenuItem.setEnabled(isEditable && getSelectionStart() < getSelectionEnd());
formatMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
formatSelection();
}
});
popupMenu.add(formatMenuItem);
if(popupMenu.getComponentCount() > 0) {
return popupMenu;
}
return null;
}
private void formatSelection() {
String text = getSelectedText();
String newText = Utils.getFormattedSql(text);
if(!Utils.equals(text, newText)) {
replaceSelection(newText);
}
}
}
| 42.596491 | 120 | 0.63413 |
ab413925e570b77b49979aae3065309e0b76b16b | 956 | package org.theeric.auth.user.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.theeric.auth.core.service.AbstractService;
import org.theeric.auth.user.model.UserSession;
import org.theeric.auth.user.repository.UserSessionDao;
@Service
public class UserSessionService extends AbstractService {
private UserSessionDao userSessionDao;
@Autowired
public void setUserSessionDao(UserSessionDao userSessionDao) {
this.userSessionDao = userSessionDao;
}
public Page<UserSession> list(Long userId, Pageable pageable) {
return userSessionDao.findAllByUserId(userId, pageable);
}
@Transactional
public void delete(Long id) {
userSessionDao.deleteById(id);
}
}
| 29.875 | 67 | 0.784519 |
d52f42e773166f583133a06404e112cf77d43729 | 3,430 | package me.lightdream.skybank.commands;
import me.lightdream.skybank.SkyBank;
import me.lightdream.skybank.utils.API;
import me.lightdream.skybank.utils.Language;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
public class TaxCommand extends BaseCommand{
public TaxCommand() {
forcePlayer = true;
commandName = "tax";
argLength = 0;
}
@Override
public boolean run() {
int tax = API.getTaxData(player.getUniqueId());
int size = API.getIslandSize(player.getUniqueId());
double taxValue = API.getTaxValue(player.getUniqueId());
double taxPrice = API.getTaxPrice(player.getUniqueId());
double overtaxValue = API.getPlayerOvertaxValue(player.getUniqueId());
double overtaxPrice = API.getPlayerOvertaxPrice(player.getUniqueId());
double totalPrice = overtaxPrice + taxPrice * tax;
if(size == 0){
API.sendColoredMessage(player, Language.size_0_island);
return true;
}
if(args.length == 1){
API.sendColoredMessage(player, Language.unpaid_taxes.replace("%tax%", String.valueOf(tax)));
API.sendColoredMessage(player, Language.island_size.replace("%size%", String.valueOf(size)));
API.sendColoredMessage(player, Language.tax_value.replace("%tax%", String.valueOf(taxValue)));
API.sendColoredMessage(player, Language.tax_price.replace("%tax%", String.valueOf(taxPrice * tax)));
API.sendColoredMessage(player, Language.overtax_percent.replace("%tax%", String.valueOf(overtaxValue)));
API.sendColoredMessage(player, Language.overtax_price.replace("%tax%", String.valueOf(overtaxPrice)));
API.sendColoredMessage(player, "");
API.sendColoredMessage(player, Language.total_price.replace("%tax%", String.valueOf(totalPrice)));
}
else if(args.length == 2){
if(args[1].equalsIgnoreCase("pay")){
payTax(player);
}
}
return true;
}
public static void payTax(Player player){
int tax = API.getTaxData(player.getUniqueId());
double taxPrice = API.getTaxPrice(player.getUniqueId());
double overtaxPrice = API.getPlayerOvertaxPrice(player.getUniqueId());
double totalPrice = overtaxPrice + taxPrice * tax;
double balance = API.getBalance(player.getUniqueId());
if(totalPrice <= 0){
API.sendColoredMessage(player, Language.something_went_wrong);
}
if(balance >= totalPrice){
balance -= totalPrice;
FileConfiguration data = API.loadPlayerDataFile(player.getUniqueId());
data.set("tax", SkyBank.data.getInt("tax"));
if(data.getBoolean("over-tax")){
API.getIsland(player.getUniqueId()).setProtectionRange(data.getInt("before-sanction-size"));
data.set("before-sanction-size", 0);
data.set("over-tax", false);
}
API.savePlayerDataFile(player.getUniqueId(), data);
API.removeBalance(player.getUniqueId(), balance);
API.sendColoredMessage(player, Language.paid_taxes);
API.logAction(API.processLogAction(player, String.valueOf(balance)));
}
else{
API.sendColoredMessage(player, Language.not_enough_money);
}
}
}
| 38.539326 | 116 | 0.641983 |
41364d4323693e3a07f789fb6b0b1d7cb3cebf87 | 1,247 | package com.ruoyi.project.system.mapper;
import java.util.List;
import java.util.Map;
import com.ruoyi.project.system.domain.SysOssRecord;
/**
* OSS上传Mapper接口
*
* @author sun
* @date 2020-04-27
*/
public interface SysOssRecordMapper {
/**
* 查询OSS上传
*
* @param id OSS上传ID
* @return OSS上传
*/
SysOssRecord selectSysOssRecordById(String id);
/**
* 查询OSS上传列表
*
* @param sysOssRecord OSS上传
* @return OSS上传集合
*/
List<SysOssRecord> selectSysOssRecordList(SysOssRecord sysOssRecord);
/**
* 查询OSS上传选项
*
* @return Map 集合
*/
List<Map<String, Object>> selectSysOssRecordOptions(SysOssRecord sysOssRecord);
/**
* 新增OSS上传
*
* @param sysOssRecord OSS上传
* @return 结果
*/
int insertSysOssRecord(SysOssRecord sysOssRecord);
/**
* 修改OSS上传
*
* @param sysOssRecord OSS上传
* @return 结果
*/
int updateSysOssRecord(SysOssRecord sysOssRecord);
/**
* 删除OSS上传
*
* @param id OSS上传ID
* @return 结果
*/
int deleteSysOssRecordById(String id);
/**
* 批量删除OSS上传
*
* @param ids 需要删除的数据ID
* @return 结果
*/
int deleteSysOssRecordByIds(String[] ids);
}
| 18.072464 | 83 | 0.596632 |
f72ae971375efedde31721a835f218b9779ec3a3 | 1,799 | /**
* Copyright 2011-2019 Asakusa Framework Team.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.asakusafw.windgate.stream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
/**
* Provides {@link InputStream}s.
* @since 0.2.4
*/
public abstract class InputStreamProvider implements Closeable {
/**
* Returns whether a next {@link InputStream} exists,
* and advances the current stream to the next one.
* Note that the {@link #openStream() current} stream should be closed by the client.
* @return {@code true} if the next {@link InputStream} exists, otherwise {@code false}.
* @throws IOException if failed to obtain next stream
*/
public abstract boolean next() throws IOException;
/**
* Returns the path about the current stream.
* @return the path
* @throws IllegalStateException if the current stream is not prepared
*/
public abstract String getCurrentPath();
/**
* Returns the current stream.
* @return the opened stream
* @throws IOException if failed to obtain the current stream
* @throws IllegalStateException if the current stream is not prepared
*/
public abstract CountingInputStream openStream() throws IOException;
}
| 34.596154 | 92 | 0.712618 |
acd527c3b0b7ea1043768b4454ceb011da2d2900 | 43,243 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*/
package com.microsoft.azure.management.sql.implementation;
import com.microsoft.azure.management.apigeneration.LangDefinition;
import com.microsoft.azure.management.resources.fluentcore.arm.Region;
import com.microsoft.azure.management.resources.fluentcore.arm.ResourceId;
import com.microsoft.azure.management.resources.fluentcore.arm.ResourceUtils;
import com.microsoft.azure.management.resources.fluentcore.arm.models.implementation.ExternalChildResourceImpl;
import com.microsoft.azure.management.resources.fluentcore.dag.FunctionalTaskItem;
import com.microsoft.azure.management.resources.fluentcore.dag.TaskGroup;
import com.microsoft.azure.management.resources.fluentcore.model.Creatable;
import com.microsoft.azure.management.resources.fluentcore.model.Indexable;
import com.microsoft.azure.management.sql.AuthenticationType;
import com.microsoft.azure.management.sql.CreateMode;
import com.microsoft.azure.management.sql.DatabaseEdition;
import com.microsoft.azure.management.sql.DatabaseMetric;
import com.microsoft.azure.management.sql.ImportRequest;
import com.microsoft.azure.management.sql.ReplicationLink;
import com.microsoft.azure.management.sql.RestorePoint;
import com.microsoft.azure.management.sql.SampleName;
import com.microsoft.azure.management.sql.ServiceObjectiveName;
import com.microsoft.azure.management.sql.ServiceTierAdvisor;
import com.microsoft.azure.management.sql.SqlDatabase;
import com.microsoft.azure.management.sql.SqlDatabaseAutomaticTuning;
import com.microsoft.azure.management.sql.SqlDatabaseBasicStorage;
import com.microsoft.azure.management.sql.SqlDatabaseMetric;
import com.microsoft.azure.management.sql.SqlDatabaseMetricDefinition;
import com.microsoft.azure.management.sql.SqlDatabaseOperations;
import com.microsoft.azure.management.sql.SqlDatabasePremiumServiceObjective;
import com.microsoft.azure.management.sql.SqlDatabasePremiumStorage;
import com.microsoft.azure.management.sql.SqlDatabaseStandardServiceObjective;
import com.microsoft.azure.management.sql.SqlDatabaseStandardStorage;
import com.microsoft.azure.management.sql.SqlDatabaseThreatDetectionPolicy;
import com.microsoft.azure.management.sql.SqlDatabaseUsageMetric;
import com.microsoft.azure.management.sql.SqlElasticPool;
import com.microsoft.azure.management.sql.SqlRestorableDroppedDatabase;
import com.microsoft.azure.management.sql.SqlServer;
import com.microsoft.azure.management.sql.SqlSyncGroupOperations;
import com.microsoft.azure.management.sql.SqlWarehouse;
import com.microsoft.azure.management.sql.StorageKeyType;
import com.microsoft.azure.management.sql.DatabaseUpdate;
import com.microsoft.azure.management.sql.TransparentDataEncryption;
import com.microsoft.azure.management.storage.StorageAccount;
import com.microsoft.azure.management.storage.StorageAccountKey;
import org.joda.time.DateTime;
import rx.Completable;
import rx.Observable;
import rx.functions.Func1;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
/**
* Implementation for SqlDatabase and its parent interfaces.
*/
@LangDefinition
class SqlDatabaseImpl
extends
ExternalChildResourceImpl<SqlDatabase, DatabaseInner, SqlServerImpl, SqlServer>
implements
SqlDatabase,
SqlDatabase.SqlDatabaseDefinition<SqlServer.DefinitionStages.WithCreate>,
SqlDatabase.DefinitionStages.WithExistingDatabaseAfterElasticPool<SqlServer.DefinitionStages.WithCreate>,
SqlDatabase.DefinitionStages.WithStorageKeyAfterElasticPool<SqlServer.DefinitionStages.WithCreate>,
SqlDatabase.DefinitionStages.WithAuthenticationAfterElasticPool<SqlServer.DefinitionStages.WithCreate>,
SqlDatabase.DefinitionStages.WithRestorePointDatabaseAfterElasticPool<SqlServer.DefinitionStages.WithCreate>,
SqlDatabase.Update,
SqlDatabaseOperations.DefinitionStages.WithExistingDatabaseAfterElasticPool,
SqlDatabaseOperations.DefinitionStages.WithStorageKeyAfterElasticPool,
SqlDatabaseOperations.DefinitionStages.WithAuthenticationAfterElasticPool,
SqlDatabaseOperations.DefinitionStages.WithRestorePointDatabaseAfterElasticPool,
SqlDatabaseOperations.DefinitionStages.WithCreateAfterElasticPoolOptions,
SqlDatabaseOperations.SqlDatabaseOperationsDefinition {
private SqlElasticPoolsAsExternalChildResourcesImpl sqlElasticPools;
protected SqlServerManager sqlServerManager;
protected String resourceGroupName;
protected String sqlServerName;
protected String sqlServerLocation;
private boolean isPatchUpdate;
private ImportRequest importRequestInner;
private SqlSyncGroupOperationsImpl syncGroups;
/**
* Creates an instance of external child resource in-memory.
*
* @param name the name of this external child resource
* @param parent reference to the parent of this external child resource
* @param innerObject reference to the inner object representing this external child resource
* @param sqlServerManager reference to the SQL server manager that accesses firewall rule operations
*/
SqlDatabaseImpl(String name, SqlServerImpl parent, DatabaseInner innerObject, SqlServerManager sqlServerManager) {
super(name, parent, innerObject);
Objects.requireNonNull(parent);
Objects.requireNonNull(sqlServerManager);
this.sqlServerManager = sqlServerManager;
this.resourceGroupName = parent.resourceGroupName();
this.sqlServerName = parent.name();
this.sqlServerLocation = parent.regionName();
this.sqlElasticPools = null;
this.isPatchUpdate = false;
this.importRequestInner = null;
}
/**
* Creates an instance of external child resource in-memory.
*
* @param resourceGroupName the resource group name
* @param sqlServerName the parent SQL server name
* @param sqlServerLocation the parent SQL server location
* @param name the name of this external child resource
* @param innerObject reference to the inner object representing this external child resource
* @param sqlServerManager reference to the SQL server manager that accesses firewall rule operations
*/
SqlDatabaseImpl(String resourceGroupName, String sqlServerName, String sqlServerLocation, String name, DatabaseInner innerObject, SqlServerManager sqlServerManager) {
super(name, null, innerObject);
Objects.requireNonNull(sqlServerManager);
this.sqlServerManager = sqlServerManager;
this.resourceGroupName = resourceGroupName;
this.sqlServerName = sqlServerName;
this.sqlServerLocation = sqlServerLocation;
this.sqlElasticPools = new SqlElasticPoolsAsExternalChildResourcesImpl(this.sqlServerManager, "SqlElasticPool");
this.isPatchUpdate = false;
this.importRequestInner = null;
}
/**
* Creates an instance of external child resource in-memory.
*
* @param parentSqlElasticPool the parent SqlElasticPool this database belongs to
* @param name the name of this external child resource
* @param innerObject reference to the inner object representing this external child resource
* @param sqlServerManager reference to the SQL server manager that accesses firewall rule operations
*/
SqlDatabaseImpl(TaskGroup.HasTaskGroup parentSqlElasticPool, String name, DatabaseInner innerObject, SqlServerManager sqlServerManager) {
super(name, null, innerObject);
Objects.requireNonNull(parentSqlElasticPool);
Objects.requireNonNull(sqlServerManager);
this.sqlServerManager = sqlServerManager;
this.sqlElasticPools = new SqlElasticPoolsAsExternalChildResourcesImpl(this.sqlServerManager, "SqlElasticPool");
this.isPatchUpdate = false;
this.importRequestInner = null;
}
@Override
public String id() {
return this.inner().id();
}
@Override
public String resourceGroupName() {
return this.resourceGroupName;
}
@Override
public String sqlServerName() {
return this.sqlServerName;
}
@Override
public String collation() {
return this.inner().collation();
}
@Override
public DateTime creationDate() {
return this.inner().creationDate();
}
@Override
public UUID currentServiceObjectiveId() {
return this.inner().currentServiceObjectiveId();
}
@Override
public String databaseId() {
return this.inner().databaseId().toString();
}
@Override
public DateTime earliestRestoreDate() {
return this.inner().earliestRestoreDate();
}
@Override
public DatabaseEdition edition() {
return this.inner().edition();
}
@Override
public UUID requestedServiceObjectiveId() {
return this.inner().requestedServiceObjectiveId();
}
@Override
public long maxSizeBytes() {
return Long.valueOf(this.inner().maxSizeBytes());
}
@Override
public ServiceObjectiveName requestedServiceObjectiveName() {
return this.inner().requestedServiceObjectiveName();
}
@Override
public ServiceObjectiveName serviceLevelObjective() {
return this.inner().serviceLevelObjective();
}
@Override
public String status() {
return this.inner().status();
}
@Override
public String elasticPoolName() {
return this.inner().elasticPoolName();
}
@Override
public String defaultSecondaryLocation() {
return this.inner().defaultSecondaryLocation();
}
@Override
public boolean isDataWarehouse() {
return this.inner().edition().toString().equalsIgnoreCase(DatabaseEdition.DATA_WAREHOUSE.toString());
}
@Override
public SqlWarehouse asWarehouse() {
if (this.isDataWarehouse()) {
if (this.parent() != null) {
return new SqlWarehouseImpl(this.name(), this.parent(), this.inner(), this.sqlServerManager);
} else {
return new SqlWarehouseImpl(this.resourceGroupName, this.sqlServerName, this.sqlServerLocation, this.name(), this.inner(), this.sqlServerManager);
}
}
return null;
}
@Override
public List<RestorePoint> listRestorePoints() {
List<RestorePoint> restorePoints = new ArrayList<>();
List<RestorePointInner> restorePointInners = this.sqlServerManager.inner()
.restorePoints().listByDatabase(this.resourceGroupName, this.sqlServerName, this.name());
if (restorePointInners != null) {
for (RestorePointInner inner : restorePointInners) {
restorePoints.add(new RestorePointImpl(this.resourceGroupName, this.sqlServerName, inner));
}
}
return Collections.unmodifiableList(restorePoints);
}
@Override
public Observable<RestorePoint> listRestorePointsAsync() {
final SqlDatabaseImpl self = this;
return this.sqlServerManager.inner()
.restorePoints().listByDatabaseAsync(this.resourceGroupName, this.sqlServerName, this.name())
.flatMap(new Func1<List<RestorePointInner>, Observable<RestorePointInner>>() {
@Override
public Observable<RestorePointInner> call(List<RestorePointInner> restorePointInners) {
return Observable.from(restorePointInners);
}
})
.map(new Func1<RestorePointInner, RestorePoint>() {
@Override
public RestorePoint call(RestorePointInner restorePointInner) {
return new RestorePointImpl(self.resourceGroupName, self.sqlServerName, restorePointInner);
}
});
}
@Override
public Map<String, ReplicationLink> listReplicationLinks() {
Map<String, ReplicationLink> replicationLinkMap = new HashMap<>();
List<ReplicationLinkInner> replicationLinkInners = this.sqlServerManager.inner()
.replicationLinks().listByDatabase(this.resourceGroupName, this.sqlServerName, this.name());
if (replicationLinkInners != null) {
for (ReplicationLinkInner inner : replicationLinkInners) {
replicationLinkMap.put(inner.name(), new ReplicationLinkImpl(this.resourceGroupName, this.sqlServerName, inner, this.sqlServerManager));
}
}
return Collections.unmodifiableMap(replicationLinkMap);
}
@Override
public Observable<ReplicationLink> listReplicationLinksAsync() {
final SqlDatabaseImpl self = this;
return this.sqlServerManager.inner()
.replicationLinks().listByDatabaseAsync(this.resourceGroupName, this.sqlServerName, this.name())
.flatMap(new Func1<List<ReplicationLinkInner>, Observable<ReplicationLinkInner>>() {
@Override
public Observable<ReplicationLinkInner> call(List<ReplicationLinkInner> replicationLinkInners) {
return Observable.from(replicationLinkInners);
}
})
.map(new Func1<ReplicationLinkInner, ReplicationLink>() {
@Override
public ReplicationLink call(ReplicationLinkInner replicationLinkInner) {
return new ReplicationLinkImpl(self.resourceGroupName, self.sqlServerName, replicationLinkInner, self.sqlServerManager);
}
});
}
@Override
public SqlDatabaseExportRequestImpl exportTo(String storageUri) {
return new SqlDatabaseExportRequestImpl(this, this.sqlServerManager)
.exportTo(storageUri);
}
@Override
public SqlDatabaseExportRequestImpl exportTo(StorageAccount storageAccount, String containerName, String fileName) {
Objects.requireNonNull(storageAccount);
return new SqlDatabaseExportRequestImpl(this, this.sqlServerManager)
.exportTo(storageAccount, containerName, fileName);
}
@Override
public SqlDatabaseExportRequestImpl exportTo(Creatable<StorageAccount> storageAccountCreatable, String containerName, String fileName) {
Objects.requireNonNull(storageAccountCreatable);
return new SqlDatabaseExportRequestImpl(this, this.sqlServerManager)
.exportTo(storageAccountCreatable, containerName, fileName);
}
@Override
public SqlDatabaseImportRequestImpl importBacpac(String storageUri) {
return new SqlDatabaseImportRequestImpl(this, this.sqlServerManager)
.importFrom(storageUri);
}
@Override
public SqlDatabaseImportRequestImpl importBacpac(StorageAccount storageAccount, String containerName, String fileName) {
Objects.requireNonNull(storageAccount);
return new SqlDatabaseImportRequestImpl(this, this.sqlServerManager)
.importFrom(storageAccount, containerName, fileName);
}
@Override
public SqlDatabaseThreatDetectionPolicy.DefinitionStages.Blank defineThreatDetectionPolicy(String policyName) {
return new SqlDatabaseThreatDetectionPolicyImpl(policyName, this, new DatabaseSecurityAlertPolicyInner(), this.sqlServerManager);
}
@Override
public SqlDatabaseThreatDetectionPolicy getThreatDetectionPolicy() {
DatabaseSecurityAlertPolicyInner policyInner = this.sqlServerManager.inner().databaseThreatDetectionPolicies()
.get(this.resourceGroupName, this.sqlServerName, this.name());
return policyInner != null ? new SqlDatabaseThreatDetectionPolicyImpl(policyInner.name(), this, policyInner, this.sqlServerManager) : null;
}
@Override
public SqlDatabaseAutomaticTuning getDatabaseAutomaticTuning() {
DatabaseAutomaticTuningInner databaseAutomaticTuningInner = this.sqlServerManager.inner().databaseAutomaticTunings()
.get(this.resourceGroupName, this.sqlServerName, this.name());
return databaseAutomaticTuningInner != null ? new SqlDatabaseAutomaticTuningImpl(this, databaseAutomaticTuningInner) : null;
}
@Override
public List<SqlDatabaseUsageMetric> listUsageMetrics() {
List<SqlDatabaseUsageMetric> databaseUsageMetrics = new ArrayList<>();
List<DatabaseUsageInner> databaseUsageInners = this.sqlServerManager.inner().databaseUsages()
.listByDatabase(this.resourceGroupName, this.sqlServerName, this.name());
if (databaseUsageInners != null) {
for (DatabaseUsageInner inner : databaseUsageInners) {
databaseUsageMetrics.add(new SqlDatabaseUsageMetricImpl(inner));
}
}
return Collections.unmodifiableList(databaseUsageMetrics);
}
@Override
public Observable<SqlDatabaseUsageMetric> listUsageMetricsAsync() {
return this.sqlServerManager.inner().databaseUsages()
.listByDatabaseAsync(this.resourceGroupName, this.sqlServerName, this.name())
.flatMap(new Func1<List<DatabaseUsageInner>, Observable<DatabaseUsageInner>>() {
@Override
public Observable<DatabaseUsageInner> call(List<DatabaseUsageInner> databaseUsageInners) {
return Observable.from(databaseUsageInners);
}
})
.map(new Func1<DatabaseUsageInner, SqlDatabaseUsageMetric>() {
@Override
public SqlDatabaseUsageMetric call(DatabaseUsageInner databaseUsageInner) {
return new SqlDatabaseUsageMetricImpl(databaseUsageInner);
}
});
}
@Override
public SqlDatabase rename(String newDatabaseName) {
ResourceId resourceId = ResourceId.fromString(this.id());
String newId = resourceId.parent().id() + "/databases/" + newDatabaseName;
this.sqlServerManager.inner().databases()
.rename(this.resourceGroupName, this.sqlServerName, this.name(), newId);
return this.sqlServerManager.sqlServers().databases()
.getBySqlServer(this.resourceGroupName, this.sqlServerName, newDatabaseName);
}
@Override
public Observable<SqlDatabase> renameAsync(final String newDatabaseName) {
final SqlDatabaseImpl self = this;
ResourceId resourceId = ResourceId.fromString(this.id());
String newId = resourceId.parent().id() + "/databases/" + newDatabaseName;
return this.sqlServerManager.inner().databases()
.renameAsync(this.resourceGroupName, this.sqlServerName, self.name(), newId)
.flatMap(new Func1<Void, Observable<SqlDatabase>>() {
@Override
public Observable<SqlDatabase> call(Void aVoid) {
return self.sqlServerManager.sqlServers().databases()
.getBySqlServerAsync(self.resourceGroupName, self.sqlServerName, newDatabaseName);
}
});
}
@Override
public List<DatabaseMetric> listUsages() {
// This method was deprecated in favor of the other database metric related methods
return Collections.unmodifiableList(new ArrayList<DatabaseMetric>());
}
@Override
public List<SqlDatabaseMetric> listMetrics(String filter) {
List<SqlDatabaseMetric> sqlDatabaseMetrics = new ArrayList<>();
List<MetricInner> metricInners = this.sqlServerManager.inner().databases()
.listMetrics(this.resourceGroupName, this.sqlServerName, this.name(), filter);
if (metricInners != null) {
for (MetricInner metricInner : metricInners) {
sqlDatabaseMetrics.add(new SqlDatabaseMetricImpl(metricInner));
}
}
return Collections.unmodifiableList(sqlDatabaseMetrics);
}
@Override
public Observable<SqlDatabaseMetric> listMetricsAsync(final String filter) {
return this.sqlServerManager.inner().databases()
.listMetricsAsync(this.resourceGroupName, this.sqlServerName, this.name(), filter)
.flatMap(new Func1<List<MetricInner>, Observable<MetricInner>>() {
@Override
public Observable<MetricInner> call(List<MetricInner> metricInners) {
return Observable.from(metricInners);
}
})
.map(new Func1<MetricInner, SqlDatabaseMetric>() {
@Override
public SqlDatabaseMetric call(MetricInner metricInner) {
return new SqlDatabaseMetricImpl(metricInner);
}
});
}
@Override
public List<SqlDatabaseMetricDefinition> listMetricDefinitions() {
List<SqlDatabaseMetricDefinition> sqlDatabaseMetricDefinitions = new ArrayList<>();
List<MetricDefinitionInner> metricDefinitionInners = this.sqlServerManager.inner().databases()
.listMetricDefinitions(this.resourceGroupName, this.sqlServerName, this.name());
if (metricDefinitionInners != null) {
for (MetricDefinitionInner metricDefinitionInner : metricDefinitionInners) {
sqlDatabaseMetricDefinitions.add(new SqlDatabaseMetricDefinitionImpl(metricDefinitionInner));
}
}
return Collections.unmodifiableList(sqlDatabaseMetricDefinitions);
}
@Override
public Observable<SqlDatabaseMetricDefinition> listMetricDefinitionsAsync() {
return this.sqlServerManager.inner().databases()
.listMetricDefinitionsAsync(this.resourceGroupName, this.sqlServerName, this.name())
.flatMap(new Func1<List<MetricDefinitionInner>, Observable<MetricDefinitionInner>>() {
@Override
public Observable<MetricDefinitionInner> call(List<MetricDefinitionInner> metricDefinitionInners) {
return Observable.from(metricDefinitionInners);
}
})
.map(new Func1<MetricDefinitionInner, SqlDatabaseMetricDefinition>() {
@Override
public SqlDatabaseMetricDefinition call(MetricDefinitionInner metricDefinitionInner) {
return new SqlDatabaseMetricDefinitionImpl(metricDefinitionInner);
}
});
}
@Override
public TransparentDataEncryption getTransparentDataEncryption() {
TransparentDataEncryptionInner transparentDataEncryptionInner = this.sqlServerManager.inner()
.transparentDataEncryptions().get(this.resourceGroupName, this.sqlServerName, this.name());
return new TransparentDataEncryptionImpl(this.resourceGroupName, this.sqlServerName, transparentDataEncryptionInner, this.sqlServerManager);
}
@Override
public Observable<TransparentDataEncryption> getTransparentDataEncryptionAsync() {
final SqlDatabaseImpl self = this;
return this.sqlServerManager.inner()
.transparentDataEncryptions().getAsync(this.resourceGroupName, this.sqlServerName, this.name())
.map(new Func1<TransparentDataEncryptionInner, TransparentDataEncryption>() {
@Override
public TransparentDataEncryption call(TransparentDataEncryptionInner transparentDataEncryptionInner) {
return new TransparentDataEncryptionImpl(self.resourceGroupName, self.sqlServerName, transparentDataEncryptionInner, self.sqlServerManager);
}
});
}
@Override
public Map<String, ServiceTierAdvisor> listServiceTierAdvisors() {
Map<String, ServiceTierAdvisor> serviceTierAdvisorMap = new HashMap<>();
List<ServiceTierAdvisorInner> serviceTierAdvisorInners = this.sqlServerManager.inner()
.serviceTierAdvisors().listByDatabase(this.resourceGroupName, this.sqlServerName, this.name());
if (serviceTierAdvisorInners != null) {
for (ServiceTierAdvisorInner serviceTierAdvisorInner : serviceTierAdvisorInners) {
serviceTierAdvisorMap.put(serviceTierAdvisorInner.name(),
new ServiceTierAdvisorImpl(this.resourceGroupName, this.sqlServerName, serviceTierAdvisorInner, this.sqlServerManager));
}
}
return Collections.unmodifiableMap(serviceTierAdvisorMap);
}
@Override
public Observable<ServiceTierAdvisor> listServiceTierAdvisorsAsync() {
final SqlDatabaseImpl self = this;
return this.sqlServerManager.inner()
.serviceTierAdvisors().listByDatabaseAsync(this.resourceGroupName, this.sqlServerName, this.name())
.flatMap(new Func1<List<ServiceTierAdvisorInner>, Observable<ServiceTierAdvisorInner>>() {
@Override
public Observable<ServiceTierAdvisorInner> call(List<ServiceTierAdvisorInner> serviceTierAdvisorInners) {
return Observable.from(serviceTierAdvisorInners);
}
})
.map(new Func1<ServiceTierAdvisorInner, ServiceTierAdvisor>() {
@Override
public ServiceTierAdvisor call(ServiceTierAdvisorInner serviceTierAdvisorInner) {
return new ServiceTierAdvisorImpl(self.resourceGroupName, self.sqlServerName, serviceTierAdvisorInner, self.sqlServerManager);
}
});
}
@Override
public String parentId() {
return ResourceUtils.parentResourceIdFromResourceId(this.id());
}
@Override
public String regionName() {
return this.inner().location();
}
@Override
public Region region() {
return Region.fromName(this.regionName());
}
@Override
public SqlSyncGroupOperations.SqlSyncGroupActionsDefinition syncGroups() {
if (this.syncGroups == null) {
this.syncGroups = new SqlSyncGroupOperationsImpl(this, this.sqlServerManager);
}
return this.syncGroups;
}
SqlDatabaseImpl withPatchUpdate() {
this.isPatchUpdate = true;
return this;
}
@Override
protected Observable<DatabaseInner> getInnerAsync() {
return this.sqlServerManager.inner().databases().getAsync(this.resourceGroupName, this.sqlServerName, this.name());
}
void addParentDependency(TaskGroup.HasTaskGroup parentDependency) {
this.addDependency(parentDependency);
}
@Override
public void beforeGroupCreateOrUpdate() {
if (this.importRequestInner != null && this.elasticPoolName() != null) {
final SqlDatabaseImpl self = this;
final String epName = this.elasticPoolName();
this.addPostRunDependent(new FunctionalTaskItem() {
@Override
public Observable<Indexable> call(final Context context) {
self.importRequestInner = null;
self.withExistingElasticPool(epName);
return self.createResourceAsync()
.flatMap(new Func1<SqlDatabase, Observable<Indexable>>() {
@Override
public Observable<Indexable> call(SqlDatabase sqlDatabase) {
return context.voidObservable();
}
});
}
});
}
}
@Override
public Observable<SqlDatabase> createResourceAsync() {
final SqlDatabaseImpl self = this;
this.inner().withLocation(this.sqlServerLocation);
if (this.importRequestInner != null) {
this.importRequestInner.withDatabaseName(this.name());
if (this.importRequestInner.edition() == null) {
this.importRequestInner.withEdition(this.inner().edition());
}
if (this.importRequestInner.serviceObjectiveName() == null) {
this.importRequestInner.withServiceObjectiveName((this.inner().requestedServiceObjectiveName()));
}
if (this.importRequestInner.maxSizeBytes() == null) {
this.importRequestInner.withMaxSizeBytes(this.inner().maxSizeBytes());
}
return this.sqlServerManager.inner().databases()
.importMethodAsync(this.resourceGroupName, this.sqlServerName, this.importRequestInner)
.flatMap(new Func1<ImportExportResponseInner, Observable<SqlDatabase>>() {
@Override
public Observable<SqlDatabase> call(ImportExportResponseInner importExportResponseInner) {
if (self.elasticPoolName() != null) {
self.importRequestInner = null;
return self.withExistingElasticPool(self.elasticPoolName()).withPatchUpdate().updateResourceAsync();
} else {
return self.refreshAsync();
}
}
});
} else {
return this.sqlServerManager.inner().databases()
.createOrUpdateAsync(this.resourceGroupName, this.sqlServerName, this.name(), this.inner())
.map(new Func1<DatabaseInner, SqlDatabase>() {
@Override
public SqlDatabase call(DatabaseInner inner) {
self.setInner(inner);
return self;
}
});
}
}
@Override
public Observable<SqlDatabase> updateResourceAsync() {
if (this.isPatchUpdate) {
final SqlDatabaseImpl self = this;
DatabaseUpdate databaseUpdateInner = new DatabaseUpdate()
.withTags(self.inner().getTags())
.withCollation(self.inner().collation())
.withSourceDatabaseId(self.inner().sourceDatabaseId())
.withCreateMode(self.inner().createMode())
.withEdition(self.inner().edition())
.withRequestedServiceObjectiveName(this.inner().requestedServiceObjectiveName())
.withMaxSizeBytes(this.inner().maxSizeBytes())
.withElasticPoolName(this.inner().elasticPoolName());
return this.sqlServerManager.inner().databases()
.updateAsync(this.resourceGroupName, this.sqlServerName, this.name(), databaseUpdateInner)
.map(new Func1<DatabaseInner, SqlDatabase>() {
@Override
public SqlDatabase call(DatabaseInner inner) {
self.setInner(inner);
self.isPatchUpdate = false;
return self;
}
});
} else {
return this.createResourceAsync();
}
}
@Override
public SqlDatabaseImpl update() {
super.prepareUpdate();
return this;
}
@Override
public Completable afterPostRunAsync(boolean isGroupFaulted) {
if (this.sqlElasticPools != null) {
this.sqlElasticPools.clear();
}
this.importRequestInner = null;
return Completable.complete();
}
@Override
public Observable<Void> deleteResourceAsync() {
return this.sqlServerManager.inner().databases().deleteAsync(this.resourceGroupName, this.sqlServerName, this.name());
}
@Override
public void delete() {
this.sqlServerManager.inner().databases().delete(this.resourceGroupName, this.sqlServerName, this.name());
}
@Override
public Completable deleteAsync() {
return this.deleteResourceAsync().toCompletable();
}
@Override
public SqlDatabaseImpl withExistingSqlServer(String resourceGroupName, String sqlServerName, String sqlServerLocation) {
this.resourceGroupName = resourceGroupName;
this.sqlServerName = sqlServerName;
this.sqlServerLocation = sqlServerLocation;
return this;
}
@Override
public SqlDatabaseImpl withExistingSqlServer(SqlServer sqlServer) {
Objects.requireNonNull(sqlServer);
this.resourceGroupName = sqlServer.resourceGroupName();
this.sqlServerName = sqlServer.name();
this.sqlServerLocation = sqlServer.regionName();
return this;
}
@Override
public SqlServerImpl attach() {
return this.parent();
}
@Override
public SqlDatabaseImpl withoutElasticPool() {
this.inner().withElasticPoolName(null);
this.inner().withRequestedServiceObjectiveId(null);
this.inner().withRequestedServiceObjectiveName(ServiceObjectiveName.S0);
return this;
}
@Override
public SqlDatabaseImpl withExistingElasticPool(String elasticPoolName) {
this.inner().withEdition(null);
this.inner().withRequestedServiceObjectiveId(null);
this.inner().withRequestedServiceObjectiveName(null);
this.inner().withElasticPoolName(elasticPoolName);
return this;
}
@Override
public SqlDatabaseImpl withExistingElasticPool(SqlElasticPool sqlElasticPool) {
Objects.requireNonNull(sqlElasticPool);
this.inner().withEdition(null);
this.inner().withRequestedServiceObjectiveId(null);
this.inner().withRequestedServiceObjectiveName(null);
this.inner().withElasticPoolName(sqlElasticPool.name());
return this;
}
@Override
public SqlDatabaseImpl withNewElasticPool(final Creatable<SqlElasticPool> sqlElasticPool) {
Objects.requireNonNull(sqlElasticPool);
this.inner().withEdition(null);
this.inner().withRequestedServiceObjectiveId(null);
this.inner().withRequestedServiceObjectiveName(null);
this.inner().withElasticPoolName(sqlElasticPool.name());
this.addDependency(sqlElasticPool);
return this;
}
@Override
public SqlElasticPoolForDatabaseImpl defineElasticPool(String elasticPoolName) {
if (this.sqlElasticPools == null) {
this.sqlElasticPools = new SqlElasticPoolsAsExternalChildResourcesImpl(this.taskGroup(), this.sqlServerManager, "SqlElasticPool");
}
this.inner().withEdition(null);
this.inner().withRequestedServiceObjectiveId(null);
this.inner().withRequestedServiceObjectiveName(null);
this.inner().withElasticPoolName(elasticPoolName);
return new SqlElasticPoolForDatabaseImpl(this, this.sqlElasticPools
.defineIndependentElasticPool(elasticPoolName).withExistingSqlServer(this.resourceGroupName, this.sqlServerName, this.sqlServerLocation));
}
@Override
public SqlDatabaseImpl fromRestorableDroppedDatabase(SqlRestorableDroppedDatabase restorableDroppedDatabase) {
Objects.requireNonNull(restorableDroppedDatabase);
return this.withSourceDatabase(restorableDroppedDatabase.id())
.withMode(CreateMode.RESTORE);
}
private void initializeImportRequestInner() {
this.importRequestInner = new ImportRequest();
if (this.elasticPoolName() != null) {
this.importRequestInner.withEdition(DatabaseEdition.BASIC);
this.importRequestInner.withServiceObjectiveName(ServiceObjectiveName.BASIC);
this.importRequestInner.withMaxSizeBytes(Long.toString(SqlDatabaseBasicStorage.MAX_2_GB.capacity()));
} else {
this.withStandardEdition(SqlDatabaseStandardServiceObjective.S0);
}
}
@Override
public SqlDatabaseImpl importFrom(String storageUri) {
this.initializeImportRequestInner();
this.importRequestInner.withStorageUri(storageUri);
return this;
}
@Override
public SqlDatabaseImpl importFrom(final StorageAccount storageAccount, final String containerName, final String fileName) {
final SqlDatabaseImpl self = this;
Objects.requireNonNull(storageAccount);
this.initializeImportRequestInner();
this.addDependency(new FunctionalTaskItem() {
@Override
public Observable<Indexable> call(final Context context) {
return storageAccount.getKeysAsync()
.flatMap(new Func1<List<StorageAccountKey>, Observable<StorageAccountKey>>() {
@Override
public Observable<StorageAccountKey> call(List<StorageAccountKey> storageAccountKeys) {
return Observable.from(storageAccountKeys).first();
}
})
.flatMap(new Func1<StorageAccountKey, Observable<Indexable>>() {
@Override
public Observable<Indexable> call(StorageAccountKey storageAccountKey) {
self.importRequestInner.withStorageUri(String.format("%s%s/%s", storageAccount.endPoints().primary().blob(), containerName, fileName));
self.importRequestInner.withStorageKeyType(StorageKeyType.STORAGE_ACCESS_KEY);
self.importRequestInner.withStorageKey(storageAccountKey.value());
return context.voidObservable();
}
});
}
});
return this;
}
@Override
public SqlDatabaseImpl withStorageAccessKey(String storageAccessKey) {
this.importRequestInner.withStorageKeyType(StorageKeyType.STORAGE_ACCESS_KEY);
this.importRequestInner.withStorageKey(storageAccessKey);
return this;
}
@Override
public SqlDatabaseImpl withSharedAccessKey(String sharedAccessKey) {
this.importRequestInner.withStorageKeyType(StorageKeyType.SHARED_ACCESS_KEY);
this.importRequestInner.withStorageKey(sharedAccessKey);
return this;
}
@Override
public SqlDatabaseImpl withSqlAdministratorLoginAndPassword(String administratorLogin, String administratorPassword) {
this.importRequestInner.withAuthenticationType(AuthenticationType.SQL);
this.importRequestInner.withAdministratorLogin(administratorLogin);
this.importRequestInner.withAdministratorLoginPassword(administratorPassword);
return this;
}
@Override
public SqlDatabaseImpl withActiveDirectoryLoginAndPassword(String administratorLogin, String administratorPassword) {
this.importRequestInner.withAuthenticationType(AuthenticationType.ADPASSWORD);
this.importRequestInner.withAdministratorLogin(administratorLogin);
this.importRequestInner.withAdministratorLoginPassword(administratorPassword);
return this;
}
@Override
public SqlDatabaseImpl fromRestorePoint(RestorePoint restorePoint) {
return fromRestorePoint(restorePoint, restorePoint.earliestRestoreDate());
}
@Override
public SqlDatabaseImpl fromRestorePoint(RestorePoint restorePoint, DateTime restorePointDateTime) {
Objects.requireNonNull(restorePoint);
this.inner().withRestorePointInTime(restorePointDateTime);
return this.withSourceDatabase(restorePoint.databaseId())
.withMode(CreateMode.POINT_IN_TIME_RESTORE);
}
@Override
public SqlDatabaseImpl withSourceDatabase(String sourceDatabaseId) {
this.inner().withSourceDatabaseId(sourceDatabaseId);
return this;
}
@Override
public SqlDatabaseImpl withSourceDatabase(SqlDatabase sourceDatabase) {
return this.withSourceDatabase(sourceDatabase.id());
}
@Override
public SqlDatabaseImpl withMode(CreateMode createMode) {
this.inner().withCreateMode(createMode);
return this;
}
@Override
public SqlDatabaseImpl withCollation(String collation) {
this.inner().withCollation(collation);
return this;
}
@Override
public SqlDatabaseImpl withMaxSizeBytes(long maxSizeBytes) {
this.inner().withMaxSizeBytes(Long.toString(maxSizeBytes));
return this;
}
@Override
public SqlDatabaseImpl withEdition(DatabaseEdition edition) {
this.inner().withElasticPoolName(null);
this.inner().withRequestedServiceObjectiveId(null);
this.inner().withEdition(edition);
return this;
}
@Override
public SqlDatabaseImpl withBasicEdition() {
return this.withBasicEdition(SqlDatabaseBasicStorage.MAX_2_GB);
}
@Override
public SqlDatabaseImpl withBasicEdition(SqlDatabaseBasicStorage maxStorageCapacity) {
this.inner().withEdition(DatabaseEdition.BASIC);
this.withServiceObjective(ServiceObjectiveName.BASIC);
this.inner().withMaxSizeBytes(Long.toString(maxStorageCapacity.capacity()));
return this;
}
@Override
public SqlDatabaseImpl withStandardEdition(SqlDatabaseStandardServiceObjective serviceObjective) {
return this.withStandardEdition(serviceObjective, SqlDatabaseStandardStorage.MAX_250_GB);
}
@Override
public SqlDatabaseImpl withStandardEdition(SqlDatabaseStandardServiceObjective serviceObjective, SqlDatabaseStandardStorage maxStorageCapacity) {
this.inner().withEdition(DatabaseEdition.STANDARD);
this.withServiceObjective(ServiceObjectiveName.fromString(serviceObjective.toString()));
this.inner().withMaxSizeBytes(Long.toString(maxStorageCapacity.capacity()));
return this;
}
@Override
public SqlDatabaseImpl withPremiumEdition(SqlDatabasePremiumServiceObjective serviceObjective) {
return this.withPremiumEdition(serviceObjective, SqlDatabasePremiumStorage.MAX_500_GB);
}
@Override
public SqlDatabaseImpl withPremiumEdition(SqlDatabasePremiumServiceObjective serviceObjective, SqlDatabasePremiumStorage maxStorageCapacity) {
this.inner().withEdition(DatabaseEdition.PREMIUM);
this.withServiceObjective(ServiceObjectiveName.fromString(serviceObjective.toString()));
this.inner().withMaxSizeBytes(Long.toString(maxStorageCapacity.capacity()));
return this;
}
@Override
public SqlDatabaseImpl withServiceObjective(ServiceObjectiveName serviceLevelObjective) {
this.inner().withElasticPoolName(null);
this.inner().withRequestedServiceObjectiveId(null);
this.inner().withRequestedServiceObjectiveName(serviceLevelObjective);
return this;
}
@Override
public SqlDatabaseImpl withTags(Map<String, String> tags) {
this.inner().withTags(new HashMap<>(tags));
return this;
}
@Override
public SqlDatabaseImpl withTag(String key, String value) {
if (this.inner().getTags() == null) {
this.inner().withTags(new HashMap<String, String>());
}
this.inner().getTags().put(key, value);
return this;
}
@Override
public SqlDatabaseImpl withoutTag(String key) {
if (this.inner().getTags() != null) {
this.inner().getTags().remove(key);
}
return this;
}
@Override
public SqlDatabaseImpl fromSample(SampleName sampleName) {
this.inner().withSampleName(sampleName);
return this;
}
}
| 42.645957 | 170 | 0.691696 |
33c1babc397c8df4a3e90dad5840863794e75fcd | 1,330 | package com.booksan.dao;
import java.sql.*;
public class DBUtils {
private DBUtils() {
}
public static Connection getConnection() {
Connection conn = null;
try {
PropertiesUtil propertiesUtil = PropertiesUtil.getInstance();
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(propertiesUtil.getDbURL(), propertiesUtil.getProperties());
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return conn;
}
public static void close(Connection conn, PreparedStatement ps) {
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(Connection conn, PreparedStatement ps, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
close(conn, ps);
}
}
| 25.576923 | 106 | 0.5 |
a127dea1bb8444027dbca8e3f8af6776d30c2b93 | 2,667 | /*
* Digital Invisible Ink Toolkit
* Copyright (C) 2005 K. Hempstalk
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
package invisibleinktoolkit.benchmark.gui;
import javax.swing.JPanel;
import javax.swing.BoxLayout;
import javax.swing.border.TitledBorder;
import java.awt.Dimension;
import javax.swing.JRadioButton;
import javax.swing.ButtonGroup;
/**
* A panel to pick the formats for file output.
*
* @author Kathryn Hempstalk.
*/
public class FormatPanel extends JPanel{
//CONSTRUCTORS
/**
* Sets up the panel with all the formats.
*/
public FormatPanel(){
super();
//setup the layout
this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
this.setBorder(new TitledBorder("Choose the output format"));
this.setPreferredSize(new Dimension(740,50));
//setup the radio buttons
mCSVButton = new JRadioButton("CSV file");
mCSVButton.setToolTipText("CSV File - Comma Separated Values");
mCSVButton.setPreferredSize(new Dimension(180, 26));
mCSVButton.setSelected(true);
mARFFButton = new JRadioButton("ARFF (WEKA) file");
mARFFButton.setToolTipText("ARFF file - WEKA machine learning file format");
mARFFButton.setPreferredSize(new Dimension(180, 26));
mARFFButton.setSelected(false);
//group them
ButtonGroup bgroup = new ButtonGroup();
bgroup.add(mCSVButton);
bgroup.add(mARFFButton);
//add them to the panel
this.add(mCSVButton);
this.add(mARFFButton);
//put in a spacer panel
JPanel spacer1 = new JPanel();
this.add(spacer1);
}
//FUNCTIONS
/**
* Whether CSV is selected.
*
* @return Whether CSV is selected.
*/
public boolean isCSVSelected(){
return mCSVButton.isSelected();
}
//VARIABLES
/**
* A radio button for CSV files.
*/
private JRadioButton mCSVButton;
/**
* A radio button for ARFF files.
*/
private JRadioButton mARFFButton;
/**
* The serialisation ID.
*/
private static final long serialVersionUID = 0;
}
//end of class
| 25.644231 | 78 | 0.707912 |
50d83a766b2aa3d21886b9676a2780c07db372bb | 884 | package com.mountzoft.bakingapp;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class MyRecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView mTextView;
ImageView mImageView;
MyRecyclerViewClickListener itemClickListener;
MyRecyclerViewHolder(View itemView) {
super(itemView);
mTextView = itemView.findViewById(R.id.tv_item);
mImageView = itemView.findViewById(R.id.recipe_background);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View view) {
this.itemClickListener.onItemClick(this.getLayoutPosition());
}
void setItemClickListener(MyRecyclerViewClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
}
| 30.482759 | 99 | 0.756787 |
bb5c0c7143c84e08ad3bd4ec5e6d0d7f906f95f4 | 3,902 | package com.radish.master.controller.safty;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.hibernate.type.StringType;
import org.hibernate.type.Type;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONArray;
import com.cnpc.framework.base.entity.User;
import com.cnpc.framework.base.pojo.Result;
import com.cnpc.framework.base.service.BaseService;
import com.cnpc.framework.utils.SecurityUtil;
import com.radish.master.entity.safty.AqTest;
import com.radish.master.entity.safty.AqTestModel;
import com.radish.master.entity.safty.AqTestMx;
import com.radish.master.pojo.AqtestVO;
import com.radish.master.pojo.Options;
import com.radish.master.service.BudgetService;
@Controller
@RequestMapping("/aqtest")
public class AqTestController {
@Autowired
private BaseService baseService;
@Autowired
private BudgetService budgetService;
private String prefix = "/safetyManage/aqtest/";
@RequestMapping("/search")
public String search(HttpServletRequest request){
String type = request.getParameter("type");
request.setAttribute("type", type);
request.setAttribute("projectOptions", JSONArray.toJSONString(budgetService.getProjectCombobox()));
if("2".equals(type)){
return prefix +"list2";
}else if("4".equals(type)){
return prefix +"list4";
}
return prefix +"list";
}
/**
* 1-项目部考核
* 2-安全生产
* 3-安全目表
* 4-形象
*
*/
@RequestMapping("/addindex")
public String jobduty(HttpServletRequest request){
User u = SecurityUtil.getUser();
request.setAttribute("name", u.getName());
request.setAttribute("projectOptions", JSONArray.toJSONString(budgetService.getProjectCombobox()));
String type = request.getParameter("type");
if("2".equals(type)){
return prefix +"addindex2";
}else if("4".equals(type)){
return prefix +"addindex4";
}
return prefix +"addindex";
}
@RequestMapping("/getModelGroup")
@ResponseBody
public Result getModelGroup(String type){
List<Options> wjs = baseService.findMapBySql("select station data,station value from tbl_aqtestmodel "
+ "where type='"+type+"' group by station", new Object[]{}, new Type[]{StringType.INSTANCE}, Options.class);
return new Result(true,wjs);
}
@RequestMapping("/getModelInfo")
@ResponseBody
public Result getModelInfo(String type,String gw){
List<AqTestModel> yyfjs = baseService.find(" from AqTestModel where type='"+type+"' and station='"+gw+"' order by orderNum");
return new Result(true,yyfjs);
}
@RequestMapping("/save")
@ResponseBody
public Result save(AqtestVO vo,AqTest test,HttpServletRequest request){
List<Map<String,String>> css = vo.getList();
if(css==null||css.size()==0){
return new Result(false,"请录入考核明细");
}
List<AqTestMx> mxs = new ArrayList<AqTestMx>();
for(Map<String,String> cs :css){
String df = cs.get("df");
String kf = cs.get("kf");
String mbid = cs.get("mbid");
if(df==null||kf==null){
return new Result(false,"明细不完整,请补充");
}
AqTestMx mx = new AqTestMx();
mx.setDf(df);
mx.setKf(kf);
mx.setMbid(mbid);
mxs.add(mx);
}
baseService.save(test);
String id = test.getId();
for(AqTestMx mx : mxs){
mx.setPid(id);
baseService.save(mx);
}
return new Result(true,"保存成功");
}
@RequestMapping("/delete")
@ResponseBody
public Result delete(String id,HttpServletRequest request){
Result r= new Result();
AqTest jd = baseService.get(AqTest.class, id);
List<AqTestMx> wjs = baseService.find(" from AqTestMx where pid='"+id+"'");
for(AqTestMx tp:wjs){
baseService.delete(tp);
}
baseService.delete(jd);
return r;
}
}
| 29.78626 | 127 | 0.717324 |
2cd6fb6970d4ca2560dd04d73d0f80cd6b72bd86 | 1,711 | /**
* Copyright 2017 The OpenTracing Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package io.opentracing.contrib.spring.cloud.websocket;
import io.opentracing.Tracer;
import io.opentracing.propagation.Format;
import io.opentracing.propagation.TextMap;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.springframework.messaging.MessageHeaders;
/**
* A TextMap carrier for use with Tracer.extract() to extract tracing context from Spring messaging
* {@link MessageHeaders}.
*
* @see Tracer#extract(Format, Object)
*/
public final class TextMapExtractAdapter implements TextMap {
private final Map<String, String> headers = new HashMap<>();
public TextMapExtractAdapter(final MessageHeaders headers) {
for (Map.Entry<String, Object> entry : headers.entrySet()) {
this.headers.put(entry.getKey(), entry.getValue().toString());
}
}
@Override
public Iterator<Map.Entry<String, String>> iterator() {
return headers.entrySet().iterator();
}
@Override
public void put(String key, String value) {
throw new UnsupportedOperationException(
"TextMapInjectAdapter should only be used with Tracer.extract()");
}
}
| 33.54902 | 100 | 0.746932 |
0c92337c8798ae6013ccc2db5953df50548ae0d0 | 10,571 | package com.mt.user_profile.domain.biz_order;
import com.mt.common.domain.model.domain_event.DomainEventPublisher;
import com.mt.common.domain.model.validate.Validator;
import com.mt.user_profile.application.biz_order.command.CustomerPlaceBizOrderCommand;
import com.mt.user_profile.application.biz_order.command.CustomerUpdateBizOrderAddressCommand;
import com.mt.user_profile.domain.DomainRegistry;
import com.mt.user_profile.domain.biz_order.event.OrderOperationEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.persistence.EntityManager;
import java.time.Instant;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;
@Slf4j
@Service
public class BizOrderService {
@Autowired
private EntityManager entityManager;
@Value("${order.expireAfter.milliseconds}")
private Long expireAfter;
public BizOrderId handlePlaceOrderAction(CustomerPlaceBizOrderCommand commandsProductList, String changeId) {
log.debug("before submit order to saga");
Validator.notEmpty(commandsProductList.getProductList(), "order must have at least one product");
commandsProductList.getProductList().forEach((production)->{
Validator.notNull(production.getVersion(), "version must not be null");
});
BizOrderId bizOrderId = new BizOrderId();
OrderOperationEvent event = new OrderOperationEvent();
List<CartDetail> collect2 = getBizOrderItems(commandsProductList.getProductList());
event.setOrderId(bizOrderId.getDomainId());
event.setBizOrderEvent(BizOrderEvent.NEW_ORDER);
event.setCreatedBy(UserThreadLocal.get());
event.setUserId(UserThreadLocal.get());
event.setOrderState(BizOrderStatus.DRAFT);
event.setTxId(changeId);
event.setPaymentAmt(commandsProductList.getPaymentAmt());
event.setPaymentType(commandsProductList.getPaymentType());
event.setAddress(commandsProductList.getAddress());
event.setProductList(collect2);
DomainEventPublisher.instance().publish(event);
log.debug("order submitted to saga");
return bizOrderId;
}
private List<CartDetail> getBizOrderItems(List<CustomerPlaceBizOrderCommand.BizOrderItemCommand> productList) {
return productList.stream().map(CartDetail::new).collect(Collectors.toList());
}
public void confirmPayment(String orderId, String changeId) {
BizOrderId bizOrderId = new BizOrderId(orderId);
Optional<BizOrderSummary> bizOrder = DomainRegistry.getBizOderSummaryRepository().ordersOfQuery(new BizOrderQuery(bizOrderId, false)).findFirst();
if (bizOrder.isPresent()) {
BizOrderSummary rep = bizOrder.get();
log.debug("start of confirmPayment");
OrderOperationEvent event = new OrderOperationEvent();
event.setOrderId(rep.getOrderId().getDomainId());
event.setBizOrderEvent(BizOrderEvent.CONFIRM_PAYMENT);
event.setCreatedBy(UserThreadLocal.get());
event.setUserId(UserThreadLocal.get());
event.setProductList(rep.getProductList());
event.setOrderState(rep.getOrderState());
event.setTxId(changeId);
event.setVersion(rep.getVersion());
DomainEventPublisher.instance().publish(event);
} else {
throw new IllegalArgumentException("invalid order id");
}
}
public void reserveOrder(String id, String changeId) {
Optional<BizOrderSummary> optionalBizOrder = DomainRegistry.getBizOderSummaryRepository()
.ordersOfQuery(new BizOrderQuery(new BizOrderId(id), false)).findFirst();
if (optionalBizOrder.isPresent()) {
BizOrderSummary orderDetail = optionalBizOrder.get();
OrderOperationEvent event = new OrderOperationEvent();
event.setOrderId(orderDetail.getOrderId().getDomainId());
event.setBizOrderEvent(BizOrderEvent.RESERVE);
event.setCreatedBy(UserThreadLocal.get());
event.setUserId(UserThreadLocal.get());
event.setProductList(orderDetail.getProductList());
event.setOrderState(orderDetail.getOrderState());
event.setTxId(changeId);
event.setVersion(orderDetail.getVersion());
DomainEventPublisher.instance().publish(event);
} else {
throw new IllegalArgumentException("invalid order id");
}
}
public void releaseExpiredOrder() {
log.trace("start release expired orders");
Date from = Date.from(Instant.ofEpochMilli(Instant.now().toEpochMilli() - expireAfter));
List<BizOrderSummary> expiredOrderList = DomainRegistry.getBizOderSummaryRepository().findExpiredNotPaidReserved(from);
if (!expiredOrderList.isEmpty()) {
//only send first 5 orders due to saga pool size is 100
expiredOrderList.stream().limit(5).collect(Collectors.toList()).forEach(expiredOrder -> {
OrderOperationEvent event = new OrderOperationEvent();
event.setTxId(UUID.randomUUID().toString());
event.setOrderId(expiredOrder.getOrderId().getDomainId());
event.setOrderState(expiredOrder.getOrderState());
event.setBizOrderEvent(BizOrderEvent.RECYCLE_ORDER_STORAGE);
event.setVersion(expiredOrder.getVersion());
event.setProductList(expiredOrder.getProductList());
DomainEventPublisher.instance().publish(event);
});
log.info("expired order(s) found");
}
}
public void concludeOrder() {
List<BizOrderSummary> paidReserved = DomainRegistry.getBizOderSummaryRepository().findPaidReservedDraft();
if (!paidReserved.isEmpty()) {
log.info("paid reserved order(s) found {}", paidReserved.stream().map(BizOrderSummary::getOrderId).collect(Collectors.toList()));
//only send first order due to saga pool size
paidReserved.stream().limit(1).forEach(order -> {
OrderOperationEvent event = new OrderOperationEvent();
event.setTxId(UUID.randomUUID().toString());
event.setOrderId(order.getOrderId().getDomainId());
event.setOrderState(order.getOrderState());
event.setBizOrderEvent(BizOrderEvent.CONFIRM_ORDER);
event.setProductList(order.getProductList());
event.setVersion(order.getVersion());
DomainEventPublisher.instance().publish(event);
});
}
}
public void resubmitOrder() {
List<BizOrderSummary> paidRecycled = DomainRegistry.getBizOderSummaryRepository().findPaidRecycled();
if (!paidRecycled.isEmpty()) {
log.info("paid recycled order(s) found {}", paidRecycled.stream().map(BizOrderSummary::getOrderId).collect(Collectors.toList()));
paidRecycled.forEach(order -> {
OrderOperationEvent event = new OrderOperationEvent();
event.setTxId(UUID.randomUUID().toString());
event.setOrderId(order.getOrderId().getDomainId());
event.setOrderState(order.getOrderState());
event.setBizOrderEvent(BizOrderEvent.RESERVE);
event.setVersion(order.getVersion());
event.setProductList(order.getProductList());
DomainEventPublisher.instance().publish(event);
});
}
}
public void updateAddress(String id, String changeId, CustomerUpdateBizOrderAddressCommand command) {
BizOrderId bizOrderId = new BizOrderId(id);
Optional<BizOrderSummary> bizOrder = DomainRegistry.getBizOderSummaryRepository().ordersOfQuery(new BizOrderQuery(bizOrderId, false)).findFirst();
if (bizOrder.isPresent() ) {
if(!bizOrder.get().isPaid() && !bizOrder.get().isRequestCancel()){
BizOrderSummary rep = bizOrder.get();
log.debug("start of update address");
OrderOperationEvent event = new OrderOperationEvent();
event.setOrderId(rep.getOrderId().getDomainId());
event.setBizOrderEvent(BizOrderEvent.UPDATE_ADDRESS);
event.setCreatedBy(UserThreadLocal.get());
event.setUserId(UserThreadLocal.get());
event.setOrderState(rep.getOrderState());
event.setTxId(changeId);
event.setVersion(rep.getVersion());
event.setAddress(new CustomerPlaceBizOrderCommand.BizOrderAddressCmdRep(command));
event.setOriginalAddress(rep.getAddress());
event.setOriginalModifiedByUserAt(rep.getModifiedByUserAt().getTime());
DomainEventPublisher.instance().publish(event);
}else{
throw new IllegalStateException("cannot update address of paid or cancelled request");
}
} else {
throw new IllegalArgumentException("invalid order id "+id);
}
}
public void userCancelOrder(String id, String changeId) {
BizOrderId bizOrderId = new BizOrderId(id);
Optional<BizOrderSummary> bizOrder = DomainRegistry.getBizOderSummaryRepository().ordersOfQuery(new BizOrderQuery(bizOrderId, false)).findFirst();
if (bizOrder.isPresent() ) {
if(!bizOrder.get().isRequestCancel()){
BizOrderSummary rep = bizOrder.get();
log.debug("start of cancel order");
OrderOperationEvent event = new OrderOperationEvent();
event.setOrderId(rep.getOrderId().getDomainId());
event.setBizOrderEvent(BizOrderEvent.CANCEL_ORDER);
event.setCreatedBy(UserThreadLocal.get());
event.setUserId(UserThreadLocal.get());
event.setOrderState(rep.getOrderState());
event.setTxId(changeId);
event.setProductList(rep.getProductList());
event.setVersion(rep.getVersion());
DomainEventPublisher.instance().publish(event);
}else{
throw new IllegalStateException("cannot re-cancel order");
}
} else {
throw new IllegalArgumentException("invalid order id");
}
}
}
| 50.822115 | 154 | 0.666351 |
702c300e4363e88438996378135db4e023926582 | 9,358 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alipay.sofa.registry.server.data.resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import com.alipay.sofa.registry.common.model.constants.ValueConstants;
import org.springframework.beans.factory.annotation.Autowired;
import com.alipay.remoting.Connection;
import com.alipay.sofa.registry.common.model.dataserver.Datum;
import com.alipay.sofa.registry.common.model.store.DataInfo;
import com.alipay.sofa.registry.common.model.store.Publisher;
import com.alipay.sofa.registry.net.NetUtil;
import com.alipay.sofa.registry.server.data.bootstrap.DataServerConfig;
import com.alipay.sofa.registry.server.data.cache.DataServerCache;
import com.alipay.sofa.registry.server.data.cache.DatumCache;
import com.alipay.sofa.registry.server.data.node.DataServerNode;
import com.alipay.sofa.registry.server.data.remoting.dataserver.DataServerNodeFactory;
import com.alipay.sofa.registry.server.data.remoting.metaserver.MetaServerConnectionFactory;
import com.alipay.sofa.registry.server.data.remoting.sessionserver.SessionServerConnectionFactory;
/**
*
* @author shangyu.wh
* @version $Id: DataDigestResource.java, v 0.1 2018-10-19 16:16 shangyu.wh Exp $
*/
@Path("digest")
public class DataDigestResource {
private final static String SESSION = "SESSION";
private final static String DATA = "DATA";
private final static String META = "META";
@Autowired
private SessionServerConnectionFactory sessionServerConnectionFactory;
@Autowired
private MetaServerConnectionFactory metaServerConnectionFactory;
@Autowired
private DataServerConfig dataServerConfig;
@Autowired
private DatumCache datumCache;
@Autowired
private DataServerCache dataServerCache;
@GET
@Path("datum/query")
@Produces(MediaType.APPLICATION_JSON)
public Map<String, Datum> getDatumByDataInfoId(@QueryParam("dataId") String dataId,
@QueryParam("group") String group,
@QueryParam("instanceId") String instanceId,
@QueryParam("dataCenter") String dataCenter) {
Map<String, Datum> retList = new HashMap<>();
if (!isBlank(dataId) && !isBlank(instanceId) && !isBlank(group)) {
String dataInfoId = DataInfo.toDataInfoId(dataId, instanceId, group);
if (isBlank(dataCenter)) {
retList = datumCache.get(dataInfoId);
} else {
retList.put(dataCenter, datumCache.get(dataCenter, dataInfoId));
}
}
return retList;
}
@POST
@Path("connect/query")
@Produces(MediaType.APPLICATION_JSON)
public Map<String, Map<String, Publisher>> getPublishersByConnectId(Map<String, String> map) {
Map<String, Map<String, Publisher>> ret = new HashMap<>();
if (map != null && !map.isEmpty()) {
map.forEach((clientConnectId, sessionConnectId) -> {
String connectId = clientConnectId + ValueConstants.CONNECT_ID_SPLIT + sessionConnectId;
if (!connectId.isEmpty()) {
Map<String, Publisher> publisherMap = datumCache.getByConnectId(connectId);
if (publisherMap != null && !publisherMap.isEmpty()) {
ret.put(connectId, publisherMap);
}
}
});
}
return ret;
}
@GET
@Path("datum/count")
@Produces(MediaType.APPLICATION_JSON)
public String getDatumCount() {
return getLocalDatumCount();
}
protected String getLocalDatumCount() {
StringBuilder sb = new StringBuilder("CacheDigest");
try {
Map<String, Map<String, Datum>> allMap = datumCache.getAll();
if (!allMap.isEmpty()) {
for (Entry<String, Map<String, Datum>> dataCenterEntry : allMap.entrySet()) {
String dataCenter = dataCenterEntry.getKey();
Map<String, Datum> datumMap = dataCenterEntry.getValue();
sb.append(String.format(" [Datum] size of datum in %s is %s", dataCenter, datumMap.size()));
int pubCount = datumMap.values().stream().map(Datum::getPubMap)
.filter(map -> map != null && !map.isEmpty()).mapToInt(Map::size).sum();
sb.append(String.format(",[Publisher] size of publisher in %s is %s", dataCenter, pubCount));
}
} else {
sb.append(" datum cache is empty");
}
} catch (Throwable t) {
sb.append(" cache digest error!");
}
return sb.toString();
}
@GET
@Path("{type}/serverList/query")
@Produces(MediaType.APPLICATION_JSON)
public Map<String, List<String>> getServerListAll(@PathParam("type") String type) {
Map<String, List<String>> map = new HashMap<>();
if (type != null && !type.isEmpty()) {
String inputType = type.toUpperCase();
switch (inputType) {
case SESSION:
List<String> sessionList = getSessionServerList();
if (sessionList != null) {
map = new HashMap<>();
map.put(dataServerConfig.getLocalDataCenter(), sessionList);
}
break;
case DATA:
map = getDataServerList();
break;
case META:
map = getMetaServerList();
break;
default:
map = new HashMap<>();
break;
}
}
return map;
}
public List<String> getSessionServerList() {
List<String> connections = sessionServerConnectionFactory.getSessionConnections().stream()
.filter(connection -> connection != null && connection.isFine())
.map(connection -> connection.getRemoteIP() + ":" + connection.getRemotePort())
.collect(Collectors.toList());
return connections;
}
public Map<String, List<String>> getDataServerList() {
Map<String, List<String>> map = new HashMap<>();
Set<String> allDataCenter = new HashSet<>(dataServerCache.getAllDataCenters());
for (String dataCenter : allDataCenter) {
List<String> list = map.computeIfAbsent(dataCenter, k -> new ArrayList<>());
Map<String, DataServerNode> dataNodes = DataServerNodeFactory.getDataServerNodes(dataCenter);
if (dataNodes != null && !dataNodes.isEmpty()) {
dataNodes.forEach((ip, dataServerNode) -> {
if (ip != null && !ip.equals(DataServerConfig.IP)) {
Connection connection = dataServerNode.getConnection();
if (connection != null && connection.isFine()) {
list.add(connection.getRemoteIP());
}
}
});
}
}
return map;
}
public Map<String, List<String>> getMetaServerList() {
Map<String, List<String>> map = new HashMap<>();
Set<String> allDataCenter = new HashSet<>(metaServerConnectionFactory.getAllDataCenters());
for (String dataCenter : allDataCenter) {
List<String> list = map.computeIfAbsent(dataCenter, k -> new ArrayList<>());
Map<String, Connection> metaConnections = metaServerConnectionFactory.getConnections(dataCenter);
if (metaConnections != null && !metaConnections.isEmpty()) {
metaConnections.forEach((ip, connection) -> {
if (connection != null && connection.isFine()) {
list.add(connection.getRemoteIP());
}
});
}
}
return map;
}
private boolean isBlank(String dataInfoId) {
return dataInfoId == null || dataInfoId.isEmpty();
}
} | 38.669421 | 113 | 0.605685 |
04dfc24718f991ad5b86f6ee86c0fe46580d1ae4 | 3,938 | package com.guiabolso.mock.helper;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class OperationHelperTest {
private final OperationHelper operationHelper = new OperationHelper();
@Test
public void testIsLeapYear() {
int[] years = new int[] {2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013,
2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021};
for (int testYear : years) {
switch (testYear) {
case 2000:
case 2004:
case 2008:
case 2012:
case 2016:
case 2020:
assertTrue(operationHelper.isLeapYear(testYear));
break;
case 2001:
case 2002:
case 2003:
case 2005:
case 2006:
case 2007:
case 2009:
case 2010:
case 2011:
case 2013:
case 2014:
case 2015:
case 2017:
case 2018:
case 2019:
case 2021:
assertFalse(operationHelper.isLeapYear(testYear));
}
}
}
@Test
public void testGetMaxDaysOfMonth() {
int actualNumberOfDays = operationHelper.getMaxDaysOfMonth(2020, 5);
int actualNumberOfDays2 = operationHelper.getMaxDaysOfMonth(2020, 4);
int actualNumberOfDays3 = operationHelper.getMaxDaysOfMonth(2020, 2);
int actualNumberOfDays4 = operationHelper.getMaxDaysOfMonth(2019, 2);
assertEquals(31, actualNumberOfDays);
assertEquals(30, actualNumberOfDays2);
assertEquals(29, actualNumberOfDays3);
assertEquals(28, actualNumberOfDays4);
}
@Test
public void testGetQuantity() {
int id = 2432;
int month = 12;
int id2 = 99999;
assertEquals(24, operationHelper.getQuantity(id, month));
assertEquals(108, operationHelper.getQuantity(id2, month));
}
@Test
public void testGetRanomDay() {
int year = 2020;
int month = 5;
int month2 = 5;
assertNotEquals(operationHelper.getRandomDay(year, month), operationHelper.getRandomDay(year, month2));
}
@Test
public void testGetTimestamp() {
long[] testDates = operationHelper.getTimestamp(2020, 10, 20);
assertNotEquals(testDates[10], testDates[1]);
assertNotEquals(testDates[2], testDates[4]);
assertNotEquals(testDates[5], testDates[6]);
assertEquals(20, testDates.length);
}
@Test
public void testGetTransactionValue() {
int[] testValues = operationHelper.getTransactionValue(3245, 30);
assertNotEquals(testValues[0], testValues[1]);
assertNotEquals(testValues[2], testValues[4]);
assertNotEquals(testValues[5], testValues[6]);
assertEquals(30, testValues.length);
}
@Test
public void testGetDescription() {
String[] testDescriptions = operationHelper.getDescription(108);
assertNotEquals(testDescriptions[0], testDescriptions[1]);
assertNotEquals(testDescriptions[2], testDescriptions[4]);
assertNotEquals(testDescriptions[5], testDescriptions[6]);
assertNotEquals(testDescriptions[7], testDescriptions[8]);
assertNotEquals(testDescriptions[9], testDescriptions[10]);
assertNotEquals(testDescriptions[11], testDescriptions[12]);
assertNotEquals(testDescriptions[13], testDescriptions[14]);
assertNotEquals(testDescriptions[15], testDescriptions[16]);
assertNotEquals(testDescriptions[17], testDescriptions[18]);
assertNotNull(testDescriptions);
assertNotNull(testDescriptions[34]);
assertEquals(108, testDescriptions.length);
}
}
| 33.65812 | 116 | 0.608939 |
7bd1c69b72ba5d6dc54b04f0d8d000f6e49a62b0 | 14,281 | package org.arquillian.algeron.pact.provider.core.httptarget;
import au.com.dius.pact.model.RequestResponseInteraction;
import au.com.dius.pact.provider.ConsumerInfo;
import au.com.dius.pact.provider.HttpClientFactory;
import au.com.dius.pact.provider.ProviderClient;
import au.com.dius.pact.provider.ProviderInfo;
import au.com.dius.pact.provider.ProviderVerifier;
import au.com.dius.pact.provider.reporters.ReporterManager;
import au.com.dius.pact.provider.reporters.VerifierReporter;
import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpRequest;
import org.arquillian.algeron.configuration.SystemPropertyResolver;
import org.arquillian.algeron.pact.provider.core.recorder.ArquillianVerifierReporter;
import org.arquillian.algeron.pact.provider.spi.ArquillianTestClassAwareTarget;
import org.arquillian.algeron.pact.provider.spi.PactProviderExecutionAwareTarget;
import org.arquillian.algeron.pact.provider.spi.Provider;
import org.arquillian.algeron.pact.provider.spi.Target;
import org.arquillian.algeron.pact.provider.spi.TargetRequestFilter;
import org.arquillian.algeron.pact.provider.spi.VerificationReports;
import org.jboss.arquillian.core.api.Injector;
import org.jboss.arquillian.test.spi.TestClass;
public class HttpTarget implements Target, ArquillianTestClassAwareTarget, PactProviderExecutionAwareTarget {
private String path;
private String host;
private int port;
private String protocol;
private boolean insecure;
private final SystemPropertyResolver systemPropertyResolver = new SystemPropertyResolver();
private TestClass testClass;
private Object testInstance;
private au.com.dius.pact.model.Consumer currentConsumer;
private RequestResponseInteraction currentRequestResponseInteraction;
private Injector injector;
/**
* @param host
* host of tested service
* @param port
* port of tested service
*/
public HttpTarget(final String host, final int port) {
this("http", host, port);
}
/**
* Host of tested service is assumed as "localhost"
*
* @param port
* port of tested service
*/
public HttpTarget(final int port) {
this("http", "localhost", port);
}
/**
* @param host
* host of tested service
* @param port
* port of tested service
* @param protocol
* protocol of tested service
*/
public HttpTarget(final String protocol, final String host, final int port) {
this(protocol, host, port, "/");
}
/**
* @param host
* host of tested service
* @param port
* port of tested service
* @param protocol
* protocol of tested service
* @param path
* protocol of the tested service
*/
public HttpTarget(final String protocol, final String host, final int port, final String path) {
this(protocol, host, port, path, false);
}
/**
* @param host
* host of tested service
* @param port
* port of tested service
* @param protocol
* protocol of the tested service
* @param path
* path of the tested service
* @param insecure
* true if certificates should be ignored
*/
public HttpTarget(final String protocol, final String host, final int port, final String path,
final boolean insecure) {
this.host = host;
this.port = port;
this.protocol = protocol;
this.path = removeFinalSlash(path);
this.insecure = insecure;
}
// Due a bug in Pact we need to remove final slash character on path
private String removeFinalSlash(String path) {
if (path != null && !path.isEmpty() && path.endsWith("/")) {
return path.substring(0, path.length() -1);
}
return path;
}
/**
* @param url
* url of the tested service
*/
public HttpTarget(final URL url) {
this(url, false);
}
/**
* @param url
* url of the tested service
* @param insecure
* true if certificates should be ignored
*/
public HttpTarget(final URL url, final boolean insecure) {
this(url.getProtocol() == null ? "http" : url.getProtocol(),
url.getHost(),
url.getPort() == -1 ? 8080 : url.getPort(),
url.getPath() == null ? "/" : url.getPath(),
insecure);
}
@Override
public void testInteraction() {
if (this.currentConsumer == null || this.currentRequestResponseInteraction == null) {
throw new IllegalArgumentException(
"Current Consumer or Current Request Response Interaction has not been set.");
}
try {
testInteraction(this.currentConsumer.getName(), this.currentRequestResponseInteraction);
} finally {
// Each run should provide a new pair of objects.
resetCurrentFields();
}
}
@Override
public void testInteraction(URL url) {
if (this.currentConsumer == null || this.currentRequestResponseInteraction == null) {
throw new IllegalArgumentException(
"Current Consumer or Current Request Response Interaction has not been set.");
}
try {
testInteraction(url, this.currentConsumer.getName(), this.currentRequestResponseInteraction);
} finally {
// Each run should provide a new pair of objects.
resetCurrentFields();
}
}
private void resetCurrentFields() {
this.currentConsumer = null;
this.currentRequestResponseInteraction = null;
}
@Override
public void testInteraction(URL url, String consumer, RequestResponseInteraction interaction) {
this.protocol = url.getProtocol() == null ? "http" : url.getProtocol();
this.host = url.getHost();
this.port = url.getPort() == -1 ? 8080 : url.getPort();
this.path = removeFinalSlash(url.getPath() == null ? "/" : url.getPath());
this.testInteraction(consumer, interaction);
}
@Override
public void testInteraction(String consumerName, RequestResponseInteraction interaction) {
ProviderInfo provider = getProviderInfo();
ConsumerInfo consumer = new ConsumerInfo(consumerName);
ProviderVerifier verifier = setupVerifier(interaction, provider, consumer);
Map<String, Object> failures = new HashMap<>();
ProviderClient client = new ProviderClient(provider, new HttpClientFactory());
verifier.verifyResponseFromProvider(provider, interaction, interaction.getDescription(), failures, client);
try {
if (!failures.isEmpty()) {
verifier.displayFailures(failures);
throw getAssertionError(failures);
}
} finally {
verifier.finialiseReports();
}
}
private ProviderVerifier setupVerifier(RequestResponseInteraction interaction, ProviderInfo provider,
ConsumerInfo consumer) {
ProviderVerifier verifier = new ProviderVerifier();
setupReporters(verifier, provider.getName(), interaction.getDescription());
verifier.initialiseReporters(provider);
verifier.reportVerificationForConsumer(consumer, provider);
if (interaction.getProviderState() != null) {
verifier.reportStateForInteraction(interaction.getProviderState(), provider, consumer, true);
}
verifier.reportInteractionDescription(interaction);
return verifier;
}
private void setupReporters(ProviderVerifier verifier, String name, String description) {
String reportDirectory = "target/pact/reports";
String[] reports = new String[] {};
boolean reportingEnabled = false;
VerificationReports verificationReports = testClass.getAnnotation(VerificationReports.class);
if (verificationReports != null) {
reportingEnabled = true;
reportDirectory = verificationReports.reportDir();
reports = verificationReports.value();
} else if (systemPropertyResolver.propertyDefined("pact.verification.reports")) {
reportingEnabled = true;
reportDirectory = systemPropertyResolver.resolveValue("pact.verification.reportDir:" + reportDirectory);
reports = systemPropertyResolver.resolveValue("pact.verification.reports:").split(",");
}
if (reportingEnabled) {
File reportDir = new File(reportDirectory);
reportDir.mkdirs();
verifier.setReporters(Arrays.stream(reports)
.filter(r -> !r.isEmpty())
.map(r -> {
final String reportType = r.trim();
if ("recorder".equals(reportType)) {
return injector.inject(new ArquillianVerifierReporter());
} else {
VerifierReporter reporter = ReporterManager.createReporter(reportType);
reporter.setReportDir(reportDir);
reporter.setReportFile(new File(reportDir, name + " - " + description + reporter.getExt()));
return reporter;
}
}).collect(Collectors.toList()));
}
}
private ProviderInfo getProviderInfo() {
Provider provider = testClass.getAnnotation(Provider.class);
final ProviderInfo providerInfo = new ProviderInfo(provider.value());
providerInfo.setPort(port);
providerInfo.setHost(host);
providerInfo.setProtocol(protocol);
providerInfo.setPath(path);
providerInfo.setInsecure(insecure);
if (testClass != null && testInstance != null) {
final Method[] methods = testClass.getMethods(TargetRequestFilter.class);
if (methods != null && methods.length > 0) {
providerInfo.setRequestFilter(
(Consumer<HttpRequest>) httpRequest -> Arrays.stream(methods).forEach(method -> {
try {
method.invoke(testInstance, httpRequest);
} catch (Throwable t) {
throw new AssertionError(
"Request filter method " + method.getName() + " failed with an exception", t);
}
}));
}
}
return providerInfo;
}
private AssertionError getAssertionError(final Map<String, Object> mismatches) {
final Collection<Object> values = mismatches.values();
StringBuilder error = new StringBuilder(System.lineSeparator());
int i = 0;
for (Object value : values) {
String errPrefix = String.valueOf(i) + ": ";
error.append(errPrefix);
if (value instanceof Throwable) {
error.append(exceptionMessage((Throwable) value, errPrefix.length()));
} else if (value instanceof Map) {
error.append(convertMapToErrorString((Map) value));
} else {
error.append(value.toString());
}
error.append(System.lineSeparator());
i++;
}
return new AssertionError(error.toString());
}
private String exceptionMessage(Throwable err, int prefixLength) {
String message = err.getMessage();
if (message.contains("\n")) {
String padString = StringUtils.leftPad("", prefixLength);
final String[] split = message.split("\n");
StringBuilder messageError = new StringBuilder();
String firstElement = "";
if (split.length > 0) {
firstElement = split[0];
}
messageError.append(firstElement)
.append(System.lineSeparator());
for (int i = 1; i < split.length; i++) {
messageError.append(padString)
.append(split[i])
.append(System.lineSeparator());
}
return messageError.toString();
} else {
return message;
}
}
private String convertMapToErrorString(Map mismatches) {
if (mismatches.containsKey("comparison")) {
Object comparison = mismatches.get("comparison");
if (mismatches.containsKey("diff")) {
return String.format("%s%n%s", mapToString((Map) comparison),
listToString(((List) mismatches.get("diff"))));
} else {
if (comparison instanceof Map) {
return mapToString((Map) comparison);
} else {
return String.valueOf(comparison);
}
}
} else {
return mapToString(mismatches);
}
}
private String listToString(List<String> list) {
return list.stream().collect(Collectors.joining(System.lineSeparator())).toString();
}
private String mapToString(Map comparison) {
return comparison.entrySet().stream()
.map(e -> String.valueOf(((Map.Entry) e).getKey()) + " -> " + ((Map.Entry) e).getValue())
.collect(Collectors.joining(System.lineSeparator())).toString();
}
@Override
public void setTestClass(TestClass testClass, Object testInstance) {
this.testClass = testClass;
this.testInstance = testInstance;
}
@Override
public void setInjector(Injector injector) {
this.injector = injector;
}
@Override
public void setConsumer(au.com.dius.pact.model.Consumer consumer) {
this.currentConsumer = consumer;
}
@Override
public void setRequestResponseInteraction(RequestResponseInteraction requestResponseInteraction) {
this.currentRequestResponseInteraction = requestResponseInteraction;
}
}
| 35.972292 | 116 | 0.623976 |
89115f1156f10f66d72b00c6cfd40cb9e646db77 | 4,008 | package au.com.agilepractices.rules.engine.core.condition;
import au.com.agilepractices.rules.engine.core.auditor.RuleAuditor;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.mockito.quality.Strictness;
import org.mockito.stubbing.Answer;
import java.util.Arrays;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
public class OrConditionTest {
private static final String VALUE = "Foo";
@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS);
@Mock
private Condition<String> condition1;
@Mock
private Condition<String> condition2;
@Mock
private RuleAuditor<String> ruleAuditor;
private OrCondition<String> underTest;
@Before
public void setUp() {
underTest = new OrCondition<>(Arrays.asList(condition1, condition2));
}
@Test
public void testStaticConstructor() {
final OrCondition<String> underTest = OrCondition.or(condition1, condition2);
assertEquals(Arrays.asList(condition1, condition2), underTest.getConditions());
}
@Test
public void resultIsTrueAnd2ndConditionIsNotEvaluatedWhen1stConditionIsTrue() {
when(ruleAuditor.withResult(anyCondition(), anyBoolean())).then(returnResult());
when(condition1.test(VALUE, ruleAuditor)).thenReturn(true);
assertThat(underTest.test(VALUE, ruleAuditor)).isTrue();
verify(condition1).test(VALUE, ruleAuditor);
verifyZeroInteractions(condition2);
verify(ruleAuditor).withResult(condition1, true);
verify(ruleAuditor).withResult(underTest, true);
verifyNoMoreInteractions(ruleAuditor);
}
@Test
public void resultIsTrueWhen1stConditionIsFalseAnd2ndConditionIsTrue() {
when(ruleAuditor.withResult(anyCondition(), anyBoolean())).then(returnResult());
when(condition1.test(VALUE, ruleAuditor)).thenReturn(false);
when(condition2.test(VALUE, ruleAuditor)).thenReturn(true);
assertThat(underTest.test(VALUE, ruleAuditor)).isTrue();
verify(condition1).test(VALUE, ruleAuditor);
verify(condition2).test(VALUE, ruleAuditor);
verify(ruleAuditor).withResult(condition1, false);
verify(ruleAuditor).withResult(condition2, true);
verify(ruleAuditor).withResult(underTest, true);
verifyNoMoreInteractions(ruleAuditor);
}
@Test
public void resultIsFalseWhenAllConditionsAreFalse() {
when(ruleAuditor.withResult(anyCondition(), anyBoolean())).then(returnResult());
when(condition1.test(VALUE, ruleAuditor)).thenReturn(false);
when(condition2.test(VALUE, ruleAuditor)).thenReturn(false);
assertThat(underTest.test(VALUE, ruleAuditor)).isFalse();
verify(condition1).test(VALUE, ruleAuditor);
verify(condition2).test(VALUE, ruleAuditor);
verify(ruleAuditor).withResult(condition1, false);
verify(ruleAuditor).withResult(condition2, false);
verify(ruleAuditor).withResult(underTest, false);
verifyZeroInteractions(condition2);
}
@Test
public void toStringTest() {
when(condition1.toString()).thenReturn("condition1");
when(condition2.toString()).thenReturn("condition2");
assertThat(underTest.toString()).isEqualTo("( condition1 ) or ( condition2 )");
}
private Answer<Boolean> returnResult() {
return invocationOnMock -> invocationOnMock.getArgument(1);
}
private Condition<String> anyCondition() {
return any();
}
}
| 36.108108 | 93 | 0.72505 |
4fbb8cef9628373d82fdcb731ff9a9e9eb5d8c8b | 1,987 | /* $Id: TransformerModule.java 18622 2010-08-03 18:56:14Z mvw $
*****************************************************************************
* Copyright (c) 2010 Contributors - see below
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Michiel van der Wulp
* Bob Tarling
*****************************************************************************
*/
package org.argouml.transformer;
import org.apache.log4j.Logger;
import org.argouml.moduleloader.ModuleInterface;
import org.argouml.ui.ContextActionFactoryManager;
public class TransformerModule implements ModuleInterface {
private static final Logger LOG = Logger
.getLogger(TransformerModule.class);
public boolean enable() {
TransformerManager.getInstance().addTransformer(
new EventTransformer());
TransformerManager.getInstance().addTransformer(
new SimpleStateTransformer());
ContextActionFactoryManager.addContextPopupFactory(TransformerManager.getInstance());
LOG.info("Transformer Module enabled.");
return true;
}
public boolean disable() {
ContextActionFactoryManager.removeContextPopupFactory(TransformerManager.getInstance());
LOG.info("Transformer Module disabled.");
return true;
}
public String getName() {
return "ArgoUML-Transformer";
}
public String getInfo(int type) {
switch (type) {
case DESCRIPTION:
return "The model element transformer";
case AUTHOR:
return "The ArgoUML Team";
case VERSION:
return "0.32";
case DOWNLOADSITE:
return "http://argouml.tigris.org";
default:
return null;
}
}
}
| 31.046875 | 96 | 0.611978 |
48109e900e526e940a99dcb5646dd82d0388fbe4 | 4,841 | package org.openstreetmap.atlas.checks.validation.linear;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import org.openstreetmap.atlas.checks.base.BaseCheck;
import org.openstreetmap.atlas.checks.flag.CheckFlag;
import org.openstreetmap.atlas.geography.atlas.items.AtlasObject;
import org.openstreetmap.atlas.geography.atlas.items.Edge;
import org.openstreetmap.atlas.geography.atlas.items.Line;
import org.openstreetmap.atlas.geography.atlas.items.LineItem;
import org.openstreetmap.atlas.tags.NaturalTag;
import org.openstreetmap.atlas.tags.WaterTag;
import org.openstreetmap.atlas.tags.WaterwayTag;
import org.openstreetmap.atlas.tags.annotations.validation.Validators;
import org.openstreetmap.atlas.utilities.collections.Iterables;
import org.openstreetmap.atlas.utilities.configuration.Configuration;
import org.openstreetmap.atlas.utilities.scalars.Distance;
/**
* Flag lines that have only one point, or none, and the ones that are too long.
*
* @author matthieun
* @author cuthbertm
*/
public class MalformedPolyLineCheck extends BaseCheck<Long>
{
private static final Distance MAXIMUM_LENGTH = Distance.kilometers(100);
private static final int MAXIMUM_POINTS = 500;
private static final String MAX_LENGTH_INSTRUCTION = "Line is {0}, which is longer than the maximum of {1}";
private static final String MAX_POINTS_INSTRUCTION = "Line contains {0} points more than maximum of {1}";
private static final String MAX_POINTS_MAX_LENGTH_INSTRUCTION = "Line contains {0} points more than maximum of {1} and line is {2}, which is longer than the maximum of {3}";
private static final List<String> FALLBACK_INSTRUCTIONS = Arrays.asList(MAX_POINTS_INSTRUCTION,
MAX_LENGTH_INSTRUCTION, MAX_POINTS_MAX_LENGTH_INSTRUCTION);
private static final long serialVersionUID = -6190296606600063334L;
private static final WaterwayTag[] WATERWAY_TAGS = { WaterwayTag.CANAL, WaterwayTag.STREAM,
WaterwayTag.RIVER, WaterwayTag.RIVERBANK };
public MalformedPolyLineCheck(final Configuration configuration)
{
super(configuration);
}
@Override
public boolean validCheckForObject(final AtlasObject object)
{
return object instanceof Edge && ((Edge) object).isMasterEdge() || object instanceof Line;
}
@Override
protected Optional<CheckFlag> flag(final AtlasObject object)
{
final LineItem line = (LineItem) object;
final int numberPoints = Iterables.asList(line.getRawGeometry()).size();
final Distance length = line.asPolyLine().length();
// We exclude certain complex PolyLines from the check.
if (this.isComplexPolyLine(line) || this.isMemberOfRelationWithWaterTag(line))
{
return Optional.empty();
}
if (numberPoints > MAXIMUM_POINTS && length.isGreaterThan(MAXIMUM_LENGTH))
{
return Optional.of(createFlag(object, this.getLocalizedInstruction(2, numberPoints,
MAXIMUM_POINTS, length, MAXIMUM_LENGTH)));
}
if (numberPoints < 1 || numberPoints > MAXIMUM_POINTS)
{
return Optional.of(createFlag(object,
this.getLocalizedInstruction(0, numberPoints, MAXIMUM_POINTS)));
}
if (length.isGreaterThan(MAXIMUM_LENGTH))
{
return Optional.of(
createFlag(object, this.getLocalizedInstruction(1, length, MAXIMUM_LENGTH)));
}
return Optional.empty();
}
@Override
protected List<String> getFallbackInstructions()
{
return FALLBACK_INSTRUCTIONS;
}
/**
* Certain polylines like river, coastline, stream etc should be excluded from the check, as
* they can be irregular and long, but still valid polylines. This method checks if a polyline
* is part of such entities.
*
* @param line
* @return {@code true} if this object meets the conditions for complex polyline
*/
private boolean isComplexPolyLine(final LineItem line)
{
return Validators.isOfType(line, WaterwayTag.class, WATERWAY_TAGS)
|| Validators.isOfType(line, NaturalTag.class, NaturalTag.COASTLINE)
|| Validators.isOfType(line, NaturalTag.class, NaturalTag.WATER)
&& Validators.isOfType(line, WaterTag.class, WaterTag.RIVER);
}
/**
* Checks if {@link LineItem} is part of relation having WaterTag associated with it
*
* @param line
* @return {@code true} if the LineItem is part of relation with WaterTag
*/
private boolean isMemberOfRelationWithWaterTag(final LineItem line)
{
return line.relations().stream().anyMatch(
relation -> Validators.isOfType(relation, NaturalTag.class, NaturalTag.WATER));
}
}
| 42.464912 | 177 | 0.708118 |
1e5ce8618a44652a207f0a0410f723245e065207 | 4,022 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.resourcemanager.eventhubs.implementation;
import com.azure.core.http.rest.PagedFlux;
import com.azure.core.http.rest.PagedIterable;
import com.azure.resourcemanager.eventhubs.EventHubsManager;
import com.azure.resourcemanager.eventhubs.fluent.EventHubsClient;
import com.azure.resourcemanager.eventhubs.fluent.inner.AuthorizationRuleInner;
import com.azure.resourcemanager.eventhubs.models.EventHubAuthorizationRule;
import com.azure.resourcemanager.eventhubs.models.EventHubAuthorizationRules;
import com.azure.resourcemanager.resources.fluentcore.arm.ResourceId;
import reactor.core.publisher.Mono;
import java.util.Objects;
/**
* Implementation for {@link EventHubAuthorizationRules}.
*/
public final class EventHubAuthorizationRulesImpl
extends AuthorizationRulesBaseImpl<EventHubsClient,
EventHubAuthorizationRule,
EventHubAuthorizationRuleImpl>
implements EventHubAuthorizationRules {
public EventHubAuthorizationRulesImpl(EventHubsManager manager) {
super(manager, manager.inner().getEventHubs());
}
@Override
public EventHubAuthorizationRuleImpl define(String name) {
return new EventHubAuthorizationRuleImpl(name, this.manager);
}
@Override
public Mono<EventHubAuthorizationRule> getByIdAsync(String id) {
Objects.requireNonNull(id);
ResourceId resourceId = ResourceId.fromString(id);
return getByNameAsync(resourceId.resourceGroupName(),
resourceId.parent().parent().name(),
resourceId.parent().name(),
resourceId.name());
}
@Override
public EventHubAuthorizationRule getByName(
String resourceGroupName, String namespaceName, String eventHubName, String name) {
return getByNameAsync(resourceGroupName, namespaceName, eventHubName, name).block();
}
@Override
public Mono<EventHubAuthorizationRule> getByNameAsync(
String resourceGroupName, String namespaceName, String eventHubName, String name) {
return this.inner().getAuthorizationRuleAsync(resourceGroupName, namespaceName, eventHubName, name)
.map(this::wrapModel);
}
@Override
public PagedIterable<EventHubAuthorizationRule> listByEventHub(
final String resourceGroupName, final String namespaceName, final String eventHubName) {
return inner()
.listAuthorizationRules(resourceGroupName, namespaceName, eventHubName)
.mapPage(this::wrapModel);
}
@Override
public PagedFlux<EventHubAuthorizationRule> listByEventHubAsync(
String resourceGroupName, String namespaceName, final String eventHubName) {
return this.inner()
.listAuthorizationRulesAsync(resourceGroupName, namespaceName, eventHubName)
.mapPage(this::wrapModel);
}
@Override
public Mono<Void> deleteByIdAsync(String id) {
Objects.requireNonNull(id);
ResourceId resourceId = ResourceId.fromString(id);
return deleteByNameAsync(resourceId.resourceGroupName(),
resourceId.parent().parent().name(),
resourceId.parent().name(),
resourceId.name());
}
@Override
public void deleteByName(String resourceGroupName, String namespaceName, String eventHubName, String name) {
deleteByNameAsync(resourceGroupName, namespaceName, eventHubName, name).block();
}
@Override
public Mono<Void> deleteByNameAsync(
String resourceGroupName, String namespaceName, String eventHubName, String name) {
return this.inner().deleteAuthorizationRuleAsync(resourceGroupName,
namespaceName,
eventHubName,
name);
}
@Override
protected EventHubAuthorizationRuleImpl wrapModel(AuthorizationRuleInner innerModel) {
return new EventHubAuthorizationRuleImpl(innerModel.name(), innerModel, this.manager);
}
}
| 38.304762 | 112 | 0.731974 |
314a695d622f9e693bb66ecf2e2958eaf7ee4adc | 1,964 | package com.utopia.recovery.core;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import com.utopia.recovery.tools.RecoveryLog;
import com.utopia.recovery.tools.RecoveryUtil;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
/**
* ActivityManager动态代理
*/
class ActivityManagerDelegate implements InvocationHandler {
private final Object mBaseActivityManagerProxy;
ActivityManagerDelegate(Object o) {
this.mBaseActivityManagerProxy = o;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if ("finishActivity".equals(method.getName())) {
Class<? extends Activity> clazz = Recovery.getInstance().getMainPageClass();
if (clazz == null) {
return method.invoke(mBaseActivityManagerProxy, args);
}
Context context = Recovery.getInstance().getContext();
int count = ActivityStackCompat.getActivityCount(context);
String baseActivityName = ActivityStackCompat.getBaseActivityName(context);
if (TextUtils.isEmpty(baseActivityName)) {
return method.invoke(mBaseActivityManagerProxy, args);
}
RecoveryLog.e("currentActivityCount: " + count);
RecoveryLog.e("baseActivityName: " + baseActivityName);
if (count == 1 && !clazz.getName().equals(baseActivityName)) {
Intent intent = new Intent(Recovery.getInstance().getContext(), clazz);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
if (RecoveryUtil.isIntentAvailable(Recovery.getInstance().getContext(), intent))
Recovery.getInstance().getContext().startActivity(intent);
}
}
return method.invoke(mBaseActivityManagerProxy, args);
}
}
| 37.056604 | 97 | 0.677699 |
446dc6a5c86ca930a84163c560ac8455ec932e66 | 1,006 | package net.glowstone.command.minecraft;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.command.defaults.VanillaCommand;
import java.util.Collections;
import java.util.List;
public class SaveAllCommand extends VanillaCommand
{
public SaveAllCommand()
{
super( "save-all", "Saves the server to disk.", "/save-all", Collections.emptyList() );
setPermission( "minecraft.command.save-all" );
}
@Override
public boolean execute( CommandSender sender, String label, String[] args )
{
if ( !testPermission( sender ) )
{
return false;
}
sender.sendMessage( "Saving..." );
for ( World world : sender.getServer().getWorlds() )
{
world.save();
sender.sendMessage( "Saved world '" + world.getName() + "'" );
}
sender.sendMessage( "Saved the worlds" );
return true;
}
@Override
public List<String> tabComplete( CommandSender sender, String alias, String[] args ) throws IllegalArgumentException
{
return Collections.emptyList();
}
}
| 24.536585 | 117 | 0.714712 |
6f5e6c18cdb0571252ce88f0bd1fadce112e31a1 | 672 | package org.opendata.web;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import java.util.Date;
@Controller
public class WelcomeController {
@RequestMapping("/welcome")
public ModelAndView test() {
return new ModelAndView("index");
}
@RequestMapping(method = RequestMethod.GET)
public String showMenu(Model model) {
model.addAttribute("today", new Date());
return "index";
}
} | 26.88 | 63 | 0.717262 |
01eb443c96756509af1d2567d2bdc145f4c6a9f6 | 580 | /**
* *************************************************
* Copyright (c) 2019, Grindrod Bank Limited
* License MIT: https://opensource.org/licenses/MIT
* **************************************************
*/
package org.tilkynna.common.storage;
public class ContentStorageException extends RuntimeException {
private static final long serialVersionUID = 7927067730656869797L;
public ContentStorageException(String message) {
super(message);
}
public ContentStorageException(String message, Throwable cause) {
super(message, cause);
}
}
| 27.619048 | 70 | 0.594828 |
67abeef3f97131f54b43b57ba7480e4b6da011ce | 26,786 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.nuklear;
import java.nio.*;
import org.lwjgl.*;
import org.lwjgl.system.*;
import static org.lwjgl.system.MemoryUtil.*;
import static org.lwjgl.system.MemoryStack.*;
/**
* <h3>Layout</h3>
*
* <pre><code>struct nk_style_progress {
{@link NkStyleItem struct nk_style_item} normal;
{@link NkStyleItem struct nk_style_item} hover;
{@link NkStyleItem struct nk_style_item} active;
{@link NkColor struct nk_color} border_color;
{@link NkStyleItem struct nk_style_item} cursor_normal;
{@link NkStyleItem struct nk_style_item} cursor_hover;
{@link NkStyleItem struct nk_style_item} cursor_active;
{@link NkColor struct nk_color} cursor_border_color;
float rounding;
float border;
float cursor_border;
float cursor_rounding;
{@link NkVec2 struct nk_vec2} padding;
{@link NkHandle nk_handle} userdata;
nk_draw_begin draw_begin;
nk_draw_end draw_end;
}</code></pre>
*/
public class NkStyleProgress extends Struct implements NativeResource {
/** The struct size in bytes. */
public static final int SIZEOF;
public static final int ALIGNOF;
/** The struct member offsets. */
public static final int
NORMAL,
HOVER,
ACTIVE,
BORDER_COLOR,
CURSOR_NORMAL,
CURSOR_HOVER,
CURSOR_ACTIVE,
CURSOR_BORDER_COLOR,
ROUNDING,
BORDER,
CURSOR_BORDER,
CURSOR_ROUNDING,
PADDING,
USERDATA,
DRAW_BEGIN,
DRAW_END;
static {
Layout layout = __struct(
__member(NkStyleItem.SIZEOF, NkStyleItem.ALIGNOF),
__member(NkStyleItem.SIZEOF, NkStyleItem.ALIGNOF),
__member(NkStyleItem.SIZEOF, NkStyleItem.ALIGNOF),
__member(NkColor.SIZEOF, NkColor.ALIGNOF),
__member(NkStyleItem.SIZEOF, NkStyleItem.ALIGNOF),
__member(NkStyleItem.SIZEOF, NkStyleItem.ALIGNOF),
__member(NkStyleItem.SIZEOF, NkStyleItem.ALIGNOF),
__member(NkColor.SIZEOF, NkColor.ALIGNOF),
__member(4),
__member(4),
__member(4),
__member(4),
__member(NkVec2.SIZEOF, NkVec2.ALIGNOF),
__member(NkHandle.SIZEOF, NkHandle.ALIGNOF),
__member(POINTER_SIZE),
__member(POINTER_SIZE)
);
SIZEOF = layout.getSize();
ALIGNOF = layout.getAlignment();
NORMAL = layout.offsetof(0);
HOVER = layout.offsetof(1);
ACTIVE = layout.offsetof(2);
BORDER_COLOR = layout.offsetof(3);
CURSOR_NORMAL = layout.offsetof(4);
CURSOR_HOVER = layout.offsetof(5);
CURSOR_ACTIVE = layout.offsetof(6);
CURSOR_BORDER_COLOR = layout.offsetof(7);
ROUNDING = layout.offsetof(8);
BORDER = layout.offsetof(9);
CURSOR_BORDER = layout.offsetof(10);
CURSOR_ROUNDING = layout.offsetof(11);
PADDING = layout.offsetof(12);
USERDATA = layout.offsetof(13);
DRAW_BEGIN = layout.offsetof(14);
DRAW_END = layout.offsetof(15);
}
NkStyleProgress(long address, ByteBuffer container) {
super(address, container);
}
/**
* Creates a {@link NkStyleProgress} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be
* visible to the struct instance and vice versa.
*
* <p>The created instance holds a strong reference to the container object.</p>
*/
public NkStyleProgress(ByteBuffer container) {
this(memAddress(container), checkContainer(container, SIZEOF));
}
@Override
public int sizeof() { return SIZEOF; }
/** Returns a {@link NkStyleItem} view of the {@code normal} field. */
public NkStyleItem normal() { return nnormal(address()); }
/** Returns a {@link NkStyleItem} view of the {@code hover} field. */
public NkStyleItem hover() { return nhover(address()); }
/** Returns a {@link NkStyleItem} view of the {@code active} field. */
public NkStyleItem active() { return nactive(address()); }
/** Returns a {@link NkColor} view of the {@code border_color} field. */
public NkColor border_color() { return nborder_color(address()); }
/** Returns a {@link NkStyleItem} view of the {@code cursor_normal} field. */
public NkStyleItem cursor_normal() { return ncursor_normal(address()); }
/** Returns a {@link NkStyleItem} view of the {@code cursor_hover} field. */
public NkStyleItem cursor_hover() { return ncursor_hover(address()); }
/** Returns a {@link NkStyleItem} view of the {@code cursor_active} field. */
public NkStyleItem cursor_active() { return ncursor_active(address()); }
/** Returns a {@link NkColor} view of the {@code cursor_border_color} field. */
public NkColor cursor_border_color() { return ncursor_border_color(address()); }
/** Returns the value of the {@code rounding} field. */
public float rounding() { return nrounding(address()); }
/** Returns the value of the {@code border} field. */
public float border() { return nborder(address()); }
/** Returns the value of the {@code cursor_border} field. */
public float cursor_border() { return ncursor_border(address()); }
/** Returns the value of the {@code cursor_rounding} field. */
public float cursor_rounding() { return ncursor_rounding(address()); }
/** Returns a {@link NkVec2} view of the {@code padding} field. */
public NkVec2 padding() { return npadding(address()); }
/** Returns a {@link NkHandle} view of the {@code userdata} field. */
public NkHandle userdata() { return nuserdata(address()); }
/** Returns the {@code NkDrawBeginCallback} instance at the {@code draw_begin} field. */
public NkDrawBeginCallback draw_begin() { return NkDrawBeginCallback.create(ndraw_begin(address())); }
/** Returns the {@code NkDrawEndCallback} instance at the {@code draw_end} field. */
public NkDrawEndCallback draw_end() { return NkDrawEndCallback.create(ndraw_end(address())); }
/** Copies the specified {@link NkStyleItem} to the {@code normal} field. */
public NkStyleProgress normal(NkStyleItem value) { nnormal(address(), value); return this; }
/** Copies the specified {@link NkStyleItem} to the {@code hover} field. */
public NkStyleProgress hover(NkStyleItem value) { nhover(address(), value); return this; }
/** Copies the specified {@link NkStyleItem} to the {@code active} field. */
public NkStyleProgress active(NkStyleItem value) { nactive(address(), value); return this; }
/** Copies the specified {@link NkColor} to the {@code border_color} field. */
public NkStyleProgress border_color(NkColor value) { nborder_color(address(), value); return this; }
/** Copies the specified {@link NkStyleItem} to the {@code cursor_normal} field. */
public NkStyleProgress cursor_normal(NkStyleItem value) { ncursor_normal(address(), value); return this; }
/** Copies the specified {@link NkStyleItem} to the {@code cursor_hover} field. */
public NkStyleProgress cursor_hover(NkStyleItem value) { ncursor_hover(address(), value); return this; }
/** Copies the specified {@link NkStyleItem} to the {@code cursor_active} field. */
public NkStyleProgress cursor_active(NkStyleItem value) { ncursor_active(address(), value); return this; }
/** Copies the specified {@link NkColor} to the {@code cursor_border_color} field. */
public NkStyleProgress cursor_border_color(NkColor value) { ncursor_border_color(address(), value); return this; }
/** Sets the specified value to the {@code rounding} field. */
public NkStyleProgress rounding(float value) { nrounding(address(), value); return this; }
/** Sets the specified value to the {@code border} field. */
public NkStyleProgress border(float value) { nborder(address(), value); return this; }
/** Sets the specified value to the {@code cursor_border} field. */
public NkStyleProgress cursor_border(float value) { ncursor_border(address(), value); return this; }
/** Sets the specified value to the {@code cursor_rounding} field. */
public NkStyleProgress cursor_rounding(float value) { ncursor_rounding(address(), value); return this; }
/** Copies the specified {@link NkVec2} to the {@code padding} field. */
public NkStyleProgress padding(NkVec2 value) { npadding(address(), value); return this; }
/** Copies the specified {@link NkHandle} to the {@code userdata} field. */
public NkStyleProgress userdata(NkHandle value) { nuserdata(address(), value); return this; }
/** Sets the address of the specified {@link NkDrawBeginCallbackI} to the {@code draw_begin} field. */
public NkStyleProgress draw_begin(NkDrawBeginCallbackI value) { ndraw_begin(address(), addressSafe(value)); return this; }
/** Sets the address of the specified {@link NkDrawEndCallbackI} to the {@code draw_end} field. */
public NkStyleProgress draw_end(NkDrawEndCallbackI value) { ndraw_end(address(), addressSafe(value)); return this; }
/** Unsafe version of {@link #set(NkStyleProgress) set}. */
public NkStyleProgress nset(long struct) {
memCopy(struct, address(), SIZEOF);
return this;
}
/**
* Copies the specified struct data to this struct.
*
* @param src the source struct
*
* @return this struct
*/
public NkStyleProgress set(NkStyleProgress src) {
return nset(src.address());
}
// -----------------------------------
/** Returns a new {@link NkStyleProgress} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. */
public static NkStyleProgress malloc() {
return create(nmemAlloc(SIZEOF));
}
/** Returns a new {@link NkStyleProgress} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. */
public static NkStyleProgress calloc() {
return create(nmemCalloc(1, SIZEOF));
}
/** Returns a new {@link NkStyleProgress} instance allocated with {@link BufferUtils}. */
public static NkStyleProgress create() {
return new NkStyleProgress(BufferUtils.createByteBuffer(SIZEOF));
}
/** Returns a new {@link NkStyleProgress} instance for the specified memory address or {@code null} if the address is {@code NULL}. */
public static NkStyleProgress create(long address) {
return address == NULL ? null : new NkStyleProgress(address, null);
}
/**
* Returns a new {@link NkStyleProgress.Buffer} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed.
*
* @param capacity the buffer capacity
*/
public static Buffer malloc(int capacity) {
return create(nmemAlloc(capacity * SIZEOF), capacity);
}
/**
* Returns a new {@link NkStyleProgress.Buffer} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed.
*
* @param capacity the buffer capacity
*/
public static Buffer calloc(int capacity) {
return create(nmemCalloc(capacity, SIZEOF), capacity);
}
/**
* Returns a new {@link NkStyleProgress.Buffer} instance allocated with {@link BufferUtils}.
*
* @param capacity the buffer capacity
*/
public static Buffer create(int capacity) {
return new Buffer(BufferUtils.createByteBuffer(capacity * SIZEOF));
}
/**
* Create a {@link NkStyleProgress.Buffer} instance at the specified memory.
*
* @param address the memory address
* @param capacity the buffer capacity
*/
public static Buffer create(long address, int capacity) {
return address == NULL ? null : new Buffer(address, null, -1, 0, capacity, capacity);
}
// -----------------------------------
/** Returns a new {@link NkStyleProgress} instance allocated on the thread-local {@link MemoryStack}. */
public static NkStyleProgress mallocStack() {
return mallocStack(stackGet());
}
/** Returns a new {@link NkStyleProgress} instance allocated on the thread-local {@link MemoryStack} and initializes all its bits to zero. */
public static NkStyleProgress callocStack() {
return callocStack(stackGet());
}
/**
* Returns a new {@link NkStyleProgress} instance allocated on the specified {@link MemoryStack}.
*
* @param stack the stack from which to allocate
*/
public static NkStyleProgress mallocStack(MemoryStack stack) {
return create(stack.nmalloc(ALIGNOF, SIZEOF));
}
/**
* Returns a new {@link NkStyleProgress} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
*
* @param stack the stack from which to allocate
*/
public static NkStyleProgress callocStack(MemoryStack stack) {
return create(stack.ncalloc(ALIGNOF, 1, SIZEOF));
}
/**
* Returns a new {@link NkStyleProgress.Buffer} instance allocated on the thread-local {@link MemoryStack}.
*
* @param capacity the buffer capacity
*/
public static Buffer mallocStack(int capacity) {
return mallocStack(capacity, stackGet());
}
/**
* Returns a new {@link NkStyleProgress.Buffer} instance allocated on the thread-local {@link MemoryStack} and initializes all its bits to zero.
*
* @param capacity the buffer capacity
*/
public static Buffer callocStack(int capacity) {
return callocStack(capacity, stackGet());
}
/**
* Returns a new {@link NkStyleProgress.Buffer} instance allocated on the specified {@link MemoryStack}.
*
* @param stack the stack from which to allocate
* @param capacity the buffer capacity
*/
public static Buffer mallocStack(int capacity, MemoryStack stack) {
return create(stack.nmalloc(ALIGNOF, capacity * SIZEOF), capacity);
}
/**
* Returns a new {@link NkStyleProgress.Buffer} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
*
* @param stack the stack from which to allocate
* @param capacity the buffer capacity
*/
public static Buffer callocStack(int capacity, MemoryStack stack) {
return create(stack.ncalloc(ALIGNOF, capacity, SIZEOF), capacity);
}
// -----------------------------------
/** Unsafe version of {@link #normal}. */
public static NkStyleItem nnormal(long struct) { return NkStyleItem.create(struct + NkStyleProgress.NORMAL); }
/** Unsafe version of {@link #hover}. */
public static NkStyleItem nhover(long struct) { return NkStyleItem.create(struct + NkStyleProgress.HOVER); }
/** Unsafe version of {@link #active}. */
public static NkStyleItem nactive(long struct) { return NkStyleItem.create(struct + NkStyleProgress.ACTIVE); }
/** Unsafe version of {@link #border_color}. */
public static NkColor nborder_color(long struct) { return NkColor.create(struct + NkStyleProgress.BORDER_COLOR); }
/** Unsafe version of {@link #cursor_normal}. */
public static NkStyleItem ncursor_normal(long struct) { return NkStyleItem.create(struct + NkStyleProgress.CURSOR_NORMAL); }
/** Unsafe version of {@link #cursor_hover}. */
public static NkStyleItem ncursor_hover(long struct) { return NkStyleItem.create(struct + NkStyleProgress.CURSOR_HOVER); }
/** Unsafe version of {@link #cursor_active}. */
public static NkStyleItem ncursor_active(long struct) { return NkStyleItem.create(struct + NkStyleProgress.CURSOR_ACTIVE); }
/** Unsafe version of {@link #cursor_border_color}. */
public static NkColor ncursor_border_color(long struct) { return NkColor.create(struct + NkStyleProgress.CURSOR_BORDER_COLOR); }
/** Unsafe version of {@link #rounding}. */
public static float nrounding(long struct) { return memGetFloat(struct + NkStyleProgress.ROUNDING); }
/** Unsafe version of {@link #border}. */
public static float nborder(long struct) { return memGetFloat(struct + NkStyleProgress.BORDER); }
/** Unsafe version of {@link #cursor_border}. */
public static float ncursor_border(long struct) { return memGetFloat(struct + NkStyleProgress.CURSOR_BORDER); }
/** Unsafe version of {@link #cursor_rounding}. */
public static float ncursor_rounding(long struct) { return memGetFloat(struct + NkStyleProgress.CURSOR_ROUNDING); }
/** Unsafe version of {@link #padding}. */
public static NkVec2 npadding(long struct) { return NkVec2.create(struct + NkStyleProgress.PADDING); }
/** Unsafe version of {@link #userdata}. */
public static NkHandle nuserdata(long struct) { return NkHandle.create(struct + NkStyleProgress.USERDATA); }
/** Unsafe version of {@link #draw_begin}. */
public static long ndraw_begin(long struct) { return memGetAddress(struct + NkStyleProgress.DRAW_BEGIN); }
/** Unsafe version of {@link #draw_end}. */
public static long ndraw_end(long struct) { return memGetAddress(struct + NkStyleProgress.DRAW_END); }
/** Unsafe version of {@link #normal(NkStyleItem) normal}. */
public static void nnormal(long struct, NkStyleItem value) { memCopy(value.address(), struct + NkStyleProgress.NORMAL, NkStyleItem.SIZEOF); }
/** Unsafe version of {@link #hover(NkStyleItem) hover}. */
public static void nhover(long struct, NkStyleItem value) { memCopy(value.address(), struct + NkStyleProgress.HOVER, NkStyleItem.SIZEOF); }
/** Unsafe version of {@link #active(NkStyleItem) active}. */
public static void nactive(long struct, NkStyleItem value) { memCopy(value.address(), struct + NkStyleProgress.ACTIVE, NkStyleItem.SIZEOF); }
/** Unsafe version of {@link #border_color(NkColor) border_color}. */
public static void nborder_color(long struct, NkColor value) { memCopy(value.address(), struct + NkStyleProgress.BORDER_COLOR, NkColor.SIZEOF); }
/** Unsafe version of {@link #cursor_normal(NkStyleItem) cursor_normal}. */
public static void ncursor_normal(long struct, NkStyleItem value) { memCopy(value.address(), struct + NkStyleProgress.CURSOR_NORMAL, NkStyleItem.SIZEOF); }
/** Unsafe version of {@link #cursor_hover(NkStyleItem) cursor_hover}. */
public static void ncursor_hover(long struct, NkStyleItem value) { memCopy(value.address(), struct + NkStyleProgress.CURSOR_HOVER, NkStyleItem.SIZEOF); }
/** Unsafe version of {@link #cursor_active(NkStyleItem) cursor_active}. */
public static void ncursor_active(long struct, NkStyleItem value) { memCopy(value.address(), struct + NkStyleProgress.CURSOR_ACTIVE, NkStyleItem.SIZEOF); }
/** Unsafe version of {@link #cursor_border_color(NkColor) cursor_border_color}. */
public static void ncursor_border_color(long struct, NkColor value) { memCopy(value.address(), struct + NkStyleProgress.CURSOR_BORDER_COLOR, NkColor.SIZEOF); }
/** Unsafe version of {@link #rounding(float) rounding}. */
public static void nrounding(long struct, float value) { memPutFloat(struct + NkStyleProgress.ROUNDING, value); }
/** Unsafe version of {@link #border(float) border}. */
public static void nborder(long struct, float value) { memPutFloat(struct + NkStyleProgress.BORDER, value); }
/** Unsafe version of {@link #cursor_border(float) cursor_border}. */
public static void ncursor_border(long struct, float value) { memPutFloat(struct + NkStyleProgress.CURSOR_BORDER, value); }
/** Unsafe version of {@link #cursor_rounding(float) cursor_rounding}. */
public static void ncursor_rounding(long struct, float value) { memPutFloat(struct + NkStyleProgress.CURSOR_ROUNDING, value); }
/** Unsafe version of {@link #padding(NkVec2) padding}. */
public static void npadding(long struct, NkVec2 value) { memCopy(value.address(), struct + NkStyleProgress.PADDING, NkVec2.SIZEOF); }
/** Unsafe version of {@link #userdata(NkHandle) userdata}. */
public static void nuserdata(long struct, NkHandle value) { memCopy(value.address(), struct + NkStyleProgress.USERDATA, NkHandle.SIZEOF); }
/** Unsafe version of {@link #draw_begin(NkDrawBeginCallbackI) draw_begin}. */
public static void ndraw_begin(long struct, long value) { memPutAddress(struct + NkStyleProgress.DRAW_BEGIN, value); }
/** Unsafe version of {@link #draw_end(NkDrawEndCallbackI) draw_end}. */
public static void ndraw_end(long struct, long value) { memPutAddress(struct + NkStyleProgress.DRAW_END, value); }
// -----------------------------------
/** An array of {@link NkStyleProgress} structs. */
public static class Buffer extends StructBuffer<NkStyleProgress, Buffer> implements NativeResource {
/**
* Creates a new {@link NkStyleProgress.Buffer} instance backed by the specified container.
*
* Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values
* will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided
* by {@link NkStyleProgress#SIZEOF}, and its mark will be undefined.
*
* <p>The created buffer instance holds a strong reference to the container object.</p>
*/
public Buffer(ByteBuffer container) {
super(container, container.remaining() / SIZEOF);
}
Buffer(long address, ByteBuffer container, int mark, int pos, int lim, int cap) {
super(address, container, mark, pos, lim, cap);
}
@Override
protected Buffer self() {
return this;
}
@Override
protected Buffer newBufferInstance(long address, ByteBuffer container, int mark, int pos, int lim, int cap) {
return new Buffer(address, container, mark, pos, lim, cap);
}
@Override
protected NkStyleProgress newInstance(long address) {
return new NkStyleProgress(address, container);
}
@Override
protected int sizeof() {
return SIZEOF;
}
/** Returns a {@link NkStyleItem} view of the {@code normal} field. */
public NkStyleItem normal() { return NkStyleProgress.nnormal(address()); }
/** Returns a {@link NkStyleItem} view of the {@code hover} field. */
public NkStyleItem hover() { return NkStyleProgress.nhover(address()); }
/** Returns a {@link NkStyleItem} view of the {@code active} field. */
public NkStyleItem active() { return NkStyleProgress.nactive(address()); }
/** Returns a {@link NkColor} view of the {@code border_color} field. */
public NkColor border_color() { return NkStyleProgress.nborder_color(address()); }
/** Returns a {@link NkStyleItem} view of the {@code cursor_normal} field. */
public NkStyleItem cursor_normal() { return NkStyleProgress.ncursor_normal(address()); }
/** Returns a {@link NkStyleItem} view of the {@code cursor_hover} field. */
public NkStyleItem cursor_hover() { return NkStyleProgress.ncursor_hover(address()); }
/** Returns a {@link NkStyleItem} view of the {@code cursor_active} field. */
public NkStyleItem cursor_active() { return NkStyleProgress.ncursor_active(address()); }
/** Returns a {@link NkColor} view of the {@code cursor_border_color} field. */
public NkColor cursor_border_color() { return NkStyleProgress.ncursor_border_color(address()); }
/** Returns the value of the {@code rounding} field. */
public float rounding() { return NkStyleProgress.nrounding(address()); }
/** Returns the value of the {@code border} field. */
public float border() { return NkStyleProgress.nborder(address()); }
/** Returns the value of the {@code cursor_border} field. */
public float cursor_border() { return NkStyleProgress.ncursor_border(address()); }
/** Returns the value of the {@code cursor_rounding} field. */
public float cursor_rounding() { return NkStyleProgress.ncursor_rounding(address()); }
/** Returns a {@link NkVec2} view of the {@code padding} field. */
public NkVec2 padding() { return NkStyleProgress.npadding(address()); }
/** Returns a {@link NkHandle} view of the {@code userdata} field. */
public NkHandle userdata() { return NkStyleProgress.nuserdata(address()); }
/** Returns the {@code NkDrawBeginCallback} instance at the {@code draw_begin} field. */
public NkDrawBeginCallback draw_begin() { return NkDrawBeginCallback.create(NkStyleProgress.ndraw_begin(address())); }
/** Returns the {@code NkDrawEndCallback} instance at the {@code draw_end} field. */
public NkDrawEndCallback draw_end() { return NkDrawEndCallback.create(NkStyleProgress.ndraw_end(address())); }
/** Copies the specified {@link NkStyleItem} to the {@code normal} field. */
public NkStyleProgress.Buffer normal(NkStyleItem value) { NkStyleProgress.nnormal(address(), value); return this; }
/** Copies the specified {@link NkStyleItem} to the {@code hover} field. */
public NkStyleProgress.Buffer hover(NkStyleItem value) { NkStyleProgress.nhover(address(), value); return this; }
/** Copies the specified {@link NkStyleItem} to the {@code active} field. */
public NkStyleProgress.Buffer active(NkStyleItem value) { NkStyleProgress.nactive(address(), value); return this; }
/** Copies the specified {@link NkColor} to the {@code border_color} field. */
public NkStyleProgress.Buffer border_color(NkColor value) { NkStyleProgress.nborder_color(address(), value); return this; }
/** Copies the specified {@link NkStyleItem} to the {@code cursor_normal} field. */
public NkStyleProgress.Buffer cursor_normal(NkStyleItem value) { NkStyleProgress.ncursor_normal(address(), value); return this; }
/** Copies the specified {@link NkStyleItem} to the {@code cursor_hover} field. */
public NkStyleProgress.Buffer cursor_hover(NkStyleItem value) { NkStyleProgress.ncursor_hover(address(), value); return this; }
/** Copies the specified {@link NkStyleItem} to the {@code cursor_active} field. */
public NkStyleProgress.Buffer cursor_active(NkStyleItem value) { NkStyleProgress.ncursor_active(address(), value); return this; }
/** Copies the specified {@link NkColor} to the {@code cursor_border_color} field. */
public NkStyleProgress.Buffer cursor_border_color(NkColor value) { NkStyleProgress.ncursor_border_color(address(), value); return this; }
/** Sets the specified value to the {@code rounding} field. */
public NkStyleProgress.Buffer rounding(float value) { NkStyleProgress.nrounding(address(), value); return this; }
/** Sets the specified value to the {@code border} field. */
public NkStyleProgress.Buffer border(float value) { NkStyleProgress.nborder(address(), value); return this; }
/** Sets the specified value to the {@code cursor_border} field. */
public NkStyleProgress.Buffer cursor_border(float value) { NkStyleProgress.ncursor_border(address(), value); return this; }
/** Sets the specified value to the {@code cursor_rounding} field. */
public NkStyleProgress.Buffer cursor_rounding(float value) { NkStyleProgress.ncursor_rounding(address(), value); return this; }
/** Copies the specified {@link NkVec2} to the {@code padding} field. */
public NkStyleProgress.Buffer padding(NkVec2 value) { NkStyleProgress.npadding(address(), value); return this; }
/** Copies the specified {@link NkHandle} to the {@code userdata} field. */
public NkStyleProgress.Buffer userdata(NkHandle value) { NkStyleProgress.nuserdata(address(), value); return this; }
/** Sets the address of the specified {@link NkDrawBeginCallbackI} to the {@code draw_begin} field. */
public NkStyleProgress.Buffer draw_begin(NkDrawBeginCallbackI value) { NkStyleProgress.ndraw_begin(address(), addressSafe(value)); return this; }
/** Sets the address of the specified {@link NkDrawEndCallbackI} to the {@code draw_end} field. */
public NkStyleProgress.Buffer draw_end(NkDrawEndCallbackI value) { NkStyleProgress.ndraw_end(address(), addressSafe(value)); return this; }
}
} | 52.521569 | 160 | 0.73292 |
42d059c2fb8f7fe39b41849d197be1f6749e24d7 | 5,464 | package me.earth.phobos.features.modules.combat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import me.earth.phobos.features.modules.Module;
import me.earth.phobos.features.setting.Setting;
import me.earth.phobos.util.BlockUtil;
import me.earth.phobos.util.InventoryUtil;
import me.earth.phobos.util.Timer;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityEnderCrystal;
import net.minecraft.init.Items;
import net.minecraft.network.Packet;
import net.minecraft.network.play.client.CPacketPlayerTryUseItemOnBlock;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
public class Crasher extends Module {
private final Setting<Boolean> oneDot15 = register(new Setting("1.15", Boolean.valueOf(false)));
private final Setting<Float> placeRange = register(new Setting("PlaceRange", Float.valueOf(6.0F), Float.valueOf(0.0F), Float.valueOf(10.0F)));
private final Setting<Integer> crystals = register(new Setting("Packets", Integer.valueOf(25), Integer.valueOf(0), Integer.valueOf(100)));
private final Setting<Integer> coolDown = register(new Setting("CoolDown", Integer.valueOf(400), Integer.valueOf(0), Integer.valueOf(1000)));
private final Setting<InventoryUtil.Switch> switchMode = register(new Setting("Switch", InventoryUtil.Switch.NORMAL));
private final Timer timer = new Timer();
private final List<Integer> entityIDs = new ArrayList<>();
public Setting<Integer> sort = register(new Setting("Sort", Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(2)));
private boolean offhand = false;
private boolean mainhand = false;
private int lastHotbarSlot = -1;
private boolean switchedItem = false;
private boolean chinese = false;
private int currentID = -1000;
public Crasher() {
super("CrystalCrash", "Attempts to crash chinese AutoCrystals", Module.Category.COMBAT, false, false, true);
}
public void onEnable() {
this.chinese = false;
if (fullNullCheck() || !this.timer.passedMs(((Integer)this.coolDown.getValue()).intValue())) {
disable();
return;
}
this.lastHotbarSlot = mc.player.inventory.currentItem;
placeCrystals();
disable();
}
public void onDisable() {
if (!fullNullCheck())
for (Iterator<Integer> iterator = this.entityIDs.iterator(); iterator.hasNext(); ) {
int i = ((Integer)iterator.next()).intValue();
mc.world.removeEntityFromWorld(i);
}
this.entityIDs.clear();
this.currentID = -1000;
this.timer.reset();
}
@SubscribeEvent
public void onTick(TickEvent.ClientTickEvent event) {
if (fullNullCheck() || event.phase == TickEvent.Phase.START || (isOff() && this.timer.passedMs(10L)))
return;
switchItem(true);
}
private void placeCrystals() {
this.offhand = (mc.player.getHeldItemOffhand().getItem() == Items.END_CRYSTAL);
this.mainhand = (mc.player.getHeldItemMainhand().getItem() == Items.END_CRYSTAL);
int crystalcount = 0;
List<BlockPos> blocks = BlockUtil.possiblePlacePositions(((Float)this.placeRange.getValue()).floatValue(), false, ((Boolean)this.oneDot15.getValue()).booleanValue());
if (((Integer)this.sort.getValue()).intValue() == 1) {
blocks.sort(Comparator.comparingDouble(hole -> mc.player.getDistanceSq(hole)));
} else if (((Integer)this.sort.getValue()).intValue() == 2) {
blocks.sort(Comparator.comparingDouble(hole -> -mc.player.getDistanceSq(hole)));
}
for (BlockPos pos : blocks) {
if (isOff() || crystalcount >= ((Integer)this.crystals.getValue()).intValue())
break;
if (!BlockUtil.canPlaceCrystal(pos, false, ((Boolean)this.oneDot15.getValue()).booleanValue()))
continue;
placeCrystal(pos);
crystalcount++;
}
}
private void placeCrystal(BlockPos pos) {
if (!this.chinese && !this.mainhand && !this.offhand && !switchItem(false)) {
disable();
return;
}
RayTraceResult result = mc.world.rayTraceBlocks(new Vec3d(mc.player.posX, mc.player.posY + mc.player.getEyeHeight(), mc.player.posZ), new Vec3d(pos.getX() + 0.5D, pos.getY() - 0.5D, pos.getZ() + 0.5D));
EnumFacing facing = (result == null || result.sideHit == null) ? EnumFacing.UP : result.sideHit;
mc.player.connection.sendPacket((Packet)new CPacketPlayerTryUseItemOnBlock(pos, facing, this.offhand ? EnumHand.OFF_HAND : EnumHand.MAIN_HAND, 0.0F, 0.0F, 0.0F));
mc.player.swingArm(EnumHand.MAIN_HAND);
EntityEnderCrystal fakeCrystal = new EntityEnderCrystal((World)mc.world, (pos.getX() + 0.5F), (pos.getY() + 1), (pos.getZ() + 0.5F));
int newID = this.currentID--;
this.entityIDs.add(Integer.valueOf(newID));
mc.world.addEntityToWorld(newID, (Entity)fakeCrystal);
}
private boolean switchItem(boolean back) {
this.chinese = true;
if (this.offhand)
return true;
boolean[] value = InventoryUtil.switchItemToItem(back, this.lastHotbarSlot, this.switchedItem, (InventoryUtil.Switch)this.switchMode.getValue(), Items.END_CRYSTAL);
this.switchedItem = value[0];
return value[1];
}
}
| 41.393939 | 206 | 0.708638 |
4ba3989216fab6e5aac446e753580c3a79e61551 | 235 | package org.activitymgr.ui.web.logic;
public abstract class AbstractEvent {
private ILogic<?> source;
public AbstractEvent(ILogic<?> source) {
this.source = source;
}
public ILogic<?> getSource() {
return source;
}
}
| 13.823529 | 41 | 0.689362 |
c4008623d52402e7fe92789a53dcd5e08666492d | 17,214 | /*****************************************************************
JADE - Java Agent DEvelopment Framework is a framework to develop
multi-agent systems in compliance with the FIPA specifications.
Copyright (C) 2000 CSELT S.p.A.
GNU Lesser General Public License
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation,
version 2.1 of the License.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*****************************************************************/
package jade.core.behaviours;
import jade.util.leap.Serializable;
import jade.core.Agent;
/**
Abstract base class for <b><em>JADE</em></b> behaviours. Extending
this class directly should only be needed for particular behaviours
with special synchronization needs; this is because event based
notification used for blocking and restarting behaviours is
directly accessible at this level.
@author Giovanni Rimassa - Universita' di Parma
@version $Date: 2013-03-11 09:55:05 +0100 (lun, 11 mar 2013) $ $Revision: 6645 $
*/
public abstract class Behaviour implements Serializable {
private static final long serialVersionUID = 3487495895819001L;
//#APIDOC_EXCLUDE_BEGIN
/**
A constant for child-to-parent notifications.
@serial
*/
protected static final int NOTIFY_UP = -1;
/**
A constant for parent-to-child notifications.
@serial
*/
protected static final int NOTIFY_DOWN = 1;
/**
A constant identifying the runnable state.
@serial
*/
public static final String STATE_READY = "READY";
/**
A constant identifying the blocked state.
@serial
*/
public static final String STATE_BLOCKED = "BLOCKED";
/**
A constant identifying the running state.
@serial
*/
public static final String STATE_RUNNING = "RUNNING";
/**
Event class for notifying blocked and restarted behaviours.
This class is used to notify interested behaviours when a
Behaviour changes its runnable state. It may be sent to
behaviour's parent (<em>upward notification</em> or to behaviour's
children (<em>downward notification</em>).
*/
protected class RunnableChangedEvent implements Serializable {
private static final long serialVersionUID = 3487495895819002L;
/**
@serial
*/
private boolean runnable;
/**
@serial
*/
private int direction;
/**
Re-init event content. This method can be used to rewrite an
existing event with new data (much cheaper than making a new
object).
@param b A <code>boolean</code> flag; when <code>false</code>
it means that a behaviour passed from <em>Ready</em> to
<em>Blocked</em> state. When <code>true</code> it means that a
behaviour passed from <em>Blocked</em> to <em>Ready</em> (this
flag is the truth value of the predicate <em><b>'The behaviour
has now become runnable'</b></em>.
@param d A notification direction: when direction is
<code>NOTIFY_UP</code>, the event travels upwards the behaviour
containment hierarchy; when it is <code>NOTIFY_DOWN</code>, the
event travels downwards.
*/
public void init(boolean b, int d) {
runnable = b;
direction = d;
}
/**
Read event source.
@return The <code>Behaviour</code> object which generated this event.
*/
public Behaviour getSource() {
return Behaviour.this;
}
/**
Check whether the event is runnable.
@return <code>true</code> when the behaviour generating this
event has become <em>Ready</em>, <code>false</code> when it has
become <em>Blocked</em>. */
public boolean isRunnable() {
return runnable;
}
/**
Check which direction this event is travelling.
@return <code>true</code> when the event is a notification
going from a child behaviour to its parent; <code>false</code>
otherwise.
*/
public boolean isUpwards() {
return direction == NOTIFY_UP;
}
} // End of RunnableChangedEvent class
//#APIDOC_EXCLUDE_END
private String myName;
private boolean startFlag = true;
/**
The agent this behaviour belongs to.
This is an instance variable that holds a reference to the Agent
object and allows the usage of its methods within the body of the
behaviour. As the class <code>Behaviour</code> is the superclass
of all the other behaviour classes, this variable is always
available. Of course, remind to use the appropriate constructor,
i.e. the one that accepts an agent object as argument; otherwise,
this variable is set to <code>null</code>.
*/
protected Agent myAgent;
/**
Flag indicating whether this Behaviour is runnable or not
*/
private volatile boolean runnableState = true;
private volatile long restartCounter = 0;
private volatile String executionState = STATE_READY;
//#APIDOC_EXCLUDE_BEGIN
/**
This event object will be re-used for every state change
notification.
*/
protected RunnableChangedEvent myEvent = new RunnableChangedEvent();
//#APIDOC_EXCLUDE_END
//#CUSTOM_EXCLUDE_BEGIN
/**
The private data store of this Behaviour
*/
private DataStore myStore;
void setParent(CompositeBehaviour cb) {
parent = cb;
if (parent != null) {
myAgent = parent.myAgent;
}
wrappedParent = null;
}
void setWrappedParent(CompositeBehaviour cb) {
wrappedParent = cb;
}
private CompositeBehaviour wrappedParent;
//#APIDOC_EXCLUDE_BEGIN
protected CompositeBehaviour parent;
//#APIDOC_EXCLUDE_END
/**
* Retrieve the enclosing CompositeBehaviour (if present). In order to access the parent behaviour
* it is strongly suggested to use this method rather than the <core>parent</code> member variable
* directly. In case of threaded or wrapped behaviour in facts the latter may have unexpected values.
@return The enclosing CompositeBehaviour (if present).
@see jade.core.behaviours.CompositeBehaviour
*/
protected CompositeBehaviour getParent() {
if (wrappedParent != null) {
return wrappedParent;
}
else {
return parent;
}
}
//#CUSTOM_EXCLUDE_END
/**
Default constructor. It does not set the agent owning this
behaviour object.
*/
public Behaviour() {
// Construct a default name
myName = getClass().getName();
// Remove the class name and the '$' characters from
// the class name for readability.
int dotIndex = myName.lastIndexOf('.');
int dollarIndex = myName.lastIndexOf('$');
int lastIndex = (dotIndex > dollarIndex ? dotIndex : dollarIndex);
if (lastIndex != -1) {
myName = myName.substring(lastIndex+1);
}
}
/**
Constructor with owner agent.
@param a The agent owning this behaviour.
*/
public Behaviour(Agent a) {
this();
myAgent = a;
}
/**
Give a name to this behaviour object.
@param name The name to give to this behaviour.
*/
public final void setBehaviourName(String name) {
myName = name;
}
/**
Retrieve the name of this behaviour object. If no explicit name
was set, a default one is given, based on the behaviour class
name.
@return The name of this behaviour.
*/
public final String getBehaviourName() {
return myName;
}
/**
Runs the behaviour. This abstract method must be implemented by
<code>Behaviour</code>subclasses to perform ordinary behaviour
duty. An agent schedules its behaviours calling their
<code>action()</code> method; since all the behaviours belonging
to the same agent are scheduled cooperatively, this method
<b>must not</b> enter in an endless loop and should return as
soon as possible to preserve agent responsiveness. To split a
long and slow task into smaller section, recursive behaviour
aggregation may be used.
@see jade.core.behaviours.CompositeBehaviour
*/
public abstract void action();
/**
Check if this behaviour is done. The agent scheduler calls this
method to see whether a <code>Behaviour</code> still need to be
run or it has completed its task. Concrete behaviours must
implement this method to return their completion state. Finished
behaviours are removed from the scheduling queue, while others
are kept within to be run again when their turn comes again.
@return <code>true</code> if the behaviour has completely executed.
*/
public abstract boolean done();
/**
This method is just an empty placeholder for subclasses. It is
invoked just once after this behaviour has ended. Therefore,
it acts as an epilog for the task represented by this
<code>Behaviour</code>.
<br>
Note that <code>onEnd</code> is called after the behaviour has been
removed from the pool of behaviours to be executed by an agent.
Therefore calling
<code>reset()</code> is not sufficient to cyclically repeat the task
represented by this <code>Behaviour</code>. In order to achieve that,
this <code>Behaviour</code> must be added again to the agent
(using <code>myAgent.addBehaviour(this)</code>). The same applies to
in the case of a <code>Behaviour</code> that is a child of a
<code>ParallelBehaviour</code>.
@return an integer code representing the termination value of
the behaviour.
*/
public int onEnd() {
return 0;
}
/**
This method is just an empty placeholders for subclasses. It is
executed just once before starting behaviour execution.
Therefore, it acts as a prolog to the task
represented by this <code>Behaviour</code>.
*/
public void onStart() {
}
//#APIDOC_EXCLUDE_BEGIN
/**
This method is called internally by the JADE framework
and should not be called by the user.
*/
public final void actionWrapper() {
if (startFlag) {
onStart();
startFlag = false;
}
//#MIDP_EXCLUDE_BEGIN
// Maybe the behaviour was removed from another thread
if (myAgent != null) {
myAgent.notifyChangeBehaviourState(this, Behaviour.STATE_READY, Behaviour.STATE_RUNNING);
}
//#MIDP_EXCLUDE_END
action();
//#MIDP_EXCLUDE_BEGIN
if (myAgent != null) {
myAgent.notifyChangeBehaviourState(this, Behaviour.STATE_RUNNING, Behaviour.STATE_READY);
}
//#MIDP_EXCLUDE_END
}
public final void setExecutionState(String s) {
executionState = s;
}
public final String getExecutionState() {
return executionState;
}
//#APIDOC_EXCLUDE_END
/**
Restores behaviour initial state. This method must be implemented
by concrete subclasses in such a way that calling
<code>reset()</code> on a behaviour object is equivalent to
destroying it and recreating it back. The main purpose for this
method is to realize multistep cyclic behaviours without needing
expensive constructions an deletion of objects at each loop
iteration.
Remind to call super.reset() from the sub-classes.
*/
public void reset() {
startFlag = true;
restart();
}
//#APIDOC_EXCLUDE_BEGIN
/**
Handler for block/restart events. This method handles
notification by copying its runnable state and then by simply
forwarding the event when it is traveling upwards and by doing
nothing when it is traveling downwards, since an ordinary
behaviour has no children.
@param rce The event to handle
*/
protected void handle(RunnableChangedEvent rce) {
// Set the new runnable state
setRunnable(rce.isRunnable());
//#CUSTOM_EXCLUDE_BEGIN
// If the notification is upwords and a parent exists -->
// Notify the parent
if( (parent != null) && (rce.isUpwards()) ) {
parent.handle(rce);
}
//#CUSTOM_EXCLUDE_END
}
//#APIDOC_EXCLUDE_END
/**
Returns the root for this <code>Behaviour</code> object. That is,
the top-level behaviour this one is a part of. Agents apply
scheduling only to top-level behaviour objects, so they just call
<code>restart()</code> on root behaviours.
@return The top-level behaviour this behaviour is a part of. If
this one is a top level behaviour itself, then simply
<code>this</code> is returned.
@see jade.core.behaviours.Behaviour#restart()
*/
public Behaviour root() {
//#CUSTOM_EXCLUDE_BEGIN
Behaviour p = getParent();
if (p != null) {
return p.root();
}
//#CUSTOM_EXCLUDE_END
return this;
}
// Sets the runnable/not-runnable state
void setRunnable(boolean runnable) {
runnableState = runnable;
if (runnableState) {
restartCounter++;
}
}
/**
Returns whether this <code>Behaviour</code> object is blocked or
not.
@return <code>true</code> when this behaviour is not blocked,
<code>false</code> when it is.
*/
public boolean isRunnable() {
return runnableState;
}
//#APIDOC_EXCLUDE_BEGIN
/**
* This method is used internally by the framework. Developer should not call or redefine it.
*/
public final long getRestartCounter() {
return restartCounter;
}
//#APIDOC_EXCLUDE_END
/**
Blocks this behaviour. It should be noticed that this method is NOT a
blocking call: when it is invoked, the internal behaviour
state is set to <em>Blocked</em> so that, as soon as the <code>action()</code>
method returns, the behaviour is put into a blocked behaviours queue so that it will
not be scheduled anymore.<br>
The behaviour is moved back in the pool of active behaviours when either
a message is received or the behaviour is explicitly restarted by means of its
<code>restart()</code> method.<br>
If this behaviour is a child of a <code>CompositeBehaviour</code> a suitable event is fired to
notify its parent behaviour up to the behaviour composition hierarchy root.
@see jade.core.behaviours.Behaviour#restart()
*/
public void block() {
handleBlockEvent();
}
//#APIDOC_EXCLUDE_BEGIN
/**
* This method is used internally by the framework. Developer should not call or redefine it.
*/
protected void handleBlockEvent() {
myEvent.init(false, NOTIFY_UP);
handle(myEvent);
}
//#APIDOC_EXCLUDE_END
/**
Blocks this behaviour for a specified amount of time. The
behaviour will be restarted when among the three following
events happens.
<ul>
<li> <em>A time of <code>millis</code> milliseconds has passed
since the call to <code>block()</code>.</em>
<li> <em>An ACL message is received by the agent this behaviour
belongs to.</em>
<li> <em>Method <code>restart()</code> is called explicitly on
this behaviour object.</em>
</ul>
@param millis The amount of time to block, in
milliseconds. <em><b>Notice:</b> a value of 0 for
<code>millis</code> is equivalent to a call to
<code>block()</code> without arguments.</em>
@see jade.core.behaviours.Behaviour#block()
*/
public void block(long millis) {
// Note that it is important to block the behaviour before
// adding a Timer to restart it in a millis time. In fact if
// the two operations are cerried out the other way around, it
// could happen that the Timer expires before the block()
// operation is executed --> The TimerDispatcher thread restarts
// the behaviour (that has not blocked yet) and just after the
// behaviour blocks.
block();
if (myAgent != null) {
myAgent.restartLater(this, millis);
}
}
/**
Restarts a blocked behaviour. This method fires a suitable event
to notify this behaviour's parent. When the agent scheduler
inserts a blocked event back into the agent ready queue, it
restarts it automatically. When this method is called, any timer
associated with this behaviour object is cleared.
@see jade.core.behaviours.Behaviour#block()
*/
public void restart() {
if(myAgent != null) {
myAgent.removeTimer(this);
}
handleRestartEvent();
if(myAgent != null) {
myAgent.notifyRestarted(this);
}
}
//#APIDOC_EXCLUDE_BEGIN
/**
* This method is used internally by the framework. Developer should not call or redefine it.
*/
public void handleRestartEvent() {
myEvent.init(true, NOTIFY_UP);
handle(myEvent);
}
//#APIDOC_EXCLUDE_END
/**
Associates this behaviour with the agent it belongs to. There is
no need to call this method explicitly, since the
<code>addBehaviour()</code> call takes care of the association
transparently.
@param a The agent this behaviour belongs to.
@see jade.core.Agent#addBehaviour(Behaviour b)
*/
public void setAgent(Agent a) {
myAgent = a;
}
public Agent getAgent() {
return myAgent;
}
//#CUSTOM_EXCLUDE_BEGIN
/**
Return the private data store of this <code>Behaviour</code>.
If it was null, a new DataStore is created and returned.
@return The private data store of this <code>Behaviour</code>
*/
public DataStore getDataStore() {
if (myStore == null) {
myStore = new DataStore();
}
return myStore;
}
/**
Set the private data store of this <code>Behaviour</code>
@param ds the <code>DataStore</code> that this <code>Behaviour</code>
will use as its private data store
*/
public void setDataStore(DataStore ds) {
myStore = ds;
}
//#CUSTOM_EXCLUDE_END
}
| 29.782007 | 103 | 0.713896 |
535dbf4c6fcf516e02e69528be649cec5c74dc55 | 3,488 | package authoring.parser;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import authoring.frontend.editor_features.SpawnEntityRow;
/**
*
* @author Frank, Jonathan Ma
*
*/
public class GlobalParser {
public static Map<String, String[]> pathParse(String path) {
Map<String, String[]> map = new TreeMap<String, String[]>();
String[] paths = path.split("_");
for (String str : paths) {
String[] pathInfo = str.split(":");
String pathID = pathInfo[0];
String[] curves = pathInfo[1].split(" ");
map.put(pathID, curves);
}
return map;
}
public static String pathCompress(Map<String, String[]> path) {
StringBuilder sb = new StringBuilder();
for (String key : path.keySet()) {
sb.append(key);
sb.append(":");
String[] curves = path.get(key);
for (int i = 0; i < curves.length - 1; i++) {
sb.append(curves[i]);
sb.append(" ");
}
sb.append(curves[curves.length - 1]);
sb.append("_");
}
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
public static Map<String, String[]> spawnParse(String spawn) {
Map<String, String[]> spawns = new TreeMap<String, String[]>();
if (spawn.equals("0")) {
return spawns;
} else {
String[] temp = spawn.split(",");
for (String str : temp) {
String[] info = str.split(":");
String pathID = info[0];
String[] spawnObjects = info[1].split("_");
spawns.put(pathID, spawnObjects);
}
return spawns;
}
}
/**
* Takes unordered inputs and sorts them by pathID, then delineated (in no
* order) by entity names, followed by wave order, number, and rate.
*
* @param map
* @return
*/
public static String compressSpawnsInputs(TreeMap<String, SpawnEntityRow> map) {
String result = "";
Set<String> myIDs = new HashSet<String>();
for (String tag : map.keySet()) {
String[] split = tag.split(":");
String id = split[0];
myIDs.add(id);
}
for (String id : myIDs) {
String pathString = new String(id + ":");
for (String tag : map.keySet()) {
String[] split = tag.split(":");
String currentID = split[0];
if (currentID.equals(id)) {
SpawnEntityRow row = map.get(tag);
String name = row.getMyName().getText();
String wave = row.getMyWaveOrder().getText();
String number = row.getMyNumber().getText();
String rate = row.getMyRate().getText();
String entityObject = name + "." + wave + "." + number + "." + rate + "_";
pathString += entityObject;
}
}
String completePath = pathString.substring(0, pathString.length() - 1);
result = result + completePath + ",";
}
result = result.substring(0, result.length() - 1);
return result;
}
public static List<String> parseLevels(String string) {
List<String> sortedLevels = new ArrayList<String>();
String[] allLevels = string.split(" ");
for (String level : allLevels) {
String[] split = level.split(":");
sortedLevels.add(split[1]);
}
return sortedLevels;
}
public static String compressLevels(Map<Integer, String> levels) {
int[] indexes = new int[levels.size()];
int index = 0;
for (Integer i : levels.keySet()) {
indexes[index] = i;
index++;
}
Arrays.sort(indexes);
String result = "";
for (int j : indexes) {
result += Integer.toString(j) + ":" + levels.get(j) + " ";
}
return result.substring(0, result.length() - 1);
}
}
| 24.914286 | 81 | 0.627294 |
3e1b22baf4bc61534e52fb5f21b80bc9368b6cad | 693 | package com.demo.entity;
/**
* @author zhang pan
* @Description 类描述
*/
public class Blog {
private Integer id;
private String blog;
public Blog() {
}
public Blog(Integer id, String blog) {
this.id = id;
this.blog = blog;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getBlog() {
return blog;
}
public void setBlog(String blog) {
this.blog = blog;
}
@Override
public String toString() {
return "Blog{" +
"id=" + id +
", blog='" + blog + '\'' +
'}';
}
}
| 15.4 | 42 | 0.477633 |
bdefa1b4b3253292ecc7f8c886b7be43dfda7c3a | 1,735 | package com.breeziness.timetable.data.bean;
public class CourseBean {
private int id; //唯一的id
private String cname;//课程名称
private String courseno;//课号
private String name;//老师名字
private String term;//学期
private String croomno;//教师
private int startweek;//起始周次
private int endweek;//结束周次
private int week;//星期几
private String seq;//节次
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public String getCourseno() {
return courseno;
}
public void setCourseno(String courseno) {
this.courseno = courseno;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTerm() {
return term;
}
public void setTerm(String term) {
this.term = term;
}
public String getCroomno() {
return croomno;
}
public void setCroomno(String croomno) {
this.croomno = croomno;
}
public int getStartweek() {
return startweek;
}
public void setStartweek(int startweek) {
this.startweek = startweek;
}
public int getEndweek() {
return endweek;
}
public void setEndweek(int endweek) {
this.endweek = endweek;
}
public int getWeek() {
return week;
}
public void setWeek(int week) {
this.week = week;
}
public String getSeq() {
return seq;
}
public void setSeq(String seq) {
this.seq = seq;
}
}
| 17.525253 | 46 | 0.573487 |
33ad0c84b1c146b413e0b940fe0b6acc0f72a64b | 349 | package me.jessyan.mvparms.hsy.mvp.eventbus;
/**
* Created by haosiyuan on 2017/5/15.
* weibo管理取消解绑
*/
public class WeiBoManagerCancleEvent {
private int position;
public WeiBoManagerCancleEvent(int position) {
this.position = position;
}
public int getPosition(){
return position;
}
}
| 17.45 | 51 | 0.633238 |
90d523e08190ee66e61a444ac6c2c860f4848f4e | 487 | package com.hzqing.system.api.dto.button;
import com.hzqing.common.core.service.request.PageRequest;
import lombok.Data;
import lombok.ToString;
/**
* @author hzqing
* @date 2019-08-12 23:01
*/
@Data
@ToString(callSuper = true)
public class ElementPageRequest extends PageRequest {
/**
* 菜单id
*/
private String menuId;
public ElementPageRequest() {
}
public ElementPageRequest(int pageNum, int pageSize) {
super(pageNum, pageSize);
}
}
| 17.392857 | 58 | 0.681725 |
6bb0d2f7d03f7d5599af0711c2a854885dc384d3 | 884 | package com.abc.web.filter;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import java.io.IOException;
import java.util.Date;
//@Component
public class TimeFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("Time filter init...");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("Time filter start------");
long start = new Date().getTime();
chain.doFilter(request,response);
long time = new Date().getTime() - start;
System.out.println("Time filter finish------, time: "+time+" ms");
}
@Override
public void destroy() {
System.out.println("Time filter destroy...");
}
}
| 26.787879 | 132 | 0.674208 |
e805011c4a1a1045048f9a6be16023b38b8b6f73 | 349 | package moviles.guiass.data.datasource.memory;
import java.util.List;
import moviles.guiass.data.models.Document;
import moviles.guiass.utils.DocumentCriteria;
public interface IMemoryDocumentsDataSource {
List<Document> find(DocumentCriteria criteria);
void save(Document document);
void deleteAll();
boolean mapIsNull();
}
| 18.368421 | 51 | 0.770774 |
1c0352d79ef45c9faf47ceecf49a6838d8932603 | 228 | package life.qbic.projectwizard.control;
import java.sql.SQLException;
public interface IRegistrationController {
void performPostRegistrationTasks(boolean success) throws SQLException;
String getRegistrationError();
}
| 19 | 73 | 0.824561 |
4634c36cf31b445ca888af21d7489fbfac4c36b5 | 1,193 | /*******************************************************************************
* Copyright SemanticBits, Northwestern University and Akaza Research
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/caaers/LICENSE.txt for details.
******************************************************************************/
package gov.nih.nci.cabig.caaers.domain;
import java.util.Date;
import junit.framework.TestCase;
/**
*
* @author Biju Joseph
*
*/
public class SiteResearchStaffTest extends TestCase {
protected void setUp() throws Exception {
super.setUp();
}
public void testIsActive() {
assertTrue(new SiteResearchStaff().isActive());
}
public void testGetActiveSiteResearchStaffRoles() {
assertNotNull(new SiteResearchStaff().getActiveSiteResearchStaffRoles());
}
public void testIsActive_ReallyActive(){
SiteResearchStaffRole role1 = new SiteResearchStaffRole();
role1.setStartDate(new Date());
SiteResearchStaff srs = new SiteResearchStaff();
srs.addSiteResearchStaffRole(role1);
assertTrue(srs.isActive());
}
public void testGetActiveDate(){
assertNotNull(new SiteResearchStaff().getActiveDate());
}
}
| 27.113636 | 80 | 0.654652 |
55de0edab5f91ebad4b1869f59e68493f6d25feb | 7,644 | package net.minecraft.src;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
public class ChunkLoader implements IChunkLoader {
private File saveDir;
private boolean createIfNecessary;
public ChunkLoader(File var1, boolean var2) {
this.saveDir = var1;
this.createIfNecessary = var2;
}
private File chunkFileForXZ(int var1, int var2) {
String var3 = "c." + Integer.toString(var1, 36) + "." + Integer.toString(var2, 36) + ".dat";
String var4 = Integer.toString(var1 & 63, 36);
String var5 = Integer.toString(var2 & 63, 36);
File var6 = new File(this.saveDir, var4);
if (!var6.exists()) {
if (!this.createIfNecessary) {
return null;
}
var6.mkdir();
}
var6 = new File(var6, var5);
if (!var6.exists()) {
if (!this.createIfNecessary) {
return null;
}
var6.mkdir();
}
var6 = new File(var6, var3);
return !var6.exists() && !this.createIfNecessary ? null : var6;
}
public Chunk loadChunk(World var1, int var2, int var3) throws IOException {
File var4 = this.chunkFileForXZ(var2, var3);
if (var4 != null && var4.exists()) {
try {
FileInputStream var5 = new FileInputStream(var4);
NBTTagCompound var6 = CompressedStreamTools.func_770_a(var5);
if (!var6.hasKey("Level")) {
System.out.println("Chunk file at " + var2 + "," + var3 + " is missing level data, skipping");
return null;
}
if (!var6.getCompoundTag("Level").hasKey("Blocks")) {
System.out.println("Chunk file at " + var2 + "," + var3 + " is missing block data, skipping");
return null;
}
Chunk var7 = loadChunkIntoWorldFromCompound(var1, var6.getCompoundTag("Level"));
if (!var7.isAtLocation(var2, var3)) {
System.out.println("Chunk file at " + var2 + "," + var3 + " is in the wrong location; relocating. (Expected " + var2 + ", " + var3 + ", got " + var7.xPosition + ", " + var7.zPosition + ")");
var6.setInteger("xPos", var2);
var6.setInteger("zPos", var3);
var7 = loadChunkIntoWorldFromCompound(var1, var6.getCompoundTag("Level"));
}
var7.func_25083_h();
return var7;
} catch (Exception var8) {
var8.printStackTrace();
}
}
return null;
}
public void saveChunk(World var1, Chunk var2) throws IOException {
var1.checkSessionLock();
File var3 = this.chunkFileForXZ(var2.xPosition, var2.zPosition);
if (var3.exists()) {
WorldInfo var4 = var1.getWorldInfo();
var4.setSizeOnDisk(var4.getSizeOnDisk() - var3.length());
}
try {
File var10 = new File(this.saveDir, "tmp_chunk.dat");
FileOutputStream var5 = new FileOutputStream(var10);
NBTTagCompound var6 = new NBTTagCompound();
NBTTagCompound var7 = new NBTTagCompound();
var6.setTag("Level", var7);
storeChunkInCompound(var2, var1, var7);
CompressedStreamTools.writeGzippedCompoundToOutputStream(var6, var5);
var5.close();
if (var3.exists()) {
var3.delete();
}
var10.renameTo(var3);
WorldInfo var8 = var1.getWorldInfo();
var8.setSizeOnDisk(var8.getSizeOnDisk() + var3.length());
} catch (Exception var9) {
var9.printStackTrace();
}
}
public static void storeChunkInCompound(Chunk var0, World var1, NBTTagCompound var2) {
var1.checkSessionLock();
var2.setInteger("xPos", var0.xPosition);
var2.setInteger("zPos", var0.zPosition);
var2.setLong("LastUpdate", var1.getWorldTime());
var2.setByteArray("Blocks", var0.blocks);
var2.setByteArray("Data", var0.data.data);
var2.setByteArray("SkyLight", var0.skylightMap.data);
var2.setByteArray("BlockLight", var0.blocklightMap.data);
var2.setByteArray("HeightMap", var0.heightMap);
var2.setBoolean("TerrainPopulated", var0.isTerrainPopulated);
var0.hasEntities = false;
NBTTagList var3 = new NBTTagList();
Iterator var5;
NBTTagCompound var7;
for(int var4 = 0; var4 < var0.entities.length; ++var4) {
var5 = var0.entities[var4].iterator();
while(var5.hasNext()) {
Entity var6 = (Entity)var5.next();
var0.hasEntities = true;
var7 = new NBTTagCompound();
if (var6.addEntityID(var7)) {
var3.setTag(var7);
}
}
}
var2.setTag("Entities", var3);
NBTTagList var8 = new NBTTagList();
var5 = var0.chunkTileEntityMap.values().iterator();
while(var5.hasNext()) {
TileEntity var9 = (TileEntity)var5.next();
var7 = new NBTTagCompound();
var9.writeToNBT(var7);
var8.setTag(var7);
}
var2.setTag("TileEntities", var8);
}
public static Chunk loadChunkIntoWorldFromCompound(World var0, NBTTagCompound var1) {
int var2 = var1.getInteger("xPos");
int var3 = var1.getInteger("zPos");
Chunk var4 = new Chunk(var0, var2, var3);
var4.blocks = var1.getByteArray("Blocks");
var4.data = new NibbleArray(var1.getByteArray("Data"));
var4.skylightMap = new NibbleArray(var1.getByteArray("SkyLight"));
var4.blocklightMap = new NibbleArray(var1.getByteArray("BlockLight"));
var4.heightMap = var1.getByteArray("HeightMap");
var4.isTerrainPopulated = var1.getBoolean("TerrainPopulated");
if (!var4.data.isValid()) {
var4.data = new NibbleArray(var4.blocks.length);
}
if (var4.heightMap == null || !var4.skylightMap.isValid()) {
var4.heightMap = new byte[256];
var4.skylightMap = new NibbleArray(var4.blocks.length);
var4.func_353_b();
}
if (!var4.blocklightMap.isValid()) {
var4.blocklightMap = new NibbleArray(var4.blocks.length);
var4.func_348_a();
}
NBTTagList var5 = var1.getTagList("Entities");
if (var5 != null) {
for(int var6 = 0; var6 < var5.tagCount(); ++var6) {
NBTTagCompound var7 = (NBTTagCompound)var5.tagAt(var6);
Entity var8 = EntityList.createEntityFromNBT(var7, var0);
var4.hasEntities = true;
if (var8 != null) {
var4.addEntity(var8);
}
}
}
NBTTagList var10 = var1.getTagList("TileEntities");
if (var10 != null) {
for(int var11 = 0; var11 < var10.tagCount(); ++var11) {
NBTTagCompound var12 = (NBTTagCompound)var10.tagAt(var11);
TileEntity var9 = TileEntity.createAndLoadEntity(var12);
if (var9 != null) {
var4.addTileEntity(var9);
}
}
}
return var4;
}
public void func_661_a() {
}
public void saveExtraData() {
}
public void saveExtraChunkData(World var1, Chunk var2) throws IOException {
}
}
| 36.227488 | 210 | 0.5573 |
9e89335e2fff493e48a902fb28ec4554d332d6a7 | 1,702 | /**
*
* Copyright (C) 2011-2017 KSFX. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ch.ksfx.web.services.scheduler;
import ch.ksfx.model.activity.Activity;
import ch.ksfx.model.spidering.SpideringConfiguration;
import org.quartz.SchedulerException;
import java.util.Date;
import java.util.List;
public interface SchedulerService
{
public void initializeScheduler();
public List<String> getAllRunningJobs() throws SchedulerException;
public List<String> getAllTriggers() throws SchedulerException;
public void scheduleSpidering(SpideringConfiguration spideringConfiguration);
public void scheduleActivity(Activity activity);
public void pauseJob(String jobName, String groupName) throws SchedulerException;
public void resumeJob(String jobName, String groupName) throws SchedulerException;
public void deleteJob(String jobName, String groupName) throws SchedulerException;
public boolean jobExists(String jobName, String groupName) throws SchedulerException;
public boolean isPaused(String triggerName) throws SchedulerException;
public Date getNextFireTime(String triggerName) throws SchedulerException;
}
| 40.52381 | 89 | 0.784959 |
9f49c27e2477050c0ff8a602c9a196a63bccaa24 | 3,879 | package kandrm.JLatVis.lattice.editing.history;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
/**
* History manager. Stores history events, supports manipullating with them a moving in history back or forward.
*
* @author Michal Kandr
*/
public class History implements IHistoryEventListener{
protected List<ChangeListener> changeListeners = new LinkedList<ChangeListener>();
protected List<HistoryEvent> history = new LinkedList<HistoryEvent>();
protected boolean transactionActive = false;
protected List<HistoryEvent> catchedEvents = new ArrayList<HistoryEvent>();
/**
* Actual position in history
*/
protected int actualHistoryPosition = 0;
protected void fireChangeEvents(){
ChangeEvent e = new ChangeEvent(0);
for(ChangeListener l : changeListeners){
l.stateChanged(e);
}
}
public void addChangeListener(ChangeListener l){
changeListeners.add(l);
}
public void removeChangeListener(ChangeListener l){
changeListeners.remove(l);
}
/**
* Delete all inverted events (events after actual position).
*/
private void clearNextEvents(){
if(actualHistoryPosition <= history.size()-1){
history.subList(actualHistoryPosition, history.size()).clear();
}
}
public void startTransaction(){
if(catchedEvents.size() > 0){
endTransaction();
}
transactionActive = true;
}
public void endTransaction(){
transactionActive = false;
if(catchedEvents.size() > 0){
eventPerformed(new HistoryEventCompound(catchedEvents));
}
catchedEvents.clear();
}
/**
* Add new history event.
* Reverted events are deleted.
* @param evt added event
*/
@Override
public void eventPerformed(HistoryEvent e){
if(transactionActive){
catchedEvents.add(e);
} else {
if(actualHistoryPosition <= history.size()){
clearNextEvents();
}
history.add(e);
++ actualHistoryPosition;
fireChangeEvents();
}
}
/**
* Delete all events.
*/
public void clear(){
history.clear();
actualHistoryPosition = 0;
fireChangeEvents();
}
/**
* Revert last event if present.
*/
public void backward(){
if(canBackward()){
actualHistoryPosition --;
history.get(actualHistoryPosition).reverse();
fireChangeEvents();
}
}
/**
* Do again last reverted event, if exists.
*/
public void forward(){
if(canForward()){
history.get(actualHistoryPosition).doAgain();
actualHistoryPosition ++;
}
fireChangeEvents();
}
/**
* Revert all actions.
*/
public void toBegining(){
while(canBackward()){
backward();
}
}
/**
* Do again all reverted actions
*/
public void toEnd(){
while(canForward()){
forward();
}
}
/**
* @return are there any events to revert
*/
public boolean canBackward(){
return actualHistoryPosition > 0;
}
/**
* @return are there any reverted events
*/
public boolean canForward(){
return actualHistoryPosition < history.size();
}
/**
* @return hash of current position in history
*/
public int getActualPositionHash(){
return (actualHistoryPosition + "-" + (history.isEmpty() || ! canBackward() ? 0 : history.get( actualHistoryPosition > 0 ? actualHistoryPosition - 1 : 0).hashCode() )).hashCode();
}
}
| 25.025806 | 187 | 0.59139 |
6cd381bf95792e0025c96ba98a5bb399baa9a732 | 819 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package metodosEstaticos;
import aula07.*;
/**
*
* @author Lab
*/
public final class Retangulo extends FormaGeometrica {
double largura;
double altura;
public Retangulo(double largura, double altura) {
super();
this.largura = largura;
this.altura = altura;
}
@Override
public double calcularArea() {
return CalculoArea.calcularAreaRetangulo(this.largura, this.altura);
}
@Override
public double calcularPerimetro() {
return (this.altura * this.largura) * 2;
}
@Override
public String quemSou() {
return "Retangulo";
}
}
| 20.475 | 79 | 0.647131 |
1e4137e74d27b4e613b50759135e3bb001160333 | 492 | package com.luxoft.effectivejava.module02.item11.accounts;
public abstract class AbstractAccount {
double balance;
abstract void verifyAccount();
public AbstractAccount(double balance){
this.balance = balance;
}
@Override
public Object clone() {
Object clone = null;
try {
clone = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return clone;
}
} | 22.363636 | 59 | 0.593496 |
efdb8de0c6ccf0b3bfdfb346a5da15969e47298c | 1,181 | package ar.com.javacurisioties.jaxb.lesson5;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;
import java.util.Date;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
@XmlSeeAlso(value = {Child.class, SubChild.class})
public class Parent {
private String name;
private String lastName;
private Date birthdate;
public Parent() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Date getBirthdate() {
return birthdate;
}
public void setBirthdate(Date birthdate) {
this.birthdate = birthdate;
}
@Override
public String toString() {
return "Parent{" +
"name='" + name + '\'' +
", lastName='" + lastName + '\'' +
", birthdate=" + birthdate +
'}';
}
}
| 21.472727 | 50 | 0.616427 |
1f8b820e27eb511adecc21032821488ee535f3cf | 2,709 | package com.haohan.platform.service.sys.modules.thirdplatform.feieyun.entity;
import com.haohan.platform.service.sys.common.utils.StringUtils;
import com.haohan.platform.service.sys.modules.xiaodian.entity.printer.FeiePrinter;
import java.io.Serializable;
/**
* Created by dy on 2018/8/1.
*/
public class FeieyunRequestParam implements Serializable{
private static final long serialVersionUID = 1L;
private String printerContent; // 打印机编号(必填) # 打印机识别码(必填) # 备注名称(选填) # 流量卡号码(选填),多台打印机请换行(\n)添加新打印机信息,每次最多100台。
private String sn; // 打印机编号
private String content; // 打印内容,不能超过5000字节
private String times; // 打印次数,默认为1
private String snList; // 打印机编号,多台打印机请用减号“-”连接起来。
private String name; // 打印机备注名称
private String phoneNum; // 打印机流量卡号码(飞鹅)
private String orderId; // 订单ID,由接口Open_printMsg返回。
private String date; // 查询日期,格式YY-MM-DD,如:2016-09-20
// 设置添加打印机时参数
public String fetchPrinterContent(FeiePrinter feiePrinter){
String content = "";
String sn = feiePrinter.getPrinterSn();
String key = feiePrinter.getPrinterKey();
String name = feiePrinter.getPrinterName();
if(!StringUtils.isAnyEmpty(sn, key)){
content = sn + "#" + key;
if(StringUtils.isEmpty(name)){
content = "#" + name;
}
}
this.printerContent = content;
return content;
}
public String getPrinterContent() {
return printerContent;
}
public void setPrinterContent(String printerContent) {
this.printerContent = printerContent;
}
public String getSn() {
return sn;
}
public void setSn(String sn) {
this.sn = sn;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getTimes() {
return times;
}
public void setTimes(String times) {
this.times = times;
}
public String getSnList() {
return snList;
}
public void setSnList(String snList) {
this.snList = snList;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoneNum() {
return phoneNum;
}
public void setPhoneNum(String phoneNum) {
this.phoneNum = phoneNum;
}
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
| 23.973451 | 114 | 0.622739 |
309731cdb873dd94ff41a6a782e5c5a9a236dd03 | 6,207 | package de.fourtytwoways.onion.infrastructure.contracts.db;
import de.fourtytwoways.onion.application.repository.ContractRepository;
import de.fourtytwoways.onion.application.repository.EnumRepository;
import de.fourtytwoways.onion.application.repository.PersonRepository;
import de.fourtytwoways.onion.application.repository.RepositoryRegistry;
import de.fourtytwoways.onion.domain.model.contract.Contract;
import de.fourtytwoways.onion.domain.model.person.Person;
import de.fourtytwoways.onion.domain.model.asset.Money;
import de.fourtytwoways.onion.domain.model.enumeration.EnumType;
import de.fourtytwoways.onion.domain.model.enumeration.Product;
import de.fourtytwoways.onion.domain.model.enumeration.Sex;
import de.fourtytwoways.onion.infrastructure.ExampleTestRepositoryRegistration;
import de.fourtytwoways.onion.infrastructure.database.contract.ContractDAO;
import de.fourtytwoways.onion.infrastructure.database.contract.ContractDbMapper;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.time.LocalDate;
import static org.junit.jupiter.api.Assertions.assertEquals;
class ExampleContractRepositoryTest {
@BeforeAll
public static void setUp() {
ExampleTestRepositoryRegistration.registerRepos();
}
@AfterEach
public void tearDown() {
}
@Test
void createContract() {
EnumRepository myEnumRepository = (EnumRepository) RepositoryRegistry.getInstance().getRepository(EnumRepository.class);
Product endowmentInsurance = (Product) myEnumRepository.getEntryByKey(EnumType.PRODUCT, "GV").orElse(null);
ContractRepository contractRepository =
(ContractRepository) RepositoryRegistry.getInstance().getRepository(ContractRepository.class);
Object contract = contractRepository.createContract("4711",
endowmentInsurance, null,
LocalDate.of(2022, 1, 1),
LocalDate.of(2032, 1, 1),
Money.valueOf(31415.93),
Money.valueOf(3.14));
assert contract instanceof Contract;
assert contract instanceof ContractDbMapper;
assert contract instanceof ContractDAO;
assertEquals("4711", ((Contract) contract).getContractNumber());
assertEquals(endowmentInsurance, ((Contract) contract).getProduct());
}
@Test
void getContractByNumber() {
EnumRepository myEnumRepository = (EnumRepository) RepositoryRegistry.getInstance().getRepository(EnumRepository.class);
Product endowmentInsurance = (Product) myEnumRepository.getEntryByKey(EnumType.PRODUCT, "GV").orElse(null);
PersonRepository personRepository =
(PersonRepository) RepositoryRegistry.getInstance().getRepository(PersonRepository.class);
Sex male = new Sex(2, "M", "Male");
Person beneficiary =
Person.builder()
.id(42)
.name("Tom")
.surname("Flint")
.birthday(LocalDate.of(1966, 6, 6))
.sex(male)
.build();
personRepository.savePerson(beneficiary);
ContractRepository contractRepository =
(ContractRepository) RepositoryRegistry.getInstance().getRepository(ContractRepository.class);
Contract contract = contractRepository.createContract("4711",
endowmentInsurance, beneficiary,
LocalDate.of(2022, 1, 1),
LocalDate.of(2032, 1, 1),
Money.valueOf(31415.93),
Money.valueOf(3.14));
Contract savedContract = contractRepository.saveContract(contract);
assertEquals("4711", savedContract.getContractNumber());
assertEquals(endowmentInsurance, savedContract.getProduct());
assertEquals(beneficiary, savedContract.getBeneficiary());
Contract contractInDb = contractRepository.getContractByNumber("4711");
assert contractInDb instanceof Contract;
assert contractInDb instanceof ContractDbMapper;
assert contractInDb instanceof ContractDAO;
assertEquals("4711", contractInDb.getContractNumber());
assertEquals(endowmentInsurance, contractInDb.getProduct());
assertEquals(beneficiary, contractInDb.getBeneficiary());
assertEquals(savedContract, contractInDb);
}
@Test
void saveContract() {
EnumRepository myEnumRepository = (EnumRepository) RepositoryRegistry.getInstance().getRepository(EnumRepository.class);
Product endowmentInsurance = (Product) myEnumRepository.getEntryByKey(EnumType.PRODUCT, "GV").orElse(null);
ContractRepository contractRepository =
(ContractRepository) RepositoryRegistry.getInstance().getRepository(ContractRepository.class);
Contract contract = contractRepository.createContract("4711",
endowmentInsurance, null,
LocalDate.of(2022, 1, 1),
LocalDate.of(2032, 1, 1),
Money.valueOf(31415.93),
Money.valueOf(3.14));
Contract savedContract = contractRepository.saveContract(contract);
assert savedContract instanceof Contract;
assert savedContract instanceof ContractDbMapper;
assert savedContract instanceof ContractDAO;
assertEquals("4711", savedContract.getContractNumber());
assertEquals(endowmentInsurance, savedContract.getProduct());
}
} | 53.508621 | 128 | 0.626873 |
1488496ebc3a3544d35ece15025475f3775aec22 | 2,007 | /*
* Copyright 2013-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.annotations;
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Artur Konczak
* @author Zeng Zetang
* @author Peter-Josef Meisch
* @author Aleksei Arsenev
* @author Brian Kimmig
* @author Morgan Lutz
*/
public enum FieldType {
Auto("auto"), //
Text("text"), //
Keyword("keyword"), //
Long("long"), //
Integer("integer"), //
Short("short"), //
Byte("byte"), //
Double("double"), //
Float("float"), //
Half_Float("half_float"), //
Scaled_Float("scaled_float"), //
Date("date"), //
Date_Nanos("date_nanos"), //
Boolean("boolean"), //
Binary("binary"), //
Integer_Range("integer_range"), //
Float_Range("float_range"), //
Long_Range("long_range"), //
Double_Range("double_range"), //
Date_Range("date_range"), //
Ip_Range("ip_range"), //
Object("object"), //
Nested("nested"), //
Ip("ip"), //
TokenCount("token_count"), //
Percolator("percolator"), //
Flattened("flattened"), //
Search_As_You_Type("search_as_you_type"), //
/** @since 4.1 */
Rank_Feature("rank_feature"), //
/** @since 4.1 */
Rank_Features("rank_features"), //
/** since 4.2 */
Wildcard("wildcard"), //
/** @since 4.2 */
Dense_Vector("dense_vector") //
;
private final String mappedName;
FieldType(String mappedName) {
this.mappedName = mappedName;
}
public String getMappedName() {
return mappedName;
}
}
| 26.064935 | 75 | 0.674141 |
5258eb2b6743e7cc1d21248a1ac0dd510c198e1e | 2,152 | package shopping.content.v2_1.samples.shippingsettings;
import com.google.api.services.content.model.PostalCodeGroup;
import com.google.api.services.content.model.Service;
import com.google.api.services.content.model.ShippingSettings;
/** Utility class for working with Shippingsettings resources. */
public class ShippingsettingsUtils {
// Currently, this only prints a partial view of the resource, but it's enough to verify
// the results of get()ing/update()ing.
public static void printShippingSettings(ShippingSettings settings) {
System.out.printf("Shipping information for account %d:\n", settings.getAccountId());
if (settings.getPostalCodeGroups() == null || settings.getPostalCodeGroups().isEmpty()) {
System.out.println("- No postal code groups.");
} else {
System.out.printf("- %d postal code group(s):\n", settings.getPostalCodeGroups().size());
for (PostalCodeGroup group : settings.getPostalCodeGroups()) {
System.out.printf(" Postal code group \"%s\":\n", group.getName());
System.out.printf(" - Country: %s\n", group.getCountry());
System.out.printf(
" - Contains %d postal code ranges.\n", group.getPostalCodeRanges().size());
}
}
if (settings.getServices() == null || settings.getServices().isEmpty()) {
System.out.println("- No shipping services.");
} else {
System.out.printf("- %d shipping service(s):\n", settings.getServices().size());
for (Service service : settings.getServices()) {
System.out.printf(" Service \"%s\":\n", service.getName());
System.out.printf(" - Active: %b\n", service.getActive());
System.out.printf(" - Country: %s\n", service.getDeliveryCountry());
System.out.printf(" - Currency: %s\n", service.getCurrency());
System.out.printf(
" - Delivery time: %d - %d days\n",
service.getDeliveryTime().getMinTransitTimeInDays(),
service.getDeliveryTime().getMaxTransitTimeInDays());
System.out.printf(
" - %d rate group(s) in this service.\n", service.getRateGroups().size());
}
}
}
}
| 50.046512 | 95 | 0.657528 |
5f9c0cb40ece16d87c011a07e00588631f156cac | 476 | package com.goshgarmirzayev.lastrebound.service.inter;
import com.goshgarmirzayev.lastrebound.entity.Link;
import com.goshgarmirzayev.lastrebound.entity.Match;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public interface LinkServiceInter {
List<Link> findAll();
Link findById(Integer id);
Link save(Link link);
int deleteById(Integer id);
void deleteAllByMatchId(Match match);
Link findBySlug(String slug);
}
| 20.695652 | 54 | 0.768908 |
06083e4a94605260dc3e6878f85ea35360950d00 | 1,102 | package io.sim.demo.x7;
import io.sim.demo.x7.controller.OmsController;
import io.sim.demo.x7.controller.OrderController;
import io.sim.demo.x7.entity.OrderType;
import io.sim.demo.x7.ro.FindRo;
import io.sim.demo.x7.ro.OrderRo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest
@RunWith(SpringRunner.class)
public class AppTest {
@Autowired
private OrderController orderController;
@Autowired
private OmsController omsController;
@Test
public void testAll(){
OrderRo ro = new OrderRo();
ro.setName("WAAA");
ro.setType(OrderType.PING);
ro.setUserId(1);
orderController.create(ro);
OrderRo refresh = new OrderRo();
refresh.setType(OrderType.SINGLE);
refresh.setId(7);
orderController.refresh(refresh);
orderController.remove(8);
omsController.find(new FindRo());
}
}
| 23.446809 | 62 | 0.713249 |
80e3a2201b1f011d9281db7ac03938e925ed3971 | 4,733 | package com.example.application.views.pegawai;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import com.example.application.entity.Customer;
import com.example.application.entity.Nilai;
import com.example.application.repo.CustomerRepo;
import com.example.application.repo.NilaiRepo;
import com.example.application.views.Action;
import com.example.application.views.main.MainView;
import com.vaadin.flow.component.AttachEvent;
import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.NumberField;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.router.BeforeEvent;
import com.vaadin.flow.router.HasUrlParameter;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.router.RoutePrefix;
import com.vaadin.flow.router.WildcardParameter;
import org.springframework.beans.factory.annotation.Autowired;
@RoutePrefix(value = "pegawai")
@Route(value = "form", layout = MainView.class)
@PageTitle(value = "Pegawai Form")
public class PegawaiForm extends Div implements HasUrlParameter<String> {
@Autowired
private CustomerRepo customerRepo;
@Autowired
private NilaiRepo nilaiRepo;
private Action act;
private Optional<Long> customerId;
private VerticalLayout vLayout = new VerticalLayout();
// private HorizontalLayout hLayout = new HorizontalLayout();
private Customer customer;
private TextField firstName = new TextField("First Name");
private TextField lastName = new TextField("Last Name");
private VerticalLayout vLayoutNilai = new VerticalLayout();
public PegawaiForm() {
}
@Override
public void setParameter(BeforeEvent event, @WildcardParameter String parameter) {
// TODO Auto-generated method stub
// QueryParameters queryParameters = event.getLocation().getQueryParameters();
// Map<String, List<String>> params = queryParameters.getParameters();
// System.out.println(parameter);
this.customerId = Optional.ofNullable(Long.valueOf(event.getLocation().getSegments().get(2)));
this.act = Action.valueOf(event.getLocation().getSegments().get(3));
}
@Override
protected void onAttach(AttachEvent attachEvent) {
// TODO Auto-generated method stub
if (attachEvent.isInitialAttach()) {
initComponents();
}
}
private void simpan() {
customer.setFirstName(firstName.getValue());
customer.setLastName(lastName.getValue());
customer.setAuditDate(new Date());
List<Nilai> liNilais = new ArrayList<>();
Iterator<Component> iterator = vLayoutNilai.getChildren().iterator();
while (iterator.hasNext()) {
Component component = iterator.next();
if (component.getClass().getSimpleName().equalsIgnoreCase("numberfield")) {
NumberField numberField = (NumberField) component;
Nilai nilai = nilaiRepo.findById(Long.valueOf(numberField.getId().get())).get();
if (numberField.getValue() == null) {
numberField.setInvalid(true);
numberField.setErrorMessage("tidak boleh kosong");
return;
}
nilai.setNilai(numberField.getValue());
nilaiRepo.save(nilai);
liNilais.add(nilai);
}
}
customer.setLNilais(liNilais);
customerRepo.save(customer);
}
private void initComponents() {
customer = customerRepo.findById(customerId.get()).get();
firstName.setValue(customer.getFirstName());
lastName.setValue(customer.getLastName());
for (Nilai nilai : customer.getLNilais()) {
NumberField numberField = new NumberField("Nilai " + nilai.getMataKuliah().getNamaMatakuliah());
numberField.setValue(nilai.getNilai());
numberField.setId(String.valueOf(nilai.getId()));
vLayoutNilai.add(numberField);
}
HorizontalLayout layoutButton = new HorizontalLayout();
layoutButton.add(new Button("Batal", e -> UI.getCurrent().navigate(Pegawai.class)), new Button("Simpan", e -> {
simpan();
UI.getCurrent().navigate(Pegawai.class);
}));
vLayout.add(firstName, lastName, vLayoutNilai, layoutButton);
add(vLayout);
}
}
| 40.110169 | 119 | 0.691105 |
0f7d31e827289a1d9f307ffa44d272708a267dfc | 5,636 | package com.pi.ut.automation.services;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Logger;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import com.pi.ut.automation.beans.Servers.Server;
import com.pi.ut.automation.util.ApplicationUtil;
import com.pi.ut.automation.util.HTTPMethod;
import com.pi.ut.automation.util.LogManager;
public abstract class AbstractWebService {
private String wsEndPoint;
protected Server wsServer;
protected XPath xpath = null;
private HashMap<String, String> httpHdrFieldsMap;
private static final String URL_WITH_PORT_FMT = "http://%s:%s/%s";
private static final String URL_NO_PORT_FMT = "http://%s/%s";
private static final Set<Integer> httpSuccessCodes = new HashSet<Integer>(Arrays.asList(200,202));
private static final Logger log = LogManager.getInstance().getLogger();
public AbstractWebService(Server aServer){
this.wsServer = aServer;
this.xpath= XPathFactory.newInstance().newXPath();
this.httpHdrFieldsMap = new HashMap<String, String>();
this.httpHdrFieldsMap.put("Accept-Charset", "UTF-8");
this.httpHdrFieldsMap.put("Content-Type", "text/xml");
}
protected void setWsEndPoint(String wsEndPoint) {
this.wsEndPoint = wsEndPoint;
}
/**
* Method to get the assigned server for this instance
* @return
*/
public Server getAssignedServer(){
return this.wsServer;
}
/**
* Utility method to compose the Service URL to be used to http request.
* @return
*/
public String getServiceURL(){
if(ApplicationUtil.isBlankOrNull(this.wsServer.getPort())){
return String.format(URL_NO_PORT_FMT, this.wsServer.getHostName(),this.wsEndPoint);
}
return String.format(URL_WITH_PORT_FMT, this.wsServer.getHostName(),this.wsServer.getPort(),this.wsEndPoint);
}
/**
* <p>Helper method to create the auth header for basic authentication module</p>
* @return
*/
protected String getBasicAuthorisationHeader(){
String sUserCredentials = this.wsServer.getUserName()+":"+this.wsServer.getPassword();
String sBasicAuth = "Basic " +ApplicationUtil.base64Encode(sUserCredentials);
return sBasicAuth;
}
/**
* Method to add custom HTTP header
* @param sHeader
* @param sValue
*/
protected void addHTTPHeader(String sHeader,String sValue){
this.httpHdrFieldsMap.put(sHeader, sValue);
}
/**
* Utility method to perform a HTTP call to the server.
* @param sPayload
* @param httpMethod
* @return
* @throws Exception
*/
protected String executeHTTPRequest(String sPayload,HTTPMethod httpMethod) throws Exception{
log.entering(getClass().getName(), "performHTTPCall");
PrintWriter writer = null;
//OutputStreamWriter writer = null;
BufferedReader reader = null;
HttpURLConnection httpCon = null;
String sTargetURL = getServiceURL();
log.info("Performing HTTP "+httpMethod.name()+" to "+sTargetURL);
try{
URL url = new URL(sTargetURL);
httpCon = (HttpURLConnection)url.openConnection();
httpCon.setRequestProperty ("Authorization", getBasicAuthorisationHeader());
httpCon.setRequestMethod(httpMethod.name());
for(String sHdr : this.httpHdrFieldsMap.keySet()){
log.fine("Setting HTTP Header: Name="+sHdr+" , value="+this.httpHdrFieldsMap.get(sHdr));
httpCon.setRequestProperty(sHdr,this.httpHdrFieldsMap.get(sHdr));
}
httpCon.setRequestProperty("Content-Length", "" + Integer.toString(sPayload.getBytes().length));
httpCon.setUseCaches(false);
httpCon.setDoInput(true);
httpCon.setDoOutput(true);
/* Trigger HTTP Request */
log.fine("Sending HTTP request with payload : "+sPayload);
writer = new PrintWriter(new OutputStreamWriter(httpCon.getOutputStream()),true);//new OutputStreamWriter(httpCon.getOutputStream());
writer.write(new String(sPayload.getBytes("UTF-8")));
writer.write(new String(sPayload.getBytes()));
log.info("HTTP request send to server, reading response from server");
writer.flush();
/* Read Response from server */
log.info("HTTP status code "+httpCon.getResponseCode()+" received");
if(!httpSuccessCodes.contains(httpCon.getResponseCode())){
/* Any response code other that HTTP 200 or 202 is treated as error,
* read response from error stream */
reader = new BufferedReader(new InputStreamReader(httpCon.getErrorStream()));
}else{
reader = new BufferedReader(new InputStreamReader(httpCon.getInputStream(),"UTF-8"));
}
StringBuilder sResponseBuilder = new StringBuilder();
String sLine;
while ((sLine = reader.readLine()) != null) {
sResponseBuilder.append(sLine);
}
if(!httpSuccessCodes.contains(httpCon.getResponseCode())){
log.severe("HTTP ERROR status code "+httpCon.getResponseCode()+" received, raising exception");
log.severe("HTTP ERROR Message "+sResponseBuilder.toString());
throw new ConnectException("HTTP Code: "+httpCon.getResponseCode()+", HTTP Message :"+sResponseBuilder.toString());
}
log.fine("HTTP response : "+sResponseBuilder.toString());
return sResponseBuilder.toString();
}finally{
if(null!=writer) writer.close();
if(null!=reader) reader.close();
log.exiting(getClass().getName(), "performHTTPCall");
}
}
}
| 36.597403 | 138 | 0.715224 |
558e255067f54fca2b0293a9ac985b503c0eeb6c | 129 | package model.multipleturtle;
public interface MultipleTurtleCommand {
public AskTellData getData();
public void execute();
}
| 18.428571 | 40 | 0.79845 |
56edfa202a4353d23949147dd7996a2986147664 | 1,041 | package com.antheminc.oss.nimbus.domain.config.builder;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.mock.web.MockHttpServletRequest;
import com.antheminc.oss.nimbus.InvalidConfigException;
import com.antheminc.oss.nimbus.domain.cmd.Action;
import com.antheminc.oss.nimbus.test.domain.support.AbstractFrameworkIntegrationTests;
import com.antheminc.oss.nimbus.test.domain.support.utils.MockHttpRequestBuilder;
public class ExcludePackageScanTest extends AbstractFrameworkIntegrationTests {
@Rule
public ExpectedException thrown= ExpectedException.none();
@Test
public void testShouldNotScanTheConfiguredBasePackage(){
MockHttpServletRequest request = MockHttpRequestBuilder.withUri(PLATFORM_ROOT+"/sampleExcludeEntity").addAction(Action._new).getMock();
thrown.expect(InvalidConfigException.class);
thrown.expectMessage("Domain model config not found for root-alias: sampleExcludeEntity");
controller.handlePost(request, null);
}
}
| 40.038462 | 152 | 0.820365 |
67d0fdecbc287243057cbcb160605e4ccbc30c72 | 546 | package tech.xuanwu.northstar.meta;
import java.util.ArrayList;
import java.util.List;
import org.apache.lucene.util.RamUsageEstimator;
import tech.xuanwu.northstar.persistence.po.MinBarDataPO;
import tech.xuanwu.northstar.persistence.po.TickDataPO;
public class ObjectSizeTest {
public static void main(String[] args) {
List<TickDataPO> tickList = new ArrayList<>();
for(int i=0; i<120; i++) {
tickList.add(new TickDataPO());
}
MinBarDataPO po = new MinBarDataPO();
System.out.println(RamUsageEstimator.humanSizeOf(po));
}
}
| 24.818182 | 57 | 0.754579 |
81a34123dfaaca02d1aca3e2656c767e47955673 | 8,503 | package edu.ucsd.library.dams.triple;
import java.util.Set;
/**
* Primary interface for TripleStores. All general-purposes classes that work
* with TripleStores should use this interface, not the abstract classes or
* implementing classes directly.
* @author [email protected]
**/
public interface TripleStore
{
/**************************************************************************/
/*** Read-Only Triple API *************************************************/
/**************************************************************************/
/**
* Export subjects or statements to a file.
* @param f File to export to.
* @param subjectsOnly If true, only list subjects. If false, export all
* statements.
**/
public void export( java.io.File f, boolean subjectsOnly )
throws TripleStoreException;
/**
* Export subjects or statements to a file.
* @param f File to export to.
* @param subjectsOnly If true, only list subjects. If false, export all
* statements.
* @param parent Limit export to objects matching substring.
**/
public void export( java.io.File f, boolean subjectsOnly, String parent )
throws TripleStoreException;
/**
* List statements contained in the triplestore, optionally limited by one
* or more of the parameters (any null parameters will match all values).
* @param subject Limit to statements about this subject, null matches all.
* @param predicate Limit to statements containing this predicate, null
* matches all.
* @param object Limit to statements containing this object, null matches
* all.
**/
public StatementIterator listLiteralStatements( Identifier subject,
Identifier predicate, String object ) throws TripleStoreException;
/**
* List statements contained in the triplestore, optionally limited by one
* or more of the parameters (any null parameters will match all values).
* @param subject Limit to statements about this subject, null matches all.
* @param predicate Limit to statements containing this predicate, null
* matches all.
* @param object Limit to statements containing this object, null matches
* all.
**/
public StatementIterator listStatements( Identifier subject,
Identifier predicate, Identifier object ) throws TripleStoreException;
/**
* List the subjects described in the triplestore.
**/
public SubjectIterator listSubjects() throws TripleStoreException;
/**
* Test whether an object is described in the triplestore.
**/
public boolean exists( Identifier subject ) throws TripleStoreException;
/**************************************************************************/
/*** Read-Write Triple API ************************************************/
/**************************************************************************/
/**
* Add a statement to the triplestore, with a literal value object.
* @param subject Subject URI or blank node id.
* @param predicate Predicate URI.
* @param object Literal value.
**/
public void addLiteralStatement( Identifier subject, Identifier predicate,
String object, Identifier parent ) throws TripleStoreException;
/**
* Add a statement to the triplestore.
* @param stmt Statement object to add.
**/
public void addStatement( Statement stmt, Identifier parent )
throws TripleStoreException;
/**
* Add a statement to the triplestore, with a URI or blank node object.
* @param subject Subject URI or blank node.
* @param predicate Predicate URI.
* @param object Object URI or blank node.
**/
public void addStatement( Identifier subject, Identifier predicate,
Identifier object, Identifier parent ) throws TripleStoreException;
/**
* Create a blank node.
**/
public Identifier blankNode() throws TripleStoreException;
/**
* Create a blank node with the specified id.
* @param subject The subject for the object which contains this blank node.
* @param id The blank node identifier.
**/
public Identifier blankNode( Identifier subject, String id )
throws TripleStoreException;
/**
* Remove multiple statements, optionally limited by one or more of the
* parameters (any null parameters will match all values).
* @param subject Limit to statements about this subject, null matches all.
* @param predicate Limit to statements containing this predicate, null
* matches all.
* @param object Limit to statements containing this object, null matches
* all.
**/
public void removeStatements( Identifier subject, Identifier predicate,
Identifier object ) throws TripleStoreException;
/**
* Remove multiple statements, optionally limited by one or more of the
* parameters (any null parameters will match all values).
* @param subject Limit to statements about this subject, null matches all.
* @param predicate Limit to statements containing this predicate, null
* matches all.
* @param object Limit to statements containing this literal value, null
* matches all.
**/
public void removeLiteralStatements( Identifier subject,
Identifier predicate, String object ) throws TripleStoreException;
/**
* Recursively remove all statements associated with a subject, including
* blank nodes and their children.
* @param subject Subject of the object to delete.
**/
public void removeObject( Identifier subject ) throws TripleStoreException;
/**
* Remove all statements from the triplestore.
**/
public void removeAll() throws TripleStoreException;
/**************************************************************************/
/*** Utility API **********************************************************/
/**************************************************************************/
/**
* Close the triplestore and release any resources.
**/
public void close() throws TripleStoreException;
/**
* Setup new triplestore.
**/
public void init() throws TripleStoreException;
/**
* Test whether a triplestore instance is connected and ready to use.
**/
public boolean isConnected();
/**
* Load triples from an N-triples file on disk.
* @param filename RDF filename.
**/
public void loadNTriples( String filename, Set<String> validClasses,
Set<String> validProperties ) throws TripleStoreException;
/**
* Load triples from an RDF XML file on disk.
* @param filename RDF filename.
**/
public void loadRDFXML( String filename, Set<String> validClasses, Set<String> validProperties )
throws TripleStoreException;
/**
* Perform any maintenance required after performing triplestore updates.
**/
public void optimize() throws TripleStoreException;
/**
* Get the number of triples in the triplestore.
**/
public long size() throws TripleStoreException;
/**
* Get the name of this triplestore.
**/
public String name();
/**************************************************************************/
/*** SPARQL Query API *****************************************************/
/**************************************************************************/
/**
* Perform a SPARQL ASK query.
* @param query SPARQL ASK query to execute.
**/
public boolean sparqlAsk( String query ) throws TripleStoreException;
/**
* Perform a SPARQL SELECT query and count the results.
* @param query SPARQL SELECT query to execute.
**/
public long sparqlCount( String query ) throws TripleStoreException;
/**
* Perform a SPARQL DESCRIBE query.
* @param query SPARQL DESCRIBE query to execute.
**/
public StatementIterator sparqlDescribe( String query )
throws TripleStoreException;
/**
* Perform a SPARQL DESCRIBE query.
* @param id Identifier for the object to describe.
**/
public StatementIterator sparqlDescribe( Identifier id )
throws TripleStoreException;
/**
* Perform SPARQL DESCRIBE queries for each identifier listed.
* @param ids Set of Identifiers for the objects to describe.
**/
public StatementIterator sparqlDescribe( Set<Identifier> ids )
throws TripleStoreException;
/**
* Perform a SPARQL SELECT query.
* @param query SPARQL SELECT query to execute.
**/
public BindingIterator sparqlSelect( String query )
throws TripleStoreException;
}
| 34.565041 | 97 | 0.634835 |
64837a768384b1c797b1a5f00a1819ace79921f9 | 3,567 | /*
* Copyright 2017 Google, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.spinnaker.orca.clouddriver.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.netflix.spinnaker.kork.annotations.NonnullByDefault;
import com.netflix.spinnaker.kork.artifacts.model.Artifact;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.annotation.ParametersAreNullableByDefault;
import lombok.Builder;
import lombok.Value;
@JsonDeserialize(builder = Manifest.ManifestBuilder.class)
@NonnullByDefault
@Value
public final class Manifest {
private final ImmutableMap<String, Object> manifest;
private final ImmutableList<Artifact> artifacts;
private final Status status;
private final String name;
private final ImmutableList<String> warnings;
@Builder(toBuilder = true)
@ParametersAreNullableByDefault
private Manifest(
Map<String, Object> manifest,
List<Artifact> artifacts,
Status status,
String name,
List<String> warnings) {
this.manifest =
Optional.ofNullable(manifest).map(ImmutableMap::copyOf).orElseGet(ImmutableMap::of);
this.artifacts =
Optional.ofNullable(artifacts).map(ImmutableList::copyOf).orElseGet(ImmutableList::of);
this.status = Optional.ofNullable(status).orElseGet(() -> Status.builder().build());
this.name = Optional.ofNullable(name).orElse("");
this.warnings =
Optional.ofNullable(warnings).map(ImmutableList::copyOf).orElseGet(ImmutableList::of);
}
@JsonDeserialize(builder = Manifest.Status.StatusBuilder.class)
@Value
public static final class Status {
private final Condition stable;
private final Condition failed;
@Builder(toBuilder = true)
@ParametersAreNullableByDefault
private Status(Condition stable, Condition failed) {
this.stable = Optional.ofNullable(stable).orElseGet(Condition::emptyFalse);
this.failed = Optional.ofNullable(failed).orElseGet(Condition::emptyFalse);
}
@JsonPOJOBuilder(withPrefix = "")
public static final class StatusBuilder {}
}
@Value
public static final class Condition {
private static final Condition TRUE = new Condition(true, "");
private static final Condition FALSE = new Condition(false, "");
private final boolean state;
private final String message;
@ParametersAreNullableByDefault
public Condition(
@JsonProperty("state") boolean state, @JsonProperty("message") String message) {
this.state = state;
this.message = Optional.ofNullable(message).orElse("");
}
public static Condition emptyFalse() {
return FALSE;
}
public static Condition emptyTrue() {
return TRUE;
}
}
@JsonPOJOBuilder(withPrefix = "")
public static final class ManifestBuilder {}
}
| 33.650943 | 95 | 0.742361 |
755ce0d5a8b5e66d3bf925bc788cf09abe0d9bb3 | 1,928 | package com.eiffel.annotators;
import com.eiffel.ide.quickfix.EiffelRemoveElementsQuickFix;
import com.eiffel.psi.*;
import com.intellij.lang.annotation.AnnotationHolder;
import com.intellij.lang.annotation.Annotator;
import com.intellij.psi.PsiElement;
import org.jetbrains.annotations.NotNull;
import java.util.Arrays;
/**
* Creation features must not have a return value
*/
public class EiffelCreationFeatureNotVoidAnnotator extends EiffelNewFeatureAnnotatorBase {
@Override
protected void annotate_impl(@NotNull PsiElement element, @NotNull AnnotationHolder holder) {
final String featureName = element.getText();
EiffelClassDeclaration currentClass = EiffelClassUtil.findClassDeclaration(element);
if (currentClass == null) return;
EiffelNewFeature creationFeature = currentClass.getNewFeature(featureName);
if (creationFeature == null) return;
if (!currentClass.getCreationProcedures().contains(creationFeature)) return;
if (creationFeature.getTypeString() != null) {
EiffelFeatureDeclaration featureDeclaration = creationFeature.getFeatureDeclaration();
EiffelType type = featureDeclaration.getType();
PsiElement colon = type;
do {
colon = colon.getPrevSibling();
} while (colon != null && !colon.getNode().getElementType().equals(EiffelTypes.COLON));
if (colon == null)
holder.createWarningAnnotation(element.getTextRange(), "Creation feature with return value")
.registerFix(new EiffelRemoveElementsQuickFix("Remove return value", Arrays.asList(type)));
else
holder.createWarningAnnotation(element.getTextRange(), "Creation feature with return value")
.registerFix(new EiffelRemoveElementsQuickFix("Remove return value", Arrays.asList(type, colon)));
}
}
}
| 47.02439 | 122 | 0.704876 |
b151150179e0fe8f73924d50b9a5af8c75504bd8 | 4,342 | /*
* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.registry.webdav;
import java.util.HashSet;
import javax.jcr.Credentials;
import javax.jcr.LoginException;
import javax.jcr.SimpleCredentials;
import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import org.apache.jackrabbit.server.CredentialsProvider;
import org.apache.jackrabbit.webdav.DavException;
import org.apache.jackrabbit.webdav.DavServletResponse;
import org.apache.jackrabbit.webdav.DavSession;
import org.apache.jackrabbit.webdav.DavSessionProvider;
import org.apache.jackrabbit.webdav.WebdavRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wso2.carbon.registry.core.Registry;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
public class RegistrySessionProvider implements DavSessionProvider{
private static Logger log = LoggerFactory.getLogger(RegistrySessionProvider.class);
private CredentialsProvider credentialsProvider;
private ThreadLocal<RegistryWebDavContext> threadLocal;
private WebDavEnviorment enviorment;
public RegistrySessionProvider(CredentialsProvider credentialsProvider, ThreadLocal<RegistryWebDavContext> threadLocal, WebDavEnviorment enviorment) {
this.credentialsProvider = credentialsProvider;
this.threadLocal = threadLocal;
this.enviorment = enviorment;
this.enviorment.setSessionProvider(this);
}
public boolean attachSession(WebdavRequest request) throws DavException {
try {
HttpSession session = request.getSession(true);
RegistryWebDavContext webdavContext = (RegistryWebDavContext) session
.getAttribute(RegistryServlet.WEBDAV_CONTEXT);
if(webdavContext == null){
Credentials credentials = credentialsProvider.getCredentials(request);
SimpleCredentials simpleCredentials = (SimpleCredentials)credentials;
final String userID = simpleCredentials.getUserID();
String password = new String(simpleCredentials.getPassword());
if(userID == null || password == null || userID.length() == 0 || password.length() == 0){
throw new DavException(DavServletResponse.SC_UNAUTHORIZED,"Bassic HTTP Autentication is required");
}
//TODOD remove this
// String userID = "admin";
// String password = "admin";
Registry registry = WebdavServiceComponet.getRegistryInstance(
userID, password);
webdavContext = new RegistryWebDavContext(registry, request.getContextPath());
webdavContext.setEnviorment(enviorment);
session.setAttribute(RegistryServlet.WEBDAV_CONTEXT, webdavContext);
}
threadLocal.set(webdavContext);
request.setDavSession(new DavSession() {
private final HashSet lockTokens = new HashSet();
public void removeReference(Object reference) {
}
public void removeLockToken(String token) {
lockTokens.remove(token);
}
public String[] getLockTokens() {
return (String[]) lockTokens.toArray(new String[lockTokens.size()]);
}
public void addReference(Object reference) {
}
public void addLockToken(String token) {
lockTokens.add(token);
}
});
webdavContext.setSession(request.getDavSession());
return true;
} catch (LoginException e) {
e.printStackTrace();
throw new DavException(DavServletResponse.SC_BAD_REQUEST,e);
} catch (ServletException e) {
e.printStackTrace();
throw new DavException(DavServletResponse.SC_BAD_REQUEST,e);
} catch (RegistryException e) {
e.printStackTrace();
throw new DavException(DavServletResponse.SC_BAD_REQUEST,e);
}
}
public void releaseSession(WebdavRequest request) {
// TODO We use http session here, hence nothing to be done
}
}
| 35.300813 | 151 | 0.756794 |
3b1f8d20c2af0a297a8924775b28f43b2c93f0f8 | 3,787 | /*
@author-name: Roger Ulate Rivera
@author-creation-date: 09/08/2017
*/
import javax.swing.JOptionPane;
public class LaboratorioCuatro {
public static void main(String[] args) {
// Nuevas variables
String valor;
String valorDos;
int numeroALetra;
String resultadoUno;
int resultadoDos;
int numeroUno;
int numeroDos;
int resultadoTres;
String numeroString;
String resultadoCuatro;
int resultadoCinco;
// Listado de instancias
ConversorNumerico conversorNumerico = new ConversorNumerico();
Ciclos ciclos = new Ciclos();
// Impresiones
System.out.println(" * --------------- Conectando a Sistema ------------- *");
System.out.println(" * ");
System.out.println(" * ");
System.out.println(" * ");
System.out.println(" * ------------------- Inicializado ----------------- *");
System.out.println(" ");
System.out.println(" ");
//Parte I
JOptionPane.showMessageDialog(null, "Ejercicios, Parte I");
// Ejercicio #1
valor = JOptionPane.showInputDialog("Convertire un numero entero de 1 al 10 a letras, por favor ingrese el numero:");
numeroALetra = ciclos.obtenerResultadoTryCatch(valor);
resultadoUno = conversorNumerico.convertirALetras(numeroALetra);
JOptionPane.showMessageDialog(null, "El pasar el numero " + numeroALetra + " a letras es: " + resultadoUno);
// Ejercicio #2
valor = JOptionPane.showInputDialog("Convertire un nombre de numero de 1 al 10 a numero, por favor escriba el numero en letras:");
resultadoDos = conversorNumerico.convertirANumeros(valor);
JOptionPane.showMessageDialog(null, "El pasar el numero en letras " + valor + " a numero es: " + resultadoDos);
//Parte II
JOptionPane.showMessageDialog(null, "Ejercicios, Parte II");
// Ejercicio #1
JOptionPane.showMessageDialog(null, "Con un ciclo tipo While calculare la sumatoria desde un numero hasta otro numero");
valor = JOptionPane.showInputDialog("Ingrese el numero desde donde comenzare a calcular");
numeroUno = ciclos.obtenerResultadoTryCatch(valor);
valorDos = JOptionPane.showInputDialog("Ingrese el numero hasta donde calculare");
numeroDos = ciclos.obtenerResultadoTryCatch(valorDos);
resultadoTres = ciclos.sumatoriaNumeros(numeroUno, numeroDos);
JOptionPane.showMessageDialog(null, "El resultado de la sumatoria de " + numeroUno + " hasta " + numeroDos + " es de:" + resultadoTres);
// Ejercicio #2
JOptionPane.showMessageDialog(null, "Usando un ciclo tipo Do/While calculare la sumatoria de un numero");
valor = JOptionPane.showInputDialog("Ingrese el numero hasta donde llegare");
resultadoCuatro = ciclos.devolverSumatoriaEntero(valor);
JOptionPane.showMessageDialog(null, "La sumatoria de " + valor + " es: " + resultadoCuatro);
// Ejercicio #3
JOptionPane.showMessageDialog(null, "Utilizando un ciclo for, calculare y retornare la suma de todos los numeros impares entre 0 al numero que me des.");
valor = JOptionPane.showInputDialog("Ingrese un numero entero que sera mi limite");
numeroUno = ciclos.obtenerResultadoTryCatch(valor);
resultadoCinco = ciclos.sumatoriaNumerosImpares(numeroUno);
JOptionPane.showMessageDialog(null, "La sumatoria de los numeros impares hasta el " + valor + ", es de: " + resultadoCinco);
// Ejercicio #4
JOptionPane.showMessageDialog(null, "Imprimire la cantidad de multiplos que me digas desde donde me digas, el resultado lo mostrare en CONSOLA");
valor = JOptionPane.showInputDialog("Dame la cantidad de multiplos que debere imprimir");
numeroUno = ciclos.obtenerResultadoTryCatch(valor);
valorDos = JOptionPane.showInputDialog("Dame la el numoer desde donde comenzare y tambien sera el multiplo que calculare");
numeroDos = ciclos.obtenerResultadoTryCatch(valorDos);
ciclos.multiplos(numeroUno, numeroDos);
}
} | 38.252525 | 155 | 0.736995 |
252c9ed6964dbb79fda335f69cf667e2206218b8 | 3,575 | package com.kdp.starbarcode.core;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import java.util.Collection;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.Map;
/***
* @author kdp
* @date 2019/1/15 11:52
*/
class BarCodeReaderManager {
private final MultiFormatReader multiFormatReader;
private Map<DecodeHintType, Object> hintTypeMap;
private Collection<BarcodeFormat> decodeFormats;
BarCodeReaderManager() {
multiFormatReader = new MultiFormatReader();
hintTypeMap = new EnumMap<>(DecodeHintType.class);
decodeFormats = EnumSet.noneOf(BarcodeFormat.class);
}
Map<DecodeHintType, Object> getHintTypeMap() {
return hintTypeMap;
}
/**
* 解码条形码
*
* @param bitmap
*/
Result decodeWithState(BinaryBitmap bitmap) {
try {
return multiFormatReader.decodeWithState(bitmap);
} catch (NotFoundException e) {
e.printStackTrace();
} finally {
multiFormatReader.reset();
}
return null;
}
/**
* 添加所有条码格式
*/
void addAllBarCodeFormat() {
decodeFormats.addAll(BarCodeFormatManager.ALL_FORMATS);
hintTypeMap.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormats);
hintTypeMap.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
hintTypeMap.put(DecodeHintType.CHARACTER_SET, "utf-8");
multiFormatReader.setHints(hintTypeMap);
}
/**
* 添加所有的一维条形码格式
*/
void addOneDBarCodeFormat() {
decodeFormats.addAll(BarCodeFormatManager.ONE_D_FORMATS);
hintTypeMap.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormats);
hintTypeMap.put(DecodeHintType.CHARACTER_SET, "utf-8");
multiFormatReader.setHints(hintTypeMap);
}
/**
* 添加所有的二维条形码格式
*/
void addTwoDBarCodeForamt() {
decodeFormats.addAll(BarCodeFormatManager.TWO_D_FORMATS);
hintTypeMap.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormats);
hintTypeMap.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
hintTypeMap.put(DecodeHintType.CHARACTER_SET, "utf-8");
multiFormatReader.setHints(hintTypeMap);
}
/**
* 添加二维码QR_CODE格式
*/
void addQRBarCode() {
decodeFormats.addAll(BarCodeFormatManager.QR_CODE_FORMATS);
hintTypeMap.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormats);
hintTypeMap.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
hintTypeMap.put(DecodeHintType.CHARACTER_SET, "utf-8");
multiFormatReader.setHints(hintTypeMap);
}
/**
* 添加Code 128格式
*/
void addCode128BarCode() {
decodeFormats.addAll(BarCodeFormatManager.CODE_128_FORMATS);
hintTypeMap.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormats);
hintTypeMap.put(DecodeHintType.CHARACTER_SET, "utf-8");
multiFormatReader.setHints(hintTypeMap);
}
/**
* 添加指定条码格式
*
* @param formats
*/
void addBarCodeFormat(Collection<BarcodeFormat> formats) {
decodeFormats.addAll(formats);
hintTypeMap.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormats);
if (formats.contains(BarcodeFormat.QR_CODE))
hintTypeMap.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
hintTypeMap.put(DecodeHintType.CHARACTER_SET, "utf-8");
multiFormatReader.setHints(hintTypeMap);
}
}
| 30.555556 | 72 | 0.685035 |
7d7969f9096e4b3e37507108e0bccbbfff8312ff | 586 | //,temp,FhirSearchIT.java,40,50,temp,FhirExtraParametersIT.java,44,58
//,3
public class xxx {
@Test
public void testSearchByUrl() throws Exception {
String url = "Patient?given=Vincent&family=Freeman&_format=json";
Bundle result = requestBody("direct://SEARCH_BY_URL", url);
LOG.debug("searchByUrl: " + result);
assertNotNull(result, "searchByUrl result");
Patient patient = (Patient) result.getEntry().get(0).getResource();
assertNotNull(patient);
assertEquals("Freeman", patient.getName().get(0).getFamily());
}
}; | 36.625 | 75 | 0.665529 |
75fcf4c27b08cb5615df623d62f9373fb49bfcc8 | 1,062 | package io.redspark.ireadme.init;
import javax.servlet.Filter;
import org.springframework.core.annotation.Order;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
@Order(1)
public class AppBootstrap extends AbstractAnnotationConfigDispatcherServletInitializer{
private static final String APP_ENCONDING_DEFAULT = "UTF-8";
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { AppConfig.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { AppWebConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String [] { "/api/*" };
}
@Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding(APP_ENCONDING_DEFAULT);
characterEncodingFilter.setForceEncoding(true);
return new Filter[] { characterEncodingFilter };
}
}
| 27.230769 | 100 | 0.785311 |
db8a72b95492be2656f5096fb444f93fa52d0e65 | 365 | package ie.gmit.sw;
// 第一步
import java.util.*;
public class InheritStack<E> extends ArrayList<E> implements Stackator<E> {
private static final long serialVersionUID = 777L;
public E peek() {
return get(size() - 1);
}
public E pop() {
E element = peek();
remove(size() - 1);
return element;
}
public void push(E element) {
add(element);
}
}
| 14.6 | 75 | 0.652055 |
31e86fc9f9b1a5b9a733657accec1d64becf34b0 | 7,645 | /*
* Copyright (C) 2010-2015 FBReader.ORG Limited <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
package org.geometerplus.android.fbreader.network;
import java.util.*;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.*;
import android.widget.*;
import com.mobeta.android.dslv.DragSortListView;
import org.geometerplus.zlibrary.ui.android.R;
import org.geometerplus.fbreader.network.*;
import org.geometerplus.android.fbreader.FBReader;
import org.geometerplus.android.fbreader.covers.CoverManager;
import org.geometerplus.android.util.ViewUtil;
import org.geometerplus.android.fbreader.util.AndroidImageSynchronizer;
public class CatalogManagerActivity extends ListActivity {
private final AndroidImageSynchronizer myImageSynchronizer = new AndroidImageSynchronizer(this);
private final List<Item> myAllItems = new ArrayList<Item>();
private final List<Item> mySelectedItems = new ArrayList<Item>();
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.catalog_manager_view);
}
@Override
protected void onStart() {
super.onStart();
myAllItems.clear();
final Intent intent = getIntent();
myAllItems.add(new SectionItem("enabled"));
final List<String> enabledIds =
intent.getStringArrayListExtra(NetworkLibraryActivity.ENABLED_CATALOG_IDS_KEY);
if (enabledIds.size() > 0) {
final List<CatalogItem> cItems = new ArrayList<CatalogItem>();
for (String id : enabledIds) {
final NetworkTree tree = Util.networkLibrary(this).getCatalogTreeByUrlAll(id);
if (tree != null && tree.getLink() != null) {
cItems.add(new CatalogItem(id, true, tree));
}
}
myAllItems.addAll(cItems);
mySelectedItems.addAll(cItems);
}
myAllItems.add(new SectionItem("disabled"));
final List<String> disabledIds =
intent.getStringArrayListExtra(NetworkLibraryActivity.DISABLED_CATALOG_IDS_KEY);
if (disabledIds.size() > 0) {
final TreeSet<CatalogItem> cItems = new TreeSet<CatalogItem>();
for (String id : disabledIds) {
final NetworkTree tree = Util.networkLibrary(this).getCatalogTreeByUrlAll(id);
if (tree != null && tree.getLink() != null) {
cItems.add(new CatalogItem(id, false, tree));
}
}
myAllItems.addAll(cItems);
}
setListAdapter(new CatalogsListAdapter());
}
@Override
protected void onDestroy() {
myImageSynchronizer.clear();
super.onDestroy();
}
@Override
public DragSortListView getListView() {
return (DragSortListView)super.getListView();
}
private static interface Item {
}
private static class SectionItem implements Item {
private final String Title;
public SectionItem(String key) {
Title = NetworkLibrary.resource().getResource("manageCatalogs").getResource(key).getValue();
}
}
private static class CatalogItem implements Item, Comparable<CatalogItem> {
private final String Id;
private final NetworkTree Tree;
private boolean IsChecked;
public CatalogItem(String id, boolean checked, NetworkTree tree) {
Id = id;
IsChecked = checked;
Tree = tree;
}
public String getTitle() {
return Tree.getLink().getTitle();
}
private String getTitleLower() {
return getTitle().toLowerCase(Locale.getDefault());
}
@Override
public int compareTo(CatalogItem another) {
return getTitleLower().compareTo(another.getTitleLower());
}
}
private class CatalogsListAdapter extends ArrayAdapter<Item> implements DragSortListView.DropListener, DragSortListView.RemoveListener {
private CoverManager myCoverManager;
public CatalogsListAdapter() {
super(CatalogManagerActivity.this, R.layout.catalog_manager_item, myAllItems);
}
private int indexOfDisabledSectionItem() {
for (int i = 1; i < getCount(); i++) {
if (getItem(i) instanceof SectionItem) {
return i;
}
}
// should be impossible
return 0;
}
private void setResultIds() {
final ArrayList<String> ids = new ArrayList<String>();
for (int i = 1; i < getCount(); ++i) {
final Item item = getItem(i);
if (item instanceof SectionItem) {
continue;
}
final CatalogItem catalogItem = (CatalogItem)item;
if (catalogItem.IsChecked) {
ids.add(catalogItem.Id);
}
}
setResult(RESULT_OK, new Intent().putStringArrayListExtra(NetworkLibraryActivity.ENABLED_CATALOG_IDS_KEY, ids));
}
@Override
public View getView(int position, View convertView, final ViewGroup parent) {
final Item item = getItem(position);
final View view;
if (convertView != null && item.getClass().equals(convertView.getTag())) {
view = convertView;
} else {
view = getLayoutInflater().inflate(
item instanceof SectionItem
? R.layout.catalog_manager_section_head : R.layout.catalog_manager_item,
null
);
view.setTag(item.getClass());
}
if (item instanceof SectionItem) {
ViewUtil.setSubviewText(
view, R.id.catalog_manager_section_head_title, ((SectionItem)item).Title
);
} else /* if (item instanceof CatalogItem) */ {
final CatalogItem catalogItem = (CatalogItem)item;
if (myCoverManager == null) {
view.measure(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
final int coverHeight = view.getMeasuredHeight();
myCoverManager = new CoverManager(CatalogManagerActivity.this, myImageSynchronizer, coverHeight * 15 / 22, coverHeight);
view.requestLayout();
}
final INetworkLink link = catalogItem.Tree.getLink();
ViewUtil.setSubviewText(view, R.id.catalog_manager_item_title, link.getTitle());
ViewUtil.setSubviewText(view, R.id.catalog_manager_item_subtitle, link.getSummary());
final ImageView coverView = ViewUtil.findImageView(view, R.id.catalog_manager_item_icon);
if (!myCoverManager.trySetCoverImage(coverView, catalogItem.Tree)) {
coverView.setImageResource(R.drawable.ic_list_library_books);
}
final CheckBox checkBox = (CheckBox)ViewUtil.findView(view, R.id.catalog_manager_item_checkbox);
checkBox.setChecked(catalogItem.IsChecked);
checkBox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
catalogItem.IsChecked = checkBox.isChecked();
setResultIds();
}
});
}
return view;
}
// method from DragSortListView.DropListener
public void drop(int from, int to) {
to = Math.max(to, 1);
if (from == to) {
return;
}
final Item item = getItem(from);
if (item instanceof CatalogItem) {
remove(item);
insert(item, to);
((CatalogItem)item).IsChecked = to < indexOfDisabledSectionItem();
getListView().moveCheckState(from, to);
setResultIds();
}
}
// method from DragSortListView.RemoveListener
public void remove(int which) {
final Item item = getItem(which);
if (item instanceof CatalogItem) {
remove(item);
getListView().removeCheckState(which);
}
}
}
}
| 30.702811 | 137 | 0.724657 |
eda58d88c543454eb0aa27b37afe9e1fe0ccc330 | 2,567 | /**
* Copyright 2013 Mohawk College of Applied Arts and Technology
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*
*
* Date: October 29, 2013
*
*/
package org.marc.shic.core;
import java.util.ArrayList;
import java.util.List;
/**
* Represents a person's address.
*
* @author ibrahimm
*/
public class PersonAddress {
private ArrayList<AddressComponent> parts;
private AddressUse use;
/**
* Create an address with a specific use.
*
* @param use
* The type of address (Work, home, et cetera)
*/
public PersonAddress(AddressUse use) {
this.parts = new ArrayList<AddressComponent>();
this.use = use;
}
/**
* Creates an address with a specified use and an initial set of parts.
*
* @param use
* The type of address (Work, home, et cetera)
* @param parts
* The collection of parts the address is to have
*/
public PersonAddress(AddressUse use, List<AddressComponent> parts) {
this.use = use;
this.parts = (ArrayList) parts;
}
/**
* Adds an address part to the address.
*
* @param value
* The value of the address part
* @param type
* The type of address part to set.
*/
public void addAddressPart(String value, AddressPartType type) {
AddressComponent addressPart = new AddressComponent();
addressPart.setValue(value);
addressPart.setType(type);
parts.add(addressPart);
}
/**
* Gets the list of all parts of an address.
*
* @return ArrayList of all parts of an address.
*/
public ArrayList<AddressComponent> getParts() {
return parts;
}
/**
* Gets a specific part of an address
*
* @param type
* The part of the address to retrieve
* @return The part of the address with the given type
*/
public AddressComponent getPartByType(AddressPartType type) {
for (AddressComponent part : parts) {
if (part.getType() == type)
return part;
}
return null;
}
public AddressUse getUse() {
return use;
}
public void setUse(AddressUse use) {
this.use = use;
}
}
| 23.990654 | 81 | 0.67277 |
45e402d97c517a69d71a6c0c5584d9daef5171ee | 14,873 | package mobileapp.ctemplar.com.ctemplarapp.billing.view;
import static mobileapp.ctemplar.com.ctemplarapp.billing.view.MySubscriptionDialog.CURRENT_PLAN_DATA;
import static mobileapp.ctemplar.com.ctemplarapp.utils.DateUtils.GENERAL_GSON;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import com.android.billingclient.api.Purchase;
import com.android.billingclient.api.SkuDetails;
import com.google.android.material.tabs.TabLayoutMediator;
import java.util.ArrayList;
import java.util.List;
import io.reactivex.SingleObserver;
import io.reactivex.disposables.Disposable;
import mobileapp.ctemplar.com.ctemplarapp.R;
import mobileapp.ctemplar.com.ctemplarapp.billing.BillingConstants;
import mobileapp.ctemplar.com.ctemplarapp.utils.BillingUtils;
import mobileapp.ctemplar.com.ctemplarapp.billing.BillingViewModel;
import mobileapp.ctemplar.com.ctemplarapp.billing.model.CurrentPlanData;
import mobileapp.ctemplar.com.ctemplarapp.billing.model.PlanType;
import mobileapp.ctemplar.com.ctemplarapp.billing.model.PlanInfo;
import mobileapp.ctemplar.com.ctemplarapp.databinding.ActivitySubscriptionBinding;
import mobileapp.ctemplar.com.ctemplarapp.net.request.SubscriptionMobileUpgradeRequest;
import mobileapp.ctemplar.com.ctemplarapp.net.response.SubscriptionMobileUpgradeResponse;
import mobileapp.ctemplar.com.ctemplarapp.utils.ThemeUtils;
import mobileapp.ctemplar.com.ctemplarapp.utils.ToastUtils;
import mobileapp.ctemplar.com.ctemplarapp.view.menu.BillingPlanCycleMenuItem;
import timber.log.Timber;
public class SubscriptionActivity extends AppCompatActivity implements ViewPagerAdapter.ViewPagerAdapterListener,
BillingPlanCycleMenuItem.OnPlanCycleChangeListener {
public static final String SELECT_PLAN_TYPE_KEY = "select_plan_type_key";
private ActivitySubscriptionBinding binding;
private BillingViewModel billingViewModel;
private final ViewPagerAdapter adapter = new ViewPagerAdapter(this);
private String planJsonData;
private Disposable nextPurchasesListenerDisposable;
private BillingPlanCycleMenuItem billingPlanCycleMenuItem;
private String selectPlanType;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ThemeUtils.setTheme(this);
binding = ActivitySubscriptionBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
setSupportActionBar(binding.toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
}
Intent intent = getIntent();
if (intent != null) {
selectPlanType = intent.getStringExtra(SELECT_PLAN_TYPE_KEY);
}
planJsonData = PlanInfo.getJSON(this);
binding.viewPager.setAdapter(adapter);
billingViewModel = new ViewModelProvider(this).get(BillingViewModel.class);
billingViewModel.getSkuDetailListLiveData().observe(this, this::onSkuDetailsListUpdated);
billingViewModel.getCurrentPlanDataLiveData().observe(this, this::onCurrentPlanDataChanged);
new TabLayoutMediator(binding.tabs, binding.viewPager, (tab, position) ->
tab.setText(adapter.getItemTitle(position))).attach();
nextPurchasesListenerDisposable = billingViewModel.listenForNextPurchasesUpdate((purchasesToAck) -> {
ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.show();
if (purchasesToAck.length == 0) {
progressDialog.dismiss();
return;
}
if (purchasesToAck.length > 1) {
Timber.e("Purchases count is more than 1");
}
boolean requestedSubscription = false;
for (Purchase purchase : purchasesToAck) {
String subscription = BillingUtils.getPurchaseSubscription(purchase);
if (subscription == null) {
Timber.e("Subscription not found for purchase: %s", purchase.toString());
continue;
}
PlanType planType = getPlanType(subscription);
if (planType == null) {
Timber.e("Plan type not found for subscription %s", subscription);
continue;
}
requestedSubscription = true;
billingViewModel.subscriptionUpgrade(new SubscriptionMobileUpgradeRequest(
purchase.getPurchaseToken(),
subscription,
BillingConstants.GOOGLE,
isMonthlySku(subscription) ? BillingConstants.MONTHLY : BillingConstants.ANNUALLY,
planType.name()
)).subscribe(new SingleObserver<SubscriptionMobileUpgradeResponse>() {
@Override
public void onSubscribe(@NonNull Disposable d) {
}
@Override
public void onSuccess(@NonNull SubscriptionMobileUpgradeResponse subscriptionMobileUpgradeResponse) {
if (!subscriptionMobileUpgradeResponse.isStatus()) {
ToastUtils.showToast(SubscriptionActivity.this, getString(R.string.subscription_upgrade_fail));
} else {
ToastUtils.showToast(SubscriptionActivity.this, getString(R.string.subscription_upgrade_success));
billingViewModel.updateUserSubscription();
}
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
@Override
public void onError(@NonNull Throwable e) {
Timber.e(e);
ToastUtils.showToast(SubscriptionActivity.this,
getString(R.string.subscription_upgrade_fail) + e.getMessage());
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
});
}
if (!requestedSubscription) {
ToastUtils.showToast(this, getString(R.string.error_connection));
progressDialog.dismiss();
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.billing_cycle_menu, menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem item = menu.findItem(R.id.plan_cycle_menu_item);
billingPlanCycleMenuItem = (BillingPlanCycleMenuItem) item.getActionView();
billingPlanCycleMenuItem.setIsYearly(true);
billingPlanCycleMenuItem.setOnChangeListener(this);
return super.onPrepareOptionsMenu(menu);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (nextPurchasesListenerDisposable != null) {
nextPurchasesListenerDisposable.dispose();
nextPurchasesListenerDisposable = null;
}
}
private void subscribe(String sku) {
boolean isPurchaseOwnerDevice = billingViewModel.getIsPurchaseOwnerDeviceLiveData().getValue();
if (!isPurchaseOwnerDevice) {
ToastUtils.showToast(this, getString(R.string.subscription_upgrade_another_device));
return;
}
try {
if (sku == null) {
Intent intent = new Intent(Intent.ACTION_VIEW);
CurrentPlanData currentPlanData = billingViewModel.getCurrentPlanDataLiveData().getValue();
if (currentPlanData != null) {
boolean isMonthly = BillingConstants.MONTHLY.equals(currentPlanData.getPaymentTransactionDTO() == null
? null : currentPlanData.getPaymentTransactionDTO().getPaymentType());
String currentSku = getPlanSku(currentPlanData.getPlanType(), isMonthly);
intent.setData(Uri.parse(String.format(BillingConstants.PLAY_STORE_SUBSCRIPTION_DEEPLINK_URL,
currentSku, getPackageName())));
startActivity(intent);
} else {
intent.setData(Uri.parse(BillingConstants.PLAY_STORE_SUBSCRIPTION_URL));
startActivity(intent);
}
}
billingViewModel.subscribe(this, sku);
} catch (Throwable e) {
ToastUtils.showToast(this, e.getMessage());
}
}
@Override
public void onSubscribeClicked(String sku) {
subscribe(sku);
}
@Override
public void onOpenCurrentPlanClicked(CurrentPlanData currentPlanData) {
if (currentPlanData.getPlanType() == PlanType.FREE) {
return;
}
MySubscriptionDialog dialog = new MySubscriptionDialog();
Bundle bundle = new Bundle();
bundle.putString(CURRENT_PLAN_DATA, GENERAL_GSON.toJson(currentPlanData));
dialog.setArguments(bundle);
dialog.show(getSupportFragmentManager(), getClass().getSimpleName());
}
@Override
public void onPlanCycleChange(boolean isYearly) {
adapter.setPlanCycle(isYearly);
}
private void onSkuDetailsListUpdated(List<SkuDetails> skuDetails) {
List<PlanInfo> itemsList = new ArrayList<>();
PlanInfo freePlanInfo = new PlanInfo(PlanType.FREE, planJsonData);
PlanInfo primePlanInfo = new PlanInfo(PlanType.PRIME, planJsonData);
PlanInfo knightPlanInfo = new PlanInfo(PlanType.KNIGHT, planJsonData);
PlanInfo marshalPlanInfo = new PlanInfo(PlanType.MARSHAL, planJsonData);
PlanInfo championPlanInfo = new PlanInfo(PlanType.CHAMPION, planJsonData);
itemsList.add(freePlanInfo);
itemsList.add(primePlanInfo);
itemsList.add(knightPlanInfo);
itemsList.add(marshalPlanInfo);
itemsList.add(championPlanInfo);
for (SkuDetails skuDetail : skuDetails) {
switch (skuDetail.getSku()) {
case BillingConstants.PRIME_MONTHLY_SKU:
primePlanInfo.setMonthlyPlanSkuDetails(skuDetail);
break;
case BillingConstants.PRIME_ANNUAL_SKU:
primePlanInfo.setYearlyPlanSkuDetails(skuDetail);
break;
case BillingConstants.KNIGHT_MONTHLY_SKU:
knightPlanInfo.setMonthlyPlanSkuDetails(skuDetail);
break;
case BillingConstants.KNIGHT_ANNUAL_SKU:
knightPlanInfo.setYearlyPlanSkuDetails(skuDetail);
break;
case BillingConstants.MARSHAL_MONTHLY_SKU:
marshalPlanInfo.setMonthlyPlanSkuDetails(skuDetail);
break;
case BillingConstants.MARSHAL_ANNUAL_SKU:
marshalPlanInfo.setYearlyPlanSkuDetails(skuDetail);
break;
case BillingConstants.CHAMPION_MONTHLY_SKU:
championPlanInfo.setMonthlyPlanSkuDetails(skuDetail);
break;
default:
Timber.e("Undefined sku %s", skuDetail.getSku());
}
}
adapter.setItems(itemsList);
}
private String getPlanSku(PlanType planType, boolean isMonthly) {
switch (planType) {
case FREE:
return null;
case PRIME:
return isMonthly ? BillingConstants.PRIME_MONTHLY_SKU : BillingConstants.PRIME_ANNUAL_SKU;
case KNIGHT:
return isMonthly ? BillingConstants.KNIGHT_MONTHLY_SKU : BillingConstants.KNIGHT_ANNUAL_SKU;
case MARSHAL:
return isMonthly ? BillingConstants.MARSHAL_MONTHLY_SKU : BillingConstants.MARSHAL_ANNUAL_SKU;
case CHAMPION:
return isMonthly ? BillingConstants.CHAMPION_MONTHLY_SKU : null;
}
return null;
}
private static boolean isMonthlySku(String sku) {
switch (sku) {
case BillingConstants.PRIME_MONTHLY_SKU:
case BillingConstants.MARSHAL_MONTHLY_SKU:
case BillingConstants.KNIGHT_MONTHLY_SKU:
case BillingConstants.CHAMPION_MONTHLY_SKU:
return true;
case BillingConstants.PRIME_ANNUAL_SKU:
case BillingConstants.MARSHAL_ANNUAL_SKU:
case BillingConstants.KNIGHT_ANNUAL_SKU:
default:
return false;
}
}
private static PlanType getPlanType(String sku) {
switch (sku) {
case BillingConstants.PRIME_MONTHLY_SKU:
case BillingConstants.PRIME_ANNUAL_SKU:
return PlanType.PRIME;
case BillingConstants.MARSHAL_MONTHLY_SKU:
case BillingConstants.MARSHAL_ANNUAL_SKU:
return PlanType.MARSHAL;
case BillingConstants.KNIGHT_MONTHLY_SKU:
case BillingConstants.KNIGHT_ANNUAL_SKU:
return PlanType.KNIGHT;
case BillingConstants.CHAMPION_MONTHLY_SKU:
return PlanType.CHAMPION;
}
return null;
}
private void onCurrentPlanDataChanged(CurrentPlanData currentPlanData) {
adapter.setCurrentPlanData(currentPlanData);
int index;
if (selectPlanType == null) {
index = adapter.getItemIndexByPlanType(currentPlanData.getPlanType());
} else {
index = adapter.getItemIndexByPlanType(PlanType.valueOf(selectPlanType));
}
if (index >= 0) {
binding.tabs.selectTab(binding.tabs.getTabAt(index));
if (currentPlanData.getPaymentTransactionDTO() != null) {
if (billingPlanCycleMenuItem == null) {
return;
}
boolean isMonthlyType = BillingConstants.MONTHLY.equals(
currentPlanData.getPaymentTransactionDTO().getPaymentType());
billingPlanCycleMenuItem.setIsYearly(!isMonthlyType);
}
}
}
}
| 43.873156 | 126 | 0.640557 |
8bcb172eabd9f11edbb3582000b7ec0d6c97fb8b | 2,050 | /**
* Copyright 2012 Diego Ceccarelli
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.cnr.isti.hpc.dexter.spot;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import it.cnr.isti.hpc.dexter.entity.Entity;
import it.cnr.isti.hpc.dexter.spot.cleanpipe.filter.CommonnessFilter;
import org.junit.Test;
/**
* SpotReaderTest.java
*
* @author Diego Ceccarelli, [email protected]
* created on 01/ago/2012
*/
public class SpotReaderTest {
@Test
public void test() {
SpotReader reader = new SpotReader("./src/test/resources/spot-src-target-sample.txt","./src/test/resources/spot-frequencies.txt");
reader.addFilter(new CommonnessFilter());
Spot s = reader.next();
assertEquals(20, s.getLink());
assertEquals("argentina", s.getMention());
assertEquals(38541,s.getFrequency());
assertEquals(1,s.getEntities().size());
assertTrue(s.getEntities().contains(new Entity(18951905)));
System.out.println(s);
System.out.println(s.toTsv());
s = reader.next();
assertEquals(5, s.getLink());
assertEquals("goodbye argentina", s.getMention());
assertEquals(1,s.getFrequency());
assertEquals(2,s.getEntities().size());
assertTrue(s.getEntities().contains(new Entity(8423965)));
assertTrue(s.getEntities().contains(new Entity(8423966)));
assertEquals(1,s.getLinkProbability(),0.001);
System.out.println(s);
System.out.println(s.toTsv());
s = reader.next();
System.out.println(s);
System.out.println(s.toTsv());
}
}
| 31.060606 | 132 | 0.72 |
57b886a6d2aad6f24bf824675637f79e70569567 | 812 | package r20.top.stream.statistics;
import org.junit.Assert;
import org.junit.Test;
/**
* author: roger.luo
*
* createTime : 2018/8/13 15:06
*
* description :
**/
public class TestRollingTimeWindowStatistics {
@Test
public void testRollingTimeWindowStatistics() throws InterruptedException {
RollingTimeWindowStatistics rtw = new RollingTimeWindowStatistics(2);
rtw.incSuccess();
rtw.incSuccess();
rtw.incSuccess();
rtw.incSuccess();
rtw.incSuccess();
rtw.incSuccess();
rtw.incSuccess();
rtw.incSuccess();
rtw.incSuccess();
rtw.incFail();
Assert.assertEquals(0.1d, rtw.getFailPercent(), 2);
Thread.sleep(1000l);
rtw.incFail();
Assert.assertEquals(1d, rtw.getFailPercent(), 2);
}
public void testRollingTimeWindowCleanUp(){
}
}
| 18.883721 | 77 | 0.683498 |
8ff825e81759db815313511ed7dd1052f73bcfb5 | 2,148 | /*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.camunda.bpm.qa.upgrade.timestamp;
import org.camunda.bpm.engine.ProcessEngine;
import org.camunda.bpm.engine.impl.util.ClockUtil;
import org.camunda.bpm.model.bpmn.Bpmn;
import org.camunda.bpm.model.bpmn.BpmnModelInstance;
import org.camunda.bpm.qa.upgrade.DescribesScenario;
import org.camunda.bpm.qa.upgrade.ScenarioSetup;
import org.camunda.bpm.qa.upgrade.Times;
/**
* @author Nikola Koevski
*/
public class DeploymentDeployTimeScenario extends AbstractTimestampMigrationScenario {
protected static final String PROCESS_DEFINITION_KEY = "deploymentDeployTimeProcess";
protected static final String DEPLOYMENT_NAME = "DeployTimeDeploymentTest";
protected static final BpmnModelInstance DEPLOYMENT_MODEL = Bpmn.createExecutableProcess(PROCESS_DEFINITION_KEY)
.startEvent("start")
.serviceTask("task")
.camundaDelegateExpression("${true}")
.endEvent("end")
.done();
@DescribesScenario("initDeploymentDeployTime")
@Times(1)
public static ScenarioSetup initDeploymentDeployTime() {
return new ScenarioSetup() {
@Override
public void execute(ProcessEngine processEngine, String s) {
ClockUtil. setCurrentTime(TIMESTAMP);
deployModel(processEngine, DEPLOYMENT_NAME, PROCESS_DEFINITION_KEY, DEPLOYMENT_MODEL);
ClockUtil.reset();
}
};
}
} | 38.357143 | 115 | 0.767225 |
28722e045391c8da8f95f0f1874bfa3955435450 | 808 | /*
* Copyright 2016 West Coast Informatics, LLC
*/
package com.wci.umls.server.jpa.helpers.content;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import com.wci.umls.server.helpers.AbstractResultList;
import com.wci.umls.server.helpers.content.MappingList;
import com.wci.umls.server.jpa.content.MappingJpa;
import com.wci.umls.server.model.content.Mapping;
/**
* JAXB enabled implementation of {@link MappingList}.
*/
@XmlRootElement(name = "mappingList")
public class MappingListJpa extends AbstractResultList<Mapping> implements
MappingList {
/* see superclass */
@Override
@XmlElement(type = MappingJpa.class, name = "mappings")
public List<Mapping> getObjects() {
return super.getObjectsTransient();
}
}
| 26.064516 | 74 | 0.766089 |
5a1ded3a28681b3e46dfdd0e67256028abdd61a7 | 5,052 | package com.c2b.coin.account.entity;
import java.math.BigDecimal;
import javax.persistence.*;
@Table(name = "asset_change_log")
public class AssetChangeLog {
@Id
@GeneratedValue(generator = "JDBC")
private Long id;
/**
* user_id
*/
@Column(name = "user_id")
private Long userId;
/**
* username
*/
private String username;
/**
* 订单号
*/
@Column(name = "order_no")
private String orderNo;
@Column(name="currency_type")
private Integer currencyType;
/**
* 变动类型(增加,减少)
*/
@Column(name = "change_type")
private Integer changeType;
/**
* 业务类型(1充值,2提现,3买入,4卖出)
*/
@Column(name = "biz_type")
private Integer bizType;
/**
* 变动账户
*/
@Column(name = "account_id")
private Long accountId;
/**
* 变动前资产
*/
@Column(name = "pre_balance")
private BigDecimal preBalance;
/**
* 变动后资产
*/
@Column(name = "after_balance")
private BigDecimal afterBalance;
/**
* 变更时间
*/
@Column(name = "update_time")
private Long updateTime;
/**
* 费用类型
*/
@Column(name = "fee_type")
private Integer feeType;
/**
* 变动金额
*/
@Column(name = "change_asset")
private BigDecimal changeAsset;
/**
* @return id
*/
public Long getId() {
return id;
}
/**
* @param id
*/
public void setId(Long id) {
this.id = id;
}
/**
* 获取user_id
*
* @return user_id - user_id
*/
public Long getUserId() {
return userId;
}
/**
* 设置user_id
*
* @param userId user_id
*/
public void setUserId(Long userId) {
this.userId = userId;
}
/**
* 获取username
*
* @return username - username
*/
public String getUsername() {
return username;
}
/**
* 设置username
*
* @param username username
*/
public void setUsername(String username) {
this.username = username;
}
/**
* 获取订单号
*
* @return order_no - 订单号
*/
public String getOrderNo() {
return orderNo;
}
/**
* 设置订单号
*
* @param orderNo 订单号
*/
public void setOrderNo(String orderNo) {
this.orderNo = orderNo;
}
/**
* 获取变动类型(增加,减少)
*
* @return change_type - 变动类型(增加,减少)
*/
public Integer getChangeType() {
return changeType;
}
/**
* 设置变动类型(增加,减少)
*
* @param changeType 变动类型(增加,减少)
*/
public void setChangeType(Integer changeType) {
this.changeType = changeType;
}
/**
* 获取业务类型(1充值,2提现,3买入,4卖出)
*
* @return biz_type - 业务类型(1充值,2提现,3买入,4卖出)
*/
public Integer getBizType() {
return bizType;
}
/**
* 设置业务类型(1充值,2提现,3买入,4卖出)
*
* @param bizType 业务类型(1充值,2提现,3买入,4卖出)
*/
public void setBizType(Integer bizType) {
this.bizType = bizType;
}
/**
* 获取变动账户
*
* @return account_id - 变动账户
*/
public Long getAccountId() {
return accountId;
}
/**
* 设置变动账户
*
* @param accountId 变动账户
*/
public void setAccountId(Long accountId) {
this.accountId = accountId;
}
/**
* 获取变动前资产
*
* @return pre_balance - 变动前资产
*/
public BigDecimal getPreBalance() {
return preBalance;
}
/**
* 设置变动前资产
*
* @param preBalance 变动前资产
*/
public void setPreBalance(BigDecimal preBalance) {
this.preBalance = preBalance;
}
/**
* 获取变动后资产
*
* @return after_balance - 变动后资产
*/
public BigDecimal getAfterBalance() {
return afterBalance;
}
/**
* 设置变动后资产
*
* @param afterBalance 变动后资产
*/
public void setAfterBalance(BigDecimal afterBalance) {
this.afterBalance = afterBalance;
}
/**
* 获取变更时间
*
* @return update_time - 变更时间
*/
public Long getUpdateTime() {
return updateTime;
}
/**
* 设置变更时间
*
* @param updateTime 变更时间
*/
public void setUpdateTime(Long updateTime) {
this.updateTime = updateTime;
}
/**
* 获取费用类型
*
* @return fee_type - 费用类型
*/
public Integer getFeeType() {
return feeType;
}
/**
* 设置费用类型
*
* @param feeType 费用类型
*/
public void setFeeType(Integer feeType) {
this.feeType = feeType;
}
/**
* 获取变动金额
*
* @return change_asset - 变动金额
*/
public BigDecimal getChangeAsset() {
return changeAsset;
}
/**
* 设置变动金额
*
* @param changeAsset 变动金额
*/
public void setChangeAsset(BigDecimal changeAsset) {
this.changeAsset = changeAsset;
}
public Integer getCurrencyType() {
return currencyType;
}
public void setCurrencyType(Integer currencyType) {
this.currencyType = currencyType;
}
} | 16.784053 | 58 | 0.523159 |
1bdb346e088d6a24e542b08cf63b053cdc572261 | 591 | package Patterns;
import java.util.Scanner;
public class PatternTenth {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("Enter the Number: ");
int n = sc.nextInt();
int nst = 2 * n - 1;
int nsp = 0;
int row = 1;
while (row <= n) {
for (int csp = 1; csp <= nsp; csp++)
System.out.print(" ");
for (int cst = 1; cst <= nst; cst++)
System.out.print("* ");
System.out.println();
row = row + 1;
nst = nst - 2;
nsp = nsp + 1;
}
}
}
| 19.7 | 44 | 0.543147 |
c74050f1e5784daf880be5107ead8e733149491c | 2,853 | package com.weimore.caringhelper.ui.activity;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import com.weimore.base.BaseActivity;
import com.weimore.caringhelper.R;
import com.weimore.caringhelper.databinding.ActivityChangePasswordBinding;
import com.weimore.caringhelper.ui.contract.ChangePasswordContract;
import com.weimore.caringhelper.ui.presenter.ChangePasswordPresenter;
import com.weimore.util.NumberUtil;
/**
* @author Weimore
* 2019/1/1.
* description:
*/
public class ChangePasswordActivity extends BaseActivity<ChangePasswordContract.Presenter> implements ChangePasswordContract.View {
private ActivityChangePasswordBinding mBinding;
public static void startActivity(Context context) {
context.startActivity(new Intent(context, ChangePasswordActivity.class));
}
@Override
public int getLayoutRes() {
return R.layout.activity_change_password;
}
@NonNull
@Override
public ChangePasswordContract.Presenter getPresenter() {
return new ChangePasswordPresenter(this);
}
@Override
public boolean dataBinding() {
mBinding = DataBindingUtil.setContentView(this, R.layout.activity_change_password);
return true;
}
@Override
public void initView() {
mBinding.tvRegister.setOnClickListener(v -> {
if (TextUtils.isEmpty(mBinding.etPhone.getText())) {
showToast("请输入手机号");
return;
}
if (!NumberUtil.isMobile(mBinding.etPhone.getText().toString())) {
showToast("请输入正确的手机号");
return;
}
if (TextUtils.isEmpty(mBinding.etOldPassword.getText())) {
showToast("昵称不能为空");
return;
}
if (TextUtils.isEmpty(mBinding.etNewPassword.getText())) {
showToast("请输入密码");
return;
}
if (TextUtils.isEmpty(mBinding.etPasswordConfirm.getText())) {
showToast("请输入验证密码");
return;
}
if (!TextUtils.equals(mBinding.etNewPassword.getText(), mBinding.etPasswordConfirm.getText())) {
showToast("新密码输入不一致");
return;
}
showLoading();
getMPresenter().reLogin(mBinding.etPhone.getText().toString(),
mBinding.etOldPassword.getText().toString());
});
}
@Override
public void reLoginSuccess() {
getMPresenter().updatePassword(mBinding.etPhone.getText().toString(),
mBinding.etNewPassword.getText().toString());
}
@Override
public void updateSuccess() {
finish();
}
} | 31.01087 | 131 | 0.636523 |
cc2736edd0f961ff40be29260e4180da78b2cd52 | 4,933 | package com.qlzw.smartwc.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.sql.Timestamp;
@Entity
public class Dev_repair {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id; // 记录ID
private String title; // 报修标题
private String content; // 报修详情
private Integer err_type; // 保修类型 0:设备故障 1:设备缺液 2:质量问题 3:其他
private String images; // 报修图片
private String dev_info; // 设备信息
private String phone; // 联系电话
private String position; // 经纬度
private String address; // 地址
private Integer admin_user_id; // 关联的用户id
private Integer status; // 报修状态 0:等待受理 1:受理中 2:受理完成
private Integer time_out; // 是否过期
private Timestamp create_at; // 创建于
private Timestamp update_at; // 更新于
private Timestamp delete_at; // 删除于
public Dev_repair(Long id,String title,String content,Integer err_type,String images,String dev_info,String phone,String position,String address,Integer admin_user_id,Integer status,Integer time_out,Timestamp create_at,Timestamp update_at,Timestamp delete_at) {
this.id=id;
this.title=title;
this.content=content;
this.err_type=err_type;
this.images=images;
this.dev_info=dev_info;
this.phone=phone;
this.position=position;
this.address=address;
this.admin_user_id=admin_user_id;
this.status=status;
this.time_out=time_out;
this.create_at=create_at;
this.update_at=update_at;
this.delete_at=delete_at;
}
public Dev_repair() {}
public Long getId () { return this.id;}
public String getTitle () { return this.title;}
public String getContent () { return this.content;}
public Integer getErr_type () { return this.err_type;}
public String getImages () { return this.images;}
public String getDev_info () { return this.dev_info;}
public String getPhone () { return this.phone;}
public String getPosition () { return this.position;}
public String getAddress () { return this.address;}
public Integer getAdmin_user_id () { return this.admin_user_id;}
public Integer getStatus () { return this.status;}
public Integer getTime_out () { return this.time_out;}
public Timestamp getCreate_at () { return this.create_at;}
public Timestamp getUpdate_at () { return this.update_at;}
public Timestamp getDelete_at () { return this.delete_at;}
public void setId (Long id) { this.id = id;}
public void setTitle (String title) { this.title = title;}
public void setContent (String content) { this.content = content;}
public void setErr_type (Integer err_type) { this.err_type = err_type;}
public void setImages (String images) { this.images = images;}
public void setDev_info (String dev_info) { this.dev_info = dev_info;}
public void setPhone (String phone) { this.phone = phone;}
public void setPosition (String position) { this.position = position;}
public void setAddress (String address) { this.address = address;}
public void setAdmin_user_id (Integer admin_user_id) { this.admin_user_id = admin_user_id;}
public void setStatus (Integer status) { this.status = status;}
public void setTime_out (Integer time_out) { this.time_out = time_out;}
public void setCreate_at (Timestamp create_at) { this.create_at = create_at;}
public void setUpdate_at (Timestamp update_at) { this.update_at = update_at;}
public void setDelete_at (Timestamp delete_at) { this.delete_at = delete_at;}
public String toString() {
return " <Dev_repair> {id = " + id + ", " +
"title = " + title + ", " +
"title = '" + title + "', " +
"content = " + content + ", " +
"content = '" + content + "', " +
"err_type = " + err_type + ", " +
"images = " + images + ", " +
"images = '" + images + "', " +
"dev_info = " + dev_info + ", " +
"dev_info = '" + dev_info + "', " +
"phone = " + phone + ", " +
"phone = '" + phone + "', " +
"position = " + position + ", " +
"position = '" + position + "', " +
"address = " + address + ", " +
"address = '" + address + "', " +
"admin_user_id = " + admin_user_id + ", " +
"status = " + status + ", " +
"time_out = " + time_out + ", " +
"create_at = " + create_at + ", " +
"update_at = " + update_at + ", " +
"delete_at = " + delete_at + ", " + "}";
}
} | 36.540741 | 266 | 0.59254 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.