proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/utils/GpsUtil.java
|
GpsUtil
|
Wgs84ToBd09
|
class GpsUtil {
private static Logger logger = LoggerFactory.getLogger(GpsUtil.class);
public static BaiduPoint Wgs84ToBd09(String xx, String yy) {<FILL_FUNCTION_BODY>}
/**
* BASE64解码
* @param str
* @return string
*/
public static byte[] decode(String str) {
byte[] bt = null;
final Base64.Decoder decoder = Base64.getDecoder();
bt = decoder.decode(str); // .decodeBuffer(str);
return bt;
}
}
|
double lng = Double.parseDouble(xx);
double lat = Double.parseDouble(yy);
Double[] gcj02 = Coordtransform.WGS84ToGCJ02(lng, lat);
Double[] doubles = Coordtransform.GCJ02ToBD09(gcj02[0], gcj02[1]);
BaiduPoint bdPoint= new BaiduPoint();
bdPoint.setBdLng(doubles[0] + "");
bdPoint.setBdLat(doubles[1] + "");
return bdPoint;
| 167
| 159
| 326
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/utils/JsonUtil.java
|
JsonUtil
|
redisJsonToObject
|
class JsonUtil {
private JsonUtil() {
}
/**
* safe json type conversion
*
* @param key redis key
* @param clazz cast type
* @param <T>
* @return result type
*/
public static <T> T redisJsonToObject(RedisTemplate<Object, Object> redisTemplate, String key, Class<T> clazz) {<FILL_FUNCTION_BODY>}
}
|
Object jsonObject = redisTemplate.opsForValue().get(key);
if (Objects.isNull(jsonObject)) {
return null;
}
return clazz.cast(jsonObject);
| 118
| 53
| 171
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/utils/SSLSocketClientUtil.java
|
SSLSocketClientUtil
|
getSocketFactory
|
class SSLSocketClientUtil {
public static SSLSocketFactory getSocketFactory(TrustManager manager) {<FILL_FUNCTION_BODY>}
public static X509TrustManager getX509TrustManager() {
return new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
};
}
public static HostnameVerifier getHostnameVerifier() {
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
};
return hostnameVerifier;
}
}
|
SSLSocketFactory socketFactory = null;
try {
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new TrustManager[]{manager}, new SecureRandom());
socketFactory = sslContext.getSocketFactory();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
return socketFactory;
| 265
| 115
| 380
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/utils/SpringBeanFactory.java
|
SpringBeanFactory
|
getBean
|
class SpringBeanFactory implements ApplicationContextAware {
// Spring应用上下文环境
private static ApplicationContext applicationContext;
/**
* 实现ApplicationContextAware接口的回调方法,设置上下文环境
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
SpringBeanFactory.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 获取对象 这里重写了bean方法,起主要作用
*/
public static <T> T getBean(String beanId) throws BeansException {<FILL_FUNCTION_BODY>}
/**
* 获取当前环境
*/
public static String getActiveProfile() {
return applicationContext.getEnvironment().getActiveProfiles()[0];
}
}
|
if (applicationContext == null) {
return null;
}
return (T) applicationContext.getBean(beanId);
| 221
| 36
| 257
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/utils/SystemInfoUtils.java
|
SystemInfoUtils
|
getNetworkTotal
|
class SystemInfoUtils {
private final static Logger logger = LoggerFactory.getLogger(SystemInfoUtils.class);
/**
* 获取cpu信息
* @return
* @throws InterruptedException
*/
public static double getCpuInfo() throws InterruptedException {
SystemInfo systemInfo = new SystemInfo();
CentralProcessor processor = systemInfo.getHardware().getProcessor();
long[] prevTicks = processor.getSystemCpuLoadTicks();
// 睡眠1s
TimeUnit.SECONDS.sleep(1);
long[] ticks = processor.getSystemCpuLoadTicks();
long nice = ticks[CentralProcessor.TickType.NICE.getIndex()] - prevTicks[CentralProcessor.TickType.NICE.getIndex()];
long irq = ticks[CentralProcessor.TickType.IRQ.getIndex()] - prevTicks[CentralProcessor.TickType.IRQ.getIndex()];
long softirq = ticks[CentralProcessor.TickType.SOFTIRQ.getIndex()] - prevTicks[CentralProcessor.TickType.SOFTIRQ.getIndex()];
long steal = ticks[CentralProcessor.TickType.STEAL.getIndex()] - prevTicks[CentralProcessor.TickType.STEAL.getIndex()];
long cSys = ticks[CentralProcessor.TickType.SYSTEM.getIndex()] - prevTicks[CentralProcessor.TickType.SYSTEM.getIndex()];
long user = ticks[CentralProcessor.TickType.USER.getIndex()] - prevTicks[CentralProcessor.TickType.USER.getIndex()];
long iowait = ticks[CentralProcessor.TickType.IOWAIT.getIndex()] - prevTicks[CentralProcessor.TickType.IOWAIT.getIndex()];
long idle = ticks[CentralProcessor.TickType.IDLE.getIndex()] - prevTicks[CentralProcessor.TickType.IDLE.getIndex()];
long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal;
return 1.0-(idle * 1.0 / totalCpu);
}
/**
* 获取内存使用率
* @return
*/
public static double getMemInfo(){
SystemInfo systemInfo = new SystemInfo();
GlobalMemory memory = systemInfo.getHardware().getMemory();
//总内存
long totalByte = memory.getTotal();
//剩余
long acaliableByte = memory.getAvailable();
return (totalByte-acaliableByte)*1.0/totalByte;
}
/**
* 获取网络上传和下载
* @return
*/
public static Map<String,Double> getNetworkInterfaces() {
SystemInfo si = new SystemInfo();
HardwareAbstractionLayer hal = si.getHardware();
List<NetworkIF> beforeRecvNetworkIFs = hal.getNetworkIFs();
NetworkIF beforeBet= beforeRecvNetworkIFs.get(beforeRecvNetworkIFs.size() - 1);
long beforeRecv = beforeBet.getBytesRecv();
long beforeSend = beforeBet.getBytesSent();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
logger.error("[线程休眠失败] : {}", e.getMessage());
}
List<NetworkIF> afterNetworkIFs = hal.getNetworkIFs();
NetworkIF afterNet = afterNetworkIFs.get(afterNetworkIFs.size() - 1);
HashMap<String, Double> map = new HashMap<>();
// 速度单位: Mbps
map.put("in",formatUnits(afterNet.getBytesRecv()-beforeRecv, 1048576L));
map.put("out",formatUnits(afterNet.getBytesSent()-beforeSend, 1048576L));
return map;
}
/**
* 获取带宽总值
* @return
*/
public static long getNetworkTotal() {<FILL_FUNCTION_BODY>}
public static double formatUnits(long value, long prefix) {
return (double)value / (double)prefix;
}
/**
* 获取进程数
* @return
*/
public static int getProcessesCount(){
SystemInfo si = new SystemInfo();
OperatingSystem os = si.getOperatingSystem();
int processCount = os.getProcessCount();
return processCount;
}
public static List<Map<String, Object>> getDiskInfo() {
List<Map<String, Object>> result = new ArrayList<>();
String osName = System.getProperty("os.name");
List<String> pathArray = new ArrayList<>();
if (osName.startsWith("Mac OS")) {
// 苹果
pathArray.add("/");
} else if (osName.startsWith("Windows")) {
// windows
pathArray.add("C:");
} else {
pathArray.add("/");
pathArray.add("/home");
}
for (String path : pathArray) {
Map<String, Object> infoMap = new HashMap<>();
infoMap.put("path", path);
File partitionFile = new File(path);
// 单位: GB
infoMap.put("use", (partitionFile.getTotalSpace() - partitionFile.getFreeSpace())/1024/1024/1024D);
infoMap.put("free", partitionFile.getFreeSpace()/1024/1024/1024D);
result.add(infoMap);
}
return result;
}
}
|
SystemInfo si = new SystemInfo();
HardwareAbstractionLayer hal = si.getHardware();
List<NetworkIF> recvNetworkIFs = hal.getNetworkIFs();
NetworkIF networkIF= recvNetworkIFs.get(recvNetworkIFs.size() - 1);
return networkIF.getSpeed()/1048576L/8L;
| 1,468
| 99
| 1,567
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/utils/UJson.java
|
UJson
|
readJson
|
class UJson {
private static Logger logger = LoggerFactory.getLogger(UJson.class);
public static final ObjectMapper JSON_MAPPER = new ObjectMapper();
static {
JSON_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
}
private ObjectNode node;
public UJson(){
this.node = JSON_MAPPER.createObjectNode();
}
public UJson(String json){
if(StringUtils.isBlank(json)){
this.node = JSON_MAPPER.createObjectNode();
}else{
try {
this.node = JSON_MAPPER.readValue(json, ObjectNode.class);
}catch (Exception e){
logger.error(e.getMessage(), e);
this.node = JSON_MAPPER.createObjectNode();
}
}
}
public UJson(ObjectNode node){
this.node = node;
}
public String asText(String key){
JsonNode jsonNode = node.get(key);
if(Objects.isNull(jsonNode)){
return "";
}
return jsonNode.asText();
}
public String asText(String key, String defaultVal){
JsonNode jsonNode = node.get(key);
if(Objects.isNull(jsonNode)){
return "";
}
return jsonNode.asText(defaultVal);
}
public UJson put(String key, String value){
this.node.put(key, value);
return this;
}
public UJson put(String key, Integer value){
this.node.put(key, value);
return this;
}
public static UJson json(){
return new UJson();
}
public static UJson json(String json){
return new UJson(json);
}
public static <T> T readJson(String json, Class<T> clazz){<FILL_FUNCTION_BODY>}
public static String writeJson(Object object) {
try{
return JSON_MAPPER.writeValueAsString(object);
}catch (Exception e){
logger.error(e.getMessage(), e);
return "";
}
}
@Override
public String toString() {
return node.toString();
}
public int asInt(String key, int defValue) {
JsonNode jsonNode = this.node.get(key);
if(Objects.isNull(jsonNode)){
return defValue;
}
return jsonNode.asInt(defValue);
}
public UJson getSon(String key) {
JsonNode sonNode = this.node.get(key);
if(Objects.isNull(sonNode)){
return new UJson();
}
return new UJson((ObjectNode) sonNode);
}
public UJson set(String key, ObjectNode sonNode) {
this.node.set(key, sonNode);
return this;
}
public UJson set(String key, UJson sonNode) {
this.node.set(key, sonNode.node);
return this;
}
public Iterator<Map.Entry<String, JsonNode>> fields() {
return this.node.fields();
}
public ObjectNode getNode() {
return this.node;
}
public UJson setAll(UJson json) {
this.node.setAll(json.node);
return this;
}
}
|
if(StringUtils.isBlank(json)){
return null;
}
try {
return JSON_MAPPER.readValue(json, clazz);
}catch (Exception e){
logger.error(e.getMessage(), e);
return null;
}
| 894
| 72
| 966
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/utils/redis/FastJsonRedisSerializer.java
|
FastJsonRedisSerializer
|
deserialize
|
class FastJsonRedisSerializer<T> implements RedisSerializer<T> {
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private Class<T> clazz;
public FastJsonRedisSerializer(Class<T> clazz) {
super();
this.clazz = clazz;
}
@Override
public byte[] serialize(T t) throws SerializationException {
if (t == null) {
return new byte[0];
}
return JSON.toJSONString(t, JSONWriter.Feature.WriteClassName, JSONWriter.Feature.WritePairAsJavaBean).getBytes(DEFAULT_CHARSET);
}
@Override
public T deserialize(byte[] bytes) throws SerializationException {<FILL_FUNCTION_BODY>}
}
|
if (bytes == null || bytes.length <= 0) {
return null;
}
String str = new String(bytes, DEFAULT_CHARSET);
return JSON.parseObject(str, clazz, JSONReader.Feature.SupportAutoType);
| 211
| 63
| 274
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/utils/redis/RedisUtil.java
|
RedisUtil
|
scan
|
class RedisUtil {
/**
* 模糊查询
*
* @param query 查询参数
* @return
*/
public static List<Object> scan(RedisTemplate redisTemplate, String query) {<FILL_FUNCTION_BODY>}
}
|
Set<String> resultKeys = (Set<String>) redisTemplate.execute((RedisCallback<Set<String>>) connection -> {
ScanOptions scanOptions = ScanOptions.scanOptions().match("*" + query + "*").count(1000).build();
Cursor<byte[]> scan = connection.scan(scanOptions);
Set<String> keys = new HashSet<>();
while (scan.hasNext()) {
byte[] next = scan.next();
keys.add(new String(next));
}
return keys;
});
return Lists.newArrayList(resultKeys);
| 74
| 154
| 228
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/vmanager/bean/BaseTree.java
|
BaseTree
|
compareTo
|
class BaseTree<T> implements Comparable<BaseTree>{
private String id;
private String deviceId;
private String pid;
private String name;
private boolean parent;
private T basicData;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDeviceId() {
return deviceId;
}
public void setDeviceId(String deviceId) {
this.deviceId = deviceId;
}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public T getBasicData() {
return basicData;
}
public void setBasicData(T basicData) {
this.basicData = basicData;
}
public boolean isParent() {
return parent;
}
public void setParent(boolean parent) {
this.parent = parent;
}
@Override
public int compareTo(@NotNull BaseTree treeNode) {<FILL_FUNCTION_BODY>}
}
|
if (this.parent || treeNode.isParent()) {
if (!this.parent && !treeNode.isParent()) {
Comparator cmp = Collator.getInstance(java.util.Locale.CHINA);
return cmp.compare(treeNode.getName(), this.getName());
}else {
if (this.isParent()) {
return 1;
}else {
return -1;
}
}
}else{
Comparator cmp = Collator.getInstance(java.util.Locale.CHINA);
return cmp.compare(treeNode.getName(), this.getName());
}
| 343
| 162
| 505
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/vmanager/bean/OtherPsSendInfo.java
|
OtherPsSendInfo
|
toString
|
class OtherPsSendInfo {
/**
* 发流IP
*/
private String sendLocalIp;
/**
* 发流端口
*/
private int sendLocalPort;
/**
* 收流IP
*/
private String receiveIp;
/**
* 收流端口
*/
private int receivePort;
/**
* 会话ID
*/
private String callId;
/**
* 流ID
*/
private String stream;
/**
* 推流应用名
*/
private String pushApp;
/**
* 推流流ID
*/
private String pushStream;
/**
* 推流SSRC
*/
private String pushSSRC;
public String getSendLocalIp() {
return sendLocalIp;
}
public void setSendLocalIp(String sendLocalIp) {
this.sendLocalIp = sendLocalIp;
}
public int getSendLocalPort() {
return sendLocalPort;
}
public void setSendLocalPort(int sendLocalPort) {
this.sendLocalPort = sendLocalPort;
}
public String getReceiveIp() {
return receiveIp;
}
public void setReceiveIp(String receiveIp) {
this.receiveIp = receiveIp;
}
public int getReceivePort() {
return receivePort;
}
public void setReceivePort(int receivePort) {
this.receivePort = receivePort;
}
public String getCallId() {
return callId;
}
public void setCallId(String callId) {
this.callId = callId;
}
public String getStream() {
return stream;
}
public void setStream(String stream) {
this.stream = stream;
}
public String getPushApp() {
return pushApp;
}
public void setPushApp(String pushApp) {
this.pushApp = pushApp;
}
public String getPushStream() {
return pushStream;
}
public void setPushStream(String pushStream) {
this.pushStream = pushStream;
}
public String getPushSSRC() {
return pushSSRC;
}
public void setPushSSRC(String pushSSRC) {
this.pushSSRC = pushSSRC;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "OtherPsSendInfo{" +
"sendLocalIp='" + sendLocalIp + '\'' +
", sendLocalPort=" + sendLocalPort +
", receiveIp='" + receiveIp + '\'' +
", receivePort=" + receivePort +
", callId='" + callId + '\'' +
", stream='" + stream + '\'' +
", pushApp='" + pushApp + '\'' +
", pushStream='" + pushStream + '\'' +
", pushSSRC='" + pushSSRC + '\'' +
'}';
| 682
| 146
| 828
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/vmanager/bean/OtherRtpSendInfo.java
|
OtherRtpSendInfo
|
toString
|
class OtherRtpSendInfo {
/**
* 发流IP
*/
private String sendLocalIp;
/**
* 音频发流端口
*/
private int sendLocalPortForAudio;
/**
* 视频发流端口
*/
private int sendLocalPortForVideo;
/**
* 收流IP
*/
private String receiveIp;
/**
* 音频收流端口
*/
private int receivePortForAudio;
/**
* 视频收流端口
*/
private int receivePortForVideo;
/**
* 会话ID
*/
private String callId;
/**
* 流ID
*/
private String stream;
/**
* 推流应用名
*/
private String pushApp;
/**
* 推流流ID
*/
private String pushStream;
/**
* 推流SSRC
*/
private String pushSSRC;
public String getReceiveIp() {
return receiveIp;
}
public void setReceiveIp(String receiveIp) {
this.receiveIp = receiveIp;
}
public int getReceivePortForAudio() {
return receivePortForAudio;
}
public void setReceivePortForAudio(int receivePortForAudio) {
this.receivePortForAudio = receivePortForAudio;
}
public int getReceivePortForVideo() {
return receivePortForVideo;
}
public void setReceivePortForVideo(int receivePortForVideo) {
this.receivePortForVideo = receivePortForVideo;
}
public String getCallId() {
return callId;
}
public void setCallId(String callId) {
this.callId = callId;
}
public String getStream() {
return stream;
}
public void setStream(String stream) {
this.stream = stream;
}
public String getPushApp() {
return pushApp;
}
public void setPushApp(String pushApp) {
this.pushApp = pushApp;
}
public String getPushStream() {
return pushStream;
}
public void setPushStream(String pushStream) {
this.pushStream = pushStream;
}
public String getPushSSRC() {
return pushSSRC;
}
public void setPushSSRC(String pushSSRC) {
this.pushSSRC = pushSSRC;
}
public String getSendLocalIp() {
return sendLocalIp;
}
public void setSendLocalIp(String sendLocalIp) {
this.sendLocalIp = sendLocalIp;
}
public int getSendLocalPortForAudio() {
return sendLocalPortForAudio;
}
public void setSendLocalPortForAudio(int sendLocalPortForAudio) {
this.sendLocalPortForAudio = sendLocalPortForAudio;
}
public int getSendLocalPortForVideo() {
return sendLocalPortForVideo;
}
public void setSendLocalPortForVideo(int sendLocalPortForVideo) {
this.sendLocalPortForVideo = sendLocalPortForVideo;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "OtherRtpSendInfo{" +
"sendLocalIp='" + sendLocalIp + '\'' +
", sendLocalPortForAudio=" + sendLocalPortForAudio +
", sendLocalPortForVideo=" + sendLocalPortForVideo +
", receiveIp='" + receiveIp + '\'' +
", receivePortForAudio=" + receivePortForAudio +
", receivePortForVideo=" + receivePortForVideo +
", callId='" + callId + '\'' +
", stream='" + stream + '\'' +
", pushApp='" + pushApp + '\'' +
", pushStream='" + pushStream + '\'' +
", pushSSRC='" + pushSSRC + '\'' +
'}';
| 892
| 187
| 1,079
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/vmanager/bean/PageInfo.java
|
PageInfo
|
startPage
|
class PageInfo<T> {
//当前页
private int pageNum;
//每页的数量
private int pageSize;
//当前页的数量
private int size;
//总页数
private int pages;
//总数
private int total;
private List<T> resultData;
private List<T> list;
public PageInfo(List<T> resultData) {
this.resultData = resultData;
}
public PageInfo() {
}
public void startPage(int page, int count) {<FILL_FUNCTION_BODY>}
public int getPageNum() {
return pageNum;
}
public void setPageNum(int pageNum) {
this.pageNum = pageNum;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = pages;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
}
|
if (count <= 0) count = 10;
if (page <= 0) page = 1;
this.pageNum = page;
this.pageSize = count;
this.total = resultData.size();
this.pages = total % count == 0 ? total / count : total / count + 1;
int fromIndx = (page - 1) * count;
if (fromIndx > this.total - 1) {
this.list = new ArrayList<>();
this.size = 0;
return;
}
int toIndx = page * count;
if (toIndx > this.total) {
toIndx = this.total;
}
this.list = this.resultData.subList(fromIndx, toIndx);
this.size = this.list.size();
| 417
| 209
| 626
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/vmanager/bean/SnapPath.java
|
SnapPath
|
getInstance
|
class SnapPath {
@Schema(description = "相对地址")
private String path;
@Schema(description = "绝对地址")
private String absoluteFilePath;
@Schema(description = "请求地址")
private String url;
public static SnapPath getInstance(String path, String absoluteFilePath, String url) {<FILL_FUNCTION_BODY>}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getAbsoluteFilePath() {
return absoluteFilePath;
}
public void setAbsoluteFilePath(String absoluteFilePath) {
this.absoluteFilePath = absoluteFilePath;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
|
SnapPath snapPath = new SnapPath();
snapPath.setPath(path);
snapPath.setAbsoluteFilePath(absoluteFilePath);
snapPath.setUrl(url);
return snapPath;
| 234
| 56
| 290
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/vmanager/gb28181/MobilePosition/MobilePositionController.java
|
MobilePositionController
|
positionTransform
|
class MobilePositionController {
private final static Logger logger = LoggerFactory.getLogger(MobilePositionController.class);
@Autowired
private IVideoManagerStorage storager;
@Autowired
private SIPCommander cmder;
@Autowired
private DeferredResultHolder resultHolder;
@Autowired
private IDeviceService deviceService;
@Autowired
private IDeviceChannelService deviceChannelService;
/**
* 查询历史轨迹
* @param deviceId 设备ID
* @param start 开始时间
* @param end 结束时间
* @return
*/
@Operation(summary = "查询历史轨迹", security = @SecurityRequirement(name = JwtUtils.HEADER))
@Parameter(name = "deviceId", description = "设备国标编号", required = true)
@Parameter(name = "channelId", description = "通道国标编号")
@Parameter(name = "start", description = "开始时间")
@Parameter(name = "end", description = "结束时间")
@GetMapping("/history/{deviceId}")
public List<MobilePosition> positions(@PathVariable String deviceId,
@RequestParam(required = false) String channelId,
@RequestParam(required = false) String start,
@RequestParam(required = false) String end) {
if (StringUtil.isEmpty(start)) {
start = null;
}
if (StringUtil.isEmpty(end)) {
end = null;
}
return storager.queryMobilePositions(deviceId, channelId, start, end);
}
/**
* 查询设备最新位置
* @param deviceId 设备ID
* @return
*/
@Operation(summary = "查询设备最新位置", security = @SecurityRequirement(name = JwtUtils.HEADER))
@Parameter(name = "deviceId", description = "设备国标编号", required = true)
@GetMapping("/latest/{deviceId}")
public MobilePosition latestPosition(@PathVariable String deviceId) {
return storager.queryLatestPosition(deviceId);
}
/**
* 获取移动位置信息
* @param deviceId 设备ID
* @return
*/
@Operation(summary = "获取移动位置信息", security = @SecurityRequirement(name = JwtUtils.HEADER))
@Parameter(name = "deviceId", description = "设备国标编号", required = true)
@GetMapping("/realtime/{deviceId}")
public DeferredResult<MobilePosition> realTimePosition(@PathVariable String deviceId) {
Device device = storager.queryVideoDevice(deviceId);
String uuid = UUID.randomUUID().toString();
String key = DeferredResultHolder.CALLBACK_CMD_MOBILE_POSITION + deviceId;
try {
cmder.mobilePostitionQuery(device, event -> {
RequestMessage msg = new RequestMessage();
msg.setId(uuid);
msg.setKey(key);
msg.setData(String.format("获取移动位置信息失败,错误码: %s, %s", event.statusCode, event.msg));
resultHolder.invokeResult(msg);
});
} catch (InvalidArgumentException | SipException | ParseException e) {
logger.error("[命令发送失败] 获取移动位置信息: {}", e.getMessage());
throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage());
}
DeferredResult<MobilePosition> result = new DeferredResult<MobilePosition>(5*1000L);
result.onTimeout(()->{
logger.warn(String.format("获取移动位置信息超时"));
// 释放rtpserver
RequestMessage msg = new RequestMessage();
msg.setId(uuid);
msg.setKey(key);
msg.setData("Timeout");
resultHolder.invokeResult(msg);
});
resultHolder.put(key, uuid, result);
return result;
}
/**
* 订阅位置信息
* @param deviceId 设备ID
* @param expires 订阅超时时间
* @param interval 上报时间间隔
* @return true = 命令发送成功
*/
@Operation(summary = "订阅位置信息", security = @SecurityRequirement(name = JwtUtils.HEADER))
@Parameter(name = "deviceId", description = "设备国标编号", required = true)
@Parameter(name = "expires", description = "订阅超时时间", required = true)
@Parameter(name = "interval", description = "上报时间间隔", required = true)
@GetMapping("/subscribe/{deviceId}")
public void positionSubscribe(@PathVariable String deviceId,
@RequestParam String expires,
@RequestParam String interval) {
if (StringUtil.isEmpty(interval)) {
interval = "5";
}
Device device = storager.queryVideoDevice(deviceId);
device.setSubscribeCycleForMobilePosition(Integer.parseInt(expires));
device.setMobilePositionSubmissionInterval(Integer.parseInt(interval));
deviceService.updateCustomDevice(device);
}
/**
* 数据位置信息格式处理
* @param deviceId 设备ID
* @return true = 命令发送成功
*/
@Operation(summary = "数据位置信息格式处理", security = @SecurityRequirement(name = JwtUtils.HEADER))
@Parameter(name = "deviceId", description = "设备国标编号", required = true)
@GetMapping("/transform/{deviceId}")
public void positionTransform(@PathVariable String deviceId) {<FILL_FUNCTION_BODY>}
}
|
Device device = deviceService.getDevice(deviceId);
if (device == null) {
throw new ControllerException(ErrorCode.ERROR400.getCode(), "未找到设备: " + deviceId);
}
boolean result = deviceChannelService.updateAllGps(device);
if (!result) {
throw new ControllerException(ErrorCode.ERROR100);
}
| 1,461
| 100
| 1,561
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/vmanager/gb28181/alarm/AlarmController.java
|
AlarmController
|
delete
|
class AlarmController {
private final static Logger logger = LoggerFactory.getLogger(AlarmController.class);
@Autowired
private IDeviceAlarmService deviceAlarmService;
@Autowired
private ISIPCommander commander;
@Autowired
private ISIPCommanderForPlatform commanderForPlatform;
@Autowired
private IVideoManagerStorage storage;
/**
* 删除报警
*
* @param id 报警id
* @param deviceIds 多个设备id,逗号分隔
* @param time 结束时间(这个时间之前的报警会被删除)
* @return
*/
@DeleteMapping("/delete")
@Operation(summary = "删除报警", security = @SecurityRequirement(name = JwtUtils.HEADER))
@Parameter(name = "id", description = "ID")
@Parameter(name = "deviceIds", description = "多个设备id,逗号分隔")
@Parameter(name = "time", description = "结束时间")
public Integer delete(
@RequestParam(required = false) Integer id,
@RequestParam(required = false) String deviceIds,
@RequestParam(required = false) String time
) {<FILL_FUNCTION_BODY>}
/**
* 测试向上级/设备发送模拟报警通知
*
* @param deviceId 报警id
* @return
*/
@GetMapping("/test/notify/alarm")
@Operation(summary = "测试向上级/设备发送模拟报警通知", security = @SecurityRequirement(name = JwtUtils.HEADER))
@Parameter(name = "deviceId", description = "设备国标编号")
public void delete(@RequestParam String deviceId) {
Device device = storage.queryVideoDevice(deviceId);
ParentPlatform platform = storage.queryParentPlatByServerGBId(deviceId);
DeviceAlarm deviceAlarm = new DeviceAlarm();
deviceAlarm.setChannelId(deviceId);
deviceAlarm.setAlarmDescription("test");
deviceAlarm.setAlarmMethod("1");
deviceAlarm.setAlarmPriority("1");
deviceAlarm.setAlarmTime(DateUtil.getNow());
deviceAlarm.setAlarmType("1");
deviceAlarm.setLongitude(115.33333);
deviceAlarm.setLatitude(39.33333);
if (device != null && platform == null) {
try {
commander.sendAlarmMessage(device, deviceAlarm);
} catch (InvalidArgumentException | SipException | ParseException e) {
}
}else if (device == null && platform != null){
try {
commanderForPlatform.sendAlarmMessage(platform, deviceAlarm);
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 国标级联 发送BYE: {}", e.getMessage());
throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage());
}
}else {
throw new ControllerException(ErrorCode.ERROR100.getCode(),"无法确定" + deviceId + "是平台还是设备");
}
}
/**
* 分页查询报警
*
* @param deviceId 设备id
* @param page 当前页
* @param count 每页查询数量
* @param alarmPriority 报警级别
* @param alarmMethod 报警方式
* @param alarmType 报警类型
* @param startTime 开始时间
* @param endTime 结束时间
* @return
*/
@Operation(summary = "分页查询报警", security = @SecurityRequirement(name = JwtUtils.HEADER))
@Parameter(name = "page",description = "当前页",required = true)
@Parameter(name = "count",description = "每页查询数量",required = true)
@Parameter(name = "deviceId",description = "设备id")
@Parameter(name = "alarmPriority",description = "查询内容")
@Parameter(name = "alarmMethod",description = "查询内容")
@Parameter(name = "alarmType",description = "每页查询数量")
@Parameter(name = "startTime",description = "开始时间")
@Parameter(name = "endTime",description = "结束时间")
@GetMapping("/all")
public PageInfo<DeviceAlarm> getAll(
@RequestParam int page,
@RequestParam int count,
@RequestParam(required = false) String deviceId,
@RequestParam(required = false) String alarmPriority,
@RequestParam(required = false) String alarmMethod,
@RequestParam(required = false) String alarmType,
@RequestParam(required = false) String startTime,
@RequestParam(required = false) String endTime
) {
if (ObjectUtils.isEmpty(alarmPriority)) {
alarmPriority = null;
}
if (ObjectUtils.isEmpty(alarmMethod)) {
alarmMethod = null;
}
if (ObjectUtils.isEmpty(alarmType)) {
alarmType = null;
}
if (ObjectUtils.isEmpty(startTime)) {
startTime = null;
}else if (!DateUtil.verification(startTime, DateUtil.formatter) ){
throw new ControllerException(ErrorCode.ERROR400.getCode(), "startTime格式为" + DateUtil.PATTERN);
}
if (ObjectUtils.isEmpty(endTime)) {
endTime = null;
}else if (!DateUtil.verification(endTime, DateUtil.formatter) ){
throw new ControllerException(ErrorCode.ERROR400.getCode(), "endTime格式为" + DateUtil.PATTERN);
}
return deviceAlarmService.getAllAlarm(page, count, deviceId, alarmPriority, alarmMethod,
alarmType, startTime, endTime);
}
}
|
if (ObjectUtils.isEmpty(id)) {
id = null;
}
if (ObjectUtils.isEmpty(deviceIds)) {
deviceIds = null;
}
if (ObjectUtils.isEmpty(time)) {
time = null;
}else if (!DateUtil.verification(time, DateUtil.formatter) ){
throw new ControllerException(ErrorCode.ERROR400.getCode(), "time格式为" + DateUtil.PATTERN);
}
List<String> deviceIdList = null;
if (deviceIds != null) {
String[] deviceIdArray = deviceIds.split(",");
deviceIdList = Arrays.asList(deviceIdArray);
}
return deviceAlarmService.clearAlarmBeforeTime(id, deviceIdList, time);
| 1,539
| 203
| 1,742
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/vmanager/gb28181/device/DeviceConfig.java
|
DeviceConfig
|
configDownloadApi
|
class DeviceConfig {
private final static Logger logger = LoggerFactory.getLogger(DeviceQuery.class);
@Autowired
private IVideoManagerStorage storager;
@Autowired
private SIPCommander cmder;
@Autowired
private DeferredResultHolder resultHolder;
/**
* 看守位控制命令API接口
* @param deviceId 设备ID
* @param channelId 通道ID
* @param name 名称
* @param expiration 到期时间
* @param heartBeatInterval 心跳间隔
* @param heartBeatCount 心跳计数
* @return
*/
@GetMapping("/basicParam/{deviceId}")
@Operation(summary = "基本配置设置命令", security = @SecurityRequirement(name = JwtUtils.HEADER))
@Parameter(name = "deviceId", description = "设备国标编号", required = true)
@Parameter(name = "channelId", description = "通道国标编号", required = true)
@Parameter(name = "name", description = "名称")
@Parameter(name = "expiration", description = "到期时间")
@Parameter(name = "heartBeatInterval", description = "心跳间隔")
@Parameter(name = "heartBeatCount", description = "心跳计数")
public DeferredResult<String> homePositionApi(@PathVariable String deviceId,
String channelId,
@RequestParam(required = false) String name,
@RequestParam(required = false) String expiration,
@RequestParam(required = false) String heartBeatInterval,
@RequestParam(required = false) String heartBeatCount) {
if (logger.isDebugEnabled()) {
logger.debug("报警复位API调用");
}
Device device = storager.queryVideoDevice(deviceId);
String uuid = UUID.randomUUID().toString();
String key = DeferredResultHolder.CALLBACK_CMD_DEVICECONFIG + deviceId + channelId;
try {
cmder.deviceBasicConfigCmd(device, channelId, name, expiration, heartBeatInterval, heartBeatCount, event -> {
RequestMessage msg = new RequestMessage();
msg.setId(uuid);
msg.setKey(key);
msg.setData(String.format("设备配置操作失败,错误码: %s, %s", event.statusCode, event.msg));
resultHolder.invokeResult(msg);
});
} catch (InvalidArgumentException | SipException | ParseException e) {
logger.error("[命令发送失败] 设备配置: {}", e.getMessage());
throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage());
}
DeferredResult<String> result = new DeferredResult<String>(3 * 1000L);
result.onTimeout(() -> {
logger.warn(String.format("设备配置操作超时, 设备未返回应答指令"));
// 释放rtpserver
RequestMessage msg = new RequestMessage();
msg.setId(uuid);
msg.setKey(key);
JSONObject json = new JSONObject();
json.put("DeviceID", deviceId);
json.put("Status", "Timeout");
json.put("Description", "设备配置操作超时, 设备未返回应答指令");
msg.setData(json); //("看守位控制操作超时, 设备未返回应答指令");
resultHolder.invokeResult(msg);
});
resultHolder.put(key, uuid, result);
return result;
}
/**
* 设备配置查询请求API接口
* @param deviceId 设备ID
* @param configType 配置类型
* @param channelId 通道ID
* @return
*/
@Operation(summary = "设备配置查询请求", security = @SecurityRequirement(name = JwtUtils.HEADER))
@Parameter(name = "deviceId", description = "设备国标编号", required = true)
@Parameter(name = "channelId", description = "通道国标编号", required = true)
@Parameter(name = "configType", description = "配置类型")
@GetMapping("/query/{deviceId}/{configType}")
public DeferredResult<String> configDownloadApi(@PathVariable String deviceId,
@PathVariable String configType,
@RequestParam(required = false) String channelId) {<FILL_FUNCTION_BODY>}
}
|
if (logger.isDebugEnabled()) {
logger.debug("设备状态查询API调用");
}
String key = DeferredResultHolder.CALLBACK_CMD_CONFIGDOWNLOAD + (ObjectUtils.isEmpty(channelId) ? deviceId : channelId);
String uuid = UUID.randomUUID().toString();
Device device = storager.queryVideoDevice(deviceId);
try {
cmder.deviceConfigQuery(device, channelId, configType, event -> {
RequestMessage msg = new RequestMessage();
msg.setId(uuid);
msg.setKey(key);
msg.setData(String.format("获取设备配置失败,错误码: %s, %s", event.statusCode, event.msg));
resultHolder.invokeResult(msg);
});
} catch (InvalidArgumentException | SipException | ParseException e) {
logger.error("[命令发送失败] 获取设备配置: {}", e.getMessage());
throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage());
}
DeferredResult<String> result = new DeferredResult<String > (3 * 1000L);
result.onTimeout(()->{
logger.warn(String.format("获取设备配置超时"));
// 释放rtpserver
RequestMessage msg = new RequestMessage();
msg.setId(uuid);
msg.setKey(key);
msg.setData("Timeout. Device did not response to this command.");
resultHolder.invokeResult(msg);
});
resultHolder.put(key, uuid, result);
return result;
| 1,151
| 432
| 1,583
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/vmanager/gb28181/gbStream/GbStreamController.java
|
GbStreamController
|
add
|
class GbStreamController {
private final static Logger logger = LoggerFactory.getLogger(GbStreamController.class);
@Autowired
private IGbStreamService gbStreamService;
@Autowired
private IStreamPushService service;
@Autowired
private IPlatformService platformService;
/**
* 查询国标通道
* @param page 当前页
* @param count 每页条数
* @param platformId 平台ID
* @return
*/
@Operation(summary = "查询国标通道", security = @SecurityRequirement(name = JwtUtils.HEADER))
@Parameter(name = "page", description = "当前页", required = true)
@Parameter(name = "count", description = "每页条数", required = true)
@Parameter(name = "platformId", description = "平台ID", required = true)
@Parameter(name = "catalogId", description = "目录ID")
@Parameter(name = "query", description = "查询内容")
@Parameter(name = "mediaServerId", description = "流媒体ID")
@GetMapping(value = "/list")
@ResponseBody
public PageInfo<GbStream> list(@RequestParam(required = true)Integer page,
@RequestParam(required = true)Integer count,
@RequestParam(required = true)String platformId,
@RequestParam(required = false)String catalogId,
@RequestParam(required = false)String query,
@RequestParam(required = false)String mediaServerId){
if (ObjectUtils.isEmpty(catalogId)) {
catalogId = null;
}
if (ObjectUtils.isEmpty(query)) {
query = null;
}
if (ObjectUtils.isEmpty(mediaServerId)) {
mediaServerId = null;
}
// catalogId 为null 查询未在平台下分配的数据
// catalogId 不为null 查询平台下这个,目录下的通道
return gbStreamService.getAll(page, count, platformId, catalogId, query, mediaServerId);
}
/**
* 移除国标关联
* @param gbStreamParam
* @return
*/
@Operation(summary = "移除国标关联", security = @SecurityRequirement(name = JwtUtils.HEADER))
@DeleteMapping(value = "/del")
@ResponseBody
public void del(@RequestBody GbStreamParam gbStreamParam){
if (gbStreamParam.getGbStreams() == null || gbStreamParam.getGbStreams().isEmpty()) {
if (gbStreamParam.isAll()) {
gbStreamService.delAllPlatformInfo(gbStreamParam.getPlatformId(), gbStreamParam.getCatalogId());
}
}else {
gbStreamService.delPlatformInfo(gbStreamParam.getPlatformId(), gbStreamParam.getGbStreams());
}
}
/**
* 保存国标关联
* @param gbStreamParam
* @return
*/
@Operation(summary = "保存国标关联", security = @SecurityRequirement(name = JwtUtils.HEADER))
@PostMapping(value = "/add")
@ResponseBody
public void add(@RequestBody GbStreamParam gbStreamParam){<FILL_FUNCTION_BODY>}
/**
* 保存国标关联
* @param gbId
* @return
*/
@Operation(summary = "保存国标关联", security = @SecurityRequirement(name = JwtUtils.HEADER))
@GetMapping(value = "/addWithGbid")
@ResponseBody
public void add(String gbId, String platformGbId, @RequestParam(required = false) String catalogGbId){
List<GbStream> gbStreams = gbStreamService.getGbChannelWithGbid(gbId);
if (gbStreams.isEmpty()) {
throw new ControllerException(ErrorCode.ERROR100.getCode(), "gbId的信息未找到");
}
gbStreamService.addPlatformInfo(gbStreams, platformGbId, catalogGbId);
}
}
|
if (gbStreamParam.getGbStreams() == null || gbStreamParam.getGbStreams().isEmpty()) {
if (gbStreamParam.isAll()) {
List<GbStream> allGBChannels = gbStreamService.getAllGBChannels(gbStreamParam.getPlatformId());
gbStreamService.addPlatformInfo(allGBChannels, gbStreamParam.getPlatformId(), gbStreamParam.getCatalogId());
}
}else {
gbStreamService.addPlatformInfo(gbStreamParam.getGbStreams(), gbStreamParam.getPlatformId(), gbStreamParam.getCatalogId());
}
| 1,062
| 164
| 1,226
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/vmanager/gb28181/media/MediaController.java
|
MediaController
|
getStreamInfoByAppAndStream
|
class MediaController {
private final static Logger logger = LoggerFactory.getLogger(MediaController.class);
@Autowired
private IRedisCatchStorage redisCatchStorage;
@Autowired
private IStreamProxyService streamProxyService;
@Autowired
private IMediaServerService mediaServerService;
/**
* 根据应用名和流id获取播放地址
* @param app 应用名
* @param stream 流id
* @return
*/
@Operation(summary = "根据应用名和流id获取播放地址", security = @SecurityRequirement(name = JwtUtils.HEADER))
@Parameter(name = "app", description = "应用名", required = true)
@Parameter(name = "stream", description = "流id", required = true)
@Parameter(name = "mediaServerId", description = "媒体服务器id")
@Parameter(name = "callId", description = "推流时携带的自定义鉴权ID")
@Parameter(name = "useSourceIpAsStreamIp", description = "是否使用请求IP作为返回的地址IP")
@GetMapping(value = "/stream_info_by_app_and_stream")
@ResponseBody
public StreamContent getStreamInfoByAppAndStream(HttpServletRequest request, @RequestParam String app,
@RequestParam String stream,
@RequestParam(required = false) String mediaServerId,
@RequestParam(required = false) String callId,
@RequestParam(required = false) Boolean useSourceIpAsStreamIp){<FILL_FUNCTION_BODY>}
}
|
boolean authority = false;
if (callId != null) {
// 权限校验
StreamAuthorityInfo streamAuthorityInfo = redisCatchStorage.getStreamAuthorityInfo(app, stream);
if (streamAuthorityInfo != null
&& streamAuthorityInfo.getCallId() != null
&& streamAuthorityInfo.getCallId().equals(callId)) {
authority = true;
}else {
throw new ControllerException(ErrorCode.ERROR400.getCode(), "获取播放地址鉴权失败");
}
}else {
// 是否登陆用户, 登陆用户返回完整信息
LoginUser userInfo = SecurityUtils.getUserInfo();
if (userInfo!= null) {
authority = true;
}
}
StreamInfo streamInfo;
if (useSourceIpAsStreamIp != null && useSourceIpAsStreamIp) {
String host = request.getHeader("Host");
String localAddr = host.split(":")[0];
logger.info("使用{}作为返回流的ip", localAddr);
streamInfo = mediaServerService.getStreamInfoByAppAndStreamWithCheck(app, stream, mediaServerId, localAddr, authority);
}else {
streamInfo = mediaServerService.getStreamInfoByAppAndStreamWithCheck(app, stream, mediaServerId, authority);
}
if (streamInfo != null){
return new StreamContent(streamInfo);
}else {
//获取流失败,重启拉流后重试一次
streamProxyService.stop(app,stream);
boolean start = streamProxyService.start(app, stream);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
logger.error("[线程休眠失败], {}", e.getMessage());
}
if (useSourceIpAsStreamIp != null && useSourceIpAsStreamIp) {
String host = request.getHeader("Host");
String localAddr = host.split(":")[0];
logger.info("使用{}作为返回流的ip", localAddr);
streamInfo = mediaServerService.getStreamInfoByAppAndStreamWithCheck(app, stream, mediaServerId, localAddr, authority);
}else {
streamInfo = mediaServerService.getStreamInfoByAppAndStreamWithCheck(app, stream, mediaServerId, authority);
}
if (streamInfo != null){
return new StreamContent(streamInfo);
}else {
throw new ControllerException(ErrorCode.ERROR100);
}
}
| 408
| 653
| 1,061
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/vmanager/gb28181/ptz/PtzController.java
|
PtzController
|
ptz
|
class PtzController {
private final static Logger logger = LoggerFactory.getLogger(PtzController.class);
@Autowired
private SIPCommander cmder;
@Autowired
private IVideoManagerStorage storager;
@Autowired
private DeferredResultHolder resultHolder;
/***
* 云台控制
* @param deviceId 设备id
* @param channelId 通道id
* @param command 控制指令
* @param horizonSpeed 水平移动速度
* @param verticalSpeed 垂直移动速度
* @param zoomSpeed 缩放速度
*/
@Operation(summary = "云台控制", security = @SecurityRequirement(name = JwtUtils.HEADER))
@Parameter(name = "deviceId", description = "设备国标编号", required = true)
@Parameter(name = "channelId", description = "通道国标编号", required = true)
@Parameter(name = "command", description = "控制指令,允许值: left, right, up, down, upleft, upright, downleft, downright, zoomin, zoomout, stop", required = true)
@Parameter(name = "horizonSpeed", description = "水平速度", required = true)
@Parameter(name = "verticalSpeed", description = "垂直速度", required = true)
@Parameter(name = "zoomSpeed", description = "缩放速度", required = true)
@PostMapping("/control/{deviceId}/{channelId}")
public void ptz(@PathVariable String deviceId,@PathVariable String channelId, String command, int horizonSpeed, int verticalSpeed, int zoomSpeed){<FILL_FUNCTION_BODY>}
@Operation(summary = "通用前端控制命令", security = @SecurityRequirement(name = JwtUtils.HEADER))
@Parameter(name = "deviceId", description = "设备国标编号", required = true)
@Parameter(name = "channelId", description = "通道国标编号", required = true)
@Parameter(name = "cmdCode", description = "指令码", required = true)
@Parameter(name = "parameter1", description = "数据一", required = true)
@Parameter(name = "parameter2", description = "数据二", required = true)
@Parameter(name = "combindCode2", description = "组合码二", required = true)
@PostMapping("/front_end_command/{deviceId}/{channelId}")
public void frontEndCommand(@PathVariable String deviceId,@PathVariable String channelId,int cmdCode, int parameter1, int parameter2, int combindCode2){
if (logger.isDebugEnabled()) {
logger.debug(String.format("设备云台控制 API调用,deviceId:%s ,channelId:%s ,cmdCode:%d parameter1:%d parameter2:%d",deviceId, channelId, cmdCode, parameter1, parameter2));
}
Device device = storager.queryVideoDevice(deviceId);
try {
cmder.frontEndCmd(device, channelId, cmdCode, parameter1, parameter2, combindCode2);
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 前端控制: {}", e.getMessage());
throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage());
}
}
@Operation(summary = "预置位查询", security = @SecurityRequirement(name = JwtUtils.HEADER))
@Parameter(name = "deviceId", description = "设备国标编号", required = true)
@Parameter(name = "channelId", description = "通道国标编号", required = true)
@GetMapping("/preset/query/{deviceId}/{channelId}")
public DeferredResult<String> presetQueryApi(@PathVariable String deviceId, @PathVariable String channelId) {
if (logger.isDebugEnabled()) {
logger.debug("设备预置位查询API调用");
}
Device device = storager.queryVideoDevice(deviceId);
String uuid = UUID.randomUUID().toString();
String key = DeferredResultHolder.CALLBACK_CMD_PRESETQUERY + (ObjectUtils.isEmpty(channelId) ? deviceId : channelId);
DeferredResult<String> result = new DeferredResult<String> (3 * 1000L);
result.onTimeout(()->{
logger.warn(String.format("获取设备预置位超时"));
// 释放rtpserver
RequestMessage msg = new RequestMessage();
msg.setId(uuid);
msg.setKey(key);
msg.setData("获取设备预置位超时");
resultHolder.invokeResult(msg);
});
if (resultHolder.exist(key, null)) {
return result;
}
resultHolder.put(key, uuid, result);
try {
cmder.presetQuery(device, channelId, event -> {
RequestMessage msg = new RequestMessage();
msg.setId(uuid);
msg.setKey(key);
msg.setData(String.format("获取设备预置位失败,错误码: %s, %s", event.statusCode, event.msg));
resultHolder.invokeResult(msg);
});
} catch (InvalidArgumentException | SipException | ParseException e) {
logger.error("[命令发送失败] 获取设备预置位: {}", e.getMessage());
throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage());
}
return result;
}
}
|
if (logger.isDebugEnabled()) {
logger.debug(String.format("设备云台控制 API调用,deviceId:%s ,channelId:%s ,command:%s ,horizonSpeed:%d ,verticalSpeed:%d ,zoomSpeed:%d",deviceId, channelId, command, horizonSpeed, verticalSpeed, zoomSpeed));
}
Device device = storager.queryVideoDevice(deviceId);
int cmdCode = 0;
switch (command){
case "left":
cmdCode = 2;
break;
case "right":
cmdCode = 1;
break;
case "up":
cmdCode = 8;
break;
case "down":
cmdCode = 4;
break;
case "upleft":
cmdCode = 10;
break;
case "upright":
cmdCode = 9;
break;
case "downleft":
cmdCode = 6;
break;
case "downright":
cmdCode = 5;
break;
case "zoomin":
cmdCode = 16;
break;
case "zoomout":
cmdCode = 32;
break;
case "stop":
horizonSpeed = 0;
verticalSpeed = 0;
zoomSpeed = 0;
break;
default:
break;
}
try {
cmder.frontEndCmd(device, channelId, cmdCode, horizonSpeed, verticalSpeed, zoomSpeed);
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 云台控制: {}", e.getMessage());
throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage());
}
| 1,419
| 479
| 1,898
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/vmanager/gb28181/sse/SseController.java
|
SseController
|
emit
|
class SseController {
@Resource
private AlarmEventListener alarmEventListener;
/**
* SSE 推送.
*
* @param response 响应
* @param browserId 浏览器ID
* @throws IOException IOEXCEPTION
* @author <a href="mailto:xiaoQQya@126.com">xiaoQQya</a>
* @since 2023/11/06
*/
@GetMapping("/emit")
public void emit(HttpServletResponse response, @RequestParam String browserId) throws IOException, InterruptedException {<FILL_FUNCTION_BODY>}
}
|
response.setContentType("text/event-stream");
response.setCharacterEncoding("utf-8");
PrintWriter writer = response.getWriter();
alarmEventListener.addSseEmitter(browserId, writer);
while (!writer.checkError()) {
Thread.sleep(1000);
writer.write(":keep alive\n\n");
writer.flush();
}
alarmEventListener.removeSseEmitter(browserId, writer);
| 172
| 120
| 292
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/vmanager/log/LogController.java
|
LogController
|
getAll
|
class LogController {
private final static Logger logger = LoggerFactory.getLogger(LogController.class);
@Autowired
private ILogService logService;
@Autowired
private UserSetting userSetting;
/**
* 分页查询日志
*
* @param query 查询内容
* @param page 当前页
* @param count 每页查询数量
* @param type 类型
* @param startTime 开始时间
* @param endTime 结束时间
* @return
*/
@GetMapping("/all")
@Operation(summary = "分页查询日志", security = @SecurityRequirement(name = JwtUtils.HEADER))
@Parameter(name = "query", description = "查询内容", required = true)
@Parameter(name = "page", description = "当前页", required = true)
@Parameter(name = "count", description = "每页查询数量", required = true)
@Parameter(name = "type", description = "类型", required = true)
@Parameter(name = "startTime", description = "开始时间", required = true)
@Parameter(name = "endTime", description = "结束时间", required = true)
public PageInfo<LogDto> getAll(
@RequestParam int page,
@RequestParam int count,
@RequestParam(required = false) String query,
@RequestParam(required = false) String type,
@RequestParam(required = false) String startTime,
@RequestParam(required = false) String endTime
) {<FILL_FUNCTION_BODY>}
/**
* 清空日志
*
*/
@Operation(summary = "清空日志", security = @SecurityRequirement(name = JwtUtils.HEADER))
@DeleteMapping("/clear")
public void clear() {
logService.clear();
}
}
|
if (ObjectUtils.isEmpty(query)) {
query = null;
}
if (!userSetting.getLogInDatabase()) {
logger.warn("自动记录日志功能已关闭,查询结果可能不完整。");
}
if (ObjectUtils.isEmpty(startTime)) {
startTime = null;
}else if (!DateUtil.verification(startTime, DateUtil.formatter) ){
throw new ControllerException(ErrorCode.ERROR400.getCode(), "startTime格式为" + DateUtil.PATTERN);
}
if (ObjectUtils.isEmpty(endTime)) {
endTime = null;
}else if (!DateUtil.verification(endTime, DateUtil.formatter) ){
throw new ControllerException(ErrorCode.ERROR400.getCode(), "endTime格式为" + DateUtil.PATTERN);
}
return logService.getAll(page, count, query, type, startTime, endTime);
| 484
| 248
| 732
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/vmanager/streamProxy/StreamProxyController.java
|
StreamProxyController
|
getFFmpegCMDs
|
class StreamProxyController {
private final static Logger logger = LoggerFactory.getLogger(StreamProxyController.class);
@Autowired
private IMediaServerService mediaServerService;
@Autowired
private IStreamProxyService streamProxyService;
@Autowired
private DeferredResultHolder resultHolder;
@Autowired
private UserSetting userSetting;
@Operation(summary = "分页查询流代理", security = @SecurityRequirement(name = JwtUtils.HEADER))
@Parameter(name = "page", description = "当前页")
@Parameter(name = "count", description = "每页查询数量")
@Parameter(name = "query", description = "查询内容")
@Parameter(name = "online", description = "是否在线")
@GetMapping(value = "/list")
@ResponseBody
public PageInfo<StreamProxyItem> list(@RequestParam(required = false)Integer page,
@RequestParam(required = false)Integer count,
@RequestParam(required = false)String query,
@RequestParam(required = false)Boolean online ){
return streamProxyService.getAll(page, count);
}
@Operation(summary = "查询流代理", security = @SecurityRequirement(name = JwtUtils.HEADER))
@Parameter(name = "app", description = "应用名")
@Parameter(name = "stream", description = "流Id")
@GetMapping(value = "/one")
@ResponseBody
public StreamProxyItem one(String app, String stream){
return streamProxyService.getStreamProxyByAppAndStream(app, stream);
}
@Operation(summary = "保存代理", security = @SecurityRequirement(name = JwtUtils.HEADER), parameters = {
@Parameter(name = "param", description = "代理参数", required = true),
})
@PostMapping(value = "/save")
@ResponseBody
public DeferredResult<Object> save(@RequestBody StreamProxyItem param){
logger.info("添加代理: " + JSONObject.toJSONString(param));
if (ObjectUtils.isEmpty(param.getMediaServerId())) {
param.setMediaServerId("auto");
}
if (ObjectUtils.isEmpty(param.getType())) {
param.setType("default");
}
if (ObjectUtils.isEmpty(param.getRtpType())) {
param.setRtpType("1");
}
if (ObjectUtils.isEmpty(param.getGbId())) {
param.setGbId(null);
}
StreamProxyItem streamProxyItem = streamProxyService.getStreamProxyByAppAndStream(param.getApp(), param.getStream());
if (streamProxyItem != null) {
streamProxyService.del(param.getApp(), param.getStream());
}
RequestMessage requestMessage = new RequestMessage();
String key = DeferredResultHolder.CALLBACK_CMD_PROXY + param.getApp() + param.getStream();
requestMessage.setKey(key);
String uuid = UUID.randomUUID().toString();
requestMessage.setId(uuid);
DeferredResult<Object> result = new DeferredResult<>(userSetting.getPlayTimeout().longValue());
// 录像查询以channelId作为deviceId查询
resultHolder.put(key, uuid, result);
result.onTimeout(()->{
WVPResult<StreamInfo> wvpResult = new WVPResult<>();
wvpResult.setCode(ErrorCode.ERROR100.getCode());
wvpResult.setMsg("超时");
requestMessage.setData(wvpResult);
resultHolder.invokeAllResult(requestMessage);
});
streamProxyService.save(param, (code, msg, streamInfo) -> {
logger.info("[拉流代理] {}", code == ErrorCode.SUCCESS.getCode()? "成功":"失败: " + msg);
if (code == ErrorCode.SUCCESS.getCode()) {
requestMessage.setData(new StreamContent(streamInfo));
}else {
requestMessage.setData(WVPResult.fail(code, msg));
}
resultHolder.invokeAllResult(requestMessage);
});
return result;
}
@GetMapping(value = "/ffmpeg_cmd/list")
@ResponseBody
@Operation(summary = "获取ffmpeg.cmd模板", security = @SecurityRequirement(name = JwtUtils.HEADER))
@Parameter(name = "mediaServerId", description = "流媒体ID", required = true)
public Map<String, String> getFFmpegCMDs(@RequestParam String mediaServerId){<FILL_FUNCTION_BODY>}
@DeleteMapping(value = "/del")
@ResponseBody
@Operation(summary = "移除代理", security = @SecurityRequirement(name = JwtUtils.HEADER))
@Parameter(name = "app", description = "应用名", required = true)
@Parameter(name = "stream", description = "流id", required = true)
public void del(@RequestParam String app, @RequestParam String stream){
logger.info("移除代理: " + app + "/" + stream);
if (app == null || stream == null) {
throw new ControllerException(ErrorCode.ERROR400.getCode(), app == null ?"app不能为null":"stream不能为null");
}else {
streamProxyService.del(app, stream);
}
}
@GetMapping(value = "/start")
@ResponseBody
@Operation(summary = "启用代理", security = @SecurityRequirement(name = JwtUtils.HEADER))
@Parameter(name = "app", description = "应用名", required = true)
@Parameter(name = "stream", description = "流id", required = true)
public void start(String app, String stream){
logger.info("启用代理: " + app + "/" + stream);
boolean result = streamProxyService.start(app, stream);
if (!result) {
throw new ControllerException(ErrorCode.ERROR100);
}
}
@GetMapping(value = "/stop")
@ResponseBody
@Operation(summary = "停用代理", security = @SecurityRequirement(name = JwtUtils.HEADER))
@Parameter(name = "app", description = "应用名", required = true)
@Parameter(name = "stream", description = "流id", required = true)
public void stop(String app, String stream){
logger.info("停用代理: " + app + "/" + stream);
boolean result = streamProxyService.stop(app, stream);
if (!result) {
logger.info("停用代理失败: " + app + "/" + stream);
throw new ControllerException(ErrorCode.ERROR100);
}
}
}
|
logger.debug("获取节点[ {} ]ffmpeg.cmd模板", mediaServerId );
MediaServer mediaServerItem = mediaServerService.getOne(mediaServerId);
if (mediaServerItem == null) {
throw new ControllerException(ErrorCode.ERROR100.getCode(), "流媒体: " + mediaServerId + "未找到");
}
return streamProxyService.getFFmpegCMDs(mediaServerItem);
| 1,715
| 113
| 1,828
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/vmanager/user/RoleController.java
|
RoleController
|
delete
|
class RoleController {
@Autowired
private IRoleService roleService;
@PostMapping("/add")
@Operation(summary = "添加角色", security = @SecurityRequirement(name = JwtUtils.HEADER))
@Parameter(name = "name", description = "角色名", required = true)
@Parameter(name = "authority", description = "权限(自行定义内容,目前未使用)", required = true)
public void add(@RequestParam String name,
@RequestParam(required = false) String authority){
// 获取当前登录用户id
int currenRoleId = SecurityUtils.getUserInfo().getRole().getId();
if (currenRoleId != 1) {
// 只用角色id为1才可以删除和添加用户
throw new ControllerException(ErrorCode.ERROR403);
}
Role role = new Role();
role.setName(name);
role.setAuthority(authority);
role.setCreateTime(DateUtil.getNow());
role.setUpdateTime(DateUtil.getNow());
int addResult = roleService.add(role);
if (addResult <= 0) {
throw new ControllerException(ErrorCode.ERROR100);
}
}
@DeleteMapping("/delete")
@Operation(summary = "删除角色", security = @SecurityRequirement(name = JwtUtils.HEADER))
@Parameter(name = "id", description = "用户Id", required = true)
public void delete(@RequestParam Integer id){<FILL_FUNCTION_BODY>}
@GetMapping("/all")
@Operation(summary = "查询角色", security = @SecurityRequirement(name = JwtUtils.HEADER))
public List<Role> all(){
// 获取当前登录用户id
List<Role> allRoles = roleService.getAll();
return roleService.getAll();
}
}
|
// 获取当前登录用户id
int currenRoleId = SecurityUtils.getUserInfo().getRole().getId();
if (currenRoleId != 1) {
// 只用角色id为0才可以删除和添加用户
throw new ControllerException(ErrorCode.ERROR403);
}
int deleteResult = roleService.delete(id);
if (deleteResult <= 0) {
throw new ControllerException(ErrorCode.ERROR100);
}
| 484
| 123
| 607
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/web/gb28181/ApiControlController.java
|
ApiControlController
|
list
|
class ApiControlController {
private final static Logger logger = LoggerFactory.getLogger(ApiControlController.class);
@Autowired
private SIPCommander cmder;
@Autowired
private IVideoManagerStorage storager;
/**
* 设备控制 - 云台控制
* @param serial 设备编号
* @param command 控制指令 允许值: left, right, up, down, upleft, upright, downleft, downright, zoomin, zoomout, stop
* @param channel 通道序号
* @param code 通道编号
* @param speed 速度(0~255) 默认值: 129
* @return
*/
@GetMapping(value = "/ptz")
private void list(String serial,String command,
@RequestParam(required = false)Integer channel,
@RequestParam(required = false)String code,
@RequestParam(required = false)Integer speed){<FILL_FUNCTION_BODY>}
/**
* 设备控制 - 预置位控制
* @param serial 设备编号
* @param code 通道编号,通过 /api/v1/device/channellist 获取的 ChannelList.ID, 该参数和 channel 二选一传递即可
* @param channel 通道序号, 默认值: 1
* @param command 控制指令 允许值: set, goto, remove
* @param preset 预置位编号(1~255)
* @param name 预置位名称, command=set 时有效
* @return
*/
@GetMapping(value = "/preset")
private void list(String serial,String command,
@RequestParam(required = false)Integer channel,
@RequestParam(required = false)String code,
@RequestParam(required = false)String name,
@RequestParam(required = false)Integer preset){
if (logger.isDebugEnabled()) {
logger.debug("模拟接口> 预置位控制 API调用,deviceId:{} ,channelId:{} ,command:{} ,name:{} ,preset:{} ",
serial, code, command, name, preset);
}
if (channel == null) {channel = 0;}
Device device = storager.queryVideoDevice(serial);
if (device == null) {
throw new ControllerException(ErrorCode.ERROR100.getCode(), "device[ " + serial + " ]未找到");
}
int cmdCode = 0;
switch (command){
case "set":
cmdCode = 129;
break;
case "goto":
cmdCode = 130;
break;
case "remove":
cmdCode = 131;
break;
default:
break;
}
try {
cmder.frontEndCmd(device, code, cmdCode, 0, preset, 0);
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 预置位控制: {}", e.getMessage());
throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage());
}
}
}
|
if (logger.isDebugEnabled()) {
logger.debug("模拟接口> 设备云台控制 API调用,deviceId:{} ,channelId:{} ,command:{} ,speed:{} ",
serial, code, command, speed);
}
if (channel == null) {channel = 0;}
if (speed == null) {speed = 0;}
Device device = storager.queryVideoDevice(serial);
if (device == null) {
throw new ControllerException(ErrorCode.ERROR100.getCode(), "device[ " + serial + " ]未找到");
}
int cmdCode = 0;
switch (command){
case "left":
cmdCode = 2;
break;
case "right":
cmdCode = 1;
break;
case "up":
cmdCode = 8;
break;
case "down":
cmdCode = 4;
break;
case "upleft":
cmdCode = 10;
break;
case "upright":
cmdCode = 9;
break;
case "downleft":
cmdCode = 6;
break;
case "downright":
cmdCode = 5;
break;
case "zoomin":
cmdCode = 16;
break;
case "zoomout":
cmdCode = 32;
break;
case "stop":
cmdCode = 0;
break;
default:
break;
}
// 默认值 50
try {
cmder.frontEndCmd(device, code, cmdCode, speed, speed, speed);
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 云台控制: {}", e.getMessage());
throw new ControllerException(ErrorCode.ERROR100.getCode(), "命令发送失败: " + e.getMessage());
}
| 835
| 489
| 1,324
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/web/gb28181/ApiController.java
|
ApiController
|
userinfo
|
class ApiController {
private final static Logger logger = LoggerFactory.getLogger(ApiController.class);
@Autowired
private SipConfig sipConfig;
@GetMapping("/getserverinfo")
private JSONObject getserverinfo(){
JSONObject result = new JSONObject();
result.put("Authorization","ceshi");
result.put("Hardware","");
result.put("InterfaceVersion","2.5.5");
result.put("IsDemo","");
result.put("Hardware","false");
result.put("APIAuth","false");
result.put("RemainDays","永久");
result.put("RunningTime","");
result.put("ServerTime","2020-09-02 17:11");
result.put("StartUpTime","2020-09-02 17:11");
result.put("Server","");
result.put("SIPSerial", sipConfig.getId());
result.put("SIPRealm", sipConfig.getDomain());
result.put("SIPHost", sipConfig.getIp());
result.put("SIPPort", sipConfig.getPort());
result.put("ChannelCount","1000");
result.put("VersionType","");
result.put("LogoMiniText","");
result.put("LogoText","");
result.put("CopyrightText","");
return result;
}
@GetMapping(value = "/userinfo")
private JSONObject userinfo(){<FILL_FUNCTION_BODY>}
/**
* 系统接口 - 登录
* @param username 用户名
* @param password 密码(经过md5加密,32位长度,不带中划线,不区分大小写)
* @return
*/
@GetMapping(value = "/login")
@ResponseBody
private JSONObject login(String username,String password ){
if (logger.isDebugEnabled()) {
logger.debug(String.format("模拟接口> 登录 API调用,username:%s ,password:%s ",
username, password));
}
JSONObject result = new JSONObject();
result.put("CookieToken","ynBDDiKMg");
result.put("URLToken","MOBkORkqnrnoVGcKIAHXppgfkNWRdV7utZSkDrI448Q.oxNjAxNTM4NDk3LCJwIjoiZGJjODg5NzliNzVj" +
"Nzc2YmU5MzBjM2JjNjg1ZWFiNGI5ZjhhN2Y0N2RlZjg3NWUyOTJkY2VkYjkwYmEwMTA0NyIsInQiOjE2MDA5MzM2OTcsInUiOiI" +
"4ODlkZDYyM2ViIn0eyJlIj.GciOiJIUzI1NiIsInR5cCI6IkpXVCJ9eyJhb");
result.put("TokenTimeout",604800);
result.put("AuthToken","MOBkORkqnrnoVGcKIAHXppgfkNWRdV7utZSkDrI448Q.oxNjAxNTM4NDk3LCJwIjoiZGJjODg5NzliNzVj" +
"Nzc2YmU5MzBjM2JjNjg1ZWFiNGI5ZjhhN2Y0N2RlZjg3NWUyOTJkY2VkYjkwYmEwMTA0NyIsInQiOjE2MDA5MzM2OTcsInUiOiI" +
"4ODlkZDYyM2ViIn0eyJlIj.GciOiJIUzI1NiIsInR5cCI6IkpXVCJ9eyJhb");
result.put("Token","ynBDDiKMg");
return result;
}
}
|
// JSONObject result = new JSONObject();
// result.put("ID","ceshi");
// result.put("Hardware","");
// result.put("InterfaceVersion","2.5.5");
// result.put("IsDemo","");
// result.put("Hardware","false");
// result.put("APIAuth","false");
// result.put("RemainDays","永久");
// result.put("RunningTime","");
// result.put("ServerTime","2020-09-02 17:11");
// result.put("StartUpTime","2020-09-02 17:11");
// result.put("Server","");
// result.put("SIPSerial", sipConfig.getId());
// result.put("SIPRealm", sipConfig.getDomain());
// result.put("SIPHost", sipConfig.getIp());
// result.put("SIPPort", sipConfig.getPort());
// result.put("ChannelCount","1000");
// result.put("VersionType","");
// result.put("LogoMiniText","");
// result.put("LogoText","");
// result.put("CopyrightText","");
return null;
| 1,071
| 325
| 1,396
|
<no_super_class>
|
648540858_wvp-GB28181-pro
|
wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/web/gb28181/AuthController.java
|
AuthController
|
devices
|
class AuthController {
@Autowired
private IUserService userService;
@GetMapping("/login")
public String devices(String name, String passwd){<FILL_FUNCTION_BODY>}
}
|
User user = userService.getUser(name, passwd);
if (user != null) {
return "success";
}else {
return "fail";
}
| 57
| 49
| 106
|
<no_super_class>
|
DeemOpen_zkui
|
zkui/src/main/java/com/deem/zkui/Main.java
|
Main
|
main
|
class Main {
private final static org.slf4j.Logger logger = LoggerFactory.getLogger(Main.class);
public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>}
}
|
logger.debug("Starting ZKUI!");
Properties globalProps = new Properties();
File f = new File("config.cfg");
if (f.exists()) {
globalProps.load(new FileInputStream("config.cfg"));
} else {
System.out.println("Please create config.cfg properties file and then execute the program!");
System.exit(1);
}
globalProps.setProperty("uptime", new Date().toString());
new Dao(globalProps).checkNCreate();
String webFolder = "webapp";
Server server = new Server();
WebAppContext servletContextHandler = new WebAppContext();
servletContextHandler.setContextPath("/");
servletContextHandler.setResourceBase("src/main/resources/" + webFolder);
ClassList clist = ClassList.setServerDefault(server);
clist.addBefore(JettyWebXmlConfiguration.class.getName(), AnnotationConfiguration.class.getName());
servletContextHandler.setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", ".*(/target/classes/|.*.jar)");
servletContextHandler.setParentLoaderPriority(true);
servletContextHandler.setInitParameter("useFileMappedBuffer", "false");
servletContextHandler.setAttribute("globalProps", globalProps);
ResourceHandler staticResourceHandler = new ResourceHandler();
staticResourceHandler.setDirectoriesListed(false);
Resource staticResources = Resource.newClassPathResource(webFolder);
staticResourceHandler.setBaseResource(staticResources);
staticResourceHandler.setWelcomeFiles(new String[]{"html/index.html"});
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[]{staticResourceHandler, servletContextHandler});
server.setHandler(handlers);
HttpConfiguration http_config = new HttpConfiguration();
http_config.setSecureScheme("https");
http_config.setSecurePort(Integer.parseInt(globalProps.getProperty("serverPort")));
if (globalProps.getProperty("https").equals("true")) {
File keystoreFile = new File(globalProps.getProperty("keystoreFile"));
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setKeyStorePath(keystoreFile.getAbsolutePath());
sslContextFactory.setKeyStorePassword(globalProps.getProperty("keystorePwd"));
sslContextFactory.setKeyManagerPassword(globalProps.getProperty("keystoreManagerPwd"));
HttpConfiguration https_config = new HttpConfiguration(http_config);
https_config.addCustomizer(new SecureRequestCustomizer());
ServerConnector https = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(https_config));
https.setPort(Integer.parseInt(globalProps.getProperty("serverPort")));
server.setConnectors(new Connector[]{https});
} else {
if(globalProps.getProperty("X-Forwarded-For").equals("true")) {
http_config.addCustomizer(new org.eclipse.jetty.server.ForwardedRequestCustomizer());
}
ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(http_config));
http.setPort(Integer.parseInt(globalProps.getProperty("serverPort")));
server.setConnectors(new Connector[]{http});
}
server.start();
server.join();
| 61
| 886
| 947
|
<no_super_class>
|
DeemOpen_zkui
|
zkui/src/main/java/com/deem/zkui/controller/ChangeLog.java
|
ChangeLog
|
doPost
|
class ChangeLog extends HttpServlet {
private final static Logger logger = LoggerFactory.getLogger(ChangeLog.class);
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
logger.debug("History Get Action!");
try {
Properties globalProps = (Properties) this.getServletContext().getAttribute("globalProps");
Dao dao = new Dao(globalProps);
Map<String, Object> templateParam = new HashMap<>();
List<History> historyLst = dao.fetchHistoryRecords();
templateParam.put("historyLst", historyLst);
templateParam.put("historyNode", "");
ServletUtil.INSTANCE.renderHtml(request, response, templateParam, "history.ftl.html");
} catch (TemplateException ex) {
logger.error(Arrays.toString(ex.getStackTrace()));
ServletUtil.INSTANCE.renderError(request, response, ex.getMessage());
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {<FILL_FUNCTION_BODY>}
}
|
logger.debug("History Post Action!");
try {
Properties globalProps = (Properties) this.getServletContext().getAttribute("globalProps");
Dao dao = new Dao(globalProps);
Map<String, Object> templateParam = new HashMap<>();
String action = request.getParameter("action");
List<History> historyLst;
if (action.equals("showhistory")) {
String historyNode = request.getParameter("historyNode");
historyLst = dao.fetchHistoryRecordsByNode("%" + historyNode + "%");
templateParam.put("historyLst", historyLst);
templateParam.put("historyNode", historyNode);
ServletUtil.INSTANCE.renderHtml(request, response, templateParam, "history.ftl.html");
} else {
response.sendRedirect("/history");
}
} catch (TemplateException ex) {
logger.error(Arrays.toString(ex.getStackTrace()));
ServletUtil.INSTANCE.renderError(request, response, ex.getMessage());
}
| 294
| 265
| 559
|
<no_super_class>
|
DeemOpen_zkui
|
zkui/src/main/java/com/deem/zkui/controller/Export.java
|
Export
|
doGet
|
class Export extends HttpServlet {
private final static Logger logger = LoggerFactory.getLogger(Export.class);
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {<FILL_FUNCTION_BODY>}
}
|
logger.debug("Export Get Action!");
try {
Properties globalProps = (Properties) this.getServletContext().getAttribute("globalProps");
String zkServer = globalProps.getProperty("zkServer");
String[] zkServerLst = zkServer.split(",");
String authRole = (String) request.getSession().getAttribute("authRole");
if (authRole == null) {
authRole = ZooKeeperUtil.ROLE_USER;
}
String zkPath = request.getParameter("zkPath");
StringBuilder output = new StringBuilder();
output.append("#App Config Dashboard (ACD) dump created on :").append(new Date()).append("\n");
Set<LeafBean> leaves = ZooKeeperUtil.INSTANCE.exportTree(zkPath, ServletUtil.INSTANCE.getZookeeper(request, response, zkServerLst[0], globalProps), authRole);
for (LeafBean leaf : leaves) {
output.append(leaf.getPath()).append('=').append(leaf.getName()).append('=').append(ServletUtil.INSTANCE.externalizeNodeValue(leaf.getValue())).append('\n');
}// for all leaves
response.setContentType("text/plain;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
out.write(output.toString());
}
} catch (InterruptedException | KeeperException ex) {
logger.error(Arrays.toString(ex.getStackTrace()));
ServletUtil.INSTANCE.renderError(request, response, ex.getMessage());
}
| 72
| 407
| 479
|
<no_super_class>
|
DeemOpen_zkui
|
zkui/src/main/java/com/deem/zkui/controller/Import.java
|
Import
|
doPost
|
class Import extends HttpServlet {
private final static Logger logger = LoggerFactory.getLogger(Import.class);
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {<FILL_FUNCTION_BODY>}
}
|
logger.debug("Importing Action!");
try {
Properties globalProps = (Properties) this.getServletContext().getAttribute("globalProps");
Dao dao = new Dao(globalProps);
String zkServer = globalProps.getProperty("zkServer");
String[] zkServerLst = zkServer.split(",");
StringBuilder sbFile = new StringBuilder();
String scmOverwrite = "false";
String scmServer = "";
String scmFilePath = "";
String scmFileRevision = "";
String uploadFileName = "";
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1034);
ServletFileUpload upload = new ServletFileUpload(factory);
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
if (item.getFieldName().equals("scmOverwrite")) {
scmOverwrite = item.getString();
}
if (item.getFieldName().equals("scmServer")) {
scmServer = item.getString();
}
if (item.getFieldName().equals("scmFilePath")) {
scmFilePath = item.getString();
}
if (item.getFieldName().equals("scmFileRevision")) {
scmFileRevision = item.getString();
}
} else {
uploadFileName = item.getName();
sbFile.append(item.getString("UTF-8"));
}
}
InputStream inpStream;
if (sbFile.toString().length() == 0) {
uploadFileName = scmServer + scmFileRevision + "@" + scmFilePath;
logger.debug("P4 file Processing " + uploadFileName);
dao.insertHistory((String) request.getSession().getAttribute("authName"), request.getRemoteAddr(), "Importing P4 File: " + uploadFileName + "<br/>" + "Overwrite: " + scmOverwrite);
URL url = new URL(uploadFileName);
URLConnection conn = url.openConnection();
inpStream = conn.getInputStream();
} else {
logger.debug("Upload file Processing " + uploadFileName);
dao.insertHistory((String) request.getSession().getAttribute("authName"), request.getRemoteAddr(), "Uploading File: " + uploadFileName + "<br/>" + "Overwrite: " + scmOverwrite);
inpStream = new ByteArrayInputStream(sbFile.toString().getBytes("UTF-8"));
}
// open the stream and put it into BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(inpStream));
String inputLine;
List<String> importFile = new ArrayList<>();
Integer lineCnt = 0;
while ((inputLine = br.readLine()) != null) {
lineCnt++;
// Empty or comment?
if (inputLine.trim().equals("") || inputLine.trim().startsWith("#")) {
continue;
}
if (inputLine.startsWith("-")) {
//DO nothing.
} else if (!inputLine.matches("/.+=.+=.*")) {
throw new IOException("Invalid format at line " + lineCnt + ": " + inputLine);
}
importFile.add(inputLine);
}
br.close();
ZooKeeperUtil.INSTANCE.importData(importFile, Boolean.valueOf(scmOverwrite), ServletUtil.INSTANCE.getZookeeper(request, response, zkServerLst[0], globalProps));
for (String line : importFile) {
if (line.startsWith("-")) {
dao.insertHistory((String) request.getSession().getAttribute("authName"), request.getRemoteAddr(), "File: " + uploadFileName + ", Deleting Entry: " + line);
} else {
dao.insertHistory((String) request.getSession().getAttribute("authName"), request.getRemoteAddr(), "File: " + uploadFileName + ", Adding Entry: " + line);
}
}
request.getSession().setAttribute("flashMsg", "Import Completed!");
response.sendRedirect("/home");
} catch (FileUploadException | IOException | InterruptedException | KeeperException ex) {
logger.error(Arrays.toString(ex.getStackTrace()));
ServletUtil.INSTANCE.renderError(request, response, ex.getMessage());
}
| 71
| 1,154
| 1,225
|
<no_super_class>
|
DeemOpen_zkui
|
zkui/src/main/java/com/deem/zkui/controller/Login.java
|
Login
|
doGet
|
class Login extends HttpServlet {
private final static Logger logger = LoggerFactory.getLogger(Login.class);
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {<FILL_FUNCTION_BODY>}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
logger.debug("Login Post Action!");
try {
Properties globalProps = (Properties) getServletContext().getAttribute("globalProps");
Map<String, Object> templateParam = new HashMap<>();
HttpSession session = request.getSession(true);
session.setMaxInactiveInterval(Integer.valueOf(globalProps.getProperty("sessionTimeout")));
//TODO: Implement custom authentication logic if required.
String username = request.getParameter("username");
String password = request.getParameter("password");
String role = null;
Boolean authenticated = false;
//if ldap is provided then it overrides roleset.
if (globalProps.getProperty("ldapAuth").equals("true")) {
authenticated = new LdapAuth().authenticateUser(globalProps.getProperty("ldapUrl"), username, password, globalProps.getProperty("ldapDomain"));
if (authenticated) {
JSONArray jsonRoleSet = (JSONArray) ((JSONObject) new JSONParser().parse(globalProps.getProperty("ldapRoleSet"))).get("users");
for (Iterator it = jsonRoleSet.iterator(); it.hasNext();) {
JSONObject jsonUser = (JSONObject) it.next();
if (jsonUser.get("username") != null && jsonUser.get("username").equals("*")) {
role = (String) jsonUser.get("role");
}
if (jsonUser.get("username") != null && jsonUser.get("username").equals(username)) {
role = (String) jsonUser.get("role");
}
}
if (role == null) {
role = ZooKeeperUtil.ROLE_USER;
}
}
} else {
JSONArray jsonRoleSet = (JSONArray) ((JSONObject) new JSONParser().parse(globalProps.getProperty("userSet"))).get("users");
for (Iterator it = jsonRoleSet.iterator(); it.hasNext();) {
JSONObject jsonUser = (JSONObject) it.next();
if (jsonUser.get("username").equals(username) && jsonUser.get("password").equals(password)) {
authenticated = true;
role = (String) jsonUser.get("role");
}
}
}
if (authenticated) {
logger.info("Login successful: " + username);
session.setAttribute("authName", username);
session.setAttribute("authRole", role);
response.sendRedirect("/home");
} else {
session.setAttribute("flashMsg", "Invalid Login");
ServletUtil.INSTANCE.renderHtml(request, response, templateParam, "login.ftl.html");
}
} catch (ParseException | TemplateException ex) {
logger.error(Arrays.toString(ex.getStackTrace()));
ServletUtil.INSTANCE.renderError(request, response, ex.getMessage());
}
}
}
|
logger.debug("Login Action!");
try {
Properties globalProps = (Properties) getServletContext().getAttribute("globalProps");
Map<String, Object> templateParam = new HashMap<>();
templateParam.put("uptime", globalProps.getProperty("uptime"));
templateParam.put("loginMessage", globalProps.getProperty("loginMessage"));
ServletUtil.INSTANCE.renderHtml(request, response, templateParam, "login.ftl.html");
} catch (TemplateException ex) {
logger.error(Arrays.toString(ex.getStackTrace()));
ServletUtil.INSTANCE.renderError(request, response, ex.getMessage());
}
| 817
| 168
| 985
|
<no_super_class>
|
DeemOpen_zkui
|
zkui/src/main/java/com/deem/zkui/controller/Logout.java
|
Logout
|
doGet
|
class Logout extends HttpServlet {
private final static Logger logger = LoggerFactory.getLogger(Logout.class);
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {<FILL_FUNCTION_BODY>}
}
|
try {
logger.debug("Logout Action!");
Properties globalProps = (Properties) getServletContext().getAttribute("globalProps");
String zkServer = globalProps.getProperty("zkServer");
String[] zkServerLst = zkServer.split(",");
ZooKeeper zk = ServletUtil.INSTANCE.getZookeeper(request, response, zkServerLst[0],globalProps);
request.getSession().invalidate();
zk.close();
response.sendRedirect("/login");
} catch (InterruptedException ex) {
logger.error(Arrays.toString(ex.getStackTrace()));
ServletUtil.INSTANCE.renderError(request, response, ex.getMessage());
}
| 73
| 189
| 262
|
<no_super_class>
|
DeemOpen_zkui
|
zkui/src/main/java/com/deem/zkui/controller/Monitor.java
|
Monitor
|
doGet
|
class Monitor extends HttpServlet {
private final static Logger logger = LoggerFactory.getLogger(Monitor.class);
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {<FILL_FUNCTION_BODY>}
}
|
logger.debug("Monitor Action!");
try {
Properties globalProps = (Properties) this.getServletContext().getAttribute("globalProps");
String zkServer = globalProps.getProperty("zkServer");
String[] zkServerLst = zkServer.split(",");
Map<String, Object> templateParam = new HashMap<>();
StringBuffer stats = new StringBuffer();
for (String zkObj : zkServerLst) {
stats.append("<br/><hr/><br/>").append("Server: ").append(zkObj).append("<br/><hr/><br/>");
String[] monitorZKServer = zkObj.split(":");
stats.append(CmdUtil.INSTANCE.executeCmd("stat", monitorZKServer[0], monitorZKServer[1]));
stats.append(CmdUtil.INSTANCE.executeCmd("envi", monitorZKServer[0], monitorZKServer[1]));
}
templateParam.put("stats", stats);
ServletUtil.INSTANCE.renderHtml(request, response, templateParam, "monitor.ftl.html");
} catch (IOException | TemplateException ex) {
logger.error(Arrays.toString(ex.getStackTrace()));
ServletUtil.INSTANCE.renderError(request, response, ex.getMessage());
}
| 71
| 334
| 405
|
<no_super_class>
|
DeemOpen_zkui
|
zkui/src/main/java/com/deem/zkui/controller/RestAccess.java
|
RestAccess
|
doGet
|
class RestAccess extends HttpServlet {
private final static Logger logger = LoggerFactory.getLogger(RestAccess.class);
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {<FILL_FUNCTION_BODY>}
}
|
logger.debug("Rest Action!");
ZooKeeper zk = null;
try {
Properties globalProps = (Properties) this.getServletContext().getAttribute("globalProps");
String zkServer = globalProps.getProperty("zkServer");
String[] zkServerLst = zkServer.split(",");
String accessRole = ZooKeeperUtil.ROLE_USER;
if ((globalProps.getProperty("blockPwdOverRest") != null) && (Boolean.valueOf(globalProps.getProperty("blockPwdOverRest")) == Boolean.FALSE)) {
accessRole = ZooKeeperUtil.ROLE_ADMIN;
}
StringBuilder resultOut = new StringBuilder();
String clusterName = request.getParameter("cluster");
String appName = request.getParameter("app");
String hostName = request.getParameter("host");
String[] propNames = request.getParameterValues("propNames");
String propValue = "";
LeafBean propertyNode;
if (hostName == null) {
hostName = ServletUtil.INSTANCE.getRemoteAddr(request);
}
zk = ServletUtil.INSTANCE.getZookeeper(request, response, zkServerLst[0], globalProps);
//get the path of the hosts entry.
LeafBean hostsNode = null;
//If app name is mentioned then lookup path is appended with it.
if (appName != null && ZooKeeperUtil.INSTANCE.nodeExists(ZooKeeperUtil.ZK_HOSTS + "/" + hostName + ":" + appName, zk)) {
hostsNode = ZooKeeperUtil.INSTANCE.getNodeValue(zk, ZooKeeperUtil.ZK_HOSTS, ZooKeeperUtil.ZK_HOSTS + "/" + hostName + ":" + appName, hostName + ":" + appName, accessRole);
} else {
hostsNode = ZooKeeperUtil.INSTANCE.getNodeValue(zk, ZooKeeperUtil.ZK_HOSTS, ZooKeeperUtil.ZK_HOSTS + "/" + hostName, hostName, accessRole);
}
String lookupPath = hostsNode.getStrValue();
logger.trace("Root Path:" + lookupPath);
String[] pathElements = lookupPath.split("/");
//Form all combinations of search path you want to look up the property in.
List<String> searchPath = new ArrayList<>();
StringBuilder pathSubSet = new StringBuilder();
for (String pathElement : pathElements) {
pathSubSet.append(pathElement);
pathSubSet.append("/");
searchPath.add(pathSubSet.substring(0, pathSubSet.length() - 1));
}
//You specify a cluster or an app name to group.
if (clusterName != null && appName == null) {
if (ZooKeeperUtil.INSTANCE.nodeExists(lookupPath + "/" + hostName, zk)) {
searchPath.add(lookupPath + "/" + hostName);
}
if (ZooKeeperUtil.INSTANCE.nodeExists(lookupPath + "/" + clusterName, zk)) {
searchPath.add(lookupPath + "/" + clusterName);
}
if (ZooKeeperUtil.INSTANCE.nodeExists(lookupPath + "/" + clusterName + "/" + hostName, zk)) {
searchPath.add(lookupPath + "/" + clusterName + "/" + hostName);
}
} else if (appName != null && clusterName == null) {
if (ZooKeeperUtil.INSTANCE.nodeExists(lookupPath + "/" + hostName, zk)) {
searchPath.add(lookupPath + "/" + hostName);
}
if (ZooKeeperUtil.INSTANCE.nodeExists(lookupPath + "/" + appName, zk)) {
searchPath.add(lookupPath + "/" + appName);
}
if (ZooKeeperUtil.INSTANCE.nodeExists(lookupPath + "/" + appName + "/" + hostName, zk)) {
searchPath.add(lookupPath + "/" + appName + "/" + hostName);
}
} else if (appName != null && clusterName != null) {
//Order in which these paths are listed is important as the lookup happens in that order.
//Precedence is give to cluster over app.
if (ZooKeeperUtil.INSTANCE.nodeExists(lookupPath + "/" + hostName, zk)) {
searchPath.add(lookupPath + "/" + hostName);
}
if (ZooKeeperUtil.INSTANCE.nodeExists(lookupPath + "/" + appName, zk)) {
searchPath.add(lookupPath + "/" + appName);
}
if (ZooKeeperUtil.INSTANCE.nodeExists(lookupPath + "/" + appName + "/" + hostName, zk)) {
searchPath.add(lookupPath + "/" + appName + "/" + hostName);
}
if (ZooKeeperUtil.INSTANCE.nodeExists(lookupPath + "/" + clusterName, zk)) {
searchPath.add(lookupPath + "/" + clusterName);
}
if (ZooKeeperUtil.INSTANCE.nodeExists(lookupPath + "/" + clusterName + "/" + hostName, zk)) {
searchPath.add(lookupPath + "/" + clusterName + "/" + hostName);
}
if (ZooKeeperUtil.INSTANCE.nodeExists(lookupPath + "/" + clusterName + "/" + appName, zk)) {
searchPath.add(lookupPath + "/" + clusterName + "/" + appName);
}
if (ZooKeeperUtil.INSTANCE.nodeExists(lookupPath + "/" + clusterName + "/" + appName + "/" + hostName, zk)) {
searchPath.add(lookupPath + "/" + clusterName + "/" + appName + "/" + hostName);
}
}
//Search the property in all lookup paths.
for (String propName : propNames) {
propValue = null;
for (String path : searchPath) {
logger.trace("Looking up " + path);
propertyNode = ZooKeeperUtil.INSTANCE.getNodeValue(zk, path, path + "/" + propName, propName, accessRole);
if (propertyNode != null) {
propValue = propertyNode.getStrValue();
}
}
if (propValue != null) {
resultOut.append(propName).append("=").append(propValue).append("\n");
}
}
response.setContentType("text/plain;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
out.write(resultOut.toString());
}
} catch (KeeperException | InterruptedException ex) {
logger.error(Arrays.toString(ex.getStackTrace()));
ServletUtil.INSTANCE.renderError(request, response, ex.getMessage());
} finally {
if (zk != null) {
ServletUtil.INSTANCE.closeZookeeper(zk);
}
}
| 73
| 1,856
| 1,929
|
<no_super_class>
|
DeemOpen_zkui
|
zkui/src/main/java/com/deem/zkui/dao/Dao.java
|
Dao
|
checkNCreate
|
class Dao {
private final static Integer FETCH_LIMIT = 50;
private final static org.slf4j.Logger logger = LoggerFactory.getLogger(Dao.class);
private final Properties globalProps;
public Dao(Properties globalProps) {
this.globalProps = globalProps;
}
public void open() {
Base.open(globalProps.getProperty("jdbcClass"), globalProps.getProperty("jdbcUrl"), globalProps.getProperty("jdbcUser"), globalProps.getProperty("jdbcPwd"));
}
public void close() {
Base.close();
}
public void checkNCreate() {<FILL_FUNCTION_BODY>}
public List<History> fetchHistoryRecords() {
this.open();
List<History> history = History.findAll().orderBy("ID desc").limit(FETCH_LIMIT);
history.size();
this.close();
return history;
}
public List<History> fetchHistoryRecordsByNode(String historyNode) {
this.open();
List<History> history = History.where("CHANGE_SUMMARY like ?", historyNode).orderBy("ID desc").limit(FETCH_LIMIT);
history.size();
this.close();
return history;
}
public void insertHistory(String user, String ipAddress, String summary) {
try {
this.open();
//To avoid errors due to truncation.
if (summary.length() >= 500) {
summary = summary.substring(0, 500);
}
History history = new History();
history.setChangeUser(user);
history.setChangeIp(ipAddress);
history.setChangeSummary(summary);
history.setChangeDate(new Date());
history.save();
this.close();
} catch (Exception ex) {
logger.error(Arrays.toString(ex.getStackTrace()));
}
}
}
|
try {
Flyway flyway = new Flyway();
flyway.setDataSource(globalProps.getProperty("jdbcUrl"), globalProps.getProperty("jdbcUser"), globalProps.getProperty("jdbcPwd"));
//Will wipe db each time. Avoid this in prod.
if (globalProps.getProperty("env").equals("dev")) {
flyway.clean();
}
//Remove the above line if deploying to prod.
flyway.migrate();
} catch (Exception ex) {
logger.error("Error trying to migrate db! Not severe hence proceeding forward.");
}
| 511
| 156
| 667
|
<no_super_class>
|
DeemOpen_zkui
|
zkui/src/main/java/com/deem/zkui/filter/AuthFilter.java
|
AuthFilter
|
doFilter
|
class AuthFilter implements Filter {
@Override
public void init(FilterConfig fc) throws ServletException {
//Do Nothing
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain fc) throws IOException, ServletException {<FILL_FUNCTION_BODY>}
@Override
public void destroy() {
//Do nothing
}
}
|
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
if (!request.getRequestURI().contains("/login") && !request.getRequestURI().contains("/acd/appconfig")) {
RequestDispatcher dispatcher;
HttpSession session = request.getSession();
if (session != null) {
if (session.getAttribute("authName") == null || session.getAttribute("authRole") == null) {
response.sendRedirect("/login");
return;
}
} else {
request.setAttribute("fail_msg", "Session timed out!");
dispatcher = request.getRequestDispatcher("/Login");
dispatcher.forward(request, response);
return;
}
}
fc.doFilter(req, res);
| 104
| 208
| 312
|
<no_super_class>
|
DeemOpen_zkui
|
zkui/src/main/java/com/deem/zkui/listener/SessionListener.java
|
SessionListener
|
sessionDestroyed
|
class SessionListener implements HttpSessionListener {
private static final Logger logger = LoggerFactory.getLogger(SessionListener.class);
@Override
public void sessionCreated(HttpSessionEvent event) {
logger.trace("Session created");
}
@Override
public void sessionDestroyed(HttpSessionEvent event) {<FILL_FUNCTION_BODY>}
}
|
try {
ZooKeeper zk = (ZooKeeper) event.getSession().getAttribute("zk");
zk.close();
logger.trace("Session destroyed");
} catch (InterruptedException ex) {
logger.error(Arrays.toString(ex.getStackTrace()));
}
| 96
| 82
| 178
|
<no_super_class>
|
DeemOpen_zkui
|
zkui/src/main/java/com/deem/zkui/utils/LdapAuth.java
|
LdapAuth
|
authenticateUser
|
class LdapAuth {
DirContext ctx = null;
private final static org.slf4j.Logger logger = LoggerFactory.getLogger(LdapAuth.class);
public boolean authenticateUser(String ldapUrl, String username, String password, String domains) {<FILL_FUNCTION_BODY>}
}
|
String[] domainArr = domains.split(",");
for (String domain : domainArr) {
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, ldapUrl);
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, domain + "\\" + username);
env.put(Context.SECURITY_CREDENTIALS, password);
try {
ctx = new InitialDirContext(env);
return true;
} catch (NamingException e) {
} finally {
if (ctx != null) {
try {
ctx.close();
} catch (NamingException ex) {
logger.warn(ex.getMessage());
}
}
}
}
return false;
| 84
| 261
| 345
|
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/BinaryBitmap.java
|
BinaryBitmap
|
getBlackMatrix
|
class BinaryBitmap {
private final Binarizer binarizer;
private BitMatrix matrix;
public BinaryBitmap(Binarizer binarizer) {
if (binarizer == null) {
throw new IllegalArgumentException("Binarizer must be non-null.");
}
this.binarizer = binarizer;
}
/**
* @return The width of the bitmap.
*/
public int getWidth() {
return binarizer.getWidth();
}
/**
* @return The height of the bitmap.
*/
public int getHeight() {
return binarizer.getHeight();
}
/**
* Converts one row of luminance data to 1 bit data. May actually do the conversion, or return
* cached data. Callers should assume this method is expensive and call it as seldom as possible.
* This method is intended for decoding 1D barcodes and may choose to apply sharpening.
*
* @param y The row to fetch, which must be in [0, bitmap height)
* @param row An optional preallocated array. If null or too small, it will be ignored.
* If used, the Binarizer will call BitArray.clear(). Always use the returned object.
* @return The array of bits for this row (true means black).
* @throws NotFoundException if row can't be binarized
*/
public BitArray getBlackRow(int y, BitArray row) throws NotFoundException {
return binarizer.getBlackRow(y, row);
}
/**
* Converts a 2D array of luminance data to 1 bit. As above, assume this method is expensive
* and do not call it repeatedly. This method is intended for decoding 2D barcodes and may or
* may not apply sharpening. Therefore, a row from this matrix may not be identical to one
* fetched using getBlackRow(), so don't mix and match between them.
*
* @return The 2D array of bits for the image (true means black).
* @throws NotFoundException if image can't be binarized to make a matrix
*/
public BitMatrix getBlackMatrix() throws NotFoundException {<FILL_FUNCTION_BODY>}
/**
* @return Whether this bitmap can be cropped.
*/
public boolean isCropSupported() {
return binarizer.getLuminanceSource().isCropSupported();
}
/**
* Returns a new object with cropped image data. Implementations may keep a reference to the
* original data rather than a copy. Only callable if isCropSupported() is true.
*
* @param left The left coordinate, which must be in [0,getWidth())
* @param top The top coordinate, which must be in [0,getHeight())
* @param width The width of the rectangle to crop.
* @param height The height of the rectangle to crop.
* @return A cropped version of this object.
*/
public BinaryBitmap crop(int left, int top, int width, int height) {
LuminanceSource newSource = binarizer.getLuminanceSource().crop(left, top, width, height);
return new BinaryBitmap(binarizer.createBinarizer(newSource));
}
/**
* @return Whether this bitmap supports counter-clockwise rotation.
*/
public boolean isRotateSupported() {
return binarizer.getLuminanceSource().isRotateSupported();
}
/**
* Returns a new object with rotated image data by 90 degrees counterclockwise.
* Only callable if {@link #isRotateSupported()} is true.
*
* @return A rotated version of this object.
*/
public BinaryBitmap rotateCounterClockwise() {
LuminanceSource newSource = binarizer.getLuminanceSource().rotateCounterClockwise();
return new BinaryBitmap(binarizer.createBinarizer(newSource));
}
/**
* Returns a new object with rotated image data by 45 degrees counterclockwise.
* Only callable if {@link #isRotateSupported()} is true.
*
* @return A rotated version of this object.
*/
public BinaryBitmap rotateCounterClockwise45() {
LuminanceSource newSource = binarizer.getLuminanceSource().rotateCounterClockwise45();
return new BinaryBitmap(binarizer.createBinarizer(newSource));
}
@Override
public String toString() {
try {
return getBlackMatrix().toString();
} catch (NotFoundException e) {
return "";
}
}
}
|
// The matrix is created on demand the first time it is requested, then cached. There are two
// reasons for this:
// 1. This work will never be done if the caller only installs 1D Reader objects, or if a
// 1D Reader finds a barcode before the 2D Readers run.
// 2. This work will only be done once even if the caller installs multiple 2D Readers.
if (matrix == null) {
matrix = binarizer.getBlackMatrix();
}
return matrix;
| 1,199
| 137
| 1,336
|
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/Dimension.java
|
Dimension
|
equals
|
class Dimension {
private final int width;
private final int height;
public Dimension(int width, int height) {
if (width < 0 || height < 0) {
throw new IllegalArgumentException();
}
this.width = width;
this.height = height;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
@Override
public boolean equals(Object other) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return width * 32713 + height;
}
@Override
public String toString() {
return width + "x" + height;
}
}
|
if (other instanceof Dimension) {
Dimension d = (Dimension) other;
return width == d.width && height == d.height;
}
return false;
| 197
| 48
| 245
|
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/InvertedLuminanceSource.java
|
InvertedLuminanceSource
|
getMatrix
|
class InvertedLuminanceSource extends LuminanceSource {
private final LuminanceSource delegate;
public InvertedLuminanceSource(LuminanceSource delegate) {
super(delegate.getWidth(), delegate.getHeight());
this.delegate = delegate;
}
@Override
public byte[] getRow(int y, byte[] row) {
row = delegate.getRow(y, row);
int width = getWidth();
for (int i = 0; i < width; i++) {
row[i] = (byte) (255 - (row[i] & 0xFF));
}
return row;
}
@Override
public byte[] getMatrix() {<FILL_FUNCTION_BODY>}
@Override
public boolean isCropSupported() {
return delegate.isCropSupported();
}
@Override
public LuminanceSource crop(int left, int top, int width, int height) {
return new InvertedLuminanceSource(delegate.crop(left, top, width, height));
}
@Override
public boolean isRotateSupported() {
return delegate.isRotateSupported();
}
/**
* @return original delegate {@link LuminanceSource} since invert undoes itself
*/
@Override
public LuminanceSource invert() {
return delegate;
}
@Override
public LuminanceSource rotateCounterClockwise() {
return new InvertedLuminanceSource(delegate.rotateCounterClockwise());
}
@Override
public LuminanceSource rotateCounterClockwise45() {
return new InvertedLuminanceSource(delegate.rotateCounterClockwise45());
}
}
|
byte[] matrix = delegate.getMatrix();
int length = getWidth() * getHeight();
byte[] invertedMatrix = new byte[length];
for (int i = 0; i < length; i++) {
invertedMatrix[i] = (byte) (255 - (matrix[i] & 0xFF));
}
return invertedMatrix;
| 453
| 94
| 547
|
<methods>public com.google.zxing.LuminanceSource crop(int, int, int, int) ,public final int getHeight() ,public abstract byte[] getMatrix() ,public abstract byte[] getRow(int, byte[]) ,public final int getWidth() ,public com.google.zxing.LuminanceSource invert() ,public boolean isCropSupported() ,public boolean isRotateSupported() ,public com.google.zxing.LuminanceSource rotateCounterClockwise() ,public com.google.zxing.LuminanceSource rotateCounterClockwise45() ,public final java.lang.String toString() <variables>private final non-sealed int height,private final non-sealed int width
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/LuminanceSource.java
|
LuminanceSource
|
toString
|
class LuminanceSource {
private final int width;
private final int height;
protected LuminanceSource(int width, int height) {
this.width = width;
this.height = height;
}
/**
* Fetches one row of luminance data from the underlying platform's bitmap. Values range from
* 0 (black) to 255 (white). Because Java does not have an unsigned byte type, callers will have
* to bitwise and with 0xff for each value. It is preferable for implementations of this method
* to only fetch this row rather than the whole image, since no 2D Readers may be installed and
* getMatrix() may never be called.
*
* @param y The row to fetch, which must be in [0,getHeight())
* @param row An optional preallocated array. If null or too small, it will be ignored.
* Always use the returned object, and ignore the .length of the array.
* @return An array containing the luminance data.
*/
public abstract byte[] getRow(int y, byte[] row);
/**
* Fetches luminance data for the underlying bitmap. Values should be fetched using:
* {@code int luminance = array[y * width + x] & 0xff}
*
* @return A row-major 2D array of luminance values. Do not use result.length as it may be
* larger than width * height bytes on some platforms. Do not modify the contents
* of the result.
*/
public abstract byte[] getMatrix();
/**
* @return The width of the bitmap.
*/
public final int getWidth() {
return width;
}
/**
* @return The height of the bitmap.
*/
public final int getHeight() {
return height;
}
/**
* @return Whether this subclass supports cropping.
*/
public boolean isCropSupported() {
return false;
}
/**
* Returns a new object with cropped image data. Implementations may keep a reference to the
* original data rather than a copy. Only callable if isCropSupported() is true.
*
* @param left The left coordinate, which must be in [0,getWidth())
* @param top The top coordinate, which must be in [0,getHeight())
* @param width The width of the rectangle to crop.
* @param height The height of the rectangle to crop.
* @return A cropped version of this object.
*/
public LuminanceSource crop(int left, int top, int width, int height) {
throw new UnsupportedOperationException("This luminance source does not support cropping.");
}
/**
* @return Whether this subclass supports counter-clockwise rotation.
*/
public boolean isRotateSupported() {
return false;
}
/**
* @return a wrapper of this {@code LuminanceSource} which inverts the luminances it returns -- black becomes
* white and vice versa, and each value becomes (255-value).
*/
public LuminanceSource invert() {
return new InvertedLuminanceSource(this);
}
/**
* Returns a new object with rotated image data by 90 degrees counterclockwise.
* Only callable if {@link #isRotateSupported()} is true.
*
* @return A rotated version of this object.
*/
public LuminanceSource rotateCounterClockwise() {
throw new UnsupportedOperationException("This luminance source does not support rotation by 90 degrees.");
}
/**
* Returns a new object with rotated image data by 45 degrees counterclockwise.
* Only callable if {@link #isRotateSupported()} is true.
*
* @return A rotated version of this object.
*/
public LuminanceSource rotateCounterClockwise45() {
throw new UnsupportedOperationException("This luminance source does not support rotation by 45 degrees.");
}
@Override
public final String toString() {<FILL_FUNCTION_BODY>}
}
|
byte[] row = new byte[width];
StringBuilder result = new StringBuilder(height * (width + 1));
for (int y = 0; y < height; y++) {
row = getRow(y, row);
for (int x = 0; x < width; x++) {
int luminance = row[x] & 0xFF;
char c;
if (luminance < 0x40) {
c = '#';
} else if (luminance < 0x80) {
c = '+';
} else if (luminance < 0xC0) {
c = '.';
} else {
c = ' ';
}
result.append(c);
}
result.append('\n');
}
return result.toString();
| 1,051
| 207
| 1,258
|
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/MultiFormatReader.java
|
MultiFormatReader
|
reset
|
class MultiFormatReader implements Reader {
private static final Reader[] EMPTY_READER_ARRAY = new Reader[0];
private Map<DecodeHintType,?> hints;
private Reader[] readers;
/**
* This version of decode honors the intent of Reader.decode(BinaryBitmap) in that it
* passes null as a hint to the decoders. However, that makes it inefficient to call repeatedly.
* Use setHints() followed by decodeWithState() for continuous scan applications.
*
* @param image The pixel data to decode
* @return The contents of the image
* @throws NotFoundException Any errors which occurred
*/
@Override
public Result decode(BinaryBitmap image) throws NotFoundException {
setHints(null);
return decodeInternal(image);
}
/**
* Decode an image using the hints provided. Does not honor existing state.
*
* @param image The pixel data to decode
* @param hints The hints to use, clearing the previous state.
* @return The contents of the image
* @throws NotFoundException Any errors which occurred
*/
@Override
public Result decode(BinaryBitmap image, Map<DecodeHintType,?> hints) throws NotFoundException {
setHints(hints);
return decodeInternal(image);
}
/**
* Decode an image using the state set up by calling setHints() previously. Continuous scan
* clients will get a <b>large</b> speed increase by using this instead of decode().
*
* @param image The pixel data to decode
* @return The contents of the image
* @throws NotFoundException Any errors which occurred
*/
public Result decodeWithState(BinaryBitmap image) throws NotFoundException {
// Make sure to set up the default state so we don't crash
if (readers == null) {
setHints(null);
}
return decodeInternal(image);
}
/**
* This method adds state to the MultiFormatReader. By setting the hints once, subsequent calls
* to decodeWithState(image) can reuse the same set of readers without reallocating memory. This
* is important for performance in continuous scan clients.
*
* @param hints The set of hints to use for subsequent calls to decode(image)
*/
public void setHints(Map<DecodeHintType,?> hints) {
this.hints = hints;
boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER);
@SuppressWarnings("unchecked")
Collection<BarcodeFormat> formats =
hints == null ? null : (Collection<BarcodeFormat>) hints.get(DecodeHintType.POSSIBLE_FORMATS);
Collection<Reader> readers = new ArrayList<>();
if (formats != null) {
boolean addOneDReader =
formats.contains(BarcodeFormat.UPC_A) ||
formats.contains(BarcodeFormat.UPC_E) ||
formats.contains(BarcodeFormat.EAN_13) ||
formats.contains(BarcodeFormat.EAN_8) ||
formats.contains(BarcodeFormat.CODABAR) ||
formats.contains(BarcodeFormat.CODE_39) ||
formats.contains(BarcodeFormat.CODE_93) ||
formats.contains(BarcodeFormat.CODE_128) ||
formats.contains(BarcodeFormat.ITF) ||
formats.contains(BarcodeFormat.RSS_14) ||
formats.contains(BarcodeFormat.RSS_EXPANDED);
// Put 1D readers upfront in "normal" mode
if (addOneDReader && !tryHarder) {
readers.add(new MultiFormatOneDReader(hints));
}
if (formats.contains(BarcodeFormat.QR_CODE)) {
readers.add(new QRCodeReader());
}
if (formats.contains(BarcodeFormat.DATA_MATRIX)) {
readers.add(new DataMatrixReader());
}
if (formats.contains(BarcodeFormat.AZTEC)) {
readers.add(new AztecReader());
}
if (formats.contains(BarcodeFormat.PDF_417)) {
readers.add(new PDF417Reader());
}
if (formats.contains(BarcodeFormat.MAXICODE)) {
readers.add(new MaxiCodeReader());
}
// At end in "try harder" mode
if (addOneDReader && tryHarder) {
readers.add(new MultiFormatOneDReader(hints));
}
}
if (readers.isEmpty()) {
if (!tryHarder) {
readers.add(new MultiFormatOneDReader(hints));
}
readers.add(new QRCodeReader());
readers.add(new DataMatrixReader());
readers.add(new AztecReader());
readers.add(new PDF417Reader());
readers.add(new MaxiCodeReader());
if (tryHarder) {
readers.add(new MultiFormatOneDReader(hints));
}
}
this.readers = readers.toArray(EMPTY_READER_ARRAY);
}
@Override
public void reset() {<FILL_FUNCTION_BODY>}
private Result decodeInternal(BinaryBitmap image) throws NotFoundException {
if (readers != null) {
for (Reader reader : readers) {
if (Thread.currentThread().isInterrupted()) {
throw NotFoundException.getNotFoundInstance();
}
try {
return reader.decode(image, hints);
} catch (ReaderException re) {
// continue
}
}
if (hints != null && hints.containsKey(DecodeHintType.ALSO_INVERTED)) {
// Calling all readers again with inverted image
image.getBlackMatrix().flip();
for (Reader reader : readers) {
if (Thread.currentThread().isInterrupted()) {
throw NotFoundException.getNotFoundInstance();
}
try {
return reader.decode(image, hints);
} catch (ReaderException re) {
// continue
}
}
}
}
throw NotFoundException.getNotFoundInstance();
}
}
|
if (readers != null) {
for (Reader reader : readers) {
reader.reset();
}
}
| 1,636
| 36
| 1,672
|
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/MultiFormatWriter.java
|
MultiFormatWriter
|
encode
|
class MultiFormatWriter implements Writer {
@Override
public BitMatrix encode(String contents,
BarcodeFormat format,
int width,
int height) throws WriterException {
return encode(contents, format, width, height, null);
}
@Override
public BitMatrix encode(String contents,
BarcodeFormat format,
int width, int height,
Map<EncodeHintType,?> hints) throws WriterException {<FILL_FUNCTION_BODY>}
}
|
Writer writer;
switch (format) {
case EAN_8:
writer = new EAN8Writer();
break;
case UPC_E:
writer = new UPCEWriter();
break;
case EAN_13:
writer = new EAN13Writer();
break;
case UPC_A:
writer = new UPCAWriter();
break;
case QR_CODE:
writer = new QRCodeWriter();
break;
case CODE_39:
writer = new Code39Writer();
break;
case CODE_93:
writer = new Code93Writer();
break;
case CODE_128:
writer = new Code128Writer();
break;
case ITF:
writer = new ITFWriter();
break;
case PDF_417:
writer = new PDF417Writer();
break;
case CODABAR:
writer = new CodaBarWriter();
break;
case DATA_MATRIX:
writer = new DataMatrixWriter();
break;
case AZTEC:
writer = new AztecWriter();
break;
default:
throw new IllegalArgumentException("No encoder available for format " + format);
}
return writer.encode(contents, format, width, height, hints);
| 130
| 350
| 480
|
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/PlanarYUVLuminanceSource.java
|
PlanarYUVLuminanceSource
|
renderThumbnail
|
class PlanarYUVLuminanceSource extends LuminanceSource {
private static final int THUMBNAIL_SCALE_FACTOR = 2;
private final byte[] yuvData;
private final int dataWidth;
private final int dataHeight;
private final int left;
private final int top;
public PlanarYUVLuminanceSource(byte[] yuvData,
int dataWidth,
int dataHeight,
int left,
int top,
int width,
int height,
boolean reverseHorizontal) {
super(width, height);
if (left + width > dataWidth || top + height > dataHeight) {
throw new IllegalArgumentException("Crop rectangle does not fit within image data.");
}
this.yuvData = yuvData;
this.dataWidth = dataWidth;
this.dataHeight = dataHeight;
this.left = left;
this.top = top;
if (reverseHorizontal) {
reverseHorizontal(width, height);
}
}
@Override
public byte[] getRow(int y, byte[] row) {
if (y < 0 || y >= getHeight()) {
throw new IllegalArgumentException("Requested row is outside the image: " + y);
}
int width = getWidth();
if (row == null || row.length < width) {
row = new byte[width];
}
int offset = (y + top) * dataWidth + left;
System.arraycopy(yuvData, offset, row, 0, width);
return row;
}
@Override
public byte[] getMatrix() {
int width = getWidth();
int height = getHeight();
// If the caller asks for the entire underlying image, save the copy and give them the
// original data. The docs specifically warn that result.length must be ignored.
if (width == dataWidth && height == dataHeight) {
return yuvData;
}
int area = width * height;
byte[] matrix = new byte[area];
int inputOffset = top * dataWidth + left;
// If the width matches the full width of the underlying data, perform a single copy.
if (width == dataWidth) {
System.arraycopy(yuvData, inputOffset, matrix, 0, area);
return matrix;
}
// Otherwise copy one cropped row at a time.
for (int y = 0; y < height; y++) {
int outputOffset = y * width;
System.arraycopy(yuvData, inputOffset, matrix, outputOffset, width);
inputOffset += dataWidth;
}
return matrix;
}
@Override
public boolean isCropSupported() {
return true;
}
@Override
public LuminanceSource crop(int left, int top, int width, int height) {
return new PlanarYUVLuminanceSource(yuvData,
dataWidth,
dataHeight,
this.left + left,
this.top + top,
width,
height,
false);
}
public int[] renderThumbnail() {<FILL_FUNCTION_BODY>}
/**
* @return width of image from {@link #renderThumbnail()}
*/
public int getThumbnailWidth() {
return getWidth() / THUMBNAIL_SCALE_FACTOR;
}
/**
* @return height of image from {@link #renderThumbnail()}
*/
public int getThumbnailHeight() {
return getHeight() / THUMBNAIL_SCALE_FACTOR;
}
private void reverseHorizontal(int width, int height) {
byte[] yuvData = this.yuvData;
for (int y = 0, rowStart = top * dataWidth + left; y < height; y++, rowStart += dataWidth) {
int middle = rowStart + width / 2;
for (int x1 = rowStart, x2 = rowStart + width - 1; x1 < middle; x1++, x2--) {
byte temp = yuvData[x1];
yuvData[x1] = yuvData[x2];
yuvData[x2] = temp;
}
}
}
}
|
int width = getWidth() / THUMBNAIL_SCALE_FACTOR;
int height = getHeight() / THUMBNAIL_SCALE_FACTOR;
int[] pixels = new int[width * height];
byte[] yuv = yuvData;
int inputOffset = top * dataWidth + left;
for (int y = 0; y < height; y++) {
int outputOffset = y * width;
for (int x = 0; x < width; x++) {
int grey = yuv[inputOffset + x * THUMBNAIL_SCALE_FACTOR] & 0xff;
pixels[outputOffset + x] = 0xFF000000 | (grey * 0x00010101);
}
inputOffset += dataWidth * THUMBNAIL_SCALE_FACTOR;
}
return pixels;
| 1,087
| 233
| 1,320
|
<methods>public com.google.zxing.LuminanceSource crop(int, int, int, int) ,public final int getHeight() ,public abstract byte[] getMatrix() ,public abstract byte[] getRow(int, byte[]) ,public final int getWidth() ,public com.google.zxing.LuminanceSource invert() ,public boolean isCropSupported() ,public boolean isRotateSupported() ,public com.google.zxing.LuminanceSource rotateCounterClockwise() ,public com.google.zxing.LuminanceSource rotateCounterClockwise45() ,public final java.lang.String toString() <variables>private final non-sealed int height,private final non-sealed int width
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/RGBLuminanceSource.java
|
RGBLuminanceSource
|
getMatrix
|
class RGBLuminanceSource extends LuminanceSource {
private final byte[] luminances;
private final int dataWidth;
private final int dataHeight;
private final int left;
private final int top;
public RGBLuminanceSource(int width, int height, int[] pixels) {
super(width, height);
dataWidth = width;
dataHeight = height;
left = 0;
top = 0;
// In order to measure pure decoding speed, we convert the entire image to a greyscale array
// up front, which is the same as the Y channel of the YUVLuminanceSource in the real app.
//
// Total number of pixels suffices, can ignore shape
int size = width * height;
luminances = new byte[size];
for (int offset = 0; offset < size; offset++) {
int pixel = pixels[offset];
int r = (pixel >> 16) & 0xff; // red
int g2 = (pixel >> 7) & 0x1fe; // 2 * green
int b = pixel & 0xff; // blue
// Calculate green-favouring average cheaply
luminances[offset] = (byte) ((r + g2 + b) / 4);
}
}
private RGBLuminanceSource(byte[] pixels,
int dataWidth,
int dataHeight,
int left,
int top,
int width,
int height) {
super(width, height);
if (left + width > dataWidth || top + height > dataHeight) {
throw new IllegalArgumentException("Crop rectangle does not fit within image data.");
}
this.luminances = pixels;
this.dataWidth = dataWidth;
this.dataHeight = dataHeight;
this.left = left;
this.top = top;
}
@Override
public byte[] getRow(int y, byte[] row) {
if (y < 0 || y >= getHeight()) {
throw new IllegalArgumentException("Requested row is outside the image: " + y);
}
int width = getWidth();
if (row == null || row.length < width) {
row = new byte[width];
}
int offset = (y + top) * dataWidth + left;
System.arraycopy(luminances, offset, row, 0, width);
return row;
}
@Override
public byte[] getMatrix() {<FILL_FUNCTION_BODY>}
@Override
public boolean isCropSupported() {
return true;
}
@Override
public LuminanceSource crop(int left, int top, int width, int height) {
return new RGBLuminanceSource(luminances,
dataWidth,
dataHeight,
this.left + left,
this.top + top,
width,
height);
}
}
|
int width = getWidth();
int height = getHeight();
// If the caller asks for the entire underlying image, save the copy and give them the
// original data. The docs specifically warn that result.length must be ignored.
if (width == dataWidth && height == dataHeight) {
return luminances;
}
int area = width * height;
byte[] matrix = new byte[area];
int inputOffset = top * dataWidth + left;
// If the width matches the full width of the underlying data, perform a single copy.
if (width == dataWidth) {
System.arraycopy(luminances, inputOffset, matrix, 0, area);
return matrix;
}
// Otherwise copy one cropped row at a time.
for (int y = 0; y < height; y++) {
int outputOffset = y * width;
System.arraycopy(luminances, inputOffset, matrix, outputOffset, width);
inputOffset += dataWidth;
}
return matrix;
| 732
| 256
| 988
|
<methods>public com.google.zxing.LuminanceSource crop(int, int, int, int) ,public final int getHeight() ,public abstract byte[] getMatrix() ,public abstract byte[] getRow(int, byte[]) ,public final int getWidth() ,public com.google.zxing.LuminanceSource invert() ,public boolean isCropSupported() ,public boolean isRotateSupported() ,public com.google.zxing.LuminanceSource rotateCounterClockwise() ,public com.google.zxing.LuminanceSource rotateCounterClockwise45() ,public final java.lang.String toString() <variables>private final non-sealed int height,private final non-sealed int width
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/Result.java
|
Result
|
addResultPoints
|
class Result {
private final String text;
private final byte[] rawBytes;
private final int numBits;
private ResultPoint[] resultPoints;
private final BarcodeFormat format;
private Map<ResultMetadataType,Object> resultMetadata;
private final long timestamp;
public Result(String text,
byte[] rawBytes,
ResultPoint[] resultPoints,
BarcodeFormat format) {
this(text, rawBytes, resultPoints, format, System.currentTimeMillis());
}
public Result(String text,
byte[] rawBytes,
ResultPoint[] resultPoints,
BarcodeFormat format,
long timestamp) {
this(text, rawBytes, rawBytes == null ? 0 : 8 * rawBytes.length,
resultPoints, format, timestamp);
}
public Result(String text,
byte[] rawBytes,
int numBits,
ResultPoint[] resultPoints,
BarcodeFormat format,
long timestamp) {
this.text = text;
this.rawBytes = rawBytes;
this.numBits = numBits;
this.resultPoints = resultPoints;
this.format = format;
this.resultMetadata = null;
this.timestamp = timestamp;
}
/**
* @return raw text encoded by the barcode
*/
public String getText() {
return text;
}
/**
* @return raw bytes encoded by the barcode, if applicable, otherwise {@code null}
*/
public byte[] getRawBytes() {
return rawBytes;
}
/**
* @return how many bits of {@link #getRawBytes()} are valid; typically 8 times its length
* @since 3.3.0
*/
public int getNumBits() {
return numBits;
}
/**
* @return points related to the barcode in the image. These are typically points
* identifying finder patterns or the corners of the barcode. The exact meaning is
* specific to the type of barcode that was decoded.
*/
public ResultPoint[] getResultPoints() {
return resultPoints;
}
/**
* @return {@link BarcodeFormat} representing the format of the barcode that was decoded
*/
public BarcodeFormat getBarcodeFormat() {
return format;
}
/**
* @return {@link Map} mapping {@link ResultMetadataType} keys to values. May be
* {@code null}. This contains optional metadata about what was detected about the barcode,
* like orientation.
*/
public Map<ResultMetadataType,Object> getResultMetadata() {
return resultMetadata;
}
public void putMetadata(ResultMetadataType type, Object value) {
if (resultMetadata == null) {
resultMetadata = new EnumMap<>(ResultMetadataType.class);
}
resultMetadata.put(type, value);
}
public void putAllMetadata(Map<ResultMetadataType,Object> metadata) {
if (metadata != null) {
if (resultMetadata == null) {
resultMetadata = metadata;
} else {
resultMetadata.putAll(metadata);
}
}
}
public void addResultPoints(ResultPoint[] newPoints) {<FILL_FUNCTION_BODY>}
public long getTimestamp() {
return timestamp;
}
@Override
public String toString() {
return text;
}
}
|
ResultPoint[] oldPoints = resultPoints;
if (oldPoints == null) {
resultPoints = newPoints;
} else if (newPoints != null && newPoints.length > 0) {
ResultPoint[] allPoints = new ResultPoint[oldPoints.length + newPoints.length];
System.arraycopy(oldPoints, 0, allPoints, 0, oldPoints.length);
System.arraycopy(newPoints, 0, allPoints, oldPoints.length, newPoints.length);
resultPoints = allPoints;
}
| 885
| 135
| 1,020
|
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/ResultPoint.java
|
ResultPoint
|
orderBestPatterns
|
class ResultPoint {
private final float x;
private final float y;
public ResultPoint(float x, float y) {
this.x = x;
this.y = y;
}
public final float getX() {
return x;
}
public final float getY() {
return y;
}
@Override
public final boolean equals(Object other) {
if (other instanceof ResultPoint) {
ResultPoint otherPoint = (ResultPoint) other;
return x == otherPoint.x && y == otherPoint.y;
}
return false;
}
@Override
public final int hashCode() {
return 31 * Float.floatToIntBits(x) + Float.floatToIntBits(y);
}
@Override
public final String toString() {
return "(" + x + ',' + y + ')';
}
/**
* Orders an array of three ResultPoints in an order [A,B,C] such that AB is less than AC
* and BC is less than AC, and the angle between BC and BA is less than 180 degrees.
*
* @param patterns array of three {@code ResultPoint} to order
*/
public static void orderBestPatterns(ResultPoint[] patterns) {<FILL_FUNCTION_BODY>}
/**
* @param pattern1 first pattern
* @param pattern2 second pattern
* @return distance between two points
*/
public static float distance(ResultPoint pattern1, ResultPoint pattern2) {
return MathUtils.distance(pattern1.x, pattern1.y, pattern2.x, pattern2.y);
}
/**
* Returns the z component of the cross product between vectors BC and BA.
*/
private static float crossProductZ(ResultPoint pointA,
ResultPoint pointB,
ResultPoint pointC) {
float bX = pointB.x;
float bY = pointB.y;
return ((pointC.x - bX) * (pointA.y - bY)) - ((pointC.y - bY) * (pointA.x - bX));
}
}
|
// Find distances between pattern centers
float zeroOneDistance = distance(patterns[0], patterns[1]);
float oneTwoDistance = distance(patterns[1], patterns[2]);
float zeroTwoDistance = distance(patterns[0], patterns[2]);
ResultPoint pointA;
ResultPoint pointB;
ResultPoint pointC;
// Assume one closest to other two is B; A and C will just be guesses at first
if (oneTwoDistance >= zeroOneDistance && oneTwoDistance >= zeroTwoDistance) {
pointB = patterns[0];
pointA = patterns[1];
pointC = patterns[2];
} else if (zeroTwoDistance >= oneTwoDistance && zeroTwoDistance >= zeroOneDistance) {
pointB = patterns[1];
pointA = patterns[0];
pointC = patterns[2];
} else {
pointB = patterns[2];
pointA = patterns[0];
pointC = patterns[1];
}
// Use cross product to figure out whether A and C are correct or flipped.
// This asks whether BC x BA has a positive z component, which is the arrangement
// we want for A, B, C. If it's negative, then we've got it flipped around and
// should swap A and C.
if (crossProductZ(pointA, pointB, pointC) < 0.0f) {
ResultPoint temp = pointA;
pointA = pointC;
pointC = temp;
}
patterns[0] = pointA;
patterns[1] = pointB;
patterns[2] = pointC;
| 550
| 401
| 951
|
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/aztec/AztecReader.java
|
AztecReader
|
decode
|
class AztecReader implements Reader {
/**
* Locates and decodes a Data Matrix code in an image.
*
* @return a String representing the content encoded by the Data Matrix code
* @throws NotFoundException if a Data Matrix code cannot be found
* @throws FormatException if a Data Matrix code cannot be decoded
*/
@Override
public Result decode(BinaryBitmap image) throws NotFoundException, FormatException {
return decode(image, null);
}
@Override
public Result decode(BinaryBitmap image, Map<DecodeHintType,?> hints)
throws NotFoundException, FormatException {<FILL_FUNCTION_BODY>}
@Override
public void reset() {
// do nothing
}
}
|
NotFoundException notFoundException = null;
FormatException formatException = null;
Detector detector = new Detector(image.getBlackMatrix());
ResultPoint[] points = null;
DecoderResult decoderResult = null;
int errorsCorrected = 0;
try {
AztecDetectorResult detectorResult = detector.detect(false);
points = detectorResult.getPoints();
errorsCorrected = detectorResult.getErrorsCorrected();
decoderResult = new Decoder().decode(detectorResult);
} catch (NotFoundException e) {
notFoundException = e;
} catch (FormatException e) {
formatException = e;
}
if (decoderResult == null) {
try {
AztecDetectorResult detectorResult = detector.detect(true);
points = detectorResult.getPoints();
errorsCorrected = detectorResult.getErrorsCorrected();
decoderResult = new Decoder().decode(detectorResult);
} catch (NotFoundException | FormatException e) {
if (notFoundException != null) {
throw notFoundException;
}
if (formatException != null) {
throw formatException;
}
throw e;
}
}
if (hints != null) {
ResultPointCallback rpcb = (ResultPointCallback) hints.get(DecodeHintType.NEED_RESULT_POINT_CALLBACK);
if (rpcb != null) {
for (ResultPoint point : points) {
rpcb.foundPossibleResultPoint(point);
}
}
}
Result result = new Result(decoderResult.getText(),
decoderResult.getRawBytes(),
decoderResult.getNumBits(),
points,
BarcodeFormat.AZTEC,
System.currentTimeMillis());
List<byte[]> byteSegments = decoderResult.getByteSegments();
if (byteSegments != null) {
result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, byteSegments);
}
String ecLevel = decoderResult.getECLevel();
if (ecLevel != null) {
result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel);
}
errorsCorrected += decoderResult.getErrorsCorrected();
result.putMetadata(ResultMetadataType.ERRORS_CORRECTED, errorsCorrected);
result.putMetadata(ResultMetadataType.SYMBOLOGY_IDENTIFIER, "]z" + decoderResult.getSymbologyModifier());
return result;
| 194
| 662
| 856
|
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/aztec/AztecWriter.java
|
AztecWriter
|
encode
|
class AztecWriter implements Writer {
@Override
public BitMatrix encode(String contents, BarcodeFormat format, int width, int height) {
return encode(contents, format, width, height, null);
}
@Override
public BitMatrix encode(String contents, BarcodeFormat format, int width, int height, Map<EncodeHintType,?> hints) {<FILL_FUNCTION_BODY>}
private static BitMatrix encode(String contents, BarcodeFormat format,
int width, int height,
Charset charset, int eccPercent, int layers) {
if (format != BarcodeFormat.AZTEC) {
throw new IllegalArgumentException("Can only encode AZTEC, but got " + format);
}
AztecCode aztec = Encoder.encode(contents, eccPercent, layers, charset);
return renderResult(aztec, width, height);
}
private static BitMatrix renderResult(AztecCode code, int width, int height) {
BitMatrix input = code.getMatrix();
if (input == null) {
throw new IllegalStateException();
}
int inputWidth = input.getWidth();
int inputHeight = input.getHeight();
int outputWidth = Math.max(width, inputWidth);
int outputHeight = Math.max(height, inputHeight);
int multiple = Math.min(outputWidth / inputWidth, outputHeight / inputHeight);
int leftPadding = (outputWidth - (inputWidth * multiple)) / 2;
int topPadding = (outputHeight - (inputHeight * multiple)) / 2;
BitMatrix output = new BitMatrix(outputWidth, outputHeight);
for (int inputY = 0, outputY = topPadding; inputY < inputHeight; inputY++, outputY += multiple) {
// Write the contents of this row of the barcode
for (int inputX = 0, outputX = leftPadding; inputX < inputWidth; inputX++, outputX += multiple) {
if (input.get(inputX, inputY)) {
output.setRegion(outputX, outputY, multiple, multiple);
}
}
}
return output;
}
}
|
Charset charset = null; // Do not add any ECI code by default
int eccPercent = Encoder.DEFAULT_EC_PERCENT;
int layers = Encoder.DEFAULT_AZTEC_LAYERS;
if (hints != null) {
if (hints.containsKey(EncodeHintType.CHARACTER_SET)) {
charset = Charset.forName(hints.get(EncodeHintType.CHARACTER_SET).toString());
}
if (hints.containsKey(EncodeHintType.ERROR_CORRECTION)) {
eccPercent = Integer.parseInt(hints.get(EncodeHintType.ERROR_CORRECTION).toString());
}
if (hints.containsKey(EncodeHintType.AZTEC_LAYERS)) {
layers = Integer.parseInt(hints.get(EncodeHintType.AZTEC_LAYERS).toString());
}
}
return encode(contents, format, width, height, charset, eccPercent, layers);
| 554
| 266
| 820
|
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/aztec/encoder/BinaryShiftToken.java
|
BinaryShiftToken
|
toString
|
class BinaryShiftToken extends Token {
private final int binaryShiftStart;
private final int binaryShiftByteCount;
BinaryShiftToken(Token previous,
int binaryShiftStart,
int binaryShiftByteCount) {
super(previous);
this.binaryShiftStart = binaryShiftStart;
this.binaryShiftByteCount = binaryShiftByteCount;
}
@Override
public void appendTo(BitArray bitArray, byte[] text) {
int bsbc = binaryShiftByteCount;
for (int i = 0; i < bsbc; i++) {
if (i == 0 || (i == 31 && bsbc <= 62)) {
// We need a header before the first character, and before
// character 31 when the total byte code is <= 62
bitArray.appendBits(31, 5); // BINARY_SHIFT
if (bsbc > 62) {
bitArray.appendBits(bsbc - 31, 16);
} else if (i == 0) {
// 1 <= binaryShiftByteCode <= 62
bitArray.appendBits(Math.min(bsbc, 31), 5);
} else {
// 32 <= binaryShiftCount <= 62 and i == 31
bitArray.appendBits(bsbc - 31, 5);
}
}
bitArray.appendBits(text[binaryShiftStart + i], 8);
}
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "<" + binaryShiftStart + "::" + (binaryShiftStart + binaryShiftByteCount - 1) + '>';
| 401
| 35
| 436
|
<methods><variables>static final com.google.zxing.aztec.encoder.Token EMPTY,private final non-sealed com.google.zxing.aztec.encoder.Token previous
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/aztec/encoder/SimpleToken.java
|
SimpleToken
|
toString
|
class SimpleToken extends Token {
// For normal words, indicates value and bitCount
private final short value;
private final short bitCount;
SimpleToken(Token previous, int value, int bitCount) {
super(previous);
this.value = (short) value;
this.bitCount = (short) bitCount;
}
@Override
void appendTo(BitArray bitArray, byte[] text) {
bitArray.appendBits(value, bitCount);
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
int value = this.value & ((1 << bitCount) - 1);
value |= 1 << bitCount;
return '<' + Integer.toBinaryString(value | (1 << bitCount)).substring(1) + '>';
| 152
| 62
| 214
|
<methods><variables>static final com.google.zxing.aztec.encoder.Token EMPTY,private final non-sealed com.google.zxing.aztec.encoder.Token previous
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/aztec/encoder/State.java
|
State
|
toBitArray
|
class State {
static final State INITIAL_STATE = new State(Token.EMPTY, HighLevelEncoder.MODE_UPPER, 0, 0);
// The current mode of the encoding (or the mode to which we'll return if
// we're in Binary Shift mode.
private final int mode;
// The list of tokens that we output. If we are in Binary Shift mode, this
// token list does *not* yet included the token for those bytes
private final Token token;
// If non-zero, the number of most recent bytes that should be output
// in Binary Shift mode.
private final int binaryShiftByteCount;
// The total number of bits generated (including Binary Shift).
private final int bitCount;
private final int binaryShiftCost;
private State(Token token, int mode, int binaryBytes, int bitCount) {
this.token = token;
this.mode = mode;
this.binaryShiftByteCount = binaryBytes;
this.bitCount = bitCount;
this.binaryShiftCost = calculateBinaryShiftCost(binaryBytes);
}
int getMode() {
return mode;
}
Token getToken() {
return token;
}
int getBinaryShiftByteCount() {
return binaryShiftByteCount;
}
int getBitCount() {
return bitCount;
}
State appendFLGn(int eci) {
State result = shiftAndAppend(HighLevelEncoder.MODE_PUNCT, 0); // 0: FLG(n)
Token token = result.token;
int bitsAdded = 3;
if (eci < 0) {
token = token.add(0, 3); // 0: FNC1
} else if (eci > 999999) {
throw new IllegalArgumentException("ECI code must be between 0 and 999999");
} else {
byte[] eciDigits = Integer.toString(eci).getBytes(StandardCharsets.ISO_8859_1);
token = token.add(eciDigits.length, 3); // 1-6: number of ECI digits
for (byte eciDigit : eciDigits) {
token = token.add(eciDigit - '0' + 2, 4);
}
bitsAdded += eciDigits.length * 4;
}
return new State(token, mode, 0, bitCount + bitsAdded);
}
// Create a new state representing this state with a latch to a (not
// necessary different) mode, and then a code.
State latchAndAppend(int mode, int value) {
int bitCount = this.bitCount;
Token token = this.token;
if (mode != this.mode) {
int latch = HighLevelEncoder.LATCH_TABLE[this.mode][mode];
token = token.add(latch & 0xFFFF, latch >> 16);
bitCount += latch >> 16;
}
int latchModeBitCount = mode == HighLevelEncoder.MODE_DIGIT ? 4 : 5;
token = token.add(value, latchModeBitCount);
return new State(token, mode, 0, bitCount + latchModeBitCount);
}
// Create a new state representing this state, with a temporary shift
// to a different mode to output a single value.
State shiftAndAppend(int mode, int value) {
Token token = this.token;
int thisModeBitCount = this.mode == HighLevelEncoder.MODE_DIGIT ? 4 : 5;
// Shifts exist only to UPPER and PUNCT, both with tokens size 5.
token = token.add(HighLevelEncoder.SHIFT_TABLE[this.mode][mode], thisModeBitCount);
token = token.add(value, 5);
return new State(token, this.mode, 0, this.bitCount + thisModeBitCount + 5);
}
// Create a new state representing this state, but an additional character
// output in Binary Shift mode.
State addBinaryShiftChar(int index) {
Token token = this.token;
int mode = this.mode;
int bitCount = this.bitCount;
if (this.mode == HighLevelEncoder.MODE_PUNCT || this.mode == HighLevelEncoder.MODE_DIGIT) {
int latch = HighLevelEncoder.LATCH_TABLE[mode][HighLevelEncoder.MODE_UPPER];
token = token.add(latch & 0xFFFF, latch >> 16);
bitCount += latch >> 16;
mode = HighLevelEncoder.MODE_UPPER;
}
int deltaBitCount =
(binaryShiftByteCount == 0 || binaryShiftByteCount == 31) ? 18 :
(binaryShiftByteCount == 62) ? 9 : 8;
State result = new State(token, mode, binaryShiftByteCount + 1, bitCount + deltaBitCount);
if (result.binaryShiftByteCount == 2047 + 31) {
// The string is as long as it's allowed to be. We should end it.
result = result.endBinaryShift(index + 1);
}
return result;
}
// Create the state identical to this one, but we are no longer in
// Binary Shift mode.
State endBinaryShift(int index) {
if (binaryShiftByteCount == 0) {
return this;
}
Token token = this.token;
token = token.addBinaryShift(index - binaryShiftByteCount, binaryShiftByteCount);
return new State(token, mode, 0, this.bitCount);
}
// Returns true if "this" state is better (or equal) to be in than "that"
// state under all possible circumstances.
boolean isBetterThanOrEqualTo(State other) {
int newModeBitCount = this.bitCount + (HighLevelEncoder.LATCH_TABLE[this.mode][other.mode] >> 16);
if (this.binaryShiftByteCount < other.binaryShiftByteCount) {
// add additional B/S encoding cost of other, if any
newModeBitCount += other.binaryShiftCost - this.binaryShiftCost;
} else if (this.binaryShiftByteCount > other.binaryShiftByteCount && other.binaryShiftByteCount > 0) {
// maximum possible additional cost (we end up exceeding the 31 byte boundary and other state can stay beneath it)
newModeBitCount += 10;
}
return newModeBitCount <= other.bitCount;
}
BitArray toBitArray(byte[] text) {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return String.format("%s bits=%d bytes=%d", HighLevelEncoder.MODE_NAMES[mode], bitCount, binaryShiftByteCount);
}
private static int calculateBinaryShiftCost(int binaryShiftByteCount) {
if (binaryShiftByteCount > 62) {
return 21; // B/S with extended length
}
if (binaryShiftByteCount > 31) {
return 20; // two B/S
}
if (binaryShiftByteCount > 0) {
return 10; // one B/S
}
return 0;
}
}
|
List<Token> symbols = new ArrayList<>();
for (Token token = endBinaryShift(text.length).token; token != null; token = token.getPrevious()) {
symbols.add(token);
}
BitArray bitArray = new BitArray();
// Add each token to the result in forward order
for (int i = symbols.size() - 1; i >= 0; i--) {
symbols.get(i).appendTo(bitArray, text);
}
return bitArray;
| 1,876
| 127
| 2,003
|
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/aztec/encoder/Token.java
|
Token
|
addBinaryShift
|
class Token {
static final Token EMPTY = new SimpleToken(null, 0, 0);
private final Token previous;
Token(Token previous) {
this.previous = previous;
}
final Token getPrevious() {
return previous;
}
final Token add(int value, int bitCount) {
return new SimpleToken(this, value, bitCount);
}
final Token addBinaryShift(int start, int byteCount) {<FILL_FUNCTION_BODY>}
abstract void appendTo(BitArray bitArray, byte[] text);
}
|
//int bitCount = (byteCount * 8) + (byteCount <= 31 ? 10 : byteCount <= 62 ? 20 : 21);
return new BinaryShiftToken(this, start, byteCount);
| 159
| 59
| 218
|
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/client/result/AddressBookAUResultParser.java
|
AddressBookAUResultParser
|
parse
|
class AddressBookAUResultParser extends ResultParser {
@Override
public AddressBookParsedResult parse(Result result) {<FILL_FUNCTION_BODY>}
private static String[] matchMultipleValuePrefix(String prefix, String rawText) {
List<String> values = null;
// For now, always 3, and always trim
for (int i = 1; i <= 3; i++) {
String value = matchSinglePrefixedField(prefix + i + ':', rawText, '\r', true);
if (value == null) {
break;
}
if (values == null) {
values = new ArrayList<>(3); // lazy init
}
values.add(value);
}
if (values == null) {
return null;
}
return values.toArray(EMPTY_STR_ARRAY);
}
}
|
String rawText = getMassagedText(result);
// MEMORY is mandatory; seems like a decent indicator, as does end-of-record separator CR/LF
if (!rawText.contains("MEMORY") || !rawText.contains("\r\n")) {
return null;
}
// NAME1 and NAME2 have specific uses, namely written name and pronunciation, respectively.
// Therefore we treat them specially instead of as an array of names.
String name = matchSinglePrefixedField("NAME1:", rawText, '\r', true);
String pronunciation = matchSinglePrefixedField("NAME2:", rawText, '\r', true);
String[] phoneNumbers = matchMultipleValuePrefix("TEL", rawText);
String[] emails = matchMultipleValuePrefix("MAIL", rawText);
String note = matchSinglePrefixedField("MEMORY:", rawText, '\r', false);
String address = matchSinglePrefixedField("ADD:", rawText, '\r', true);
String[] addresses = address == null ? null : new String[] {address};
return new AddressBookParsedResult(maybeWrap(name),
null,
pronunciation,
phoneNumbers,
null,
emails,
null,
null,
note,
addresses,
null,
null,
null,
null,
null,
null);
| 221
| 342
| 563
|
<methods>public non-sealed void <init>() ,public abstract com.google.zxing.client.result.ParsedResult parse(com.google.zxing.Result) ,public static com.google.zxing.client.result.ParsedResult parseResult(com.google.zxing.Result) <variables>private static final java.util.regex.Pattern AMPERSAND,private static final java.lang.String BYTE_ORDER_MARK,private static final java.util.regex.Pattern DIGITS,static final java.lang.String[] EMPTY_STR_ARRAY,private static final java.util.regex.Pattern EQUALS,private static final com.google.zxing.client.result.ResultParser[] PARSERS
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/client/result/AddressBookDoCoMoResultParser.java
|
AddressBookDoCoMoResultParser
|
parse
|
class AddressBookDoCoMoResultParser extends AbstractDoCoMoResultParser {
@Override
public AddressBookParsedResult parse(Result result) {<FILL_FUNCTION_BODY>}
private static String parseName(String name) {
int comma = name.indexOf(',');
if (comma >= 0) {
// Format may be last,first; switch it around
return name.substring(comma + 1) + ' ' + name.substring(0, comma);
}
return name;
}
}
|
String rawText = getMassagedText(result);
if (!rawText.startsWith("MECARD:")) {
return null;
}
String[] rawName = matchDoCoMoPrefixedField("N:", rawText);
if (rawName == null) {
return null;
}
String name = parseName(rawName[0]);
String pronunciation = matchSingleDoCoMoPrefixedField("SOUND:", rawText, true);
String[] phoneNumbers = matchDoCoMoPrefixedField("TEL:", rawText);
String[] emails = matchDoCoMoPrefixedField("EMAIL:", rawText);
String note = matchSingleDoCoMoPrefixedField("NOTE:", rawText, false);
String[] addresses = matchDoCoMoPrefixedField("ADR:", rawText);
String birthday = matchSingleDoCoMoPrefixedField("BDAY:", rawText, true);
if (!isStringOfDigits(birthday, 8)) {
// No reason to throw out the whole card because the birthday is formatted wrong.
birthday = null;
}
String[] urls = matchDoCoMoPrefixedField("URL:", rawText);
// Although ORG may not be strictly legal in MECARD, it does exist in VCARD and we might as well
// honor it when found in the wild.
String org = matchSingleDoCoMoPrefixedField("ORG:", rawText, true);
return new AddressBookParsedResult(maybeWrap(name),
null,
pronunciation,
phoneNumbers,
null,
emails,
null,
null,
note,
addresses,
null,
org,
birthday,
null,
urls,
null);
| 136
| 439
| 575
|
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/client/result/AddressBookParsedResult.java
|
AddressBookParsedResult
|
getDisplayResult
|
class AddressBookParsedResult extends ParsedResult {
private final String[] names;
private final String[] nicknames;
private final String pronunciation;
private final String[] phoneNumbers;
private final String[] phoneTypes;
private final String[] emails;
private final String[] emailTypes;
private final String instantMessenger;
private final String note;
private final String[] addresses;
private final String[] addressTypes;
private final String org;
private final String birthday;
private final String title;
private final String[] urls;
private final String[] geo;
public AddressBookParsedResult(String[] names,
String[] phoneNumbers,
String[] phoneTypes,
String[] emails,
String[] emailTypes,
String[] addresses,
String[] addressTypes) {
this(names,
null,
null,
phoneNumbers,
phoneTypes,
emails,
emailTypes,
null,
null,
addresses,
addressTypes,
null,
null,
null,
null,
null);
}
public AddressBookParsedResult(String[] names,
String[] nicknames,
String pronunciation,
String[] phoneNumbers,
String[] phoneTypes,
String[] emails,
String[] emailTypes,
String instantMessenger,
String note,
String[] addresses,
String[] addressTypes,
String org,
String birthday,
String title,
String[] urls,
String[] geo) {
super(ParsedResultType.ADDRESSBOOK);
if (phoneNumbers != null && phoneTypes != null && phoneNumbers.length != phoneTypes.length) {
throw new IllegalArgumentException("Phone numbers and types lengths differ");
}
if (emails != null && emailTypes != null && emails.length != emailTypes.length) {
throw new IllegalArgumentException("Emails and types lengths differ");
}
if (addresses != null && addressTypes != null && addresses.length != addressTypes.length) {
throw new IllegalArgumentException("Addresses and types lengths differ");
}
this.names = names;
this.nicknames = nicknames;
this.pronunciation = pronunciation;
this.phoneNumbers = phoneNumbers;
this.phoneTypes = phoneTypes;
this.emails = emails;
this.emailTypes = emailTypes;
this.instantMessenger = instantMessenger;
this.note = note;
this.addresses = addresses;
this.addressTypes = addressTypes;
this.org = org;
this.birthday = birthday;
this.title = title;
this.urls = urls;
this.geo = geo;
}
public String[] getNames() {
return names;
}
public String[] getNicknames() {
return nicknames;
}
/**
* In Japanese, the name is written in kanji, which can have multiple readings. Therefore a hint
* is often provided, called furigana, which spells the name phonetically.
*
* @return The pronunciation of the getNames() field, often in hiragana or katakana.
*/
public String getPronunciation() {
return pronunciation;
}
public String[] getPhoneNumbers() {
return phoneNumbers;
}
/**
* @return optional descriptions of the type of each phone number. It could be like "HOME", but,
* there is no guaranteed or standard format.
*/
public String[] getPhoneTypes() {
return phoneTypes;
}
public String[] getEmails() {
return emails;
}
/**
* @return optional descriptions of the type of each e-mail. It could be like "WORK", but,
* there is no guaranteed or standard format.
*/
public String[] getEmailTypes() {
return emailTypes;
}
public String getInstantMessenger() {
return instantMessenger;
}
public String getNote() {
return note;
}
public String[] getAddresses() {
return addresses;
}
/**
* @return optional descriptions of the type of each e-mail. It could be like "WORK", but,
* there is no guaranteed or standard format.
*/
public String[] getAddressTypes() {
return addressTypes;
}
public String getTitle() {
return title;
}
public String getOrg() {
return org;
}
public String[] getURLs() {
return urls;
}
/**
* @return birthday formatted as yyyyMMdd (e.g. 19780917)
*/
public String getBirthday() {
return birthday;
}
/**
* @return a location as a latitude/longitude pair
*/
public String[] getGeo() {
return geo;
}
@Override
public String getDisplayResult() {<FILL_FUNCTION_BODY>}
}
|
StringBuilder result = new StringBuilder(100);
maybeAppend(names, result);
maybeAppend(nicknames, result);
maybeAppend(pronunciation, result);
maybeAppend(title, result);
maybeAppend(org, result);
maybeAppend(addresses, result);
maybeAppend(phoneNumbers, result);
maybeAppend(emails, result);
maybeAppend(instantMessenger, result);
maybeAppend(urls, result);
maybeAppend(birthday, result);
maybeAppend(geo, result);
maybeAppend(note, result);
return result.toString();
| 1,314
| 156
| 1,470
|
<methods>public abstract java.lang.String getDisplayResult() ,public final com.google.zxing.client.result.ParsedResultType getType() ,public static void maybeAppend(java.lang.String, java.lang.StringBuilder) ,public static void maybeAppend(java.lang.String[], java.lang.StringBuilder) ,public final java.lang.String toString() <variables>private final non-sealed com.google.zxing.client.result.ParsedResultType type
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/client/result/BizcardResultParser.java
|
BizcardResultParser
|
buildPhoneNumbers
|
class BizcardResultParser extends AbstractDoCoMoResultParser {
// Yes, we extend AbstractDoCoMoResultParser since the format is very much
// like the DoCoMo MECARD format, but this is not technically one of
// DoCoMo's proposed formats
@Override
public AddressBookParsedResult parse(Result result) {
String rawText = getMassagedText(result);
if (!rawText.startsWith("BIZCARD:")) {
return null;
}
String firstName = matchSingleDoCoMoPrefixedField("N:", rawText, true);
String lastName = matchSingleDoCoMoPrefixedField("X:", rawText, true);
String fullName = buildName(firstName, lastName);
String title = matchSingleDoCoMoPrefixedField("T:", rawText, true);
String org = matchSingleDoCoMoPrefixedField("C:", rawText, true);
String[] addresses = matchDoCoMoPrefixedField("A:", rawText);
String phoneNumber1 = matchSingleDoCoMoPrefixedField("B:", rawText, true);
String phoneNumber2 = matchSingleDoCoMoPrefixedField("M:", rawText, true);
String phoneNumber3 = matchSingleDoCoMoPrefixedField("F:", rawText, true);
String email = matchSingleDoCoMoPrefixedField("E:", rawText, true);
return new AddressBookParsedResult(maybeWrap(fullName),
null,
null,
buildPhoneNumbers(phoneNumber1, phoneNumber2, phoneNumber3),
null,
maybeWrap(email),
null,
null,
null,
addresses,
null,
org,
null,
title,
null,
null);
}
private static String[] buildPhoneNumbers(String number1,
String number2,
String number3) {<FILL_FUNCTION_BODY>}
private static String buildName(String firstName, String lastName) {
if (firstName == null) {
return lastName;
} else {
return lastName == null ? firstName : firstName + ' ' + lastName;
}
}
}
|
List<String> numbers = new ArrayList<>(3);
if (number1 != null) {
numbers.add(number1);
}
if (number2 != null) {
numbers.add(number2);
}
if (number3 != null) {
numbers.add(number3);
}
int size = numbers.size();
if (size == 0) {
return null;
}
return numbers.toArray(new String[size]);
| 551
| 125
| 676
|
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/client/result/BookmarkDoCoMoResultParser.java
|
BookmarkDoCoMoResultParser
|
parse
|
class BookmarkDoCoMoResultParser extends AbstractDoCoMoResultParser {
@Override
public URIParsedResult parse(Result result) {<FILL_FUNCTION_BODY>}
}
|
String rawText = result.getText();
if (!rawText.startsWith("MEBKM:")) {
return null;
}
String title = matchSingleDoCoMoPrefixedField("TITLE:", rawText, true);
String[] rawUri = matchDoCoMoPrefixedField("URL:", rawText);
if (rawUri == null) {
return null;
}
String uri = rawUri[0];
return URIResultParser.isBasicallyValidURI(uri) ? new URIParsedResult(uri, title) : null;
| 52
| 143
| 195
|
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/client/result/EmailAddressParsedResult.java
|
EmailAddressParsedResult
|
getDisplayResult
|
class EmailAddressParsedResult extends ParsedResult {
private final String[] tos;
private final String[] ccs;
private final String[] bccs;
private final String subject;
private final String body;
EmailAddressParsedResult(String to) {
this(new String[] {to}, null, null, null, null);
}
EmailAddressParsedResult(String[] tos,
String[] ccs,
String[] bccs,
String subject,
String body) {
super(ParsedResultType.EMAIL_ADDRESS);
this.tos = tos;
this.ccs = ccs;
this.bccs = bccs;
this.subject = subject;
this.body = body;
}
/**
* @return first elements of {@link #getTos()} or {@code null} if none
* @deprecated use {@link #getTos()}
*/
@Deprecated
public String getEmailAddress() {
return tos == null || tos.length == 0 ? null : tos[0];
}
public String[] getTos() {
return tos;
}
public String[] getCCs() {
return ccs;
}
public String[] getBCCs() {
return bccs;
}
public String getSubject() {
return subject;
}
public String getBody() {
return body;
}
/**
* @return "mailto:"
* @deprecated without replacement
*/
@Deprecated
public String getMailtoURI() {
return "mailto:";
}
@Override
public String getDisplayResult() {<FILL_FUNCTION_BODY>}
}
|
StringBuilder result = new StringBuilder(30);
maybeAppend(tos, result);
maybeAppend(ccs, result);
maybeAppend(bccs, result);
maybeAppend(subject, result);
maybeAppend(body, result);
return result.toString();
| 458
| 72
| 530
|
<methods>public abstract java.lang.String getDisplayResult() ,public final com.google.zxing.client.result.ParsedResultType getType() ,public static void maybeAppend(java.lang.String, java.lang.StringBuilder) ,public static void maybeAppend(java.lang.String[], java.lang.StringBuilder) ,public final java.lang.String toString() <variables>private final non-sealed com.google.zxing.client.result.ParsedResultType type
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/client/result/EmailAddressResultParser.java
|
EmailAddressResultParser
|
parse
|
class EmailAddressResultParser extends ResultParser {
private static final Pattern COMMA = Pattern.compile(",");
@Override
public EmailAddressParsedResult parse(Result result) {<FILL_FUNCTION_BODY>}
}
|
String rawText = getMassagedText(result);
if (rawText.startsWith("mailto:") || rawText.startsWith("MAILTO:")) {
// If it starts with mailto:, assume it is definitely trying to be an email address
String hostEmail = rawText.substring(7);
int queryStart = hostEmail.indexOf('?');
if (queryStart >= 0) {
hostEmail = hostEmail.substring(0, queryStart);
}
try {
hostEmail = urlDecode(hostEmail);
} catch (IllegalArgumentException iae) {
return null;
}
String[] tos = null;
if (!hostEmail.isEmpty()) {
tos = COMMA.split(hostEmail);
}
Map<String,String> nameValues = parseNameValuePairs(rawText);
String[] ccs = null;
String[] bccs = null;
String subject = null;
String body = null;
if (nameValues != null) {
if (tos == null) {
String tosString = nameValues.get("to");
if (tosString != null) {
tos = COMMA.split(tosString);
}
}
String ccString = nameValues.get("cc");
if (ccString != null) {
ccs = COMMA.split(ccString);
}
String bccString = nameValues.get("bcc");
if (bccString != null) {
bccs = COMMA.split(bccString);
}
subject = nameValues.get("subject");
body = nameValues.get("body");
}
return new EmailAddressParsedResult(tos, ccs, bccs, subject, body);
} else {
if (!EmailDoCoMoResultParser.isBasicallyValidEmailAddress(rawText)) {
return null;
}
return new EmailAddressParsedResult(rawText);
}
| 63
| 500
| 563
|
<methods>public non-sealed void <init>() ,public abstract com.google.zxing.client.result.ParsedResult parse(com.google.zxing.Result) ,public static com.google.zxing.client.result.ParsedResult parseResult(com.google.zxing.Result) <variables>private static final java.util.regex.Pattern AMPERSAND,private static final java.lang.String BYTE_ORDER_MARK,private static final java.util.regex.Pattern DIGITS,static final java.lang.String[] EMPTY_STR_ARRAY,private static final java.util.regex.Pattern EQUALS,private static final com.google.zxing.client.result.ResultParser[] PARSERS
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/client/result/EmailDoCoMoResultParser.java
|
EmailDoCoMoResultParser
|
isBasicallyValidEmailAddress
|
class EmailDoCoMoResultParser extends AbstractDoCoMoResultParser {
private static final Pattern ATEXT_ALPHANUMERIC = Pattern.compile("[a-zA-Z0-9@.!#$%&'*+\\-/=?^_`{|}~]+");
@Override
public EmailAddressParsedResult parse(Result result) {
String rawText = getMassagedText(result);
if (!rawText.startsWith("MATMSG:")) {
return null;
}
String[] tos = matchDoCoMoPrefixedField("TO:", rawText);
if (tos == null) {
return null;
}
for (String to : tos) {
if (!isBasicallyValidEmailAddress(to)) {
return null;
}
}
String subject = matchSingleDoCoMoPrefixedField("SUB:", rawText, false);
String body = matchSingleDoCoMoPrefixedField("BODY:", rawText, false);
return new EmailAddressParsedResult(tos, null, null, subject, body);
}
/**
* This implements only the most basic checking for an email address's validity -- that it contains
* an '@' and contains no characters disallowed by RFC 2822. This is an overly lenient definition of
* validity. We want to generally be lenient here since this class is only intended to encapsulate what's
* in a barcode, not "judge" it.
*/
static boolean isBasicallyValidEmailAddress(String email) {<FILL_FUNCTION_BODY>}
}
|
return email != null && ATEXT_ALPHANUMERIC.matcher(email).matches() && email.indexOf('@') >= 0;
| 410
| 39
| 449
|
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/client/result/ExpandedProductParsedResult.java
|
ExpandedProductParsedResult
|
equals
|
class ExpandedProductParsedResult extends ParsedResult {
public static final String KILOGRAM = "KG";
public static final String POUND = "LB";
private final String rawText;
private final String productID;
private final String sscc;
private final String lotNumber;
private final String productionDate;
private final String packagingDate;
private final String bestBeforeDate;
private final String expirationDate;
private final String weight;
private final String weightType;
private final String weightIncrement;
private final String price;
private final String priceIncrement;
private final String priceCurrency;
// For AIS that not exist in this object
private final Map<String,String> uncommonAIs;
public ExpandedProductParsedResult(String rawText,
String productID,
String sscc,
String lotNumber,
String productionDate,
String packagingDate,
String bestBeforeDate,
String expirationDate,
String weight,
String weightType,
String weightIncrement,
String price,
String priceIncrement,
String priceCurrency,
Map<String,String> uncommonAIs) {
super(ParsedResultType.PRODUCT);
this.rawText = rawText;
this.productID = productID;
this.sscc = sscc;
this.lotNumber = lotNumber;
this.productionDate = productionDate;
this.packagingDate = packagingDate;
this.bestBeforeDate = bestBeforeDate;
this.expirationDate = expirationDate;
this.weight = weight;
this.weightType = weightType;
this.weightIncrement = weightIncrement;
this.price = price;
this.priceIncrement = priceIncrement;
this.priceCurrency = priceCurrency;
this.uncommonAIs = uncommonAIs;
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
int hash = Objects.hashCode(productID);
hash ^= Objects.hashCode(sscc);
hash ^= Objects.hashCode(lotNumber);
hash ^= Objects.hashCode(productionDate);
hash ^= Objects.hashCode(bestBeforeDate);
hash ^= Objects.hashCode(expirationDate);
hash ^= Objects.hashCode(weight);
hash ^= Objects.hashCode(weightType);
hash ^= Objects.hashCode(weightIncrement);
hash ^= Objects.hashCode(price);
hash ^= Objects.hashCode(priceIncrement);
hash ^= Objects.hashCode(priceCurrency);
hash ^= Objects.hashCode(uncommonAIs);
return hash;
}
public String getRawText() {
return rawText;
}
public String getProductID() {
return productID;
}
public String getSscc() {
return sscc;
}
public String getLotNumber() {
return lotNumber;
}
public String getProductionDate() {
return productionDate;
}
public String getPackagingDate() {
return packagingDate;
}
public String getBestBeforeDate() {
return bestBeforeDate;
}
public String getExpirationDate() {
return expirationDate;
}
public String getWeight() {
return weight;
}
public String getWeightType() {
return weightType;
}
public String getWeightIncrement() {
return weightIncrement;
}
public String getPrice() {
return price;
}
public String getPriceIncrement() {
return priceIncrement;
}
public String getPriceCurrency() {
return priceCurrency;
}
public Map<String,String> getUncommonAIs() {
return uncommonAIs;
}
@Override
public String getDisplayResult() {
return String.valueOf(rawText);
}
}
|
if (!(o instanceof ExpandedProductParsedResult)) {
return false;
}
ExpandedProductParsedResult other = (ExpandedProductParsedResult) o;
return Objects.equals(productID, other.productID)
&& Objects.equals(sscc, other.sscc)
&& Objects.equals(lotNumber, other.lotNumber)
&& Objects.equals(productionDate, other.productionDate)
&& Objects.equals(bestBeforeDate, other.bestBeforeDate)
&& Objects.equals(expirationDate, other.expirationDate)
&& Objects.equals(weight, other.weight)
&& Objects.equals(weightType, other.weightType)
&& Objects.equals(weightIncrement, other.weightIncrement)
&& Objects.equals(price, other.price)
&& Objects.equals(priceIncrement, other.priceIncrement)
&& Objects.equals(priceCurrency, other.priceCurrency)
&& Objects.equals(uncommonAIs, other.uncommonAIs);
| 1,061
| 273
| 1,334
|
<methods>public abstract java.lang.String getDisplayResult() ,public final com.google.zxing.client.result.ParsedResultType getType() ,public static void maybeAppend(java.lang.String, java.lang.StringBuilder) ,public static void maybeAppend(java.lang.String[], java.lang.StringBuilder) ,public final java.lang.String toString() <variables>private final non-sealed com.google.zxing.client.result.ParsedResultType type
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/client/result/ExpandedProductResultParser.java
|
ExpandedProductResultParser
|
parse
|
class ExpandedProductResultParser extends ResultParser {
@Override
public ExpandedProductParsedResult parse(Result result) {<FILL_FUNCTION_BODY>}
private static String findAIvalue(int i, String rawText) {
char c = rawText.charAt(i);
// First character must be a open parenthesis.If not, ERROR
if (c != '(') {
return null;
}
CharSequence rawTextAux = rawText.substring(i + 1);
StringBuilder buf = new StringBuilder();
for (int index = 0; index < rawTextAux.length(); index++) {
char currentChar = rawTextAux.charAt(index);
if (currentChar == ')') {
return buf.toString();
}
if (currentChar < '0' || currentChar > '9') {
return null;
}
buf.append(currentChar);
}
return buf.toString();
}
private static String findValue(int i, String rawText) {
StringBuilder buf = new StringBuilder();
String rawTextAux = rawText.substring(i);
for (int index = 0; index < rawTextAux.length(); index++) {
char c = rawTextAux.charAt(index);
if (c == '(') {
// We look for a new AI. If it doesn't exist (ERROR), we continue
// with the iteration
if (findAIvalue(index, rawTextAux) != null) {
break;
}
buf.append('(');
} else {
buf.append(c);
}
}
return buf.toString();
}
}
|
BarcodeFormat format = result.getBarcodeFormat();
if (format != BarcodeFormat.RSS_EXPANDED) {
// ExtendedProductParsedResult NOT created. Not a RSS Expanded barcode
return null;
}
String rawText = getMassagedText(result);
String productID = null;
String sscc = null;
String lotNumber = null;
String productionDate = null;
String packagingDate = null;
String bestBeforeDate = null;
String expirationDate = null;
String weight = null;
String weightType = null;
String weightIncrement = null;
String price = null;
String priceIncrement = null;
String priceCurrency = null;
Map<String,String> uncommonAIs = new HashMap<>();
int i = 0;
while (i < rawText.length()) {
String ai = findAIvalue(i, rawText);
if (ai == null) {
// Error. Code doesn't match with RSS expanded pattern
// ExtendedProductParsedResult NOT created. Not match with RSS Expanded pattern
return null;
}
i += ai.length() + 2;
String value = findValue(i, rawText);
i += value.length();
switch (ai) {
case "00":
sscc = value;
break;
case "01":
productID = value;
break;
case "10":
lotNumber = value;
break;
case "11":
productionDate = value;
break;
case "13":
packagingDate = value;
break;
case "15":
bestBeforeDate = value;
break;
case "17":
expirationDate = value;
break;
case "3100":
case "3101":
case "3102":
case "3103":
case "3104":
case "3105":
case "3106":
case "3107":
case "3108":
case "3109":
weight = value;
weightType = ExpandedProductParsedResult.KILOGRAM;
weightIncrement = ai.substring(3);
break;
case "3200":
case "3201":
case "3202":
case "3203":
case "3204":
case "3205":
case "3206":
case "3207":
case "3208":
case "3209":
weight = value;
weightType = ExpandedProductParsedResult.POUND;
weightIncrement = ai.substring(3);
break;
case "3920":
case "3921":
case "3922":
case "3923":
price = value;
priceIncrement = ai.substring(3);
break;
case "3930":
case "3931":
case "3932":
case "3933":
if (value.length() < 4) {
// The value must have more of 3 symbols (3 for currency and
// 1 at least for the price)
// ExtendedProductParsedResult NOT created. Not match with RSS Expanded pattern
return null;
}
price = value.substring(3);
priceCurrency = value.substring(0, 3);
priceIncrement = ai.substring(3);
break;
default:
// No match with common AIs
uncommonAIs.put(ai, value);
break;
}
}
return new ExpandedProductParsedResult(rawText,
productID,
sscc,
lotNumber,
productionDate,
packagingDate,
bestBeforeDate,
expirationDate,
weight,
weightType,
weightIncrement,
price,
priceIncrement,
priceCurrency,
uncommonAIs);
| 432
| 1,089
| 1,521
|
<methods>public non-sealed void <init>() ,public abstract com.google.zxing.client.result.ParsedResult parse(com.google.zxing.Result) ,public static com.google.zxing.client.result.ParsedResult parseResult(com.google.zxing.Result) <variables>private static final java.util.regex.Pattern AMPERSAND,private static final java.lang.String BYTE_ORDER_MARK,private static final java.util.regex.Pattern DIGITS,static final java.lang.String[] EMPTY_STR_ARRAY,private static final java.util.regex.Pattern EQUALS,private static final com.google.zxing.client.result.ResultParser[] PARSERS
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/client/result/GeoParsedResult.java
|
GeoParsedResult
|
getDisplayResult
|
class GeoParsedResult extends ParsedResult {
private final double latitude;
private final double longitude;
private final double altitude;
private final String query;
GeoParsedResult(double latitude, double longitude, double altitude, String query) {
super(ParsedResultType.GEO);
this.latitude = latitude;
this.longitude = longitude;
this.altitude = altitude;
this.query = query;
}
public String getGeoURI() {
StringBuilder result = new StringBuilder();
result.append("geo:");
result.append(latitude);
result.append(',');
result.append(longitude);
if (altitude > 0) {
result.append(',');
result.append(altitude);
}
if (query != null) {
result.append('?');
result.append(query);
}
return result.toString();
}
/**
* @return latitude in degrees
*/
public double getLatitude() {
return latitude;
}
/**
* @return longitude in degrees
*/
public double getLongitude() {
return longitude;
}
/**
* @return altitude in meters. If not specified, in the geo URI, returns 0.0
*/
public double getAltitude() {
return altitude;
}
/**
* @return query string associated with geo URI or null if none exists
*/
public String getQuery() {
return query;
}
@Override
public String getDisplayResult() {<FILL_FUNCTION_BODY>}
}
|
StringBuilder result = new StringBuilder(20);
result.append(latitude);
result.append(", ");
result.append(longitude);
if (altitude > 0.0) {
result.append(", ");
result.append(altitude);
result.append('m');
}
if (query != null) {
result.append(" (");
result.append(query);
result.append(')');
}
return result.toString();
| 436
| 126
| 562
|
<methods>public abstract java.lang.String getDisplayResult() ,public final com.google.zxing.client.result.ParsedResultType getType() ,public static void maybeAppend(java.lang.String, java.lang.StringBuilder) ,public static void maybeAppend(java.lang.String[], java.lang.StringBuilder) ,public final java.lang.String toString() <variables>private final non-sealed com.google.zxing.client.result.ParsedResultType type
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/client/result/GeoResultParser.java
|
GeoResultParser
|
parse
|
class GeoResultParser extends ResultParser {
private static final Pattern GEO_URL_PATTERN =
Pattern.compile("geo:([\\-0-9.]+),([\\-0-9.]+)(?:,([\\-0-9.]+))?(?:\\?(.*))?", Pattern.CASE_INSENSITIVE);
@Override
public GeoParsedResult parse(Result result) {<FILL_FUNCTION_BODY>}
}
|
CharSequence rawText = getMassagedText(result);
Matcher matcher = GEO_URL_PATTERN.matcher(rawText);
if (!matcher.matches()) {
return null;
}
String query = matcher.group(4);
double latitude;
double longitude;
double altitude;
try {
latitude = Double.parseDouble(matcher.group(1));
if (latitude > 90.0 || latitude < -90.0) {
return null;
}
longitude = Double.parseDouble(matcher.group(2));
if (longitude > 180.0 || longitude < -180.0) {
return null;
}
if (matcher.group(3) == null) {
altitude = 0.0;
} else {
altitude = Double.parseDouble(matcher.group(3));
if (altitude < 0.0) {
return null;
}
}
} catch (NumberFormatException ignored) {
return null;
}
return new GeoParsedResult(latitude, longitude, altitude, query);
| 120
| 299
| 419
|
<methods>public non-sealed void <init>() ,public abstract com.google.zxing.client.result.ParsedResult parse(com.google.zxing.Result) ,public static com.google.zxing.client.result.ParsedResult parseResult(com.google.zxing.Result) <variables>private static final java.util.regex.Pattern AMPERSAND,private static final java.lang.String BYTE_ORDER_MARK,private static final java.util.regex.Pattern DIGITS,static final java.lang.String[] EMPTY_STR_ARRAY,private static final java.util.regex.Pattern EQUALS,private static final com.google.zxing.client.result.ResultParser[] PARSERS
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/client/result/ISBNResultParser.java
|
ISBNResultParser
|
parse
|
class ISBNResultParser extends ResultParser {
/**
* See <a href="http://www.bisg.org/isbn-13/for.dummies.html">ISBN-13 For Dummies</a>
*/
@Override
public ISBNParsedResult parse(Result result) {<FILL_FUNCTION_BODY>}
}
|
BarcodeFormat format = result.getBarcodeFormat();
if (format != BarcodeFormat.EAN_13) {
return null;
}
String rawText = getMassagedText(result);
int length = rawText.length();
if (length != 13) {
return null;
}
if (!rawText.startsWith("978") && !rawText.startsWith("979")) {
return null;
}
return new ISBNParsedResult(rawText);
| 95
| 140
| 235
|
<methods>public non-sealed void <init>() ,public abstract com.google.zxing.client.result.ParsedResult parse(com.google.zxing.Result) ,public static com.google.zxing.client.result.ParsedResult parseResult(com.google.zxing.Result) <variables>private static final java.util.regex.Pattern AMPERSAND,private static final java.lang.String BYTE_ORDER_MARK,private static final java.util.regex.Pattern DIGITS,static final java.lang.String[] EMPTY_STR_ARRAY,private static final java.util.regex.Pattern EQUALS,private static final com.google.zxing.client.result.ResultParser[] PARSERS
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/client/result/ParsedResult.java
|
ParsedResult
|
maybeAppend
|
class ParsedResult {
private final ParsedResultType type;
protected ParsedResult(ParsedResultType type) {
this.type = type;
}
public final ParsedResultType getType() {
return type;
}
public abstract String getDisplayResult();
@Override
public final String toString() {
return getDisplayResult();
}
public static void maybeAppend(String value, StringBuilder result) {
if (value != null && !value.isEmpty()) {
// Don't add a newline before the first value
if (result.length() > 0) {
result.append('\n');
}
result.append(value);
}
}
public static void maybeAppend(String[] values, StringBuilder result) {<FILL_FUNCTION_BODY>}
}
|
if (values != null) {
for (String value : values) {
maybeAppend(value, result);
}
}
| 220
| 38
| 258
|
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/client/result/ProductResultParser.java
|
ProductResultParser
|
parse
|
class ProductResultParser extends ResultParser {
// Treat all UPC and EAN variants as UPCs, in the sense that they are all product barcodes.
@Override
public ProductParsedResult parse(Result result) {<FILL_FUNCTION_BODY>}
}
|
BarcodeFormat format = result.getBarcodeFormat();
if (!(format == BarcodeFormat.UPC_A || format == BarcodeFormat.UPC_E ||
format == BarcodeFormat.EAN_8 || format == BarcodeFormat.EAN_13)) {
return null;
}
String rawText = getMassagedText(result);
if (!isStringOfDigits(rawText, rawText.length())) {
return null;
}
// Not actually checking the checksum again here
String normalizedProductID;
// Expand UPC-E for purposes of searching
if (format == BarcodeFormat.UPC_E && rawText.length() == 8) {
normalizedProductID = UPCEReader.convertUPCEtoUPCA(rawText);
} else {
normalizedProductID = rawText;
}
return new ProductParsedResult(rawText, normalizedProductID);
| 71
| 239
| 310
|
<methods>public non-sealed void <init>() ,public abstract com.google.zxing.client.result.ParsedResult parse(com.google.zxing.Result) ,public static com.google.zxing.client.result.ParsedResult parseResult(com.google.zxing.Result) <variables>private static final java.util.regex.Pattern AMPERSAND,private static final java.lang.String BYTE_ORDER_MARK,private static final java.util.regex.Pattern DIGITS,static final java.lang.String[] EMPTY_STR_ARRAY,private static final java.util.regex.Pattern EQUALS,private static final com.google.zxing.client.result.ResultParser[] PARSERS
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/client/result/SMSMMSResultParser.java
|
SMSMMSResultParser
|
parse
|
class SMSMMSResultParser extends ResultParser {
@Override
public SMSParsedResult parse(Result result) {<FILL_FUNCTION_BODY>}
private static void addNumberVia(Collection<String> numbers,
Collection<String> vias,
String numberPart) {
int numberEnd = numberPart.indexOf(';');
if (numberEnd < 0) {
numbers.add(numberPart);
vias.add(null);
} else {
numbers.add(numberPart.substring(0, numberEnd));
String maybeVia = numberPart.substring(numberEnd + 1);
String via;
if (maybeVia.startsWith("via=")) {
via = maybeVia.substring(4);
} else {
via = null;
}
vias.add(via);
}
}
}
|
String rawText = getMassagedText(result);
if (!(rawText.startsWith("sms:") || rawText.startsWith("SMS:") ||
rawText.startsWith("mms:") || rawText.startsWith("MMS:"))) {
return null;
}
// Check up front if this is a URI syntax string with query arguments
Map<String,String> nameValuePairs = parseNameValuePairs(rawText);
String subject = null;
String body = null;
boolean querySyntax = false;
if (nameValuePairs != null && !nameValuePairs.isEmpty()) {
subject = nameValuePairs.get("subject");
body = nameValuePairs.get("body");
querySyntax = true;
}
// Drop sms, query portion
int queryStart = rawText.indexOf('?', 4);
String smsURIWithoutQuery;
// If it's not query syntax, the question mark is part of the subject or message
if (queryStart < 0 || !querySyntax) {
smsURIWithoutQuery = rawText.substring(4);
} else {
smsURIWithoutQuery = rawText.substring(4, queryStart);
}
int lastComma = -1;
int comma;
List<String> numbers = new ArrayList<>(1);
List<String> vias = new ArrayList<>(1);
while ((comma = smsURIWithoutQuery.indexOf(',', lastComma + 1)) > lastComma) {
String numberPart = smsURIWithoutQuery.substring(lastComma + 1, comma);
addNumberVia(numbers, vias, numberPart);
lastComma = comma;
}
addNumberVia(numbers, vias, smsURIWithoutQuery.substring(lastComma + 1));
return new SMSParsedResult(numbers.toArray(EMPTY_STR_ARRAY),
vias.toArray(EMPTY_STR_ARRAY),
subject,
body);
| 224
| 515
| 739
|
<methods>public non-sealed void <init>() ,public abstract com.google.zxing.client.result.ParsedResult parse(com.google.zxing.Result) ,public static com.google.zxing.client.result.ParsedResult parseResult(com.google.zxing.Result) <variables>private static final java.util.regex.Pattern AMPERSAND,private static final java.lang.String BYTE_ORDER_MARK,private static final java.util.regex.Pattern DIGITS,static final java.lang.String[] EMPTY_STR_ARRAY,private static final java.util.regex.Pattern EQUALS,private static final com.google.zxing.client.result.ResultParser[] PARSERS
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/client/result/SMSParsedResult.java
|
SMSParsedResult
|
getDisplayResult
|
class SMSParsedResult extends ParsedResult {
private final String[] numbers;
private final String[] vias;
private final String subject;
private final String body;
public SMSParsedResult(String number,
String via,
String subject,
String body) {
super(ParsedResultType.SMS);
this.numbers = new String[] {number};
this.vias = new String[] {via};
this.subject = subject;
this.body = body;
}
public SMSParsedResult(String[] numbers,
String[] vias,
String subject,
String body) {
super(ParsedResultType.SMS);
this.numbers = numbers;
this.vias = vias;
this.subject = subject;
this.body = body;
}
public String getSMSURI() {
StringBuilder result = new StringBuilder();
result.append("sms:");
boolean first = true;
for (int i = 0; i < numbers.length; i++) {
if (first) {
first = false;
} else {
result.append(',');
}
result.append(numbers[i]);
if (vias != null && vias[i] != null) {
result.append(";via=");
result.append(vias[i]);
}
}
boolean hasBody = body != null;
boolean hasSubject = subject != null;
if (hasBody || hasSubject) {
result.append('?');
if (hasBody) {
result.append("body=");
result.append(body);
}
if (hasSubject) {
if (hasBody) {
result.append('&');
}
result.append("subject=");
result.append(subject);
}
}
return result.toString();
}
public String[] getNumbers() {
return numbers;
}
public String[] getVias() {
return vias;
}
public String getSubject() {
return subject;
}
public String getBody() {
return body;
}
@Override
public String getDisplayResult() {<FILL_FUNCTION_BODY>}
}
|
StringBuilder result = new StringBuilder(100);
maybeAppend(numbers, result);
maybeAppend(subject, result);
maybeAppend(body, result);
return result.toString();
| 593
| 52
| 645
|
<methods>public abstract java.lang.String getDisplayResult() ,public final com.google.zxing.client.result.ParsedResultType getType() ,public static void maybeAppend(java.lang.String, java.lang.StringBuilder) ,public static void maybeAppend(java.lang.String[], java.lang.StringBuilder) ,public final java.lang.String toString() <variables>private final non-sealed com.google.zxing.client.result.ParsedResultType type
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/client/result/SMSTOMMSTOResultParser.java
|
SMSTOMMSTOResultParser
|
parse
|
class SMSTOMMSTOResultParser extends ResultParser {
@Override
public SMSParsedResult parse(Result result) {<FILL_FUNCTION_BODY>}
}
|
String rawText = getMassagedText(result);
if (!(rawText.startsWith("smsto:") || rawText.startsWith("SMSTO:") ||
rawText.startsWith("mmsto:") || rawText.startsWith("MMSTO:"))) {
return null;
}
// Thanks to dominik.wild for suggesting this enhancement to support
// smsto:number:body URIs
String number = rawText.substring(6);
String body = null;
int bodyStart = number.indexOf(':');
if (bodyStart >= 0) {
body = number.substring(bodyStart + 1);
number = number.substring(0, bodyStart);
}
return new SMSParsedResult(number, null, null, body);
| 50
| 200
| 250
|
<methods>public non-sealed void <init>() ,public abstract com.google.zxing.client.result.ParsedResult parse(com.google.zxing.Result) ,public static com.google.zxing.client.result.ParsedResult parseResult(com.google.zxing.Result) <variables>private static final java.util.regex.Pattern AMPERSAND,private static final java.lang.String BYTE_ORDER_MARK,private static final java.util.regex.Pattern DIGITS,static final java.lang.String[] EMPTY_STR_ARRAY,private static final java.util.regex.Pattern EQUALS,private static final com.google.zxing.client.result.ResultParser[] PARSERS
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/client/result/SMTPResultParser.java
|
SMTPResultParser
|
parse
|
class SMTPResultParser extends ResultParser {
@Override
public EmailAddressParsedResult parse(Result result) {<FILL_FUNCTION_BODY>}
}
|
String rawText = getMassagedText(result);
if (!(rawText.startsWith("smtp:") || rawText.startsWith("SMTP:"))) {
return null;
}
String emailAddress = rawText.substring(5);
String subject = null;
String body = null;
int colon = emailAddress.indexOf(':');
if (colon >= 0) {
subject = emailAddress.substring(colon + 1);
emailAddress = emailAddress.substring(0, colon);
colon = subject.indexOf(':');
if (colon >= 0) {
body = subject.substring(colon + 1);
subject = subject.substring(0, colon);
}
}
return new EmailAddressParsedResult(new String[] {emailAddress},
null,
null,
subject,
body);
| 44
| 216
| 260
|
<methods>public non-sealed void <init>() ,public abstract com.google.zxing.client.result.ParsedResult parse(com.google.zxing.Result) ,public static com.google.zxing.client.result.ParsedResult parseResult(com.google.zxing.Result) <variables>private static final java.util.regex.Pattern AMPERSAND,private static final java.lang.String BYTE_ORDER_MARK,private static final java.util.regex.Pattern DIGITS,static final java.lang.String[] EMPTY_STR_ARRAY,private static final java.util.regex.Pattern EQUALS,private static final com.google.zxing.client.result.ResultParser[] PARSERS
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/client/result/TelParsedResult.java
|
TelParsedResult
|
getDisplayResult
|
class TelParsedResult extends ParsedResult {
private final String number;
private final String telURI;
private final String title;
public TelParsedResult(String number, String telURI, String title) {
super(ParsedResultType.TEL);
this.number = number;
this.telURI = telURI;
this.title = title;
}
public String getNumber() {
return number;
}
public String getTelURI() {
return telURI;
}
public String getTitle() {
return title;
}
@Override
public String getDisplayResult() {<FILL_FUNCTION_BODY>}
}
|
StringBuilder result = new StringBuilder(20);
maybeAppend(number, result);
maybeAppend(title, result);
return result.toString();
| 183
| 41
| 224
|
<methods>public abstract java.lang.String getDisplayResult() ,public final com.google.zxing.client.result.ParsedResultType getType() ,public static void maybeAppend(java.lang.String, java.lang.StringBuilder) ,public static void maybeAppend(java.lang.String[], java.lang.StringBuilder) ,public final java.lang.String toString() <variables>private final non-sealed com.google.zxing.client.result.ParsedResultType type
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/client/result/TelResultParser.java
|
TelResultParser
|
parse
|
class TelResultParser extends ResultParser {
@Override
public TelParsedResult parse(Result result) {<FILL_FUNCTION_BODY>}
}
|
String rawText = getMassagedText(result);
if (!rawText.startsWith("tel:") && !rawText.startsWith("TEL:")) {
return null;
}
// Normalize "TEL:" to "tel:"
String telURI = rawText.startsWith("TEL:") ? "tel:" + rawText.substring(4) : rawText;
// Drop tel, query portion
int queryStart = rawText.indexOf('?', 4);
String number = queryStart < 0 ? rawText.substring(4) : rawText.substring(4, queryStart);
return new TelParsedResult(number, telURI, null);
| 43
| 173
| 216
|
<methods>public non-sealed void <init>() ,public abstract com.google.zxing.client.result.ParsedResult parse(com.google.zxing.Result) ,public static com.google.zxing.client.result.ParsedResult parseResult(com.google.zxing.Result) <variables>private static final java.util.regex.Pattern AMPERSAND,private static final java.lang.String BYTE_ORDER_MARK,private static final java.util.regex.Pattern DIGITS,static final java.lang.String[] EMPTY_STR_ARRAY,private static final java.util.regex.Pattern EQUALS,private static final com.google.zxing.client.result.ResultParser[] PARSERS
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/client/result/URIParsedResult.java
|
URIParsedResult
|
getDisplayResult
|
class URIParsedResult extends ParsedResult {
private final String uri;
private final String title;
public URIParsedResult(String uri, String title) {
super(ParsedResultType.URI);
this.uri = massageURI(uri);
this.title = title;
}
public String getURI() {
return uri;
}
public String getTitle() {
return title;
}
/**
* @return true if the URI contains suspicious patterns that may suggest it intends to
* mislead the user about its true nature
* @deprecated see {@link URIResultParser#isPossiblyMaliciousURI(String)}
*/
@Deprecated
public boolean isPossiblyMaliciousURI() {
return URIResultParser.isPossiblyMaliciousURI(uri);
}
@Override
public String getDisplayResult() {<FILL_FUNCTION_BODY>}
/**
* Transforms a string that represents a URI into something more proper, by adding or canonicalizing
* the protocol.
*/
private static String massageURI(String uri) {
uri = uri.trim();
int protocolEnd = uri.indexOf(':');
if (protocolEnd < 0 || isColonFollowedByPortNumber(uri, protocolEnd)) {
// No protocol, or found a colon, but it looks like it is after the host, so the protocol is still missing,
// so assume http
uri = "http://" + uri;
}
return uri;
}
private static boolean isColonFollowedByPortNumber(String uri, int protocolEnd) {
int start = protocolEnd + 1;
int nextSlash = uri.indexOf('/', start);
if (nextSlash < 0) {
nextSlash = uri.length();
}
return ResultParser.isSubstringOfDigits(uri, start, nextSlash - start);
}
}
|
StringBuilder result = new StringBuilder(30);
maybeAppend(title, result);
maybeAppend(uri, result);
return result.toString();
| 486
| 41
| 527
|
<methods>public abstract java.lang.String getDisplayResult() ,public final com.google.zxing.client.result.ParsedResultType getType() ,public static void maybeAppend(java.lang.String, java.lang.StringBuilder) ,public static void maybeAppend(java.lang.String[], java.lang.StringBuilder) ,public final java.lang.String toString() <variables>private final non-sealed com.google.zxing.client.result.ParsedResultType type
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/client/result/URIResultParser.java
|
URIResultParser
|
isBasicallyValidURI
|
class URIResultParser extends ResultParser {
private static final Pattern ALLOWED_URI_CHARS_PATTERN =
Pattern.compile("[-._~:/?#\\[\\]@!$&'()*+,;=%A-Za-z0-9]+");
private static final Pattern USER_IN_HOST = Pattern.compile(":/*([^/@]+)@[^/]+");
// See http://www.ietf.org/rfc/rfc2396.txt
private static final Pattern URL_WITH_PROTOCOL_PATTERN = Pattern.compile("[a-zA-Z][a-zA-Z0-9+-.]+:");
private static final Pattern URL_WITHOUT_PROTOCOL_PATTERN = Pattern.compile(
"([a-zA-Z0-9\\-]+\\.){1,6}[a-zA-Z]{2,}" + // host name elements; allow up to say 6 domain elements
"(:\\d{1,5})?" + // maybe port
"(/|\\?|$)"); // query, path or nothing
@Override
public URIParsedResult parse(Result result) {
String rawText = getMassagedText(result);
// We specifically handle the odd "URL" scheme here for simplicity and add "URI" for fun
// Assume anything starting this way really means to be a URI
if (rawText.startsWith("URL:") || rawText.startsWith("URI:")) {
return new URIParsedResult(rawText.substring(4).trim(), null);
}
rawText = rawText.trim();
if (!isBasicallyValidURI(rawText) || isPossiblyMaliciousURI(rawText)) {
return null;
}
return new URIParsedResult(rawText, null);
}
/**
* @return true if the URI contains suspicious patterns that may suggest it intends to
* mislead the user about its true nature. At the moment this looks for the presence
* of user/password syntax in the host/authority portion of a URI which may be used
* in attempts to make the URI's host appear to be other than it is. Example:
* http://yourbank.com@phisher.com This URI connects to phisher.com but may appear
* to connect to yourbank.com at first glance.
*/
static boolean isPossiblyMaliciousURI(String uri) {
return !ALLOWED_URI_CHARS_PATTERN.matcher(uri).matches() || USER_IN_HOST.matcher(uri).find();
}
static boolean isBasicallyValidURI(String uri) {<FILL_FUNCTION_BODY>}
}
|
if (uri.contains(" ")) {
// Quick hack check for a common case
return false;
}
Matcher m = URL_WITH_PROTOCOL_PATTERN.matcher(uri);
if (m.find() && m.start() == 0) { // match at start only
return true;
}
m = URL_WITHOUT_PROTOCOL_PATTERN.matcher(uri);
return m.find() && m.start() == 0;
| 694
| 122
| 816
|
<methods>public non-sealed void <init>() ,public abstract com.google.zxing.client.result.ParsedResult parse(com.google.zxing.Result) ,public static com.google.zxing.client.result.ParsedResult parseResult(com.google.zxing.Result) <variables>private static final java.util.regex.Pattern AMPERSAND,private static final java.lang.String BYTE_ORDER_MARK,private static final java.util.regex.Pattern DIGITS,static final java.lang.String[] EMPTY_STR_ARRAY,private static final java.util.regex.Pattern EQUALS,private static final com.google.zxing.client.result.ResultParser[] PARSERS
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/client/result/URLTOResultParser.java
|
URLTOResultParser
|
parse
|
class URLTOResultParser extends ResultParser {
@Override
public URIParsedResult parse(Result result) {<FILL_FUNCTION_BODY>}
}
|
String rawText = getMassagedText(result);
if (!rawText.startsWith("urlto:") && !rawText.startsWith("URLTO:")) {
return null;
}
int titleEnd = rawText.indexOf(':', 6);
if (titleEnd < 0) {
return null;
}
String title = titleEnd <= 6 ? null : rawText.substring(6, titleEnd);
String uri = rawText.substring(titleEnd + 1);
return new URIParsedResult(uri, title);
| 47
| 141
| 188
|
<methods>public non-sealed void <init>() ,public abstract com.google.zxing.client.result.ParsedResult parse(com.google.zxing.Result) ,public static com.google.zxing.client.result.ParsedResult parseResult(com.google.zxing.Result) <variables>private static final java.util.regex.Pattern AMPERSAND,private static final java.lang.String BYTE_ORDER_MARK,private static final java.util.regex.Pattern DIGITS,static final java.lang.String[] EMPTY_STR_ARRAY,private static final java.util.regex.Pattern EQUALS,private static final com.google.zxing.client.result.ResultParser[] PARSERS
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/client/result/VEventResultParser.java
|
VEventResultParser
|
parse
|
class VEventResultParser extends ResultParser {
@Override
public CalendarParsedResult parse(Result result) {<FILL_FUNCTION_BODY>}
private static String matchSingleVCardPrefixedField(CharSequence prefix,
String rawText) {
List<String> values = VCardResultParser.matchSingleVCardPrefixedField(prefix, rawText, true, false);
return values == null || values.isEmpty() ? null : values.get(0);
}
private static String[] matchVCardPrefixedField(CharSequence prefix, String rawText) {
List<List<String>> values = VCardResultParser.matchVCardPrefixedField(prefix, rawText, true, false);
if (values == null || values.isEmpty()) {
return null;
}
int size = values.size();
String[] result = new String[size];
for (int i = 0; i < size; i++) {
result[i] = values.get(i).get(0);
}
return result;
}
private static String stripMailto(String s) {
if (s != null && (s.startsWith("mailto:") || s.startsWith("MAILTO:"))) {
s = s.substring(7);
}
return s;
}
}
|
String rawText = getMassagedText(result);
int vEventStart = rawText.indexOf("BEGIN:VEVENT");
if (vEventStart < 0) {
return null;
}
String summary = matchSingleVCardPrefixedField("SUMMARY", rawText);
String start = matchSingleVCardPrefixedField("DTSTART", rawText);
if (start == null) {
return null;
}
String end = matchSingleVCardPrefixedField("DTEND", rawText);
String duration = matchSingleVCardPrefixedField("DURATION", rawText);
String location = matchSingleVCardPrefixedField("LOCATION", rawText);
String organizer = stripMailto(matchSingleVCardPrefixedField("ORGANIZER", rawText));
String[] attendees = matchVCardPrefixedField("ATTENDEE", rawText);
if (attendees != null) {
for (int i = 0; i < attendees.length; i++) {
attendees[i] = stripMailto(attendees[i]);
}
}
String description = matchSingleVCardPrefixedField("DESCRIPTION", rawText);
String geoString = matchSingleVCardPrefixedField("GEO", rawText);
double latitude;
double longitude;
if (geoString == null) {
latitude = Double.NaN;
longitude = Double.NaN;
} else {
int semicolon = geoString.indexOf(';');
if (semicolon < 0) {
return null;
}
try {
latitude = Double.parseDouble(geoString.substring(0, semicolon));
longitude = Double.parseDouble(geoString.substring(semicolon + 1));
} catch (NumberFormatException ignored) {
return null;
}
}
try {
return new CalendarParsedResult(summary,
start,
end,
duration,
location,
organizer,
attendees,
description,
latitude,
longitude);
} catch (IllegalArgumentException ignored) {
return null;
}
| 332
| 542
| 874
|
<methods>public non-sealed void <init>() ,public abstract com.google.zxing.client.result.ParsedResult parse(com.google.zxing.Result) ,public static com.google.zxing.client.result.ParsedResult parseResult(com.google.zxing.Result) <variables>private static final java.util.regex.Pattern AMPERSAND,private static final java.lang.String BYTE_ORDER_MARK,private static final java.util.regex.Pattern DIGITS,static final java.lang.String[] EMPTY_STR_ARRAY,private static final java.util.regex.Pattern EQUALS,private static final com.google.zxing.client.result.ResultParser[] PARSERS
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/client/result/VINParsedResult.java
|
VINParsedResult
|
getDisplayResult
|
class VINParsedResult extends ParsedResult {
private final String vin;
private final String worldManufacturerID;
private final String vehicleDescriptorSection;
private final String vehicleIdentifierSection;
private final String countryCode;
private final String vehicleAttributes;
private final int modelYear;
private final char plantCode;
private final String sequentialNumber;
public VINParsedResult(String vin,
String worldManufacturerID,
String vehicleDescriptorSection,
String vehicleIdentifierSection,
String countryCode,
String vehicleAttributes,
int modelYear,
char plantCode,
String sequentialNumber) {
super(ParsedResultType.VIN);
this.vin = vin;
this.worldManufacturerID = worldManufacturerID;
this.vehicleDescriptorSection = vehicleDescriptorSection;
this.vehicleIdentifierSection = vehicleIdentifierSection;
this.countryCode = countryCode;
this.vehicleAttributes = vehicleAttributes;
this.modelYear = modelYear;
this.plantCode = plantCode;
this.sequentialNumber = sequentialNumber;
}
public String getVIN() {
return vin;
}
public String getWorldManufacturerID() {
return worldManufacturerID;
}
public String getVehicleDescriptorSection() {
return vehicleDescriptorSection;
}
public String getVehicleIdentifierSection() {
return vehicleIdentifierSection;
}
public String getCountryCode() {
return countryCode;
}
public String getVehicleAttributes() {
return vehicleAttributes;
}
public int getModelYear() {
return modelYear;
}
public char getPlantCode() {
return plantCode;
}
public String getSequentialNumber() {
return sequentialNumber;
}
@Override
public String getDisplayResult() {<FILL_FUNCTION_BODY>}
}
|
StringBuilder result = new StringBuilder(50);
result.append(worldManufacturerID).append(' ');
result.append(vehicleDescriptorSection).append(' ');
result.append(vehicleIdentifierSection).append('\n');
if (countryCode != null) {
result.append(countryCode).append(' ');
}
result.append(modelYear).append(' ');
result.append(plantCode).append(' ');
result.append(sequentialNumber).append('\n');
return result.toString();
| 502
| 140
| 642
|
<methods>public abstract java.lang.String getDisplayResult() ,public final com.google.zxing.client.result.ParsedResultType getType() ,public static void maybeAppend(java.lang.String, java.lang.StringBuilder) ,public static void maybeAppend(java.lang.String[], java.lang.StringBuilder) ,public final java.lang.String toString() <variables>private final non-sealed com.google.zxing.client.result.ParsedResultType type
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/client/result/VINResultParser.java
|
VINResultParser
|
parse
|
class VINResultParser extends ResultParser {
private static final Pattern IOQ = Pattern.compile("[IOQ]");
private static final Pattern AZ09 = Pattern.compile("[A-Z0-9]{17}");
@Override
public VINParsedResult parse(Result result) {<FILL_FUNCTION_BODY>}
private static boolean checkChecksum(CharSequence vin) {
int sum = 0;
for (int i = 0; i < vin.length(); i++) {
sum += vinPositionWeight(i + 1) * vinCharValue(vin.charAt(i));
}
char checkChar = vin.charAt(8);
char expectedCheckChar = checkChar(sum % 11);
return checkChar == expectedCheckChar;
}
private static int vinCharValue(char c) {
if (c >= 'A' && c <= 'I') {
return (c - 'A') + 1;
}
if (c >= 'J' && c <= 'R') {
return (c - 'J') + 1;
}
if (c >= 'S' && c <= 'Z') {
return (c - 'S') + 2;
}
if (c >= '0' && c <= '9') {
return c - '0';
}
throw new IllegalArgumentException();
}
private static int vinPositionWeight(int position) {
if (position >= 1 && position <= 7) {
return 9 - position;
}
if (position == 8) {
return 10;
}
if (position == 9) {
return 0;
}
if (position >= 10 && position <= 17) {
return 19 - position;
}
throw new IllegalArgumentException();
}
private static char checkChar(int remainder) {
if (remainder < 10) {
return (char) ('0' + remainder);
}
if (remainder == 10) {
return 'X';
}
throw new IllegalArgumentException();
}
private static int modelYear(char c) {
if (c >= 'E' && c <= 'H') {
return (c - 'E') + 1984;
}
if (c >= 'J' && c <= 'N') {
return (c - 'J') + 1988;
}
if (c == 'P') {
return 1993;
}
if (c >= 'R' && c <= 'T') {
return (c - 'R') + 1994;
}
if (c >= 'V' && c <= 'Y') {
return (c - 'V') + 1997;
}
if (c >= '1' && c <= '9') {
return (c - '1') + 2001;
}
if (c >= 'A' && c <= 'D') {
return (c - 'A') + 2010;
}
throw new IllegalArgumentException();
}
private static String countryCode(CharSequence wmi) {
char c1 = wmi.charAt(0);
char c2 = wmi.charAt(1);
switch (c1) {
case '1':
case '4':
case '5':
return "US";
case '2':
return "CA";
case '3':
if (c2 >= 'A' && c2 <= 'W') {
return "MX";
}
break;
case '9':
if ((c2 >= 'A' && c2 <= 'E') || (c2 >= '3' && c2 <= '9')) {
return "BR";
}
break;
case 'J':
if (c2 >= 'A' && c2 <= 'T') {
return "JP";
}
break;
case 'K':
if (c2 >= 'L' && c2 <= 'R') {
return "KO";
}
break;
case 'L':
return "CN";
case 'M':
if (c2 >= 'A' && c2 <= 'E') {
return "IN";
}
break;
case 'S':
if (c2 >= 'A' && c2 <= 'M') {
return "UK";
}
if (c2 >= 'N' && c2 <= 'T') {
return "DE";
}
break;
case 'V':
if (c2 >= 'F' && c2 <= 'R') {
return "FR";
}
if (c2 >= 'S' && c2 <= 'W') {
return "ES";
}
break;
case 'W':
return "DE";
case 'X':
if (c2 == '0' || (c2 >= '3' && c2 <= '9')) {
return "RU";
}
break;
case 'Z':
if (c2 >= 'A' && c2 <= 'R') {
return "IT";
}
break;
}
return null;
}
}
|
if (result.getBarcodeFormat() != BarcodeFormat.CODE_39) {
return null;
}
String rawText = result.getText();
rawText = IOQ.matcher(rawText).replaceAll("").trim();
if (!AZ09.matcher(rawText).matches()) {
return null;
}
try {
if (!checkChecksum(rawText)) {
return null;
}
String wmi = rawText.substring(0, 3);
return new VINParsedResult(rawText,
wmi,
rawText.substring(3, 9),
rawText.substring(9, 17),
countryCode(wmi),
rawText.substring(3, 8),
modelYear(rawText.charAt(9)),
rawText.charAt(10),
rawText.substring(11));
} catch (IllegalArgumentException iae) {
return null;
}
| 1,321
| 257
| 1,578
|
<methods>public non-sealed void <init>() ,public abstract com.google.zxing.client.result.ParsedResult parse(com.google.zxing.Result) ,public static com.google.zxing.client.result.ParsedResult parseResult(com.google.zxing.Result) <variables>private static final java.util.regex.Pattern AMPERSAND,private static final java.lang.String BYTE_ORDER_MARK,private static final java.util.regex.Pattern DIGITS,static final java.lang.String[] EMPTY_STR_ARRAY,private static final java.util.regex.Pattern EQUALS,private static final com.google.zxing.client.result.ResultParser[] PARSERS
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/client/result/WifiParsedResult.java
|
WifiParsedResult
|
getDisplayResult
|
class WifiParsedResult extends ParsedResult {
private final String ssid;
private final String networkEncryption;
private final String password;
private final boolean hidden;
private final String identity;
private final String anonymousIdentity;
private final String eapMethod;
private final String phase2Method;
public WifiParsedResult(String networkEncryption, String ssid, String password) {
this(networkEncryption, ssid, password, false);
}
public WifiParsedResult(String networkEncryption, String ssid, String password, boolean hidden) {
this(networkEncryption, ssid, password, hidden, null, null, null, null);
}
public WifiParsedResult(String networkEncryption,
String ssid,
String password,
boolean hidden,
String identity,
String anonymousIdentity,
String eapMethod,
String phase2Method) {
super(ParsedResultType.WIFI);
this.ssid = ssid;
this.networkEncryption = networkEncryption;
this.password = password;
this.hidden = hidden;
this.identity = identity;
this.anonymousIdentity = anonymousIdentity;
this.eapMethod = eapMethod;
this.phase2Method = phase2Method;
}
public String getSsid() {
return ssid;
}
public String getNetworkEncryption() {
return networkEncryption;
}
public String getPassword() {
return password;
}
public boolean isHidden() {
return hidden;
}
public String getIdentity() {
return identity;
}
public String getAnonymousIdentity() {
return anonymousIdentity;
}
public String getEapMethod() {
return eapMethod;
}
public String getPhase2Method() {
return phase2Method;
}
@Override
public String getDisplayResult() {<FILL_FUNCTION_BODY>}
}
|
StringBuilder result = new StringBuilder(80);
maybeAppend(ssid, result);
maybeAppend(networkEncryption, result);
maybeAppend(password, result);
maybeAppend(Boolean.toString(hidden), result);
return result.toString();
| 514
| 66
| 580
|
<methods>public abstract java.lang.String getDisplayResult() ,public final com.google.zxing.client.result.ParsedResultType getType() ,public static void maybeAppend(java.lang.String, java.lang.StringBuilder) ,public static void maybeAppend(java.lang.String[], java.lang.StringBuilder) ,public final java.lang.String toString() <variables>private final non-sealed com.google.zxing.client.result.ParsedResultType type
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/client/result/WifiResultParser.java
|
WifiResultParser
|
parse
|
class WifiResultParser extends ResultParser {
@Override
public WifiParsedResult parse(Result result) {<FILL_FUNCTION_BODY>}
}
|
String rawText = getMassagedText(result);
if (!rawText.startsWith("WIFI:")) {
return null;
}
rawText = rawText.substring("WIFI:".length());
String ssid = matchSinglePrefixedField("S:", rawText, ';', false);
if (ssid == null || ssid.isEmpty()) {
return null;
}
String pass = matchSinglePrefixedField("P:", rawText, ';', false);
String type = matchSinglePrefixedField("T:", rawText, ';', false);
if (type == null) {
type = "nopass";
}
// Unfortunately, in the past, H: was not just used for boolean 'hidden', but 'phase 2 method'.
// To try to retain backwards compatibility, we set one or the other based on whether the string
// is 'true' or 'false':
boolean hidden = false;
String phase2Method = matchSinglePrefixedField("PH2:", rawText, ';', false);
String hValue = matchSinglePrefixedField("H:", rawText, ';', false);
if (hValue != null) {
// If PH2 was specified separately, or if the value is clearly boolean, interpret it as 'hidden'
if (phase2Method != null || "true".equalsIgnoreCase(hValue) || "false".equalsIgnoreCase(hValue)) {
hidden = Boolean.parseBoolean(hValue);
} else {
phase2Method = hValue;
}
}
String identity = matchSinglePrefixedField("I:", rawText, ';', false);
String anonymousIdentity = matchSinglePrefixedField("A:", rawText, ';', false);
String eapMethod = matchSinglePrefixedField("E:", rawText, ';', false);
return new WifiParsedResult(type, ssid, pass, hidden, identity, anonymousIdentity, eapMethod, phase2Method);
| 44
| 487
| 531
|
<methods>public non-sealed void <init>() ,public abstract com.google.zxing.client.result.ParsedResult parse(com.google.zxing.Result) ,public static com.google.zxing.client.result.ParsedResult parseResult(com.google.zxing.Result) <variables>private static final java.util.regex.Pattern AMPERSAND,private static final java.lang.String BYTE_ORDER_MARK,private static final java.util.regex.Pattern DIGITS,static final java.lang.String[] EMPTY_STR_ARRAY,private static final java.util.regex.Pattern EQUALS,private static final com.google.zxing.client.result.ResultParser[] PARSERS
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/common/BitSource.java
|
BitSource
|
readBits
|
class BitSource {
private final byte[] bytes;
private int byteOffset;
private int bitOffset;
/**
* @param bytes bytes from which this will read bits. Bits will be read from the first byte first.
* Bits are read within a byte from most-significant to least-significant bit.
*/
public BitSource(byte[] bytes) {
this.bytes = bytes;
}
/**
* @return index of next bit in current byte which would be read by the next call to {@link #readBits(int)}.
*/
public int getBitOffset() {
return bitOffset;
}
/**
* @return index of next byte in input byte array which would be read by the next call to {@link #readBits(int)}.
*/
public int getByteOffset() {
return byteOffset;
}
/**
* @param numBits number of bits to read
* @return int representing the bits read. The bits will appear as the least-significant
* bits of the int
* @throws IllegalArgumentException if numBits isn't in [1,32] or more than is available
*/
public int readBits(int numBits) {<FILL_FUNCTION_BODY>}
/**
* @return number of bits that can be read successfully
*/
public int available() {
return 8 * (bytes.length - byteOffset) - bitOffset;
}
}
|
if (numBits < 1 || numBits > 32 || numBits > available()) {
throw new IllegalArgumentException(String.valueOf(numBits));
}
int result = 0;
// First, read remainder from current byte
if (bitOffset > 0) {
int bitsLeft = 8 - bitOffset;
int toRead = Math.min(numBits, bitsLeft);
int bitsToNotRead = bitsLeft - toRead;
int mask = (0xFF >> (8 - toRead)) << bitsToNotRead;
result = (bytes[byteOffset] & mask) >> bitsToNotRead;
numBits -= toRead;
bitOffset += toRead;
if (bitOffset == 8) {
bitOffset = 0;
byteOffset++;
}
}
// Next read whole bytes
if (numBits > 0) {
while (numBits >= 8) {
result = (result << 8) | (bytes[byteOffset] & 0xFF);
byteOffset++;
numBits -= 8;
}
// Finally read a partial byte
if (numBits > 0) {
int bitsToNotRead = 8 - numBits;
int mask = (0xFF >> bitsToNotRead) << bitsToNotRead;
result = (result << numBits) | ((bytes[byteOffset] & mask) >> bitsToNotRead);
bitOffset += numBits;
}
}
return result;
| 367
| 378
| 745
|
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/common/DefaultGridSampler.java
|
DefaultGridSampler
|
sampleGrid
|
class DefaultGridSampler extends GridSampler {
@Override
public BitMatrix sampleGrid(BitMatrix image,
int dimensionX,
int dimensionY,
float p1ToX, float p1ToY,
float p2ToX, float p2ToY,
float p3ToX, float p3ToY,
float p4ToX, float p4ToY,
float p1FromX, float p1FromY,
float p2FromX, float p2FromY,
float p3FromX, float p3FromY,
float p4FromX, float p4FromY) throws NotFoundException {
PerspectiveTransform transform = PerspectiveTransform.quadrilateralToQuadrilateral(
p1ToX, p1ToY, p2ToX, p2ToY, p3ToX, p3ToY, p4ToX, p4ToY,
p1FromX, p1FromY, p2FromX, p2FromY, p3FromX, p3FromY, p4FromX, p4FromY);
return sampleGrid(image, dimensionX, dimensionY, transform);
}
@Override
public BitMatrix sampleGrid(BitMatrix image,
int dimensionX,
int dimensionY,
PerspectiveTransform transform) throws NotFoundException {<FILL_FUNCTION_BODY>}
}
|
if (dimensionX <= 0 || dimensionY <= 0) {
throw NotFoundException.getNotFoundInstance();
}
BitMatrix bits = new BitMatrix(dimensionX, dimensionY);
float[] points = new float[2 * dimensionX];
for (int y = 0; y < dimensionY; y++) {
int max = points.length;
float iValue = y + 0.5f;
for (int x = 0; x < max; x += 2) {
points[x] = (float) (x / 2) + 0.5f;
points[x + 1] = iValue;
}
transform.transformPoints(points);
// Quick check to see if points transformed to something inside the image;
// sufficient to check the endpoints
checkAndNudgePoints(image, points);
try {
for (int x = 0; x < max; x += 2) {
if (image.get((int) points[x], (int) points[x + 1])) {
// Black(-ish) pixel
bits.set(x / 2, y);
}
}
} catch (ArrayIndexOutOfBoundsException aioobe) {
// This feels wrong, but, sometimes if the finder patterns are misidentified, the resulting
// transform gets "twisted" such that it maps a straight line of points to a set of points
// whose endpoints are in bounds, but others are not. There is probably some mathematical
// way to detect this about the transformation that I don't know yet.
// This results in an ugly runtime exception despite our clever checks above -- can't have
// that. We could check each point's coordinates but that feels duplicative. We settle for
// catching and wrapping ArrayIndexOutOfBoundsException.
throw NotFoundException.getNotFoundInstance();
}
}
return bits;
| 338
| 455
| 793
|
<methods>public non-sealed void <init>() ,public static com.google.zxing.common.GridSampler getInstance() ,public abstract com.google.zxing.common.BitMatrix sampleGrid(com.google.zxing.common.BitMatrix, int, int, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float) throws com.google.zxing.NotFoundException,public abstract com.google.zxing.common.BitMatrix sampleGrid(com.google.zxing.common.BitMatrix, int, int, com.google.zxing.common.PerspectiveTransform) throws com.google.zxing.NotFoundException,public static void setGridSampler(com.google.zxing.common.GridSampler) <variables>private static com.google.zxing.common.GridSampler gridSampler
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/common/ECIEncoderSet.java
|
ECIEncoderSet
|
canEncode
|
class ECIEncoderSet {
// List of encoders that potentially encode characters not in ISO-8859-1 in one byte.
private static final List<CharsetEncoder> ENCODERS = new ArrayList<>();
static {
String[] names = { "IBM437",
"ISO-8859-2",
"ISO-8859-3",
"ISO-8859-4",
"ISO-8859-5",
"ISO-8859-6",
"ISO-8859-7",
"ISO-8859-8",
"ISO-8859-9",
"ISO-8859-10",
"ISO-8859-11",
"ISO-8859-13",
"ISO-8859-14",
"ISO-8859-15",
"ISO-8859-16",
"windows-1250",
"windows-1251",
"windows-1252",
"windows-1256",
"Shift_JIS" };
for (String name : names) {
if (CharacterSetECI.getCharacterSetECIByName(name) != null) {
try {
ENCODERS.add(Charset.forName(name).newEncoder());
} catch (UnsupportedCharsetException e) {
// continue
}
}
}
}
private final CharsetEncoder[] encoders;
private final int priorityEncoderIndex;
/**
* Constructs an encoder set
*
* @param stringToEncode the string that needs to be encoded
* @param priorityCharset The preferred {@link Charset} or null.
* @param fnc1 fnc1 denotes the character in the input that represents the FNC1 character or -1 for a non-GS1 bar
* code. When specified, it is considered an error to pass it as argument to the methods canEncode() or encode().
*/
public ECIEncoderSet(String stringToEncode, Charset priorityCharset, int fnc1) {
List<CharsetEncoder> neededEncoders = new ArrayList<>();
//we always need the ISO-8859-1 encoder. It is the default encoding
neededEncoders.add(StandardCharsets.ISO_8859_1.newEncoder());
boolean needUnicodeEncoder = priorityCharset != null && priorityCharset.name().startsWith("UTF");
//Walk over the input string and see if all characters can be encoded with the list of encoders
for (int i = 0; i < stringToEncode.length(); i++) {
boolean canEncode = false;
for (CharsetEncoder encoder : neededEncoders) {
char c = stringToEncode.charAt(i);
if (c == fnc1 || encoder.canEncode(c)) {
canEncode = true;
break;
}
}
if (!canEncode) {
//for the character at position i we don't yet have an encoder in the list
for (CharsetEncoder encoder : ENCODERS) {
if (encoder.canEncode(stringToEncode.charAt(i))) {
//Good, we found an encoder that can encode the character. We add him to the list and continue scanning
//the input
neededEncoders.add(encoder);
canEncode = true;
break;
}
}
}
if (!canEncode) {
//The character is not encodeable by any of the single byte encoders so we remember that we will need a
//Unicode encoder.
needUnicodeEncoder = true;
}
}
if (neededEncoders.size() == 1 && !needUnicodeEncoder) {
//the entire input can be encoded by the ISO-8859-1 encoder
encoders = new CharsetEncoder[] { neededEncoders.get(0) };
} else {
// we need more than one single byte encoder or we need a Unicode encoder.
// In this case we append a UTF-8 and UTF-16 encoder to the list
encoders = new CharsetEncoder[neededEncoders.size() + 2];
int index = 0;
for (CharsetEncoder encoder : neededEncoders) {
encoders[index++] = encoder;
}
encoders[index] = StandardCharsets.UTF_8.newEncoder();
encoders[index + 1] = StandardCharsets.UTF_16BE.newEncoder();
}
//Compute priorityEncoderIndex by looking up priorityCharset in encoders
int priorityEncoderIndexValue = -1;
if (priorityCharset != null) {
for (int i = 0; i < encoders.length; i++) {
if (encoders[i] != null && priorityCharset.name().equals(encoders[i].charset().name())) {
priorityEncoderIndexValue = i;
break;
}
}
}
priorityEncoderIndex = priorityEncoderIndexValue;
//invariants
assert encoders[0].charset().equals(StandardCharsets.ISO_8859_1);
}
public int length() {
return encoders.length;
}
public String getCharsetName(int index) {
assert index < length();
return encoders[index].charset().name();
}
public Charset getCharset(int index) {
assert index < length();
return encoders[index].charset();
}
public int getECIValue(int encoderIndex) {
return CharacterSetECI.getCharacterSetECI(encoders[encoderIndex].charset()).getValue();
}
/*
* returns -1 if no priority charset was defined
*/
public int getPriorityEncoderIndex() {
return priorityEncoderIndex;
}
public boolean canEncode(char c, int encoderIndex) {<FILL_FUNCTION_BODY>}
public byte[] encode(char c, int encoderIndex) {
assert encoderIndex < length();
CharsetEncoder encoder = encoders[encoderIndex];
assert encoder.canEncode("" + c);
return ("" + c).getBytes(encoder.charset());
}
public byte[] encode(String s, int encoderIndex) {
assert encoderIndex < length();
CharsetEncoder encoder = encoders[encoderIndex];
return s.getBytes(encoder.charset());
}
}
|
assert encoderIndex < length();
CharsetEncoder encoder = encoders[encoderIndex];
return encoder.canEncode("" + c);
| 1,699
| 40
| 1,739
|
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/common/ECIStringBuilder.java
|
ECIStringBuilder
|
encodeCurrentBytesIfAny
|
class ECIStringBuilder {
private StringBuilder currentBytes;
private StringBuilder result;
private Charset currentCharset = StandardCharsets.ISO_8859_1;
public ECIStringBuilder() {
currentBytes = new StringBuilder();
}
public ECIStringBuilder(int initialCapacity) {
currentBytes = new StringBuilder(initialCapacity);
}
/**
* Appends {@code value} as a byte value
*
* @param value character whose lowest byte is to be appended
*/
public void append(char value) {
currentBytes.append((char) (value & 0xff));
}
/**
* Appends {@code value} as a byte value
*
* @param value byte to append
*/
public void append(byte value) {
currentBytes.append((char) (value & 0xff));
}
/**
* Appends the characters in {@code value} as bytes values
*
* @param value string to append
*/
public void append(String value) {
currentBytes.append(value);
}
/**
* Append the string repesentation of {@code value} (short for {@code append(String.valueOf(value))})
*
* @param value int to append as a string
*/
public void append(int value) {
append(String.valueOf(value));
}
/**
* Appends ECI value to output.
*
* @param value ECI value to append, as an int
* @throws FormatException on invalid ECI value
*/
public void appendECI(int value) throws FormatException {
encodeCurrentBytesIfAny();
CharacterSetECI characterSetECI = CharacterSetECI.getCharacterSetECIByValue(value);
if (characterSetECI == null) {
throw FormatException.getFormatInstance();
}
currentCharset = characterSetECI.getCharset();
}
private void encodeCurrentBytesIfAny() {<FILL_FUNCTION_BODY>}
/**
* Appends the characters from {@code value} (unlike all other append methods of this class who append bytes)
*
* @param value characters to append
*/
public void appendCharacters(StringBuilder value) {
encodeCurrentBytesIfAny();
result.append(value);
}
/**
* Short for {@code toString().length()} (if possible, use {@link #isEmpty()} instead)
*
* @return length of string representation in characters
*/
public int length() {
return toString().length();
}
/**
* @return true iff nothing has been appended
*/
public boolean isEmpty() {
return currentBytes.length() == 0 && (result == null || result.length() == 0);
}
@Override
public String toString() {
encodeCurrentBytesIfAny();
return result == null ? "" : result.toString();
}
}
|
if (currentCharset.equals(StandardCharsets.ISO_8859_1)) {
if (currentBytes.length() > 0) {
if (result == null) {
result = currentBytes;
currentBytes = new StringBuilder();
} else {
result.append(currentBytes);
currentBytes = new StringBuilder();
}
}
} else if (currentBytes.length() > 0) {
byte[] bytes = currentBytes.toString().getBytes(StandardCharsets.ISO_8859_1);
currentBytes = new StringBuilder();
if (result == null) {
result = new StringBuilder(new String(bytes, currentCharset));
} else {
result.append(new String(bytes, currentCharset));
}
}
| 763
| 197
| 960
|
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/common/GlobalHistogramBinarizer.java
|
GlobalHistogramBinarizer
|
getBlackRow
|
class GlobalHistogramBinarizer extends Binarizer {
private static final int LUMINANCE_BITS = 5;
private static final int LUMINANCE_SHIFT = 8 - LUMINANCE_BITS;
private static final int LUMINANCE_BUCKETS = 1 << LUMINANCE_BITS;
private static final byte[] EMPTY = new byte[0];
private byte[] luminances;
private final int[] buckets;
public GlobalHistogramBinarizer(LuminanceSource source) {
super(source);
luminances = EMPTY;
buckets = new int[LUMINANCE_BUCKETS];
}
// Applies simple sharpening to the row data to improve performance of the 1D Readers.
@Override
public BitArray getBlackRow(int y, BitArray row) throws NotFoundException {<FILL_FUNCTION_BODY>}
// Does not sharpen the data, as this call is intended to only be used by 2D Readers.
@Override
public BitMatrix getBlackMatrix() throws NotFoundException {
LuminanceSource source = getLuminanceSource();
int width = source.getWidth();
int height = source.getHeight();
BitMatrix matrix = new BitMatrix(width, height);
// Quickly calculates the histogram by sampling four rows from the image. This proved to be
// more robust on the blackbox tests than sampling a diagonal as we used to do.
initArrays(width);
int[] localBuckets = buckets;
for (int y = 1; y < 5; y++) {
int row = height * y / 5;
byte[] localLuminances = source.getRow(row, luminances);
int right = (width * 4) / 5;
for (int x = width / 5; x < right; x++) {
int pixel = localLuminances[x] & 0xff;
localBuckets[pixel >> LUMINANCE_SHIFT]++;
}
}
int blackPoint = estimateBlackPoint(localBuckets);
// We delay reading the entire image luminance until the black point estimation succeeds.
// Although we end up reading four rows twice, it is consistent with our motto of
// "fail quickly" which is necessary for continuous scanning.
byte[] localLuminances = source.getMatrix();
for (int y = 0; y < height; y++) {
int offset = y * width;
for (int x = 0; x < width; x++) {
int pixel = localLuminances[offset + x] & 0xff;
if (pixel < blackPoint) {
matrix.set(x, y);
}
}
}
return matrix;
}
@Override
public Binarizer createBinarizer(LuminanceSource source) {
return new GlobalHistogramBinarizer(source);
}
private void initArrays(int luminanceSize) {
if (luminances.length < luminanceSize) {
luminances = new byte[luminanceSize];
}
for (int x = 0; x < LUMINANCE_BUCKETS; x++) {
buckets[x] = 0;
}
}
private static int estimateBlackPoint(int[] buckets) throws NotFoundException {
// Find the tallest peak in the histogram.
int numBuckets = buckets.length;
int maxBucketCount = 0;
int firstPeak = 0;
int firstPeakSize = 0;
for (int x = 0; x < numBuckets; x++) {
if (buckets[x] > firstPeakSize) {
firstPeak = x;
firstPeakSize = buckets[x];
}
if (buckets[x] > maxBucketCount) {
maxBucketCount = buckets[x];
}
}
// Find the second-tallest peak which is somewhat far from the tallest peak.
int secondPeak = 0;
int secondPeakScore = 0;
for (int x = 0; x < numBuckets; x++) {
int distanceToBiggest = x - firstPeak;
// Encourage more distant second peaks by multiplying by square of distance.
int score = buckets[x] * distanceToBiggest * distanceToBiggest;
if (score > secondPeakScore) {
secondPeak = x;
secondPeakScore = score;
}
}
// Make sure firstPeak corresponds to the black peak.
if (firstPeak > secondPeak) {
int temp = firstPeak;
firstPeak = secondPeak;
secondPeak = temp;
}
// If there is too little contrast in the image to pick a meaningful black point, throw rather
// than waste time trying to decode the image, and risk false positives.
if (secondPeak - firstPeak <= numBuckets / 16) {
throw NotFoundException.getNotFoundInstance();
}
// Find a valley between them that is low and closer to the white peak.
int bestValley = secondPeak - 1;
int bestValleyScore = -1;
for (int x = secondPeak - 1; x > firstPeak; x--) {
int fromFirst = x - firstPeak;
int score = fromFirst * fromFirst * (secondPeak - x) * (maxBucketCount - buckets[x]);
if (score > bestValleyScore) {
bestValley = x;
bestValleyScore = score;
}
}
return bestValley << LUMINANCE_SHIFT;
}
}
|
LuminanceSource source = getLuminanceSource();
int width = source.getWidth();
if (row == null || row.getSize() < width) {
row = new BitArray(width);
} else {
row.clear();
}
initArrays(width);
byte[] localLuminances = source.getRow(y, luminances);
int[] localBuckets = buckets;
for (int x = 0; x < width; x++) {
localBuckets[(localLuminances[x] & 0xff) >> LUMINANCE_SHIFT]++;
}
int blackPoint = estimateBlackPoint(localBuckets);
if (width < 3) {
// Special case for very small images
for (int x = 0; x < width; x++) {
if ((localLuminances[x] & 0xff) < blackPoint) {
row.set(x);
}
}
} else {
int left = localLuminances[0] & 0xff;
int center = localLuminances[1] & 0xff;
for (int x = 1; x < width - 1; x++) {
int right = localLuminances[x + 1] & 0xff;
// A simple -1 4 -1 box filter with a weight of 2.
if (((center * 4) - left - right) / 2 < blackPoint) {
row.set(x);
}
left = center;
center = right;
}
}
return row;
| 1,448
| 405
| 1,853
|
<methods>public abstract com.google.zxing.Binarizer createBinarizer(com.google.zxing.LuminanceSource) ,public abstract com.google.zxing.common.BitMatrix getBlackMatrix() throws com.google.zxing.NotFoundException,public abstract com.google.zxing.common.BitArray getBlackRow(int, com.google.zxing.common.BitArray) throws com.google.zxing.NotFoundException,public final int getHeight() ,public final com.google.zxing.LuminanceSource getLuminanceSource() ,public final int getWidth() <variables>private final non-sealed com.google.zxing.LuminanceSource source
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/common/GridSampler.java
|
GridSampler
|
checkAndNudgePoints
|
class GridSampler {
private static GridSampler gridSampler = new DefaultGridSampler();
/**
* Sets the implementation of GridSampler used by the library. One global
* instance is stored, which may sound problematic. But, the implementation provided
* ought to be appropriate for the entire platform, and all uses of this library
* in the whole lifetime of the JVM. For instance, an Android activity can swap in
* an implementation that takes advantage of native platform libraries.
*
* @param newGridSampler The platform-specific object to install.
*/
public static void setGridSampler(GridSampler newGridSampler) {
gridSampler = newGridSampler;
}
/**
* @return the current implementation of GridSampler
*/
public static GridSampler getInstance() {
return gridSampler;
}
/**
* Samples an image for a rectangular matrix of bits of the given dimension. The sampling
* transformation is determined by the coordinates of 4 points, in the original and transformed
* image space.
*
* @param image image to sample
* @param dimensionX width of {@link BitMatrix} to sample from image
* @param dimensionY height of {@link BitMatrix} to sample from image
* @param p1ToX point 1 preimage X
* @param p1ToY point 1 preimage Y
* @param p2ToX point 2 preimage X
* @param p2ToY point 2 preimage Y
* @param p3ToX point 3 preimage X
* @param p3ToY point 3 preimage Y
* @param p4ToX point 4 preimage X
* @param p4ToY point 4 preimage Y
* @param p1FromX point 1 image X
* @param p1FromY point 1 image Y
* @param p2FromX point 2 image X
* @param p2FromY point 2 image Y
* @param p3FromX point 3 image X
* @param p3FromY point 3 image Y
* @param p4FromX point 4 image X
* @param p4FromY point 4 image Y
* @return {@link BitMatrix} representing a grid of points sampled from the image within a region
* defined by the "from" parameters
* @throws NotFoundException if image can't be sampled, for example, if the transformation defined
* by the given points is invalid or results in sampling outside the image boundaries
*/
public abstract BitMatrix sampleGrid(BitMatrix image,
int dimensionX,
int dimensionY,
float p1ToX, float p1ToY,
float p2ToX, float p2ToY,
float p3ToX, float p3ToY,
float p4ToX, float p4ToY,
float p1FromX, float p1FromY,
float p2FromX, float p2FromY,
float p3FromX, float p3FromY,
float p4FromX, float p4FromY) throws NotFoundException;
public abstract BitMatrix sampleGrid(BitMatrix image,
int dimensionX,
int dimensionY,
PerspectiveTransform transform) throws NotFoundException;
/**
* <p>Checks a set of points that have been transformed to sample points on an image against
* the image's dimensions to see if the point are even within the image.</p>
*
* <p>This method will actually "nudge" the endpoints back onto the image if they are found to be
* barely (less than 1 pixel) off the image. This accounts for imperfect detection of finder
* patterns in an image where the QR Code runs all the way to the image border.</p>
*
* <p>For efficiency, the method will check points from either end of the line until one is found
* to be within the image. Because the set of points are assumed to be linear, this is valid.</p>
*
* @param image image into which the points should map
* @param points actual points in x1,y1,...,xn,yn form
* @throws NotFoundException if an endpoint is lies outside the image boundaries
*/
protected static void checkAndNudgePoints(BitMatrix image,
float[] points) throws NotFoundException {<FILL_FUNCTION_BODY>}
}
|
int width = image.getWidth();
int height = image.getHeight();
// Check and nudge points from start until we see some that are OK:
boolean nudged = true;
int maxOffset = points.length - 1; // points.length must be even
for (int offset = 0; offset < maxOffset && nudged; offset += 2) {
int x = (int) points[offset];
int y = (int) points[offset + 1];
if (x < -1 || x > width || y < -1 || y > height) {
throw NotFoundException.getNotFoundInstance();
}
nudged = false;
if (x == -1) {
points[offset] = 0.0f;
nudged = true;
} else if (x == width) {
points[offset] = width - 1;
nudged = true;
}
if (y == -1) {
points[offset + 1] = 0.0f;
nudged = true;
} else if (y == height) {
points[offset + 1] = height - 1;
nudged = true;
}
}
// Check and nudge points from end:
nudged = true;
for (int offset = points.length - 2; offset >= 0 && nudged; offset -= 2) {
int x = (int) points[offset];
int y = (int) points[offset + 1];
if (x < -1 || x > width || y < -1 || y > height) {
throw NotFoundException.getNotFoundInstance();
}
nudged = false;
if (x == -1) {
points[offset] = 0.0f;
nudged = true;
} else if (x == width) {
points[offset] = width - 1;
nudged = true;
}
if (y == -1) {
points[offset + 1] = 0.0f;
nudged = true;
} else if (y == height) {
points[offset + 1] = height - 1;
nudged = true;
}
}
| 1,078
| 552
| 1,630
|
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/common/PerspectiveTransform.java
|
PerspectiveTransform
|
times
|
class PerspectiveTransform {
private final float a11;
private final float a12;
private final float a13;
private final float a21;
private final float a22;
private final float a23;
private final float a31;
private final float a32;
private final float a33;
private PerspectiveTransform(float a11, float a21, float a31,
float a12, float a22, float a32,
float a13, float a23, float a33) {
this.a11 = a11;
this.a12 = a12;
this.a13 = a13;
this.a21 = a21;
this.a22 = a22;
this.a23 = a23;
this.a31 = a31;
this.a32 = a32;
this.a33 = a33;
}
public static PerspectiveTransform quadrilateralToQuadrilateral(float x0, float y0,
float x1, float y1,
float x2, float y2,
float x3, float y3,
float x0p, float y0p,
float x1p, float y1p,
float x2p, float y2p,
float x3p, float y3p) {
PerspectiveTransform qToS = quadrilateralToSquare(x0, y0, x1, y1, x2, y2, x3, y3);
PerspectiveTransform sToQ = squareToQuadrilateral(x0p, y0p, x1p, y1p, x2p, y2p, x3p, y3p);
return sToQ.times(qToS);
}
public void transformPoints(float[] points) {
float a11 = this.a11;
float a12 = this.a12;
float a13 = this.a13;
float a21 = this.a21;
float a22 = this.a22;
float a23 = this.a23;
float a31 = this.a31;
float a32 = this.a32;
float a33 = this.a33;
int maxI = points.length - 1; // points.length must be even
for (int i = 0; i < maxI; i += 2) {
float x = points[i];
float y = points[i + 1];
float denominator = a13 * x + a23 * y + a33;
points[i] = (a11 * x + a21 * y + a31) / denominator;
points[i + 1] = (a12 * x + a22 * y + a32) / denominator;
}
}
public void transformPoints(float[] xValues, float[] yValues) {
int n = xValues.length;
for (int i = 0; i < n; i++) {
float x = xValues[i];
float y = yValues[i];
float denominator = a13 * x + a23 * y + a33;
xValues[i] = (a11 * x + a21 * y + a31) / denominator;
yValues[i] = (a12 * x + a22 * y + a32) / denominator;
}
}
public static PerspectiveTransform squareToQuadrilateral(float x0, float y0,
float x1, float y1,
float x2, float y2,
float x3, float y3) {
float dx3 = x0 - x1 + x2 - x3;
float dy3 = y0 - y1 + y2 - y3;
if (dx3 == 0.0f && dy3 == 0.0f) {
// Affine
return new PerspectiveTransform(x1 - x0, x2 - x1, x0,
y1 - y0, y2 - y1, y0,
0.0f, 0.0f, 1.0f);
} else {
float dx1 = x1 - x2;
float dx2 = x3 - x2;
float dy1 = y1 - y2;
float dy2 = y3 - y2;
float denominator = dx1 * dy2 - dx2 * dy1;
float a13 = (dx3 * dy2 - dx2 * dy3) / denominator;
float a23 = (dx1 * dy3 - dx3 * dy1) / denominator;
return new PerspectiveTransform(x1 - x0 + a13 * x1, x3 - x0 + a23 * x3, x0,
y1 - y0 + a13 * y1, y3 - y0 + a23 * y3, y0,
a13, a23, 1.0f);
}
}
public static PerspectiveTransform quadrilateralToSquare(float x0, float y0,
float x1, float y1,
float x2, float y2,
float x3, float y3) {
// Here, the adjoint serves as the inverse:
return squareToQuadrilateral(x0, y0, x1, y1, x2, y2, x3, y3).buildAdjoint();
}
PerspectiveTransform buildAdjoint() {
// Adjoint is the transpose of the cofactor matrix:
return new PerspectiveTransform(a22 * a33 - a23 * a32,
a23 * a31 - a21 * a33,
a21 * a32 - a22 * a31,
a13 * a32 - a12 * a33,
a11 * a33 - a13 * a31,
a12 * a31 - a11 * a32,
a12 * a23 - a13 * a22,
a13 * a21 - a11 * a23,
a11 * a22 - a12 * a21);
}
PerspectiveTransform times(PerspectiveTransform other) {<FILL_FUNCTION_BODY>}
}
|
return new PerspectiveTransform(a11 * other.a11 + a21 * other.a12 + a31 * other.a13,
a11 * other.a21 + a21 * other.a22 + a31 * other.a23,
a11 * other.a31 + a21 * other.a32 + a31 * other.a33,
a12 * other.a11 + a22 * other.a12 + a32 * other.a13,
a12 * other.a21 + a22 * other.a22 + a32 * other.a23,
a12 * other.a31 + a22 * other.a32 + a32 * other.a33,
a13 * other.a11 + a23 * other.a12 + a33 * other.a13,
a13 * other.a21 + a23 * other.a22 + a33 * other.a23,
a13 * other.a31 + a23 * other.a32 + a33 * other.a33);
| 1,625
| 298
| 1,923
|
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/common/detector/MathUtils.java
|
MathUtils
|
distance
|
class MathUtils {
private MathUtils() {
}
/**
* Ends up being a bit faster than {@link Math#round(float)}. This merely rounds its
* argument to the nearest int, where x.5 rounds up to x+1. Semantics of this shortcut
* differ slightly from {@link Math#round(float)} in that half rounds down for negative
* values. -2.5 rounds to -3, not -2. For purposes here it makes no difference.
*
* @param d real value to round
* @return nearest {@code int}
*/
public static int round(float d) {
return (int) (d + (d < 0.0f ? -0.5f : 0.5f));
}
/**
* @param aX point A x coordinate
* @param aY point A y coordinate
* @param bX point B x coordinate
* @param bY point B y coordinate
* @return Euclidean distance between points A and B
*/
public static float distance(float aX, float aY, float bX, float bY) {
double xDiff = aX - bX;
double yDiff = aY - bY;
return (float) Math.sqrt(xDiff * xDiff + yDiff * yDiff);
}
/**
* @param aX point A x coordinate
* @param aY point A y coordinate
* @param bX point B x coordinate
* @param bY point B y coordinate
* @return Euclidean distance between points A and B
*/
public static float distance(int aX, int aY, int bX, int bY) {<FILL_FUNCTION_BODY>}
/**
* @param array values to sum
* @return sum of values in array
*/
public static int sum(int[] array) {
int count = 0;
for (int a : array) {
count += a;
}
return count;
}
}
|
double xDiff = aX - bX;
double yDiff = aY - bY;
return (float) Math.sqrt(xDiff * xDiff + yDiff * yDiff);
| 496
| 49
| 545
|
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/common/reedsolomon/GenericGF.java
|
GenericGF
|
buildMonomial
|
class GenericGF {
public static final GenericGF AZTEC_DATA_12 = new GenericGF(0b1000001101001, 4096, 1); // x^12 + x^6 + x^5 + x^3 + 1
public static final GenericGF AZTEC_DATA_10 = new GenericGF(0b10000001001, 1024, 1); // x^10 + x^3 + 1
public static final GenericGF AZTEC_DATA_6 = new GenericGF(0b1000011, 64, 1); // x^6 + x + 1
public static final GenericGF AZTEC_PARAM = new GenericGF(0b10011, 16, 1); // x^4 + x + 1
public static final GenericGF QR_CODE_FIELD_256 = new GenericGF(0b100011101, 256, 0); // x^8 + x^4 + x^3 + x^2 + 1
public static final GenericGF DATA_MATRIX_FIELD_256 = new GenericGF(0b100101101, 256, 1); // x^8 + x^5 + x^3 + x^2 + 1
public static final GenericGF AZTEC_DATA_8 = DATA_MATRIX_FIELD_256;
public static final GenericGF MAXICODE_FIELD_64 = AZTEC_DATA_6;
private final int[] expTable;
private final int[] logTable;
private final GenericGFPoly zero;
private final GenericGFPoly one;
private final int size;
private final int primitive;
private final int generatorBase;
/**
* Create a representation of GF(size) using the given primitive polynomial.
*
* @param primitive irreducible polynomial whose coefficients are represented by
* the bits of an int, where the least-significant bit represents the constant
* coefficient
* @param size the size of the field
* @param b the factor b in the generator polynomial can be 0- or 1-based
* (g(x) = (x+a^b)(x+a^(b+1))...(x+a^(b+2t-1))).
* In most cases it should be 1, but for QR code it is 0.
*/
public GenericGF(int primitive, int size, int b) {
this.primitive = primitive;
this.size = size;
this.generatorBase = b;
expTable = new int[size];
logTable = new int[size];
int x = 1;
for (int i = 0; i < size; i++) {
expTable[i] = x;
x *= 2; // 2 (the polynomial x) is a primitive element
if (x >= size) {
x ^= primitive;
x &= size - 1;
}
}
for (int i = 0; i < size - 1; i++) {
logTable[expTable[i]] = i;
}
// logTable[0] == 0 but this should never be used
zero = new GenericGFPoly(this, new int[]{0});
one = new GenericGFPoly(this, new int[]{1});
}
GenericGFPoly getZero() {
return zero;
}
GenericGFPoly getOne() {
return one;
}
/**
* @return the monomial representing coefficient * x^degree
*/
GenericGFPoly buildMonomial(int degree, int coefficient) {<FILL_FUNCTION_BODY>}
/**
* Implements both addition and subtraction -- they are the same in GF(size).
*
* @return sum/difference of a and b
*/
static int addOrSubtract(int a, int b) {
return a ^ b;
}
/**
* @return 2 to the power of a in GF(size)
*/
int exp(int a) {
return expTable[a];
}
/**
* @return base 2 log of a in GF(size)
*/
int log(int a) {
if (a == 0) {
throw new IllegalArgumentException();
}
return logTable[a];
}
/**
* @return multiplicative inverse of a
*/
int inverse(int a) {
if (a == 0) {
throw new ArithmeticException();
}
return expTable[size - logTable[a] - 1];
}
/**
* @return product of a and b in GF(size)
*/
int multiply(int a, int b) {
if (a == 0 || b == 0) {
return 0;
}
return expTable[(logTable[a] + logTable[b]) % (size - 1)];
}
public int getSize() {
return size;
}
public int getGeneratorBase() {
return generatorBase;
}
@Override
public String toString() {
return "GF(0x" + Integer.toHexString(primitive) + ',' + size + ')';
}
}
|
if (degree < 0) {
throw new IllegalArgumentException();
}
if (coefficient == 0) {
return zero;
}
int[] coefficients = new int[degree + 1];
coefficients[0] = coefficient;
return new GenericGFPoly(this, coefficients);
| 1,381
| 76
| 1,457
|
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/common/reedsolomon/ReedSolomonEncoder.java
|
ReedSolomonEncoder
|
buildGenerator
|
class ReedSolomonEncoder {
private final GenericGF field;
private final List<GenericGFPoly> cachedGenerators;
public ReedSolomonEncoder(GenericGF field) {
this.field = field;
this.cachedGenerators = new ArrayList<>();
cachedGenerators.add(new GenericGFPoly(field, new int[]{1}));
}
private GenericGFPoly buildGenerator(int degree) {<FILL_FUNCTION_BODY>}
public void encode(int[] toEncode, int ecBytes) {
if (ecBytes == 0) {
throw new IllegalArgumentException("No error correction bytes");
}
int dataBytes = toEncode.length - ecBytes;
if (dataBytes <= 0) {
throw new IllegalArgumentException("No data bytes provided");
}
GenericGFPoly generator = buildGenerator(ecBytes);
int[] infoCoefficients = new int[dataBytes];
System.arraycopy(toEncode, 0, infoCoefficients, 0, dataBytes);
GenericGFPoly info = new GenericGFPoly(field, infoCoefficients);
info = info.multiplyByMonomial(ecBytes, 1);
GenericGFPoly remainder = info.divide(generator)[1];
int[] coefficients = remainder.getCoefficients();
int numZeroCoefficients = ecBytes - coefficients.length;
for (int i = 0; i < numZeroCoefficients; i++) {
toEncode[dataBytes + i] = 0;
}
System.arraycopy(coefficients, 0, toEncode, dataBytes + numZeroCoefficients, coefficients.length);
}
}
|
if (degree >= cachedGenerators.size()) {
GenericGFPoly lastGenerator = cachedGenerators.get(cachedGenerators.size() - 1);
for (int d = cachedGenerators.size(); d <= degree; d++) {
GenericGFPoly nextGenerator = lastGenerator.multiply(
new GenericGFPoly(field, new int[] { 1, field.exp(d - 1 + field.getGeneratorBase()) }));
cachedGenerators.add(nextGenerator);
lastGenerator = nextGenerator;
}
}
return cachedGenerators.get(degree);
| 428
| 152
| 580
|
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/datamatrix/DataMatrixReader.java
|
DataMatrixReader
|
extractPureBits
|
class DataMatrixReader implements Reader {
private static final ResultPoint[] NO_POINTS = new ResultPoint[0];
private final Decoder decoder = new Decoder();
/**
* Locates and decodes a Data Matrix code in an image.
*
* @return a String representing the content encoded by the Data Matrix code
* @throws NotFoundException if a Data Matrix code cannot be found
* @throws FormatException if a Data Matrix code cannot be decoded
* @throws ChecksumException if error correction fails
*/
@Override
public Result decode(BinaryBitmap image) throws NotFoundException, ChecksumException, FormatException {
return decode(image, null);
}
@Override
public Result decode(BinaryBitmap image, Map<DecodeHintType,?> hints)
throws NotFoundException, ChecksumException, FormatException {
DecoderResult decoderResult;
ResultPoint[] points;
if (hints != null && hints.containsKey(DecodeHintType.PURE_BARCODE)) {
BitMatrix bits = extractPureBits(image.getBlackMatrix());
decoderResult = decoder.decode(bits);
points = NO_POINTS;
} else {
DetectorResult detectorResult = new Detector(image.getBlackMatrix()).detect();
decoderResult = decoder.decode(detectorResult.getBits());
points = detectorResult.getPoints();
}
Result result = new Result(decoderResult.getText(), decoderResult.getRawBytes(), points,
BarcodeFormat.DATA_MATRIX);
List<byte[]> byteSegments = decoderResult.getByteSegments();
if (byteSegments != null) {
result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, byteSegments);
}
String ecLevel = decoderResult.getECLevel();
if (ecLevel != null) {
result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel);
}
result.putMetadata(ResultMetadataType.ERRORS_CORRECTED, decoderResult.getErrorsCorrected());
result.putMetadata(ResultMetadataType.SYMBOLOGY_IDENTIFIER, "]d" + decoderResult.getSymbologyModifier());
return result;
}
@Override
public void reset() {
// do nothing
}
/**
* This method detects a code in a "pure" image -- that is, pure monochrome image
* which contains only an unrotated, unskewed, image of a code, with some white border
* around it. This is a specialized method that works exceptionally fast in this special
* case.
*/
private static BitMatrix extractPureBits(BitMatrix image) throws NotFoundException {<FILL_FUNCTION_BODY>}
private static int moduleSize(int[] leftTopBlack, BitMatrix image) throws NotFoundException {
int width = image.getWidth();
int x = leftTopBlack[0];
int y = leftTopBlack[1];
while (x < width && image.get(x, y)) {
x++;
}
if (x == width) {
throw NotFoundException.getNotFoundInstance();
}
int moduleSize = x - leftTopBlack[0];
if (moduleSize == 0) {
throw NotFoundException.getNotFoundInstance();
}
return moduleSize;
}
}
|
int[] leftTopBlack = image.getTopLeftOnBit();
int[] rightBottomBlack = image.getBottomRightOnBit();
if (leftTopBlack == null || rightBottomBlack == null) {
throw NotFoundException.getNotFoundInstance();
}
int moduleSize = moduleSize(leftTopBlack, image);
int top = leftTopBlack[1];
int bottom = rightBottomBlack[1];
int left = leftTopBlack[0];
int right = rightBottomBlack[0];
int matrixWidth = (right - left + 1) / moduleSize;
int matrixHeight = (bottom - top + 1) / moduleSize;
if (matrixWidth <= 0 || matrixHeight <= 0) {
throw NotFoundException.getNotFoundInstance();
}
// Push in the "border" by half the module width so that we start
// sampling in the middle of the module. Just in case the image is a
// little off, this will help recover.
int nudge = moduleSize / 2;
top += nudge;
left += nudge;
// Now just read off the bits
BitMatrix bits = new BitMatrix(matrixWidth, matrixHeight);
for (int y = 0; y < matrixHeight; y++) {
int iOffset = top + y * moduleSize;
for (int x = 0; x < matrixWidth; x++) {
if (image.get(left + x * moduleSize, iOffset)) {
bits.set(x, y);
}
}
}
return bits;
| 868
| 385
| 1,253
|
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/datamatrix/DataMatrixWriter.java
|
DataMatrixWriter
|
encode
|
class DataMatrixWriter implements Writer {
@Override
public BitMatrix encode(String contents, BarcodeFormat format, int width, int height) {
return encode(contents, format, width, height, null);
}
@Override
public BitMatrix encode(String contents, BarcodeFormat format, int width, int height, Map<EncodeHintType,?> hints) {<FILL_FUNCTION_BODY>}
/**
* Encode the given symbol info to a bit matrix.
*
* @param placement The DataMatrix placement.
* @param symbolInfo The symbol info to encode.
* @return The bit matrix generated.
*/
private static BitMatrix encodeLowLevel(DefaultPlacement placement, SymbolInfo symbolInfo, int width, int height) {
int symbolWidth = symbolInfo.getSymbolDataWidth();
int symbolHeight = symbolInfo.getSymbolDataHeight();
ByteMatrix matrix = new ByteMatrix(symbolInfo.getSymbolWidth(), symbolInfo.getSymbolHeight());
int matrixY = 0;
for (int y = 0; y < symbolHeight; y++) {
// Fill the top edge with alternate 0 / 1
int matrixX;
if ((y % symbolInfo.matrixHeight) == 0) {
matrixX = 0;
for (int x = 0; x < symbolInfo.getSymbolWidth(); x++) {
matrix.set(matrixX, matrixY, (x % 2) == 0);
matrixX++;
}
matrixY++;
}
matrixX = 0;
for (int x = 0; x < symbolWidth; x++) {
// Fill the right edge with full 1
if ((x % symbolInfo.matrixWidth) == 0) {
matrix.set(matrixX, matrixY, true);
matrixX++;
}
matrix.set(matrixX, matrixY, placement.getBit(x, y));
matrixX++;
// Fill the right edge with alternate 0 / 1
if ((x % symbolInfo.matrixWidth) == symbolInfo.matrixWidth - 1) {
matrix.set(matrixX, matrixY, (y % 2) == 0);
matrixX++;
}
}
matrixY++;
// Fill the bottom edge with full 1
if ((y % symbolInfo.matrixHeight) == symbolInfo.matrixHeight - 1) {
matrixX = 0;
for (int x = 0; x < symbolInfo.getSymbolWidth(); x++) {
matrix.set(matrixX, matrixY, true);
matrixX++;
}
matrixY++;
}
}
return convertByteMatrixToBitMatrix(matrix, width, height);
}
/**
* Convert the ByteMatrix to BitMatrix.
*
* @param reqHeight The requested height of the image (in pixels) with the Datamatrix code
* @param reqWidth The requested width of the image (in pixels) with the Datamatrix code
* @param matrix The input matrix.
* @return The output matrix.
*/
private static BitMatrix convertByteMatrixToBitMatrix(ByteMatrix matrix, int reqWidth, int reqHeight) {
int matrixWidth = matrix.getWidth();
int matrixHeight = matrix.getHeight();
int outputWidth = Math.max(reqWidth, matrixWidth);
int outputHeight = Math.max(reqHeight, matrixHeight);
int multiple = Math.min(outputWidth / matrixWidth, outputHeight / matrixHeight);
int leftPadding = (outputWidth - (matrixWidth * multiple)) / 2 ;
int topPadding = (outputHeight - (matrixHeight * multiple)) / 2 ;
BitMatrix output;
// remove padding if requested width and height are too small
if (reqHeight < matrixHeight || reqWidth < matrixWidth) {
leftPadding = 0;
topPadding = 0;
output = new BitMatrix(matrixWidth, matrixHeight);
} else {
output = new BitMatrix(reqWidth, reqHeight);
}
output.clear();
for (int inputY = 0, outputY = topPadding; inputY < matrixHeight; inputY++, outputY += multiple) {
// Write the contents of this row of the bytematrix
for (int inputX = 0, outputX = leftPadding; inputX < matrixWidth; inputX++, outputX += multiple) {
if (matrix.get(inputX, inputY) == 1) {
output.setRegion(outputX, outputY, multiple, multiple);
}
}
}
return output;
}
}
|
if (contents.isEmpty()) {
throw new IllegalArgumentException("Found empty contents");
}
if (format != BarcodeFormat.DATA_MATRIX) {
throw new IllegalArgumentException("Can only encode DATA_MATRIX, but got " + format);
}
if (width < 0 || height < 0) {
throw new IllegalArgumentException("Requested dimensions can't be negative: " + width + 'x' + height);
}
// Try to get force shape & min / max size
SymbolShapeHint shape = SymbolShapeHint.FORCE_NONE;
Dimension minSize = null;
Dimension maxSize = null;
if (hints != null) {
SymbolShapeHint requestedShape = (SymbolShapeHint) hints.get(EncodeHintType.DATA_MATRIX_SHAPE);
if (requestedShape != null) {
shape = requestedShape;
}
@SuppressWarnings("deprecation")
Dimension requestedMinSize = (Dimension) hints.get(EncodeHintType.MIN_SIZE);
if (requestedMinSize != null) {
minSize = requestedMinSize;
}
@SuppressWarnings("deprecation")
Dimension requestedMaxSize = (Dimension) hints.get(EncodeHintType.MAX_SIZE);
if (requestedMaxSize != null) {
maxSize = requestedMaxSize;
}
}
//1. step: Data encodation
String encoded;
boolean hasCompactionHint = hints != null && hints.containsKey(EncodeHintType.DATA_MATRIX_COMPACT) &&
Boolean.parseBoolean(hints.get(EncodeHintType.DATA_MATRIX_COMPACT).toString());
if (hasCompactionHint) {
boolean hasGS1FormatHint = hints.containsKey(EncodeHintType.GS1_FORMAT) &&
Boolean.parseBoolean(hints.get(EncodeHintType.GS1_FORMAT).toString());
Charset charset = null;
boolean hasEncodingHint = hints.containsKey(EncodeHintType.CHARACTER_SET);
if (hasEncodingHint) {
charset = Charset.forName(hints.get(EncodeHintType.CHARACTER_SET).toString());
}
encoded = MinimalEncoder.encodeHighLevel(contents, charset, hasGS1FormatHint ? 0x1D : -1, shape);
} else {
boolean hasForceC40Hint = hints != null && hints.containsKey(EncodeHintType.FORCE_C40) &&
Boolean.parseBoolean(hints.get(EncodeHintType.FORCE_C40).toString());
encoded = HighLevelEncoder.encodeHighLevel(contents, shape, minSize, maxSize, hasForceC40Hint);
}
SymbolInfo symbolInfo = SymbolInfo.lookup(encoded.length(), shape, minSize, maxSize, true);
//2. step: ECC generation
String codewords = ErrorCorrection.encodeECC200(encoded, symbolInfo);
//3. step: Module placement in Matrix
DefaultPlacement placement =
new DefaultPlacement(codewords, symbolInfo.getSymbolDataWidth(), symbolInfo.getSymbolDataHeight());
placement.place();
//4. step: low-level encoding
return encodeLowLevel(placement, symbolInfo, width, height);
| 1,143
| 872
| 2,015
|
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/datamatrix/decoder/DataBlock.java
|
DataBlock
|
getDataBlocks
|
class DataBlock {
private final int numDataCodewords;
private final byte[] codewords;
private DataBlock(int numDataCodewords, byte[] codewords) {
this.numDataCodewords = numDataCodewords;
this.codewords = codewords;
}
/**
* <p>When Data Matrix Codes use multiple data blocks, they actually interleave the bytes of each of them.
* That is, the first byte of data block 1 to n is written, then the second bytes, and so on. This
* method will separate the data into original blocks.</p>
*
* @param rawCodewords bytes as read directly from the Data Matrix Code
* @param version version of the Data Matrix Code
* @return DataBlocks containing original bytes, "de-interleaved" from representation in the
* Data Matrix Code
*/
static DataBlock[] getDataBlocks(byte[] rawCodewords,
Version version) {<FILL_FUNCTION_BODY>}
int getNumDataCodewords() {
return numDataCodewords;
}
byte[] getCodewords() {
return codewords;
}
}
|
// Figure out the number and size of data blocks used by this version
Version.ECBlocks ecBlocks = version.getECBlocks();
// First count the total number of data blocks
int totalBlocks = 0;
Version.ECB[] ecBlockArray = ecBlocks.getECBlocks();
for (Version.ECB ecBlock : ecBlockArray) {
totalBlocks += ecBlock.getCount();
}
// Now establish DataBlocks of the appropriate size and number of data codewords
DataBlock[] result = new DataBlock[totalBlocks];
int numResultBlocks = 0;
for (Version.ECB ecBlock : ecBlockArray) {
for (int i = 0; i < ecBlock.getCount(); i++) {
int numDataCodewords = ecBlock.getDataCodewords();
int numBlockCodewords = ecBlocks.getECCodewords() + numDataCodewords;
result[numResultBlocks++] = new DataBlock(numDataCodewords, new byte[numBlockCodewords]);
}
}
// All blocks have the same amount of data, except that the last n
// (where n may be 0) have 1 less byte. Figure out where these start.
// TODO(bbrown): There is only one case where there is a difference for Data Matrix for size 144
int longerBlocksTotalCodewords = result[0].codewords.length;
//int shorterBlocksTotalCodewords = longerBlocksTotalCodewords - 1;
int longerBlocksNumDataCodewords = longerBlocksTotalCodewords - ecBlocks.getECCodewords();
int shorterBlocksNumDataCodewords = longerBlocksNumDataCodewords - 1;
// The last elements of result may be 1 element shorter for 144 matrix
// first fill out as many elements as all of them have minus 1
int rawCodewordsOffset = 0;
for (int i = 0; i < shorterBlocksNumDataCodewords; i++) {
for (int j = 0; j < numResultBlocks; j++) {
result[j].codewords[i] = rawCodewords[rawCodewordsOffset++];
}
}
// Fill out the last data block in the longer ones
boolean specialVersion = version.getVersionNumber() == 24;
int numLongerBlocks = specialVersion ? 8 : numResultBlocks;
for (int j = 0; j < numLongerBlocks; j++) {
result[j].codewords[longerBlocksNumDataCodewords - 1] = rawCodewords[rawCodewordsOffset++];
}
// Now add in error correction blocks
int max = result[0].codewords.length;
for (int i = longerBlocksNumDataCodewords; i < max; i++) {
for (int j = 0; j < numResultBlocks; j++) {
int jOffset = specialVersion ? (j + 8) % numResultBlocks : j;
int iOffset = specialVersion && jOffset > 7 ? i - 1 : i;
result[jOffset].codewords[iOffset] = rawCodewords[rawCodewordsOffset++];
}
}
if (rawCodewordsOffset != rawCodewords.length) {
throw new IllegalArgumentException();
}
return result;
| 291
| 822
| 1,113
|
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/datamatrix/decoder/Decoder.java
|
Decoder
|
decode
|
class Decoder {
private final ReedSolomonDecoder rsDecoder;
public Decoder() {
rsDecoder = new ReedSolomonDecoder(GenericGF.DATA_MATRIX_FIELD_256);
}
/**
* <p>Convenience method that can decode a Data Matrix Code represented as a 2D array of booleans.
* "true" is taken to mean a black module.</p>
*
* @param image booleans representing white/black Data Matrix Code modules
* @return text and bytes encoded within the Data Matrix Code
* @throws FormatException if the Data Matrix Code cannot be decoded
* @throws ChecksumException if error correction fails
*/
public DecoderResult decode(boolean[][] image) throws FormatException, ChecksumException {
return decode(BitMatrix.parse(image));
}
/**
* <p>Decodes a Data Matrix Code represented as a {@link BitMatrix}. A 1 or "true" is taken
* to mean a black module.</p>
*
* @param bits booleans representing white/black Data Matrix Code modules
* @return text and bytes encoded within the Data Matrix Code
* @throws FormatException if the Data Matrix Code cannot be decoded
* @throws ChecksumException if error correction fails
*/
public DecoderResult decode(BitMatrix bits) throws FormatException, ChecksumException {<FILL_FUNCTION_BODY>}
/**
* <p>Given data and error-correction codewords received, possibly corrupted by errors, attempts to
* correct the errors in-place using Reed-Solomon error correction.</p>
*
* @param codewordBytes data and error correction codewords
* @param numDataCodewords number of codewords that are data bytes
* @return the number of errors corrected
* @throws ChecksumException if error correction fails
*/
private int correctErrors(byte[] codewordBytes, int numDataCodewords) throws ChecksumException {
int numCodewords = codewordBytes.length;
// First read into an array of ints
int[] codewordsInts = new int[numCodewords];
for (int i = 0; i < numCodewords; i++) {
codewordsInts[i] = codewordBytes[i] & 0xFF;
}
int errorsCorrected = 0;
try {
errorsCorrected = rsDecoder.decodeWithECCount(codewordsInts, codewordBytes.length - numDataCodewords);
} catch (ReedSolomonException ignored) {
throw ChecksumException.getChecksumInstance();
}
// Copy back into array of bytes -- only need to worry about the bytes that were data
// We don't care about errors in the error-correction codewords
for (int i = 0; i < numDataCodewords; i++) {
codewordBytes[i] = (byte) codewordsInts[i];
}
return errorsCorrected;
}
}
|
// Construct a parser and read version, error-correction level
BitMatrixParser parser = new BitMatrixParser(bits);
Version version = parser.getVersion();
// Read codewords
byte[] codewords = parser.readCodewords();
// Separate into data blocks
DataBlock[] dataBlocks = DataBlock.getDataBlocks(codewords, version);
// Count total number of data bytes
int totalBytes = 0;
for (DataBlock db : dataBlocks) {
totalBytes += db.getNumDataCodewords();
}
byte[] resultBytes = new byte[totalBytes];
int errorsCorrected = 0;
int dataBlocksCount = dataBlocks.length;
// Error-correct and copy data blocks together into a stream of bytes
for (int j = 0; j < dataBlocksCount; j++) {
DataBlock dataBlock = dataBlocks[j];
byte[] codewordBytes = dataBlock.getCodewords();
int numDataCodewords = dataBlock.getNumDataCodewords();
errorsCorrected += correctErrors(codewordBytes, numDataCodewords);
for (int i = 0; i < numDataCodewords; i++) {
// De-interlace data blocks.
resultBytes[i * dataBlocksCount + j] = codewordBytes[i];
}
}
// Decode the contents of that stream of bytes
DecoderResult result = DecodedBitStreamParser.decode(resultBytes);
result.setErrorsCorrected(errorsCorrected);
return result;
| 758
| 387
| 1,145
|
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/datamatrix/encoder/ASCIIEncoder.java
|
ASCIIEncoder
|
encodeASCIIDigits
|
class ASCIIEncoder implements Encoder {
@Override
public int getEncodingMode() {
return HighLevelEncoder.ASCII_ENCODATION;
}
@Override
public void encode(EncoderContext context) {
//step B
int n = HighLevelEncoder.determineConsecutiveDigitCount(context.getMessage(), context.pos);
if (n >= 2) {
context.writeCodeword(encodeASCIIDigits(context.getMessage().charAt(context.pos),
context.getMessage().charAt(context.pos + 1)));
context.pos += 2;
} else {
char c = context.getCurrentChar();
int newMode = HighLevelEncoder.lookAheadTest(context.getMessage(), context.pos, getEncodingMode());
if (newMode != getEncodingMode()) {
switch (newMode) {
case HighLevelEncoder.BASE256_ENCODATION:
context.writeCodeword(HighLevelEncoder.LATCH_TO_BASE256);
context.signalEncoderChange(HighLevelEncoder.BASE256_ENCODATION);
return;
case HighLevelEncoder.C40_ENCODATION:
context.writeCodeword(HighLevelEncoder.LATCH_TO_C40);
context.signalEncoderChange(HighLevelEncoder.C40_ENCODATION);
return;
case HighLevelEncoder.X12_ENCODATION:
context.writeCodeword(HighLevelEncoder.LATCH_TO_ANSIX12);
context.signalEncoderChange(HighLevelEncoder.X12_ENCODATION);
break;
case HighLevelEncoder.TEXT_ENCODATION:
context.writeCodeword(HighLevelEncoder.LATCH_TO_TEXT);
context.signalEncoderChange(HighLevelEncoder.TEXT_ENCODATION);
break;
case HighLevelEncoder.EDIFACT_ENCODATION:
context.writeCodeword(HighLevelEncoder.LATCH_TO_EDIFACT);
context.signalEncoderChange(HighLevelEncoder.EDIFACT_ENCODATION);
break;
default:
throw new IllegalStateException("Illegal mode: " + newMode);
}
} else if (HighLevelEncoder.isExtendedASCII(c)) {
context.writeCodeword(HighLevelEncoder.UPPER_SHIFT);
context.writeCodeword((char) (c - 128 + 1));
context.pos++;
} else {
context.writeCodeword((char) (c + 1));
context.pos++;
}
}
}
private static char encodeASCIIDigits(char digit1, char digit2) {<FILL_FUNCTION_BODY>}
}
|
if (HighLevelEncoder.isDigit(digit1) && HighLevelEncoder.isDigit(digit2)) {
int num = (digit1 - 48) * 10 + (digit2 - 48);
return (char) (num + 130);
}
throw new IllegalArgumentException("not digits: " + digit1 + digit2);
| 715
| 98
| 813
|
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/datamatrix/encoder/Base256Encoder.java
|
Base256Encoder
|
encode
|
class Base256Encoder implements Encoder {
@Override
public int getEncodingMode() {
return HighLevelEncoder.BASE256_ENCODATION;
}
@Override
public void encode(EncoderContext context) {<FILL_FUNCTION_BODY>}
private static char randomize255State(char ch, int codewordPosition) {
int pseudoRandom = ((149 * codewordPosition) % 255) + 1;
int tempVariable = ch + pseudoRandom;
if (tempVariable <= 255) {
return (char) tempVariable;
} else {
return (char) (tempVariable - 256);
}
}
}
|
StringBuilder buffer = new StringBuilder();
buffer.append('\0'); //Initialize length field
while (context.hasMoreCharacters()) {
char c = context.getCurrentChar();
buffer.append(c);
context.pos++;
int newMode = HighLevelEncoder.lookAheadTest(context.getMessage(), context.pos, getEncodingMode());
if (newMode != getEncodingMode()) {
// Return to ASCII encodation, which will actually handle latch to new mode
context.signalEncoderChange(HighLevelEncoder.ASCII_ENCODATION);
break;
}
}
int dataCount = buffer.length() - 1;
int lengthFieldSize = 1;
int currentSize = context.getCodewordCount() + dataCount + lengthFieldSize;
context.updateSymbolInfo(currentSize);
boolean mustPad = (context.getSymbolInfo().getDataCapacity() - currentSize) > 0;
if (context.hasMoreCharacters() || mustPad) {
if (dataCount <= 249) {
buffer.setCharAt(0, (char) dataCount);
} else if (dataCount <= 1555) {
buffer.setCharAt(0, (char) ((dataCount / 250) + 249));
buffer.insert(1, (char) (dataCount % 250));
} else {
throw new IllegalStateException(
"Message length not in valid ranges: " + dataCount);
}
}
for (int i = 0, c = buffer.length(); i < c; i++) {
context.writeCodeword(randomize255State(
buffer.charAt(i), context.getCodewordCount() + 1));
}
| 183
| 441
| 624
|
<no_super_class>
|
zxing_zxing
|
zxing/core/src/main/java/com/google/zxing/datamatrix/encoder/C40Encoder.java
|
C40Encoder
|
encodeChar
|
class C40Encoder implements Encoder {
@Override
public int getEncodingMode() {
return HighLevelEncoder.C40_ENCODATION;
}
void encodeMaximal(EncoderContext context) {
StringBuilder buffer = new StringBuilder();
int lastCharSize = 0;
int backtrackStartPosition = context.pos;
int backtrackBufferLength = 0;
while (context.hasMoreCharacters()) {
char c = context.getCurrentChar();
context.pos++;
lastCharSize = encodeChar(c, buffer);
if (buffer.length() % 3 == 0) {
backtrackStartPosition = context.pos;
backtrackBufferLength = buffer.length();
}
}
if (backtrackBufferLength != buffer.length()) {
int unwritten = (buffer.length() / 3) * 2;
int curCodewordCount = context.getCodewordCount() + unwritten + 1; // +1 for the latch to C40
context.updateSymbolInfo(curCodewordCount);
int available = context.getSymbolInfo().getDataCapacity() - curCodewordCount;
int rest = buffer.length() % 3;
if ((rest == 2 && available != 2) ||
(rest == 1 && (lastCharSize > 3 || available != 1))) {
buffer.setLength(backtrackBufferLength);
context.pos = backtrackStartPosition;
}
}
if (buffer.length() > 0) {
context.writeCodeword(HighLevelEncoder.LATCH_TO_C40);
}
handleEOD(context, buffer);
}
@Override
public void encode(EncoderContext context) {
//step C
StringBuilder buffer = new StringBuilder();
while (context.hasMoreCharacters()) {
char c = context.getCurrentChar();
context.pos++;
int lastCharSize = encodeChar(c, buffer);
int unwritten = (buffer.length() / 3) * 2;
int curCodewordCount = context.getCodewordCount() + unwritten;
context.updateSymbolInfo(curCodewordCount);
int available = context.getSymbolInfo().getDataCapacity() - curCodewordCount;
if (!context.hasMoreCharacters()) {
//Avoid having a single C40 value in the last triplet
StringBuilder removed = new StringBuilder();
if ((buffer.length() % 3) == 2 && available != 2) {
lastCharSize = backtrackOneCharacter(context, buffer, removed, lastCharSize);
}
while ((buffer.length() % 3) == 1 && (lastCharSize > 3 || available != 1)) {
lastCharSize = backtrackOneCharacter(context, buffer, removed, lastCharSize);
}
break;
}
int count = buffer.length();
if ((count % 3) == 0) {
int newMode = HighLevelEncoder.lookAheadTest(context.getMessage(), context.pos, getEncodingMode());
if (newMode != getEncodingMode()) {
// Return to ASCII encodation, which will actually handle latch to new mode
context.signalEncoderChange(HighLevelEncoder.ASCII_ENCODATION);
break;
}
}
}
handleEOD(context, buffer);
}
private int backtrackOneCharacter(EncoderContext context,
StringBuilder buffer, StringBuilder removed, int lastCharSize) {
int count = buffer.length();
buffer.delete(count - lastCharSize, count);
context.pos--;
char c = context.getCurrentChar();
lastCharSize = encodeChar(c, removed);
context.resetSymbolInfo(); //Deal with possible reduction in symbol size
return lastCharSize;
}
static void writeNextTriplet(EncoderContext context, StringBuilder buffer) {
context.writeCodewords(encodeToCodewords(buffer));
buffer.delete(0, 3);
}
/**
* Handle "end of data" situations
*
* @param context the encoder context
* @param buffer the buffer with the remaining encoded characters
*/
void handleEOD(EncoderContext context, StringBuilder buffer) {
int unwritten = (buffer.length() / 3) * 2;
int rest = buffer.length() % 3;
int curCodewordCount = context.getCodewordCount() + unwritten;
context.updateSymbolInfo(curCodewordCount);
int available = context.getSymbolInfo().getDataCapacity() - curCodewordCount;
if (rest == 2) {
buffer.append('\0'); //Shift 1
while (buffer.length() >= 3) {
writeNextTriplet(context, buffer);
}
if (context.hasMoreCharacters()) {
context.writeCodeword(HighLevelEncoder.C40_UNLATCH);
}
} else if (available == 1 && rest == 1) {
while (buffer.length() >= 3) {
writeNextTriplet(context, buffer);
}
if (context.hasMoreCharacters()) {
context.writeCodeword(HighLevelEncoder.C40_UNLATCH);
}
// else no unlatch
context.pos--;
} else if (rest == 0) {
while (buffer.length() >= 3) {
writeNextTriplet(context, buffer);
}
if (available > 0 || context.hasMoreCharacters()) {
context.writeCodeword(HighLevelEncoder.C40_UNLATCH);
}
} else {
throw new IllegalStateException("Unexpected case. Please report!");
}
context.signalEncoderChange(HighLevelEncoder.ASCII_ENCODATION);
}
int encodeChar(char c, StringBuilder sb) {<FILL_FUNCTION_BODY>}
private static String encodeToCodewords(CharSequence sb) {
int v = (1600 * sb.charAt(0)) + (40 * sb.charAt(1)) + sb.charAt(2) + 1;
char cw1 = (char) (v / 256);
char cw2 = (char) (v % 256);
return new String(new char[] {cw1, cw2});
}
}
|
if (c == ' ') {
sb.append('\3');
return 1;
}
if (c >= '0' && c <= '9') {
sb.append((char) (c - 48 + 4));
return 1;
}
if (c >= 'A' && c <= 'Z') {
sb.append((char) (c - 65 + 14));
return 1;
}
if (c < ' ') {
sb.append('\0'); //Shift 1 Set
sb.append(c);
return 2;
}
if (c <= '/') {
sb.append('\1'); //Shift 2 Set
sb.append((char) (c - 33));
return 2;
}
if (c <= '@') {
sb.append('\1'); //Shift 2 Set
sb.append((char) (c - 58 + 15));
return 2;
}
if (c <= '_') {
sb.append('\1'); //Shift 2 Set
sb.append((char) (c - 91 + 22));
return 2;
}
if (c <= 127) {
sb.append('\2'); //Shift 3 Set
sb.append((char) (c - 96));
return 2;
}
sb.append("\1\u001e"); //Shift 2, Upper Shift
int len = 2;
len += encodeChar((char) (c - 128), sb);
return len;
| 1,606
| 407
| 2,013
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.