blob_id stringlengths 40 40 | __id__ int64 225 39,780B | directory_id stringlengths 40 40 | path stringlengths 6 313 | content_id stringlengths 40 40 | detected_licenses list | license_type stringclasses 2
values | repo_name stringlengths 6 132 | repo_url stringlengths 25 151 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 70 | visit_date timestamp[ns] | revision_date timestamp[ns] | committer_date timestamp[ns] | github_id int64 7.28k 689M ⌀ | star_events_count int64 0 131k | fork_events_count int64 0 48k | gha_license_id stringclasses 23
values | gha_fork bool 2
classes | gha_event_created_at timestamp[ns] | gha_created_at timestamp[ns] | gha_updated_at timestamp[ns] | gha_pushed_at timestamp[ns] | gha_size int64 0 40.4M ⌀ | gha_stargazers_count int32 0 112k ⌀ | gha_forks_count int32 0 39.4k ⌀ | gha_open_issues_count int32 0 11k ⌀ | gha_language stringlengths 1 21 ⌀ | gha_archived bool 2
classes | gha_disabled bool 1
class | content stringlengths 7 4.37M | src_encoding stringlengths 3 16 | language stringclasses 1
value | length_bytes int64 7 4.37M | extension stringclasses 24
values | filename stringlengths 4 174 | language_id stringclasses 1
value | entities list | contaminating_dataset stringclasses 0
values | malware_signatures list | redacted_content stringlengths 7 4.37M | redacted_length_bytes int64 7 4.37M | alphanum_fraction float32 0.25 0.94 | alpha_fraction float32 0.25 0.94 | num_lines int32 1 84k | avg_line_length float32 0.76 99.9 | std_line_length float32 0 220 | max_line_length int32 5 998 | is_vendor bool 2
classes | is_generated bool 1
class | max_hex_length int32 0 319 | hex_fraction float32 0 0.38 | max_unicode_length int32 0 408 | unicode_fraction float32 0 0.36 | max_base64_length int32 0 506 | base64_fraction float32 0 0.5 | avg_csv_sep_count float32 0 4 | is_autogen_header bool 1
class | is_empty_html bool 1
class | shard stringclasses 16
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
568e22a1a41f47848b02254647d0ebf51bac2d89 | 15,633,681,019,542 | 7d0669cd73ca1bd5bdf89a42adada2c8ca3c3577 | /src/main/java/Application.java | a3b3bebc0b2fbdf2eb6f889a536fa5e680417543 | [] | no_license | offthebench/java-advanced-features | https://github.com/offthebench/java-advanced-features | a5f3cc9a8582bf81c3327eda89abb10060fab594 | f44d12a2c17a366df590d0bd08a3e31f637f71f4 | refs/heads/master | 2023-03-09T18:46:51.038000 | 2021-02-21T08:04:31 | 2021-02-21T08:04:31 | 340,640,849 | 0 | 2 | null | false | 2021-02-20T21:23:15 | 2021-02-20T11:43:32 | 2021-02-20T11:45:58 | 2021-02-20T11:45:56 | 11 | 0 | 1 | 1 | Java | false | false | import QuestionTwo.entity.Product;
import QuestionTwo.entity.SmallProduct;
import QuestionTwo.entity.SmallWarehouse;
import QuestionTwo.entity.Warehouse;
import QuestionTwo.repository.SmallWarehouseRepository;
import com.sun.tools.javac.util.List;
import reader.Reader;
import reader.ReaderFactory;
import writer.WriterFactory;
import writer.WriterType;
import java.io.FileReader;
public class Application {
public static void main(String[] args) {
// SmallWarehouseRepository repository = SmallWarehouseRepository.getInstance();
// repository.initializeWarehouse();
//
// Warehouse warehouse = repository.displayDetails(1L);
// System.out.println(warehouse.getName());
//
// Warehouse warehouse2 = repository.displayDetails(2L);
// System.out.println(warehouse2.getName());
//
// Warehouse warehouse3 = repository.displayDetails(3L);
// System.out.println(warehouse3.getName());
//
// Warehouse warehouse4 = new SmallWarehouse(4L, "Janpath Warehouse");
// repository.add(warehouse4);
//
//
// Product product1 = new SmallProduct("Chicken", 2.40);
// Product product2 = new SmallProduct("Eggs", 1.30);
//
// repository.addProduct(4L, List.of(product1, product2));
//
// System.out.println(repository.displayDetails(4L).getProducts().get(0).getName());
// System.out.println(repository.averagePriceOfProducts(4l));
String read = ReaderFactory.getInstance().getReader("output/fileWriter.txt").read();
WriterFactory.getInstance().getWriter(WriterType.CONSOLE).write(read);
}
}
| UTF-8 | Java | 1,608 | java | Application.java | Java | [] | null | [] | import QuestionTwo.entity.Product;
import QuestionTwo.entity.SmallProduct;
import QuestionTwo.entity.SmallWarehouse;
import QuestionTwo.entity.Warehouse;
import QuestionTwo.repository.SmallWarehouseRepository;
import com.sun.tools.javac.util.List;
import reader.Reader;
import reader.ReaderFactory;
import writer.WriterFactory;
import writer.WriterType;
import java.io.FileReader;
public class Application {
public static void main(String[] args) {
// SmallWarehouseRepository repository = SmallWarehouseRepository.getInstance();
// repository.initializeWarehouse();
//
// Warehouse warehouse = repository.displayDetails(1L);
// System.out.println(warehouse.getName());
//
// Warehouse warehouse2 = repository.displayDetails(2L);
// System.out.println(warehouse2.getName());
//
// Warehouse warehouse3 = repository.displayDetails(3L);
// System.out.println(warehouse3.getName());
//
// Warehouse warehouse4 = new SmallWarehouse(4L, "Janpath Warehouse");
// repository.add(warehouse4);
//
//
// Product product1 = new SmallProduct("Chicken", 2.40);
// Product product2 = new SmallProduct("Eggs", 1.30);
//
// repository.addProduct(4L, List.of(product1, product2));
//
// System.out.println(repository.displayDetails(4L).getProducts().get(0).getName());
// System.out.println(repository.averagePriceOfProducts(4l));
String read = ReaderFactory.getInstance().getReader("output/fileWriter.txt").read();
WriterFactory.getInstance().getWriter(WriterType.CONSOLE).write(read);
}
}
| 1,608 | 0.712687 | 0.697761 | 45 | 34.733334 | 28.74671 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.733333 | false | false | 12 |
50ea1c0e4388435edcc73c4efb53aca14742ad64 | 37,512,244,371,777 | 7cd2f013e61af95eef8cece56b355a90eaaa4dd5 | /scitemav-tp/src/main/java/com/scitemav/bean/TipoVehiculoBean.java | 782841ff855412d61dedbbc306975e0f8305d08d | [] | no_license | savepap20141-TP/SCITEMAVTP2014 | https://github.com/savepap20141-TP/SCITEMAVTP2014 | de7be5e7e142c452a76142c1961f3b0ffdba2d40 | 78aee55bed16f179b4c2d106e3cb7a3cf1ed4c14 | refs/heads/master | 2020-06-02T13:23:00.869000 | 2014-06-27T04:17:30 | 2014-06-27T04:17:30 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.scitemav.bean;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
public class TipoVehiculoBean {
private Integer idTipoVehiculo;
private String nombre;
private String urlImagen;
private CommonsMultipartFile file;
public Integer getIdTipoVehiculo() {
return idTipoVehiculo;
}
public void setIdTipoVehiculo(Integer idTipoVehiculo) {
this.idTipoVehiculo = idTipoVehiculo;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getUrlImagen() {
return urlImagen;
}
public void setUrlImagen(String urlImagen) {
this.urlImagen = urlImagen;
}
public CommonsMultipartFile getFile() {
return file;
}
public void setFile(CommonsMultipartFile file) {
this.file = file;
}
}
| UTF-8 | Java | 853 | java | TipoVehiculoBean.java | Java | [] | null | [] | package com.scitemav.bean;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
public class TipoVehiculoBean {
private Integer idTipoVehiculo;
private String nombre;
private String urlImagen;
private CommonsMultipartFile file;
public Integer getIdTipoVehiculo() {
return idTipoVehiculo;
}
public void setIdTipoVehiculo(Integer idTipoVehiculo) {
this.idTipoVehiculo = idTipoVehiculo;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getUrlImagen() {
return urlImagen;
}
public void setUrlImagen(String urlImagen) {
this.urlImagen = urlImagen;
}
public CommonsMultipartFile getFile() {
return file;
}
public void setFile(CommonsMultipartFile file) {
this.file = file;
}
}
| 853 | 0.722157 | 0.722157 | 40 | 19.325001 | 18.390741 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.375 | false | false | 12 |
adee981048efa5dc2320a5b9714e5bed6c199636 | 6,287,832,180,383 | 4e9b195be0254b6d61619811e633294a3e313b87 | /sources/com/xiaomi/smarthome/framework/crash/PluginCrashHandler.java | 541d8fb7935a9d08631a8de0102974458bf4a902 | [] | no_license | TonyDongGuaPi/mihome-src | https://github.com/TonyDongGuaPi/mihome-src | 2fb9c950ce8220a26525599b1b1ae1d05767f707 | 19c0df3277d2bc652f16f8fe825ce5f5f323e9a1 | refs/heads/master | 2022-04-08T16:27:09.759000 | 2020-03-03T21:40:30 | 2020-03-03T21:40:30 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.xiaomi.smarthome.framework.crash;
import android.content.Context;
import com.xiaomi.plugin.core.XmPluginPackage;
import com.xiaomi.smarthome.application.CommonApplication;
import com.xiaomi.smarthome.frame.core.CoreApi;
import com.xiaomi.smarthome.frame.plugin.PluginRuntimeManager;
import com.xiaomi.smarthome.frame.plugin.runtime.activity.PluginHostActivity;
import com.xiaomi.smarthome.framework.api.AsyncResponseCallback;
import com.xiaomi.smarthome.framework.commonapi.CommonApiV2;
import com.xiaomi.smarthome.framework.log.MyLog;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.Thread;
import java.util.ArrayList;
public class PluginCrashHandler implements Thread.UncaughtExceptionHandler {
/* renamed from: a reason: collision with root package name */
public static final int f1536a = 5000;
private Context b;
private Thread.UncaughtExceptionHandler c = Thread.getDefaultUncaughtExceptionHandler();
public PluginCrashHandler(Context context) {
this.b = context;
}
public static void a(Throwable th, long j, long j2) {
if (th != null) {
StringWriter stringWriter = new StringWriter();
th.printStackTrace(new PrintWriter(stringWriter));
String obj = stringWriter.toString();
if (obj.length() > 5000) {
obj.substring(0, 5000);
}
if (th != null) {
th.getStackTrace()[0].getClassName();
}
if (th != null) {
th.getStackTrace()[0].getMethodName();
}
a(CommonApplication.getAppContext(), th, j, j2, (AsyncResponseCallback<Void>) null);
MyLog.a(th);
}
}
private static void a(Context context, Throwable th, long j, long j2, AsyncResponseCallback<Void> asyncResponseCallback) {
Throwable th2 = th;
if (th2 != null) {
String str = "";
String str2 = "";
StackTraceElement[] stackTrace = th.getStackTrace();
if (stackTrace != null && stackTrace.length > 0) {
str = stackTrace[0].getClassName();
str2 = stackTrace[0].getMethodName();
}
String str3 = str;
String str4 = str2;
StringWriter stringWriter = new StringWriter();
th2.printStackTrace(new PrintWriter(stringWriter));
String str5 = "===plugin crash===\npluginId=" + j + "\npkgId=" + j2 + "\n";
try {
str5 = str5 + "userId=" + CoreApi.a().s() + "\n";
} catch (Exception unused) {
}
String str6 = str5 + stringWriter.toString();
if (str6.length() > 5000) {
str6 = str6.substring(0, 5000);
}
CommonApiV2.a().a(context, j, j2, str3, str4, str6, asyncResponseCallback);
}
}
public void uncaughtException(Thread thread, Throwable th) {
XmPluginPackage xmPluginPackage;
long j;
PluginHostActivity topPluginHostActivity;
if (th != null) {
th.printStackTrace();
try {
StackTraceElement[] stackTrace = th.getStackTrace();
ArrayList arrayList = new ArrayList();
int i = 0;
int length = stackTrace.length;
while (i < length && i < 6) {
arrayList.add(stackTrace[i].getClassName());
i++;
}
xmPluginPackage = PluginRuntimeManager.getInstance().getXmPluginPackageByCrashClassName(arrayList);
} catch (Exception unused) {
xmPluginPackage = null;
}
if (xmPluginPackage == null && (topPluginHostActivity = PluginHostActivity.getTopPluginHostActivity()) != null) {
xmPluginPackage = topPluginHostActivity.getXmPluginPackage();
}
long j2 = 0;
if (xmPluginPackage != null) {
if (xmPluginPackage != null) {
j2 = xmPluginPackage.getPluginId();
j = xmPluginPackage.getPackageId();
} else {
j = 0;
}
a(th, j2, j);
} else {
a(th, 0, 0);
}
}
if (this.c != null) {
this.c.uncaughtException(thread, th);
}
}
}
| UTF-8 | Java | 4,433 | java | PluginCrashHandler.java | Java | [] | null | [] | package com.xiaomi.smarthome.framework.crash;
import android.content.Context;
import com.xiaomi.plugin.core.XmPluginPackage;
import com.xiaomi.smarthome.application.CommonApplication;
import com.xiaomi.smarthome.frame.core.CoreApi;
import com.xiaomi.smarthome.frame.plugin.PluginRuntimeManager;
import com.xiaomi.smarthome.frame.plugin.runtime.activity.PluginHostActivity;
import com.xiaomi.smarthome.framework.api.AsyncResponseCallback;
import com.xiaomi.smarthome.framework.commonapi.CommonApiV2;
import com.xiaomi.smarthome.framework.log.MyLog;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.Thread;
import java.util.ArrayList;
public class PluginCrashHandler implements Thread.UncaughtExceptionHandler {
/* renamed from: a reason: collision with root package name */
public static final int f1536a = 5000;
private Context b;
private Thread.UncaughtExceptionHandler c = Thread.getDefaultUncaughtExceptionHandler();
public PluginCrashHandler(Context context) {
this.b = context;
}
public static void a(Throwable th, long j, long j2) {
if (th != null) {
StringWriter stringWriter = new StringWriter();
th.printStackTrace(new PrintWriter(stringWriter));
String obj = stringWriter.toString();
if (obj.length() > 5000) {
obj.substring(0, 5000);
}
if (th != null) {
th.getStackTrace()[0].getClassName();
}
if (th != null) {
th.getStackTrace()[0].getMethodName();
}
a(CommonApplication.getAppContext(), th, j, j2, (AsyncResponseCallback<Void>) null);
MyLog.a(th);
}
}
private static void a(Context context, Throwable th, long j, long j2, AsyncResponseCallback<Void> asyncResponseCallback) {
Throwable th2 = th;
if (th2 != null) {
String str = "";
String str2 = "";
StackTraceElement[] stackTrace = th.getStackTrace();
if (stackTrace != null && stackTrace.length > 0) {
str = stackTrace[0].getClassName();
str2 = stackTrace[0].getMethodName();
}
String str3 = str;
String str4 = str2;
StringWriter stringWriter = new StringWriter();
th2.printStackTrace(new PrintWriter(stringWriter));
String str5 = "===plugin crash===\npluginId=" + j + "\npkgId=" + j2 + "\n";
try {
str5 = str5 + "userId=" + CoreApi.a().s() + "\n";
} catch (Exception unused) {
}
String str6 = str5 + stringWriter.toString();
if (str6.length() > 5000) {
str6 = str6.substring(0, 5000);
}
CommonApiV2.a().a(context, j, j2, str3, str4, str6, asyncResponseCallback);
}
}
public void uncaughtException(Thread thread, Throwable th) {
XmPluginPackage xmPluginPackage;
long j;
PluginHostActivity topPluginHostActivity;
if (th != null) {
th.printStackTrace();
try {
StackTraceElement[] stackTrace = th.getStackTrace();
ArrayList arrayList = new ArrayList();
int i = 0;
int length = stackTrace.length;
while (i < length && i < 6) {
arrayList.add(stackTrace[i].getClassName());
i++;
}
xmPluginPackage = PluginRuntimeManager.getInstance().getXmPluginPackageByCrashClassName(arrayList);
} catch (Exception unused) {
xmPluginPackage = null;
}
if (xmPluginPackage == null && (topPluginHostActivity = PluginHostActivity.getTopPluginHostActivity()) != null) {
xmPluginPackage = topPluginHostActivity.getXmPluginPackage();
}
long j2 = 0;
if (xmPluginPackage != null) {
if (xmPluginPackage != null) {
j2 = xmPluginPackage.getPluginId();
j = xmPluginPackage.getPackageId();
} else {
j = 0;
}
a(th, j2, j);
} else {
a(th, 0, 0);
}
}
if (this.c != null) {
this.c.uncaughtException(thread, th);
}
}
}
| 4,433 | 0.569141 | 0.554252 | 113 | 38.230087 | 26.686647 | 126 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.752212 | false | false | 12 |
9516afb32aa1d43db7241528d2f32c4d68cc6109 | 10,282,151,741,882 | e3fc69143e127a4109768d20a89d204d75d22469 | /pinyougou_cart_web/src/main/java/com/pinyougou/cart/controller/PayController.java | f4aa5842308754c3890ba807b47a26861f53d239 | [] | no_license | fcq666/pinyougou | https://github.com/fcq666/pinyougou | fc97d4cbc9e6244b8c497263c625feb9dc6c113d | ba7bab9edb4ed65d9460e01c88f2d63a624b2807 | refs/heads/master | 2020-06-14T01:19:17.955000 | 2019-07-18T00:18:41 | 2019-07-18T00:18:42 | 194,848,439 | 0 | 0 | null | false | 2020-06-15T21:35:28 | 2019-07-02T11:16:05 | 2019-07-18T00:19:30 | 2020-06-15T21:35:27 | 14,045 | 0 | 0 | 1 | JavaScript | false | false | package com.pinyougou.cart.controller;
import com.alibaba.dubbo.config.annotation.Reference;
import com.pinyougou.common.utils.IdWorker;
import com.pinyougou.order.service.OrderService;
import com.pinyougou.pay.service.WeixinPayService;
import com.pinyougou.pojo.TbPayLog;
import entity.Result;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
@RequestMapping("/pay")
public class PayController {
@Reference
private WeixinPayService weixinPayService;
@Reference
private OrderService orderService;
/**
* 生成二维码
*
* @return
*/
@RequestMapping("/createNative")
public Map createNative() {
/*IdWorker idworker = new IdWorker(0, 1);
return weixinPayService.createNative(idworker.nextId() + "", "1");*/
/*优化*/
/*获取redis订单号,和金额*/
String name = SecurityContextHolder.getContext().getAuthentication().getName();
TbPayLog tbPayLog = orderService.getPaylogFromRedis(name);
Map<String, String> map = weixinPayService.createNative(tbPayLog.getOutTradeNo(), tbPayLog.getTotalFee() + "");
return map;
}
/*传入雪花算法的生成的订单id*/
@RequestMapping("/queryStatus")
public Result queryStatus(String out_trade_no) throws InterruptedException {
Result result = new Result(false, "支付失败");
//调用支付服务,查询订单状态,5分钟过期5*60/3秒=100次
int count = 0;
try {
while (true) {
Map<String, String> resultMap = weixinPayService.queryStatus(out_trade_no);
count++;
System.out.println("支付中。。。。。。");
/*过期,为了测试超时设置次数多一点*/
/* if (count >= 100) {*/
if (count >= 20) {
result = new Result(false, "支付超时");
break;
}
/*3秒调用一次方法*/
Thread.sleep(3000);
/*固定写法*/
if ("SUCCESS".equals(resultMap.get("trade_state"))) {
//更新日志的记录,(交易流水,交易状态,交易时间 关联的订单状态和支付时间更新,清空该用户的redis的日志)
//微信返回的交易流水
String transactionId = resultMap.get("transaction_id");
//out_trade_no
orderService.updateStatus(transactionId,out_trade_no);
/*成功则进行返回*/
result = new Result(true, "支付成功");
break;
}
}
return result;
} catch (InterruptedException e) {
e.printStackTrace();
return result;
}
}
} | UTF-8 | Java | 3,050 | java | PayController.java | Java | [] | null | [] | package com.pinyougou.cart.controller;
import com.alibaba.dubbo.config.annotation.Reference;
import com.pinyougou.common.utils.IdWorker;
import com.pinyougou.order.service.OrderService;
import com.pinyougou.pay.service.WeixinPayService;
import com.pinyougou.pojo.TbPayLog;
import entity.Result;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
@RequestMapping("/pay")
public class PayController {
@Reference
private WeixinPayService weixinPayService;
@Reference
private OrderService orderService;
/**
* 生成二维码
*
* @return
*/
@RequestMapping("/createNative")
public Map createNative() {
/*IdWorker idworker = new IdWorker(0, 1);
return weixinPayService.createNative(idworker.nextId() + "", "1");*/
/*优化*/
/*获取redis订单号,和金额*/
String name = SecurityContextHolder.getContext().getAuthentication().getName();
TbPayLog tbPayLog = orderService.getPaylogFromRedis(name);
Map<String, String> map = weixinPayService.createNative(tbPayLog.getOutTradeNo(), tbPayLog.getTotalFee() + "");
return map;
}
/*传入雪花算法的生成的订单id*/
@RequestMapping("/queryStatus")
public Result queryStatus(String out_trade_no) throws InterruptedException {
Result result = new Result(false, "支付失败");
//调用支付服务,查询订单状态,5分钟过期5*60/3秒=100次
int count = 0;
try {
while (true) {
Map<String, String> resultMap = weixinPayService.queryStatus(out_trade_no);
count++;
System.out.println("支付中。。。。。。");
/*过期,为了测试超时设置次数多一点*/
/* if (count >= 100) {*/
if (count >= 20) {
result = new Result(false, "支付超时");
break;
}
/*3秒调用一次方法*/
Thread.sleep(3000);
/*固定写法*/
if ("SUCCESS".equals(resultMap.get("trade_state"))) {
//更新日志的记录,(交易流水,交易状态,交易时间 关联的订单状态和支付时间更新,清空该用户的redis的日志)
//微信返回的交易流水
String transactionId = resultMap.get("transaction_id");
//out_trade_no
orderService.updateStatus(transactionId,out_trade_no);
/*成功则进行返回*/
result = new Result(true, "支付成功");
break;
}
}
return result;
} catch (InterruptedException e) {
e.printStackTrace();
return result;
}
}
} | 3,050 | 0.58376 | 0.575713 | 90 | 29.388889 | 25.889378 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.477778 | false | false | 12 |
4690a57beac3d9157747504053dc0b3b1bd9551a | 16,973,710,755,108 | 4bbb053f8ac24762441ca16fc2a94f39bd6b7ec6 | /src/main/java/com/model/utills/randomnum/RandomNum.java | 2d42caf1277e6f42031d8ab6d54a7d987c955ee0 | [] | no_license | 14787484930/ebook | https://github.com/14787484930/ebook | a914bdd7bfe8f378a5a78498a935efdec63b6cc4 | ab21c3b17dfe675fe5d306b7aabdc0d1b6c49328 | refs/heads/master | 2022-12-21T19:59:20.316000 | 2020-09-05T14:49:57 | 2020-09-05T14:49:57 | 155,587,250 | 4 | 0 | null | false | 2022-12-16T11:32:25 | 2018-10-31T16:13:00 | 2020-09-05T14:50:25 | 2022-12-16T11:32:23 | 1,140 | 2 | 0 | 10 | JavaScript | false | false | package com.model.utills.randomnum;
import java.util.Random;
/**
* @author zxl
* @date 2019/4/8 11:52
* @describe
*/
public class RandomNum {
public static String getRandomNumer(){
Random random = new Random();
String code = "";
for(int i = 0;i<4;i++){
code += random.nextInt(10);
}
return code;
}
public static void main(String[] args) {
for(int i=0 ;i<6;i++){
System.out.println(getRandomNumer());
}
}
}
| UTF-8 | Java | 512 | java | RandomNum.java | Java | [
{
"context": "ndomnum;\n\nimport java.util.Random;\n\n/**\n * @author zxl\n * @date 2019/4/8 11:52\n * @describe\n */\npublic c",
"end": 81,
"score": 0.9996310472488403,
"start": 78,
"tag": "USERNAME",
"value": "zxl"
}
] | null | [] | package com.model.utills.randomnum;
import java.util.Random;
/**
* @author zxl
* @date 2019/4/8 11:52
* @describe
*/
public class RandomNum {
public static String getRandomNumer(){
Random random = new Random();
String code = "";
for(int i = 0;i<4;i++){
code += random.nextInt(10);
}
return code;
}
public static void main(String[] args) {
for(int i=0 ;i<6;i++){
System.out.println(getRandomNumer());
}
}
}
| 512 | 0.537109 | 0.505859 | 28 | 17.285715 | 15.797507 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.392857 | false | false | 12 |
5ad8141adeba0566c3310813010bd0a4e88d52de | 28,656,021,800,579 | d7d41b877ca812e0b37f3e0d87d3c2d0f53548cd | /Server/Bombers/src/com/vensella/bombers/delayedEvents/StandardBomb.java | 3a955f672ad1ba984d3e3859cc581450e28b9604 | [] | no_license | Stasyamba/Bombers---development | https://github.com/Stasyamba/Bombers---development | dcf9d1549dff83910349cad9ff3404a4e5636a2e | dac8654a9956475cfb3ac9b8464e8a67374f619a | refs/heads/master | 2021-05-03T04:24:16.630000 | 2010-12-15T10:11:08 | 2010-12-15T10:11:08 | 1,158,758 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.vensella.bombers.delayedEvents;
import java.util.ArrayList;
import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.entities.data.SFSObject;
import com.vensella.bombers.BombersGameProcess;
import com.vensella.bombers.DynamicGameMap;
import com.vensella.bombers.UserGameParams;
import com.vensella.bombers.gameEvents.GameEvent;
public abstract class StandardBomb extends Bomb {
private static final int BASE_POWER = 2;
public StandardBomb(User owner, int powerBonus, int x, int y) {
super(owner, powerBonus, x, y);
// TODO Auto-generated constructor stub
}
@Override
public long getExplosionDelay() {
return 2000;
}
@Override
public long getExplosionTime() {
return 500;
}
public GameEvent getEvent()
{
final User owner = getOnwer();
return new GameEvent() {
@Override
public void applyOnGame(BombersGameProcess game, DynamicGameMap gf,
ArrayList<UserGameParams> playerStates) {
int x = getX();
int y = getY();
game.trace("Bomb exploded at: " + x + ", " + y + "; Power = " + (BASE_POWER + getPowerBonus()));
//Release bomb
getUserGameParams(owner, playerStates).releaseBomb();
//Destroy walls
//gf.setObjectTypeAt(x, y, DynamicGameMap.ObjectType.EMPTY);
game.removeDynamicObject(x, y);
int power = BASE_POWER + getPowerBonus();
//Up
for (int i = 1; i <= power; ++i)
{
if (gf.getObjectTypeAt(x, y - i) == DynamicGameMap.ObjectType.WALL)
{
game.destroyWallAt(x, y - i);
break;
}
if (gf.getObjectTypeAt(x, y - i) == DynamicGameMap.ObjectType.STRONG_WALL)
{
break;
}
}
//Right
for (int i = 1; i <= power; ++i)
{
if (gf.getObjectTypeAt(x + i, y) == DynamicGameMap.ObjectType.WALL)
{
game.destroyWallAt(x + i, y);
break;
}
if (gf.getObjectTypeAt(x + i, y) == DynamicGameMap.ObjectType.STRONG_WALL)
{
break;
}
}
//Down
for (int i = 1; i <= power; ++i)
{
if (gf.getObjectTypeAt(x, y + i) == DynamicGameMap.ObjectType.WALL)
{
game.destroyWallAt(x, y + i);
break;
}
if (gf.getObjectTypeAt(x, y + i) == DynamicGameMap.ObjectType.STRONG_WALL)
{
break;
}
}
//Left
for (int i = 1; i <= power; ++i)
{
if (gf.getObjectTypeAt(x - i, y) == DynamicGameMap.ObjectType.WALL)
{
game.destroyWallAt(x - i, y);
break;
}
if (gf.getObjectTypeAt(x - i, y) == DynamicGameMap.ObjectType.STRONG_WALL)
{
break;
}
}
//Send message
SFSObject params = new SFSObject();
params.putInt("bomb_power_bonus", 0);
params.putInt("bomb_x", x);
params.putInt("bomb_y", y);
game.send("bomb_exploded", params, game.getParentRoom().getPlayersList());
}
};
}
}
| UTF-8 | Java | 2,848 | java | StandardBomb.java | Java | [] | null | [] | package com.vensella.bombers.delayedEvents;
import java.util.ArrayList;
import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.entities.data.SFSObject;
import com.vensella.bombers.BombersGameProcess;
import com.vensella.bombers.DynamicGameMap;
import com.vensella.bombers.UserGameParams;
import com.vensella.bombers.gameEvents.GameEvent;
public abstract class StandardBomb extends Bomb {
private static final int BASE_POWER = 2;
public StandardBomb(User owner, int powerBonus, int x, int y) {
super(owner, powerBonus, x, y);
// TODO Auto-generated constructor stub
}
@Override
public long getExplosionDelay() {
return 2000;
}
@Override
public long getExplosionTime() {
return 500;
}
public GameEvent getEvent()
{
final User owner = getOnwer();
return new GameEvent() {
@Override
public void applyOnGame(BombersGameProcess game, DynamicGameMap gf,
ArrayList<UserGameParams> playerStates) {
int x = getX();
int y = getY();
game.trace("Bomb exploded at: " + x + ", " + y + "; Power = " + (BASE_POWER + getPowerBonus()));
//Release bomb
getUserGameParams(owner, playerStates).releaseBomb();
//Destroy walls
//gf.setObjectTypeAt(x, y, DynamicGameMap.ObjectType.EMPTY);
game.removeDynamicObject(x, y);
int power = BASE_POWER + getPowerBonus();
//Up
for (int i = 1; i <= power; ++i)
{
if (gf.getObjectTypeAt(x, y - i) == DynamicGameMap.ObjectType.WALL)
{
game.destroyWallAt(x, y - i);
break;
}
if (gf.getObjectTypeAt(x, y - i) == DynamicGameMap.ObjectType.STRONG_WALL)
{
break;
}
}
//Right
for (int i = 1; i <= power; ++i)
{
if (gf.getObjectTypeAt(x + i, y) == DynamicGameMap.ObjectType.WALL)
{
game.destroyWallAt(x + i, y);
break;
}
if (gf.getObjectTypeAt(x + i, y) == DynamicGameMap.ObjectType.STRONG_WALL)
{
break;
}
}
//Down
for (int i = 1; i <= power; ++i)
{
if (gf.getObjectTypeAt(x, y + i) == DynamicGameMap.ObjectType.WALL)
{
game.destroyWallAt(x, y + i);
break;
}
if (gf.getObjectTypeAt(x, y + i) == DynamicGameMap.ObjectType.STRONG_WALL)
{
break;
}
}
//Left
for (int i = 1; i <= power; ++i)
{
if (gf.getObjectTypeAt(x - i, y) == DynamicGameMap.ObjectType.WALL)
{
game.destroyWallAt(x - i, y);
break;
}
if (gf.getObjectTypeAt(x - i, y) == DynamicGameMap.ObjectType.STRONG_WALL)
{
break;
}
}
//Send message
SFSObject params = new SFSObject();
params.putInt("bomb_power_bonus", 0);
params.putInt("bomb_x", x);
params.putInt("bomb_y", y);
game.send("bomb_exploded", params, game.getParentRoom().getPlayersList());
}
};
}
}
| 2,848 | 0.614115 | 0.608848 | 119 | 22.932774 | 23.932936 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.915966 | false | false | 12 |
866fd79537e90824811a0345203d874c4bba5b14 | 1,760,936,598,564 | ec2661b19936c4cb0ae242486c4a3b3484551dd1 | /src/main/java/com/github/vvinston/konfig/ParsedNumber.java | 860758904d7d01589b82a1ff00eea31128698dc4 | [] | no_license | vvinston/konfig | https://github.com/vvinston/konfig | 240eebf89d8bdad911097856209fd894881efb83 | 374e0586921e73b1677a61834a59a6d09b31c13a | refs/heads/master | 2021-03-24T09:37:00.008000 | 2017-07-10T22:12:57 | 2017-07-10T22:12:57 | 96,465,973 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.github.vvinston.konfig;
import java.util.Objects;
final class ParsedNumber extends Number {
private final String number;
ParsedNumber(final String number) {
this.number = Objects.requireNonNull(number);
}
@Override
public int intValue() {
return Integer.parseInt(number);
}
@Override
public long longValue() {
return Long.parseLong(number);
}
@Override
public float floatValue() {
return Float.parseFloat(number);
}
@Override
public double doubleValue() {
return Double.parseDouble(number);
}
}
| UTF-8 | Java | 615 | java | ParsedNumber.java | Java | [
{
"context": "package com.github.vvinston.konfig;\n\nimport java.util.Objects;\n\nfinal class P",
"end": 27,
"score": 0.6681770086288452,
"start": 19,
"tag": "USERNAME",
"value": "vvinston"
}
] | null | [] | package com.github.vvinston.konfig;
import java.util.Objects;
final class ParsedNumber extends Number {
private final String number;
ParsedNumber(final String number) {
this.number = Objects.requireNonNull(number);
}
@Override
public int intValue() {
return Integer.parseInt(number);
}
@Override
public long longValue() {
return Long.parseLong(number);
}
@Override
public float floatValue() {
return Float.parseFloat(number);
}
@Override
public double doubleValue() {
return Double.parseDouble(number);
}
}
| 615 | 0.643902 | 0.643902 | 32 | 18.21875 | 16.857368 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 12 |
6c764290e0dd5c5f448b47b121c162a7e236c65d | 9,208,409,889,424 | 66b797a51db8c8e191c2cc5d2b8651c5cde2d84d | /Spring/Spring-Database/src/main/java/com/cts/product/model/Product.java | 61ba1fb611067ce9c33890371a3375c1932410a1 | [] | no_license | richardsforu/fdcs-java | https://github.com/richardsforu/fdcs-java | f8a64c47040f722b4ae1609180ea153784b77534 | 782efd02dea355a1e6d24fbfe558b9df7887551f | refs/heads/master | 2020-05-22T12:42:03.553000 | 2019-08-08T07:14:21 | 2019-08-08T07:14:21 | 186,345,103 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cts.product.model;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Product {
@Id
private String product_id;
private String product_name;
private double salary;
public String getProduct_id() {
return product_id;
}
public void setProduct_id(String product_id) {
this.product_id = product_id;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
| UTF-8 | Java | 630 | java | Product.java | Java | [] | null | [] | package com.cts.product.model;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Product {
@Id
private String product_id;
private String product_name;
private double salary;
public String getProduct_id() {
return product_id;
}
public void setProduct_id(String product_id) {
this.product_id = product_id;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
| 630 | 0.72381 | 0.72381 | 34 | 17.529411 | 15.421977 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.264706 | false | false | 12 |
a6203da662eb3b38fbb1c52d2c9e0bfe176c70a2 | 9,947,144,265,301 | fcc04df11d063e24627c5be36ef5fc2954e33421 | /src/test/java/edu/escuelaing/arsw/dangerousbet/game/PokerTests.java | bbb2a83b050a94e9ee3c0b068bec44cdb57b87c5 | [] | no_license | AndresDa1302/DangerousBets-ARSW | https://github.com/AndresDa1302/DangerousBets-ARSW | 84593033e2c0fe44c5b9df0834e4d4597ab7eb00 | 868a604c2801ec817a301a81a8fcde6ede513f25 | refs/heads/master | 2023-04-26T10:20:44.980000 | 2021-05-20T12:33:33 | 2021-05-20T12:33:33 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.escuelaing.arsw.dangerousbet.game;
import edu.escuelaing.arsw.dangerousbet.game.impl.Poker;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class PokerTests {
/* @Test
public void agregarJugadores(){
Poker poker = new Poker();
List<String> nickNames = new ArrayList<>();
List<Integer> monedas = new ArrayList<>();
nickNames.add("Juan");
nickNames.add("Andres");
monedas.add(1000);
monedas.add(2000);
poker.iniciarPartida(nickNames,monedas);
Assertions.assertEquals(poker.getJugadores().size(), nickNames.size());
}
@Test
public void apostarConUsuarios() throws JuegoException {
Poker poker = new Poker();
List<String> nickNames = new ArrayList<>();
List<Integer> monedas = new ArrayList<>();
nickNames.add("Juan");
nickNames.add("Andres");
monedas.add(1000);
monedas.add(2000);
poker.iniciarPartida(nickNames,monedas);
Random r = new Random();
int apuesta1 =r.nextInt(200);
int apuesta2 =r.nextInt(200);
poker.apostar("Juan",apuesta1);
poker.apostar("Juan",apuesta2);
Assertions.assertTrue(poker.getApuestaByJugador("Juan")==(apuesta1+apuesta2));
}*/
/*
@Test
public void abandonarRondaSinrecibirCartas(){
Poker poker = new Poker();
List<String> nickNames = new ArrayList<>();
List<Integer> monedas = new ArrayList<>();
nickNames.add("Juan");
nickNames.add("Andres");
nickNames.add("Mario");
monedas.add(1000);
monedas.add(2000);
monedas.add(2000);
poker.iniciarPartida(nickNames,monedas);
poker.jugar();
poker.abandonar();
Assertions.assertTrue((poker.isJugador("Juan") && poker.isJugador("Andres") && !poker.isJugador("Mario")) );
}
@Test
public void abandonarRondaConCartasRecibidas(){
Poker poker = new Poker();
List<String> nickNames = new ArrayList<>();
List<Integer> monedas = new ArrayList<>();
nickNames.add("Juan");
nickNames.add("Andres");
nickNames.add("Mario");
monedas.add(1000);
monedas.add(2000);
monedas.add(2000);
poker.iniciarPartida(nickNames,monedas);
Random r = new Random();
int ite =r.nextInt(nickNames.size());
poker.jugar();
poker.abandonar(nickNames.get(ite));
Assertions.assertTrue(!poker.isJugador(nickNames.get(ite)));
}
*//*
@Test
public void seDebeIgualarLaApuesta(){
Poker poker = new Poker();
List<String> nickNames = new ArrayList<>();
List<Integer> monedas = new ArrayList<>();
nickNames.add("Juan");
nickNames.add("Andres");
nickNames.add("Mario");
monedas.add(1000);
monedas.add(2000);
monedas.add(2000);
poker.iniciarPartida(nickNames,monedas);
try {
poker.apostar("Juan",200);
poker.apostar("Andres",150);
} catch (JuegoException e) {
Assertions.assertTrue(e.getMessage().equals(JuegoException.DEBE_IGUALAR));
}
}
@Test
public void seDebeIgualarOApostarMas(){
Poker poker = new Poker();
List<String> nickNames = new ArrayList<>();
List<Integer> monedas = new ArrayList<>();
nickNames.add("Juan");
nickNames.add("Andres");
nickNames.add("Mario");
monedas.add(1000);
monedas.add(2000);
monedas.add(2000);
poker.iniciarPartida(nickNames,monedas);
try {
poker.apostar("Juan",200);
poker.apostar("Andres",200);
poker.apostar("Juan",25);
Assertions.assertTrue(poker.getApuestaByJugador("Juan")==225);
} catch (JuegoException e) {
Assertions.fail();
}
}
*/
}
| UTF-8 | Java | 4,016 | java | PokerTests.java | Java | [
{
"context": "nedas = new ArrayList<>();\n nickNames.add(\"Juan\");\n nickNames.add(\"Andres\");\n moned",
"end": 500,
"score": 0.999645471572876,
"start": 496,
"tag": "NAME",
"value": "Juan"
},
{
"context": " nickNames.add(\"Juan\");\n nickNames.add(\"... | null | [] | package edu.escuelaing.arsw.dangerousbet.game;
import edu.escuelaing.arsw.dangerousbet.game.impl.Poker;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class PokerTests {
/* @Test
public void agregarJugadores(){
Poker poker = new Poker();
List<String> nickNames = new ArrayList<>();
List<Integer> monedas = new ArrayList<>();
nickNames.add("Juan");
nickNames.add("Andres");
monedas.add(1000);
monedas.add(2000);
poker.iniciarPartida(nickNames,monedas);
Assertions.assertEquals(poker.getJugadores().size(), nickNames.size());
}
@Test
public void apostarConUsuarios() throws JuegoException {
Poker poker = new Poker();
List<String> nickNames = new ArrayList<>();
List<Integer> monedas = new ArrayList<>();
nickNames.add("Juan");
nickNames.add("Andres");
monedas.add(1000);
monedas.add(2000);
poker.iniciarPartida(nickNames,monedas);
Random r = new Random();
int apuesta1 =r.nextInt(200);
int apuesta2 =r.nextInt(200);
poker.apostar("Juan",apuesta1);
poker.apostar("Juan",apuesta2);
Assertions.assertTrue(poker.getApuestaByJugador("Juan")==(apuesta1+apuesta2));
}*/
/*
@Test
public void abandonarRondaSinrecibirCartas(){
Poker poker = new Poker();
List<String> nickNames = new ArrayList<>();
List<Integer> monedas = new ArrayList<>();
nickNames.add("Juan");
nickNames.add("Andres");
nickNames.add("Mario");
monedas.add(1000);
monedas.add(2000);
monedas.add(2000);
poker.iniciarPartida(nickNames,monedas);
poker.jugar();
poker.abandonar();
Assertions.assertTrue((poker.isJugador("Juan") && poker.isJugador("Andres") && !poker.isJugador("Mario")) );
}
@Test
public void abandonarRondaConCartasRecibidas(){
Poker poker = new Poker();
List<String> nickNames = new ArrayList<>();
List<Integer> monedas = new ArrayList<>();
nickNames.add("Juan");
nickNames.add("Andres");
nickNames.add("Mario");
monedas.add(1000);
monedas.add(2000);
monedas.add(2000);
poker.iniciarPartida(nickNames,monedas);
Random r = new Random();
int ite =r.nextInt(nickNames.size());
poker.jugar();
poker.abandonar(nickNames.get(ite));
Assertions.assertTrue(!poker.isJugador(nickNames.get(ite)));
}
*//*
@Test
public void seDebeIgualarLaApuesta(){
Poker poker = new Poker();
List<String> nickNames = new ArrayList<>();
List<Integer> monedas = new ArrayList<>();
nickNames.add("Juan");
nickNames.add("Andres");
nickNames.add("Mario");
monedas.add(1000);
monedas.add(2000);
monedas.add(2000);
poker.iniciarPartida(nickNames,monedas);
try {
poker.apostar("Juan",200);
poker.apostar("Andres",150);
} catch (JuegoException e) {
Assertions.assertTrue(e.getMessage().equals(JuegoException.DEBE_IGUALAR));
}
}
@Test
public void seDebeIgualarOApostarMas(){
Poker poker = new Poker();
List<String> nickNames = new ArrayList<>();
List<Integer> monedas = new ArrayList<>();
nickNames.add("Juan");
nickNames.add("Andres");
nickNames.add("Mario");
monedas.add(1000);
monedas.add(2000);
monedas.add(2000);
poker.iniciarPartida(nickNames,monedas);
try {
poker.apostar("Juan",200);
poker.apostar("Andres",200);
poker.apostar("Juan",25);
Assertions.assertTrue(poker.getApuestaByJugador("Juan")==225);
} catch (JuegoException e) {
Assertions.fail();
}
}
*/
}
| 4,016 | 0.594871 | 0.571713 | 129 | 30.131783 | 20.542782 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.775194 | false | false | 12 |
c1ce110703c21079ea9be229b8bf87751030995a | 21,474,836,488,278 | ffb64b4d4cb25d0f859286e521abde7117adec4c | /src/main/java/top/guitoubing/qiniuweb/util/ConstantUtil.java | baffcb1254d92b5caa981a5ee3945a7303ebf9ab | [] | no_license | RuiTan/QiniuCloud | https://github.com/RuiTan/QiniuCloud | e2a14c04c7d5f101848c51c7c166158aa128c8aa | 743221a497b907e8213405b3f77423f33f4ba576 | refs/heads/master | 2022-06-15T11:25:45.867000 | 2020-01-21T08:44:39 | 2020-01-21T08:44:39 | 190,051,266 | 2 | 0 | null | false | 2022-05-20T20:58:56 | 2019-06-03T17:31:03 | 2022-03-04T22:58:02 | 2022-05-20T20:58:55 | 23,903 | 2 | 0 | 2 | CSS | false | false | package top.guitoubing.qiniuweb.util;
public class ConstantUtil {
public static final String AccessKey = "LIjKmW98gcj0ahR_Fogx3AV8V1JsRtOQo6qT43Cu";
public static final String SecretKey = "W_lPo12yjHkaVyfibquVSJH8ImLWXw-tIXeggNSo";
public static String Bucket = "archer";
public static final String DomainName = "http://archer.guitoubing.top/";
private static final String Archer = "archer";
private static final String Guitoubing = "guitoubing";
private static final String Editor = "editor";
public static void setBucket(String bucket) {
if (bucket.equals(Archer) || bucket.equals(Guitoubing) || bucket.equals(Editor))
Bucket = bucket;
}
}
| UTF-8 | Java | 700 | java | ConstantUtil.java | Java | [
{
"context": "til {\n public static final String AccessKey = \"LIjKmW98gcj0ahR_Fogx3AV8V1JsRtOQo6qT43Cu\";\n public static final String SecretKey = \"W_l",
"end": 151,
"score": 0.9997413158416748,
"start": 111,
"tag": "KEY",
"value": "LIjKmW98gcj0ahR_Fogx3AV8V1JsRtOQo6qT43Cu"
},
{
... | null | [] | package top.guitoubing.qiniuweb.util;
public class ConstantUtil {
public static final String AccessKey = "<KEY>";
public static final String SecretKey = "<KEY>";
public static String Bucket = "archer";
public static final String DomainName = "http://archer.guitoubing.top/";
private static final String Archer = "archer";
private static final String Guitoubing = "guitoubing";
private static final String Editor = "editor";
public static void setBucket(String bucket) {
if (bucket.equals(Archer) || bucket.equals(Guitoubing) || bucket.equals(Editor))
Bucket = bucket;
}
}
| 630 | 0.724286 | 0.707143 | 16 | 42.75 | 30.200373 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8125 | false | false | 12 |
d5559eb639129a738599da7742970882946f5d00 | 26,955,214,758,137 | 2f815a4b0b550d48696d67d71c520bad2380dd3f | /Ejercicio_Java/src/ejercicio_java/Ejercicio_Java.java | a9c7f0044dc41afd959b64eb666a91a326a8f7eb | [] | no_license | erickamontero100292/CursoJava | https://github.com/erickamontero100292/CursoJava | 75f9315171a82567bad08e5ed67a6169270cfeaf | db9d59402b4e28de0790ac381c4250ed562f0dbc | refs/heads/master | 2021-01-12T14:40:29.537000 | 2016-10-27T00:25:20 | 2016-10-27T00:25:20 | 72,044,177 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ejercicio_java;
/**
*
* @author Ericka
*/
public class Ejercicio_Java {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
// Multiplicar muliplo = new Multiplicar(0);
SerieNumerica serie = new SerieNumerica(8);
// Factorial facto = new Factorial(4);
// Matrices_Estructura matriz = new Matrices_Estructura();
// ContarCifra contar = new ContarCifra();
// ConstanteConway conway = new ConstanteConway();
serie.crearSerie();
serie.mostrarSerie();
// System.out.println("El factorial es: "+facto.factorial(4));
// matriz.mejorProducto();
// contar.contarCifra();
// conway.serie();
//mul.tablas2();
EcuacionDeLaRecta recta = new EcuacionDeLaRecta();
recta.ecuacion(3, 2, 2, 2);
}
}
| UTF-8 | Java | 1,096 | java | Ejercicio_Java.java | Java | [
{
"context": "or.\n */\npackage ejercicio_java;\n\n/**\n *\n * @author Ericka\n */\npublic class Ejercicio_Java {\n\n /**\n *",
"end": 234,
"score": 0.9997949600219727,
"start": 228,
"tag": "NAME",
"value": "Ericka"
}
] | null | [] | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ejercicio_java;
/**
*
* @author Ericka
*/
public class Ejercicio_Java {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
// Multiplicar muliplo = new Multiplicar(0);
SerieNumerica serie = new SerieNumerica(8);
// Factorial facto = new Factorial(4);
// Matrices_Estructura matriz = new Matrices_Estructura();
// ContarCifra contar = new ContarCifra();
// ConstanteConway conway = new ConstanteConway();
serie.crearSerie();
serie.mostrarSerie();
// System.out.println("El factorial es: "+facto.factorial(4));
// matriz.mejorProducto();
// contar.contarCifra();
// conway.serie();
//mul.tablas2();
EcuacionDeLaRecta recta = new EcuacionDeLaRecta();
recta.ecuacion(3, 2, 2, 2);
}
}
| 1,096 | 0.625 | 0.616788 | 36 | 29.444445 | 22.694155 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.611111 | false | false | 12 |
ecd905997ef769e979ab18926456a1976d3285b5 | 27,281,632,273,318 | 5faf915f0dce2a82816c4ec75a84bf9fbfebc24a | /G.java | 5fc127c660df75053440747446e763363d3158b8 | [] | no_license | EvgenyPyankov/itmo | https://github.com/EvgenyPyankov/itmo | 8ebeeb74b42f61d3503a2022a03b9fd0efc036dd | 624e0053501eeeeabbbd8d9b05005eae047c90a8 | refs/heads/master | 2016-09-08T03:28:35.523000 | 2014-11-09T19:53:47 | 2014-11-09T19:53:47 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class G extends null {
void aa();
java.lang.Class qq();
}
| UTF-8 | Java | 75 | java | G.java | Java | [] | null | [] | public class G extends null {
void aa();
java.lang.Class qq();
}
| 75 | 0.586667 | 0.586667 | 6 | 11.5 | 12.038134 | 29 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 12 |
0d986b4d0c900b3074a1811d43a5ad968e460028 | 197,568,505,478 | 2c1582027f4a2647e013016d8d3af3374c6c25ef | /Selenium/src/main/java/com/sayem/architecture/GetCurrentArchitecture.java | 8e49a0120de1f03bb93e5877d2b1b8898f8fcc07 | [] | no_license | mdbarigidad/WebDriver | https://github.com/mdbarigidad/WebDriver | e67329f9d7de279df98c7043e6eaf2dca633425b | 7bfa134bc9674ee612109c696e3dd66c2027da4f | refs/heads/master | 2021-01-16T20:56:53.533000 | 2014-09-14T19:45:56 | 2014-09-14T19:45:56 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sayem.architecture;
import org.openqa.selenium.Architecture;
import org.openqa.selenium.Platform;
public class GetCurrentArchitecture {
public static void main(String[] args) {
// I am on Mac x64, so it return me Mac x64
System.out.print(Platform.getCurrent() + " " + Platform.getCurrent().getMajorVersion());
System.out.println(" " + Architecture.getCurrent());
}
}
| UTF-8 | Java | 416 | java | GetCurrentArchitecture.java | Java | [] | null | [] | package com.sayem.architecture;
import org.openqa.selenium.Architecture;
import org.openqa.selenium.Platform;
public class GetCurrentArchitecture {
public static void main(String[] args) {
// I am on Mac x64, so it return me Mac x64
System.out.print(Platform.getCurrent() + " " + Platform.getCurrent().getMajorVersion());
System.out.println(" " + Architecture.getCurrent());
}
}
| 416 | 0.692308 | 0.682692 | 15 | 26.733334 | 28.148336 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 12 |
f11e1a0873c0c1f4aa675c41ebe5e3a7ac9ab3f7 | 36,532,991,832,163 | 43592a4bc96a9df4587b4354ca3318e0bd825607 | /Day2/src/com/srm/java/training/EB_Bill.java | 3ed1c519388d76ec72ef63bad711df02b299c676 | [] | no_license | Divya-SRM/Java | https://github.com/Divya-SRM/Java | d809a8b4864843be858a3dfaa80dddfb76241e21 | 025a771429b9e0a8f42da47f0d58ecff9ff7a40f | refs/heads/main | 2023-06-19T04:10:07.652000 | 2021-07-17T12:56:38 | 2021-07-17T12:56:38 | 379,217,147 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.srm.java.training;
import java.util.Scanner;
public class EB_Bill {
int Consumer_No;
String Consumer_Name;
int Previous_reading;
int Current_reading;
String Connection_type;
int actUnit=0;
double amt=0;
EB_Bill(int Consumer_No,String Consumer_Name,int Previous_reading,int Current_reading,String Connection_type)
{
this.Consumer_No=Consumer_No;
this.Consumer_Name=Consumer_Name;
this.Previous_reading=Previous_reading;
this.Current_reading=Current_reading;
this.Connection_type=Connection_type;
}
public void calc()
{
actUnit=Current_reading-Previous_reading;
if(Connection_type.equalsIgnoreCase("domestic"))
{
if(actUnit<=100)
{
amt+=actUnit*1;
}
else if(actUnit>101 && actUnit<200)
{
amt+=actUnit*2.50;
}
else if(actUnit>201 && actUnit<500)
{
amt+=actUnit*4.00;
}
else if(actUnit>501)
{
amt+=actUnit*6;
}
else
{
System.out.println("Provide valid units");
}
}
else if(Connection_type.equalsIgnoreCase("commercial"))
{
if(actUnit<=100)
{
amt=amt+(actUnit*2);
}
else if(actUnit>101 && actUnit<200)
{
amt=amt+(actUnit*4.50);
}
else if(actUnit>201 && actUnit<500)
{
amt=amt+(actUnit*6.00);
}
else if(actUnit>501)
{
amt=amt+(actUnit*7);
}
else
{
System.out.println("Provide valid units");
}
}
}
void display()
{
System.out.println("*******Electricity Bill********");
System.out.println("Consumer Number :"+Consumer_No+"\nConsumer Name :"+Consumer_Name+"\nUnit Used :"+actUnit+"\nAmount :Rs."+amt);
System.out.println("*******THANK YOU***************");
}
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.println("Enter Consumer Number");
int Consumer_No=s.nextInt();
System.out.println("Enter Consumer Name");
String Consumer_Name=s.next();
System.out.println("Enter Previous Reading");
int Previous_reading=s.nextInt();
System.out.println("Enter Current Reading");
int Current_reading=s.nextInt();
System.out.println("Enter Connection Type");
String Connection_type=s.next();
EB_Bill Bill=new EB_Bill(Consumer_No,Consumer_Name,Previous_reading,Current_reading,Connection_type);
Bill.calc();
Bill.display();
s.close();
}
}
| UTF-8 | Java | 2,417 | java | EB_Bill.java | Java | [] | null | [] | package com.srm.java.training;
import java.util.Scanner;
public class EB_Bill {
int Consumer_No;
String Consumer_Name;
int Previous_reading;
int Current_reading;
String Connection_type;
int actUnit=0;
double amt=0;
EB_Bill(int Consumer_No,String Consumer_Name,int Previous_reading,int Current_reading,String Connection_type)
{
this.Consumer_No=Consumer_No;
this.Consumer_Name=Consumer_Name;
this.Previous_reading=Previous_reading;
this.Current_reading=Current_reading;
this.Connection_type=Connection_type;
}
public void calc()
{
actUnit=Current_reading-Previous_reading;
if(Connection_type.equalsIgnoreCase("domestic"))
{
if(actUnit<=100)
{
amt+=actUnit*1;
}
else if(actUnit>101 && actUnit<200)
{
amt+=actUnit*2.50;
}
else if(actUnit>201 && actUnit<500)
{
amt+=actUnit*4.00;
}
else if(actUnit>501)
{
amt+=actUnit*6;
}
else
{
System.out.println("Provide valid units");
}
}
else if(Connection_type.equalsIgnoreCase("commercial"))
{
if(actUnit<=100)
{
amt=amt+(actUnit*2);
}
else if(actUnit>101 && actUnit<200)
{
amt=amt+(actUnit*4.50);
}
else if(actUnit>201 && actUnit<500)
{
amt=amt+(actUnit*6.00);
}
else if(actUnit>501)
{
amt=amt+(actUnit*7);
}
else
{
System.out.println("Provide valid units");
}
}
}
void display()
{
System.out.println("*******Electricity Bill********");
System.out.println("Consumer Number :"+Consumer_No+"\nConsumer Name :"+Consumer_Name+"\nUnit Used :"+actUnit+"\nAmount :Rs."+amt);
System.out.println("*******THANK YOU***************");
}
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.println("Enter Consumer Number");
int Consumer_No=s.nextInt();
System.out.println("Enter Consumer Name");
String Consumer_Name=s.next();
System.out.println("Enter Previous Reading");
int Previous_reading=s.nextInt();
System.out.println("Enter Current Reading");
int Current_reading=s.nextInt();
System.out.println("Enter Connection Type");
String Connection_type=s.next();
EB_Bill Bill=new EB_Bill(Consumer_No,Consumer_Name,Previous_reading,Current_reading,Connection_type);
Bill.calc();
Bill.display();
s.close();
}
}
| 2,417 | 0.623914 | 0.601572 | 102 | 21.696079 | 24.149773 | 151 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.647059 | false | false | 12 |
102eb7e2d45b07b61aa23fa4a16ff6e500c9c1ba | 31,361,851,228,776 | ad293dcf4a0f64c16cb852545746ef107fc71d8a | /src/java/com/shopymarket/app/action/ClienteAction.java | 7ed31b6e050db76c0899de12b1e6481a5a617690 | [] | no_license | Israel2106/ProyectoLenguajesI | https://github.com/Israel2106/ProyectoLenguajesI | 932a22188476584436395c985d6a8ce0ba840ae3 | 13eba77902b1ca6d3c2c710ba7f2db88f3274a02 | refs/heads/master | 2021-01-23T15:04:58.898000 | 2017-06-16T02:02:30 | 2017-06-16T02:02:30 | 93,269,199 | 0 | 0 | null | false | 2017-06-27T16:47:00 | 2017-06-03T19:18:55 | 2017-06-12T21:39:02 | 2017-06-27T16:45:46 | 32,533 | 0 | 0 | 2 | HTML | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.shopymarket.app.action;
import com.shopymarket.app.bussiness.BussinessCliente;
import com.shopymarket.app.dominio.Cliente;
import java.util.LinkedList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
/**
*
* @author Israel
*/
public class ClienteAction extends DispatchAction {
/**
* This is the Struts action method called on
* http://.../actionPath?method=myAction1, where "method" is the value
* specified in <action> element : ( <action parameter="method" .../> )
*/
public ActionForward setCliente(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
String n=request.getParameter("nombre");
String em=request.getParameter("email");
String tel=request.getParameter("telefono");
String pass=request.getParameter("pass");
Cliente c = new Cliente(n, em, tel);
BussinessCliente bc = new BussinessCliente("root", "");
c.setId(bc.getNextID());
bc.insertarVendedor(n, em, tel,pass);
request.setAttribute("cliente",c);
return mapping.findForward("moduloCliente");
}
/**
* This is the Struts action method called on
* http://.../actionPath?method=myAction2, where "method" is the value
* specified in <action> element : ( <action parameter="method" .../> )
*/
public ActionForward actualizarCliente(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String id= request.getParameter("idEmpresa");
String n=request.getParameter("nombre");
String em=request.getParameter("email");
String tel=request.getParameter("telefono");
Cliente c= new Cliente(n, em, tel);
c.setId(Integer.parseInt(id));
BussinessCliente bc= new BussinessCliente("root", "");
bc.editarVendedor(c, id);
request.setAttribute("cliente",c);
return mapping.findForward("moduloCliente");
}
public ActionForward eliminarCliente(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String id= request.getParameter("idEmpresa");
BussinessCliente bc= new BussinessCliente("root", "");
bc.eliminarVendedor(id);
return mapping.findForward("inicio");
}
public ActionForward mostrarClientes(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
BussinessCliente bc= new BussinessCliente("root", "");
LinkedList<Cliente> supermercados= bc.obtenerTodosVendedores();
LinkedList<String> cantones = bc.obtenerCantones();
LinkedList<String> distritos = bc.obtenerDistritos();
request.setAttribute("supermercados", supermercados);
request.setAttribute("cantones", cantones);
request.setAttribute("distritos", distritos);
return mapping.findForward("tiendas");
}
public ActionForward mostrarClientesPorUbicacion(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String prov=request.getParameter("provincia");
String cant=request.getParameter("canton");
String dist=request.getParameter("distrito");
BussinessCliente bc= new BussinessCliente("root", "");
LinkedList<Cliente> supermercados= bc.obtenerVendedoresPorUbicacion(prov, cant, dist);
LinkedList<String> cantones = bc.obtenerCantones();
LinkedList<String> distritos = bc.obtenerDistritos();
request.setAttribute("supermercados", supermercados);
request.setAttribute("cantones", cantones);
request.setAttribute("distritos", distritos);
return mapping.findForward("tiendas");
}
public ActionForward setUbicacion(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String id= request.getParameter("idEmpresa");
String prov=request.getParameter("provincia");
String cant=request.getParameter("canton");
String dist=request.getParameter("distrito");
String esp=request.getParameter("especificacion");
String n=request.getParameter("nombre");
String em=request.getParameter("email");
String tel=request.getParameter("telefono");
Cliente c = new Cliente(n, em, tel);
c.setId(Integer.parseInt(id));
BussinessCliente bc = new BussinessCliente("root", "");
bc.insertarUbicacionVendedor(id, prov, cant, dist, esp);
request.setAttribute("cliente",c);
return mapping.findForward("moduloCliente");
}
}
| UTF-8 | Java | 5,655 | java | ClienteAction.java | Java | [
{
"context": "truts.action.ActionForward;\r\n\r\n/**\r\n *\r\n * @author Israel\r\n */\r\npublic class ClienteAction extends DispatchAc",
"end": 709,
"score": 0.9277893900871277,
"start": 703,
"tag": "NAME",
"value": "Israel"
}
] | null | [] | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.shopymarket.app.action;
import com.shopymarket.app.bussiness.BussinessCliente;
import com.shopymarket.app.dominio.Cliente;
import java.util.LinkedList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
/**
*
* @author Israel
*/
public class ClienteAction extends DispatchAction {
/**
* This is the Struts action method called on
* http://.../actionPath?method=myAction1, where "method" is the value
* specified in <action> element : ( <action parameter="method" .../> )
*/
public ActionForward setCliente(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
String n=request.getParameter("nombre");
String em=request.getParameter("email");
String tel=request.getParameter("telefono");
String pass=request.getParameter("pass");
Cliente c = new Cliente(n, em, tel);
BussinessCliente bc = new BussinessCliente("root", "");
c.setId(bc.getNextID());
bc.insertarVendedor(n, em, tel,pass);
request.setAttribute("cliente",c);
return mapping.findForward("moduloCliente");
}
/**
* This is the Struts action method called on
* http://.../actionPath?method=myAction2, where "method" is the value
* specified in <action> element : ( <action parameter="method" .../> )
*/
public ActionForward actualizarCliente(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String id= request.getParameter("idEmpresa");
String n=request.getParameter("nombre");
String em=request.getParameter("email");
String tel=request.getParameter("telefono");
Cliente c= new Cliente(n, em, tel);
c.setId(Integer.parseInt(id));
BussinessCliente bc= new BussinessCliente("root", "");
bc.editarVendedor(c, id);
request.setAttribute("cliente",c);
return mapping.findForward("moduloCliente");
}
public ActionForward eliminarCliente(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String id= request.getParameter("idEmpresa");
BussinessCliente bc= new BussinessCliente("root", "");
bc.eliminarVendedor(id);
return mapping.findForward("inicio");
}
public ActionForward mostrarClientes(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
BussinessCliente bc= new BussinessCliente("root", "");
LinkedList<Cliente> supermercados= bc.obtenerTodosVendedores();
LinkedList<String> cantones = bc.obtenerCantones();
LinkedList<String> distritos = bc.obtenerDistritos();
request.setAttribute("supermercados", supermercados);
request.setAttribute("cantones", cantones);
request.setAttribute("distritos", distritos);
return mapping.findForward("tiendas");
}
public ActionForward mostrarClientesPorUbicacion(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String prov=request.getParameter("provincia");
String cant=request.getParameter("canton");
String dist=request.getParameter("distrito");
BussinessCliente bc= new BussinessCliente("root", "");
LinkedList<Cliente> supermercados= bc.obtenerVendedoresPorUbicacion(prov, cant, dist);
LinkedList<String> cantones = bc.obtenerCantones();
LinkedList<String> distritos = bc.obtenerDistritos();
request.setAttribute("supermercados", supermercados);
request.setAttribute("cantones", cantones);
request.setAttribute("distritos", distritos);
return mapping.findForward("tiendas");
}
public ActionForward setUbicacion(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String id= request.getParameter("idEmpresa");
String prov=request.getParameter("provincia");
String cant=request.getParameter("canton");
String dist=request.getParameter("distrito");
String esp=request.getParameter("especificacion");
String n=request.getParameter("nombre");
String em=request.getParameter("email");
String tel=request.getParameter("telefono");
Cliente c = new Cliente(n, em, tel);
c.setId(Integer.parseInt(id));
BussinessCliente bc = new BussinessCliente("root", "");
bc.insertarUbicacionVendedor(id, prov, cant, dist, esp);
request.setAttribute("cliente",c);
return mapping.findForward("moduloCliente");
}
}
| 5,655 | 0.651459 | 0.651105 | 128 | 42.179688 | 27.005913 | 152 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.953125 | false | false | 12 |
d29e3add691ef2b7ae5d9e64c273989e66508ca6 | 30,253,749,694,300 | 1323cf7d0383d4478f97ce2bc659050aca61692f | /app/src/main/java/com/alirnp/tempviewdemo/MainActivity.java | 1f66c9a9d633e945797030d7e47cee3bd7b5e9d2 | [] | no_license | ali-moghadam/TempView | https://github.com/ali-moghadam/TempView | a94f6fb2a18756ca65561fa886231897e13c14bf | ef9617e7e95c93d8e2555a73a420e11fc408ee86 | refs/heads/master | 2022-11-07T04:07:45.651000 | 2020-07-04T09:42:25 | 2020-07-04T09:42:25 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.alirnp.tempviewdemo;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.alirnp.tempview.TempView;
public class MainActivity extends AppCompatActivity {
private TempView mTempView1;
private TempView mTempView2;
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTempView1 = findViewById(R.id.tempView1);
mTempView2 = findViewById(R.id.tempView2);
mTextView = findViewById(R.id.statusTempView1);
// setIndicatorModeValues(mTempView1);
mTempView1.setOnSeekCirclesListener(new TempView.OnSeekChangeListener() {
@Override
public void onSeekChange(int value) {
mTextView.setText(String.format("onSeekChange : value = %s", value));
}
@Override
public void onSeekComplete(int value) {
mTextView.setText(String.format("onSeekComplete : value = %s", value));
mTempView2.setTemp(value);
}
});
}
private void setIndicatorModeValues(TempView mTempView) {
mTempView.setMinValue(10);
mTempView.setMaxValue(20);
mTempView.setTemp(15);
}
}
| UTF-8 | Java | 1,374 | java | MainActivity.java | Java | [] | null | [] | package com.alirnp.tempviewdemo;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.alirnp.tempview.TempView;
public class MainActivity extends AppCompatActivity {
private TempView mTempView1;
private TempView mTempView2;
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTempView1 = findViewById(R.id.tempView1);
mTempView2 = findViewById(R.id.tempView2);
mTextView = findViewById(R.id.statusTempView1);
// setIndicatorModeValues(mTempView1);
mTempView1.setOnSeekCirclesListener(new TempView.OnSeekChangeListener() {
@Override
public void onSeekChange(int value) {
mTextView.setText(String.format("onSeekChange : value = %s", value));
}
@Override
public void onSeekComplete(int value) {
mTextView.setText(String.format("onSeekComplete : value = %s", value));
mTempView2.setTemp(value);
}
});
}
private void setIndicatorModeValues(TempView mTempView) {
mTempView.setMinValue(10);
mTempView.setMaxValue(20);
mTempView.setTemp(15);
}
}
| 1,374 | 0.660844 | 0.649199 | 49 | 27.020409 | 24.827148 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.469388 | false | false | 12 |
4d2eceda7d0f4b1ed8b9cb81ebdd8388ddc77e19 | 17,540,646,488,755 | 77b969522ef45ef691d1a7f6d9347e39c2fc7925 | /spring01/src/main/java/com/example/spring01/model/dto/UserDTO.java | dd6260f0159f6839631c8fb66612d7d0fb94d3eb | [] | no_license | bravekjel/spring01 | https://github.com/bravekjel/spring01 | bfbeee583a7963e95fa07d33e89b20fba25063c8 | 027626a2766b59c293c399eb7994a2f1e2dcbaab | refs/heads/master | 2022-12-23T03:09:03.791000 | 2019-10-16T15:22:24 | 2019-10-16T15:22:24 | 203,616,313 | 0 | 0 | null | false | 2022-12-15T23:46:19 | 2019-08-21T15:46:17 | 2019-10-16T15:22:52 | 2022-12-15T23:46:18 | 1,530 | 0 | 0 | 14 | Java | false | false | package com.example.spring01.model.dto;
import java.util.Collection;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
public class UserDTO extends User {
private String userid;
private String name;
public UserDTO(String username, String password, boolean enabled, boolean accountNonExpired,
boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities,
String userid, String name) {
super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
this.userid = userid;
this.name=name;
}
public String getUserid() {
return userid;
}
@Override
public String toString() {
return "UserDTO [userid=" + userid + " name="+name+"]";
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| UTF-8 | Java | 1,040 | java | UserDTO.java | Java | [] | null | [] | package com.example.spring01.model.dto;
import java.util.Collection;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
public class UserDTO extends User {
private String userid;
private String name;
public UserDTO(String username, String password, boolean enabled, boolean accountNonExpired,
boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities,
String userid, String name) {
super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
this.userid = userid;
this.name=name;
}
public String getUserid() {
return userid;
}
@Override
public String toString() {
return "UserDTO [userid=" + userid + " name="+name+"]";
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| 1,040 | 0.722115 | 0.720192 | 41 | 23.365854 | 28.594521 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.634146 | false | false | 12 |
78d8eb34b8f98c7bdd106c680d5f376793550baa | 17,824,114,335,145 | 7b596e65e099adefc2b26b168a91a1c403833337 | /src/Hammer.java | 11cdc274b0413958c61231c1dfccf677630ed3cc | [] | no_license | firesage123/Thor | https://github.com/firesage123/Thor | 0850e9f8e5b20d4b6767ef5c8c36e1ce62739f12 | eb534dc8b021e0b5c5a18c2353eaf59e248e5d5e | refs/heads/master | 2021-01-10T12:14:24.384000 | 2015-11-11T01:11:38 | 2015-11-11T01:11:38 | 45,950,799 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import info.gridworld.actor.*;
import info.gridworld.actor.Critter;
import info.gridworld.grid.Grid;
import info.gridworld.grid.Location;
import java.awt.Color;
import java.util.ArrayList;
public class Hammer extends Weapon
{
int hitpoint;
public Hammer(Thor t)
{
super(t);
hitpoint = 1;
}
} | UTF-8 | Java | 300 | java | Hammer.java | Java | [] | null | [] | import info.gridworld.actor.*;
import info.gridworld.actor.Critter;
import info.gridworld.grid.Grid;
import info.gridworld.grid.Location;
import java.awt.Color;
import java.util.ArrayList;
public class Hammer extends Weapon
{
int hitpoint;
public Hammer(Thor t)
{
super(t);
hitpoint = 1;
}
} | 300 | 0.756667 | 0.753333 | 16 | 17.8125 | 13.333317 | 36 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.0625 | false | false | 12 |
e671f4d448ee616bf15092d97b7f5a78407e72ef | 17,824,114,337,070 | 5451a6e13ce5afea98a3bb687b9b29e445a7113a | /src/main/java/com/example/demo/service/DemoContorller.java | d0180de1ad53b624ad022bae5f58c6d0189de959 | [] | no_license | zxc6286747/demo | https://github.com/zxc6286747/demo | c0fa361d60a578b8f4df46eb4eaa32b8dc0524de | b593ef50664adf557676279be04cab511023d840 | refs/heads/master | 2021-04-04T14:29:13.768000 | 2020-05-21T03:43:23 | 2020-05-21T03:43:23 | 248,464,593 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.demo.service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DemoContorller {
@RequestMapping("/")
public String a() {
return "你好aaaahello";
}
}
| UTF-8 | Java | 288 | java | DemoContorller.java | Java | [] | null | [] | package com.example.demo.service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DemoContorller {
@RequestMapping("/")
public String a() {
return "你好aaaahello";
}
}
| 288 | 0.778169 | 0.778169 | 15 | 17.933332 | 20.647734 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 12 |
1c307803af4bd0415b6cec0ba43fb19c496bbc94 | 6,459,630,862,146 | a2b4bb766b49a66733b93fcf20b07bf88c17ea7f | /src/test/java/auction/AuctionAppValidator.java | 804b4b3d8420a29fc83080a692528dd574d5a740 | [] | no_license | emiliabvdb/auction | https://github.com/emiliabvdb/auction | cdb2f7fd8df4de8594d9bfda11f1de30b9719ee5 | f33016c26455d04625dae24b48c33f813075f973 | refs/heads/master | 2022-12-04T15:19:39.395000 | 2018-10-26T11:49:55 | 2018-10-26T11:49:55 | 150,239,295 | 0 | 1 | null | false | 2022-11-16T09:57:44 | 2018-09-25T09:22:50 | 2018-10-26T11:50:00 | 2022-11-16T09:57:41 | 392 | 0 | 1 | 4 | Java | false | false | package auction;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import javax.xml.namespace.QName;
import javax.xml.validation.Validator;
import javax.xml.ws.Endpoint;
import javax.xml.ws.Service;
//import org.junit.Test;
import EJB.BidValidator;
import entity.Address;
import entity.Auction;
import entity.Bid;
import entity.Category;
import entity.DutchAuction;
import entity.EnglishAuction;
import entity.SystemUserRole;
import entity.User;
import junit.framework.TestCase;
public class AuctionAppValidator extends TestCase {
protected void setUp() throws Exception {
super.setUp();
}
//@Test
public void shouldCheckCreditCardValidity() throws MalformedURLException {
// Publishes the SOAP Web Service
Endpoint endpoint = Endpoint.publish("http://localhost:8080/cardValidator", new EnglishAuction());
assertTrue(endpoint.isPublished()); assertEquals("http://schemas.xmlsoap.org/wsdl/soap/http", endpoint.getBinding().getBindingID());
// Needed properties to access the web service
URL wsdlDocumentLocation = new URL("http://localhost:8080/cardValidator?wsdl");
String namespaceURI = "http://chapter14.javaee7.book.agoncal.org/";
String servicePart = "CardValidatorService";
String portName = "CardValidatorPort";
QName serviceQN = new QName(namespaceURI, servicePart);
QName portQN = new QName(namespaceURI, portName);
// Creates a service instance
Service service = Service.create(wsdlDocumentLocation, serviceQN);
BidValidator bidVal = new BidValidator();
// Invokes the web service
Category klaer = new Category();
klaer.setName("Klaer");
klaer.setDescription("Klaer og annet lignende");
Category pynt = new Category();
pynt.setName("Pynt");
pynt.setDescription("Pyntegjenstander");
Category bilder = new Category();
bilder.setName("Bilder");
bilder.setDescription("bilder, malerier, trykk og annet");
Category dyrUtstyr = new Category();
dyrUtstyr.setName("Dyr og utstyr");
dyrUtstyr.setDescription("Her selges både dyr og utstyr som kreves for å ha dyr. Kjop og salg av dode dyr er forbudt.");
//Oppretter Adresser
Address emiAddr = new Address();
emiAddr.setStreetAddress("paaNordnesEnPlass 1234");
emiAddr.setCity("Bergen");
emiAddr.setCountry("Norway");
emiAddr.setZipCode((short)5009);
Address friAddr = new Address();
friAddr.setStreetAddress("Styrmannsveien 15");
friAddr.setCity("Haugesund");
friAddr.setCountry("Norway");
friAddr.setZipCode((short)5535);
Address mikAddr = new Address();
mikAddr.setStreetAddress("IStavanger 1337");
mikAddr.setCity("Stavanger");
mikAddr.setCountry("Norway");
mikAddr.setZipCode((short)4031);
//oppretter brukere
User emilia = new User();
emilia.setFirstName("Emilia");
emilia.setLastName("Botnen");
emilia.setDateOfBirth(LocalDate.of(1992, 12, 07));
emilia.setAddress(emiAddr);
emilia.setBillingAddress(emilia.getAddress());
emilia.setEmail("emibvdb@gmail.com");
emilia.setPassword("EmiliaPassord");
emilia.setRole(SystemUserRole.USER);
User frida = new User();
frida.setFirstName("Frida");
frida.setLastName("Klockmann");
frida.setDateOfBirth(LocalDate.of(1996, 2, 06));
frida.setAddress(friAddr);
frida.setBillingAddress(frida.getAddress());
frida.setEmail("fridaklockmann@gmail.com");
frida.setPassword("Fridapassord");
frida.setRole(SystemUserRole.USER);
User mikal = new User();
mikal.setFirstName("Mikal");
mikal.setLastName("Fuglestein");
mikal.setDateOfBirth(LocalDate.of(1995, 8, 21));
//creating an auction
Auction jacketAuction = new EnglishAuction();
jacketAuction.setOwner(emilia);
jacketAuction.setProductName("Brukt jakke");
jacketAuction.setStartDate(LocalDate.of(2018, 9, 28));
jacketAuction.setEndDate(LocalDate.of(2018, 10, 10));
jacketAuction.setPublished(true);
//bidList??
Auction dutchAuction = new DutchAuction();
dutchAuction.setOwner(emilia);
dutchAuction.setProductName("Brukt jakke");
dutchAuction.setStartDate(LocalDate.of(2018, 9, 28));
dutchAuction.setEndDate(LocalDate.of(2018, 10, 10));
dutchAuction.setPublished(true);
List<Category> catList1 = new ArrayList<>();
catList1.add(klaer);
jacketAuction.setCategory(catList1);
//creating bids for auction
Bid jacketBid1 = new Bid();
jacketBid1.setTimePlaced(new GregorianCalendar(2018, Calendar.SEPTEMBER, 29).getTime());
jacketBid1.setOwner(frida);
jacketBid1.setAmount(100.0);
jacketBid1.setAuction(jacketAuction);
Bid jacketBid2 = new Bid();
jacketBid2.setTimePlaced(new GregorianCalendar(2018, Calendar.SEPTEMBER, 30).getTime());
jacketBid2.setOwner(mikal);
jacketBid2.setAmount(200.0);
jacketBid2.setAuction(jacketAuction);
Auction bildeAuct = new EnglishAuction();
bildeAuct.setProductName("Stolen Child av AFK");
List<Category> catList2 = new ArrayList<>();
catList2.add(pynt);
catList2.add(bilder);
bildeAuct.setCategory(catList2);
bildeAuct.setOwner(mikal);
bildeAuct.setStartDate(LocalDate.of(2018, 9, 29));
Bid bildeBid1 = new Bid();
bildeBid1.setTimePlaced(new GregorianCalendar(2018, Calendar.SEPTEMBER, 30).getTime());
bildeBid1.setOwner(frida);
bildeBid1.setAmount(2800);
bildeBid1.setAuction(bildeAuct);
Bid bildeBid2 = new Bid();
bildeBid2.setTimePlaced(new GregorianCalendar(2018, Calendar.OCTOBER, 01).getTime());
bildeBid2.setOwner(emilia);
bildeBid2.setAmount(3000);
bildeBid2.setAuction(bildeAuct);
Bid bildeBid3 = new Bid();
bildeBid3.setTimePlaced(new GregorianCalendar(2018, Calendar.OCTOBER, 02).getTime());
bildeBid3.setOwner(frida);
bildeBid3.setAmount(3200);
bildeBid3.setAuction(bildeAuct);
Bid bildeBid4 = new Bid();
bildeBid3.setTimePlaced(new GregorianCalendar(2018, Calendar.OCTOBER, 04).getTime());
bildeBid3.setOwner(emilia);
bildeBid3.setAmount(3100);
bildeBid3.setAuction(bildeAuct);
assertTrue("bildeBid2 should be valid", bidVal.isValidBid(bildeBid2));
assertFalse("bildeBid4 should not be valid", bidVal.isValidBid(bildeBid4));
// Unpublishes the SOAP Web Service
endpoint.stop();
assertFalse(endpoint.isPublished());
}
}
| UTF-8 | Java | 6,695 | java | AuctionAppValidator.java | Java | [
{
"context": "r emilia = new User();\n\t emilia.setFirstName(\"Emilia\");\n\t emilia.setLastName(\"Botnen\");\n\t emil",
"end": 3016,
"score": 0.9997979402542114,
"start": 3010,
"tag": "NAME",
"value": "Emilia"
},
{
"context": "setFirstName(\"Emilia\");\n\t emilia.set... | null | [] | package auction;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import javax.xml.namespace.QName;
import javax.xml.validation.Validator;
import javax.xml.ws.Endpoint;
import javax.xml.ws.Service;
//import org.junit.Test;
import EJB.BidValidator;
import entity.Address;
import entity.Auction;
import entity.Bid;
import entity.Category;
import entity.DutchAuction;
import entity.EnglishAuction;
import entity.SystemUserRole;
import entity.User;
import junit.framework.TestCase;
public class AuctionAppValidator extends TestCase {
protected void setUp() throws Exception {
super.setUp();
}
//@Test
public void shouldCheckCreditCardValidity() throws MalformedURLException {
// Publishes the SOAP Web Service
Endpoint endpoint = Endpoint.publish("http://localhost:8080/cardValidator", new EnglishAuction());
assertTrue(endpoint.isPublished()); assertEquals("http://schemas.xmlsoap.org/wsdl/soap/http", endpoint.getBinding().getBindingID());
// Needed properties to access the web service
URL wsdlDocumentLocation = new URL("http://localhost:8080/cardValidator?wsdl");
String namespaceURI = "http://chapter14.javaee7.book.agoncal.org/";
String servicePart = "CardValidatorService";
String portName = "CardValidatorPort";
QName serviceQN = new QName(namespaceURI, servicePart);
QName portQN = new QName(namespaceURI, portName);
// Creates a service instance
Service service = Service.create(wsdlDocumentLocation, serviceQN);
BidValidator bidVal = new BidValidator();
// Invokes the web service
Category klaer = new Category();
klaer.setName("Klaer");
klaer.setDescription("Klaer og annet lignende");
Category pynt = new Category();
pynt.setName("Pynt");
pynt.setDescription("Pyntegjenstander");
Category bilder = new Category();
bilder.setName("Bilder");
bilder.setDescription("bilder, malerier, trykk og annet");
Category dyrUtstyr = new Category();
dyrUtstyr.setName("Dyr og utstyr");
dyrUtstyr.setDescription("Her selges både dyr og utstyr som kreves for å ha dyr. Kjop og salg av dode dyr er forbudt.");
//Oppretter Adresser
Address emiAddr = new Address();
emiAddr.setStreetAddress("paaNordnesEnPlass 1234");
emiAddr.setCity("Bergen");
emiAddr.setCountry("Norway");
emiAddr.setZipCode((short)5009);
Address friAddr = new Address();
friAddr.setStreetAddress("Styrmannsveien 15");
friAddr.setCity("Haugesund");
friAddr.setCountry("Norway");
friAddr.setZipCode((short)5535);
Address mikAddr = new Address();
mikAddr.setStreetAddress("IStavanger 1337");
mikAddr.setCity("Stavanger");
mikAddr.setCountry("Norway");
mikAddr.setZipCode((short)4031);
//oppretter brukere
User emilia = new User();
emilia.setFirstName("Emilia");
emilia.setLastName("Botnen");
emilia.setDateOfBirth(LocalDate.of(1992, 12, 07));
emilia.setAddress(emiAddr);
emilia.setBillingAddress(emilia.getAddress());
emilia.setEmail("<EMAIL>");
emilia.setPassword("<PASSWORD>");
emilia.setRole(SystemUserRole.USER);
User frida = new User();
frida.setFirstName("Frida");
frida.setLastName("Klockmann");
frida.setDateOfBirth(LocalDate.of(1996, 2, 06));
frida.setAddress(friAddr);
frida.setBillingAddress(frida.getAddress());
frida.setEmail("<EMAIL>");
frida.setPassword("<PASSWORD>");
frida.setRole(SystemUserRole.USER);
User mikal = new User();
mikal.setFirstName("Mikal");
mikal.setLastName("Fuglestein");
mikal.setDateOfBirth(LocalDate.of(1995, 8, 21));
//creating an auction
Auction jacketAuction = new EnglishAuction();
jacketAuction.setOwner(emilia);
jacketAuction.setProductName("Brukt jakke");
jacketAuction.setStartDate(LocalDate.of(2018, 9, 28));
jacketAuction.setEndDate(LocalDate.of(2018, 10, 10));
jacketAuction.setPublished(true);
//bidList??
Auction dutchAuction = new DutchAuction();
dutchAuction.setOwner(emilia);
dutchAuction.setProductName("Brukt jakke");
dutchAuction.setStartDate(LocalDate.of(2018, 9, 28));
dutchAuction.setEndDate(LocalDate.of(2018, 10, 10));
dutchAuction.setPublished(true);
List<Category> catList1 = new ArrayList<>();
catList1.add(klaer);
jacketAuction.setCategory(catList1);
//creating bids for auction
Bid jacketBid1 = new Bid();
jacketBid1.setTimePlaced(new GregorianCalendar(2018, Calendar.SEPTEMBER, 29).getTime());
jacketBid1.setOwner(frida);
jacketBid1.setAmount(100.0);
jacketBid1.setAuction(jacketAuction);
Bid jacketBid2 = new Bid();
jacketBid2.setTimePlaced(new GregorianCalendar(2018, Calendar.SEPTEMBER, 30).getTime());
jacketBid2.setOwner(mikal);
jacketBid2.setAmount(200.0);
jacketBid2.setAuction(jacketAuction);
Auction bildeAuct = new EnglishAuction();
bildeAuct.setProductName("Stolen Child av AFK");
List<Category> catList2 = new ArrayList<>();
catList2.add(pynt);
catList2.add(bilder);
bildeAuct.setCategory(catList2);
bildeAuct.setOwner(mikal);
bildeAuct.setStartDate(LocalDate.of(2018, 9, 29));
Bid bildeBid1 = new Bid();
bildeBid1.setTimePlaced(new GregorianCalendar(2018, Calendar.SEPTEMBER, 30).getTime());
bildeBid1.setOwner(frida);
bildeBid1.setAmount(2800);
bildeBid1.setAuction(bildeAuct);
Bid bildeBid2 = new Bid();
bildeBid2.setTimePlaced(new GregorianCalendar(2018, Calendar.OCTOBER, 01).getTime());
bildeBid2.setOwner(emilia);
bildeBid2.setAmount(3000);
bildeBid2.setAuction(bildeAuct);
Bid bildeBid3 = new Bid();
bildeBid3.setTimePlaced(new GregorianCalendar(2018, Calendar.OCTOBER, 02).getTime());
bildeBid3.setOwner(frida);
bildeBid3.setAmount(3200);
bildeBid3.setAuction(bildeAuct);
Bid bildeBid4 = new Bid();
bildeBid3.setTimePlaced(new GregorianCalendar(2018, Calendar.OCTOBER, 04).getTime());
bildeBid3.setOwner(emilia);
bildeBid3.setAmount(3100);
bildeBid3.setAuction(bildeAuct);
assertTrue("bildeBid2 should be valid", bidVal.isValidBid(bildeBid2));
assertFalse("bildeBid4 should not be valid", bidVal.isValidBid(bildeBid4));
// Unpublishes the SOAP Web Service
endpoint.stop();
assertFalse(endpoint.isPublished());
}
}
| 6,663 | 0.703123 | 0.674287 | 193 | 33.678757 | 23.978842 | 134 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.777202 | false | false | 12 |
47d05da37c5bc75731e839dd81b04be18bab666c | 35,235,911,721,830 | 4aac59a656f3f5537956e9e3634d38bb695ad0e0 | /src/test/java/br/com/tools/manager/web/rest/ConsultorResourceIntTest.java | 49959993b7190ea517b541881b290eb656a89be4 | [] | no_license | alexsrosa/apptools-manager | https://github.com/alexsrosa/apptools-manager | ffeb0acd3d31231c88bdee16c21c978f3d4f2e30 | 3200b58a3ea5810ff33cf68b727ca31baee872bd | refs/heads/master | 2021-06-22T04:56:25.273000 | 2017-08-26T01:58:24 | 2017-08-26T01:58:24 | 100,435,773 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.tools.manager.web.rest;
import br.com.tools.manager.ManagerApp;
import br.com.tools.manager.domain.Consultor;
import br.com.tools.manager.repository.ConsultorRepository;
import br.com.tools.manager.web.rest.errors.ExceptionTranslator;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import br.com.tools.manager.domain.enumeration.ConsultorStatus;
/**
* Test class for the ConsultorResource REST controller.
*
* @see ConsultorResource
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ManagerApp.class)
public class ConsultorResourceIntTest {
private static final String DEFAULT_NOME = "AAAAAAAAAA";
private static final String UPDATED_NOME = "BBBBBBBBBB";
private static final LocalDate DEFAULT_DATAPRIMEIROREGISTRO = LocalDate.ofEpochDay(0L);
private static final LocalDate UPDATED_DATAPRIMEIROREGISTRO = LocalDate.now(ZoneId.systemDefault());
private static final LocalDate DEFAULT_DATAULTIMOREGISTRO = LocalDate.ofEpochDay(0L);
private static final LocalDate UPDATED_DATAULTIMOREGISTRO = LocalDate.now(ZoneId.systemDefault());
private static final ConsultorStatus DEFAULT_FLATIVO = ConsultorStatus.ATIVADO;
private static final ConsultorStatus UPDATED_FLATIVO = ConsultorStatus.DESATIVADO;
@Autowired
private ConsultorRepository consultorRepository;
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
@Autowired
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
@Autowired
private ExceptionTranslator exceptionTranslator;
@Autowired
private EntityManager em;
private MockMvc restConsultorMockMvc;
private Consultor consultor;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
ConsultorResource consultorResource = new ConsultorResource(consultorRepository);
this.restConsultorMockMvc = MockMvcBuilders.standaloneSetup(consultorResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setMessageConverters(jacksonMessageConverter).build();
}
/**
* Create an entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Consultor createEntity(EntityManager em) {
Consultor consultor = new Consultor()
.nome(DEFAULT_NOME)
.dataprimeiroregistro(DEFAULT_DATAPRIMEIROREGISTRO)
.dataultimoregistro(DEFAULT_DATAULTIMOREGISTRO)
.flativo(DEFAULT_FLATIVO);
return consultor;
}
@Before
public void initTest() {
consultor = createEntity(em);
}
@Test
@Transactional
public void createConsultor() throws Exception {
int databaseSizeBeforeCreate = consultorRepository.findAll().size();
// Create the Consultor
restConsultorMockMvc.perform(post("/api/consultors")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(consultor)))
.andExpect(status().isCreated());
// Validate the Consultor in the database
List<Consultor> consultorList = consultorRepository.findAll();
assertThat(consultorList).hasSize(databaseSizeBeforeCreate + 1);
Consultor testConsultor = consultorList.get(consultorList.size() - 1);
assertThat(testConsultor.getNome()).isEqualTo(DEFAULT_NOME);
assertThat(testConsultor.getDataprimeiroregistro()).isEqualTo(DEFAULT_DATAPRIMEIROREGISTRO);
assertThat(testConsultor.getDataultimoregistro()).isEqualTo(DEFAULT_DATAULTIMOREGISTRO);
assertThat(testConsultor.getFlativo()).isEqualTo(DEFAULT_FLATIVO);
}
@Test
@Transactional
public void createConsultorWithExistingId() throws Exception {
int databaseSizeBeforeCreate = consultorRepository.findAll().size();
// Create the Consultor with an existing ID
consultor.setId(1L);
// An entity with an existing ID cannot be created, so this API call must fail
restConsultorMockMvc.perform(post("/api/consultors")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(consultor)))
.andExpect(status().isBadRequest());
// Validate the Alice in the database
List<Consultor> consultorList = consultorRepository.findAll();
assertThat(consultorList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
public void checkNomeIsRequired() throws Exception {
int databaseSizeBeforeTest = consultorRepository.findAll().size();
// set the field null
consultor.setNome(null);
// Create the Consultor, which fails.
restConsultorMockMvc.perform(post("/api/consultors")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(consultor)))
.andExpect(status().isBadRequest());
List<Consultor> consultorList = consultorRepository.findAll();
assertThat(consultorList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void checkDataprimeiroregistroIsRequired() throws Exception {
int databaseSizeBeforeTest = consultorRepository.findAll().size();
// set the field null
consultor.setDataprimeiroregistro(null);
// Create the Consultor, which fails.
restConsultorMockMvc.perform(post("/api/consultors")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(consultor)))
.andExpect(status().isBadRequest());
List<Consultor> consultorList = consultorRepository.findAll();
assertThat(consultorList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void checkDataultimoregistroIsRequired() throws Exception {
int databaseSizeBeforeTest = consultorRepository.findAll().size();
// set the field null
consultor.setDataultimoregistro(null);
// Create the Consultor, which fails.
restConsultorMockMvc.perform(post("/api/consultors")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(consultor)))
.andExpect(status().isBadRequest());
List<Consultor> consultorList = consultorRepository.findAll();
assertThat(consultorList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void checkFlativoIsRequired() throws Exception {
int databaseSizeBeforeTest = consultorRepository.findAll().size();
// set the field null
consultor.setFlativo(null);
// Create the Consultor, which fails.
restConsultorMockMvc.perform(post("/api/consultors")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(consultor)))
.andExpect(status().isBadRequest());
List<Consultor> consultorList = consultorRepository.findAll();
assertThat(consultorList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void getAllConsultors() throws Exception {
// Initialize the database
consultorRepository.saveAndFlush(consultor);
// Get all the consultorList
restConsultorMockMvc.perform(get("/api/consultors?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(consultor.getId().intValue())))
.andExpect(jsonPath("$.[*].nome").value(hasItem(DEFAULT_NOME.toString())))
.andExpect(jsonPath("$.[*].dataprimeiroregistro").value(hasItem(DEFAULT_DATAPRIMEIROREGISTRO.toString())))
.andExpect(jsonPath("$.[*].dataultimoregistro").value(hasItem(DEFAULT_DATAULTIMOREGISTRO.toString())))
.andExpect(jsonPath("$.[*].flativo").value(hasItem(DEFAULT_FLATIVO.toString())));
}
@Test
@Transactional
public void getConsultor() throws Exception {
// Initialize the database
consultorRepository.saveAndFlush(consultor);
// Get the consultor
restConsultorMockMvc.perform(get("/api/consultors/{id}", consultor.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.id").value(consultor.getId().intValue()))
.andExpect(jsonPath("$.nome").value(DEFAULT_NOME.toString()))
.andExpect(jsonPath("$.dataprimeiroregistro").value(DEFAULT_DATAPRIMEIROREGISTRO.toString()))
.andExpect(jsonPath("$.dataultimoregistro").value(DEFAULT_DATAULTIMOREGISTRO.toString()))
.andExpect(jsonPath("$.flativo").value(DEFAULT_FLATIVO.toString()));
}
@Test
@Transactional
public void getNonExistingConsultor() throws Exception {
// Get the consultor
restConsultorMockMvc.perform(get("/api/consultors/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
}
@Test
@Transactional
public void updateConsultor() throws Exception {
// Initialize the database
consultorRepository.saveAndFlush(consultor);
int databaseSizeBeforeUpdate = consultorRepository.findAll().size();
// Update the consultor
Consultor updatedConsultor = consultorRepository.findOne(consultor.getId());
updatedConsultor
.nome(UPDATED_NOME)
.dataprimeiroregistro(UPDATED_DATAPRIMEIROREGISTRO)
.dataultimoregistro(UPDATED_DATAULTIMOREGISTRO)
.flativo(UPDATED_FLATIVO);
restConsultorMockMvc.perform(put("/api/consultors")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(updatedConsultor)))
.andExpect(status().isOk());
// Validate the Consultor in the database
List<Consultor> consultorList = consultorRepository.findAll();
assertThat(consultorList).hasSize(databaseSizeBeforeUpdate);
Consultor testConsultor = consultorList.get(consultorList.size() - 1);
assertThat(testConsultor.getNome()).isEqualTo(UPDATED_NOME);
assertThat(testConsultor.getDataprimeiroregistro()).isEqualTo(UPDATED_DATAPRIMEIROREGISTRO);
assertThat(testConsultor.getDataultimoregistro()).isEqualTo(UPDATED_DATAULTIMOREGISTRO);
assertThat(testConsultor.getFlativo()).isEqualTo(UPDATED_FLATIVO);
}
@Test
@Transactional
public void updateNonExistingConsultor() throws Exception {
int databaseSizeBeforeUpdate = consultorRepository.findAll().size();
// Create the Consultor
// If the entity doesn't have an ID, it will be created instead of just being updated
restConsultorMockMvc.perform(put("/api/consultors")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(consultor)))
.andExpect(status().isCreated());
// Validate the Consultor in the database
List<Consultor> consultorList = consultorRepository.findAll();
assertThat(consultorList).hasSize(databaseSizeBeforeUpdate + 1);
}
@Test
@Transactional
public void deleteConsultor() throws Exception {
// Initialize the database
consultorRepository.saveAndFlush(consultor);
int databaseSizeBeforeDelete = consultorRepository.findAll().size();
// Get the consultor
restConsultorMockMvc.perform(delete("/api/consultors/{id}", consultor.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
// Validate the database is empty
List<Consultor> consultorList = consultorRepository.findAll();
assertThat(consultorList).hasSize(databaseSizeBeforeDelete - 1);
}
@Test
@Transactional
public void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(Consultor.class);
Consultor consultor1 = new Consultor();
consultor1.setId(1L);
Consultor consultor2 = new Consultor();
consultor2.setId(consultor1.getId());
assertThat(consultor1).isEqualTo(consultor2);
consultor2.setId(2L);
assertThat(consultor1).isNotEqualTo(consultor2);
consultor1.setId(null);
assertThat(consultor1).isNotEqualTo(consultor2);
}
}
| UTF-8 | Java | 13,706 | java | ConsultorResourceIntTest.java | Java | [] | null | [] | package br.com.tools.manager.web.rest;
import br.com.tools.manager.ManagerApp;
import br.com.tools.manager.domain.Consultor;
import br.com.tools.manager.repository.ConsultorRepository;
import br.com.tools.manager.web.rest.errors.ExceptionTranslator;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import br.com.tools.manager.domain.enumeration.ConsultorStatus;
/**
* Test class for the ConsultorResource REST controller.
*
* @see ConsultorResource
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ManagerApp.class)
public class ConsultorResourceIntTest {
private static final String DEFAULT_NOME = "AAAAAAAAAA";
private static final String UPDATED_NOME = "BBBBBBBBBB";
private static final LocalDate DEFAULT_DATAPRIMEIROREGISTRO = LocalDate.ofEpochDay(0L);
private static final LocalDate UPDATED_DATAPRIMEIROREGISTRO = LocalDate.now(ZoneId.systemDefault());
private static final LocalDate DEFAULT_DATAULTIMOREGISTRO = LocalDate.ofEpochDay(0L);
private static final LocalDate UPDATED_DATAULTIMOREGISTRO = LocalDate.now(ZoneId.systemDefault());
private static final ConsultorStatus DEFAULT_FLATIVO = ConsultorStatus.ATIVADO;
private static final ConsultorStatus UPDATED_FLATIVO = ConsultorStatus.DESATIVADO;
@Autowired
private ConsultorRepository consultorRepository;
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
@Autowired
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
@Autowired
private ExceptionTranslator exceptionTranslator;
@Autowired
private EntityManager em;
private MockMvc restConsultorMockMvc;
private Consultor consultor;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
ConsultorResource consultorResource = new ConsultorResource(consultorRepository);
this.restConsultorMockMvc = MockMvcBuilders.standaloneSetup(consultorResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setMessageConverters(jacksonMessageConverter).build();
}
/**
* Create an entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Consultor createEntity(EntityManager em) {
Consultor consultor = new Consultor()
.nome(DEFAULT_NOME)
.dataprimeiroregistro(DEFAULT_DATAPRIMEIROREGISTRO)
.dataultimoregistro(DEFAULT_DATAULTIMOREGISTRO)
.flativo(DEFAULT_FLATIVO);
return consultor;
}
@Before
public void initTest() {
consultor = createEntity(em);
}
@Test
@Transactional
public void createConsultor() throws Exception {
int databaseSizeBeforeCreate = consultorRepository.findAll().size();
// Create the Consultor
restConsultorMockMvc.perform(post("/api/consultors")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(consultor)))
.andExpect(status().isCreated());
// Validate the Consultor in the database
List<Consultor> consultorList = consultorRepository.findAll();
assertThat(consultorList).hasSize(databaseSizeBeforeCreate + 1);
Consultor testConsultor = consultorList.get(consultorList.size() - 1);
assertThat(testConsultor.getNome()).isEqualTo(DEFAULT_NOME);
assertThat(testConsultor.getDataprimeiroregistro()).isEqualTo(DEFAULT_DATAPRIMEIROREGISTRO);
assertThat(testConsultor.getDataultimoregistro()).isEqualTo(DEFAULT_DATAULTIMOREGISTRO);
assertThat(testConsultor.getFlativo()).isEqualTo(DEFAULT_FLATIVO);
}
@Test
@Transactional
public void createConsultorWithExistingId() throws Exception {
int databaseSizeBeforeCreate = consultorRepository.findAll().size();
// Create the Consultor with an existing ID
consultor.setId(1L);
// An entity with an existing ID cannot be created, so this API call must fail
restConsultorMockMvc.perform(post("/api/consultors")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(consultor)))
.andExpect(status().isBadRequest());
// Validate the Alice in the database
List<Consultor> consultorList = consultorRepository.findAll();
assertThat(consultorList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
public void checkNomeIsRequired() throws Exception {
int databaseSizeBeforeTest = consultorRepository.findAll().size();
// set the field null
consultor.setNome(null);
// Create the Consultor, which fails.
restConsultorMockMvc.perform(post("/api/consultors")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(consultor)))
.andExpect(status().isBadRequest());
List<Consultor> consultorList = consultorRepository.findAll();
assertThat(consultorList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void checkDataprimeiroregistroIsRequired() throws Exception {
int databaseSizeBeforeTest = consultorRepository.findAll().size();
// set the field null
consultor.setDataprimeiroregistro(null);
// Create the Consultor, which fails.
restConsultorMockMvc.perform(post("/api/consultors")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(consultor)))
.andExpect(status().isBadRequest());
List<Consultor> consultorList = consultorRepository.findAll();
assertThat(consultorList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void checkDataultimoregistroIsRequired() throws Exception {
int databaseSizeBeforeTest = consultorRepository.findAll().size();
// set the field null
consultor.setDataultimoregistro(null);
// Create the Consultor, which fails.
restConsultorMockMvc.perform(post("/api/consultors")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(consultor)))
.andExpect(status().isBadRequest());
List<Consultor> consultorList = consultorRepository.findAll();
assertThat(consultorList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void checkFlativoIsRequired() throws Exception {
int databaseSizeBeforeTest = consultorRepository.findAll().size();
// set the field null
consultor.setFlativo(null);
// Create the Consultor, which fails.
restConsultorMockMvc.perform(post("/api/consultors")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(consultor)))
.andExpect(status().isBadRequest());
List<Consultor> consultorList = consultorRepository.findAll();
assertThat(consultorList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void getAllConsultors() throws Exception {
// Initialize the database
consultorRepository.saveAndFlush(consultor);
// Get all the consultorList
restConsultorMockMvc.perform(get("/api/consultors?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(consultor.getId().intValue())))
.andExpect(jsonPath("$.[*].nome").value(hasItem(DEFAULT_NOME.toString())))
.andExpect(jsonPath("$.[*].dataprimeiroregistro").value(hasItem(DEFAULT_DATAPRIMEIROREGISTRO.toString())))
.andExpect(jsonPath("$.[*].dataultimoregistro").value(hasItem(DEFAULT_DATAULTIMOREGISTRO.toString())))
.andExpect(jsonPath("$.[*].flativo").value(hasItem(DEFAULT_FLATIVO.toString())));
}
@Test
@Transactional
public void getConsultor() throws Exception {
// Initialize the database
consultorRepository.saveAndFlush(consultor);
// Get the consultor
restConsultorMockMvc.perform(get("/api/consultors/{id}", consultor.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.id").value(consultor.getId().intValue()))
.andExpect(jsonPath("$.nome").value(DEFAULT_NOME.toString()))
.andExpect(jsonPath("$.dataprimeiroregistro").value(DEFAULT_DATAPRIMEIROREGISTRO.toString()))
.andExpect(jsonPath("$.dataultimoregistro").value(DEFAULT_DATAULTIMOREGISTRO.toString()))
.andExpect(jsonPath("$.flativo").value(DEFAULT_FLATIVO.toString()));
}
@Test
@Transactional
public void getNonExistingConsultor() throws Exception {
// Get the consultor
restConsultorMockMvc.perform(get("/api/consultors/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
}
@Test
@Transactional
public void updateConsultor() throws Exception {
// Initialize the database
consultorRepository.saveAndFlush(consultor);
int databaseSizeBeforeUpdate = consultorRepository.findAll().size();
// Update the consultor
Consultor updatedConsultor = consultorRepository.findOne(consultor.getId());
updatedConsultor
.nome(UPDATED_NOME)
.dataprimeiroregistro(UPDATED_DATAPRIMEIROREGISTRO)
.dataultimoregistro(UPDATED_DATAULTIMOREGISTRO)
.flativo(UPDATED_FLATIVO);
restConsultorMockMvc.perform(put("/api/consultors")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(updatedConsultor)))
.andExpect(status().isOk());
// Validate the Consultor in the database
List<Consultor> consultorList = consultorRepository.findAll();
assertThat(consultorList).hasSize(databaseSizeBeforeUpdate);
Consultor testConsultor = consultorList.get(consultorList.size() - 1);
assertThat(testConsultor.getNome()).isEqualTo(UPDATED_NOME);
assertThat(testConsultor.getDataprimeiroregistro()).isEqualTo(UPDATED_DATAPRIMEIROREGISTRO);
assertThat(testConsultor.getDataultimoregistro()).isEqualTo(UPDATED_DATAULTIMOREGISTRO);
assertThat(testConsultor.getFlativo()).isEqualTo(UPDATED_FLATIVO);
}
@Test
@Transactional
public void updateNonExistingConsultor() throws Exception {
int databaseSizeBeforeUpdate = consultorRepository.findAll().size();
// Create the Consultor
// If the entity doesn't have an ID, it will be created instead of just being updated
restConsultorMockMvc.perform(put("/api/consultors")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(consultor)))
.andExpect(status().isCreated());
// Validate the Consultor in the database
List<Consultor> consultorList = consultorRepository.findAll();
assertThat(consultorList).hasSize(databaseSizeBeforeUpdate + 1);
}
@Test
@Transactional
public void deleteConsultor() throws Exception {
// Initialize the database
consultorRepository.saveAndFlush(consultor);
int databaseSizeBeforeDelete = consultorRepository.findAll().size();
// Get the consultor
restConsultorMockMvc.perform(delete("/api/consultors/{id}", consultor.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
// Validate the database is empty
List<Consultor> consultorList = consultorRepository.findAll();
assertThat(consultorList).hasSize(databaseSizeBeforeDelete - 1);
}
@Test
@Transactional
public void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(Consultor.class);
Consultor consultor1 = new Consultor();
consultor1.setId(1L);
Consultor consultor2 = new Consultor();
consultor2.setId(consultor1.getId());
assertThat(consultor1).isEqualTo(consultor2);
consultor2.setId(2L);
assertThat(consultor1).isNotEqualTo(consultor2);
consultor1.setId(null);
assertThat(consultor1).isNotEqualTo(consultor2);
}
}
| 13,706 | 0.70896 | 0.70626 | 337 | 39.670624 | 30.305098 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.385757 | false | false | 12 |
0c6e68295e3ad3aa10f3ee430a6f87f49d16e961 | 33,904,471,866,080 | 9ea6b3956e30e641a94bc01fce432aff4e0e952a | /Linguagem_e_Programação_Orientada/20180417/src/mifuder/umaclasse.java | c5d5ee885992e72ca8c60258486a728bda1db4a2 | [] | no_license | juniorsaldanha/UFMS | https://github.com/juniorsaldanha/UFMS | 07d0d46ba4b9f0ed3a7d529f5b34bc738e924819 | 2ce51826de2d4fd69a330f806f69d6ee53dc64b4 | refs/heads/master | 2022-12-14T13:09:44.149000 | 2020-08-12T19:21:53 | 2020-08-12T19:21:53 | 287,097,120 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package mifuder;
public class umaclasse {
char a;
public umaclasse(char x) {
// TODO Auto-generated constructor stub
this.a = x;
}
public void print_a(){
System.out.println("a = " +a);
}
/*public boolean equals(umaclasse b)
{
return this.a == b.a;
}*/
public String toString()
{
return "a = '"+a+"'";
}
}
| UTF-8 | Java | 330 | java | umaclasse.java | Java | [] | null | [] | package mifuder;
public class umaclasse {
char a;
public umaclasse(char x) {
// TODO Auto-generated constructor stub
this.a = x;
}
public void print_a(){
System.out.println("a = " +a);
}
/*public boolean equals(umaclasse b)
{
return this.a == b.a;
}*/
public String toString()
{
return "a = '"+a+"'";
}
}
| 330 | 0.609091 | 0.609091 | 22 | 14 | 13.152946 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.272727 | false | false | 12 |
5798f54739cf60f8dc0a8dd9e170e7b2352cec23 | 23,003,844,863,850 | 515a719c23e019f68978f437caf5206c24fb3749 | /app/src/main/java/com/example/timisoara/material_cal.java | 5b050b1b0669179e8ae7d10937560a64bd003b57 | [] | no_license | andreimiclea99/Visit-Timisoara | https://github.com/andreimiclea99/Visit-Timisoara | 47e5638ed67cb695963b2a3b95a3d4af32e53b35 | 868bc3574661892c79804215036feea424cb84f1 | refs/heads/master | 2020-05-16T00:54:26.626000 | 2019-07-12T14:59:32 | 2019-07-12T14:59:32 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.timisoara;
import android.support.design.card.MaterialCardView;
import android.support.design.drawable.DrawableUtils;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import com.applandeo.materialcalendarview.CalendarView;
import com.applandeo.materialcalendarview.EventDay;
import com.applandeo.materialcalendarview.exceptions.OutOfDateRangeException;
import com.applandeo.materialcalendarview.utils.DateUtils;
import com.applandeo.materialcalendarview.CalendarView;
import com.applandeo.materialcalendarview.EventDay;
import com.applandeo.materialcalendarview.exceptions.OutOfDateRangeException;
import com.applandeo.materialcalendarview.utils.DateUtils;
import com.applandeo.materialcalendarview.EventDay;
import com.applandeo.materialcalendarview.listeners.OnDayClickListener;
import com.applandeo.materialcalendarview.listeners.OnSelectDateListener;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
public class material_cal extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_material_cal);
CalendarView mat = findViewById(R.id.calendarView);
mat.setOnDayClickListener(eventDay ->
Toast.makeText(getApplicationContext(),
eventDay.getCalendar().getTime().toString() + " "
+ eventDay.isEnabled(),
Toast.LENGTH_SHORT).show());
// Calendar calendar = Calendar.getInstance();
/* mat.state().edit()
.setFirstDayOfWeek(Calendar.MONDAY)
.setMinimumDate(CalendarDay.from(1900, 1, 1))
.setMaximumDate(CalendarDay.from(2100, 12, 31))
.setCalendarDisplayMode(CalendarMode.MONTHS)
.commit();
calendar.set(2019, 5, 31);
mat.setDate(calendar);*/
List<EventDay> events = new ArrayList<>();
Calendar calendar1 = Calendar.getInstance();
calendar1.add(Calendar.DAY_OF_MONTH, 2);
events.add(new EventDay(calendar1, R.drawable.sample));
Calendar calendar2 = Calendar.getInstance();
calendar2.add(Calendar.DAY_OF_MONTH, 5);
events.add(new EventDay(calendar2, R.drawable.sample));
Calendar calendar3 = Calendar.getInstance();
calendar3.add(Calendar.DAY_OF_MONTH, 7);
events.add(new EventDay(calendar3, R.drawable.sample));
Calendar min = Calendar.getInstance();
min.add(Calendar.MONTH, -4);
Calendar max = Calendar.getInstance();
max.add(Calendar.MONTH, 4);
mat.setMinimumDate(min);
mat.setMaximumDate(max);
mat.setEvents(events);
}
}
| UTF-8 | Java | 2,871 | java | material_cal.java | Java | [
{
"context": "package com.example.timisoara;\n\nimport android.support.design.card.MaterialCard",
"end": 29,
"score": 0.7530329823493958,
"start": 20,
"tag": "USERNAME",
"value": "timisoara"
}
] | null | [] | package com.example.timisoara;
import android.support.design.card.MaterialCardView;
import android.support.design.drawable.DrawableUtils;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import com.applandeo.materialcalendarview.CalendarView;
import com.applandeo.materialcalendarview.EventDay;
import com.applandeo.materialcalendarview.exceptions.OutOfDateRangeException;
import com.applandeo.materialcalendarview.utils.DateUtils;
import com.applandeo.materialcalendarview.CalendarView;
import com.applandeo.materialcalendarview.EventDay;
import com.applandeo.materialcalendarview.exceptions.OutOfDateRangeException;
import com.applandeo.materialcalendarview.utils.DateUtils;
import com.applandeo.materialcalendarview.EventDay;
import com.applandeo.materialcalendarview.listeners.OnDayClickListener;
import com.applandeo.materialcalendarview.listeners.OnSelectDateListener;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
public class material_cal extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_material_cal);
CalendarView mat = findViewById(R.id.calendarView);
mat.setOnDayClickListener(eventDay ->
Toast.makeText(getApplicationContext(),
eventDay.getCalendar().getTime().toString() + " "
+ eventDay.isEnabled(),
Toast.LENGTH_SHORT).show());
// Calendar calendar = Calendar.getInstance();
/* mat.state().edit()
.setFirstDayOfWeek(Calendar.MONDAY)
.setMinimumDate(CalendarDay.from(1900, 1, 1))
.setMaximumDate(CalendarDay.from(2100, 12, 31))
.setCalendarDisplayMode(CalendarMode.MONTHS)
.commit();
calendar.set(2019, 5, 31);
mat.setDate(calendar);*/
List<EventDay> events = new ArrayList<>();
Calendar calendar1 = Calendar.getInstance();
calendar1.add(Calendar.DAY_OF_MONTH, 2);
events.add(new EventDay(calendar1, R.drawable.sample));
Calendar calendar2 = Calendar.getInstance();
calendar2.add(Calendar.DAY_OF_MONTH, 5);
events.add(new EventDay(calendar2, R.drawable.sample));
Calendar calendar3 = Calendar.getInstance();
calendar3.add(Calendar.DAY_OF_MONTH, 7);
events.add(new EventDay(calendar3, R.drawable.sample));
Calendar min = Calendar.getInstance();
min.add(Calendar.MONTH, -4);
Calendar max = Calendar.getInstance();
max.add(Calendar.MONTH, 4);
mat.setMinimumDate(min);
mat.setMaximumDate(max);
mat.setEvents(events);
}
}
| 2,871 | 0.706722 | 0.693835 | 86 | 32.38372 | 25.290483 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.72093 | false | false | 12 |
1567fd5f4114453b62ea1b2660762421213da396 | 23,003,844,862,570 | 5507747b0ee7c41c62a36fe07fde92ad2516c2fe | /Assignment2/src/WordApp.java | 818650183f1879b65f8936f899c2b98b769bb242 | [] | no_license | adamchin1/CSC2002-Assignment2 | https://github.com/adamchin1/CSC2002-Assignment2 | 55ea4de14c9a7c8ab60c598fe88b46638b8c43cc | 577e62de69c9bb111ce57eb6986a473ab41e68e4 | refs/heads/master | 2021-06-27T16:56:16.256000 | 2017-09-17T08:49:25 | 2017-09-17T08:49:25 | 103,113,497 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;
import java.util.concurrent.*;
import java.util.logging.Level;
import java.util.logging.Logger;
//model is separate from the view.
public class WordApp {
//shared variables
static int noWords = 4;
static int totalWords;
static int frameX = 1000;
static int frameY = 600;
static int yLimit = 480;
static WordDictionary dict = new WordDictionary(); //use default dictionary, to read from file eventually
static WordRecord[] words;
static volatile boolean done; //must be volatile
static volatile boolean pushed;
static Score score = new Score();
static WordPanel w;
static String fieldText = "";
static JLabel caught;
static JLabel missed;
static JLabel scr;
static JComboBox<String> cb;
static int startClicked = 0;
static int difficulty;
public static void updateGUI() {
caught.setText("Caught: " + score.getCaught() + " ");
missed.setText("Missed:" + score.getMissed() + " ");
scr.setText("Score:" + score.getScore() + " ");
}
public static void resetAll(WordRecord[] words) {
for (int i = 0; i < noWords; i++) {
words[i].resetWord();
}
}
public static int getDifficulty(JComboBox<String> cb) {
switch (cb.getSelectedItem().toString()) {
case "Easy":
return 1;
case "Medium":
return 2;
case "Hard":
return 3;
default:
return 100;
}
}
public static void setupGUI(int frameX, int frameY, int yLimit) {
// Frame init and dimensions
JFrame frame = new JFrame("WordGame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(frameX, frameY);
JPanel g = new JPanel();
g.setLayout(new BoxLayout(g, BoxLayout.PAGE_AXIS));
g.setSize(frameX, frameY);
w = new WordPanel(words, yLimit);
w.setSize(frameX, yLimit + 100);
g.add(w);
JPanel txt = new JPanel();
txt.setLayout(new BoxLayout(txt, BoxLayout.LINE_AXIS));
caught = new JLabel("Caught: " + score.getCaught() + " ");
missed = new JLabel("Missed:" + score.getMissed() + " ");
scr = new JLabel("Score:" + score.getScore() + " ");
txt.add(caught);
txt.add(missed);
txt.add(scr);
//[snip]
final JTextField textEntry = new JTextField("", 20);
textEntry.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
String text = textEntry.getText();
fieldText = text;
textEntry.setText("");
textEntry.requestFocus();
}
});
txt.add(textEntry);
txt.setMaximumSize(txt.getPreferredSize());
String[] choices = {"Easy", "Medium", "Hard"};
cb = new JComboBox<String>(choices);
cb.setVisible(true);
txt.add(cb);
g.add(txt);
JPanel b = new JPanel();
b.setLayout(new BoxLayout(b, BoxLayout.LINE_AXIS));
JButton startB = new JButton("Start");
// add the listener to the jbutton to handle the "pressed" event
startB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
startClicked++;
done = false;
cb.setEditable(false);
if (done == false) {
if (startClicked == 1) {
for (int i = 0; i < noWords; i++) {
Thread t = new Thread(w);
t.start();
textEntry.requestFocus();
}
}
}
//return focus to the text entry field
}
});
JButton endB = new JButton("End");
// add the listener to the jbutton to handle the "pressed" event
endB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
done = true;
startClicked = 0;
cb.setEnabled(true);
resetAll(w.words);
w.repaint();
}
});
JButton quitB = new JButton("Quit");
quitB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//call another method in the same class which will close this Jframe
frame.dispose();
}
});
b.add(startB);
b.add(endB);
b.add(quitB);
g.add(b);
frame.setLocationRelativeTo(null); // Center window on screen.
frame.add(g); //add contents to window
frame.setContentPane(g);
//frame.pack(); // don't do this - packs it into small space
frame.setVisible(true);
}
public static String[] getDictFromFile(String filename) {
String[] dictStr = null;
try {
Scanner dictReader = new Scanner(new FileInputStream(filename));
int dictLength = dictReader.nextInt();
//System.out.println("read '" + dictLength+"'");
dictStr = new String[dictLength];
for (int i = 0; i < dictLength; i++) {
dictStr[i] = new String(dictReader.next());
//System.out.println(i+ " read '" + dictStr[i]+"'"); //for checking
}
dictReader.close();
} catch (IOException e) {
System.err.println("Problem reading file " + filename + " default dictionary will be used");
}
return dictStr;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); //10 2 example_dict.txt
String s = "100 5 example_dict.txt";
String[] stuff = s.split(" ");
//deal with command line arguments
totalWords = Integer.parseInt(stuff[0]); //total words to fall
noWords = Integer.parseInt(stuff[1]); // total words falling at any point
assert (totalWords >= noWords); // this could be done more neatly
String[] tmpDict = getDictFromFile(stuff[2]); //file of words
if (tmpDict != null) {
dict = new WordDictionary(tmpDict);
}
WordRecord.dict = dict; //set the class dictionary for the words.
words = new WordRecord[noWords]; //shared array of current words
//[snip]
setupGUI(frameX, frameY, yLimit);
//Start WordPanel thread - for redrawing animation
int x_inc = (int) frameX / noWords;
//initialize shared array of current words
for (int i = 0; i < noWords; i++) {
words[i] = new WordRecord(dict.getNewWord(), i * x_inc, yLimit);
}
}
}
| UTF-8 | Java | 7,119 | java | WordApp.java | Java | [] | null | [] |
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;
import java.util.concurrent.*;
import java.util.logging.Level;
import java.util.logging.Logger;
//model is separate from the view.
public class WordApp {
//shared variables
static int noWords = 4;
static int totalWords;
static int frameX = 1000;
static int frameY = 600;
static int yLimit = 480;
static WordDictionary dict = new WordDictionary(); //use default dictionary, to read from file eventually
static WordRecord[] words;
static volatile boolean done; //must be volatile
static volatile boolean pushed;
static Score score = new Score();
static WordPanel w;
static String fieldText = "";
static JLabel caught;
static JLabel missed;
static JLabel scr;
static JComboBox<String> cb;
static int startClicked = 0;
static int difficulty;
public static void updateGUI() {
caught.setText("Caught: " + score.getCaught() + " ");
missed.setText("Missed:" + score.getMissed() + " ");
scr.setText("Score:" + score.getScore() + " ");
}
public static void resetAll(WordRecord[] words) {
for (int i = 0; i < noWords; i++) {
words[i].resetWord();
}
}
public static int getDifficulty(JComboBox<String> cb) {
switch (cb.getSelectedItem().toString()) {
case "Easy":
return 1;
case "Medium":
return 2;
case "Hard":
return 3;
default:
return 100;
}
}
public static void setupGUI(int frameX, int frameY, int yLimit) {
// Frame init and dimensions
JFrame frame = new JFrame("WordGame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(frameX, frameY);
JPanel g = new JPanel();
g.setLayout(new BoxLayout(g, BoxLayout.PAGE_AXIS));
g.setSize(frameX, frameY);
w = new WordPanel(words, yLimit);
w.setSize(frameX, yLimit + 100);
g.add(w);
JPanel txt = new JPanel();
txt.setLayout(new BoxLayout(txt, BoxLayout.LINE_AXIS));
caught = new JLabel("Caught: " + score.getCaught() + " ");
missed = new JLabel("Missed:" + score.getMissed() + " ");
scr = new JLabel("Score:" + score.getScore() + " ");
txt.add(caught);
txt.add(missed);
txt.add(scr);
//[snip]
final JTextField textEntry = new JTextField("", 20);
textEntry.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
String text = textEntry.getText();
fieldText = text;
textEntry.setText("");
textEntry.requestFocus();
}
});
txt.add(textEntry);
txt.setMaximumSize(txt.getPreferredSize());
String[] choices = {"Easy", "Medium", "Hard"};
cb = new JComboBox<String>(choices);
cb.setVisible(true);
txt.add(cb);
g.add(txt);
JPanel b = new JPanel();
b.setLayout(new BoxLayout(b, BoxLayout.LINE_AXIS));
JButton startB = new JButton("Start");
// add the listener to the jbutton to handle the "pressed" event
startB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
startClicked++;
done = false;
cb.setEditable(false);
if (done == false) {
if (startClicked == 1) {
for (int i = 0; i < noWords; i++) {
Thread t = new Thread(w);
t.start();
textEntry.requestFocus();
}
}
}
//return focus to the text entry field
}
});
JButton endB = new JButton("End");
// add the listener to the jbutton to handle the "pressed" event
endB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
done = true;
startClicked = 0;
cb.setEnabled(true);
resetAll(w.words);
w.repaint();
}
});
JButton quitB = new JButton("Quit");
quitB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//call another method in the same class which will close this Jframe
frame.dispose();
}
});
b.add(startB);
b.add(endB);
b.add(quitB);
g.add(b);
frame.setLocationRelativeTo(null); // Center window on screen.
frame.add(g); //add contents to window
frame.setContentPane(g);
//frame.pack(); // don't do this - packs it into small space
frame.setVisible(true);
}
public static String[] getDictFromFile(String filename) {
String[] dictStr = null;
try {
Scanner dictReader = new Scanner(new FileInputStream(filename));
int dictLength = dictReader.nextInt();
//System.out.println("read '" + dictLength+"'");
dictStr = new String[dictLength];
for (int i = 0; i < dictLength; i++) {
dictStr[i] = new String(dictReader.next());
//System.out.println(i+ " read '" + dictStr[i]+"'"); //for checking
}
dictReader.close();
} catch (IOException e) {
System.err.println("Problem reading file " + filename + " default dictionary will be used");
}
return dictStr;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); //10 2 example_dict.txt
String s = "100 5 example_dict.txt";
String[] stuff = s.split(" ");
//deal with command line arguments
totalWords = Integer.parseInt(stuff[0]); //total words to fall
noWords = Integer.parseInt(stuff[1]); // total words falling at any point
assert (totalWords >= noWords); // this could be done more neatly
String[] tmpDict = getDictFromFile(stuff[2]); //file of words
if (tmpDict != null) {
dict = new WordDictionary(tmpDict);
}
WordRecord.dict = dict; //set the class dictionary for the words.
words = new WordRecord[noWords]; //shared array of current words
//[snip]
setupGUI(frameX, frameY, yLimit);
//Start WordPanel thread - for redrawing animation
int x_inc = (int) frameX / noWords;
//initialize shared array of current words
for (int i = 0; i < noWords; i++) {
words[i] = new WordRecord(dict.getNewWord(), i * x_inc, yLimit);
}
}
}
| 7,119 | 0.548954 | 0.543475 | 230 | 29.947826 | 23.960781 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.621739 | false | false | 12 |
657f2fea29fb1208881757466f5356ddf0873d7f | 34,127,810,169,566 | 94d577c8678e8f419d236037fe45d44d9b92eade | /src/com/team/chatPro/DBManager.java | 16796b6029bc45df62e1b6dfb1ba6675aaac5335 | [] | no_license | gmlwnr92/ChattingProgram | https://github.com/gmlwnr92/ChattingProgram | b723074e33c09833baf15c698f818085a0ce2b59 | ab42f05221602cd42b40e7374ea8190e8027d486 | refs/heads/master | 2016-09-06T08:27:24.753000 | 2015-03-07T11:45:45 | 2015-03-07T11:46:22 | 31,810,349 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.team.chatPro;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JOptionPane;
public class DBManager {
//디비연결추가
//디비 연결을 위한 주소 ,드라이버, 아디, 비번을 스트링에 담음
private static String CLASS_NAME = "oracle.jdbc.driver.OracleDriver";
private static String URL = "jdbc:oracle:thin:@192.168.99.66:1521:XE";
private static String DB_ID = "scott";
private static String DB_PASS = "TIGER";
private static Connection CONN; // 커넥션이라는 메소드 디비연결할때 씀
//192.168.99.66 1234 1234
public static Connection getConnection() {
try {
/* 오라클 DBMS에 접속하기 위해 동적으로 OracleDriver를 메모리에 로딩하고
* OriverDriver 객체는 DriverManager의 static 멤버 변수에 저장된다.
* 즉 Class.forName()는 DriverManager 객체를 생성하고
* 지정한 드라이버를 DriverManager 객체에 등록해 주는 메소드이다.
**/
Class.forName(CLASS_NAME);
/* DriverManager를 이용해 DB Connection 객체를 얻는다.
* DriverManager 객체는 Java 응용프로그램을 JDBC 드라이버와
* 연결하고 실제 DBMS에 접속하여 활성화된 Connection 객체를 리턴 한다.
**/
CONN = DriverManager.getConnection(URL, DB_ID, DB_PASS);
} catch (ClassNotFoundException e) {
System.out.println("Driver 로딩 실패!");
System.out.println(e.getMessage());
return null;
} catch (SQLException e) {
System.out.println("SQLException 발생!");
System.out.println(e.getMessage());
e.printStackTrace();
return null;
} /*catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "DB가 닫혀있습니다.", "메시지", JOptionPane.INFORMATION_MESSAGE);
// TODO Auto-generated catch block
e.printStackTrace();
}*/
// DB에 연결된 Connection 객체를 리턴 한다.
return CONN;
}
public static void close(Connection conn, PreparedStatement pstmt) {// DB 작업에 사용된 자원을 해제하는 메소드
try { //닫는 메소드 순서는 객체만든 순서 반대로 여긴 접속만 쿼리없음
if(pstmt != null) pstmt.close();
if(conn != null) conn.close();
} catch(SQLException e) { e.printStackTrace(); }
}
public static void close(Connection conn,
PreparedStatement pstmt, ResultSet rs) {// DB 작업에 사용된 자원, 쿼리를 해제하는 메소드
try {
if(rs != null) rs.close(); //결과
if(pstmt != null) pstmt.close(); //쿼리
if(conn != null) conn.close(); //연결
} catch(SQLException e) { e.printStackTrace(); }
}
}
| UTF-8 | Java | 3,022 | java | DBManager.java | Java | [
{
"context": "\n\t\tprivate static String URL = \"jdbc:oracle:thin:@192.168.99.66:1521:XE\";\n\t\tprivate static String DB_ID = \"scott\"",
"end": 511,
"score": 0.999727189540863,
"start": 498,
"tag": "IP_ADDRESS",
"value": "192.168.99.66"
},
{
"context": "_ID = \"scott\";\n\t\tpriva... | null | [] | package com.team.chatPro;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JOptionPane;
public class DBManager {
//디비연결추가
//디비 연결을 위한 주소 ,드라이버, 아디, 비번을 스트링에 담음
private static String CLASS_NAME = "oracle.jdbc.driver.OracleDriver";
private static String URL = "jdbc:oracle:thin:@192.168.99.66:1521:XE";
private static String DB_ID = "scott";
private static String DB_PASS = "<PASSWORD>";
private static Connection CONN; // 커넥션이라는 메소드 디비연결할때 씀
//192.168.99.66 1234 1234
public static Connection getConnection() {
try {
/* 오라클 DBMS에 접속하기 위해 동적으로 OracleDriver를 메모리에 로딩하고
* OriverDriver 객체는 DriverManager의 static 멤버 변수에 저장된다.
* 즉 Class.forName()는 DriverManager 객체를 생성하고
* 지정한 드라이버를 DriverManager 객체에 등록해 주는 메소드이다.
**/
Class.forName(CLASS_NAME);
/* DriverManager를 이용해 DB Connection 객체를 얻는다.
* DriverManager 객체는 Java 응용프로그램을 JDBC 드라이버와
* 연결하고 실제 DBMS에 접속하여 활성화된 Connection 객체를 리턴 한다.
**/
CONN = DriverManager.getConnection(URL, DB_ID, DB_PASS);
} catch (ClassNotFoundException e) {
System.out.println("Driver 로딩 실패!");
System.out.println(e.getMessage());
return null;
} catch (SQLException e) {
System.out.println("SQLException 발생!");
System.out.println(e.getMessage());
e.printStackTrace();
return null;
} /*catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "DB가 닫혀있습니다.", "메시지", JOptionPane.INFORMATION_MESSAGE);
// TODO Auto-generated catch block
e.printStackTrace();
}*/
// DB에 연결된 Connection 객체를 리턴 한다.
return CONN;
}
public static void close(Connection conn, PreparedStatement pstmt) {// DB 작업에 사용된 자원을 해제하는 메소드
try { //닫는 메소드 순서는 객체만든 순서 반대로 여긴 접속만 쿼리없음
if(pstmt != null) pstmt.close();
if(conn != null) conn.close();
} catch(SQLException e) { e.printStackTrace(); }
}
public static void close(Connection conn,
PreparedStatement pstmt, ResultSet rs) {// DB 작업에 사용된 자원, 쿼리를 해제하는 메소드
try {
if(rs != null) rs.close(); //결과
if(pstmt != null) pstmt.close(); //쿼리
if(conn != null) conn.close(); //연결
} catch(SQLException e) { e.printStackTrace(); }
}
}
| 3,027 | 0.666005 | 0.653296 | 85 | 28.623529 | 22.511684 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.329412 | false | false | 12 |
f09522f5a8c8df40efd0e4dfbc07466839344751 | 34,127,810,172,082 | f44d617d540abd3cc0f0039a9567b9fce0df3cd3 | /projectportal/src/main/java/com/beiyelin/projectportal/repository/EmployeeRepository.java | 192ac80ca05524c6c8bae2ef6283da0acd47e120 | [] | no_license | newmann/group | https://github.com/newmann/group | 6c753e0050eaba73cfc660211c370a11ec2c7fc0 | 5fb13c52868215e0ceaebce869e0e1d239ef3b88 | refs/heads/master | 2018-10-09T23:58:11.569000 | 2018-10-09T14:24:43 | 2018-10-09T14:24:43 | 91,869,880 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.beiyelin.projectportal.repository;
import com.beiyelin.commonsql.jpa.BaseAbstractRepository;
import com.beiyelin.commonsql.jpa.BaseAbstractRepository;
import com.beiyelin.commonsql.jpa.BaseDomainRepository;
import com.beiyelin.projectportal.entity.BorrowMoneyQualificationPool;
import com.beiyelin.projectportal.entity.Employee;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* @Author: xinsh
* @Description:
* @Date: Created in 16:38 2018/02/21.
*/
@Repository
public interface EmployeeRepository extends BaseDomainRepository<Employee,String> {
Employee findFirstByCode(String code);
Employee findFirstByCodeAndIdIsNot(String code,String id);
List<Employee> findAllByStatus(int status);
@Query(value = "select r.* from " + Employee.TABLE_NAME + " r " +
" where ((r.code like %?1%) or (r.name like %?1%)) and r.status = 10", nativeQuery = true)
List<Employee> fetchAvailableByCodeOrName(String searchStr);
// @Query(value = "select new BorrowMoneyQualificationPool(3, id, code ,name) from Employee" +
// " where ((code like %?1%) or (name like %?1%)) and status = 10")
// List<BorrowMoneyQualificationPool> fetchAvailableBorrowMoneyQualificationPoolByCodeOrName(String searchStr);
}
| UTF-8 | Java | 1,345 | java | EmployeeRepository.java | Java | [
{
"context": "pository;\n\nimport java.util.List;\n\n/**\n * @Author: xinsh\n * @Description:\n * @Date: Created in 16:38 2018",
"end": 493,
"score": 0.9996429085731506,
"start": 488,
"tag": "USERNAME",
"value": "xinsh"
}
] | null | [] | package com.beiyelin.projectportal.repository;
import com.beiyelin.commonsql.jpa.BaseAbstractRepository;
import com.beiyelin.commonsql.jpa.BaseAbstractRepository;
import com.beiyelin.commonsql.jpa.BaseDomainRepository;
import com.beiyelin.projectportal.entity.BorrowMoneyQualificationPool;
import com.beiyelin.projectportal.entity.Employee;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* @Author: xinsh
* @Description:
* @Date: Created in 16:38 2018/02/21.
*/
@Repository
public interface EmployeeRepository extends BaseDomainRepository<Employee,String> {
Employee findFirstByCode(String code);
Employee findFirstByCodeAndIdIsNot(String code,String id);
List<Employee> findAllByStatus(int status);
@Query(value = "select r.* from " + Employee.TABLE_NAME + " r " +
" where ((r.code like %?1%) or (r.name like %?1%)) and r.status = 10", nativeQuery = true)
List<Employee> fetchAvailableByCodeOrName(String searchStr);
// @Query(value = "select new BorrowMoneyQualificationPool(3, id, code ,name) from Employee" +
// " where ((code like %?1%) or (name like %?1%)) and status = 10")
// List<BorrowMoneyQualificationPool> fetchAvailableBorrowMoneyQualificationPoolByCodeOrName(String searchStr);
}
| 1,345 | 0.752416 | 0.736803 | 38 | 34.394737 | 34.197983 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.526316 | false | false | 12 |
b678c693ad9f6c80935151d33325fc1b31ab7afc | 37,108,517,447,887 | 1398124f4db580ca10d77f9401e826ffc258eb70 | /ringtail-client/src/test/java/org/yannis/ringtail/client/zookeeper/ZookeeperConsumerTest.java | 97c6a0dafc22bd47215ad913828fef2a1873c8ea | [] | no_license | YannisZhao/ringtail | https://github.com/YannisZhao/ringtail | 6a34c90a793e2ca83f71c2b94c16e6a8c9921b0d | 16caee50ab066bd9ed261b032623bc837c3f7c21 | refs/heads/master | 2021-04-15T16:16:22.700000 | 2016-07-07T14:19:25 | 2016-07-07T14:19:25 | 60,256,013 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.yannis.ringtail.client.zookeeper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Created by dell on 2016/6/30.
*/
public class ZookeeperConsumerTest {
private ZookeeperConsumer consumer;
@Before
public void init(){
consumer = new ZookeeperConsumer(new String[]{"182.168.71.129:2181"});
}
@After
public void destroy(){
}
@Test
public void doSubscribe() throws Exception {
consumer.doSubscribe(null);
while (true);
}
@Test
public void doUnsubscribe() throws Exception {
}
} | UTF-8 | Java | 637 | java | ZookeeperConsumerTest.java | Java | [
{
"context": "port static org.junit.Assert.*;\n\n/**\n * Created by dell on 2016/6/30.\n */\npublic class ZookeeperConsumerT",
"end": 177,
"score": 0.9904836416244507,
"start": 173,
"tag": "USERNAME",
"value": "dell"
},
{
"context": " consumer = new ZookeeperConsumer(new String[]{\... | null | [] | package org.yannis.ringtail.client.zookeeper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Created by dell on 2016/6/30.
*/
public class ZookeeperConsumerTest {
private ZookeeperConsumer consumer;
@Before
public void init(){
consumer = new ZookeeperConsumer(new String[]{"192.168.127.12:2181"});
}
@After
public void destroy(){
}
@Test
public void doSubscribe() throws Exception {
consumer.doSubscribe(null);
while (true);
}
@Test
public void doUnsubscribe() throws Exception {
}
} | 637 | 0.653061 | 0.618524 | 37 | 16.243244 | 18.775208 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.243243 | false | false | 12 |
af8da94ddbd41673147f379607251c9f3c4f0ea5 | 28,312,424,470,313 | 8c82f67f86af3a84ad4eefaa41586bec801e2487 | /tehtava_14/src/tehtava_14/IngredientCheese.java | ae793e3715fad96f2ce5de5fdc49123c602d3557 | [] | no_license | Hanshoijer/Suunnittelumallit | https://github.com/Hanshoijer/Suunnittelumallit | 4876b6bee0120cd8464641a6c8b7885f5f134195 | 1b38317acce13c004cebed6da66c1be0ed43d15a | refs/heads/master | 2020-09-13T17:23:32.444000 | 2019-12-09T21:32:40 | 2019-12-09T21:32:40 | 222,571,581 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package tehtava_14;
public class IngredientCheese extends Ingredient {
public IngredientCheese() {
ingredientName = "Cheese";
}
}
| UTF-8 | Java | 144 | java | IngredientCheese.java | Java | [] | null | [] | package tehtava_14;
public class IngredientCheese extends Ingredient {
public IngredientCheese() {
ingredientName = "Cheese";
}
}
| 144 | 0.708333 | 0.694444 | 8 | 16 | 17.269917 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 12 |
40ca9e7c6a324fccbb878cbe3887d9a4f5e20d81 | 17,961,553,275,734 | d970cd9e31f6c750b819298ca3cbae7b8154258a | /microse-8001/src/main/java/com/example/microse8001/entities/FoodsEntity.java | 682651bf197e22e672b68b42d5b31c610e37f596 | [] | no_license | yanpenggmx/guishi_Backstage | https://github.com/yanpenggmx/guishi_Backstage | 5ba73d4c3f91e7dde59ace48329fbb8046060769 | d94fb9fb51710ce84452ae93cd943822f902cb88 | refs/heads/master | 2020-03-29T13:05:07.400000 | 2018-11-24T06:00:25 | 2018-11-24T06:00:25 | 149,939,214 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.microse8001.entities;
import javax.persistence.*;
import java.util.Objects;
@Entity
@Table(name = "foods", schema = "guishi", catalog = "")
public class FoodsEntity {
private Integer id;
private String name;
private Double price;
private Double oldPrice;
private String description;
private Double sellCount;
private Double rating;
private String info;
private String icon;
private String image;
private Integer goodsId;
private Integer businessId;
@Basic
@Column(name = "business_id")
public Integer getBusinessId() {
return businessId;
}
public void setBusinessId(Integer businessId) {
this.businessId = businessId;
}
@Id
@Column(name = "id")
@GeneratedValue(strategy= GenerationType.IDENTITY)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Basic
@Column(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Basic
@Column(name = "price")
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
@Basic
@Column(name = "old_price")
public Double getOldPrice() {
return oldPrice;
}
public void setOldPrice(Double oldPrice) {
this.oldPrice = oldPrice;
}
@Basic
@Column(name = "description")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Basic
@Column(name = "sell_count")
public Double getSellCount() {
return sellCount;
}
public void setSellCount(Double sellCount) {
this.sellCount = sellCount;
}
@Basic
@Column(name = "rating")
public Double getRating() {
return rating;
}
public void setRating(Double rating) {
this.rating = rating;
}
@Basic
@Column(name = "info")
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
@Basic
@Column(name = "icon")
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
@Basic
@Column(name = "image")
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
@Basic
@Column(name = "goods_id")
public Integer getGoodsId() {
return goodsId;
}
public void setGoodsId(Integer goodsId) {
this.goodsId = goodsId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
FoodsEntity that = (FoodsEntity) o;
return id == that.id &&
Objects.equals(name, that.name) &&
Objects.equals(price, that.price) &&
Objects.equals(oldPrice, that.oldPrice) &&
Objects.equals(description, that.description) &&
Objects.equals(sellCount, that.sellCount) &&
Objects.equals(rating, that.rating) &&
Objects.equals(info, that.info) &&
Objects.equals(icon, that.icon) &&
Objects.equals(image, that.image) &&
Objects.equals(goodsId, that.goodsId)&&
Objects.equals(businessId, that.businessId);
}
@Override
public int hashCode() {
return Objects.hash(id, name, price, oldPrice, description, sellCount, rating, info, icon, image, goodsId,businessId);
}
}
| UTF-8 | Java | 3,818 | java | FoodsEntity.java | Java | [] | null | [] | package com.example.microse8001.entities;
import javax.persistence.*;
import java.util.Objects;
@Entity
@Table(name = "foods", schema = "guishi", catalog = "")
public class FoodsEntity {
private Integer id;
private String name;
private Double price;
private Double oldPrice;
private String description;
private Double sellCount;
private Double rating;
private String info;
private String icon;
private String image;
private Integer goodsId;
private Integer businessId;
@Basic
@Column(name = "business_id")
public Integer getBusinessId() {
return businessId;
}
public void setBusinessId(Integer businessId) {
this.businessId = businessId;
}
@Id
@Column(name = "id")
@GeneratedValue(strategy= GenerationType.IDENTITY)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Basic
@Column(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Basic
@Column(name = "price")
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
@Basic
@Column(name = "old_price")
public Double getOldPrice() {
return oldPrice;
}
public void setOldPrice(Double oldPrice) {
this.oldPrice = oldPrice;
}
@Basic
@Column(name = "description")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Basic
@Column(name = "sell_count")
public Double getSellCount() {
return sellCount;
}
public void setSellCount(Double sellCount) {
this.sellCount = sellCount;
}
@Basic
@Column(name = "rating")
public Double getRating() {
return rating;
}
public void setRating(Double rating) {
this.rating = rating;
}
@Basic
@Column(name = "info")
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
@Basic
@Column(name = "icon")
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
@Basic
@Column(name = "image")
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
@Basic
@Column(name = "goods_id")
public Integer getGoodsId() {
return goodsId;
}
public void setGoodsId(Integer goodsId) {
this.goodsId = goodsId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
FoodsEntity that = (FoodsEntity) o;
return id == that.id &&
Objects.equals(name, that.name) &&
Objects.equals(price, that.price) &&
Objects.equals(oldPrice, that.oldPrice) &&
Objects.equals(description, that.description) &&
Objects.equals(sellCount, that.sellCount) &&
Objects.equals(rating, that.rating) &&
Objects.equals(info, that.info) &&
Objects.equals(icon, that.icon) &&
Objects.equals(image, that.image) &&
Objects.equals(goodsId, that.goodsId)&&
Objects.equals(businessId, that.businessId);
}
@Override
public int hashCode() {
return Objects.hash(id, name, price, oldPrice, description, sellCount, rating, info, icon, image, goodsId,businessId);
}
}
| 3,818 | 0.584337 | 0.58329 | 166 | 22 | 19.147808 | 126 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.421687 | false | false | 12 |
13e6619eefb253b013d96bb08b463d9c1ed6759d | 29,600,914,651,468 | 0f68e790aa8895fe39bc27f9331cc33929ec98be | /raw_dataset/74183599@isOptimal@OK.java | 5525f85497be44e8dc99f922b85f99c5cc9d3134 | [
"MIT"
] | permissive | ruanyuan115/code2vec_treelstm | https://github.com/ruanyuan115/code2vec_treelstm | c50b784cbe2a576905c372675270e95e64908575 | 0c5f98d280b506317738ba603b719cac6036896f | refs/heads/master | 2023-04-09T14:11:02.992000 | 2020-04-16T08:29:59 | 2020-04-16T08:29:59 | 256,151,081 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | private static void isOptimal(int n, BufferedReader br, BufferedWriter bw) throws IOException {
HashSet<Integer> hs = new HashSet<Integer>();
int available = -1;
for (int j = 0; j < n; j++) {
String[] row = br.readLine().split(" ");
int wishLength = Integer.parseInt(row[0]);
boolean flag = true;
for (int i = 0; i < wishLength; i++) {
int x = Integer.parseInt(row[i + 1]);
if (hs.contains(x) == false) {
flag = false;
hs.add(x);
break;
}
}
if (flag == true && available == -1) {
available = j + 1;
}
}
if (hs.size() == n) {
bw.write("OPTIMAL" + "\n");
return;
}
for (int i = 1; i <= n; i++) {
if (hs.contains(i) == false) {
bw.write("IMPROVE" + "\n");
bw.write(available + " " + i + "\n");
break;
}
}
} | UTF-8 | Java | 955 | java | 74183599@isOptimal@OK.java | Java | [] | null | [] | private static void isOptimal(int n, BufferedReader br, BufferedWriter bw) throws IOException {
HashSet<Integer> hs = new HashSet<Integer>();
int available = -1;
for (int j = 0; j < n; j++) {
String[] row = br.readLine().split(" ");
int wishLength = Integer.parseInt(row[0]);
boolean flag = true;
for (int i = 0; i < wishLength; i++) {
int x = Integer.parseInt(row[i + 1]);
if (hs.contains(x) == false) {
flag = false;
hs.add(x);
break;
}
}
if (flag == true && available == -1) {
available = j + 1;
}
}
if (hs.size() == n) {
bw.write("OPTIMAL" + "\n");
return;
}
for (int i = 1; i <= n; i++) {
if (hs.contains(i) == false) {
bw.write("IMPROVE" + "\n");
bw.write(available + " " + i + "\n");
break;
}
}
} | 955 | 0.436649 | 0.428272 | 31 | 29.838709 | 19.458967 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.741935 | false | false | 12 |
77846e1fb51e0f0299e977aa6271c59a8fa44720 | 403,726,971,449 | d6416d7c97ff4421077b62a26074c6cebab8ae87 | /commonlib/src/main/java/com/wwzl/commonlib/db/DBConstants.java | 6abbfd2accdf0bd681e450f88066145b48bd3004 | [] | no_license | zhangcongmin/Android_Common | https://github.com/zhangcongmin/Android_Common | c22fc25e337c370d35daf6e677f98f34c4e264e8 | e7bcfd7107876ad8c35a3e45047c2da1d6339542 | refs/heads/master | 2021-01-03T05:17:12.592000 | 2020-02-18T10:01:37 | 2020-02-18T10:01:37 | 239,937,880 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.wwzl.commonlib.db;
public class DBConstants {
public static final String TOKEN ="token";
}
| UTF-8 | Java | 109 | java | DBConstants.java | Java | [] | null | [] | package com.wwzl.commonlib.db;
public class DBConstants {
public static final String TOKEN ="token";
}
| 109 | 0.733945 | 0.733945 | 6 | 17.166666 | 17.911045 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 12 |
01ec89eacbdfbc36e165b6ddbfe08a04b52cff61 | 22,170,621,216,068 | 9035640d0aeb1dc8bd4d55c623638cccd0a08915 | /rest/src/com/xy/admx/common/wx/SessionHandler.java | ea0f59136d04c5c4f6de2b2d9f26b228de1580bb | [] | no_license | liuwei5815/vmes | https://github.com/liuwei5815/vmes | 8db056b65c814f921cac9190552d8958df17b735 | 5d04cfa5792fde229c949de8ec85c5d794c3955c | refs/heads/master | 2021-09-17T12:44:41.738000 | 2018-01-05T06:36:44 | 2018-01-05T06:36:44 | 114,007,857 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.xy.admx.common.wx;
import java.util.UUID;
import org.apache.commons.lang3.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.xy.admx.common.JedisPoolUtil;
import com.xy.admx.common.SysConfig;
import com.xy.cms.entity.AppUser;
/**
* session 基类
* @author dg
*
*/
public class SessionHandler {
protected String session_3rd;
/**
* 生成session
* @return
*/
public SessionHandler generate3rdSession(){
session_3rd = UUID.randomUUID().toString().replace("-", "");
int expire = SysConfig.getIntValue("redis.session3rd.expire",7200000);
JedisPoolUtil.putWithExpire(session_3rd, session_3rd, expire);
return this;
}
/**
* 将用户信息存放进去
* @param userinfo
* @return
*/
public SessionHandler putUserInfo(AppUser userinfo){
String userJson = JSONObject.toJSONString(userinfo);
int expire = SysConfig.getIntValue("redis.session3rd.expire",7200000);
JedisPoolUtil.putWithExpire(this.getSession_3rd() + "_user", userJson, expire);
return this;
}
/**
* 从cache中获取用户信息
* @param sessionToken
* @return
*/
public static AppUser getAppUser(String sessionToken){
if(StringUtils.isBlank(sessionToken)){
return null;
}
return JSONObject.parseObject(JedisPoolUtil.get(sessionToken + "_user"), AppUser.class);
}
public String getSession_3rd() {
return session_3rd;
}
public boolean isSessionExist(String id,String skey){
return true;
}
}
| UTF-8 | Java | 1,520 | java | SessionHandler.java | Java | [
{
"context": ".entity.AppUser;\r\n\r\n/**\r\n * session 基类\r\n * @author dg\r\n *\r\n */\r\npublic class SessionHandler {\r\n\t\r\n\tprot",
"end": 299,
"score": 0.9988453388214111,
"start": 297,
"tag": "USERNAME",
"value": "dg"
}
] | null | [] | package com.xy.admx.common.wx;
import java.util.UUID;
import org.apache.commons.lang3.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.xy.admx.common.JedisPoolUtil;
import com.xy.admx.common.SysConfig;
import com.xy.cms.entity.AppUser;
/**
* session 基类
* @author dg
*
*/
public class SessionHandler {
protected String session_3rd;
/**
* 生成session
* @return
*/
public SessionHandler generate3rdSession(){
session_3rd = UUID.randomUUID().toString().replace("-", "");
int expire = SysConfig.getIntValue("redis.session3rd.expire",7200000);
JedisPoolUtil.putWithExpire(session_3rd, session_3rd, expire);
return this;
}
/**
* 将用户信息存放进去
* @param userinfo
* @return
*/
public SessionHandler putUserInfo(AppUser userinfo){
String userJson = JSONObject.toJSONString(userinfo);
int expire = SysConfig.getIntValue("redis.session3rd.expire",7200000);
JedisPoolUtil.putWithExpire(this.getSession_3rd() + "_user", userJson, expire);
return this;
}
/**
* 从cache中获取用户信息
* @param sessionToken
* @return
*/
public static AppUser getAppUser(String sessionToken){
if(StringUtils.isBlank(sessionToken)){
return null;
}
return JSONObject.parseObject(JedisPoolUtil.get(sessionToken + "_user"), AppUser.class);
}
public String getSession_3rd() {
return session_3rd;
}
public boolean isSessionExist(String id,String skey){
return true;
}
}
| 1,520 | 0.690798 | 0.673884 | 64 | 21.09375 | 23.377151 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.375 | false | false | 12 |
cca840303cbd1f99244cf29ad456b87891e87f63 | 6,751,688,617,036 | 4acf5ae4d3110277f962ce9da8ab0f60514be06b | /app/src/main/java/pro/alex_zaitsev/currency/object/comparator/ui/AdvertAmountComparator.java | fb53e7feb93a29e17eb79bd5db470128aeab5ef1 | [
"Apache-2.0"
] | permissive | alexzaitsev/currency-client | https://github.com/alexzaitsev/currency-client | 6f89f2db16a047f41e5c466cdf870bf25805cd25 | a02e40489ba174e7b02ca7c783a6459363d75b0c | refs/heads/master | 2021-01-25T00:11:15.082000 | 2016-04-24T10:44:53 | 2016-04-24T10:44:53 | 56,799,396 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pro.alex_zaitsev.currency.object.comparator.ui;
import pro.alex_zaitsev.currency.object.model.Advert;
/**
* Created by rocknow on 16.03.2015.
*/
public class AdvertAmountComparator extends BaseUiAdvertComparator {
@Override
public int compareValues(Advert left, Advert right) {
return Float.valueOf(left.getAmount()).compareTo(right.getAmount());
}
}
| UTF-8 | Java | 384 | java | AdvertAmountComparator.java | Java | [
{
"context": "v.currency.object.model.Advert;\n\n/**\n * Created by rocknow on 16.03.2015.\n */\npublic class AdvertAmountCompa",
"end": 137,
"score": 0.996657133102417,
"start": 130,
"tag": "USERNAME",
"value": "rocknow"
}
] | null | [] | package pro.alex_zaitsev.currency.object.comparator.ui;
import pro.alex_zaitsev.currency.object.model.Advert;
/**
* Created by rocknow on 16.03.2015.
*/
public class AdvertAmountComparator extends BaseUiAdvertComparator {
@Override
public int compareValues(Advert left, Advert right) {
return Float.valueOf(left.getAmount()).compareTo(right.getAmount());
}
}
| 384 | 0.742188 | 0.721354 | 14 | 26.428572 | 28.301222 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 12 |
3e646ad1d5f8ed58be8c3565cb98f91fc3e0ce98 | 2,345,052,193,119 | f606d21572b90b6ff86454a79aee35538a0972d5 | /Parcours_type/Parcourstype_checkoutprofile_view.java | a3872d4e0239fedb48b2c8b0e1cc6bb12ef58b5d | [] | no_license | PDS-MASK/PDS | https://github.com/PDS-MASK/PDS | 48845b6c4586d1a7518117c47eddb383838b6601 | 2dfa41e4affa3ae53ba4f48c4d6f59883d09d8c7 | refs/heads/master | 2018-09-30T19:17:42.561000 | 2018-06-28T22:06:05 | 2018-06-28T22:06:05 | 120,525,342 | 0 | 1 | null | false | 2018-02-13T17:36:14 | 2018-02-06T21:27:57 | 2018-02-11T12:58:37 | 2018-02-13T17:36:13 | 56 | 0 | 1 | 0 | Java | false | null | package view;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextPane;
import net.proteanit.sql.DbUtils;
import java.awt.BorderLayout;
import javax.swing.JTextField;
import java.awt.SystemColor;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Parcourstype_view {
private JFrame frmPlateformeDesParcours;
private JTextField txtLeConsommateurQui;
private JTextField Name_Selected_Cons;
private int id_consumer;
private JTextField txtCettePersonnePossde;
private JTextField SelectedProfilCons;
private JTextField txtVosHabitudesDachats;
private JTextField SelectedProfilPurchasePreference;
public Parcourstype_view(int i)
{
this.id_consumer = i;
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Parcourstype_view window = new Parcourstype_view();
window.frmPlateformeDesParcours.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Parcourstype_view() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
void initialize() {
frmPlateformeDesParcours = new JFrame();
frmPlateformeDesParcours.setTitle("Plateforme des parcours type");
frmPlateformeDesParcours.setBounds(100, 100, 741, 633);
frmPlateformeDesParcours.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmPlateformeDesParcours.getContentPane().setLayout(null);
txtLeConsommateurQui = new JTextField();
txtLeConsommateurQui.setEditable(false);
txtLeConsommateurQui.setBackground(SystemColor.menu);
txtLeConsommateurQui.setText("Le consommateur qui a \u00E9t\u00E9 selectionn\u00E9 est :");
txtLeConsommateurQui.setBounds(12, 76, 263, 22);
frmPlateformeDesParcours.getContentPane().add(txtLeConsommateurQui);
txtLeConsommateurQui.setColumns(10);
Name_Selected_Cons = new JTextField();
Name_Selected_Cons.setEditable(false);
Name_Selected_Cons.setBackground(SystemColor.menu);
Name_Selected_Cons.setBounds(287, 76, 200, 22);
frmPlateformeDesParcours.getContentPane().add(Name_Selected_Cons);
Name_Selected_Cons.setColumns(10);
txtCettePersonnePossde = new JTextField();
txtCettePersonnePossde.setText("Cette personne poss\u00E8de le(s) profil(s) suivant(s) :");
txtCettePersonnePossde.setEditable(false);
txtCettePersonnePossde.setColumns(10);
txtCettePersonnePossde.setBackground(SystemColor.menu);
txtCettePersonnePossde.setBounds(12, 142, 294, 22);
frmPlateformeDesParcours.getContentPane().add(txtCettePersonnePossde);
SelectedProfilCons = new JTextField();
SelectedProfilCons.setEditable(false);
SelectedProfilCons.setColumns(10);
SelectedProfilCons.setBackground(SystemColor.menu);
SelectedProfilCons.setBounds(318, 142, 246, 77);
frmPlateformeDesParcours.getContentPane().add(SelectedProfilCons);
txtVosHabitudesDachats = new JTextField();
txtVosHabitudesDachats.setText("Vos habitudes d'achats sont : ");
txtVosHabitudesDachats.setEditable(false);
txtVosHabitudesDachats.setColumns(10);
txtVosHabitudesDachats.setBackground(SystemColor.menu);
txtVosHabitudesDachats.setBounds(12, 341, 180, 22);
frmPlateformeDesParcours.getContentPane().add(txtVosHabitudesDachats);
SelectedProfilPurchasePreference = new JTextField();
SelectedProfilPurchasePreference.setEditable(false);
SelectedProfilPurchasePreference.setColumns(10);
SelectedProfilPurchasePreference.setBackground(SystemColor.menu);
SelectedProfilPurchasePreference.setBounds(206, 326, 358, 69);
frmPlateformeDesParcours.getContentPane().add(SelectedProfilPurchasePreference);
frmPlateformeDesParcours.setVisible(true);
}
public void showSelectedIdCons(int i){
try{
Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","PDS","toto");
String sql = "Select NOM_PERSONNE,PRENOM_PERSONNE from PERSONNE where id_personne ="+i;
Object pst = connection.prepareStatement(sql);
Object rs = ((PreparedStatement) pst).executeQuery();
String resultat = " ";
System.out.print(" "+ rs);
while(((ResultSet) rs).next()){
resultat = ((ResultSet) rs).getString("nom_personne")+((ResultSet) rs).getString("prenom_personne");
}
Name_Selected_Cons.setText(resultat);
}
catch(Exception ex){
JOptionPane.showMessageDialog(null, ex);
}
}
public void showSelectedConsProfil(int i){
try{
Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","PDS","toto");
String sql = "Select nom_profil from PROFIL,PROFIL_PERSONNE,PERSONNE WHERE profil_personne.id_profil = PROFIL.ID_PROFIL and PROFIL_PERSONNE.ID_PERSONNE = PERSONNE.ID_PERSONNE and PERSONNE.ID_PERSONNE ="+i;
Object pst = connection.prepareStatement(sql);
Object rs = ((PreparedStatement) pst).executeQuery();
String resultat = " ";
System.out.print(" "+ rs);
while(((ResultSet) rs).next()){
resultat = resultat+((ResultSet) rs).getString(i);
}
SelectedProfilCons.setText(resultat);
}
catch(Exception ex){
JOptionPane.showMessageDialog(null, ex);
}
}
public void showSelectedConsPurchasePreference(int i)
{
try{
Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","PDS","toto");
String sql = "select nom_souscategorie from sous_categorie , categorie_personne where sous_categorie.id_souscategorie = categorie_personne.ID_SOUSCATEGORIE and categorie_personne.ID_PERSONNE ="+i;
Object pst = connection.prepareStatement(sql);
Object rs = ((PreparedStatement) pst).executeQuery();
String resultat = " ";
System.out.print(" "+ rs);
while(((ResultSet) rs).next()){
resultat = resultat+((ResultSet) rs).getString(i);
}
SelectedProfilPurchasePreference.setText(resultat);
}
catch(Exception ex){
JOptionPane.showMessageDialog(null, ex);
}
}
public JFrame getFrame() {
return frmPlateformeDesParcours;
}
public void setFrame(JFrame frame) {
this.frmPlateformeDesParcours = frame;
}
public JTextField getTxtLeConsommateurQui() {
return txtLeConsommateurQui;
}
public void setTxtLeConsommateurQui(JTextField txtLeConsommateurQui) {
this.txtLeConsommateurQui = txtLeConsommateurQui;
}
public JTextField getName_Selected_Cons() {
return Name_Selected_Cons;
}
public void setName_Selected_Cons(JTextField name_Selected_Cons) {
Name_Selected_Cons = name_Selected_Cons;
}
public int getId_consumer() {
return id_consumer;
}
public void setId_consumer(int id_consumer) {
this.id_consumer = id_consumer;
}
}
| UTF-8 | Java | 7,002 | java | Parcourstype_checkoutprofile_view.java | Java | [] | null | [] | package view;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextPane;
import net.proteanit.sql.DbUtils;
import java.awt.BorderLayout;
import javax.swing.JTextField;
import java.awt.SystemColor;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Parcourstype_view {
private JFrame frmPlateformeDesParcours;
private JTextField txtLeConsommateurQui;
private JTextField Name_Selected_Cons;
private int id_consumer;
private JTextField txtCettePersonnePossde;
private JTextField SelectedProfilCons;
private JTextField txtVosHabitudesDachats;
private JTextField SelectedProfilPurchasePreference;
public Parcourstype_view(int i)
{
this.id_consumer = i;
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Parcourstype_view window = new Parcourstype_view();
window.frmPlateformeDesParcours.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Parcourstype_view() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
void initialize() {
frmPlateformeDesParcours = new JFrame();
frmPlateformeDesParcours.setTitle("Plateforme des parcours type");
frmPlateformeDesParcours.setBounds(100, 100, 741, 633);
frmPlateformeDesParcours.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmPlateformeDesParcours.getContentPane().setLayout(null);
txtLeConsommateurQui = new JTextField();
txtLeConsommateurQui.setEditable(false);
txtLeConsommateurQui.setBackground(SystemColor.menu);
txtLeConsommateurQui.setText("Le consommateur qui a \u00E9t\u00E9 selectionn\u00E9 est :");
txtLeConsommateurQui.setBounds(12, 76, 263, 22);
frmPlateformeDesParcours.getContentPane().add(txtLeConsommateurQui);
txtLeConsommateurQui.setColumns(10);
Name_Selected_Cons = new JTextField();
Name_Selected_Cons.setEditable(false);
Name_Selected_Cons.setBackground(SystemColor.menu);
Name_Selected_Cons.setBounds(287, 76, 200, 22);
frmPlateformeDesParcours.getContentPane().add(Name_Selected_Cons);
Name_Selected_Cons.setColumns(10);
txtCettePersonnePossde = new JTextField();
txtCettePersonnePossde.setText("Cette personne poss\u00E8de le(s) profil(s) suivant(s) :");
txtCettePersonnePossde.setEditable(false);
txtCettePersonnePossde.setColumns(10);
txtCettePersonnePossde.setBackground(SystemColor.menu);
txtCettePersonnePossde.setBounds(12, 142, 294, 22);
frmPlateformeDesParcours.getContentPane().add(txtCettePersonnePossde);
SelectedProfilCons = new JTextField();
SelectedProfilCons.setEditable(false);
SelectedProfilCons.setColumns(10);
SelectedProfilCons.setBackground(SystemColor.menu);
SelectedProfilCons.setBounds(318, 142, 246, 77);
frmPlateformeDesParcours.getContentPane().add(SelectedProfilCons);
txtVosHabitudesDachats = new JTextField();
txtVosHabitudesDachats.setText("Vos habitudes d'achats sont : ");
txtVosHabitudesDachats.setEditable(false);
txtVosHabitudesDachats.setColumns(10);
txtVosHabitudesDachats.setBackground(SystemColor.menu);
txtVosHabitudesDachats.setBounds(12, 341, 180, 22);
frmPlateformeDesParcours.getContentPane().add(txtVosHabitudesDachats);
SelectedProfilPurchasePreference = new JTextField();
SelectedProfilPurchasePreference.setEditable(false);
SelectedProfilPurchasePreference.setColumns(10);
SelectedProfilPurchasePreference.setBackground(SystemColor.menu);
SelectedProfilPurchasePreference.setBounds(206, 326, 358, 69);
frmPlateformeDesParcours.getContentPane().add(SelectedProfilPurchasePreference);
frmPlateformeDesParcours.setVisible(true);
}
public void showSelectedIdCons(int i){
try{
Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","PDS","toto");
String sql = "Select NOM_PERSONNE,PRENOM_PERSONNE from PERSONNE where id_personne ="+i;
Object pst = connection.prepareStatement(sql);
Object rs = ((PreparedStatement) pst).executeQuery();
String resultat = " ";
System.out.print(" "+ rs);
while(((ResultSet) rs).next()){
resultat = ((ResultSet) rs).getString("nom_personne")+((ResultSet) rs).getString("prenom_personne");
}
Name_Selected_Cons.setText(resultat);
}
catch(Exception ex){
JOptionPane.showMessageDialog(null, ex);
}
}
public void showSelectedConsProfil(int i){
try{
Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","PDS","toto");
String sql = "Select nom_profil from PROFIL,PROFIL_PERSONNE,PERSONNE WHERE profil_personne.id_profil = PROFIL.ID_PROFIL and PROFIL_PERSONNE.ID_PERSONNE = PERSONNE.ID_PERSONNE and PERSONNE.ID_PERSONNE ="+i;
Object pst = connection.prepareStatement(sql);
Object rs = ((PreparedStatement) pst).executeQuery();
String resultat = " ";
System.out.print(" "+ rs);
while(((ResultSet) rs).next()){
resultat = resultat+((ResultSet) rs).getString(i);
}
SelectedProfilCons.setText(resultat);
}
catch(Exception ex){
JOptionPane.showMessageDialog(null, ex);
}
}
public void showSelectedConsPurchasePreference(int i)
{
try{
Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","PDS","toto");
String sql = "select nom_souscategorie from sous_categorie , categorie_personne where sous_categorie.id_souscategorie = categorie_personne.ID_SOUSCATEGORIE and categorie_personne.ID_PERSONNE ="+i;
Object pst = connection.prepareStatement(sql);
Object rs = ((PreparedStatement) pst).executeQuery();
String resultat = " ";
System.out.print(" "+ rs);
while(((ResultSet) rs).next()){
resultat = resultat+((ResultSet) rs).getString(i);
}
SelectedProfilPurchasePreference.setText(resultat);
}
catch(Exception ex){
JOptionPane.showMessageDialog(null, ex);
}
}
public JFrame getFrame() {
return frmPlateformeDesParcours;
}
public void setFrame(JFrame frame) {
this.frmPlateformeDesParcours = frame;
}
public JTextField getTxtLeConsommateurQui() {
return txtLeConsommateurQui;
}
public void setTxtLeConsommateurQui(JTextField txtLeConsommateurQui) {
this.txtLeConsommateurQui = txtLeConsommateurQui;
}
public JTextField getName_Selected_Cons() {
return Name_Selected_Cons;
}
public void setName_Selected_Cons(JTextField name_Selected_Cons) {
Name_Selected_Cons = name_Selected_Cons;
}
public int getId_consumer() {
return id_consumer;
}
public void setId_consumer(int id_consumer) {
this.id_consumer = id_consumer;
}
}
| 7,002 | 0.728792 | 0.713225 | 218 | 30.119267 | 30.504843 | 207 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.288991 | false | false | 12 |
7ce3b36129536b56a41d3d10a727b7c04fca4c77 | 10,488,310,162,583 | f16d85ef44bc944f88ae72e911ce343863fc81dc | /Browseword.java | 990b6da8d807d208b9a575b7d801e784daf40f3d | [] | no_license | yuchaozh/IWord | https://github.com/yuchaozh/IWord | ef38d74423047ed732f814abdc2a920a9a234487 | 21931c73185b073d489afa77ccaaf0efcb6ad342 | refs/heads/master | 2021-01-01T16:25:56.467000 | 2013-05-15T14:10:31 | 2013-05-15T14:10:31 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.awt.*;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.*;
import javax.swing.event.*;
import java.sql.*;
public class Browseword extends JFrame implements ActionListener
{
public static final String BASIC_ADDRESS ="http://192.168.1.102/word/CGI/";
public static final String APPID="&appID=MEMORYCGI";
private static final String REG_INTERFACE="register_CGI.php";
private static final String LOGIN_INTERFACE="login_CGI.php";
private static final String SYNC_INTERFACE="sync_CGI.php";
JTabbedPane browsetp = new JTabbedPane();
//从数据库中取出wordlist
String[] Wordlist;
static JList BrowseList;
static String choosedword = "";
Connection conn;
Statement showwordlist;
Statement saveUnit;
Statement Synicate;
String word;
String[] wordarray;
JPanel learnword2;
JPanel Setting2;
JTextField UnitParameter;
String textFieldValue;
String password1;
String username;
JPasswordField pwdinput;
JTextField nameinput;
int bookid;
int lastremember;
static JButton Begin;
public Browseword()
{
String choosed = Frame.choosedbook;
//创建一个选项卡容器,将之添加到顶层容器内
learnword2 = new JPanel();
Setting2 = new JPanel();
browsetp.addTab("Learn", learnword2);
browsetp.addTab("Setting", Frame.Setting);
browsetp.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
//Learn选项卡界面,使用GridBagLayout布局
learnword2.setLayout(new GridBagLayout());
learnword2.setOpaque(true);
GridBagConstraints c = new GridBagConstraints();
//Back按钮布局
JButton Back = new JButton("Back");
Back.addActionListener(this);
Begin = new JButton("Begin");
Begin.addActionListener(this);
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 1;
c.gridheight = 1;
c.weightx = 100;
c.weighty = 0;
//如果组件没有填充整个区域,可以通过设置anchor域指定其位置
c.anchor = GridBagConstraints.WEST;
//c.anchor = GridBagConstraints.NORTH;
learnword2.add(Back, c);
c.anchor = GridBagConstraints.EAST;
learnword2.add(Begin, c);
//词典List布局
c.gridx = 0;
c.gridy++;
c.gridwidth = 1;
c.gridheight = 1;
c.weightx = 100;
c.weighty = 100;
//组件拉伸至整个区域
c.fill = GridBagConstraints.BOTH;
c.anchor = GridBagConstraints.NORTHWEST;
try
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/iword","root","123456");
if(!conn.isClosed())
System.out.println("Succeeded connecting to the database(browsebord)");
showwordlist = conn.createStatement();
//System.out.println("You choosed: " + choosed);
//在mysql语句总引用java变量
ResultSet rs = showwordlist.executeQuery("select * from `" + choosed + "`");
ResultSetMetaData metaData = rs.getMetaData();
int numberOfColumns = metaData.getColumnCount();
//System.out.println(numberOfColumns);
wordarray = new String[4103];
int i = 0;
while(rs.next())
{
for (int z =1; z <= numberOfColumns; z++)
{
//System.out.printf("%-8s\t", rs.getObject(z));
}
/****************************************排列问题,存储在数组中***********************************************************************************/
wordarray[i] = rs.getString(1)+ " " + rs.getString(2) + " " + rs.getString(3);
i++;
}
for(int j = 0; j < wordarray.length; j++)
{
//System.out.println(wordarray[j]);
}
rs.close();
showwordlist.close();
conn.close();
}
catch (Exception ex)
{
System.out.println("Error: " + ex.toString());
}
//把数据库中的wordarray数组放到BrowseList中
BrowseList = new JList(wordarray);
BrowseList.addListSelectionListener(new ListSelectionListener()
{
/**************************选中高亮问题****************************************************************/
public void valueChanged(ListSelectionEvent e)
{
choosedword = (String) BrowseList.getSelectedValue();
//System.out.println(choosedword+"in Browseword");
//Browseworddetail browseworddetail = new Browseworddetail();
new Browseworddetail();
//刷新界面
//repaint();
}
});
//一次只能选择一个列表索引
BrowseList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
learnword2.add(new JScrollPane (BrowseList),c);
//Setting选项卡界面
JLabel Unit = new JLabel("Unit: ");
UnitParameter = new JTextField(10);
JButton Save = new JButton("Save");
JButton Syn= new JButton("Syn");
JButton Initialize= new JButton("Initialize");
JLabel name = new JLabel("name :");
JLabel password = new JLabel("password :");
nameinput = new JTextField(15);
pwdinput = new JPasswordField(15);
JButton login = new JButton("login");
JButton register = new JButton("register");
Setting2.setLayout(new GridBagLayout());
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 1;
c.gridheight = 1;
c.weightx = 100;
c.weighty = 0;
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.EAST;
Setting2.add(name, c);
c.gridx = 1;
c.gridy = 0;
c.gridwidth = 1;
c.gridheight = 1;
c.weightx = 100;
c.weighty = 0;
c.fill = GridBagConstraints.BOTH;
c.anchor = GridBagConstraints.CENTER;
Setting2.add(nameinput, c);
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 1;
c.gridheight = 1;
c.weightx = 100;
c.weighty = 0;
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.EAST;
Setting2.add(password, c);
c.gridx = 1;
c.gridy = 1;
c.gridwidth = 1;
c.gridheight = 1;
c.weightx = 100;
c.weighty = 0;
c.fill = GridBagConstraints.BOTH;
c.anchor = GridBagConstraints.CENTER;
Setting2.add(pwdinput, c);
c.gridx = 1;
c.gridy = 2;
c.gridwidth = 1;
c.gridheight = 1;
c.weightx = 100;
c.weighty = 0;
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.WEST;
Setting2.add(login, c);
c.gridx = 1;
c.gridy = 2;
c.gridwidth = 1;
c.gridheight = 1;
c.weightx = 100;
c.weighty = 0;
c.anchor = GridBagConstraints.EAST;
Setting2.add(register, c);
c.gridx = 0;
c.gridy = 6;
c.gridwidth = 1;
c.gridheight = 1;
c.weightx = 100;
c.weighty = 0;
c.anchor = GridBagConstraints.EAST;
Setting2.add(Unit, c);
c.gridx = 1;
c.gridy = 6;
c.fill = GridBagConstraints.BOTH;
c.anchor = GridBagConstraints.CENTER;
Setting2.add(UnitParameter, c);
c.gridx = 2;
c.gridy = 6;
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.WEST;
Setting2.add(Save, c);
c.gridy = 7;
c.gridx = 1;
c.anchor = GridBagConstraints.EAST;
Setting2.add(Syn, c);
c.gridy = 7;
c.gridx = 1;
c.anchor = GridBagConstraints.WEST;
Setting2.add(Initialize, c);
register.addActionListener(this);
login.addActionListener(this);
Save.addActionListener(this);
Syn.addActionListener(this);
Initialize.addActionListener(this);
}
/****************************返回问题*****************************************************/
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals("Back"))
{
System.out.println("here to back");
//Frame frame2 = new Frame();
//learnword2.setVisible(false);
//Setting2.setVisible(false);
Frame frame = new Frame();
setContentPane(frame.tp);
repaint();
}
if (e.getActionCommand().equals("Begin"))
{
System.out.println("Begin to learn word");
new Learnword();
Begin.setEnabled(false);
BrowseList.setEnabled(false);
repaint();
}
if (e.getActionCommand().equals("Save"))
{
textFieldValue = UnitParameter.getText();
System.out.println("You input:" + textFieldValue);
try
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/iword","root","123456");
if(!conn.isClosed())
System.out.println("Succeeded connecting to the database(frame-Setting)");
saveUnit = conn.createStatement();
ResultSet result = saveUnit.executeQuery("select amount from configuration");
while(result.next())
{
int number = (int) result.getInt(1);
System.out.println(number);
}
saveUnit.executeUpdate("update configuration set amount = " + textFieldValue + " where lastbookid = 1");
//saveUnit.executeUpdate("insert into configuration(amount) values (`" + textFieldValue + "`)");
saveUnit.close();
conn.close();
}
catch (Exception ex)
{
System.out.println("Error: " + ex.toString());
}
repaint();
}
if (e.getActionCommand().equals("Syn"))
{
try
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/iword","root","123456");
if(!conn.isClosed())
System.out.println("Succeeded connecting to the database(frame-Setting)");
Synicate = conn.createStatement();
ResultSet rs = Synicate.executeQuery("select bookid, lastremember from booklist where bookname like '" + Frame.choosedbook + "'");
rs.next();
System.out.println(rs.getInt(1) + rs.getInt(2));
bookid = rs.getInt(1);
lastremember = rs.getInt(2);
rs.close();
conn.close();
}
catch (Exception ex)
{
System.out.println("I am a Error: " + ex.toString());
}
try
{
URL u = new URL(combineSync(username, password1, bookid, lastremember));
InputStream in = u.openStream();
BufferedReader bin = new BufferedReader(new InputStreamReader(in, "GB2312"));
String result="";
String s;
while((s=bin.readLine())!=null){
result+=s;
}
if(result.charAt(0)=='1')
{
JOptionPane.showMessageDialog(getContentPane(),"同步成功" ,"确认",JOptionPane.WARNING_MESSAGE);
}else{
JOptionPane.showMessageDialog(getContentPane(),"同步失败" ,"确认",JOptionPane.WARNING_MESSAGE);
}
bin.close();
}
catch (MalformedURLException ex)
{
System.err.println(ex);
}
catch (IOException ex)
{
System.err.println(ex);
}
/*//从数据库导出csv文件
System.out.println("you clicked Syn");
try
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/iword","root","123456");
if(!conn.isClosed())
System.out.println("Succeeded connecting to the database(frame-Setting)");
Synicate = conn.createStatement();
for (int i = 0; i <= Frame.Wordbook.length; i++)
{
*//****************************************已经存在文件问题*************************************************************************//*
Synicate.execute("select * from " + Frame.Wordbook[i] + " into outfile 'F:/" + Frame.Wordbook[i] + ".csv' fields terminated by ','");
}
Synicate.close();
conn.close();
}
catch (Exception ex)
{
System.out.println("Error: " + ex.toString());
}*/
}
if (e.getActionCommand().equals("Initialize"))
{
try
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/iword","root","123456");
if(!conn.isClosed())
System.out.println("Succeeded connecting to the database(frame-Setting)");
Statement delete = conn.createStatement();
for (int i = 0; i <= Frame.Wordbook.length; i++)
{
/****************************************已经存在文件问题*************************************************************************/
delete.execute("update booklist set lastremember = 0");
}
delete.close();
conn.close();
}
catch (Exception ex)
{
System.out.println("Error: " + ex.toString());
}
}
if (e.getActionCommand().equals("register"))
{
username = nameinput.getText();
password1 = pwdinput.getText();
System.out.println("you click register!");
System.out.println(username + password1);
}
if (e.getActionCommand().equals("login"))
{
username = nameinput.getText();
password1 = pwdinput.getText();
System.out.println("you click login!");
System.out.println(username + password1);
}
}
public String combineSync(String username, String psw, int listID, int wordID)
{
String combine = this.BASIC_ADDRESS + SYNC_INTERFACE + "?username=" + username + "&password=" +psw+APPID + "&bookID=" + listID + "&wordID=" + wordID;
return combine;
}
}
| GB18030 | Java | 12,472 | java | Browseword.java | Java | [
{
"context": "public static final String BASIC_ADDRESS =\"http://192.168.1.102/word/CGI/\";\n\tpublic static final String APPID=\"&a",
"end": 427,
"score": 0.9994578957557678,
"start": 414,
"tag": "IP_ADDRESS",
"value": "192.168.1.102"
},
{
"context": "tion(\"jdbc:mysql://localhost:3... | null | [] | import java.awt.*;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.*;
import javax.swing.event.*;
import java.sql.*;
public class Browseword extends JFrame implements ActionListener
{
public static final String BASIC_ADDRESS ="http://192.168.1.102/word/CGI/";
public static final String APPID="&appID=MEMORYCGI";
private static final String REG_INTERFACE="register_CGI.php";
private static final String LOGIN_INTERFACE="login_CGI.php";
private static final String SYNC_INTERFACE="sync_CGI.php";
JTabbedPane browsetp = new JTabbedPane();
//从数据库中取出wordlist
String[] Wordlist;
static JList BrowseList;
static String choosedword = "";
Connection conn;
Statement showwordlist;
Statement saveUnit;
Statement Synicate;
String word;
String[] wordarray;
JPanel learnword2;
JPanel Setting2;
JTextField UnitParameter;
String textFieldValue;
String password1;
String username;
JPasswordField pwdinput;
JTextField nameinput;
int bookid;
int lastremember;
static JButton Begin;
public Browseword()
{
String choosed = Frame.choosedbook;
//创建一个选项卡容器,将之添加到顶层容器内
learnword2 = new JPanel();
Setting2 = new JPanel();
browsetp.addTab("Learn", learnword2);
browsetp.addTab("Setting", Frame.Setting);
browsetp.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
//Learn选项卡界面,使用GridBagLayout布局
learnword2.setLayout(new GridBagLayout());
learnword2.setOpaque(true);
GridBagConstraints c = new GridBagConstraints();
//Back按钮布局
JButton Back = new JButton("Back");
Back.addActionListener(this);
Begin = new JButton("Begin");
Begin.addActionListener(this);
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 1;
c.gridheight = 1;
c.weightx = 100;
c.weighty = 0;
//如果组件没有填充整个区域,可以通过设置anchor域指定其位置
c.anchor = GridBagConstraints.WEST;
//c.anchor = GridBagConstraints.NORTH;
learnword2.add(Back, c);
c.anchor = GridBagConstraints.EAST;
learnword2.add(Begin, c);
//词典List布局
c.gridx = 0;
c.gridy++;
c.gridwidth = 1;
c.gridheight = 1;
c.weightx = 100;
c.weighty = 100;
//组件拉伸至整个区域
c.fill = GridBagConstraints.BOTH;
c.anchor = GridBagConstraints.NORTHWEST;
try
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/iword","root","1<PASSWORD>");
if(!conn.isClosed())
System.out.println("Succeeded connecting to the database(browsebord)");
showwordlist = conn.createStatement();
//System.out.println("You choosed: " + choosed);
//在mysql语句总引用java变量
ResultSet rs = showwordlist.executeQuery("select * from `" + choosed + "`");
ResultSetMetaData metaData = rs.getMetaData();
int numberOfColumns = metaData.getColumnCount();
//System.out.println(numberOfColumns);
wordarray = new String[4103];
int i = 0;
while(rs.next())
{
for (int z =1; z <= numberOfColumns; z++)
{
//System.out.printf("%-8s\t", rs.getObject(z));
}
/****************************************排列问题,存储在数组中***********************************************************************************/
wordarray[i] = rs.getString(1)+ " " + rs.getString(2) + " " + rs.getString(3);
i++;
}
for(int j = 0; j < wordarray.length; j++)
{
//System.out.println(wordarray[j]);
}
rs.close();
showwordlist.close();
conn.close();
}
catch (Exception ex)
{
System.out.println("Error: " + ex.toString());
}
//把数据库中的wordarray数组放到BrowseList中
BrowseList = new JList(wordarray);
BrowseList.addListSelectionListener(new ListSelectionListener()
{
/**************************选中高亮问题****************************************************************/
public void valueChanged(ListSelectionEvent e)
{
choosedword = (String) BrowseList.getSelectedValue();
//System.out.println(choosedword+"in Browseword");
//Browseworddetail browseworddetail = new Browseworddetail();
new Browseworddetail();
//刷新界面
//repaint();
}
});
//一次只能选择一个列表索引
BrowseList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
learnword2.add(new JScrollPane (BrowseList),c);
//Setting选项卡界面
JLabel Unit = new JLabel("Unit: ");
UnitParameter = new JTextField(10);
JButton Save = new JButton("Save");
JButton Syn= new JButton("Syn");
JButton Initialize= new JButton("Initialize");
JLabel name = new JLabel("name :");
JLabel password = new JLabel("password :");
nameinput = new JTextField(15);
pwdinput = new JPasswordField(15);
JButton login = new JButton("login");
JButton register = new JButton("register");
Setting2.setLayout(new GridBagLayout());
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 1;
c.gridheight = 1;
c.weightx = 100;
c.weighty = 0;
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.EAST;
Setting2.add(name, c);
c.gridx = 1;
c.gridy = 0;
c.gridwidth = 1;
c.gridheight = 1;
c.weightx = 100;
c.weighty = 0;
c.fill = GridBagConstraints.BOTH;
c.anchor = GridBagConstraints.CENTER;
Setting2.add(nameinput, c);
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 1;
c.gridheight = 1;
c.weightx = 100;
c.weighty = 0;
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.EAST;
Setting2.add(password, c);
c.gridx = 1;
c.gridy = 1;
c.gridwidth = 1;
c.gridheight = 1;
c.weightx = 100;
c.weighty = 0;
c.fill = GridBagConstraints.BOTH;
c.anchor = GridBagConstraints.CENTER;
Setting2.add(pwdinput, c);
c.gridx = 1;
c.gridy = 2;
c.gridwidth = 1;
c.gridheight = 1;
c.weightx = 100;
c.weighty = 0;
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.WEST;
Setting2.add(login, c);
c.gridx = 1;
c.gridy = 2;
c.gridwidth = 1;
c.gridheight = 1;
c.weightx = 100;
c.weighty = 0;
c.anchor = GridBagConstraints.EAST;
Setting2.add(register, c);
c.gridx = 0;
c.gridy = 6;
c.gridwidth = 1;
c.gridheight = 1;
c.weightx = 100;
c.weighty = 0;
c.anchor = GridBagConstraints.EAST;
Setting2.add(Unit, c);
c.gridx = 1;
c.gridy = 6;
c.fill = GridBagConstraints.BOTH;
c.anchor = GridBagConstraints.CENTER;
Setting2.add(UnitParameter, c);
c.gridx = 2;
c.gridy = 6;
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.WEST;
Setting2.add(Save, c);
c.gridy = 7;
c.gridx = 1;
c.anchor = GridBagConstraints.EAST;
Setting2.add(Syn, c);
c.gridy = 7;
c.gridx = 1;
c.anchor = GridBagConstraints.WEST;
Setting2.add(Initialize, c);
register.addActionListener(this);
login.addActionListener(this);
Save.addActionListener(this);
Syn.addActionListener(this);
Initialize.addActionListener(this);
}
/****************************返回问题*****************************************************/
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals("Back"))
{
System.out.println("here to back");
//Frame frame2 = new Frame();
//learnword2.setVisible(false);
//Setting2.setVisible(false);
Frame frame = new Frame();
setContentPane(frame.tp);
repaint();
}
if (e.getActionCommand().equals("Begin"))
{
System.out.println("Begin to learn word");
new Learnword();
Begin.setEnabled(false);
BrowseList.setEnabled(false);
repaint();
}
if (e.getActionCommand().equals("Save"))
{
textFieldValue = UnitParameter.getText();
System.out.println("You input:" + textFieldValue);
try
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/iword","root","<PASSWORD>");
if(!conn.isClosed())
System.out.println("Succeeded connecting to the database(frame-Setting)");
saveUnit = conn.createStatement();
ResultSet result = saveUnit.executeQuery("select amount from configuration");
while(result.next())
{
int number = (int) result.getInt(1);
System.out.println(number);
}
saveUnit.executeUpdate("update configuration set amount = " + textFieldValue + " where lastbookid = 1");
//saveUnit.executeUpdate("insert into configuration(amount) values (`" + textFieldValue + "`)");
saveUnit.close();
conn.close();
}
catch (Exception ex)
{
System.out.println("Error: " + ex.toString());
}
repaint();
}
if (e.getActionCommand().equals("Syn"))
{
try
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/iword","root","<PASSWORD>");
if(!conn.isClosed())
System.out.println("Succeeded connecting to the database(frame-Setting)");
Synicate = conn.createStatement();
ResultSet rs = Synicate.executeQuery("select bookid, lastremember from booklist where bookname like '" + Frame.choosedbook + "'");
rs.next();
System.out.println(rs.getInt(1) + rs.getInt(2));
bookid = rs.getInt(1);
lastremember = rs.getInt(2);
rs.close();
conn.close();
}
catch (Exception ex)
{
System.out.println("I am a Error: " + ex.toString());
}
try
{
URL u = new URL(combineSync(username, password1, bookid, lastremember));
InputStream in = u.openStream();
BufferedReader bin = new BufferedReader(new InputStreamReader(in, "GB2312"));
String result="";
String s;
while((s=bin.readLine())!=null){
result+=s;
}
if(result.charAt(0)=='1')
{
JOptionPane.showMessageDialog(getContentPane(),"同步成功" ,"确认",JOptionPane.WARNING_MESSAGE);
}else{
JOptionPane.showMessageDialog(getContentPane(),"同步失败" ,"确认",JOptionPane.WARNING_MESSAGE);
}
bin.close();
}
catch (MalformedURLException ex)
{
System.err.println(ex);
}
catch (IOException ex)
{
System.err.println(ex);
}
/*//从数据库导出csv文件
System.out.println("you clicked Syn");
try
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/iword","root","123456");
if(!conn.isClosed())
System.out.println("Succeeded connecting to the database(frame-Setting)");
Synicate = conn.createStatement();
for (int i = 0; i <= Frame.Wordbook.length; i++)
{
*//****************************************已经存在文件问题*************************************************************************//*
Synicate.execute("select * from " + Frame.Wordbook[i] + " into outfile 'F:/" + Frame.Wordbook[i] + ".csv' fields terminated by ','");
}
Synicate.close();
conn.close();
}
catch (Exception ex)
{
System.out.println("Error: " + ex.toString());
}*/
}
if (e.getActionCommand().equals("Initialize"))
{
try
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/iword","root","1<PASSWORD>");
if(!conn.isClosed())
System.out.println("Succeeded connecting to the database(frame-Setting)");
Statement delete = conn.createStatement();
for (int i = 0; i <= Frame.Wordbook.length; i++)
{
/****************************************已经存在文件问题*************************************************************************/
delete.execute("update booklist set lastremember = 0");
}
delete.close();
conn.close();
}
catch (Exception ex)
{
System.out.println("Error: " + ex.toString());
}
}
if (e.getActionCommand().equals("register"))
{
username = nameinput.getText();
password1 = pwdinput.getText();
System.out.println("you click register!");
System.out.println(username + password1);
}
if (e.getActionCommand().equals("login"))
{
username = nameinput.getText();
password1 = <PASSWORD>.getText();
System.out.println("you click login!");
System.out.println(username + password1);
}
}
public String combineSync(String username, String psw, int listID, int wordID)
{
String combine = this.BASIC_ADDRESS + SYNC_INTERFACE + "?username=" + username + "&password=" +<PASSWORD> + "&bookID=" + listID + "&wordID=" + wordID;
return combine;
}
}
| 12,493 | 0.633987 | 0.617167 | 430 | 27.204651 | 25.192469 | 151 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.22093 | false | false | 12 |
ef49d43f3def663543b0989ec7501227a01465b0 | 3,393,024,196,675 | a0022de2c6f9f1e15ec0e46cb673e08145e90a71 | /Mobile Application/Source/gnu/bytecode/CodeAttr.java | 80a032622e5e5ba4a6433b8d53537ceaec2d3d66 | [] | no_license | mohamedaiche/Savers-Team | https://github.com/mohamedaiche/Savers-Team | 2cbd964a991812b2a9cd7113f622662d065f41a6 | 3a99fd34bc56c07d471670e7b26ec886e8035306 | refs/heads/master | 2021-01-20T12:34:48.533000 | 2017-05-12T16:28:38 | 2017-05-12T16:28:38 | 90,382,724 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package gnu.bytecode;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Array;
public class CodeAttr
extends Attribute
implements AttrContainer
{
public static final int DONT_USE_JSR = 2;
static final int FIXUP_CASE = 3;
static final int FIXUP_DEFINE = 1;
static final int FIXUP_DELETE3 = 8;
static final int FIXUP_GOTO = 4;
static final int FIXUP_JSR = 5;
static final int FIXUP_LINE_NUMBER = 15;
static final int FIXUP_LINE_PC = 14;
static final int FIXUP_MOVE = 9;
static final int FIXUP_MOVE_TO_END = 10;
static final int FIXUP_NONE = 0;
static final int FIXUP_SWITCH = 2;
static final int FIXUP_TRANSFER = 6;
static final int FIXUP_TRANSFER2 = 7;
static final int FIXUP_TRY = 11;
static final int FIXUP_TRY_END = 12;
static final int FIXUP_TRY_HANDLER = 13;
public static final int GENERATE_STACK_MAP_TABLE = 1;
public static boolean instructionLineMode = false;
int PC;
int SP;
Attribute attributes;
byte[] code;
ExitableBlock currentExitableBlock;
short[] exception_table;
int exception_table_length;
int exitableBlockLevel;
int fixup_count;
Label[] fixup_labels;
int[] fixup_offsets;
int flags;
IfState if_stack;
LineNumbersAttr lines;
Type[] local_types;
public LocalVarsAttr locals;
private int max_locals;
private int max_stack;
Label previousLabel;
SourceDebugExtAttr sourceDbgExt;
public StackMapTableAttr stackMap;
public Type[] stack_types;
TryState try_stack;
private boolean unreachable_here;
boolean[] varsSetInCurrentBlock;
public CodeAttr(Method paramMethod)
{
super("Code");
addToFrontOf(paramMethod);
paramMethod.code = this;
if (paramMethod.getDeclaringClass().getClassfileMajorVersion() >= 50) {
this.flags |= 0x3;
}
}
private int adjustTypedOp(char paramChar)
{
switch (paramChar)
{
default:
return 4;
case 'I':
return 0;
case 'J':
return 1;
case 'F':
return 2;
case 'D':
return 3;
case 'B':
case 'Z':
return 5;
case 'C':
return 6;
}
return 7;
}
private int adjustTypedOp(Type paramType)
{
return adjustTypedOp(paramType.getSignature().charAt(0));
}
public static final String calculateSplit(String paramString)
{
int i2 = paramString.length();
StringBuffer localStringBuffer = new StringBuffer(20);
int m = 0;
int j = 0;
int i = 0;
if (i < i2)
{
int k = paramString.charAt(i);
if (k >= 2048) {
k = 3;
}
for (;;)
{
int i1 = j;
int n = m;
if (j + k > 65535)
{
localStringBuffer.append((char)(i - m));
n = i;
i1 = 0;
}
j = i1 + k;
i += 1;
m = n;
break;
if ((k >= 128) || (k == 0)) {
k = 2;
} else {
k = 1;
}
}
}
localStringBuffer.append((char)(i2 - m));
return localStringBuffer.toString();
}
public static boolean castNeeded(Type paramType1, Type paramType2)
{
Type localType1 = paramType1;
Type localType2 = paramType2;
if ((paramType1 instanceof UninitializedType))
{
localType1 = ((UninitializedType)paramType1).getImplementationType();
localType2 = paramType2;
}
for (;;)
{
if (localType1 == localType2) {
return false;
}
if (((localType2 instanceof ClassType)) && ((localType1 instanceof ClassType)) && (((ClassType)localType1).isSubclass((ClassType)localType2))) {
return false;
}
if ((!(localType2 instanceof ArrayType)) || (!(localType1 instanceof ArrayType))) {
break;
}
localType2 = ((ArrayType)localType2).getComponentType();
localType1 = ((ArrayType)localType1).getComponentType();
}
return true;
}
private void emitBinop(int paramInt)
{
Type localType1 = popType().promote();
Type localType2 = popType();
Type localType3 = localType2.promote();
if ((localType3 != localType1) || (!(localType3 instanceof PrimType))) {
throw new Error("non-matching or bad types in binary operation");
}
emitTypedOp(paramInt, localType3);
pushType(localType2);
}
private void emitBinop(int paramInt, char paramChar)
{
popType();
popType();
emitTypedOp(paramInt, paramChar);
pushType(Type.signatureToPrimitive(paramChar));
}
private void emitCheckcast(Type paramType, int paramInt)
{
reserve(3);
popType();
put1(paramInt);
if ((paramType instanceof ObjectType))
{
putIndex2(getConstants().addClass((ObjectType)paramType));
return;
}
throw new Error("unimplemented type " + paramType + " in emitCheckcast/emitInstanceof");
}
private final void emitFieldop(Field paramField, int paramInt)
{
reserve(3);
put1(paramInt);
putIndex2(getConstants().addFieldRef(paramField));
}
private void emitShift(int paramInt)
{
Type localType1 = popType().promote();
Type localType2 = popType();
Type localType3 = localType2.promote();
if ((localType3 != Type.intType) && (localType3 != Type.longType)) {
throw new Error("the value shifted must be an int or a long");
}
if (localType1 != Type.intType) {
throw new Error("the amount of shift must be an int");
}
emitTypedOp(paramInt, localType3);
pushType(localType2);
}
private void emitTryEnd(boolean paramBoolean)
{
if (this.try_stack.tryClauseDone) {
return;
}
this.try_stack.tryClauseDone = true;
if (this.try_stack.finally_subr != null) {
this.try_stack.exception = addLocal(Type.javalangThrowableType);
}
gotoFinallyOrEnd(paramBoolean);
this.try_stack.end_try = getLabel();
}
private void emitTypedOp(int paramInt, char paramChar)
{
reserve(1);
put1(adjustTypedOp(paramChar) + paramInt);
}
private void emitTypedOp(int paramInt, Type paramType)
{
reserve(1);
put1(adjustTypedOp(paramType) + paramInt);
}
private final int fixupKind(int paramInt)
{
return this.fixup_offsets[paramInt] & 0xF;
}
private final int fixupOffset(int paramInt)
{
return this.fixup_offsets[paramInt] >> 4;
}
private void gotoFinallyOrEnd(boolean paramBoolean)
{
if (reachableHere())
{
if (this.try_stack.saved_result != null) {
emitStore(this.try_stack.saved_result);
}
if (this.try_stack.end_label == null) {
this.try_stack.end_label = new Label();
}
if ((this.try_stack.finally_subr != null) && (!useJsr())) {
break label102;
}
if (this.try_stack.finally_subr != null) {
emitJsr(this.try_stack.finally_subr);
}
emitGoto(this.try_stack.end_label);
}
label102:
do
{
return;
if (this.try_stack.exitCases != null) {
emitPushInt(0);
}
emitPushNull();
} while (paramBoolean);
emitGoto(this.try_stack.finally_subr);
}
private Label mergeLabels(Label paramLabel1, Label paramLabel2)
{
if (paramLabel1 != null) {
paramLabel2.setTypes(paramLabel1);
}
return paramLabel2;
}
private void print(String paramString, int paramInt, PrintWriter paramPrintWriter)
{
int i = 0;
int j = -1;
while (paramInt >= 0)
{
i = j + 1;
j = paramString.indexOf(';', i);
paramInt -= 1;
}
paramPrintWriter.write(paramString, i, j - i);
}
private int readInt(int paramInt)
{
return readUnsignedShort(paramInt) << 16 | readUnsignedShort(paramInt + 2);
}
private int readUnsignedShort(int paramInt)
{
return (this.code[paramInt] & 0xFF) << 8 | this.code[(paramInt + 1)] & 0xFF;
}
private int words(Type[] paramArrayOfType)
{
int i = 0;
int j = paramArrayOfType.length;
for (;;)
{
j -= 1;
if (j < 0) {
break;
}
if (paramArrayOfType[j].size > 4) {
i += 2;
} else {
i += 1;
}
}
return i;
}
public void addHandler(int paramInt1, int paramInt2, int paramInt3, int paramInt4)
{
int j = this.exception_table_length * 4;
if (this.exception_table == null) {
this.exception_table = new short[20];
}
for (;;)
{
short[] arrayOfShort = this.exception_table;
int i = j + 1;
arrayOfShort[j] = ((short)paramInt1);
arrayOfShort = this.exception_table;
paramInt1 = i + 1;
arrayOfShort[i] = ((short)paramInt2);
arrayOfShort = this.exception_table;
paramInt2 = paramInt1 + 1;
arrayOfShort[paramInt1] = ((short)paramInt3);
this.exception_table[paramInt2] = ((short)paramInt4);
this.exception_table_length += 1;
return;
if (this.exception_table.length <= j)
{
arrayOfShort = new short[this.exception_table.length * 2];
System.arraycopy(this.exception_table, 0, arrayOfShort, 0, j);
this.exception_table = arrayOfShort;
}
}
}
public void addHandler(Label paramLabel1, Label paramLabel2, ClassType paramClassType)
{
ConstantPool localConstantPool = getConstants();
int i;
if (paramClassType == null)
{
i = 0;
fixupAdd(11, paramLabel1);
fixupAdd(12, i, paramLabel2);
paramLabel2 = new Label();
paramLabel2.localTypes = paramLabel1.localTypes;
paramLabel2.stackTypes = new Type[1];
if (paramClassType != null) {
break label96;
}
}
label96:
for (paramLabel1 = Type.javalangThrowableType;; paramLabel1 = paramClassType)
{
paramLabel2.stackTypes[0] = paramLabel1;
setTypes(paramLabel2);
fixupAdd(13, 0, paramLabel2);
return;
i = localConstantPool.addClass(paramClassType).index;
break;
}
}
public Variable addLocal(Type paramType)
{
return this.locals.current_scope.addVariable(this, paramType, null);
}
public Variable addLocal(Type paramType, String paramString)
{
return this.locals.current_scope.addVariable(this, paramType, paramString);
}
public void addParamLocals()
{
Method localMethod = getMethod();
if ((localMethod.access_flags & 0x8) == 0) {
addLocal(localMethod.classfile).setParameter(true);
}
int j = localMethod.arg_types.length;
int i = 0;
while (i < j)
{
addLocal(localMethod.arg_types[i]).setParameter(true);
i += 1;
}
}
public void assignConstants(ClassType paramClassType)
{
if ((this.locals != null) && (this.locals.container == null) && (!this.locals.isEmpty())) {
this.locals.addToFrontOf(this);
}
processFixups();
if ((this.stackMap != null) && (this.stackMap.numEntries > 0)) {
this.stackMap.addToFrontOf(this);
}
if (instructionLineMode)
{
if (this.lines == null) {
this.lines = new LineNumbersAttr(this);
}
this.lines.linenumber_count = 0;
int j = getCodeLength();
int i = 0;
while (i < j)
{
this.lines.put(i, i);
i += 1;
}
}
super.assignConstants(paramClassType);
Attribute.assignConstants(this, paramClassType);
}
public int beginFragment(Label paramLabel)
{
return beginFragment(new Label(), paramLabel);
}
public int beginFragment(Label paramLabel1, Label paramLabel2)
{
int i = this.fixup_count;
fixupAdd(10, paramLabel2);
paramLabel1.define(this);
return i;
}
public void disAssemble(ClassTypeWriter paramClassTypeWriter, int paramInt1, int paramInt2)
{
int i = 0;
int k = paramInt1;
int m;
Object localObject;
int n;
int j;
if (k < paramInt2)
{
paramInt1 = k + 1;
m = this.code[k] & 0xFF;
localObject = Integer.toString(k);
n = 0;
j = ((String)localObject).length();
for (;;)
{
j += 1;
if (j > 3) {
break;
}
paramClassTypeWriter.print(' ');
}
paramClassTypeWriter.print((String)localObject);
paramClassTypeWriter.print(": ");
if (m < 120) {
if (m < 87) {
if (m < 3)
{
print("nop;aconst_null;iconst_m1;", m, paramClassTypeWriter);
j = n;
label115:
if (j <= 0) {
break label2030;
}
if (j != 1) {
break label2015;
}
localObject = this.code;
k = paramInt1 + 1;
j = localObject[paramInt1] & 0xFF;
paramInt1 = k;
label150:
paramClassTypeWriter.printConstantOperand(j);
}
}
}
}
label399:
label416:
label500:
label543:
label2008:
label2015:
label2030:
for (;;)
{
paramClassTypeWriter.println();
k = paramInt1;
break;
if (m < 9)
{
paramClassTypeWriter.print("iconst_");
paramClassTypeWriter.print(m - 3);
j = n;
break label115;
}
char c;
if (m < 16)
{
if (m < 11)
{
c = 'l';
j = m - 9;
}
for (;;)
{
paramClassTypeWriter.print(c);
paramClassTypeWriter.print("const_");
paramClassTypeWriter.print(j);
j = n;
break;
if (m < 14)
{
c = 'f';
j = m - 11;
}
else
{
c = 'd';
j = m - 14;
}
}
}
if (m < 21)
{
if (m < 18)
{
print("bipush ;sipush ;", m - 16, paramClassTypeWriter);
if (m == 16)
{
j = this.code[paramInt1];
paramInt1 += 1;
}
for (;;)
{
paramClassTypeWriter.print(j);
j = n;
break;
j = (short)readUnsignedShort(paramInt1);
paramInt1 += 2;
}
}
if (m == 18) {}
for (j = 1;; j = 2)
{
print("ldc;ldc_w;ldc2_w;", m - 18, paramClassTypeWriter);
break;
}
}
if (m < 54)
{
localObject = "load";
if (m >= 26) {
break label500;
}
j = -1;
k = m - 21;
paramClassTypeWriter.print("ilfdabcs".charAt(k));
if (j == -2) {
paramClassTypeWriter.write(97);
}
paramClassTypeWriter.print((String)localObject);
if (j < 0) {
break label543;
}
paramClassTypeWriter.write(95);
paramClassTypeWriter.print(j);
k = i;
m = paramInt1;
}
do
{
paramInt1 = m;
j = n;
i = k;
break;
localObject = "store";
m -= 33;
break label399;
if (m < 46)
{
k = m - 26;
j = k % 4;
k >>= 2;
break label416;
}
j = -2;
k = m - 46;
break label416;
m = paramInt1;
k = i;
} while (j != -1);
if (i != 0)
{
i = readUnsignedShort(paramInt1);
m = paramInt1 + 2;
}
for (paramInt1 = i;; paramInt1 = i)
{
k = 0;
paramClassTypeWriter.print(' ');
paramClassTypeWriter.print(paramInt1);
break;
i = this.code[paramInt1] & 0xFF;
m = paramInt1 + 1;
}
if (m < 96)
{
print("pop;pop2;dup;dup_x1;dup_x2;dup2;dup2_x1;dup2_x2;swap;", m - 87, paramClassTypeWriter);
j = n;
break label115;
}
paramClassTypeWriter.print("ilfda".charAt((m - 96) % 4));
print("add;sub;mul;div;rem;neg;", m - 96 >> 2, paramClassTypeWriter);
j = n;
break label115;
if (m < 170)
{
if (m < 132)
{
if ((m & 0x1) == 0) {}
for (c = 'i';; c = 'l')
{
paramClassTypeWriter.print(c);
print("shl;shr;ushr;and;or;xor;", m - 120 >> 1, paramClassTypeWriter);
j = n;
break;
}
}
if (m == 132)
{
paramClassTypeWriter.print("iinc");
if (i == 0)
{
localObject = this.code;
j = paramInt1 + 1;
k = localObject[paramInt1] & 0xFF;
localObject = this.code;
paramInt1 = j + 1;
j = localObject[j];
}
for (;;)
{
paramClassTypeWriter.print(' ');
paramClassTypeWriter.print(k);
paramClassTypeWriter.print(' ');
paramClassTypeWriter.print(j);
j = n;
break;
k = readUnsignedShort(paramInt1);
paramInt1 += 2;
j = (short)readUnsignedShort(paramInt1);
paramInt1 += 2;
i = 0;
}
}
if (m < 148)
{
paramClassTypeWriter.print("ilfdi".charAt((m - 133) / 3));
paramClassTypeWriter.print('2');
paramClassTypeWriter.print("lfdifdildilfbcs".charAt(m - 133));
j = n;
break label115;
}
if (m < 153)
{
print("lcmp;fcmpl;fcmpg;dcmpl;dcmpg;", m - 148, paramClassTypeWriter);
j = n;
break label115;
}
if (m < 169)
{
if (m < 159)
{
paramClassTypeWriter.print("if");
print("eq;ne;lt;ge;gt;le;", m - 153, paramClassTypeWriter);
}
for (;;)
{
j = (short)readUnsignedShort(paramInt1);
paramClassTypeWriter.print(' ');
paramClassTypeWriter.print(k + j);
paramInt1 += 2;
j = n;
break;
if (m < 167)
{
if (m < 165) {
paramClassTypeWriter.print("if_icmp");
}
for (;;)
{
print("eq;ne;lt;ge;gt;le;", m - 159, paramClassTypeWriter);
break;
paramClassTypeWriter.print("if_acmp");
m -= 6;
}
}
print("goto;jsr;", m - 167, paramClassTypeWriter);
}
}
paramClassTypeWriter.print("ret ");
if (i != 0) {
i = readUnsignedShort(paramInt1) + 2;
}
for (;;)
{
k = 0;
paramClassTypeWriter.print(i);
j = n;
i = k;
break;
i = this.code[paramInt1] & 0xFF;
paramInt1 += 1;
}
}
if (m < 172)
{
j = paramInt1;
if (this.fixup_count <= 0) {
j = paramInt1 + 3 & 0xFFFFFFFC;
}
int i2 = readInt(j);
paramInt1 = j + 4;
int i1;
if (m == 170)
{
paramClassTypeWriter.print("tableswitch");
m = readInt(paramInt1);
paramInt1 += 4;
i1 = readInt(paramInt1);
paramInt1 += 4;
paramClassTypeWriter.print(" low: ");
paramClassTypeWriter.print(m);
paramClassTypeWriter.print(" high: ");
paramClassTypeWriter.print(i1);
paramClassTypeWriter.print(" default: ");
paramClassTypeWriter.print(k + i2);
for (;;)
{
j = paramInt1;
if (m > i1) {
break;
}
j = readInt(paramInt1);
paramInt1 += 4;
paramClassTypeWriter.println();
paramClassTypeWriter.print(" ");
paramClassTypeWriter.print(m);
paramClassTypeWriter.print(": ");
paramClassTypeWriter.print(k + j);
m += 1;
}
}
paramClassTypeWriter.print("lookupswitch");
j = readInt(paramInt1);
paramInt1 += 4;
paramClassTypeWriter.print(" npairs: ");
paramClassTypeWriter.print(j);
paramClassTypeWriter.print(" default: ");
paramClassTypeWriter.print(k + i2);
for (;;)
{
m = j - 1;
j = paramInt1;
if (m < 0) {
break;
}
j = readInt(paramInt1);
paramInt1 += 4;
i1 = readInt(paramInt1);
paramInt1 += 4;
paramClassTypeWriter.println();
paramClassTypeWriter.print(" ");
paramClassTypeWriter.print(j);
paramClassTypeWriter.print(": ");
paramClassTypeWriter.print(k + i1);
j = m;
}
paramInt1 = j;
j = n;
break label115;
}
if (m < 178)
{
if (m < 177) {
paramClassTypeWriter.print("ilfda".charAt(m - 172));
}
paramClassTypeWriter.print("return");
j = n;
break label115;
}
if (m < 182)
{
print("getstatic;putstatic;getfield;putfield;", m - 178, paramClassTypeWriter);
j = 2;
break label115;
}
if (m < 185)
{
paramClassTypeWriter.print("invoke");
print("virtual;special;static;", m - 182, paramClassTypeWriter);
j = 2;
break label115;
}
if (m == 185)
{
paramClassTypeWriter.print("invokeinterface (");
j = readUnsignedShort(paramInt1);
paramInt1 += 2;
k = this.code[paramInt1];
paramClassTypeWriter.print((k & 0xFF) + " args)");
paramClassTypeWriter.printConstantOperand(j);
paramInt1 += 2;
j = n;
break label115;
}
if (m < 196)
{
print("186;new;newarray;anewarray;arraylength;athrow;checkcast;instanceof;monitorenter;monitorexit;", m - 186, paramClassTypeWriter);
if ((m == 187) || (m == 189) || (m == 192) || (m == 193))
{
j = 2;
break label115;
}
if (m != 188) {
break label2008;
}
localObject = this.code;
j = paramInt1 + 1;
paramInt1 = localObject[paramInt1];
paramClassTypeWriter.print(' ');
if ((paramInt1 >= 4) && (paramInt1 <= 11))
{
print("boolean;char;float;double;byte;short;int;long;", paramInt1 - 4, paramClassTypeWriter);
paramInt1 = j;
j = n;
break label115;
}
paramClassTypeWriter.print(paramInt1);
paramInt1 = j;
j = n;
break label115;
}
if (m == 196)
{
paramClassTypeWriter.print("wide");
i = 1;
j = n;
break label115;
}
if (m == 197)
{
paramClassTypeWriter.print("multianewarray");
j = readUnsignedShort(paramInt1);
k = paramInt1 + 2;
paramClassTypeWriter.printConstantOperand(j);
localObject = this.code;
paramInt1 = k + 1;
j = localObject[k];
paramClassTypeWriter.print(' ');
paramClassTypeWriter.print(j & 0xFF);
j = n;
break label115;
}
if (m < 200)
{
print("ifnull;ifnonnull;", m - 198, paramClassTypeWriter);
j = (short)readUnsignedShort(paramInt1);
paramClassTypeWriter.print(' ');
paramClassTypeWriter.print(k + j);
paramInt1 += 2;
j = n;
break label115;
}
if (m < 202)
{
print("goto_w;jsr_w;", m - 200, paramClassTypeWriter);
j = readInt(paramInt1);
paramClassTypeWriter.print(' ');
paramClassTypeWriter.print(k + j);
paramInt1 += 4;
j = n;
break label115;
}
paramClassTypeWriter.print(m);
j = n;
break label115;
j = readUnsignedShort(paramInt1);
paramInt1 += 2;
break label150;
return;
}
}
public final void emitAdd()
{
emitBinop(96);
}
public final void emitAdd(char paramChar)
{
emitBinop(96, paramChar);
}
public final void emitAdd(PrimType paramPrimType)
{
emitBinop(96, paramPrimType);
}
public final void emitAnd()
{
emitBinop(126);
}
public final void emitArrayLength()
{
if (!(popType() instanceof ArrayType)) {
throw new Error("non-array type in emitArrayLength");
}
reserve(1);
put1(190);
pushType(Type.intType);
}
public void emitArrayLoad()
{
popType();
Type localType = ((ArrayType)popType().getImplementationType()).getComponentType();
emitTypedOp(46, localType);
pushType(localType);
}
public void emitArrayLoad(Type paramType)
{
popType();
popType();
emitTypedOp(46, paramType);
pushType(paramType);
}
public void emitArrayStore()
{
popType();
popType();
emitTypedOp(79, ((ArrayType)popType().getImplementationType()).getComponentType());
}
public void emitArrayStore(Type paramType)
{
popType();
popType();
popType();
emitTypedOp(79, paramType);
}
public void emitBinop(int paramInt, Type paramType)
{
popType();
popType();
emitTypedOp(paramInt, paramType);
pushType(paramType);
}
public void emitCatchEnd()
{
gotoFinallyOrEnd(false);
this.try_stack.try_type = null;
}
public void emitCatchStart(Variable paramVariable)
{
emitTryEnd(false);
setTypes(this.try_stack.start_try.localTypes, Type.typeArray0);
if (this.try_stack.try_type != null) {
emitCatchEnd();
}
if (paramVariable == null) {}
for (ClassType localClassType = null;; localClassType = (ClassType)paramVariable.getType())
{
this.try_stack.try_type = localClassType;
addHandler(this.try_stack.start_try, this.try_stack.end_try, localClassType);
if (paramVariable != null) {
emitStore(paramVariable);
}
return;
}
}
public void emitCheckcast(Type paramType)
{
if (castNeeded(topType(), paramType))
{
emitCheckcast(paramType, 192);
pushType(paramType);
}
}
public final void emitConvert(Type paramType1, Type paramType2)
{
String str1 = paramType2.getSignature();
String str2 = paramType1.getSignature();
int k = -1;
int i;
int m;
if (str1.length() != 1)
{
i = k;
if (str2.length() != 1) {}
}
else
{
m = str1.charAt(0);
i = str2.charAt(0);
if (i == m) {}
int j;
do
{
return;
if (paramType1.size < 4) {
i = 73;
}
j = i;
if (paramType2.size < 4)
{
emitConvert(paramType1, Type.intType);
j = 73;
}
} while (j == m);
i = k;
switch (j)
{
default:
i = k;
}
}
while (i < 0)
{
throw new Error("unsupported CodeAttr.emitConvert");
switch (m)
{
default:
i = k;
break;
case 66:
i = 145;
break;
case 67:
i = 146;
break;
case 83:
i = 147;
break;
case 74:
i = 133;
break;
case 70:
i = 134;
break;
case 68:
i = 135;
continue;
switch (m)
{
case 69:
case 71:
case 72:
default:
i = k;
break;
case 68:
i = 138;
break;
case 73:
i = 136;
break;
case 70:
i = 137;
continue;
switch (m)
{
default:
i = k;
break;
case 68:
i = 141;
break;
case 73:
i = 139;
break;
case 74:
i = 140;
continue;
switch (m)
{
case 71:
case 72:
default:
i = k;
break;
case 70:
i = 144;
break;
case 73:
i = 142;
break;
case 74:
i = 143;
}
break;
}
break;
}
break;
}
}
reserve(1);
popType();
put1(i);
pushType(paramType2);
}
public final void emitDiv()
{
emitBinop(108);
}
public void emitDup()
{
reserve(1);
Type localType = topType();
if (localType.size <= 4) {}
for (int i = 89;; i = 92)
{
put1(i);
pushType(localType);
return;
}
}
public void emitDup(int paramInt)
{
emitDup(paramInt, 0);
}
public void emitDup(int paramInt1, int paramInt2)
{
if (paramInt1 == 0) {
return;
}
reserve(1);
Type localType3 = popType();
Object localObject2 = null;
if (paramInt1 == 1)
{
if (localType3.size > 4) {
throw new Error("using dup for 2-word type");
}
}
else
{
if (paramInt1 != 2) {
throw new Error("invalid size to emitDup");
}
if (localType3.size <= 4)
{
localObject1 = popType();
localObject2 = localObject1;
if (((Type)localObject1).size > 4) {
throw new Error("dup will cause invalid types on stack");
}
}
}
Object localObject1 = null;
Object localObject3 = null;
if (paramInt2 == 0)
{
if (paramInt1 == 1) {}
for (paramInt1 = 89;; paramInt1 = 92)
{
put1(paramInt1);
if (localObject2 != null) {
pushType((Type)localObject2);
}
pushType(localType3);
if (localObject3 != null) {
pushType((Type)localObject3);
}
if (localObject1 != null) {
pushType((Type)localObject1);
}
if (localObject2 != null) {
pushType((Type)localObject2);
}
pushType(localType3);
return;
}
}
Type localType1;
if (paramInt2 == 1)
{
if (paramInt1 == 1) {}
for (paramInt1 = 90;; paramInt1 = 93)
{
localType1 = popType();
localObject1 = localType1;
if (localType1.size <= 4) {
break;
}
throw new Error("dup will cause invalid types on stack");
}
}
if (paramInt2 == 2)
{
if (paramInt1 == 1) {}
for (paramInt2 = 91;; paramInt2 = 94)
{
localType1 = popType();
paramInt1 = paramInt2;
localObject1 = localType1;
if (localType1.size > 4) {
break;
}
Type localType2 = popType();
paramInt1 = paramInt2;
localObject1 = localType1;
localObject3 = localType2;
if (localType2.size <= 4) {
break;
}
throw new Error("dup will cause invalid types on stack");
}
}
throw new Error("emitDup: invalid offset");
}
public void emitDup(Type paramType)
{
if (paramType.size > 4) {}
for (int i = 2;; i = 1)
{
emitDup(i, 0);
return;
}
}
public void emitDupX()
{
reserve(1);
Type localType1 = popType();
Type localType2 = popType();
if (localType2.size <= 4)
{
if (localType1.size <= 4) {}
for (i = 90;; i = 93)
{
put1(i);
pushType(localType1);
pushType(localType2);
pushType(localType1);
return;
}
}
if (localType1.size <= 4) {}
for (int i = 91;; i = 94)
{
put1(i);
break;
}
}
public final void emitElse()
{
Label localLabel1 = this.if_stack.end_label;
if (reachableHere())
{
Label localLabel2 = new Label(this);
this.if_stack.end_label = localLabel2;
int i = this.SP - this.if_stack.start_stack_size;
this.if_stack.stack_growth = i;
if (i > 0)
{
this.if_stack.then_stacked_types = new Type[i];
System.arraycopy(this.stack_types, this.if_stack.start_stack_size, this.if_stack.then_stacked_types, 0, i);
emitGoto(localLabel2);
}
}
for (;;)
{
if (this.SP <= this.if_stack.start_stack_size) {
break label143;
}
popType();
continue;
this.if_stack.then_stacked_types = new Type[0];
break;
this.if_stack.end_label = null;
}
label143:
this.SP = this.if_stack.start_stack_size;
if (localLabel1 != null) {
localLabel1.define(this);
}
this.if_stack.doing_else = true;
}
public final void emitFi()
{
int j = 0;
int i;
int k;
if (!this.if_stack.doing_else)
{
i = j;
if (reachableHere())
{
i = j;
if (this.SP != this.if_stack.start_stack_size) {
throw new Error("at PC " + this.PC + " then clause grows stack with no else clause");
}
}
}
else
{
if (this.if_stack.then_stacked_types == null) {
break label258;
}
k = this.if_stack.start_stack_size + this.if_stack.stack_growth;
if (reachableHere()) {
break label194;
}
if (this.if_stack.stack_growth > 0) {
System.arraycopy(this.if_stack.then_stacked_types, 0, this.stack_types, this.if_stack.start_stack_size, this.if_stack.stack_growth);
}
this.SP = k;
i = j;
}
for (;;)
{
if (this.if_stack.end_label != null) {
this.if_stack.end_label.define(this);
}
if (i != 0) {
setUnreachable();
}
this.if_stack = this.if_stack.previous;
return;
label194:
i = j;
if (this.SP != k)
{
throw new Error("at PC " + this.PC + ": SP at end of 'then' was " + k + " while SP at end of 'else' was " + this.SP);
label258:
i = j;
if (this.unreachable_here) {
i = 1;
}
}
}
}
public void emitFinallyEnd()
{
if (useJsr()) {
emitRet(this.try_stack.finally_ret_addr);
}
for (;;)
{
popScope();
this.try_stack.finally_subr = null;
return;
if ((this.try_stack.end_label == null) && (this.try_stack.exitCases == null))
{
emitThrow();
}
else
{
emitStore(this.try_stack.exception);
emitLoad(this.try_stack.exception);
emitIfNotNull();
emitLoad(this.try_stack.exception);
emitThrow();
emitElse();
Object localObject = this.try_stack.exitCases;
if (localObject != null)
{
SwitchState localSwitchState = startSwitch();
if (localObject != null)
{
ExitableBlock localExitableBlock = ((ExitableBlock)localObject).nextCase;
((ExitableBlock)localObject).nextCase = null;
((ExitableBlock)localObject).currentTryState = null;
TryState localTryState = TryState.outerHandler(this.try_stack.previous, ((ExitableBlock)localObject).initialTryState);
if (localTryState == ((ExitableBlock)localObject).initialTryState) {
localSwitchState.addCaseGoto(((ExitableBlock)localObject).switchCase, this, ((ExitableBlock)localObject).endLabel);
}
for (;;)
{
localObject = localExitableBlock;
break;
localSwitchState.addCase(((ExitableBlock)localObject).switchCase, this);
((ExitableBlock)localObject).exit(localTryState);
}
}
this.try_stack.exitCases = null;
localSwitchState.addDefault(this);
localSwitchState.finish(this);
}
emitFi();
setUnreachable();
}
}
}
public void emitFinallyStart()
{
emitTryEnd(true);
if (this.try_stack.try_type != null) {
emitCatchEnd();
}
this.try_stack.end_try = getLabel();
pushScope();
if (useJsr())
{
this.SP = 0;
emitCatchStart(null);
emitStore(this.try_stack.exception);
emitJsr(this.try_stack.finally_subr);
emitLoad(this.try_stack.exception);
emitThrow();
}
for (;;)
{
this.try_stack.finally_subr.define(this);
if (useJsr())
{
ClassType localClassType = Type.objectType;
this.try_stack.finally_ret_addr = addLocal(localClassType);
pushType(localClassType);
emitStore(this.try_stack.finally_ret_addr);
}
return;
setUnreachable();
int i = beginFragment(new Label(this));
addHandler(this.try_stack.start_try, this.try_stack.end_try, Type.javalangThrowableType);
if (this.try_stack.saved_result != null) {
emitStoreDefaultValue(this.try_stack.saved_result);
}
if (this.try_stack.exitCases != null)
{
emitPushInt(-1);
emitSwap();
}
emitGoto(this.try_stack.finally_subr);
endFragment(i);
}
}
public final void emitGetField(Field paramField)
{
popType();
pushType(paramField.type);
emitFieldop(paramField, 180);
}
public final void emitGetStatic(Field paramField)
{
pushType(paramField.type);
emitFieldop(paramField, 178);
}
public final void emitGoto(Label paramLabel)
{
paramLabel.setTypes(this);
fixupAdd(4, paramLabel);
reserve(3);
put1(167);
this.PC += 2;
setUnreachable();
}
public final void emitGotoIfCompare1(Label paramLabel, int paramInt)
{
popType();
reserve(3);
emitTransfer(paramLabel, paramInt);
}
public final void emitGotoIfCompare2(Label paramLabel, int paramInt)
{
int i = 0;
if ((paramInt < 153) || (paramInt > 158)) {
throw new Error("emitGotoIfCompare2: logop must be one of ifeq...ifle");
}
Type localType1 = popType().promote();
Type localType2 = popType().promote();
reserve(4);
int j = localType2.getSignature().charAt(0);
int k = localType1.getSignature().charAt(0);
if ((paramInt == 155) || (paramInt == 158)) {
i = 1;
}
if ((j == 73) && (k == 73)) {
paramInt += 6;
}
for (;;)
{
emitTransfer(paramLabel, paramInt);
return;
if ((j == 74) && (k == 74))
{
put1(148);
}
else
{
if ((j == 70) && (k == 70))
{
if (i != 0) {}
for (i = 149;; i = 150)
{
put1(i);
break;
}
}
if ((j == 68) && (k == 68))
{
if (i != 0) {}
for (i = 151;; i = 152)
{
put1(i);
break;
}
}
if (((j != 76) && (j != 91)) || ((k != 76) && (k != 91)) || (paramInt > 154)) {
break;
}
paramInt += 12;
}
}
throw new Error("invalid types to emitGotoIfCompare2");
}
public final void emitGotoIfEq(Label paramLabel)
{
emitGotoIfCompare2(paramLabel, 153);
}
public final void emitGotoIfEq(Label paramLabel, boolean paramBoolean)
{
if (paramBoolean) {}
for (int i = 154;; i = 153)
{
emitGotoIfCompare2(paramLabel, i);
return;
}
}
public final void emitGotoIfGe(Label paramLabel)
{
emitGotoIfCompare2(paramLabel, 156);
}
public final void emitGotoIfGt(Label paramLabel)
{
emitGotoIfCompare2(paramLabel, 157);
}
public final void emitGotoIfIntEqZero(Label paramLabel)
{
emitGotoIfCompare1(paramLabel, 153);
}
public final void emitGotoIfIntGeZero(Label paramLabel)
{
emitGotoIfCompare1(paramLabel, 156);
}
public final void emitGotoIfIntGtZero(Label paramLabel)
{
emitGotoIfCompare1(paramLabel, 157);
}
public final void emitGotoIfIntLeZero(Label paramLabel)
{
emitGotoIfCompare1(paramLabel, 158);
}
public final void emitGotoIfIntLtZero(Label paramLabel)
{
emitGotoIfCompare1(paramLabel, 155);
}
public final void emitGotoIfIntNeZero(Label paramLabel)
{
emitGotoIfCompare1(paramLabel, 154);
}
public final void emitGotoIfLe(Label paramLabel)
{
emitGotoIfCompare2(paramLabel, 158);
}
public final void emitGotoIfLt(Label paramLabel)
{
emitGotoIfCompare2(paramLabel, 155);
}
public final void emitGotoIfNE(Label paramLabel)
{
emitGotoIfCompare2(paramLabel, 154);
}
public final void emitIOr()
{
emitBinop(128);
}
public final void emitIfCompare1(int paramInt)
{
IfState localIfState = new IfState(this);
if (popType().promote() != Type.intType) {
throw new Error("non-int type to emitIfCompare1");
}
reserve(3);
emitTransfer(localIfState.end_label, paramInt);
localIfState.start_stack_size = this.SP;
}
public final void emitIfEq()
{
IfState localIfState = new IfState(this);
emitGotoIfNE(localIfState.end_label);
localIfState.start_stack_size = this.SP;
}
public final void emitIfGe()
{
IfState localIfState = new IfState(this);
emitGotoIfLt(localIfState.end_label);
localIfState.start_stack_size = this.SP;
}
public final void emitIfGt()
{
IfState localIfState = new IfState(this);
emitGotoIfLe(localIfState.end_label);
localIfState.start_stack_size = this.SP;
}
public final void emitIfIntCompare(int paramInt)
{
IfState localIfState = new IfState(this);
popType();
popType();
reserve(3);
emitTransfer(localIfState.end_label, paramInt);
localIfState.start_stack_size = this.SP;
}
public final void emitIfIntEqZero()
{
emitIfCompare1(154);
}
public final void emitIfIntLEqZero()
{
emitIfCompare1(157);
}
public final void emitIfIntLt()
{
emitIfIntCompare(162);
}
public final void emitIfIntNotZero()
{
emitIfCompare1(153);
}
public final void emitIfLe()
{
IfState localIfState = new IfState(this);
emitGotoIfGt(localIfState.end_label);
localIfState.start_stack_size = this.SP;
}
public final void emitIfLt()
{
IfState localIfState = new IfState(this);
emitGotoIfGe(localIfState.end_label);
localIfState.start_stack_size = this.SP;
}
public final void emitIfNEq()
{
IfState localIfState = new IfState(this);
emitGotoIfEq(localIfState.end_label);
localIfState.start_stack_size = this.SP;
}
public final void emitIfNotNull()
{
emitIfRefCompare1(198);
}
public final void emitIfNull()
{
emitIfRefCompare1(199);
}
public final void emitIfRefCompare1(int paramInt)
{
IfState localIfState = new IfState(this);
if (!(popType() instanceof ObjectType)) {
throw new Error("non-ref type to emitIfRefCompare1");
}
reserve(3);
emitTransfer(localIfState.end_label, paramInt);
localIfState.start_stack_size = this.SP;
}
public final void emitIfThen()
{
new IfState(this, null);
}
public void emitInc(Variable paramVariable, short paramShort)
{
if (paramVariable.dead()) {
throw new Error("attempting to increment dead variable");
}
int j = paramVariable.offset;
if ((j < 0) || (!paramVariable.isSimple())) {
throw new Error("attempting to increment unassigned variable" + paramVariable.getName() + " simple:" + paramVariable.isSimple() + ", offset: " + j);
}
reserve(6);
if (paramVariable.getType().getImplementationType().promote() != Type.intType) {
throw new Error("attempting to increment non-int variable");
}
if ((j > 255) || (paramShort > 255) || (paramShort < 65280)) {}
for (int i = 1; i != 0; i = 0)
{
put1(196);
put1(132);
put2(j);
put2(paramShort);
return;
}
put1(132);
put1(j);
put1(paramShort);
}
public void emitInstanceof(Type paramType)
{
emitCheckcast(paramType, 193);
pushType(Type.booleanType);
}
public void emitInvoke(Method paramMethod)
{
int i;
if ((paramMethod.access_flags & 0x8) != 0) {
i = 184;
}
for (;;)
{
emitInvokeMethod(paramMethod, i);
return;
if (paramMethod.classfile.isInterface()) {
i = 185;
} else if ("<init>".equals(paramMethod.getName())) {
i = 183;
} else {
i = 182;
}
}
}
public void emitInvokeInterface(Method paramMethod)
{
emitInvokeMethod(paramMethod, 185);
}
public void emitInvokeMethod(Method paramMethod, int paramInt)
{
int m = 1;
int n;
label34:
int j;
if (paramInt == 185)
{
i = 5;
reserve(i);
n = paramMethod.arg_types.length;
if (paramInt != 184) {
break label112;
}
k = 1;
if ((paramInt != 183) || (!"<init>".equals(paramMethod.getName()))) {
break label118;
}
j = 1;
label57:
if ((paramMethod.access_flags & 0x8) == 0) {
break label124;
}
}
label112:
label118:
label124:
for (int i = m;; i = 0)
{
if (k == i) {
break label129;
}
throw new Error("emitInvokeXxx static flag mis-match method.flags=" + paramMethod.access_flags);
i = 3;
break;
k = 0;
break label34;
j = 0;
break label57;
}
label129:
i = n;
if (k == 0)
{
i = n;
if (j == 0) {
i = n + 1;
}
}
put1(paramInt);
putIndex2(getConstants().addMethodRef(paramMethod));
int k = i;
if (paramInt == 185)
{
put1(words(paramMethod.arg_types) + 1);
put1(0);
k = i;
}
Type localType;
do
{
k -= 1;
if (k < 0) {
break;
}
localType = popType();
} while (!(localType instanceof UninitializedType));
throw new Error("passing " + localType + " as parameter");
if (j != 0)
{
localType = popType();
if (!(localType instanceof UninitializedType)) {
throw new Error("calling <init> on already-initialized object");
}
ClassType localClassType = ((UninitializedType)localType).ctype;
paramInt = 0;
while (paramInt < this.SP)
{
if (this.stack_types[paramInt] == localType) {
this.stack_types[paramInt] = localClassType;
}
paramInt += 1;
}
Variable[] arrayOfVariable = this.locals.used;
if (arrayOfVariable == null) {
paramInt = 0;
}
for (;;)
{
i = paramInt - 1;
if (i < 0) {
break;
}
Variable localVariable = arrayOfVariable[i];
paramInt = i;
if (localVariable != null)
{
paramInt = i;
if (localVariable.type == localType)
{
localVariable.type = localClassType;
paramInt = i;
continue;
paramInt = arrayOfVariable.length;
}
}
}
if (this.local_types == null) {
paramInt = 0;
}
for (;;)
{
i = paramInt - 1;
if (i < 0) {
break;
}
paramInt = i;
if (this.local_types[i] == localType)
{
this.local_types[i] = localClassType;
paramInt = i;
continue;
paramInt = this.local_types.length;
}
}
}
if (paramMethod.return_type.size != 0) {
pushType(paramMethod.return_type);
}
}
public void emitInvokeSpecial(Method paramMethod)
{
emitInvokeMethod(paramMethod, 183);
}
public void emitInvokeStatic(Method paramMethod)
{
emitInvokeMethod(paramMethod, 184);
}
public void emitInvokeVirtual(Method paramMethod)
{
emitInvokeMethod(paramMethod, 182);
}
public final void emitJsr(Label paramLabel)
{
fixupAdd(5, paramLabel);
reserve(3);
put1(168);
this.PC += 2;
}
public final void emitLoad(Variable paramVariable)
{
if (paramVariable.dead()) {
throw new Error("attempting to push dead variable");
}
int i = paramVariable.offset;
if ((i < 0) || (!paramVariable.isSimple())) {
throw new Error("attempting to load from unassigned variable " + paramVariable + " simple:" + paramVariable.isSimple() + ", offset: " + i);
}
Type localType = paramVariable.getType().promote();
reserve(4);
int j = adjustTypedOp(localType);
if (i <= 3) {
put1(j * 4 + 26 + i);
}
for (;;)
{
pushType(paramVariable.getType());
return;
emitMaybeWide(j + 21, i);
}
}
void emitMaybeWide(int paramInt1, int paramInt2)
{
if (paramInt2 >= 256)
{
put1(196);
put1(paramInt1);
put2(paramInt2);
return;
}
put1(paramInt1);
put1(paramInt2);
}
public final void emitMonitorEnter()
{
popType();
reserve(1);
put1(194);
}
public final void emitMonitorExit()
{
popType();
reserve(1);
put1(195);
}
public final void emitMul()
{
emitBinop(104);
}
public void emitNew(ClassType paramClassType)
{
reserve(3);
Label localLabel = new Label(this);
localLabel.defineRaw(this);
put1(187);
putIndex2(getConstants().addClass(paramClassType));
pushType(new UninitializedType(paramClassType, localLabel));
}
void emitNewArray(int paramInt)
{
reserve(2);
put1(188);
put1(paramInt);
}
public void emitNewArray(Type paramType)
{
emitNewArray(paramType, 1);
}
public void emitNewArray(Type paramType, int paramInt)
{
if (popType().promote() != Type.intType) {
throw new Error("non-int dim. spec. in emitNewArray");
}
if ((paramType instanceof PrimType)) {
switch (paramType.getSignature().charAt(0))
{
default:
throw new Error("bad PrimType in emitNewArray");
case 'B':
paramInt = 8;
emitNewArray(paramInt);
}
}
for (;;)
{
pushType(new ArrayType(paramType));
return;
paramInt = 9;
break;
paramInt = 10;
break;
paramInt = 11;
break;
paramInt = 6;
break;
paramInt = 7;
break;
paramInt = 4;
break;
paramInt = 5;
break;
if (!(paramType instanceof ObjectType)) {
break label221;
}
reserve(3);
put1(189);
putIndex2(getConstants().addClass((ObjectType)paramType));
}
label221:
if ((paramType instanceof ArrayType))
{
reserve(4);
put1(197);
putIndex2(getConstants().addClass(new ArrayType(paramType)));
if ((paramInt < 1) || (paramInt > 255)) {
throw new Error("dims out of range in emitNewArray");
}
put1(paramInt);
do
{
paramInt -= 1;
if (paramInt <= 0) {
break;
}
} while (popType().promote() == Type.intType);
throw new Error("non-int dim. spec. in emitNewArray");
}
throw new Error("unimplemented type in emitNewArray");
}
public final void emitNot(Type paramType)
{
emitPushConstant(1, paramType);
emitAdd();
emitPushConstant(1, paramType);
emitAnd();
}
public void emitPop(int paramInt)
{
if (paramInt > 0)
{
reserve(1);
if (popType().size > 4) {
put1(88);
}
for (;;)
{
paramInt -= 1;
break;
if (paramInt > 1)
{
if (popType().size > 4)
{
put1(87);
reserve(1);
}
put1(88);
paramInt -= 1;
}
else
{
put1(87);
}
}
}
}
public void emitPrimop(int paramInt1, int paramInt2, Type paramType)
{
reserve(1);
for (;;)
{
paramInt2 -= 1;
if (paramInt2 < 0) {
break;
}
popType();
}
put1(paramInt1);
pushType(paramType);
}
public final void emitPushClass(ObjectType paramObjectType)
{
emitPushConstant(getConstants().addClass(paramObjectType));
pushType(Type.javalangClassType);
}
public final void emitPushConstant(int paramInt, Type paramType)
{
switch (paramType.getSignature().charAt(0))
{
default:
throw new Error("bad type to emitPushConstant");
case 'B':
case 'C':
case 'I':
case 'S':
case 'Z':
emitPushInt(paramInt);
return;
case 'J':
emitPushLong(paramInt);
return;
case 'F':
emitPushFloat(paramInt);
return;
}
emitPushDouble(paramInt);
}
public final void emitPushConstant(CpoolEntry paramCpoolEntry)
{
reserve(3);
int i = paramCpoolEntry.index;
if ((paramCpoolEntry instanceof CpoolValue2))
{
put1(20);
put2(i);
return;
}
if (i < 256)
{
put1(18);
put1(i);
return;
}
put1(19);
put2(i);
}
public void emitPushDefaultValue(Type paramType)
{
paramType = paramType.getImplementationType();
if ((paramType instanceof PrimType))
{
emitPushConstant(0, paramType);
return;
}
emitPushNull();
}
public void emitPushDouble(double paramDouble)
{
int i = (int)paramDouble;
if ((i == paramDouble) && (i >= -128) && (i < 128)) {
if ((i == 0) || (i == 1))
{
reserve(1);
put1(i + 14);
if ((i == 0) && (Double.doubleToLongBits(paramDouble) != 0L))
{
reserve(1);
put1(119);
}
}
}
for (;;)
{
pushType(Type.doubleType);
return;
emitPushInt(i);
reserve(1);
popType();
put1(135);
continue;
emitPushConstant(getConstants().addDouble(paramDouble));
}
}
public void emitPushFloat(float paramFloat)
{
int i = (int)paramFloat;
if ((i == paramFloat) && (i >= -128) && (i < 128)) {
if ((i >= 0) && (i <= 2))
{
reserve(1);
put1(i + 11);
if ((i == 0) && (Float.floatToIntBits(paramFloat) != 0))
{
reserve(1);
put1(118);
}
}
}
for (;;)
{
pushType(Type.floatType);
return;
emitPushInt(i);
reserve(1);
popType();
put1(134);
continue;
emitPushConstant(getConstants().addFloat(paramFloat));
}
}
public final void emitPushInt(int paramInt)
{
reserve(3);
if ((paramInt >= -1) && (paramInt <= 5)) {
put1(paramInt + 3);
}
for (;;)
{
pushType(Type.intType);
return;
if ((paramInt >= -128) && (paramInt < 128))
{
put1(16);
put1(paramInt);
}
else if ((paramInt >= 32768) && (paramInt < 32768))
{
put1(17);
put2(paramInt);
}
else
{
emitPushConstant(getConstants().addInt(paramInt));
}
}
}
public void emitPushLong(long paramLong)
{
if ((paramLong == 0L) || (paramLong == 1L))
{
reserve(1);
put1((int)paramLong + 9);
}
for (;;)
{
pushType(Type.longType);
return;
if ((int)paramLong == paramLong)
{
emitPushInt((int)paramLong);
reserve(1);
popType();
put1(133);
}
else
{
emitPushConstant(getConstants().addLong(paramLong));
}
}
}
public void emitPushNull()
{
reserve(1);
put1(1);
pushType(Type.nullType);
}
public final void emitPushPrimArray(Object paramObject, ArrayType paramArrayType)
{
Type localType = paramArrayType.getComponentType();
int j = Array.getLength(paramObject);
emitPushInt(j);
emitNewArray(localType);
int k = localType.getSignature().charAt(0);
int i = 0;
if (i < j)
{
long l1 = 0L;
float f1 = 0.0F;
double d1 = 0.0D;
switch (k)
{
default:
label128:
emitDup(paramArrayType);
emitPushInt(i);
switch (k)
{
}
break;
}
for (;;)
{
emitArrayStore(localType);
for (;;)
{
label222:
i += 1;
break;
long l2 = ((long[])(long[])paramObject)[i];
l1 = l2;
if (l2 != 0L) {
break label128;
}
continue;
l2 = ((int[])(int[])paramObject)[i];
l1 = l2;
if (l2 != 0L) {
break label128;
}
continue;
l2 = ((short[])(short[])paramObject)[i];
l1 = l2;
if (l2 != 0L) {
break label128;
}
continue;
l2 = ((char[])(char[])paramObject)[i];
l1 = l2;
if (l2 != 0L) {
break label128;
}
continue;
l2 = ((byte[])(byte[])paramObject)[i];
l1 = l2;
if (l2 != 0L) {
break label128;
}
continue;
if (((boolean[])(boolean[])paramObject)[i] != 0) {}
for (l2 = 1L;; l2 = 0L)
{
l1 = l2;
if (l2 != 0L) {
break;
}
break label222;
}
float f2 = ((float[])(float[])paramObject)[i];
f1 = f2;
if (f2 != 0.0D) {
break label128;
}
continue;
double d2 = ((double[])(double[])paramObject)[i];
d1 = d2;
if (d2 != 0.0D) {
break label128;
}
}
emitPushInt((int)l1);
continue;
emitPushLong(l1);
continue;
emitPushFloat(f1);
continue;
emitPushDouble(d1);
}
}
}
public final void emitPushString(String paramString)
{
if (paramString == null) {
emitPushNull();
}
for (;;)
{
return;
int i = paramString.length();
String str = calculateSplit(paramString);
int m = str.length();
if (m <= 1)
{
emitPushConstant(getConstants().addString(paramString));
pushType(Type.javalangStringType);
return;
}
if (m == 2)
{
i = str.charAt(0);
emitPushString(paramString.substring(0, i));
emitPushString(paramString.substring(i));
emitInvokeVirtual(Type.javalangStringType.getDeclaredMethod("concat", 1));
}
while (paramString == paramString.intern())
{
emitInvokeVirtual(Type.javalangStringType.getDeclaredMethod("intern", 0));
return;
ClassType localClassType = ClassType.make("java.lang.StringBuffer");
emitNew(localClassType);
emitDup(localClassType);
emitPushInt(i);
emitInvokeSpecial(localClassType.getDeclaredMethod("<init>", new Type[] { Type.intType }));
Method localMethod = localClassType.getDeclaredMethod("append", new Type[] { Type.javalangStringType });
int j = 0;
i = 0;
while (i < m)
{
emitDup(localClassType);
int k = j + str.charAt(i);
emitPushString(paramString.substring(j, k));
emitInvokeVirtual(localMethod);
j = k;
i += 1;
}
emitInvokeVirtual(Type.toString_method);
}
}
}
public final void emitPushThis()
{
emitLoad(this.locals.used[0]);
}
public final void emitPutField(Field paramField)
{
popType();
popType();
emitFieldop(paramField, 181);
}
public final void emitPutStatic(Field paramField)
{
popType();
emitFieldop(paramField, 179);
}
final void emitRawReturn()
{
if (getMethod().getReturnType().size == 0)
{
reserve(1);
put1(177);
}
for (;;)
{
setUnreachable();
return;
emitTypedOp(172, popType().promote());
}
}
public final void emitRem()
{
emitBinop(112);
}
public void emitRet(Variable paramVariable)
{
int i = paramVariable.offset;
if (i < 256)
{
reserve(2);
put1(169);
put1(i);
return;
}
reserve(4);
put1(196);
put1(169);
put2(i);
}
public final void emitReturn()
{
if (this.try_stack != null) {
new Error();
}
emitRawReturn();
}
public final void emitShl()
{
emitShift(120);
}
public final void emitShr()
{
emitShift(122);
}
public void emitStore(Variable paramVariable)
{
int i = paramVariable.offset;
if ((i < 0) || (!paramVariable.isSimple())) {
throw new Error("attempting to store in unassigned " + paramVariable + " simple:" + paramVariable.isSimple() + ", offset: " + i);
}
paramVariable = paramVariable.getType().promote();
noteVarType(i, paramVariable);
reserve(4);
popType();
int j = adjustTypedOp(paramVariable);
if (i <= 3)
{
put1(j * 4 + 59 + i);
return;
}
emitMaybeWide(j + 54, i);
}
public void emitStoreDefaultValue(Variable paramVariable)
{
emitPushDefaultValue(paramVariable.getType());
emitStore(paramVariable);
}
public final void emitSub()
{
emitBinop(100);
}
public final void emitSub(char paramChar)
{
emitBinop(100, paramChar);
}
public final void emitSub(PrimType paramPrimType)
{
emitBinop(100, paramPrimType);
}
public void emitSwap()
{
reserve(1);
Type localType1 = popType();
Type localType2 = popType();
if ((localType1.size > 4) || (localType2.size > 4))
{
pushType(localType2);
pushType(localType1);
emitDupX();
emitPop(1);
return;
}
pushType(localType1);
put1(95);
pushType(localType2);
}
public void emitTailCall(boolean paramBoolean, Scope paramScope)
{
if (paramBoolean)
{
Method localMethod = getMethod();
int i;
if ((localMethod.access_flags & 0x8) != 0)
{
i = 0;
j = localMethod.arg_types.length;
label31:
k = j - 1;
if (k < 0) {
break label83;
}
if (localMethod.arg_types[k].size <= 4) {
break label77;
}
}
label77:
for (int j = 2;; j = 1)
{
i += j;
j = k;
break label31;
i = 1;
break;
}
label83:
j = localMethod.arg_types.length;
int k = j - 1;
if (k >= 0)
{
if (localMethod.arg_types[k].size > 4) {}
for (j = 2;; j = 1)
{
i -= j;
emitStore(this.locals.used[i]);
j = k;
break;
}
}
}
emitGoto(paramScope.start);
}
public final void emitThen()
{
this.if_stack.start_stack_size = this.SP;
}
public final void emitThrow()
{
popType();
reserve(1);
put1(191);
setUnreachable();
}
final void emitTransfer(Label paramLabel, int paramInt)
{
paramLabel.setTypes(this);
fixupAdd(6, paramLabel);
put1(paramInt);
this.PC += 2;
}
public void emitTryCatchEnd()
{
if (this.try_stack.finally_subr != null) {
emitFinallyEnd();
}
Variable[] arrayOfVariable = this.try_stack.savedStack;
if (this.try_stack.end_label == null) {
setUnreachable();
}
for (;;)
{
if ((this.try_stack.saved_result != null) || (arrayOfVariable != null)) {
popScope();
}
this.try_stack = this.try_stack.previous;
return;
setTypes(this.try_stack.start_try.localTypes, Type.typeArray0);
this.try_stack.end_label.define(this);
if (arrayOfVariable != null)
{
int i = arrayOfVariable.length;
for (;;)
{
int j = i - 1;
if (j < 0) {
break;
}
Variable localVariable = arrayOfVariable[j];
i = j;
if (localVariable != null)
{
emitLoad(localVariable);
i = j;
}
}
}
if (this.try_stack.saved_result != null) {
emitLoad(this.try_stack.saved_result);
}
}
}
public void emitTryEnd()
{
emitTryEnd(false);
}
public void emitTryStart(boolean paramBoolean, Type paramType)
{
Type localType = paramType;
if (paramType != null)
{
localType = paramType;
if (paramType.isVoid()) {
localType = null;
}
}
paramType = null;
if ((localType != null) || (this.SP > 0)) {
pushScope();
}
int i;
if (this.SP > 0)
{
localObject = new Variable[this.SP];
i = 0;
for (;;)
{
paramType = (Type)localObject;
if (this.SP <= 0) {
break;
}
paramType = addLocal(topType());
emitStore(paramType);
localObject[i] = paramType;
i += 1;
}
}
Object localObject = new TryState(this);
((TryState)localObject).savedStack = paramType;
if (this.local_types == null)
{
i = 0;
if ((i > 0) && (this.local_types[(i - 1)] == null)) {
break label192;
}
if (i != 0) {
break label199;
}
paramType = Type.typeArray0;
}
for (;;)
{
((TryState)localObject).start_try.localTypes = paramType;
if (localType != null) {
((TryState)localObject).saved_result = addLocal(localType);
}
if (paramBoolean) {
((TryState)localObject).finally_subr = new Label();
}
return;
i = this.local_types.length;
break;
label192:
i -= 1;
break;
label199:
paramType = new Type[i];
System.arraycopy(this.local_types, 0, paramType, 0, i);
}
}
public final void emitUshr()
{
emitShift(124);
}
public void emitWithCleanupCatch(Variable paramVariable)
{
emitTryEnd();
Type[] arrayOfType;
if (this.SP > 0)
{
arrayOfType = new Type[this.SP];
System.arraycopy(this.stack_types, 0, arrayOfType, 0, this.SP);
this.SP = 0;
}
for (;;)
{
this.try_stack.savedTypes = arrayOfType;
this.try_stack.saved_result = paramVariable;
int i = this.SP;
emitCatchStart(paramVariable);
return;
arrayOfType = null;
}
}
public void emitWithCleanupDone()
{
Object localObject = this.try_stack.saved_result;
this.try_stack.saved_result = null;
if (localObject != null) {
emitLoad((Variable)localObject);
}
emitThrow();
emitCatchEnd();
localObject = this.try_stack.savedTypes;
emitTryCatchEnd();
if (localObject != null)
{
this.SP = localObject.length;
if (this.SP >= this.stack_types.length)
{
this.stack_types = ((Type[])localObject);
return;
}
System.arraycopy(localObject, 0, this.stack_types, 0, this.SP);
return;
}
this.SP = 0;
}
public void emitWithCleanupStart()
{
int i = this.SP;
this.SP = 0;
emitTryStart(false, null);
this.SP = i;
}
public final void emitXOr()
{
emitBinop(130);
}
public void endExitableBlock()
{
ExitableBlock localExitableBlock = this.currentExitableBlock;
localExitableBlock.finish();
this.currentExitableBlock = localExitableBlock.outer;
}
public void endFragment(int paramInt)
{
this.fixup_offsets[paramInt] = (this.fixup_count << 4 | 0xA);
Label localLabel = this.fixup_labels[paramInt];
fixupAdd(9, 0, null);
localLabel.define(this);
}
public void enterScope(Scope paramScope)
{
paramScope.setStartPC(this);
this.locals.enterScope(paramScope);
}
final void fixupAdd(int paramInt1, int paramInt2, Label paramLabel)
{
if ((paramLabel != null) && (paramInt1 != 1) && (paramInt1 != 0) && (paramInt1 != 2) && (paramInt1 != 11)) {
paramLabel.needsStackMapEntry = true;
}
int i = this.fixup_count;
if (i == 0)
{
this.fixup_offsets = new int[30];
this.fixup_labels = new Label[30];
}
for (;;)
{
this.fixup_offsets[i] = (paramInt2 << 4 | paramInt1);
this.fixup_labels[i] = paramLabel;
this.fixup_count = (i + 1);
return;
if (this.fixup_count == this.fixup_offsets.length)
{
int j = i * 2;
Object localObject = new Label[j];
System.arraycopy(this.fixup_labels, 0, localObject, 0, i);
this.fixup_labels = ((Label[])localObject);
localObject = new int[j];
System.arraycopy(this.fixup_offsets, 0, localObject, 0, i);
this.fixup_offsets = ((int[])localObject);
}
}
}
public final void fixupAdd(int paramInt, Label paramLabel)
{
fixupAdd(paramInt, this.PC, paramLabel);
}
public final void fixupChain(Label paramLabel1, Label paramLabel2)
{
fixupAdd(9, 0, paramLabel2);
paramLabel1.defineRaw(this);
}
public Variable getArg(int paramInt)
{
return this.locals.parameter_scope.getVariable(paramInt);
}
public final Attribute getAttributes()
{
return this.attributes;
}
public byte[] getCode()
{
return this.code;
}
public int getCodeLength()
{
return this.PC;
}
public final ConstantPool getConstants()
{
return getMethod().classfile.constants;
}
public Scope getCurrentScope()
{
return this.locals.current_scope;
}
public final TryState getCurrentTry()
{
return this.try_stack;
}
public Label getLabel()
{
Label localLabel = new Label();
localLabel.defineRaw(this);
return localLabel;
}
public final int getLength()
{
return getCodeLength() + 12 + this.exception_table_length * 8 + Attribute.getLengthAll(this);
}
public int getMaxLocals()
{
return this.max_locals;
}
public int getMaxStack()
{
return this.max_stack;
}
public final Method getMethod()
{
return (Method)getContainer();
}
public final int getPC()
{
return this.PC;
}
public final int getSP()
{
return this.SP;
}
byte invert_opcode(byte paramByte)
{
paramByte &= 0xFF;
if (((paramByte >= 153) && (paramByte <= 166)) || ((paramByte >= 198) && (paramByte <= 199))) {
return (byte)(paramByte ^ 0x1);
}
throw new Error("unknown opcode to invert_opcode");
}
public final boolean isInTry()
{
return this.try_stack != null;
}
public Variable lookup(String paramString)
{
for (Scope localScope = this.locals.current_scope; localScope != null; localScope = localScope.parent)
{
Variable localVariable = localScope.lookup(paramString);
if (localVariable != null) {
return localVariable;
}
}
return null;
}
void noteParamTypes()
{
Method localMethod = getMethod();
int i = 0;
Object localObject;
if ((localMethod.access_flags & 0x8) == 0)
{
ClassType localClassType = localMethod.classfile;
localObject = localClassType;
if ("<init>".equals(localMethod.getName()))
{
localObject = localClassType;
if (!"java.lang.Object".equals(localClassType.getName())) {
localObject = UninitializedType.uninitializedThis((ClassType)localClassType);
}
}
noteVarType(0, (Type)localObject);
i = 0 + 1;
}
int m = localMethod.arg_types.length;
int k = 0;
for (int j = i; k < m; j = i)
{
localObject = localMethod.arg_types[k];
i = j + 1;
noteVarType(j, (Type)localObject);
j = ((Type)localObject).getSizeInWords();
for (;;)
{
j -= 1;
if (j <= 0) {
break;
}
i += 1;
}
k += 1;
}
if ((this.flags & 0x1) != 0)
{
this.stackMap = new StackMapTableAttr();
localObject = new int[j + 20];
i = 0;
k = 0;
while (i < j)
{
m = this.stackMap.encodeVerificationType(this.local_types[i], this);
localObject[k] = m;
int n = m & 0xFF;
if (n != 3)
{
m = i;
if (n != 4) {}
}
else
{
m = i + 1;
}
i = m + 1;
k += 1;
}
this.stackMap.encodedLocals = ((int[])localObject);
this.stackMap.countLocals = k;
this.stackMap.encodedStack = new int[10];
this.stackMap.countStack = 0;
}
}
public void noteVarType(int paramInt, Type paramType)
{
int k = paramType.getSizeInWords();
if (this.local_types == null)
{
this.local_types = new Type[paramInt + k + 20];
this.local_types[paramInt] = paramType;
if (this.varsSetInCurrentBlock != null) {
break label192;
}
this.varsSetInCurrentBlock = new boolean[this.local_types.length];
}
for (;;)
{
this.varsSetInCurrentBlock[paramInt] = true;
int i = k;
int j = paramInt;
if (paramInt > 0)
{
paramType = this.local_types[(paramInt - 1)];
i = k;
j = paramInt;
if (paramType != null)
{
i = k;
j = paramInt;
if (paramType.getSizeInWords() == 2)
{
this.local_types[(paramInt - 1)] = null;
j = paramInt;
i = k;
}
}
}
for (;;)
{
i -= 1;
if (i <= 0) {
break;
}
paramType = this.local_types;
j += 1;
paramType[j] = null;
}
if (paramInt + k <= this.local_types.length) {
break;
}
Type[] arrayOfType = new Type[(paramInt + k) * 2];
System.arraycopy(this.local_types, 0, arrayOfType, 0, this.local_types.length);
this.local_types = arrayOfType;
break;
label192:
if (this.varsSetInCurrentBlock.length <= paramInt)
{
paramType = new boolean[this.local_types.length];
System.arraycopy(this.varsSetInCurrentBlock, 0, paramType, 0, this.varsSetInCurrentBlock.length);
this.varsSetInCurrentBlock = paramType;
}
}
}
public Scope popScope()
{
Scope localScope = this.locals.current_scope;
this.locals.current_scope = localScope.parent;
localScope.freeLocals(this);
localScope.end = getLabel();
return localScope;
}
public final Type popType()
{
if (this.SP <= 0) {
throw new Error("popType called with empty stack " + getMethod());
}
Object localObject = this.stack_types;
int i = this.SP - 1;
this.SP = i;
localObject = localObject[i];
if ((((Type)localObject).size == 8) && (!popType().isVoid())) {
throw new Error("missing void type on stack");
}
return (Type)localObject;
}
public void print(ClassTypeWriter paramClassTypeWriter)
{
paramClassTypeWriter.print("Attribute \"");
paramClassTypeWriter.print(getName());
paramClassTypeWriter.print("\", length:");
paramClassTypeWriter.print(getLength());
paramClassTypeWriter.print(", max_stack:");
paramClassTypeWriter.print(this.max_stack);
paramClassTypeWriter.print(", max_locals:");
paramClassTypeWriter.print(this.max_locals);
paramClassTypeWriter.print(", code_length:");
int i = getCodeLength();
paramClassTypeWriter.println(i);
disAssemble(paramClassTypeWriter, 0, i);
if (this.exception_table_length > 0)
{
paramClassTypeWriter.print("Exceptions (count: ");
paramClassTypeWriter.print(this.exception_table_length);
paramClassTypeWriter.println("):");
int j = this.exception_table_length;
i = 0;
j -= 1;
if (j >= 0)
{
paramClassTypeWriter.print(" start: ");
paramClassTypeWriter.print(this.exception_table[i] & 0xFFFF);
paramClassTypeWriter.print(", end: ");
paramClassTypeWriter.print(this.exception_table[(i + 1)] & 0xFFFF);
paramClassTypeWriter.print(", handler: ");
paramClassTypeWriter.print(this.exception_table[(i + 2)] & 0xFFFF);
paramClassTypeWriter.print(", type: ");
int k = this.exception_table[(i + 3)] & 0xFFFF;
if (k == 0) {
paramClassTypeWriter.print("0 /* finally */");
}
for (;;)
{
paramClassTypeWriter.println();
i += 4;
break;
paramClassTypeWriter.printOptionalIndex(k);
paramClassTypeWriter.printConstantTersely(k, 7);
}
}
}
paramClassTypeWriter.printAttributes(this);
}
public void processFixups()
{
if (this.fixup_count <= 0) {
return;
}
int k = 0;
int n = this.fixup_count;
fixupAdd(9, 0, null);
int j = 0;
int i3 = this.fixup_offsets[j];
int i2 = i3 >> 4;
Object localObject1 = this.fixup_labels[j];
int i = k;
int m = j;
int i1 = n;
switch (i3 & 0xF)
{
case 7:
case 12:
case 13:
default:
throw new Error("unexpected fixup");
case 11:
m = j + 2;
i = k;
case 0:
case 3:
case 8:
case 14:
case 1:
case 2:
case 4:
case 5:
case 6:
for (;;)
{
j = m + 1;
k = i;
break;
m = j + 1;
i = k;
continue;
((Label)localObject1).position += k;
i = k;
m = j;
continue;
i = k + 3;
m = j;
continue;
if ((((Label)localObject1).first_fixup == j + 1) && (fixupOffset(j + 1) == i2 + 3))
{
this.fixup_offsets[j] = (i2 << 4 | 0x8);
this.fixup_labels[j] = null;
i = k - 3;
m = j;
}
else
{
i = k;
m = j;
if (this.PC >= 32768)
{
i = k + 2;
m = j;
continue;
i = k;
m = j;
if (this.PC >= 32768)
{
i = k + 5;
m = j;
}
}
}
}
case 10:
this.fixup_labels[n] = this.fixup_labels[(j + 1)];
i1 = i2;
}
if (j + 1 >= this.fixup_count)
{
i = this.PC;
label358:
this.fixup_offsets[j] = (i << 4 | 0x9);
if (localObject1 != null) {
break label484;
}
i3 = this.PC;
m = 0;
i = 0;
}
Object localObject2;
label484:
label870:
label879:
label918:
byte[] arrayOfByte;
int i4;
for (;;)
{
if (i < this.fixup_count)
{
j = this.fixup_offsets[i];
i1 = j & 0xF;
localObject2 = this.fixup_labels[i];
localObject1 = localObject2;
if (localObject2 != null)
{
localObject1 = localObject2;
if (((Label)localObject2).position < 0)
{
throw new Error("undefined label " + localObject2);
i = fixupOffset(this.fixup_labels[(j + 1)].first_fixup);
break label358;
j = ((Label)localObject1).first_fixup;
k = i + k - fixupOffset(j);
n = i1;
break;
}
}
while ((localObject1 != null) && (i1 >= 4) && (i1 <= 7) && (((Label)localObject1).first_fixup + 1 < this.fixup_count) && (this.fixup_offsets[(localObject1.first_fixup + 1)] == (this.fixup_offsets[localObject1.first_fixup] & 0xF | 0x4)))
{
localObject1 = this.fixup_labels[(localObject1.first_fixup + 1)];
this.fixup_labels[i] = localObject1;
}
i2 = j >> 4;
j = m;
n = i;
k = i3;
switch (i1)
{
case 7:
case 10:
case 12:
case 13:
default:
throw new Error("unexpected fixup");
case 11:
n = i + 2;
this.fixup_labels[n].position = (i2 + m);
k = i3;
j = m;
case 0:
case 3:
case 14:
case 8:
case 1:
case 2:
case 4:
case 5:
case 6:
for (;;)
{
i = n + 1;
m = j;
i3 = k;
break;
n = i + 1;
j = m;
k = i3;
continue;
j = m - 3;
k = i3 - 3;
n = i;
continue;
((Label)localObject1).position = (i2 + m);
j = m;
n = i;
k = i3;
continue;
k = 3 - (i2 + m) & 0x3;
j = m + k;
k = i3 + k;
n = i;
continue;
j = ((Label)localObject1).position - (i2 + m);
if ((short)j != j) {
break label870;
}
this.fixup_offsets[i] = (i2 << 4 | 0x7);
j = m;
n = i;
k = i3;
}
if (i1 == 6)
{
j = 5;
k = m + j;
if (i1 != 6) {
break label918;
}
}
for (j = 5;; j = 2)
{
m = i3 + j;
j = k;
n = i;
k = m;
break;
j = 2;
break label879;
}
}
if (localObject1 != null) {
break label981;
}
}
arrayOfByte = new byte[i3];
i4 = -1;
m = 0;
k = fixupOffset(0);
localObject2 = null;
j = 0;
i = 0;
while (j < k)
{
arrayOfByte[i] = this.code[j];
j += 1;
i += 1;
}
label981:
i = ((Label)localObject1).first_fixup;
m = i2 + m - fixupOffset(i);
}
n = this.fixup_offsets[m] & 0xF;
Label localLabel = this.fixup_labels[m];
localObject1 = localObject2;
if (localObject2 != null)
{
localObject1 = localObject2;
if (((Label)localObject2).position < i)
{
this.stackMap.emitStackMapEntry((Label)localObject2, this);
localObject1 = null;
}
}
if ((localObject1 != null) && (((Label)localObject1).position > i)) {
throw new Error("labels out of order");
}
int i5;
switch (n)
{
case 3:
case 10:
case 12:
case 13:
default:
throw new Error("unexpected fixup");
case 0:
i5 = i4;
localObject2 = localObject1;
k = j;
j = i;
}
for (;;)
{
label1184:
m += 1;
i1 = fixupOffset(m);
n = k;
i = j;
k = i1;
j = n;
i4 = i5;
break;
if ((this.stackMap != null) && (localLabel != null) && (localLabel.stackTypes != null) && (localLabel.needsStackMapEntry))
{
localObject2 = mergeLabels((Label)localObject1, localLabel);
k = j;
j = i;
i5 = i4;
continue;
k = j + 3;
j = i;
localObject2 = localObject1;
i5 = i4;
continue;
k = localLabel.position - i;
n = i + 1;
arrayOfByte[i] = this.code[j];
i1 = n + 1;
arrayOfByte[n] = ((byte)(k >> 8));
i = i1 + 1;
arrayOfByte[i1] = ((byte)(k & 0xFF));
k = j + 3;
j = i;
localObject2 = localObject1;
i5 = i4;
continue;
k = localLabel.position - i;
byte b = this.code[j];
if (n == 6)
{
b = invert_opcode(b);
n = i + 1;
arrayOfByte[i] = b;
i1 = n + 1;
arrayOfByte[n] = 0;
i = i1 + 1;
arrayOfByte[i1] = 8;
}
for (b = -56;; b = (byte)(b + 33))
{
n = i + 1;
arrayOfByte[i] = b;
i = n + 1;
arrayOfByte[n] = ((byte)(k >> 24));
n = i + 1;
arrayOfByte[i] = ((byte)(k >> 16));
i = n + 1;
arrayOfByte[n] = ((byte)(k >> 8));
arrayOfByte[i] = ((byte)(k & 0xFF));
k = j + 3;
j = i + 1;
localObject2 = localObject1;
i5 = i4;
break;
}
k = 3 - i & 0x3;
localObject2 = this.code;
i1 = j + 1;
arrayOfByte[i] = localObject2[j];
j = i + 1;
for (;;)
{
k -= 1;
if (k < 0) {
break;
}
arrayOfByte[j] = 0;
j += 1;
}
label1578:
m = this.fixup_labels[i2].position - i;
n = k + 1;
arrayOfByte[k] = ((byte)(m >> 24));
k = n + 1;
arrayOfByte[n] = ((byte)(m >> 16));
n = k + 1;
arrayOfByte[k] = ((byte)(m >> 8));
arrayOfByte[n] = ((byte)(m & 0xFF));
i1 = j + 4;
n += 1;
for (;;)
{
j = n;
m = i2;
k = i1;
localObject2 = localObject1;
i5 = i4;
if (i2 >= this.fixup_count) {
break label1184;
}
j = n;
m = i2;
k = i1;
localObject2 = localObject1;
i5 = i4;
if (fixupKind(i2 + 1) != 3) {
break label1184;
}
i2 += 1;
m = fixupOffset(i2);
j = i1;
k = n;
while (j < m)
{
arrayOfByte[k] = this.code[j];
j += 1;
k += 1;
}
break label1578;
localLabel = this.fixup_labels[(m + 2)];
k = fixupOffset(m + 1);
localObject2 = localObject1;
if (this.stackMap != null) {
localObject2 = mergeLabels((Label)localObject1, localLabel);
}
addHandler(this.fixup_labels[m].position, this.fixup_labels[(m + 1)].position, i, k);
m += 2;
k = j;
j = i;
i5 = i4;
break label1184;
if (this.lines == null) {
this.lines = new LineNumbersAttr(this);
}
m += 1;
i5 = fixupOffset(m);
if (i5 != i4) {
this.lines.put(i5, i);
}
k = j;
j = i;
localObject2 = localObject1;
break label1184;
if (localLabel == null)
{
if (i3 != i) {
throw new Error("PC confusion new_pc:" + i + " new_size:" + i3);
}
}
else
{
m = localLabel.first_fixup;
j = fixupOffset(m);
k = j;
if (localLabel.position == i) {
break label2042;
}
throw new Error("bad pc");
}
this.PC = i3;
this.code = arrayOfByte;
this.fixup_count = 0;
this.fixup_labels = null;
this.fixup_offsets = null;
return;
label2042:
localObject2 = localObject1;
break;
n = j;
i2 = m;
}
}
else
{
k = j;
j = i;
localObject2 = localObject1;
i5 = i4;
}
}
}
public Scope pushScope()
{
Scope localScope = new Scope();
if (this.locals == null) {
this.locals = new LocalVarsAttr(getMethod());
}
enterScope(localScope);
if (this.locals.parameter_scope == null) {
this.locals.parameter_scope = localScope;
}
return localScope;
}
public final void pushType(Type paramType)
{
if (paramType.size == 0) {
throw new Error("pushing void type onto stack");
}
if ((this.stack_types == null) || (this.stack_types.length == 0)) {
this.stack_types = new Type[20];
}
for (;;)
{
if (paramType.size == 8)
{
arrayOfType = this.stack_types;
i = this.SP;
this.SP = (i + 1);
arrayOfType[i] = Type.voidType;
}
Type[] arrayOfType = this.stack_types;
int i = this.SP;
this.SP = (i + 1);
arrayOfType[i] = paramType;
if (this.SP > this.max_stack) {
this.max_stack = this.SP;
}
return;
if (this.SP + 1 >= this.stack_types.length)
{
arrayOfType = new Type[this.stack_types.length * 2];
System.arraycopy(this.stack_types, 0, arrayOfType, 0, this.SP);
this.stack_types = arrayOfType;
}
}
}
public final void put1(int paramInt)
{
byte[] arrayOfByte = this.code;
int i = this.PC;
this.PC = (i + 1);
arrayOfByte[i] = ((byte)paramInt);
this.unreachable_here = false;
}
public final void put2(int paramInt)
{
byte[] arrayOfByte = this.code;
int i = this.PC;
this.PC = (i + 1);
arrayOfByte[i] = ((byte)(paramInt >> 8));
arrayOfByte = this.code;
i = this.PC;
this.PC = (i + 1);
arrayOfByte[i] = ((byte)paramInt);
this.unreachable_here = false;
}
public final void put4(int paramInt)
{
byte[] arrayOfByte = this.code;
int i = this.PC;
this.PC = (i + 1);
arrayOfByte[i] = ((byte)(paramInt >> 24));
arrayOfByte = this.code;
i = this.PC;
this.PC = (i + 1);
arrayOfByte[i] = ((byte)(paramInt >> 16));
arrayOfByte = this.code;
i = this.PC;
this.PC = (i + 1);
arrayOfByte[i] = ((byte)(paramInt >> 8));
arrayOfByte = this.code;
i = this.PC;
this.PC = (i + 1);
arrayOfByte[i] = ((byte)paramInt);
this.unreachable_here = false;
}
public final void putIndex2(CpoolEntry paramCpoolEntry)
{
put2(paramCpoolEntry.index);
}
public final void putLineNumber(int paramInt)
{
int i = paramInt;
if (this.sourceDbgExt != null) {
i = this.sourceDbgExt.fixLine(paramInt);
}
fixupAdd(14, null);
fixupAdd(15, i, null);
}
public final void putLineNumber(String paramString, int paramInt)
{
if (paramString != null) {
getMethod().classfile.setSourceFile(paramString);
}
putLineNumber(paramInt);
}
public final boolean reachableHere()
{
return !this.unreachable_here;
}
public final void reserve(int paramInt)
{
if (this.code == null) {
this.code = new byte[paramInt + 100];
}
while (this.PC + paramInt <= this.code.length) {
return;
}
byte[] arrayOfByte = new byte[this.code.length * 2 + paramInt];
System.arraycopy(this.code, 0, arrayOfByte, 0, this.PC);
this.code = arrayOfByte;
}
public final void setAttributes(Attribute paramAttribute)
{
this.attributes = paramAttribute;
}
public void setCode(byte[] paramArrayOfByte)
{
this.code = paramArrayOfByte;
this.PC = paramArrayOfByte.length;
}
public void setCodeLength(int paramInt)
{
this.PC = paramInt;
}
public void setMaxLocals(int paramInt)
{
this.max_locals = paramInt;
}
public void setMaxStack(int paramInt)
{
this.max_stack = paramInt;
}
public final void setReachable(boolean paramBoolean)
{
if (!paramBoolean) {}
for (paramBoolean = true;; paramBoolean = false)
{
this.unreachable_here = paramBoolean;
return;
}
}
public final void setTypes(Label paramLabel)
{
setTypes(paramLabel.localTypes, paramLabel.stackTypes);
}
public final void setTypes(Type[] paramArrayOfType1, Type[] paramArrayOfType2)
{
int j = paramArrayOfType2.length;
int i = paramArrayOfType1.length;
if (this.local_types != null)
{
if (i > 0) {
System.arraycopy(paramArrayOfType1, 0, this.local_types, 0, i);
}
while (i < this.local_types.length)
{
this.local_types[i] = null;
i += 1;
}
}
if ((this.stack_types == null) || (j > this.stack_types.length)) {
this.stack_types = new Type[j];
}
for (;;)
{
System.arraycopy(paramArrayOfType2, 0, this.stack_types, 0, j);
this.SP = j;
return;
i = j;
while (i < this.stack_types.length)
{
this.stack_types[i] = null;
i += 1;
}
}
}
public final void setUnreachable()
{
this.unreachable_here = true;
}
public ExitableBlock startExitableBlock(Type paramType, boolean paramBoolean)
{
paramType = new ExitableBlock(paramType, this, paramBoolean);
paramType.outer = this.currentExitableBlock;
this.currentExitableBlock = paramType;
return paramType;
}
public SwitchState startSwitch()
{
SwitchState localSwitchState = new SwitchState(this);
localSwitchState.switchValuePushed(this);
return localSwitchState;
}
public final Type topType()
{
return this.stack_types[(this.SP - 1)];
}
boolean useJsr()
{
return (this.flags & 0x2) == 0;
}
public void write(DataOutputStream paramDataOutputStream)
throws IOException
{
paramDataOutputStream.writeShort(this.max_stack);
paramDataOutputStream.writeShort(this.max_locals);
paramDataOutputStream.writeInt(this.PC);
paramDataOutputStream.write(this.code, 0, this.PC);
paramDataOutputStream.writeShort(this.exception_table_length);
int j = this.exception_table_length;
int i = 0;
for (;;)
{
j -= 1;
if (j < 0) {
break;
}
paramDataOutputStream.writeShort(this.exception_table[i]);
paramDataOutputStream.writeShort(this.exception_table[(i + 1)]);
paramDataOutputStream.writeShort(this.exception_table[(i + 2)]);
paramDataOutputStream.writeShort(this.exception_table[(i + 3)]);
i += 4;
}
Attribute.writeAll(this, paramDataOutputStream);
}
}
/* Location: C:\Users\Mohamed\Downloads\dex2jar-2.0\dex2jar-2.0\classes-dex2jar.jar!\gnu\bytecode\CodeAttr.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | UTF-8 | Java | 92,913 | java | CodeAttr.java | Java | [
{
"context": "ream);\n }\n}\n\n\n/* Location: C:\\Users\\Mohamed\\Downloads\\dex2jar-2.0\\dex2jar-2.0\\classes-dex2jar",
"end": 92759,
"score": 0.9487109184265137,
"start": 92752,
"tag": "NAME",
"value": "Mohamed"
}
] | null | [] | package gnu.bytecode;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Array;
public class CodeAttr
extends Attribute
implements AttrContainer
{
public static final int DONT_USE_JSR = 2;
static final int FIXUP_CASE = 3;
static final int FIXUP_DEFINE = 1;
static final int FIXUP_DELETE3 = 8;
static final int FIXUP_GOTO = 4;
static final int FIXUP_JSR = 5;
static final int FIXUP_LINE_NUMBER = 15;
static final int FIXUP_LINE_PC = 14;
static final int FIXUP_MOVE = 9;
static final int FIXUP_MOVE_TO_END = 10;
static final int FIXUP_NONE = 0;
static final int FIXUP_SWITCH = 2;
static final int FIXUP_TRANSFER = 6;
static final int FIXUP_TRANSFER2 = 7;
static final int FIXUP_TRY = 11;
static final int FIXUP_TRY_END = 12;
static final int FIXUP_TRY_HANDLER = 13;
public static final int GENERATE_STACK_MAP_TABLE = 1;
public static boolean instructionLineMode = false;
int PC;
int SP;
Attribute attributes;
byte[] code;
ExitableBlock currentExitableBlock;
short[] exception_table;
int exception_table_length;
int exitableBlockLevel;
int fixup_count;
Label[] fixup_labels;
int[] fixup_offsets;
int flags;
IfState if_stack;
LineNumbersAttr lines;
Type[] local_types;
public LocalVarsAttr locals;
private int max_locals;
private int max_stack;
Label previousLabel;
SourceDebugExtAttr sourceDbgExt;
public StackMapTableAttr stackMap;
public Type[] stack_types;
TryState try_stack;
private boolean unreachable_here;
boolean[] varsSetInCurrentBlock;
public CodeAttr(Method paramMethod)
{
super("Code");
addToFrontOf(paramMethod);
paramMethod.code = this;
if (paramMethod.getDeclaringClass().getClassfileMajorVersion() >= 50) {
this.flags |= 0x3;
}
}
private int adjustTypedOp(char paramChar)
{
switch (paramChar)
{
default:
return 4;
case 'I':
return 0;
case 'J':
return 1;
case 'F':
return 2;
case 'D':
return 3;
case 'B':
case 'Z':
return 5;
case 'C':
return 6;
}
return 7;
}
private int adjustTypedOp(Type paramType)
{
return adjustTypedOp(paramType.getSignature().charAt(0));
}
public static final String calculateSplit(String paramString)
{
int i2 = paramString.length();
StringBuffer localStringBuffer = new StringBuffer(20);
int m = 0;
int j = 0;
int i = 0;
if (i < i2)
{
int k = paramString.charAt(i);
if (k >= 2048) {
k = 3;
}
for (;;)
{
int i1 = j;
int n = m;
if (j + k > 65535)
{
localStringBuffer.append((char)(i - m));
n = i;
i1 = 0;
}
j = i1 + k;
i += 1;
m = n;
break;
if ((k >= 128) || (k == 0)) {
k = 2;
} else {
k = 1;
}
}
}
localStringBuffer.append((char)(i2 - m));
return localStringBuffer.toString();
}
public static boolean castNeeded(Type paramType1, Type paramType2)
{
Type localType1 = paramType1;
Type localType2 = paramType2;
if ((paramType1 instanceof UninitializedType))
{
localType1 = ((UninitializedType)paramType1).getImplementationType();
localType2 = paramType2;
}
for (;;)
{
if (localType1 == localType2) {
return false;
}
if (((localType2 instanceof ClassType)) && ((localType1 instanceof ClassType)) && (((ClassType)localType1).isSubclass((ClassType)localType2))) {
return false;
}
if ((!(localType2 instanceof ArrayType)) || (!(localType1 instanceof ArrayType))) {
break;
}
localType2 = ((ArrayType)localType2).getComponentType();
localType1 = ((ArrayType)localType1).getComponentType();
}
return true;
}
private void emitBinop(int paramInt)
{
Type localType1 = popType().promote();
Type localType2 = popType();
Type localType3 = localType2.promote();
if ((localType3 != localType1) || (!(localType3 instanceof PrimType))) {
throw new Error("non-matching or bad types in binary operation");
}
emitTypedOp(paramInt, localType3);
pushType(localType2);
}
private void emitBinop(int paramInt, char paramChar)
{
popType();
popType();
emitTypedOp(paramInt, paramChar);
pushType(Type.signatureToPrimitive(paramChar));
}
private void emitCheckcast(Type paramType, int paramInt)
{
reserve(3);
popType();
put1(paramInt);
if ((paramType instanceof ObjectType))
{
putIndex2(getConstants().addClass((ObjectType)paramType));
return;
}
throw new Error("unimplemented type " + paramType + " in emitCheckcast/emitInstanceof");
}
private final void emitFieldop(Field paramField, int paramInt)
{
reserve(3);
put1(paramInt);
putIndex2(getConstants().addFieldRef(paramField));
}
private void emitShift(int paramInt)
{
Type localType1 = popType().promote();
Type localType2 = popType();
Type localType3 = localType2.promote();
if ((localType3 != Type.intType) && (localType3 != Type.longType)) {
throw new Error("the value shifted must be an int or a long");
}
if (localType1 != Type.intType) {
throw new Error("the amount of shift must be an int");
}
emitTypedOp(paramInt, localType3);
pushType(localType2);
}
private void emitTryEnd(boolean paramBoolean)
{
if (this.try_stack.tryClauseDone) {
return;
}
this.try_stack.tryClauseDone = true;
if (this.try_stack.finally_subr != null) {
this.try_stack.exception = addLocal(Type.javalangThrowableType);
}
gotoFinallyOrEnd(paramBoolean);
this.try_stack.end_try = getLabel();
}
private void emitTypedOp(int paramInt, char paramChar)
{
reserve(1);
put1(adjustTypedOp(paramChar) + paramInt);
}
private void emitTypedOp(int paramInt, Type paramType)
{
reserve(1);
put1(adjustTypedOp(paramType) + paramInt);
}
private final int fixupKind(int paramInt)
{
return this.fixup_offsets[paramInt] & 0xF;
}
private final int fixupOffset(int paramInt)
{
return this.fixup_offsets[paramInt] >> 4;
}
private void gotoFinallyOrEnd(boolean paramBoolean)
{
if (reachableHere())
{
if (this.try_stack.saved_result != null) {
emitStore(this.try_stack.saved_result);
}
if (this.try_stack.end_label == null) {
this.try_stack.end_label = new Label();
}
if ((this.try_stack.finally_subr != null) && (!useJsr())) {
break label102;
}
if (this.try_stack.finally_subr != null) {
emitJsr(this.try_stack.finally_subr);
}
emitGoto(this.try_stack.end_label);
}
label102:
do
{
return;
if (this.try_stack.exitCases != null) {
emitPushInt(0);
}
emitPushNull();
} while (paramBoolean);
emitGoto(this.try_stack.finally_subr);
}
private Label mergeLabels(Label paramLabel1, Label paramLabel2)
{
if (paramLabel1 != null) {
paramLabel2.setTypes(paramLabel1);
}
return paramLabel2;
}
private void print(String paramString, int paramInt, PrintWriter paramPrintWriter)
{
int i = 0;
int j = -1;
while (paramInt >= 0)
{
i = j + 1;
j = paramString.indexOf(';', i);
paramInt -= 1;
}
paramPrintWriter.write(paramString, i, j - i);
}
private int readInt(int paramInt)
{
return readUnsignedShort(paramInt) << 16 | readUnsignedShort(paramInt + 2);
}
private int readUnsignedShort(int paramInt)
{
return (this.code[paramInt] & 0xFF) << 8 | this.code[(paramInt + 1)] & 0xFF;
}
private int words(Type[] paramArrayOfType)
{
int i = 0;
int j = paramArrayOfType.length;
for (;;)
{
j -= 1;
if (j < 0) {
break;
}
if (paramArrayOfType[j].size > 4) {
i += 2;
} else {
i += 1;
}
}
return i;
}
public void addHandler(int paramInt1, int paramInt2, int paramInt3, int paramInt4)
{
int j = this.exception_table_length * 4;
if (this.exception_table == null) {
this.exception_table = new short[20];
}
for (;;)
{
short[] arrayOfShort = this.exception_table;
int i = j + 1;
arrayOfShort[j] = ((short)paramInt1);
arrayOfShort = this.exception_table;
paramInt1 = i + 1;
arrayOfShort[i] = ((short)paramInt2);
arrayOfShort = this.exception_table;
paramInt2 = paramInt1 + 1;
arrayOfShort[paramInt1] = ((short)paramInt3);
this.exception_table[paramInt2] = ((short)paramInt4);
this.exception_table_length += 1;
return;
if (this.exception_table.length <= j)
{
arrayOfShort = new short[this.exception_table.length * 2];
System.arraycopy(this.exception_table, 0, arrayOfShort, 0, j);
this.exception_table = arrayOfShort;
}
}
}
public void addHandler(Label paramLabel1, Label paramLabel2, ClassType paramClassType)
{
ConstantPool localConstantPool = getConstants();
int i;
if (paramClassType == null)
{
i = 0;
fixupAdd(11, paramLabel1);
fixupAdd(12, i, paramLabel2);
paramLabel2 = new Label();
paramLabel2.localTypes = paramLabel1.localTypes;
paramLabel2.stackTypes = new Type[1];
if (paramClassType != null) {
break label96;
}
}
label96:
for (paramLabel1 = Type.javalangThrowableType;; paramLabel1 = paramClassType)
{
paramLabel2.stackTypes[0] = paramLabel1;
setTypes(paramLabel2);
fixupAdd(13, 0, paramLabel2);
return;
i = localConstantPool.addClass(paramClassType).index;
break;
}
}
public Variable addLocal(Type paramType)
{
return this.locals.current_scope.addVariable(this, paramType, null);
}
public Variable addLocal(Type paramType, String paramString)
{
return this.locals.current_scope.addVariable(this, paramType, paramString);
}
public void addParamLocals()
{
Method localMethod = getMethod();
if ((localMethod.access_flags & 0x8) == 0) {
addLocal(localMethod.classfile).setParameter(true);
}
int j = localMethod.arg_types.length;
int i = 0;
while (i < j)
{
addLocal(localMethod.arg_types[i]).setParameter(true);
i += 1;
}
}
public void assignConstants(ClassType paramClassType)
{
if ((this.locals != null) && (this.locals.container == null) && (!this.locals.isEmpty())) {
this.locals.addToFrontOf(this);
}
processFixups();
if ((this.stackMap != null) && (this.stackMap.numEntries > 0)) {
this.stackMap.addToFrontOf(this);
}
if (instructionLineMode)
{
if (this.lines == null) {
this.lines = new LineNumbersAttr(this);
}
this.lines.linenumber_count = 0;
int j = getCodeLength();
int i = 0;
while (i < j)
{
this.lines.put(i, i);
i += 1;
}
}
super.assignConstants(paramClassType);
Attribute.assignConstants(this, paramClassType);
}
public int beginFragment(Label paramLabel)
{
return beginFragment(new Label(), paramLabel);
}
public int beginFragment(Label paramLabel1, Label paramLabel2)
{
int i = this.fixup_count;
fixupAdd(10, paramLabel2);
paramLabel1.define(this);
return i;
}
public void disAssemble(ClassTypeWriter paramClassTypeWriter, int paramInt1, int paramInt2)
{
int i = 0;
int k = paramInt1;
int m;
Object localObject;
int n;
int j;
if (k < paramInt2)
{
paramInt1 = k + 1;
m = this.code[k] & 0xFF;
localObject = Integer.toString(k);
n = 0;
j = ((String)localObject).length();
for (;;)
{
j += 1;
if (j > 3) {
break;
}
paramClassTypeWriter.print(' ');
}
paramClassTypeWriter.print((String)localObject);
paramClassTypeWriter.print(": ");
if (m < 120) {
if (m < 87) {
if (m < 3)
{
print("nop;aconst_null;iconst_m1;", m, paramClassTypeWriter);
j = n;
label115:
if (j <= 0) {
break label2030;
}
if (j != 1) {
break label2015;
}
localObject = this.code;
k = paramInt1 + 1;
j = localObject[paramInt1] & 0xFF;
paramInt1 = k;
label150:
paramClassTypeWriter.printConstantOperand(j);
}
}
}
}
label399:
label416:
label500:
label543:
label2008:
label2015:
label2030:
for (;;)
{
paramClassTypeWriter.println();
k = paramInt1;
break;
if (m < 9)
{
paramClassTypeWriter.print("iconst_");
paramClassTypeWriter.print(m - 3);
j = n;
break label115;
}
char c;
if (m < 16)
{
if (m < 11)
{
c = 'l';
j = m - 9;
}
for (;;)
{
paramClassTypeWriter.print(c);
paramClassTypeWriter.print("const_");
paramClassTypeWriter.print(j);
j = n;
break;
if (m < 14)
{
c = 'f';
j = m - 11;
}
else
{
c = 'd';
j = m - 14;
}
}
}
if (m < 21)
{
if (m < 18)
{
print("bipush ;sipush ;", m - 16, paramClassTypeWriter);
if (m == 16)
{
j = this.code[paramInt1];
paramInt1 += 1;
}
for (;;)
{
paramClassTypeWriter.print(j);
j = n;
break;
j = (short)readUnsignedShort(paramInt1);
paramInt1 += 2;
}
}
if (m == 18) {}
for (j = 1;; j = 2)
{
print("ldc;ldc_w;ldc2_w;", m - 18, paramClassTypeWriter);
break;
}
}
if (m < 54)
{
localObject = "load";
if (m >= 26) {
break label500;
}
j = -1;
k = m - 21;
paramClassTypeWriter.print("ilfdabcs".charAt(k));
if (j == -2) {
paramClassTypeWriter.write(97);
}
paramClassTypeWriter.print((String)localObject);
if (j < 0) {
break label543;
}
paramClassTypeWriter.write(95);
paramClassTypeWriter.print(j);
k = i;
m = paramInt1;
}
do
{
paramInt1 = m;
j = n;
i = k;
break;
localObject = "store";
m -= 33;
break label399;
if (m < 46)
{
k = m - 26;
j = k % 4;
k >>= 2;
break label416;
}
j = -2;
k = m - 46;
break label416;
m = paramInt1;
k = i;
} while (j != -1);
if (i != 0)
{
i = readUnsignedShort(paramInt1);
m = paramInt1 + 2;
}
for (paramInt1 = i;; paramInt1 = i)
{
k = 0;
paramClassTypeWriter.print(' ');
paramClassTypeWriter.print(paramInt1);
break;
i = this.code[paramInt1] & 0xFF;
m = paramInt1 + 1;
}
if (m < 96)
{
print("pop;pop2;dup;dup_x1;dup_x2;dup2;dup2_x1;dup2_x2;swap;", m - 87, paramClassTypeWriter);
j = n;
break label115;
}
paramClassTypeWriter.print("ilfda".charAt((m - 96) % 4));
print("add;sub;mul;div;rem;neg;", m - 96 >> 2, paramClassTypeWriter);
j = n;
break label115;
if (m < 170)
{
if (m < 132)
{
if ((m & 0x1) == 0) {}
for (c = 'i';; c = 'l')
{
paramClassTypeWriter.print(c);
print("shl;shr;ushr;and;or;xor;", m - 120 >> 1, paramClassTypeWriter);
j = n;
break;
}
}
if (m == 132)
{
paramClassTypeWriter.print("iinc");
if (i == 0)
{
localObject = this.code;
j = paramInt1 + 1;
k = localObject[paramInt1] & 0xFF;
localObject = this.code;
paramInt1 = j + 1;
j = localObject[j];
}
for (;;)
{
paramClassTypeWriter.print(' ');
paramClassTypeWriter.print(k);
paramClassTypeWriter.print(' ');
paramClassTypeWriter.print(j);
j = n;
break;
k = readUnsignedShort(paramInt1);
paramInt1 += 2;
j = (short)readUnsignedShort(paramInt1);
paramInt1 += 2;
i = 0;
}
}
if (m < 148)
{
paramClassTypeWriter.print("ilfdi".charAt((m - 133) / 3));
paramClassTypeWriter.print('2');
paramClassTypeWriter.print("lfdifdildilfbcs".charAt(m - 133));
j = n;
break label115;
}
if (m < 153)
{
print("lcmp;fcmpl;fcmpg;dcmpl;dcmpg;", m - 148, paramClassTypeWriter);
j = n;
break label115;
}
if (m < 169)
{
if (m < 159)
{
paramClassTypeWriter.print("if");
print("eq;ne;lt;ge;gt;le;", m - 153, paramClassTypeWriter);
}
for (;;)
{
j = (short)readUnsignedShort(paramInt1);
paramClassTypeWriter.print(' ');
paramClassTypeWriter.print(k + j);
paramInt1 += 2;
j = n;
break;
if (m < 167)
{
if (m < 165) {
paramClassTypeWriter.print("if_icmp");
}
for (;;)
{
print("eq;ne;lt;ge;gt;le;", m - 159, paramClassTypeWriter);
break;
paramClassTypeWriter.print("if_acmp");
m -= 6;
}
}
print("goto;jsr;", m - 167, paramClassTypeWriter);
}
}
paramClassTypeWriter.print("ret ");
if (i != 0) {
i = readUnsignedShort(paramInt1) + 2;
}
for (;;)
{
k = 0;
paramClassTypeWriter.print(i);
j = n;
i = k;
break;
i = this.code[paramInt1] & 0xFF;
paramInt1 += 1;
}
}
if (m < 172)
{
j = paramInt1;
if (this.fixup_count <= 0) {
j = paramInt1 + 3 & 0xFFFFFFFC;
}
int i2 = readInt(j);
paramInt1 = j + 4;
int i1;
if (m == 170)
{
paramClassTypeWriter.print("tableswitch");
m = readInt(paramInt1);
paramInt1 += 4;
i1 = readInt(paramInt1);
paramInt1 += 4;
paramClassTypeWriter.print(" low: ");
paramClassTypeWriter.print(m);
paramClassTypeWriter.print(" high: ");
paramClassTypeWriter.print(i1);
paramClassTypeWriter.print(" default: ");
paramClassTypeWriter.print(k + i2);
for (;;)
{
j = paramInt1;
if (m > i1) {
break;
}
j = readInt(paramInt1);
paramInt1 += 4;
paramClassTypeWriter.println();
paramClassTypeWriter.print(" ");
paramClassTypeWriter.print(m);
paramClassTypeWriter.print(": ");
paramClassTypeWriter.print(k + j);
m += 1;
}
}
paramClassTypeWriter.print("lookupswitch");
j = readInt(paramInt1);
paramInt1 += 4;
paramClassTypeWriter.print(" npairs: ");
paramClassTypeWriter.print(j);
paramClassTypeWriter.print(" default: ");
paramClassTypeWriter.print(k + i2);
for (;;)
{
m = j - 1;
j = paramInt1;
if (m < 0) {
break;
}
j = readInt(paramInt1);
paramInt1 += 4;
i1 = readInt(paramInt1);
paramInt1 += 4;
paramClassTypeWriter.println();
paramClassTypeWriter.print(" ");
paramClassTypeWriter.print(j);
paramClassTypeWriter.print(": ");
paramClassTypeWriter.print(k + i1);
j = m;
}
paramInt1 = j;
j = n;
break label115;
}
if (m < 178)
{
if (m < 177) {
paramClassTypeWriter.print("ilfda".charAt(m - 172));
}
paramClassTypeWriter.print("return");
j = n;
break label115;
}
if (m < 182)
{
print("getstatic;putstatic;getfield;putfield;", m - 178, paramClassTypeWriter);
j = 2;
break label115;
}
if (m < 185)
{
paramClassTypeWriter.print("invoke");
print("virtual;special;static;", m - 182, paramClassTypeWriter);
j = 2;
break label115;
}
if (m == 185)
{
paramClassTypeWriter.print("invokeinterface (");
j = readUnsignedShort(paramInt1);
paramInt1 += 2;
k = this.code[paramInt1];
paramClassTypeWriter.print((k & 0xFF) + " args)");
paramClassTypeWriter.printConstantOperand(j);
paramInt1 += 2;
j = n;
break label115;
}
if (m < 196)
{
print("186;new;newarray;anewarray;arraylength;athrow;checkcast;instanceof;monitorenter;monitorexit;", m - 186, paramClassTypeWriter);
if ((m == 187) || (m == 189) || (m == 192) || (m == 193))
{
j = 2;
break label115;
}
if (m != 188) {
break label2008;
}
localObject = this.code;
j = paramInt1 + 1;
paramInt1 = localObject[paramInt1];
paramClassTypeWriter.print(' ');
if ((paramInt1 >= 4) && (paramInt1 <= 11))
{
print("boolean;char;float;double;byte;short;int;long;", paramInt1 - 4, paramClassTypeWriter);
paramInt1 = j;
j = n;
break label115;
}
paramClassTypeWriter.print(paramInt1);
paramInt1 = j;
j = n;
break label115;
}
if (m == 196)
{
paramClassTypeWriter.print("wide");
i = 1;
j = n;
break label115;
}
if (m == 197)
{
paramClassTypeWriter.print("multianewarray");
j = readUnsignedShort(paramInt1);
k = paramInt1 + 2;
paramClassTypeWriter.printConstantOperand(j);
localObject = this.code;
paramInt1 = k + 1;
j = localObject[k];
paramClassTypeWriter.print(' ');
paramClassTypeWriter.print(j & 0xFF);
j = n;
break label115;
}
if (m < 200)
{
print("ifnull;ifnonnull;", m - 198, paramClassTypeWriter);
j = (short)readUnsignedShort(paramInt1);
paramClassTypeWriter.print(' ');
paramClassTypeWriter.print(k + j);
paramInt1 += 2;
j = n;
break label115;
}
if (m < 202)
{
print("goto_w;jsr_w;", m - 200, paramClassTypeWriter);
j = readInt(paramInt1);
paramClassTypeWriter.print(' ');
paramClassTypeWriter.print(k + j);
paramInt1 += 4;
j = n;
break label115;
}
paramClassTypeWriter.print(m);
j = n;
break label115;
j = readUnsignedShort(paramInt1);
paramInt1 += 2;
break label150;
return;
}
}
public final void emitAdd()
{
emitBinop(96);
}
public final void emitAdd(char paramChar)
{
emitBinop(96, paramChar);
}
public final void emitAdd(PrimType paramPrimType)
{
emitBinop(96, paramPrimType);
}
public final void emitAnd()
{
emitBinop(126);
}
public final void emitArrayLength()
{
if (!(popType() instanceof ArrayType)) {
throw new Error("non-array type in emitArrayLength");
}
reserve(1);
put1(190);
pushType(Type.intType);
}
public void emitArrayLoad()
{
popType();
Type localType = ((ArrayType)popType().getImplementationType()).getComponentType();
emitTypedOp(46, localType);
pushType(localType);
}
public void emitArrayLoad(Type paramType)
{
popType();
popType();
emitTypedOp(46, paramType);
pushType(paramType);
}
public void emitArrayStore()
{
popType();
popType();
emitTypedOp(79, ((ArrayType)popType().getImplementationType()).getComponentType());
}
public void emitArrayStore(Type paramType)
{
popType();
popType();
popType();
emitTypedOp(79, paramType);
}
public void emitBinop(int paramInt, Type paramType)
{
popType();
popType();
emitTypedOp(paramInt, paramType);
pushType(paramType);
}
public void emitCatchEnd()
{
gotoFinallyOrEnd(false);
this.try_stack.try_type = null;
}
public void emitCatchStart(Variable paramVariable)
{
emitTryEnd(false);
setTypes(this.try_stack.start_try.localTypes, Type.typeArray0);
if (this.try_stack.try_type != null) {
emitCatchEnd();
}
if (paramVariable == null) {}
for (ClassType localClassType = null;; localClassType = (ClassType)paramVariable.getType())
{
this.try_stack.try_type = localClassType;
addHandler(this.try_stack.start_try, this.try_stack.end_try, localClassType);
if (paramVariable != null) {
emitStore(paramVariable);
}
return;
}
}
public void emitCheckcast(Type paramType)
{
if (castNeeded(topType(), paramType))
{
emitCheckcast(paramType, 192);
pushType(paramType);
}
}
public final void emitConvert(Type paramType1, Type paramType2)
{
String str1 = paramType2.getSignature();
String str2 = paramType1.getSignature();
int k = -1;
int i;
int m;
if (str1.length() != 1)
{
i = k;
if (str2.length() != 1) {}
}
else
{
m = str1.charAt(0);
i = str2.charAt(0);
if (i == m) {}
int j;
do
{
return;
if (paramType1.size < 4) {
i = 73;
}
j = i;
if (paramType2.size < 4)
{
emitConvert(paramType1, Type.intType);
j = 73;
}
} while (j == m);
i = k;
switch (j)
{
default:
i = k;
}
}
while (i < 0)
{
throw new Error("unsupported CodeAttr.emitConvert");
switch (m)
{
default:
i = k;
break;
case 66:
i = 145;
break;
case 67:
i = 146;
break;
case 83:
i = 147;
break;
case 74:
i = 133;
break;
case 70:
i = 134;
break;
case 68:
i = 135;
continue;
switch (m)
{
case 69:
case 71:
case 72:
default:
i = k;
break;
case 68:
i = 138;
break;
case 73:
i = 136;
break;
case 70:
i = 137;
continue;
switch (m)
{
default:
i = k;
break;
case 68:
i = 141;
break;
case 73:
i = 139;
break;
case 74:
i = 140;
continue;
switch (m)
{
case 71:
case 72:
default:
i = k;
break;
case 70:
i = 144;
break;
case 73:
i = 142;
break;
case 74:
i = 143;
}
break;
}
break;
}
break;
}
}
reserve(1);
popType();
put1(i);
pushType(paramType2);
}
public final void emitDiv()
{
emitBinop(108);
}
public void emitDup()
{
reserve(1);
Type localType = topType();
if (localType.size <= 4) {}
for (int i = 89;; i = 92)
{
put1(i);
pushType(localType);
return;
}
}
public void emitDup(int paramInt)
{
emitDup(paramInt, 0);
}
public void emitDup(int paramInt1, int paramInt2)
{
if (paramInt1 == 0) {
return;
}
reserve(1);
Type localType3 = popType();
Object localObject2 = null;
if (paramInt1 == 1)
{
if (localType3.size > 4) {
throw new Error("using dup for 2-word type");
}
}
else
{
if (paramInt1 != 2) {
throw new Error("invalid size to emitDup");
}
if (localType3.size <= 4)
{
localObject1 = popType();
localObject2 = localObject1;
if (((Type)localObject1).size > 4) {
throw new Error("dup will cause invalid types on stack");
}
}
}
Object localObject1 = null;
Object localObject3 = null;
if (paramInt2 == 0)
{
if (paramInt1 == 1) {}
for (paramInt1 = 89;; paramInt1 = 92)
{
put1(paramInt1);
if (localObject2 != null) {
pushType((Type)localObject2);
}
pushType(localType3);
if (localObject3 != null) {
pushType((Type)localObject3);
}
if (localObject1 != null) {
pushType((Type)localObject1);
}
if (localObject2 != null) {
pushType((Type)localObject2);
}
pushType(localType3);
return;
}
}
Type localType1;
if (paramInt2 == 1)
{
if (paramInt1 == 1) {}
for (paramInt1 = 90;; paramInt1 = 93)
{
localType1 = popType();
localObject1 = localType1;
if (localType1.size <= 4) {
break;
}
throw new Error("dup will cause invalid types on stack");
}
}
if (paramInt2 == 2)
{
if (paramInt1 == 1) {}
for (paramInt2 = 91;; paramInt2 = 94)
{
localType1 = popType();
paramInt1 = paramInt2;
localObject1 = localType1;
if (localType1.size > 4) {
break;
}
Type localType2 = popType();
paramInt1 = paramInt2;
localObject1 = localType1;
localObject3 = localType2;
if (localType2.size <= 4) {
break;
}
throw new Error("dup will cause invalid types on stack");
}
}
throw new Error("emitDup: invalid offset");
}
public void emitDup(Type paramType)
{
if (paramType.size > 4) {}
for (int i = 2;; i = 1)
{
emitDup(i, 0);
return;
}
}
public void emitDupX()
{
reserve(1);
Type localType1 = popType();
Type localType2 = popType();
if (localType2.size <= 4)
{
if (localType1.size <= 4) {}
for (i = 90;; i = 93)
{
put1(i);
pushType(localType1);
pushType(localType2);
pushType(localType1);
return;
}
}
if (localType1.size <= 4) {}
for (int i = 91;; i = 94)
{
put1(i);
break;
}
}
public final void emitElse()
{
Label localLabel1 = this.if_stack.end_label;
if (reachableHere())
{
Label localLabel2 = new Label(this);
this.if_stack.end_label = localLabel2;
int i = this.SP - this.if_stack.start_stack_size;
this.if_stack.stack_growth = i;
if (i > 0)
{
this.if_stack.then_stacked_types = new Type[i];
System.arraycopy(this.stack_types, this.if_stack.start_stack_size, this.if_stack.then_stacked_types, 0, i);
emitGoto(localLabel2);
}
}
for (;;)
{
if (this.SP <= this.if_stack.start_stack_size) {
break label143;
}
popType();
continue;
this.if_stack.then_stacked_types = new Type[0];
break;
this.if_stack.end_label = null;
}
label143:
this.SP = this.if_stack.start_stack_size;
if (localLabel1 != null) {
localLabel1.define(this);
}
this.if_stack.doing_else = true;
}
public final void emitFi()
{
int j = 0;
int i;
int k;
if (!this.if_stack.doing_else)
{
i = j;
if (reachableHere())
{
i = j;
if (this.SP != this.if_stack.start_stack_size) {
throw new Error("at PC " + this.PC + " then clause grows stack with no else clause");
}
}
}
else
{
if (this.if_stack.then_stacked_types == null) {
break label258;
}
k = this.if_stack.start_stack_size + this.if_stack.stack_growth;
if (reachableHere()) {
break label194;
}
if (this.if_stack.stack_growth > 0) {
System.arraycopy(this.if_stack.then_stacked_types, 0, this.stack_types, this.if_stack.start_stack_size, this.if_stack.stack_growth);
}
this.SP = k;
i = j;
}
for (;;)
{
if (this.if_stack.end_label != null) {
this.if_stack.end_label.define(this);
}
if (i != 0) {
setUnreachable();
}
this.if_stack = this.if_stack.previous;
return;
label194:
i = j;
if (this.SP != k)
{
throw new Error("at PC " + this.PC + ": SP at end of 'then' was " + k + " while SP at end of 'else' was " + this.SP);
label258:
i = j;
if (this.unreachable_here) {
i = 1;
}
}
}
}
public void emitFinallyEnd()
{
if (useJsr()) {
emitRet(this.try_stack.finally_ret_addr);
}
for (;;)
{
popScope();
this.try_stack.finally_subr = null;
return;
if ((this.try_stack.end_label == null) && (this.try_stack.exitCases == null))
{
emitThrow();
}
else
{
emitStore(this.try_stack.exception);
emitLoad(this.try_stack.exception);
emitIfNotNull();
emitLoad(this.try_stack.exception);
emitThrow();
emitElse();
Object localObject = this.try_stack.exitCases;
if (localObject != null)
{
SwitchState localSwitchState = startSwitch();
if (localObject != null)
{
ExitableBlock localExitableBlock = ((ExitableBlock)localObject).nextCase;
((ExitableBlock)localObject).nextCase = null;
((ExitableBlock)localObject).currentTryState = null;
TryState localTryState = TryState.outerHandler(this.try_stack.previous, ((ExitableBlock)localObject).initialTryState);
if (localTryState == ((ExitableBlock)localObject).initialTryState) {
localSwitchState.addCaseGoto(((ExitableBlock)localObject).switchCase, this, ((ExitableBlock)localObject).endLabel);
}
for (;;)
{
localObject = localExitableBlock;
break;
localSwitchState.addCase(((ExitableBlock)localObject).switchCase, this);
((ExitableBlock)localObject).exit(localTryState);
}
}
this.try_stack.exitCases = null;
localSwitchState.addDefault(this);
localSwitchState.finish(this);
}
emitFi();
setUnreachable();
}
}
}
public void emitFinallyStart()
{
emitTryEnd(true);
if (this.try_stack.try_type != null) {
emitCatchEnd();
}
this.try_stack.end_try = getLabel();
pushScope();
if (useJsr())
{
this.SP = 0;
emitCatchStart(null);
emitStore(this.try_stack.exception);
emitJsr(this.try_stack.finally_subr);
emitLoad(this.try_stack.exception);
emitThrow();
}
for (;;)
{
this.try_stack.finally_subr.define(this);
if (useJsr())
{
ClassType localClassType = Type.objectType;
this.try_stack.finally_ret_addr = addLocal(localClassType);
pushType(localClassType);
emitStore(this.try_stack.finally_ret_addr);
}
return;
setUnreachable();
int i = beginFragment(new Label(this));
addHandler(this.try_stack.start_try, this.try_stack.end_try, Type.javalangThrowableType);
if (this.try_stack.saved_result != null) {
emitStoreDefaultValue(this.try_stack.saved_result);
}
if (this.try_stack.exitCases != null)
{
emitPushInt(-1);
emitSwap();
}
emitGoto(this.try_stack.finally_subr);
endFragment(i);
}
}
public final void emitGetField(Field paramField)
{
popType();
pushType(paramField.type);
emitFieldop(paramField, 180);
}
public final void emitGetStatic(Field paramField)
{
pushType(paramField.type);
emitFieldop(paramField, 178);
}
public final void emitGoto(Label paramLabel)
{
paramLabel.setTypes(this);
fixupAdd(4, paramLabel);
reserve(3);
put1(167);
this.PC += 2;
setUnreachable();
}
public final void emitGotoIfCompare1(Label paramLabel, int paramInt)
{
popType();
reserve(3);
emitTransfer(paramLabel, paramInt);
}
public final void emitGotoIfCompare2(Label paramLabel, int paramInt)
{
int i = 0;
if ((paramInt < 153) || (paramInt > 158)) {
throw new Error("emitGotoIfCompare2: logop must be one of ifeq...ifle");
}
Type localType1 = popType().promote();
Type localType2 = popType().promote();
reserve(4);
int j = localType2.getSignature().charAt(0);
int k = localType1.getSignature().charAt(0);
if ((paramInt == 155) || (paramInt == 158)) {
i = 1;
}
if ((j == 73) && (k == 73)) {
paramInt += 6;
}
for (;;)
{
emitTransfer(paramLabel, paramInt);
return;
if ((j == 74) && (k == 74))
{
put1(148);
}
else
{
if ((j == 70) && (k == 70))
{
if (i != 0) {}
for (i = 149;; i = 150)
{
put1(i);
break;
}
}
if ((j == 68) && (k == 68))
{
if (i != 0) {}
for (i = 151;; i = 152)
{
put1(i);
break;
}
}
if (((j != 76) && (j != 91)) || ((k != 76) && (k != 91)) || (paramInt > 154)) {
break;
}
paramInt += 12;
}
}
throw new Error("invalid types to emitGotoIfCompare2");
}
public final void emitGotoIfEq(Label paramLabel)
{
emitGotoIfCompare2(paramLabel, 153);
}
public final void emitGotoIfEq(Label paramLabel, boolean paramBoolean)
{
if (paramBoolean) {}
for (int i = 154;; i = 153)
{
emitGotoIfCompare2(paramLabel, i);
return;
}
}
public final void emitGotoIfGe(Label paramLabel)
{
emitGotoIfCompare2(paramLabel, 156);
}
public final void emitGotoIfGt(Label paramLabel)
{
emitGotoIfCompare2(paramLabel, 157);
}
public final void emitGotoIfIntEqZero(Label paramLabel)
{
emitGotoIfCompare1(paramLabel, 153);
}
public final void emitGotoIfIntGeZero(Label paramLabel)
{
emitGotoIfCompare1(paramLabel, 156);
}
public final void emitGotoIfIntGtZero(Label paramLabel)
{
emitGotoIfCompare1(paramLabel, 157);
}
public final void emitGotoIfIntLeZero(Label paramLabel)
{
emitGotoIfCompare1(paramLabel, 158);
}
public final void emitGotoIfIntLtZero(Label paramLabel)
{
emitGotoIfCompare1(paramLabel, 155);
}
public final void emitGotoIfIntNeZero(Label paramLabel)
{
emitGotoIfCompare1(paramLabel, 154);
}
public final void emitGotoIfLe(Label paramLabel)
{
emitGotoIfCompare2(paramLabel, 158);
}
public final void emitGotoIfLt(Label paramLabel)
{
emitGotoIfCompare2(paramLabel, 155);
}
public final void emitGotoIfNE(Label paramLabel)
{
emitGotoIfCompare2(paramLabel, 154);
}
public final void emitIOr()
{
emitBinop(128);
}
public final void emitIfCompare1(int paramInt)
{
IfState localIfState = new IfState(this);
if (popType().promote() != Type.intType) {
throw new Error("non-int type to emitIfCompare1");
}
reserve(3);
emitTransfer(localIfState.end_label, paramInt);
localIfState.start_stack_size = this.SP;
}
public final void emitIfEq()
{
IfState localIfState = new IfState(this);
emitGotoIfNE(localIfState.end_label);
localIfState.start_stack_size = this.SP;
}
public final void emitIfGe()
{
IfState localIfState = new IfState(this);
emitGotoIfLt(localIfState.end_label);
localIfState.start_stack_size = this.SP;
}
public final void emitIfGt()
{
IfState localIfState = new IfState(this);
emitGotoIfLe(localIfState.end_label);
localIfState.start_stack_size = this.SP;
}
public final void emitIfIntCompare(int paramInt)
{
IfState localIfState = new IfState(this);
popType();
popType();
reserve(3);
emitTransfer(localIfState.end_label, paramInt);
localIfState.start_stack_size = this.SP;
}
public final void emitIfIntEqZero()
{
emitIfCompare1(154);
}
public final void emitIfIntLEqZero()
{
emitIfCompare1(157);
}
public final void emitIfIntLt()
{
emitIfIntCompare(162);
}
public final void emitIfIntNotZero()
{
emitIfCompare1(153);
}
public final void emitIfLe()
{
IfState localIfState = new IfState(this);
emitGotoIfGt(localIfState.end_label);
localIfState.start_stack_size = this.SP;
}
public final void emitIfLt()
{
IfState localIfState = new IfState(this);
emitGotoIfGe(localIfState.end_label);
localIfState.start_stack_size = this.SP;
}
public final void emitIfNEq()
{
IfState localIfState = new IfState(this);
emitGotoIfEq(localIfState.end_label);
localIfState.start_stack_size = this.SP;
}
public final void emitIfNotNull()
{
emitIfRefCompare1(198);
}
public final void emitIfNull()
{
emitIfRefCompare1(199);
}
public final void emitIfRefCompare1(int paramInt)
{
IfState localIfState = new IfState(this);
if (!(popType() instanceof ObjectType)) {
throw new Error("non-ref type to emitIfRefCompare1");
}
reserve(3);
emitTransfer(localIfState.end_label, paramInt);
localIfState.start_stack_size = this.SP;
}
public final void emitIfThen()
{
new IfState(this, null);
}
public void emitInc(Variable paramVariable, short paramShort)
{
if (paramVariable.dead()) {
throw new Error("attempting to increment dead variable");
}
int j = paramVariable.offset;
if ((j < 0) || (!paramVariable.isSimple())) {
throw new Error("attempting to increment unassigned variable" + paramVariable.getName() + " simple:" + paramVariable.isSimple() + ", offset: " + j);
}
reserve(6);
if (paramVariable.getType().getImplementationType().promote() != Type.intType) {
throw new Error("attempting to increment non-int variable");
}
if ((j > 255) || (paramShort > 255) || (paramShort < 65280)) {}
for (int i = 1; i != 0; i = 0)
{
put1(196);
put1(132);
put2(j);
put2(paramShort);
return;
}
put1(132);
put1(j);
put1(paramShort);
}
public void emitInstanceof(Type paramType)
{
emitCheckcast(paramType, 193);
pushType(Type.booleanType);
}
public void emitInvoke(Method paramMethod)
{
int i;
if ((paramMethod.access_flags & 0x8) != 0) {
i = 184;
}
for (;;)
{
emitInvokeMethod(paramMethod, i);
return;
if (paramMethod.classfile.isInterface()) {
i = 185;
} else if ("<init>".equals(paramMethod.getName())) {
i = 183;
} else {
i = 182;
}
}
}
public void emitInvokeInterface(Method paramMethod)
{
emitInvokeMethod(paramMethod, 185);
}
public void emitInvokeMethod(Method paramMethod, int paramInt)
{
int m = 1;
int n;
label34:
int j;
if (paramInt == 185)
{
i = 5;
reserve(i);
n = paramMethod.arg_types.length;
if (paramInt != 184) {
break label112;
}
k = 1;
if ((paramInt != 183) || (!"<init>".equals(paramMethod.getName()))) {
break label118;
}
j = 1;
label57:
if ((paramMethod.access_flags & 0x8) == 0) {
break label124;
}
}
label112:
label118:
label124:
for (int i = m;; i = 0)
{
if (k == i) {
break label129;
}
throw new Error("emitInvokeXxx static flag mis-match method.flags=" + paramMethod.access_flags);
i = 3;
break;
k = 0;
break label34;
j = 0;
break label57;
}
label129:
i = n;
if (k == 0)
{
i = n;
if (j == 0) {
i = n + 1;
}
}
put1(paramInt);
putIndex2(getConstants().addMethodRef(paramMethod));
int k = i;
if (paramInt == 185)
{
put1(words(paramMethod.arg_types) + 1);
put1(0);
k = i;
}
Type localType;
do
{
k -= 1;
if (k < 0) {
break;
}
localType = popType();
} while (!(localType instanceof UninitializedType));
throw new Error("passing " + localType + " as parameter");
if (j != 0)
{
localType = popType();
if (!(localType instanceof UninitializedType)) {
throw new Error("calling <init> on already-initialized object");
}
ClassType localClassType = ((UninitializedType)localType).ctype;
paramInt = 0;
while (paramInt < this.SP)
{
if (this.stack_types[paramInt] == localType) {
this.stack_types[paramInt] = localClassType;
}
paramInt += 1;
}
Variable[] arrayOfVariable = this.locals.used;
if (arrayOfVariable == null) {
paramInt = 0;
}
for (;;)
{
i = paramInt - 1;
if (i < 0) {
break;
}
Variable localVariable = arrayOfVariable[i];
paramInt = i;
if (localVariable != null)
{
paramInt = i;
if (localVariable.type == localType)
{
localVariable.type = localClassType;
paramInt = i;
continue;
paramInt = arrayOfVariable.length;
}
}
}
if (this.local_types == null) {
paramInt = 0;
}
for (;;)
{
i = paramInt - 1;
if (i < 0) {
break;
}
paramInt = i;
if (this.local_types[i] == localType)
{
this.local_types[i] = localClassType;
paramInt = i;
continue;
paramInt = this.local_types.length;
}
}
}
if (paramMethod.return_type.size != 0) {
pushType(paramMethod.return_type);
}
}
public void emitInvokeSpecial(Method paramMethod)
{
emitInvokeMethod(paramMethod, 183);
}
public void emitInvokeStatic(Method paramMethod)
{
emitInvokeMethod(paramMethod, 184);
}
public void emitInvokeVirtual(Method paramMethod)
{
emitInvokeMethod(paramMethod, 182);
}
public final void emitJsr(Label paramLabel)
{
fixupAdd(5, paramLabel);
reserve(3);
put1(168);
this.PC += 2;
}
public final void emitLoad(Variable paramVariable)
{
if (paramVariable.dead()) {
throw new Error("attempting to push dead variable");
}
int i = paramVariable.offset;
if ((i < 0) || (!paramVariable.isSimple())) {
throw new Error("attempting to load from unassigned variable " + paramVariable + " simple:" + paramVariable.isSimple() + ", offset: " + i);
}
Type localType = paramVariable.getType().promote();
reserve(4);
int j = adjustTypedOp(localType);
if (i <= 3) {
put1(j * 4 + 26 + i);
}
for (;;)
{
pushType(paramVariable.getType());
return;
emitMaybeWide(j + 21, i);
}
}
void emitMaybeWide(int paramInt1, int paramInt2)
{
if (paramInt2 >= 256)
{
put1(196);
put1(paramInt1);
put2(paramInt2);
return;
}
put1(paramInt1);
put1(paramInt2);
}
public final void emitMonitorEnter()
{
popType();
reserve(1);
put1(194);
}
public final void emitMonitorExit()
{
popType();
reserve(1);
put1(195);
}
public final void emitMul()
{
emitBinop(104);
}
public void emitNew(ClassType paramClassType)
{
reserve(3);
Label localLabel = new Label(this);
localLabel.defineRaw(this);
put1(187);
putIndex2(getConstants().addClass(paramClassType));
pushType(new UninitializedType(paramClassType, localLabel));
}
void emitNewArray(int paramInt)
{
reserve(2);
put1(188);
put1(paramInt);
}
public void emitNewArray(Type paramType)
{
emitNewArray(paramType, 1);
}
public void emitNewArray(Type paramType, int paramInt)
{
if (popType().promote() != Type.intType) {
throw new Error("non-int dim. spec. in emitNewArray");
}
if ((paramType instanceof PrimType)) {
switch (paramType.getSignature().charAt(0))
{
default:
throw new Error("bad PrimType in emitNewArray");
case 'B':
paramInt = 8;
emitNewArray(paramInt);
}
}
for (;;)
{
pushType(new ArrayType(paramType));
return;
paramInt = 9;
break;
paramInt = 10;
break;
paramInt = 11;
break;
paramInt = 6;
break;
paramInt = 7;
break;
paramInt = 4;
break;
paramInt = 5;
break;
if (!(paramType instanceof ObjectType)) {
break label221;
}
reserve(3);
put1(189);
putIndex2(getConstants().addClass((ObjectType)paramType));
}
label221:
if ((paramType instanceof ArrayType))
{
reserve(4);
put1(197);
putIndex2(getConstants().addClass(new ArrayType(paramType)));
if ((paramInt < 1) || (paramInt > 255)) {
throw new Error("dims out of range in emitNewArray");
}
put1(paramInt);
do
{
paramInt -= 1;
if (paramInt <= 0) {
break;
}
} while (popType().promote() == Type.intType);
throw new Error("non-int dim. spec. in emitNewArray");
}
throw new Error("unimplemented type in emitNewArray");
}
public final void emitNot(Type paramType)
{
emitPushConstant(1, paramType);
emitAdd();
emitPushConstant(1, paramType);
emitAnd();
}
public void emitPop(int paramInt)
{
if (paramInt > 0)
{
reserve(1);
if (popType().size > 4) {
put1(88);
}
for (;;)
{
paramInt -= 1;
break;
if (paramInt > 1)
{
if (popType().size > 4)
{
put1(87);
reserve(1);
}
put1(88);
paramInt -= 1;
}
else
{
put1(87);
}
}
}
}
public void emitPrimop(int paramInt1, int paramInt2, Type paramType)
{
reserve(1);
for (;;)
{
paramInt2 -= 1;
if (paramInt2 < 0) {
break;
}
popType();
}
put1(paramInt1);
pushType(paramType);
}
public final void emitPushClass(ObjectType paramObjectType)
{
emitPushConstant(getConstants().addClass(paramObjectType));
pushType(Type.javalangClassType);
}
public final void emitPushConstant(int paramInt, Type paramType)
{
switch (paramType.getSignature().charAt(0))
{
default:
throw new Error("bad type to emitPushConstant");
case 'B':
case 'C':
case 'I':
case 'S':
case 'Z':
emitPushInt(paramInt);
return;
case 'J':
emitPushLong(paramInt);
return;
case 'F':
emitPushFloat(paramInt);
return;
}
emitPushDouble(paramInt);
}
public final void emitPushConstant(CpoolEntry paramCpoolEntry)
{
reserve(3);
int i = paramCpoolEntry.index;
if ((paramCpoolEntry instanceof CpoolValue2))
{
put1(20);
put2(i);
return;
}
if (i < 256)
{
put1(18);
put1(i);
return;
}
put1(19);
put2(i);
}
public void emitPushDefaultValue(Type paramType)
{
paramType = paramType.getImplementationType();
if ((paramType instanceof PrimType))
{
emitPushConstant(0, paramType);
return;
}
emitPushNull();
}
public void emitPushDouble(double paramDouble)
{
int i = (int)paramDouble;
if ((i == paramDouble) && (i >= -128) && (i < 128)) {
if ((i == 0) || (i == 1))
{
reserve(1);
put1(i + 14);
if ((i == 0) && (Double.doubleToLongBits(paramDouble) != 0L))
{
reserve(1);
put1(119);
}
}
}
for (;;)
{
pushType(Type.doubleType);
return;
emitPushInt(i);
reserve(1);
popType();
put1(135);
continue;
emitPushConstant(getConstants().addDouble(paramDouble));
}
}
public void emitPushFloat(float paramFloat)
{
int i = (int)paramFloat;
if ((i == paramFloat) && (i >= -128) && (i < 128)) {
if ((i >= 0) && (i <= 2))
{
reserve(1);
put1(i + 11);
if ((i == 0) && (Float.floatToIntBits(paramFloat) != 0))
{
reserve(1);
put1(118);
}
}
}
for (;;)
{
pushType(Type.floatType);
return;
emitPushInt(i);
reserve(1);
popType();
put1(134);
continue;
emitPushConstant(getConstants().addFloat(paramFloat));
}
}
public final void emitPushInt(int paramInt)
{
reserve(3);
if ((paramInt >= -1) && (paramInt <= 5)) {
put1(paramInt + 3);
}
for (;;)
{
pushType(Type.intType);
return;
if ((paramInt >= -128) && (paramInt < 128))
{
put1(16);
put1(paramInt);
}
else if ((paramInt >= 32768) && (paramInt < 32768))
{
put1(17);
put2(paramInt);
}
else
{
emitPushConstant(getConstants().addInt(paramInt));
}
}
}
public void emitPushLong(long paramLong)
{
if ((paramLong == 0L) || (paramLong == 1L))
{
reserve(1);
put1((int)paramLong + 9);
}
for (;;)
{
pushType(Type.longType);
return;
if ((int)paramLong == paramLong)
{
emitPushInt((int)paramLong);
reserve(1);
popType();
put1(133);
}
else
{
emitPushConstant(getConstants().addLong(paramLong));
}
}
}
public void emitPushNull()
{
reserve(1);
put1(1);
pushType(Type.nullType);
}
public final void emitPushPrimArray(Object paramObject, ArrayType paramArrayType)
{
Type localType = paramArrayType.getComponentType();
int j = Array.getLength(paramObject);
emitPushInt(j);
emitNewArray(localType);
int k = localType.getSignature().charAt(0);
int i = 0;
if (i < j)
{
long l1 = 0L;
float f1 = 0.0F;
double d1 = 0.0D;
switch (k)
{
default:
label128:
emitDup(paramArrayType);
emitPushInt(i);
switch (k)
{
}
break;
}
for (;;)
{
emitArrayStore(localType);
for (;;)
{
label222:
i += 1;
break;
long l2 = ((long[])(long[])paramObject)[i];
l1 = l2;
if (l2 != 0L) {
break label128;
}
continue;
l2 = ((int[])(int[])paramObject)[i];
l1 = l2;
if (l2 != 0L) {
break label128;
}
continue;
l2 = ((short[])(short[])paramObject)[i];
l1 = l2;
if (l2 != 0L) {
break label128;
}
continue;
l2 = ((char[])(char[])paramObject)[i];
l1 = l2;
if (l2 != 0L) {
break label128;
}
continue;
l2 = ((byte[])(byte[])paramObject)[i];
l1 = l2;
if (l2 != 0L) {
break label128;
}
continue;
if (((boolean[])(boolean[])paramObject)[i] != 0) {}
for (l2 = 1L;; l2 = 0L)
{
l1 = l2;
if (l2 != 0L) {
break;
}
break label222;
}
float f2 = ((float[])(float[])paramObject)[i];
f1 = f2;
if (f2 != 0.0D) {
break label128;
}
continue;
double d2 = ((double[])(double[])paramObject)[i];
d1 = d2;
if (d2 != 0.0D) {
break label128;
}
}
emitPushInt((int)l1);
continue;
emitPushLong(l1);
continue;
emitPushFloat(f1);
continue;
emitPushDouble(d1);
}
}
}
public final void emitPushString(String paramString)
{
if (paramString == null) {
emitPushNull();
}
for (;;)
{
return;
int i = paramString.length();
String str = calculateSplit(paramString);
int m = str.length();
if (m <= 1)
{
emitPushConstant(getConstants().addString(paramString));
pushType(Type.javalangStringType);
return;
}
if (m == 2)
{
i = str.charAt(0);
emitPushString(paramString.substring(0, i));
emitPushString(paramString.substring(i));
emitInvokeVirtual(Type.javalangStringType.getDeclaredMethod("concat", 1));
}
while (paramString == paramString.intern())
{
emitInvokeVirtual(Type.javalangStringType.getDeclaredMethod("intern", 0));
return;
ClassType localClassType = ClassType.make("java.lang.StringBuffer");
emitNew(localClassType);
emitDup(localClassType);
emitPushInt(i);
emitInvokeSpecial(localClassType.getDeclaredMethod("<init>", new Type[] { Type.intType }));
Method localMethod = localClassType.getDeclaredMethod("append", new Type[] { Type.javalangStringType });
int j = 0;
i = 0;
while (i < m)
{
emitDup(localClassType);
int k = j + str.charAt(i);
emitPushString(paramString.substring(j, k));
emitInvokeVirtual(localMethod);
j = k;
i += 1;
}
emitInvokeVirtual(Type.toString_method);
}
}
}
public final void emitPushThis()
{
emitLoad(this.locals.used[0]);
}
public final void emitPutField(Field paramField)
{
popType();
popType();
emitFieldop(paramField, 181);
}
public final void emitPutStatic(Field paramField)
{
popType();
emitFieldop(paramField, 179);
}
final void emitRawReturn()
{
if (getMethod().getReturnType().size == 0)
{
reserve(1);
put1(177);
}
for (;;)
{
setUnreachable();
return;
emitTypedOp(172, popType().promote());
}
}
public final void emitRem()
{
emitBinop(112);
}
public void emitRet(Variable paramVariable)
{
int i = paramVariable.offset;
if (i < 256)
{
reserve(2);
put1(169);
put1(i);
return;
}
reserve(4);
put1(196);
put1(169);
put2(i);
}
public final void emitReturn()
{
if (this.try_stack != null) {
new Error();
}
emitRawReturn();
}
public final void emitShl()
{
emitShift(120);
}
public final void emitShr()
{
emitShift(122);
}
public void emitStore(Variable paramVariable)
{
int i = paramVariable.offset;
if ((i < 0) || (!paramVariable.isSimple())) {
throw new Error("attempting to store in unassigned " + paramVariable + " simple:" + paramVariable.isSimple() + ", offset: " + i);
}
paramVariable = paramVariable.getType().promote();
noteVarType(i, paramVariable);
reserve(4);
popType();
int j = adjustTypedOp(paramVariable);
if (i <= 3)
{
put1(j * 4 + 59 + i);
return;
}
emitMaybeWide(j + 54, i);
}
public void emitStoreDefaultValue(Variable paramVariable)
{
emitPushDefaultValue(paramVariable.getType());
emitStore(paramVariable);
}
public final void emitSub()
{
emitBinop(100);
}
public final void emitSub(char paramChar)
{
emitBinop(100, paramChar);
}
public final void emitSub(PrimType paramPrimType)
{
emitBinop(100, paramPrimType);
}
public void emitSwap()
{
reserve(1);
Type localType1 = popType();
Type localType2 = popType();
if ((localType1.size > 4) || (localType2.size > 4))
{
pushType(localType2);
pushType(localType1);
emitDupX();
emitPop(1);
return;
}
pushType(localType1);
put1(95);
pushType(localType2);
}
public void emitTailCall(boolean paramBoolean, Scope paramScope)
{
if (paramBoolean)
{
Method localMethod = getMethod();
int i;
if ((localMethod.access_flags & 0x8) != 0)
{
i = 0;
j = localMethod.arg_types.length;
label31:
k = j - 1;
if (k < 0) {
break label83;
}
if (localMethod.arg_types[k].size <= 4) {
break label77;
}
}
label77:
for (int j = 2;; j = 1)
{
i += j;
j = k;
break label31;
i = 1;
break;
}
label83:
j = localMethod.arg_types.length;
int k = j - 1;
if (k >= 0)
{
if (localMethod.arg_types[k].size > 4) {}
for (j = 2;; j = 1)
{
i -= j;
emitStore(this.locals.used[i]);
j = k;
break;
}
}
}
emitGoto(paramScope.start);
}
public final void emitThen()
{
this.if_stack.start_stack_size = this.SP;
}
public final void emitThrow()
{
popType();
reserve(1);
put1(191);
setUnreachable();
}
final void emitTransfer(Label paramLabel, int paramInt)
{
paramLabel.setTypes(this);
fixupAdd(6, paramLabel);
put1(paramInt);
this.PC += 2;
}
public void emitTryCatchEnd()
{
if (this.try_stack.finally_subr != null) {
emitFinallyEnd();
}
Variable[] arrayOfVariable = this.try_stack.savedStack;
if (this.try_stack.end_label == null) {
setUnreachable();
}
for (;;)
{
if ((this.try_stack.saved_result != null) || (arrayOfVariable != null)) {
popScope();
}
this.try_stack = this.try_stack.previous;
return;
setTypes(this.try_stack.start_try.localTypes, Type.typeArray0);
this.try_stack.end_label.define(this);
if (arrayOfVariable != null)
{
int i = arrayOfVariable.length;
for (;;)
{
int j = i - 1;
if (j < 0) {
break;
}
Variable localVariable = arrayOfVariable[j];
i = j;
if (localVariable != null)
{
emitLoad(localVariable);
i = j;
}
}
}
if (this.try_stack.saved_result != null) {
emitLoad(this.try_stack.saved_result);
}
}
}
public void emitTryEnd()
{
emitTryEnd(false);
}
public void emitTryStart(boolean paramBoolean, Type paramType)
{
Type localType = paramType;
if (paramType != null)
{
localType = paramType;
if (paramType.isVoid()) {
localType = null;
}
}
paramType = null;
if ((localType != null) || (this.SP > 0)) {
pushScope();
}
int i;
if (this.SP > 0)
{
localObject = new Variable[this.SP];
i = 0;
for (;;)
{
paramType = (Type)localObject;
if (this.SP <= 0) {
break;
}
paramType = addLocal(topType());
emitStore(paramType);
localObject[i] = paramType;
i += 1;
}
}
Object localObject = new TryState(this);
((TryState)localObject).savedStack = paramType;
if (this.local_types == null)
{
i = 0;
if ((i > 0) && (this.local_types[(i - 1)] == null)) {
break label192;
}
if (i != 0) {
break label199;
}
paramType = Type.typeArray0;
}
for (;;)
{
((TryState)localObject).start_try.localTypes = paramType;
if (localType != null) {
((TryState)localObject).saved_result = addLocal(localType);
}
if (paramBoolean) {
((TryState)localObject).finally_subr = new Label();
}
return;
i = this.local_types.length;
break;
label192:
i -= 1;
break;
label199:
paramType = new Type[i];
System.arraycopy(this.local_types, 0, paramType, 0, i);
}
}
public final void emitUshr()
{
emitShift(124);
}
public void emitWithCleanupCatch(Variable paramVariable)
{
emitTryEnd();
Type[] arrayOfType;
if (this.SP > 0)
{
arrayOfType = new Type[this.SP];
System.arraycopy(this.stack_types, 0, arrayOfType, 0, this.SP);
this.SP = 0;
}
for (;;)
{
this.try_stack.savedTypes = arrayOfType;
this.try_stack.saved_result = paramVariable;
int i = this.SP;
emitCatchStart(paramVariable);
return;
arrayOfType = null;
}
}
public void emitWithCleanupDone()
{
Object localObject = this.try_stack.saved_result;
this.try_stack.saved_result = null;
if (localObject != null) {
emitLoad((Variable)localObject);
}
emitThrow();
emitCatchEnd();
localObject = this.try_stack.savedTypes;
emitTryCatchEnd();
if (localObject != null)
{
this.SP = localObject.length;
if (this.SP >= this.stack_types.length)
{
this.stack_types = ((Type[])localObject);
return;
}
System.arraycopy(localObject, 0, this.stack_types, 0, this.SP);
return;
}
this.SP = 0;
}
public void emitWithCleanupStart()
{
int i = this.SP;
this.SP = 0;
emitTryStart(false, null);
this.SP = i;
}
public final void emitXOr()
{
emitBinop(130);
}
public void endExitableBlock()
{
ExitableBlock localExitableBlock = this.currentExitableBlock;
localExitableBlock.finish();
this.currentExitableBlock = localExitableBlock.outer;
}
public void endFragment(int paramInt)
{
this.fixup_offsets[paramInt] = (this.fixup_count << 4 | 0xA);
Label localLabel = this.fixup_labels[paramInt];
fixupAdd(9, 0, null);
localLabel.define(this);
}
public void enterScope(Scope paramScope)
{
paramScope.setStartPC(this);
this.locals.enterScope(paramScope);
}
final void fixupAdd(int paramInt1, int paramInt2, Label paramLabel)
{
if ((paramLabel != null) && (paramInt1 != 1) && (paramInt1 != 0) && (paramInt1 != 2) && (paramInt1 != 11)) {
paramLabel.needsStackMapEntry = true;
}
int i = this.fixup_count;
if (i == 0)
{
this.fixup_offsets = new int[30];
this.fixup_labels = new Label[30];
}
for (;;)
{
this.fixup_offsets[i] = (paramInt2 << 4 | paramInt1);
this.fixup_labels[i] = paramLabel;
this.fixup_count = (i + 1);
return;
if (this.fixup_count == this.fixup_offsets.length)
{
int j = i * 2;
Object localObject = new Label[j];
System.arraycopy(this.fixup_labels, 0, localObject, 0, i);
this.fixup_labels = ((Label[])localObject);
localObject = new int[j];
System.arraycopy(this.fixup_offsets, 0, localObject, 0, i);
this.fixup_offsets = ((int[])localObject);
}
}
}
public final void fixupAdd(int paramInt, Label paramLabel)
{
fixupAdd(paramInt, this.PC, paramLabel);
}
public final void fixupChain(Label paramLabel1, Label paramLabel2)
{
fixupAdd(9, 0, paramLabel2);
paramLabel1.defineRaw(this);
}
public Variable getArg(int paramInt)
{
return this.locals.parameter_scope.getVariable(paramInt);
}
public final Attribute getAttributes()
{
return this.attributes;
}
public byte[] getCode()
{
return this.code;
}
public int getCodeLength()
{
return this.PC;
}
public final ConstantPool getConstants()
{
return getMethod().classfile.constants;
}
public Scope getCurrentScope()
{
return this.locals.current_scope;
}
public final TryState getCurrentTry()
{
return this.try_stack;
}
public Label getLabel()
{
Label localLabel = new Label();
localLabel.defineRaw(this);
return localLabel;
}
public final int getLength()
{
return getCodeLength() + 12 + this.exception_table_length * 8 + Attribute.getLengthAll(this);
}
public int getMaxLocals()
{
return this.max_locals;
}
public int getMaxStack()
{
return this.max_stack;
}
public final Method getMethod()
{
return (Method)getContainer();
}
public final int getPC()
{
return this.PC;
}
public final int getSP()
{
return this.SP;
}
byte invert_opcode(byte paramByte)
{
paramByte &= 0xFF;
if (((paramByte >= 153) && (paramByte <= 166)) || ((paramByte >= 198) && (paramByte <= 199))) {
return (byte)(paramByte ^ 0x1);
}
throw new Error("unknown opcode to invert_opcode");
}
public final boolean isInTry()
{
return this.try_stack != null;
}
public Variable lookup(String paramString)
{
for (Scope localScope = this.locals.current_scope; localScope != null; localScope = localScope.parent)
{
Variable localVariable = localScope.lookup(paramString);
if (localVariable != null) {
return localVariable;
}
}
return null;
}
void noteParamTypes()
{
Method localMethod = getMethod();
int i = 0;
Object localObject;
if ((localMethod.access_flags & 0x8) == 0)
{
ClassType localClassType = localMethod.classfile;
localObject = localClassType;
if ("<init>".equals(localMethod.getName()))
{
localObject = localClassType;
if (!"java.lang.Object".equals(localClassType.getName())) {
localObject = UninitializedType.uninitializedThis((ClassType)localClassType);
}
}
noteVarType(0, (Type)localObject);
i = 0 + 1;
}
int m = localMethod.arg_types.length;
int k = 0;
for (int j = i; k < m; j = i)
{
localObject = localMethod.arg_types[k];
i = j + 1;
noteVarType(j, (Type)localObject);
j = ((Type)localObject).getSizeInWords();
for (;;)
{
j -= 1;
if (j <= 0) {
break;
}
i += 1;
}
k += 1;
}
if ((this.flags & 0x1) != 0)
{
this.stackMap = new StackMapTableAttr();
localObject = new int[j + 20];
i = 0;
k = 0;
while (i < j)
{
m = this.stackMap.encodeVerificationType(this.local_types[i], this);
localObject[k] = m;
int n = m & 0xFF;
if (n != 3)
{
m = i;
if (n != 4) {}
}
else
{
m = i + 1;
}
i = m + 1;
k += 1;
}
this.stackMap.encodedLocals = ((int[])localObject);
this.stackMap.countLocals = k;
this.stackMap.encodedStack = new int[10];
this.stackMap.countStack = 0;
}
}
public void noteVarType(int paramInt, Type paramType)
{
int k = paramType.getSizeInWords();
if (this.local_types == null)
{
this.local_types = new Type[paramInt + k + 20];
this.local_types[paramInt] = paramType;
if (this.varsSetInCurrentBlock != null) {
break label192;
}
this.varsSetInCurrentBlock = new boolean[this.local_types.length];
}
for (;;)
{
this.varsSetInCurrentBlock[paramInt] = true;
int i = k;
int j = paramInt;
if (paramInt > 0)
{
paramType = this.local_types[(paramInt - 1)];
i = k;
j = paramInt;
if (paramType != null)
{
i = k;
j = paramInt;
if (paramType.getSizeInWords() == 2)
{
this.local_types[(paramInt - 1)] = null;
j = paramInt;
i = k;
}
}
}
for (;;)
{
i -= 1;
if (i <= 0) {
break;
}
paramType = this.local_types;
j += 1;
paramType[j] = null;
}
if (paramInt + k <= this.local_types.length) {
break;
}
Type[] arrayOfType = new Type[(paramInt + k) * 2];
System.arraycopy(this.local_types, 0, arrayOfType, 0, this.local_types.length);
this.local_types = arrayOfType;
break;
label192:
if (this.varsSetInCurrentBlock.length <= paramInt)
{
paramType = new boolean[this.local_types.length];
System.arraycopy(this.varsSetInCurrentBlock, 0, paramType, 0, this.varsSetInCurrentBlock.length);
this.varsSetInCurrentBlock = paramType;
}
}
}
public Scope popScope()
{
Scope localScope = this.locals.current_scope;
this.locals.current_scope = localScope.parent;
localScope.freeLocals(this);
localScope.end = getLabel();
return localScope;
}
public final Type popType()
{
if (this.SP <= 0) {
throw new Error("popType called with empty stack " + getMethod());
}
Object localObject = this.stack_types;
int i = this.SP - 1;
this.SP = i;
localObject = localObject[i];
if ((((Type)localObject).size == 8) && (!popType().isVoid())) {
throw new Error("missing void type on stack");
}
return (Type)localObject;
}
public void print(ClassTypeWriter paramClassTypeWriter)
{
paramClassTypeWriter.print("Attribute \"");
paramClassTypeWriter.print(getName());
paramClassTypeWriter.print("\", length:");
paramClassTypeWriter.print(getLength());
paramClassTypeWriter.print(", max_stack:");
paramClassTypeWriter.print(this.max_stack);
paramClassTypeWriter.print(", max_locals:");
paramClassTypeWriter.print(this.max_locals);
paramClassTypeWriter.print(", code_length:");
int i = getCodeLength();
paramClassTypeWriter.println(i);
disAssemble(paramClassTypeWriter, 0, i);
if (this.exception_table_length > 0)
{
paramClassTypeWriter.print("Exceptions (count: ");
paramClassTypeWriter.print(this.exception_table_length);
paramClassTypeWriter.println("):");
int j = this.exception_table_length;
i = 0;
j -= 1;
if (j >= 0)
{
paramClassTypeWriter.print(" start: ");
paramClassTypeWriter.print(this.exception_table[i] & 0xFFFF);
paramClassTypeWriter.print(", end: ");
paramClassTypeWriter.print(this.exception_table[(i + 1)] & 0xFFFF);
paramClassTypeWriter.print(", handler: ");
paramClassTypeWriter.print(this.exception_table[(i + 2)] & 0xFFFF);
paramClassTypeWriter.print(", type: ");
int k = this.exception_table[(i + 3)] & 0xFFFF;
if (k == 0) {
paramClassTypeWriter.print("0 /* finally */");
}
for (;;)
{
paramClassTypeWriter.println();
i += 4;
break;
paramClassTypeWriter.printOptionalIndex(k);
paramClassTypeWriter.printConstantTersely(k, 7);
}
}
}
paramClassTypeWriter.printAttributes(this);
}
public void processFixups()
{
if (this.fixup_count <= 0) {
return;
}
int k = 0;
int n = this.fixup_count;
fixupAdd(9, 0, null);
int j = 0;
int i3 = this.fixup_offsets[j];
int i2 = i3 >> 4;
Object localObject1 = this.fixup_labels[j];
int i = k;
int m = j;
int i1 = n;
switch (i3 & 0xF)
{
case 7:
case 12:
case 13:
default:
throw new Error("unexpected fixup");
case 11:
m = j + 2;
i = k;
case 0:
case 3:
case 8:
case 14:
case 1:
case 2:
case 4:
case 5:
case 6:
for (;;)
{
j = m + 1;
k = i;
break;
m = j + 1;
i = k;
continue;
((Label)localObject1).position += k;
i = k;
m = j;
continue;
i = k + 3;
m = j;
continue;
if ((((Label)localObject1).first_fixup == j + 1) && (fixupOffset(j + 1) == i2 + 3))
{
this.fixup_offsets[j] = (i2 << 4 | 0x8);
this.fixup_labels[j] = null;
i = k - 3;
m = j;
}
else
{
i = k;
m = j;
if (this.PC >= 32768)
{
i = k + 2;
m = j;
continue;
i = k;
m = j;
if (this.PC >= 32768)
{
i = k + 5;
m = j;
}
}
}
}
case 10:
this.fixup_labels[n] = this.fixup_labels[(j + 1)];
i1 = i2;
}
if (j + 1 >= this.fixup_count)
{
i = this.PC;
label358:
this.fixup_offsets[j] = (i << 4 | 0x9);
if (localObject1 != null) {
break label484;
}
i3 = this.PC;
m = 0;
i = 0;
}
Object localObject2;
label484:
label870:
label879:
label918:
byte[] arrayOfByte;
int i4;
for (;;)
{
if (i < this.fixup_count)
{
j = this.fixup_offsets[i];
i1 = j & 0xF;
localObject2 = this.fixup_labels[i];
localObject1 = localObject2;
if (localObject2 != null)
{
localObject1 = localObject2;
if (((Label)localObject2).position < 0)
{
throw new Error("undefined label " + localObject2);
i = fixupOffset(this.fixup_labels[(j + 1)].first_fixup);
break label358;
j = ((Label)localObject1).first_fixup;
k = i + k - fixupOffset(j);
n = i1;
break;
}
}
while ((localObject1 != null) && (i1 >= 4) && (i1 <= 7) && (((Label)localObject1).first_fixup + 1 < this.fixup_count) && (this.fixup_offsets[(localObject1.first_fixup + 1)] == (this.fixup_offsets[localObject1.first_fixup] & 0xF | 0x4)))
{
localObject1 = this.fixup_labels[(localObject1.first_fixup + 1)];
this.fixup_labels[i] = localObject1;
}
i2 = j >> 4;
j = m;
n = i;
k = i3;
switch (i1)
{
case 7:
case 10:
case 12:
case 13:
default:
throw new Error("unexpected fixup");
case 11:
n = i + 2;
this.fixup_labels[n].position = (i2 + m);
k = i3;
j = m;
case 0:
case 3:
case 14:
case 8:
case 1:
case 2:
case 4:
case 5:
case 6:
for (;;)
{
i = n + 1;
m = j;
i3 = k;
break;
n = i + 1;
j = m;
k = i3;
continue;
j = m - 3;
k = i3 - 3;
n = i;
continue;
((Label)localObject1).position = (i2 + m);
j = m;
n = i;
k = i3;
continue;
k = 3 - (i2 + m) & 0x3;
j = m + k;
k = i3 + k;
n = i;
continue;
j = ((Label)localObject1).position - (i2 + m);
if ((short)j != j) {
break label870;
}
this.fixup_offsets[i] = (i2 << 4 | 0x7);
j = m;
n = i;
k = i3;
}
if (i1 == 6)
{
j = 5;
k = m + j;
if (i1 != 6) {
break label918;
}
}
for (j = 5;; j = 2)
{
m = i3 + j;
j = k;
n = i;
k = m;
break;
j = 2;
break label879;
}
}
if (localObject1 != null) {
break label981;
}
}
arrayOfByte = new byte[i3];
i4 = -1;
m = 0;
k = fixupOffset(0);
localObject2 = null;
j = 0;
i = 0;
while (j < k)
{
arrayOfByte[i] = this.code[j];
j += 1;
i += 1;
}
label981:
i = ((Label)localObject1).first_fixup;
m = i2 + m - fixupOffset(i);
}
n = this.fixup_offsets[m] & 0xF;
Label localLabel = this.fixup_labels[m];
localObject1 = localObject2;
if (localObject2 != null)
{
localObject1 = localObject2;
if (((Label)localObject2).position < i)
{
this.stackMap.emitStackMapEntry((Label)localObject2, this);
localObject1 = null;
}
}
if ((localObject1 != null) && (((Label)localObject1).position > i)) {
throw new Error("labels out of order");
}
int i5;
switch (n)
{
case 3:
case 10:
case 12:
case 13:
default:
throw new Error("unexpected fixup");
case 0:
i5 = i4;
localObject2 = localObject1;
k = j;
j = i;
}
for (;;)
{
label1184:
m += 1;
i1 = fixupOffset(m);
n = k;
i = j;
k = i1;
j = n;
i4 = i5;
break;
if ((this.stackMap != null) && (localLabel != null) && (localLabel.stackTypes != null) && (localLabel.needsStackMapEntry))
{
localObject2 = mergeLabels((Label)localObject1, localLabel);
k = j;
j = i;
i5 = i4;
continue;
k = j + 3;
j = i;
localObject2 = localObject1;
i5 = i4;
continue;
k = localLabel.position - i;
n = i + 1;
arrayOfByte[i] = this.code[j];
i1 = n + 1;
arrayOfByte[n] = ((byte)(k >> 8));
i = i1 + 1;
arrayOfByte[i1] = ((byte)(k & 0xFF));
k = j + 3;
j = i;
localObject2 = localObject1;
i5 = i4;
continue;
k = localLabel.position - i;
byte b = this.code[j];
if (n == 6)
{
b = invert_opcode(b);
n = i + 1;
arrayOfByte[i] = b;
i1 = n + 1;
arrayOfByte[n] = 0;
i = i1 + 1;
arrayOfByte[i1] = 8;
}
for (b = -56;; b = (byte)(b + 33))
{
n = i + 1;
arrayOfByte[i] = b;
i = n + 1;
arrayOfByte[n] = ((byte)(k >> 24));
n = i + 1;
arrayOfByte[i] = ((byte)(k >> 16));
i = n + 1;
arrayOfByte[n] = ((byte)(k >> 8));
arrayOfByte[i] = ((byte)(k & 0xFF));
k = j + 3;
j = i + 1;
localObject2 = localObject1;
i5 = i4;
break;
}
k = 3 - i & 0x3;
localObject2 = this.code;
i1 = j + 1;
arrayOfByte[i] = localObject2[j];
j = i + 1;
for (;;)
{
k -= 1;
if (k < 0) {
break;
}
arrayOfByte[j] = 0;
j += 1;
}
label1578:
m = this.fixup_labels[i2].position - i;
n = k + 1;
arrayOfByte[k] = ((byte)(m >> 24));
k = n + 1;
arrayOfByte[n] = ((byte)(m >> 16));
n = k + 1;
arrayOfByte[k] = ((byte)(m >> 8));
arrayOfByte[n] = ((byte)(m & 0xFF));
i1 = j + 4;
n += 1;
for (;;)
{
j = n;
m = i2;
k = i1;
localObject2 = localObject1;
i5 = i4;
if (i2 >= this.fixup_count) {
break label1184;
}
j = n;
m = i2;
k = i1;
localObject2 = localObject1;
i5 = i4;
if (fixupKind(i2 + 1) != 3) {
break label1184;
}
i2 += 1;
m = fixupOffset(i2);
j = i1;
k = n;
while (j < m)
{
arrayOfByte[k] = this.code[j];
j += 1;
k += 1;
}
break label1578;
localLabel = this.fixup_labels[(m + 2)];
k = fixupOffset(m + 1);
localObject2 = localObject1;
if (this.stackMap != null) {
localObject2 = mergeLabels((Label)localObject1, localLabel);
}
addHandler(this.fixup_labels[m].position, this.fixup_labels[(m + 1)].position, i, k);
m += 2;
k = j;
j = i;
i5 = i4;
break label1184;
if (this.lines == null) {
this.lines = new LineNumbersAttr(this);
}
m += 1;
i5 = fixupOffset(m);
if (i5 != i4) {
this.lines.put(i5, i);
}
k = j;
j = i;
localObject2 = localObject1;
break label1184;
if (localLabel == null)
{
if (i3 != i) {
throw new Error("PC confusion new_pc:" + i + " new_size:" + i3);
}
}
else
{
m = localLabel.first_fixup;
j = fixupOffset(m);
k = j;
if (localLabel.position == i) {
break label2042;
}
throw new Error("bad pc");
}
this.PC = i3;
this.code = arrayOfByte;
this.fixup_count = 0;
this.fixup_labels = null;
this.fixup_offsets = null;
return;
label2042:
localObject2 = localObject1;
break;
n = j;
i2 = m;
}
}
else
{
k = j;
j = i;
localObject2 = localObject1;
i5 = i4;
}
}
}
public Scope pushScope()
{
Scope localScope = new Scope();
if (this.locals == null) {
this.locals = new LocalVarsAttr(getMethod());
}
enterScope(localScope);
if (this.locals.parameter_scope == null) {
this.locals.parameter_scope = localScope;
}
return localScope;
}
public final void pushType(Type paramType)
{
if (paramType.size == 0) {
throw new Error("pushing void type onto stack");
}
if ((this.stack_types == null) || (this.stack_types.length == 0)) {
this.stack_types = new Type[20];
}
for (;;)
{
if (paramType.size == 8)
{
arrayOfType = this.stack_types;
i = this.SP;
this.SP = (i + 1);
arrayOfType[i] = Type.voidType;
}
Type[] arrayOfType = this.stack_types;
int i = this.SP;
this.SP = (i + 1);
arrayOfType[i] = paramType;
if (this.SP > this.max_stack) {
this.max_stack = this.SP;
}
return;
if (this.SP + 1 >= this.stack_types.length)
{
arrayOfType = new Type[this.stack_types.length * 2];
System.arraycopy(this.stack_types, 0, arrayOfType, 0, this.SP);
this.stack_types = arrayOfType;
}
}
}
public final void put1(int paramInt)
{
byte[] arrayOfByte = this.code;
int i = this.PC;
this.PC = (i + 1);
arrayOfByte[i] = ((byte)paramInt);
this.unreachable_here = false;
}
public final void put2(int paramInt)
{
byte[] arrayOfByte = this.code;
int i = this.PC;
this.PC = (i + 1);
arrayOfByte[i] = ((byte)(paramInt >> 8));
arrayOfByte = this.code;
i = this.PC;
this.PC = (i + 1);
arrayOfByte[i] = ((byte)paramInt);
this.unreachable_here = false;
}
public final void put4(int paramInt)
{
byte[] arrayOfByte = this.code;
int i = this.PC;
this.PC = (i + 1);
arrayOfByte[i] = ((byte)(paramInt >> 24));
arrayOfByte = this.code;
i = this.PC;
this.PC = (i + 1);
arrayOfByte[i] = ((byte)(paramInt >> 16));
arrayOfByte = this.code;
i = this.PC;
this.PC = (i + 1);
arrayOfByte[i] = ((byte)(paramInt >> 8));
arrayOfByte = this.code;
i = this.PC;
this.PC = (i + 1);
arrayOfByte[i] = ((byte)paramInt);
this.unreachable_here = false;
}
public final void putIndex2(CpoolEntry paramCpoolEntry)
{
put2(paramCpoolEntry.index);
}
public final void putLineNumber(int paramInt)
{
int i = paramInt;
if (this.sourceDbgExt != null) {
i = this.sourceDbgExt.fixLine(paramInt);
}
fixupAdd(14, null);
fixupAdd(15, i, null);
}
public final void putLineNumber(String paramString, int paramInt)
{
if (paramString != null) {
getMethod().classfile.setSourceFile(paramString);
}
putLineNumber(paramInt);
}
public final boolean reachableHere()
{
return !this.unreachable_here;
}
public final void reserve(int paramInt)
{
if (this.code == null) {
this.code = new byte[paramInt + 100];
}
while (this.PC + paramInt <= this.code.length) {
return;
}
byte[] arrayOfByte = new byte[this.code.length * 2 + paramInt];
System.arraycopy(this.code, 0, arrayOfByte, 0, this.PC);
this.code = arrayOfByte;
}
public final void setAttributes(Attribute paramAttribute)
{
this.attributes = paramAttribute;
}
public void setCode(byte[] paramArrayOfByte)
{
this.code = paramArrayOfByte;
this.PC = paramArrayOfByte.length;
}
public void setCodeLength(int paramInt)
{
this.PC = paramInt;
}
public void setMaxLocals(int paramInt)
{
this.max_locals = paramInt;
}
public void setMaxStack(int paramInt)
{
this.max_stack = paramInt;
}
public final void setReachable(boolean paramBoolean)
{
if (!paramBoolean) {}
for (paramBoolean = true;; paramBoolean = false)
{
this.unreachable_here = paramBoolean;
return;
}
}
public final void setTypes(Label paramLabel)
{
setTypes(paramLabel.localTypes, paramLabel.stackTypes);
}
public final void setTypes(Type[] paramArrayOfType1, Type[] paramArrayOfType2)
{
int j = paramArrayOfType2.length;
int i = paramArrayOfType1.length;
if (this.local_types != null)
{
if (i > 0) {
System.arraycopy(paramArrayOfType1, 0, this.local_types, 0, i);
}
while (i < this.local_types.length)
{
this.local_types[i] = null;
i += 1;
}
}
if ((this.stack_types == null) || (j > this.stack_types.length)) {
this.stack_types = new Type[j];
}
for (;;)
{
System.arraycopy(paramArrayOfType2, 0, this.stack_types, 0, j);
this.SP = j;
return;
i = j;
while (i < this.stack_types.length)
{
this.stack_types[i] = null;
i += 1;
}
}
}
public final void setUnreachable()
{
this.unreachable_here = true;
}
public ExitableBlock startExitableBlock(Type paramType, boolean paramBoolean)
{
paramType = new ExitableBlock(paramType, this, paramBoolean);
paramType.outer = this.currentExitableBlock;
this.currentExitableBlock = paramType;
return paramType;
}
public SwitchState startSwitch()
{
SwitchState localSwitchState = new SwitchState(this);
localSwitchState.switchValuePushed(this);
return localSwitchState;
}
public final Type topType()
{
return this.stack_types[(this.SP - 1)];
}
boolean useJsr()
{
return (this.flags & 0x2) == 0;
}
public void write(DataOutputStream paramDataOutputStream)
throws IOException
{
paramDataOutputStream.writeShort(this.max_stack);
paramDataOutputStream.writeShort(this.max_locals);
paramDataOutputStream.writeInt(this.PC);
paramDataOutputStream.write(this.code, 0, this.PC);
paramDataOutputStream.writeShort(this.exception_table_length);
int j = this.exception_table_length;
int i = 0;
for (;;)
{
j -= 1;
if (j < 0) {
break;
}
paramDataOutputStream.writeShort(this.exception_table[i]);
paramDataOutputStream.writeShort(this.exception_table[(i + 1)]);
paramDataOutputStream.writeShort(this.exception_table[(i + 2)]);
paramDataOutputStream.writeShort(this.exception_table[(i + 3)]);
i += 4;
}
Attribute.writeAll(this, paramDataOutputStream);
}
}
/* Location: C:\Users\Mohamed\Downloads\dex2jar-2.0\dex2jar-2.0\classes-dex2jar.jar!\gnu\bytecode\CodeAttr.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | 92,913 | 0.526998 | 0.501351 | 3,903 | 22.80579 | 19.981382 | 244 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.612862 | false | false | 12 |
524dbb27aab755aa06a6af6f28ebbbcc4397c39a | 3,393,024,193,858 | 0cc69ae41b12cf832f8504d46358ca7e33075af7 | /bandit/src/main/java/com/personal/bandit/service/KafkaConsumerService.java | eb4fe414cace3911fbe473c3d0f97791dddd39ae | [
"MIT"
] | permissive | stasim101/Armorcode | https://github.com/stasim101/Armorcode | b2b0ed22501c7e9ae5befc4ca08d84fe927acad8 | 59e0f505ec11fd1d7d2bd7fe710d79f78c51b2a3 | refs/heads/main | 2023-03-03T17:11:27.553000 | 2021-02-05T03:24:15 | 2021-02-05T03:24:15 | 318,804,625 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.personal.bandit.service;
import java.io.IOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;
@Service
public class KafkaConsumerService {
@Autowired
private MessageExtractorService messageExtractorService;
@KafkaListener(topics = "bandit", groupId = "group_id")
public String consume(String message) throws IOException {
messageExtractorService.saveExtract(message);
return message;
}
}
| UTF-8 | Java | 542 | java | KafkaConsumerService.java | Java | [] | null | [] | package com.personal.bandit.service;
import java.io.IOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;
@Service
public class KafkaConsumerService {
@Autowired
private MessageExtractorService messageExtractorService;
@KafkaListener(topics = "bandit", groupId = "group_id")
public String consume(String message) throws IOException {
messageExtractorService.saveExtract(message);
return message;
}
}
| 542 | 0.819188 | 0.819188 | 20 | 26.1 | 23.98312 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.9 | false | false | 12 |
7a013021305c06f631f92cdfda6f9ca2e9e914a0 | 6,914,897,375,502 | 7faa7ba4dbd378105aeb468b9005978512f0b063 | /July20216_30AM_JavaBatch/src/com/icici/loans/eduloans/EmployeeChild.java | 4ea65d398aadcb1e26abbc8343c355eb7ab11b02 | [] | no_license | ravilella1234/July2021_6_30AM-Batch | https://github.com/ravilella1234/July2021_6_30AM-Batch | 0d455b592e7b8879b85b7086d86e62510c182a58 | 313723f3333a8b36c660b3271fc17cc87a972839 | refs/heads/main | 2023-08-11T04:53:18.920000 | 2021-10-14T01:33:48 | 2021-10-14T01:33:48 | 381,880,275 | 0 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.icici.loans.eduloans;
public class EmployeeChild extends Employee
{
String city;
public EmployeeChild(String city)
{
super(1744,"ravilella",12.34f);
this.city = city;
System.out.println(this.city);
}
public static void main(String[] args)
{
EmployeeChild e = new EmployeeChild("hyderabd");
}
}
| UTF-8 | Java | 330 | java | EmployeeChild.java | Java | [
{
"context": "blic EmployeeChild(String city) \n\t{\n\t\tsuper(1744,\"ravilella\",12.34f);\n\t\tthis.city = city;\n\t\tSystem.out.printl",
"end": 159,
"score": 0.9809030890464783,
"start": 150,
"tag": "NAME",
"value": "ravilella"
},
{
"context": "] args)\n\t{\n\t\tEmployeeChild e = n... | null | [] | package com.icici.loans.eduloans;
public class EmployeeChild extends Employee
{
String city;
public EmployeeChild(String city)
{
super(1744,"ravilella",12.34f);
this.city = city;
System.out.println(this.city);
}
public static void main(String[] args)
{
EmployeeChild e = new EmployeeChild("hyderabd");
}
}
| 330 | 0.706061 | 0.681818 | 20 | 15.5 | 17.382462 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.3 | false | false | 12 |
8238ed2824d94f00c84bf620e067ca5cb2a6eb09 | 13,013,750,927,290 | 82ee10a468daa06edb529ae8c7b155bd203d77fb | /eb-api/src/main/java/io/engineblock/activityapi/cyclelog/filters/tristate/EnumReadableMappingFilter.java | ae67f010bd2fc8c925eaba6ef0630e78299ff34b | [
"Apache-2.0"
] | permissive | engineblock/engineblock | https://github.com/engineblock/engineblock | 244728581d24075135d4c4dc8f50576e933d28ae | 9034acd8de724d6dfb6d2ff3ece3f9d8cde97ab0 | refs/heads/master | 2023-03-20T08:50:14.055000 | 2020-02-26T19:56:19 | 2020-02-26T19:56:19 | 57,073,755 | 11 | 12 | null | false | 2020-02-24T12:56:36 | 2016-04-25T20:20:59 | 2020-02-24T12:56:26 | 2020-02-24T12:56:35 | 15,561 | 9 | 10 | 48 | Java | false | false | /*
*
* Copyright 2016 jshook
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* /
*/
package io.engineblock.activityapi.cyclelog.filters.tristate;
import io.engineblock.activityapi.cyclelog.buffers.results.ResultReadable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.regex.Pattern;
/**
* A result reading filter which uses an Enum as a set of elements to filter.
* If you have an Enum that implements ResultReadable, then you can easily create
* an enum-aware filter for it with this class.
*
* @param <E> The type of the Enum which implements TristateFilter
*/
public class EnumReadableMappingFilter<E extends Enum<E> & ResultReadable> implements TristateFilter<ResultReadable> {
private final static Logger logger = LoggerFactory.getLogger(EnumReadableMappingFilter.class);
private final E[] enumValues;
private ResultMappingArrayFilter arrayFilter = new ResultMappingArrayFilter();
public EnumReadableMappingFilter(E[] enumValues, Policy defaultPolicy) {
this.enumValues = enumValues;
for (E enumValue : enumValues) {
arrayFilter.addPolicy(enumValue,defaultPolicy);
}
}
public void addPolicy(String s, Policy policy) {
Pattern p = null;
int matched=0;
if (s.matches("\\w+")) {
p = Pattern.compile("^" + s + "$");
} else {
p = Pattern.compile(s);
}
for (E enumValue : enumValues) {
if (enumValue.toString().matches(p.pattern())) {
matched++;
logger.debug("Setting policy for " + enumValue + " to " + policy);
int resultCode = enumValue.getResult();
arrayFilter.addPolicy(enumValue,policy);
}
}
if (matched==0) {
StringBuilder sb = new StringBuilder();
for (E enumValue : this.enumValues) {
sb.append(enumValue.toString()).append(",");
}
logger.warn("Unable to match any known type with pattern '" + s + "', available names: " + sb.toString());
}
}
@Override
public Policy apply(ResultReadable cycleResult) {
return arrayFilter.apply(cycleResult);
}
public String toString () {
StringBuilder sb = new StringBuilder();
for (E enumValue : enumValues) {
int result = enumValue.getResult();
sb.append(enumValue.toString())
.append("->")
.append(result)
.append("->")
.append(arrayFilter.getPolicy(result)).append("\n");
}
return sb.toString();
}
}
| UTF-8 | Java | 3,255 | java | EnumReadableMappingFilter.java | Java | [
{
"context": "/*\n *\n * Copyright 2016 jshook\n * Licensed under the Apache License, Version ",
"end": 33,
"score": 0.9994719624519348,
"start": 27,
"tag": "USERNAME",
"value": "jshook"
}
] | null | [] | /*
*
* Copyright 2016 jshook
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* /
*/
package io.engineblock.activityapi.cyclelog.filters.tristate;
import io.engineblock.activityapi.cyclelog.buffers.results.ResultReadable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.regex.Pattern;
/**
* A result reading filter which uses an Enum as a set of elements to filter.
* If you have an Enum that implements ResultReadable, then you can easily create
* an enum-aware filter for it with this class.
*
* @param <E> The type of the Enum which implements TristateFilter
*/
public class EnumReadableMappingFilter<E extends Enum<E> & ResultReadable> implements TristateFilter<ResultReadable> {
private final static Logger logger = LoggerFactory.getLogger(EnumReadableMappingFilter.class);
private final E[] enumValues;
private ResultMappingArrayFilter arrayFilter = new ResultMappingArrayFilter();
public EnumReadableMappingFilter(E[] enumValues, Policy defaultPolicy) {
this.enumValues = enumValues;
for (E enumValue : enumValues) {
arrayFilter.addPolicy(enumValue,defaultPolicy);
}
}
public void addPolicy(String s, Policy policy) {
Pattern p = null;
int matched=0;
if (s.matches("\\w+")) {
p = Pattern.compile("^" + s + "$");
} else {
p = Pattern.compile(s);
}
for (E enumValue : enumValues) {
if (enumValue.toString().matches(p.pattern())) {
matched++;
logger.debug("Setting policy for " + enumValue + " to " + policy);
int resultCode = enumValue.getResult();
arrayFilter.addPolicy(enumValue,policy);
}
}
if (matched==0) {
StringBuilder sb = new StringBuilder();
for (E enumValue : this.enumValues) {
sb.append(enumValue.toString()).append(",");
}
logger.warn("Unable to match any known type with pattern '" + s + "', available names: " + sb.toString());
}
}
@Override
public Policy apply(ResultReadable cycleResult) {
return arrayFilter.apply(cycleResult);
}
public String toString () {
StringBuilder sb = new StringBuilder();
for (E enumValue : enumValues) {
int result = enumValue.getResult();
sb.append(enumValue.toString())
.append("->")
.append(result)
.append("->")
.append(arrayFilter.getPolicy(result)).append("\n");
}
return sb.toString();
}
}
| 3,255 | 0.615361 | 0.611674 | 90 | 35.166668 | 29.674623 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.422222 | false | false | 12 |
bb88d1d4cabd0ed5f76d4b4e6e6517e5e4272679 | 29,240,137,396,958 | 6437a95e3bbc6c7cc22f7318c5af62d6cb5778e1 | /src/main/java/com/parlatech/map/repositories/EquipamentoRepository.java | cec93db56fde53949ef372220c32e7b392132cdc | [] | no_license | Faelxld/ApiDefesaCivil | https://github.com/Faelxld/ApiDefesaCivil | f16fbc912a31d6d3808e0b7c8c0145598e4f66d8 | f1964fa7a9823020a38ca2a064b896a9082d8b7f | refs/heads/master | 2020-04-07T13:46:59.678000 | 2018-12-11T18:41:48 | 2018-12-11T18:41:48 | 158,421,236 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.parlatech.map.repositories;
import com.parlatech.map.domain.Equipamento;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface EquipamentoRepository extends JpaRepository<Equipamento, Integer> {
}
| UTF-8 | Java | 298 | java | EquipamentoRepository.java | Java | [] | null | [] | package com.parlatech.map.repositories;
import com.parlatech.map.domain.Equipamento;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface EquipamentoRepository extends JpaRepository<Equipamento, Integer> {
}
| 298 | 0.852349 | 0.852349 | 9 | 32.111111 | 28.823002 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false | 12 |
33afd0f9ad08a526814df3763d68cb06f190cc15 | 2,499,671,001,720 | 939e2078d2185247ebf2648c524d381394d6a9ab | /src/dp/BOJ15988.java | 885bdbc044fd32bbafd4e3b051296a8cfba312fe | [] | no_license | dks301/BOJ | https://github.com/dks301/BOJ | dc30660d4a1f8064f84bf646286991f105c1653d | 1c08b07897faf34774314df4999aa5b3378f8ba7 | refs/heads/master | 2022-06-17T02:29:43.460000 | 2022-06-12T06:44:13 | 2022-06-12T06:44:13 | 121,115,019 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dp;
import java.io.BufferedReader;
import java.io.InputStreamReader;
/*
* 1, 2, 3 더하기3
* 정수 n이 주어졌을때, n을 1,2,3의 합으로 나타내는 방법의 수구하기
*
* 입력
* 첫째줄: 테스트케이스 개수T
* 다음T개줄: 정수n(n<=1000000인 양수)
*
* 출력
* 각 테스트 케이스마다 n을 1,2,3의 합으로 나타내는 방법의 수를 1,000,000,009로 나눈 나머지 출력
*/
public class BOJ15988 {
private static final int INF = 1_000_000;
private static final long MOD = 1_000_000_009L;
private static final char NEW_LINE = '\n';
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
long[] d = new long[INF + 1];
d[0] = d[1] = 1L;
d[2] = 2L;
for (int i = 3; i <= INF; i++) {
d[i] = (d[i - 3] + d[i - 2] + d[i - 1]) % MOD;
}
StringBuilder sb = new StringBuilder();
int T = Integer.parseInt(br.readLine());
for (int t = 1; t <= T; t++) {
int n = Integer.parseInt(br.readLine());
sb.append(d[n]).append(NEW_LINE);
}
System.out.print(sb);
}
}
| UTF-8 | Java | 1,134 | java | BOJ15988.java | Java | [] | null | [] | package dp;
import java.io.BufferedReader;
import java.io.InputStreamReader;
/*
* 1, 2, 3 더하기3
* 정수 n이 주어졌을때, n을 1,2,3의 합으로 나타내는 방법의 수구하기
*
* 입력
* 첫째줄: 테스트케이스 개수T
* 다음T개줄: 정수n(n<=1000000인 양수)
*
* 출력
* 각 테스트 케이스마다 n을 1,2,3의 합으로 나타내는 방법의 수를 1,000,000,009로 나눈 나머지 출력
*/
public class BOJ15988 {
private static final int INF = 1_000_000;
private static final long MOD = 1_000_000_009L;
private static final char NEW_LINE = '\n';
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
long[] d = new long[INF + 1];
d[0] = d[1] = 1L;
d[2] = 2L;
for (int i = 3; i <= INF; i++) {
d[i] = (d[i - 3] + d[i - 2] + d[i - 1]) % MOD;
}
StringBuilder sb = new StringBuilder();
int T = Integer.parseInt(br.readLine());
for (int t = 1; t <= T; t++) {
int n = Integer.parseInt(br.readLine());
sb.append(d[n]).append(NEW_LINE);
}
System.out.print(sb);
}
}
| 1,134 | 0.612371 | 0.550515 | 40 | 23.25 | 20.411699 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.775 | false | false | 12 |
2a437ad8c18dd4da9926602126fe0b75e336ff6f | 14,851,996,942,349 | bfba4bdbbf1e786e9b56bb547268cf8d54eb71ca | /app/src/main/java/Clases/Producto.java | 215bcefbe32df6338be460e03415bcc3f085feaf | [
"Apache-2.0"
] | permissive | JRSValdez/VLSPinventarios | https://github.com/JRSValdez/VLSPinventarios | 36b33b3b2b00129407f2a8c923b6537aa0b7743f | 29116a770c7bdae6c8033b6f1e85a73bd23927e2 | refs/heads/master | 2020-04-01T19:22:03.595000 | 2018-11-19T21:53:45 | 2018-11-19T21:53:45 | 152,934,987 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Clases;
import java.io.Serializable;
public class Producto implements Serializable{
public int idEmpresa;
public int idProducto;
public int idCategoria;
public String producto;
public float cantidad;
public double precio;
public double costo;
public String descripcion;
public String Vencimiento;
public Producto(){
}
public Producto(int _idEmp, int _idCat, String _nomb, float _cant, double _precio, double _costo, String _desc, String _exp){
this.idEmpresa = _idEmp;
this.idCategoria = _idCat;
this.producto = _nomb;
this.cantidad = _cant;
this.precio = _precio;
this.costo = _costo;
this.descripcion = _desc;
this.Vencimiento = _exp;
}
}
| UTF-8 | Java | 802 | java | Producto.java | Java | [] | null | [] | package Clases;
import java.io.Serializable;
public class Producto implements Serializable{
public int idEmpresa;
public int idProducto;
public int idCategoria;
public String producto;
public float cantidad;
public double precio;
public double costo;
public String descripcion;
public String Vencimiento;
public Producto(){
}
public Producto(int _idEmp, int _idCat, String _nomb, float _cant, double _precio, double _costo, String _desc, String _exp){
this.idEmpresa = _idEmp;
this.idCategoria = _idCat;
this.producto = _nomb;
this.cantidad = _cant;
this.precio = _precio;
this.costo = _costo;
this.descripcion = _desc;
this.Vencimiento = _exp;
}
}
| 802 | 0.619701 | 0.619701 | 31 | 23.870968 | 23.313766 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.83871 | false | false | 12 |
a2f2dffc60b6d1d0100f2eed7a15037c9bb34298 | 20,925,080,723,071 | 4c19b724f95682ed21a82ab09b05556b5beea63c | /XMSYGame/java2/server/game-manager/src/main/java/com/xmsy/server/zxyy/game/modules/manager/hall/dao/HallDao.java | 4eea0fe1e5f6a44b7735b468207b6468044d3fb1 | [] | no_license | angel-like/angel | https://github.com/angel-like/angel | a66f8fda992fba01b81c128dd52b97c67f1ef027 | 3f7d79a61dc44a9c4547a60ab8648bc390c0f01e | refs/heads/master | 2023-03-11T03:14:49.059000 | 2022-11-17T11:35:37 | 2022-11-17T11:35:37 | 222,582,930 | 3 | 5 | null | false | 2023-02-22T05:29:45 | 2019-11-19T01:41:25 | 2022-03-24T16:11:47 | 2023-02-22T05:29:40 | 340,142 | 2 | 5 | 39 | JavaScript | false | false | package com.xmsy.server.zxyy.game.modules.manager.hall.dao;
import org.apache.ibatis.annotations.Mapper;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.xmsy.server.zxyy.game.modules.manager.hall.entity.HallEntity;
/**
*
*
* @author aleng
* @email xxxxx
* @date 2019-01-31 14:03:04
*/
@Mapper
public interface HallDao extends BaseMapper<HallEntity> {
Integer updateHallById(HallEntity entity);
}
| UTF-8 | Java | 428 | java | HallDao.java | Java | [
{
"context": "er.hall.entity.HallEntity;\n\n/**\n * \n * \n * @author aleng\n * @email xxxxx\n * @date 2019-01-31 14:03:04\n */\n",
"end": 260,
"score": 0.9978244304656982,
"start": 255,
"tag": "USERNAME",
"value": "aleng"
}
] | null | [] | package com.xmsy.server.zxyy.game.modules.manager.hall.dao;
import org.apache.ibatis.annotations.Mapper;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.xmsy.server.zxyy.game.modules.manager.hall.entity.HallEntity;
/**
*
*
* @author aleng
* @email xxxxx
* @date 2019-01-31 14:03:04
*/
@Mapper
public interface HallDao extends BaseMapper<HallEntity> {
Integer updateHallById(HallEntity entity);
}
| 428 | 0.754673 | 0.721963 | 21 | 19.380953 | 23.568495 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 12 |
6df3720c124eb76c19ed185b3a216edb799f735e | 17,033,840,332,271 | 0e2a7cd24f7fad810343898ed3bd5c3f3f7fc224 | /src/test/java/cloudblue/reports/ScreenShotTaker.java | 35e508e37d578f408df1ffc173ac1d16c8ff0432 | [] | no_license | nitish0026/CucumberProject | https://github.com/nitish0026/CucumberProject | caa0ba642205fa65ecc5c1707c0ffcb2ac36de01 | 3d10a45e28e702aea5c461d34bd52cbef9d5f163 | refs/heads/master | 2023-02-20T17:12:16.799000 | 2021-01-21T11:31:17 | 2021-01-21T11:31:17 | 331,591,111 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cloudblue.reports;
import cloudblue.utility.browser.Browser;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import cloudblue.utility.LogStatus;
import cloudblue.utility.LogUtil;
public class ScreenShotTaker{
private LogUtil logUtil;
public ScreenShotTaker(){
logUtil = new LogUtil();
}
public String takeBase64ScreenShot(){
if(Browser.getEventDriver() == null ){
logUtil.log(LogStatus.WARN,"Driver object is: " + Browser.getEventDriver());
return null;
} else{
return ((TakesScreenshot)Browser.getEventDriver()).getScreenshotAs(OutputType.BASE64);
}
}
} | UTF-8 | Java | 623 | java | ScreenShotTaker.java | Java | [] | null | [] | package cloudblue.reports;
import cloudblue.utility.browser.Browser;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import cloudblue.utility.LogStatus;
import cloudblue.utility.LogUtil;
public class ScreenShotTaker{
private LogUtil logUtil;
public ScreenShotTaker(){
logUtil = new LogUtil();
}
public String takeBase64ScreenShot(){
if(Browser.getEventDriver() == null ){
logUtil.log(LogStatus.WARN,"Driver object is: " + Browser.getEventDriver());
return null;
} else{
return ((TakesScreenshot)Browser.getEventDriver()).getScreenshotAs(OutputType.BASE64);
}
}
} | 623 | 0.76886 | 0.76244 | 23 | 26.130434 | 23.46191 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.478261 | false | false | 12 |
3bff9a6942ca0c1b2482dedddde0a15847f0a0d8 | 22,471,268,926,854 | 2ed0066c2292a4d8856f79ed694823403ff38c5b | /src/com/yida/core/base/service/StaffService.java | d5621c9d82ea64456dafed2cc83a81967a365575 | [] | no_license | kevin027/yd_ecms | https://github.com/kevin027/yd_ecms | 0bc0d2a7554d4f6fbae0cbb847ce5e74a143844f | 7ec73bbd31351d858644e28d27c8b57391a912c4 | refs/heads/master | 2020-06-05T12:57:56.678000 | 2015-05-12T10:04:10 | 2015-05-12T10:04:10 | 33,706,655 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.yida.core.base.service;
import com.tools.utils.Regexp;
import com.tools.utils.StringUtils;
import com.yida.core.base.entity.AuditOrg;
import com.yida.core.base.entity.Org;
import com.yida.core.base.entity.Staff;
import com.yida.core.base.vo.ListStaffForm;
import com.yida.core.base.vo.SaveStaffForm;
import com.tools.sys.PageInfo;
import com.yida.core.exception.EntityNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
@Service
public class StaffService extends BaseService {
public Map<String, String> getAllStaffIdAndName() {
return this.staffDao.getAllStaffIdAndName();
}
/**
* 获取人员列表
* @param query
* @param pageInfo
* @return
*/
public List<Staff> listStaff(ListStaffForm query, PageInfo pageInfo) {
StringBuffer sb = new StringBuffer("from " + staffDao.getTableName() + " o where 1=1");
List<Object> params = new ArrayList<Object>();
if (null != query) {
if (StringUtils.isMeaningFul(query.getAuditOrgId())) {
sb.append(" and o.id in (select mp.staffId from mp_staff_org mp where dbo.getAuditOrgIdByOrgId(mp.orgId) = ?)");
params.add(query.getAuditOrgId());
}
if (StringUtils.isMeaningFul(query.getStaffName())) {
sb.append(" and o.name like ?");
params.add("%" + query.getStaffName().trim() + "%");
}
if (null != query.getCreateDateFrom()) {
sb.append(" and o.createDate > ?");
params.add(query.getCreateDateFrom());
}
if (null != query.getCreateDateTo()) {
Calendar delayCalendar = Calendar.getInstance();
delayCalendar.setTime(query.getCreateDateTo());
delayCalendar.add(Calendar.DAY_OF_YEAR, 1);
sb.append(" and o.createDate < ?");
params.add(delayCalendar.getTime());
}
if (null != query.getOrgId() && !"".equals(query.getOrgId())) {
Org org = this.orgDao.get(query.getOrgId());
if (null != org) {
sb.append(" and o.id in (select mp.staffId from mp_staff_org mp where mp.orgId in (");
List<Org> stack = new ArrayList<Org>();
stack.add(0, org);
while (!stack.isEmpty()) {
org = stack.remove(0);
if (null != org.getChildren() && 0 < org.getChildren().size()) {
stack.addAll(0, org.getChildren());
}
if (0 == stack.size()) {
sb.append("?");
} else {
sb.append("?,");
}
params.add(org.getId());
}
sb.append("))");
}
}
}
if (null != pageInfo) {
int total = staffDao.findCountBySql("select count(distinct o.id) " + sb, params.toArray());
pageInfo.setTotalResult(total);
}
List<Staff> list = staffDao.findListBySql("select o.* " + sb.toString(), params.toArray(), pageInfo);
return list;
}
/**
* 跟据人员ID获取人员对象
* @param staffId
* @return
*/
public Staff getStaffById(String staffId) {
return this.staffDao.get(staffId);
}
/**
* 保存人员
* @param saveStaffForm
*/
@Transactional
private Staff validImportField(SaveStaffForm saveStaffForm) {
Staff staff = new Staff();
// 用户ID
if (StringUtils.isMeaningFul(saveStaffForm.getStaffId())) {
staff.setId(saveStaffForm.getStaffId());
}
// 用户名处理
String staffName = StringUtils.notNull(saveStaffForm.getName()).trim();
if (0 == staffName.length()) {
throw new IllegalStateException("名字不能为空");
}
if (staffDao.staffNameIsExists(saveStaffForm.getName(), saveStaffForm.getStaffId())) {
throw new IllegalStateException("名字已经被使用");
}
staff.setName(staffName);
// 电子邮件处理
String email = StringUtils.notNull(saveStaffForm.getEmail()).trim();
if (0 != email.length()) {
if (!Regexp.EMAIL.validate(email)) {
throw new IllegalStateException("电子邮箱格式错误");
}
}
staff.setEmail(email);
// 手机号码处理
String phone = StringUtils.notNull(saveStaffForm.getPhone()).trim();
if (0 != phone.length()) {
if (!Regexp.PHONE_NO.validate(phone)) {
throw new IllegalStateException("手机号码格式错误");
}
}
staff.setPhone(phone);
// 所属组织机构
if (StringUtils.isMeaningFul(saveStaffForm.getOrgIds())) {
String[] tempOrgId = saveStaffForm.getOrgIds().split(",");
if (1 == tempOrgId.length) {
throw new IllegalStateException("请选择一个所属部门。");
}
List<Org> list = new ArrayList<Org>(tempOrgId.length);
list.add(new Org(tempOrgId[tempOrgId.length-1]));
staff.setOrgs(list);
} else {
throw new IllegalStateException("没有确定所属的部门机构");
}
staff.setSex(saveStaffForm.getSex());
staff.setRemark(saveStaffForm.getRemark());
return staff;
}
@Transactional
public Staff saveStaff(SaveStaffForm saveStaffForm) {
if (!StringUtils.isMeaningFul(saveStaffForm.getStaffId())) {
Staff staff = this.validImportField(saveStaffForm);
staff.setCreateDate(new Date());
staff.setInvalid(Boolean.FALSE);
this.staffDao.persist(staff);
return staff;
}
throw new IllegalStateException("提交数据有误,已经包含人员ID");
}
/**
* 修改人员信息
* @param saveStaffForm
*/
@Transactional
public Staff updateStaff(SaveStaffForm saveStaffForm) {
if (StringUtils.isMeaningFul(saveStaffForm.getStaffId())) {
Staff staff = this.validImportField(saveStaffForm);
Staff old = this.staffDao.get(saveStaffForm.getStaffId());
old.setName(staff.getName());
old.setSex(staff.getSex());
old.setEmail(staff.getEmail());
old.setPhone(staff.getPhone());
old.setRemark(staff.getRemark());
old.setOrgs(staff.getOrgs());
return staff;
}
throw new IllegalStateException("提交数据有误,没有包含人员ID");
}
/**
* 根据ID删除人员信息
* @param staffId
*/
@Transactional
public void deleteStaffById(String staffId) {
Staff staff = staffDao.get(staffId);
if (null == staff) {
throw new EntityNotFoundException(Staff.class, staffId);
}
staff.setOrgs(null);
staff.setAccounts(null);
staffDao.remove(staff);
}
/**
* 根据ID删除人员信息(复选)
* @param staffIds
*/
@Transactional
public void deleteStaffByIds(List<String> staffIds) {
if (null == staffIds) throw new IllegalStateException("");
if (null != staffIds) {
for (String staffId : staffIds) {
if (StringUtils.isMeaningFul(staffId)) {
this.deleteStaffById(staffId);
}
}
}
}
/**
* 根据组织机构ID获取人员信息
* @param orgId
* @return
*/
public List<Staff> findStaffByOrgId(String orgId) {
return staffDao.findStaffByOrgId(orgId);
}
public AuditOrg getAuditOrgForStaff(Staff loginStaff) {
if (null != loginStaff && null != loginStaff.getOrgs() && 0 < loginStaff.getOrgs().size()) {
Org org = loginStaff.getOrgs().get(0);
if (null == org) return null;
while (null != org.getParent()) {
org = org.getParent();
}
return auditOrgDao.get(org.getId());
}
return null;
}
public List<Staff> listStaffByStaffIds(String staffIds) {
if (!StringUtils.isMeaningFul(staffIds)) return new ArrayList<>(0);
return this.staffDao.listStaffByStaffIds(staffIds);
}
}
| UTF-8 | Java | 7,169 | java | StaffService.java | Java | [] | null | [] | package com.yida.core.base.service;
import com.tools.utils.Regexp;
import com.tools.utils.StringUtils;
import com.yida.core.base.entity.AuditOrg;
import com.yida.core.base.entity.Org;
import com.yida.core.base.entity.Staff;
import com.yida.core.base.vo.ListStaffForm;
import com.yida.core.base.vo.SaveStaffForm;
import com.tools.sys.PageInfo;
import com.yida.core.exception.EntityNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
@Service
public class StaffService extends BaseService {
public Map<String, String> getAllStaffIdAndName() {
return this.staffDao.getAllStaffIdAndName();
}
/**
* 获取人员列表
* @param query
* @param pageInfo
* @return
*/
public List<Staff> listStaff(ListStaffForm query, PageInfo pageInfo) {
StringBuffer sb = new StringBuffer("from " + staffDao.getTableName() + " o where 1=1");
List<Object> params = new ArrayList<Object>();
if (null != query) {
if (StringUtils.isMeaningFul(query.getAuditOrgId())) {
sb.append(" and o.id in (select mp.staffId from mp_staff_org mp where dbo.getAuditOrgIdByOrgId(mp.orgId) = ?)");
params.add(query.getAuditOrgId());
}
if (StringUtils.isMeaningFul(query.getStaffName())) {
sb.append(" and o.name like ?");
params.add("%" + query.getStaffName().trim() + "%");
}
if (null != query.getCreateDateFrom()) {
sb.append(" and o.createDate > ?");
params.add(query.getCreateDateFrom());
}
if (null != query.getCreateDateTo()) {
Calendar delayCalendar = Calendar.getInstance();
delayCalendar.setTime(query.getCreateDateTo());
delayCalendar.add(Calendar.DAY_OF_YEAR, 1);
sb.append(" and o.createDate < ?");
params.add(delayCalendar.getTime());
}
if (null != query.getOrgId() && !"".equals(query.getOrgId())) {
Org org = this.orgDao.get(query.getOrgId());
if (null != org) {
sb.append(" and o.id in (select mp.staffId from mp_staff_org mp where mp.orgId in (");
List<Org> stack = new ArrayList<Org>();
stack.add(0, org);
while (!stack.isEmpty()) {
org = stack.remove(0);
if (null != org.getChildren() && 0 < org.getChildren().size()) {
stack.addAll(0, org.getChildren());
}
if (0 == stack.size()) {
sb.append("?");
} else {
sb.append("?,");
}
params.add(org.getId());
}
sb.append("))");
}
}
}
if (null != pageInfo) {
int total = staffDao.findCountBySql("select count(distinct o.id) " + sb, params.toArray());
pageInfo.setTotalResult(total);
}
List<Staff> list = staffDao.findListBySql("select o.* " + sb.toString(), params.toArray(), pageInfo);
return list;
}
/**
* 跟据人员ID获取人员对象
* @param staffId
* @return
*/
public Staff getStaffById(String staffId) {
return this.staffDao.get(staffId);
}
/**
* 保存人员
* @param saveStaffForm
*/
@Transactional
private Staff validImportField(SaveStaffForm saveStaffForm) {
Staff staff = new Staff();
// 用户ID
if (StringUtils.isMeaningFul(saveStaffForm.getStaffId())) {
staff.setId(saveStaffForm.getStaffId());
}
// 用户名处理
String staffName = StringUtils.notNull(saveStaffForm.getName()).trim();
if (0 == staffName.length()) {
throw new IllegalStateException("名字不能为空");
}
if (staffDao.staffNameIsExists(saveStaffForm.getName(), saveStaffForm.getStaffId())) {
throw new IllegalStateException("名字已经被使用");
}
staff.setName(staffName);
// 电子邮件处理
String email = StringUtils.notNull(saveStaffForm.getEmail()).trim();
if (0 != email.length()) {
if (!Regexp.EMAIL.validate(email)) {
throw new IllegalStateException("电子邮箱格式错误");
}
}
staff.setEmail(email);
// 手机号码处理
String phone = StringUtils.notNull(saveStaffForm.getPhone()).trim();
if (0 != phone.length()) {
if (!Regexp.PHONE_NO.validate(phone)) {
throw new IllegalStateException("手机号码格式错误");
}
}
staff.setPhone(phone);
// 所属组织机构
if (StringUtils.isMeaningFul(saveStaffForm.getOrgIds())) {
String[] tempOrgId = saveStaffForm.getOrgIds().split(",");
if (1 == tempOrgId.length) {
throw new IllegalStateException("请选择一个所属部门。");
}
List<Org> list = new ArrayList<Org>(tempOrgId.length);
list.add(new Org(tempOrgId[tempOrgId.length-1]));
staff.setOrgs(list);
} else {
throw new IllegalStateException("没有确定所属的部门机构");
}
staff.setSex(saveStaffForm.getSex());
staff.setRemark(saveStaffForm.getRemark());
return staff;
}
@Transactional
public Staff saveStaff(SaveStaffForm saveStaffForm) {
if (!StringUtils.isMeaningFul(saveStaffForm.getStaffId())) {
Staff staff = this.validImportField(saveStaffForm);
staff.setCreateDate(new Date());
staff.setInvalid(Boolean.FALSE);
this.staffDao.persist(staff);
return staff;
}
throw new IllegalStateException("提交数据有误,已经包含人员ID");
}
/**
* 修改人员信息
* @param saveStaffForm
*/
@Transactional
public Staff updateStaff(SaveStaffForm saveStaffForm) {
if (StringUtils.isMeaningFul(saveStaffForm.getStaffId())) {
Staff staff = this.validImportField(saveStaffForm);
Staff old = this.staffDao.get(saveStaffForm.getStaffId());
old.setName(staff.getName());
old.setSex(staff.getSex());
old.setEmail(staff.getEmail());
old.setPhone(staff.getPhone());
old.setRemark(staff.getRemark());
old.setOrgs(staff.getOrgs());
return staff;
}
throw new IllegalStateException("提交数据有误,没有包含人员ID");
}
/**
* 根据ID删除人员信息
* @param staffId
*/
@Transactional
public void deleteStaffById(String staffId) {
Staff staff = staffDao.get(staffId);
if (null == staff) {
throw new EntityNotFoundException(Staff.class, staffId);
}
staff.setOrgs(null);
staff.setAccounts(null);
staffDao.remove(staff);
}
/**
* 根据ID删除人员信息(复选)
* @param staffIds
*/
@Transactional
public void deleteStaffByIds(List<String> staffIds) {
if (null == staffIds) throw new IllegalStateException("");
if (null != staffIds) {
for (String staffId : staffIds) {
if (StringUtils.isMeaningFul(staffId)) {
this.deleteStaffById(staffId);
}
}
}
}
/**
* 根据组织机构ID获取人员信息
* @param orgId
* @return
*/
public List<Staff> findStaffByOrgId(String orgId) {
return staffDao.findStaffByOrgId(orgId);
}
public AuditOrg getAuditOrgForStaff(Staff loginStaff) {
if (null != loginStaff && null != loginStaff.getOrgs() && 0 < loginStaff.getOrgs().size()) {
Org org = loginStaff.getOrgs().get(0);
if (null == org) return null;
while (null != org.getParent()) {
org = org.getParent();
}
return auditOrgDao.get(org.getId());
}
return null;
}
public List<Staff> listStaffByStaffIds(String staffIds) {
if (!StringUtils.isMeaningFul(staffIds)) return new ArrayList<>(0);
return this.staffDao.listStaffByStaffIds(staffIds);
}
}
| 7,169 | 0.674106 | 0.671772 | 251 | 26.310757 | 23.895336 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.553785 | false | false | 12 |
88b005c74dc4d1b48ba2729e906bdbd2ecbbd38b | 51,539,676,405 | ae4a741d99ca34e52c3ccb90208c8f74f441770b | /src/test/java/org/ihtsdo/buildcloud/core/service/build/database/Rf2FileWriterTest.java | 7c176c2dfe8c91497d4470fde37d8b06f05d4c91 | [
"Apache-2.0"
] | permissive | IHTSDO/snomed-release-service | https://github.com/IHTSDO/snomed-release-service | bdd1f888ec0f313d44df3eb5f7b92adb6dc12f3f | 64952be93b2831ec0580d09415f39e26dc275418 | refs/heads/master | 2023-08-25T11:46:31.960000 | 2023-07-07T12:22:32 | 2023-07-07T12:22:32 | 15,286,965 | 6 | 5 | Apache-2.0 | false | 2023-03-03T09:13:47 | 2013-12-18T15:40:00 | 2022-09-21T18:45:08 | 2023-03-03T09:13:45 | 64,877 | 6 | 5 | 1 | Java | false | false | package org.ihtsdo.buildcloud.core.service.build.database;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import org.ihtsdo.buildcloud.core.service.build.RF2Constants;
import org.ihtsdo.buildcloud.core.service.build.database.map.RF2TableExportDAOImpl;
import org.ihtsdo.buildcloud.test.StreamTestUtils;
import org.ihtsdo.snomed.util.rf2.schema.TableSchema;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class Rf2FileWriterTest {
private static final String PREVIOUS_EXTENDED_MAP_REFSET_FULL = "der2_iisssccRefset_ExtendedMapFull_INT_20140131.txt";
private static final String PREVIOUS_RELEASE_DATE = "20130630";
private static final String RELEASE_DATE = "20130930";
private static final String PREVIOUS_SIMPLE_REFSET_FULL = "der2_Refset_SimpleFull_INT_20130630.txt";
private static final String EXPECTED_SIMPLE_SNAPSHOT_INT_20130630 = "expected-der2_Refset_SimpleSnapshot_INT_20130630.txt";
private static final String EXPECTED_REFSET_SIMPLE_SNAPSHOT_20130930 = "expected-der2_Refset_SimpleSnapshot_INT_20130930.txt";
private static final String EXPECTED_REFSET_SIMPLE_FULL_20130930 = "expected-der2_Refset_SimpleFull_INT_20130930.txt";
private static final String SIMPLE_REFSET_FULL_PLUS_DELTA = "der2_Refset_SimpleFullPlusDelta_INT_20130930.txt";
private static final String CURRENT_SIMPLE_REFSET_DELTA = "der2_Refset_SimpleDelta_INT_20130930.txt";
private static final String CURRENT_EXTENDED_MAP_REFSET_DELTA = "der2_iisssccRefset_ExtendedMapDelta_INT_20140731.txt";
private static final String EXPECTED_EXTENDED_MAP_SNAPSHOT_INT = "expected-der2_iisssccRefset_ExtendedMapSnapshot_INT_20140731.txt";
private static final String EXPECTED_EXTENDED_MAP_FULL_20140731 = "expected-der2_iisssccRefset_ExtendedMapFull_INT_20140731.txt";
private TableSchema tableSchema;
private Rf2FileWriter rf2FileWriter;
private ByteArrayOutputStream fullOutputStream;
private ByteArrayOutputStream snapshotOutputStream;
private ByteArrayOutputStream deltaOutputStream;
private RF2TableExportDAO rf2TableDAO;
@BeforeEach
public void setUp() throws Exception {
rf2TableDAO = new RF2TableExportDAOImpl( null);
rf2FileWriter = new Rf2FileWriter();
fullOutputStream = new ByteArrayOutputStream();
snapshotOutputStream = new ByteArrayOutputStream();
deltaOutputStream = new ByteArrayOutputStream();
}
/** Testing simple refset export using full plus delta file
* @throws Exception
*/
@Test
public void testSimpleRefsetExportFullAndSnapshot() throws Exception {
// Prepare test object for this test
tableSchema = rf2TableDAO.createTable(SIMPLE_REFSET_FULL_PLUS_DELTA, getClass().getResourceAsStream(SIMPLE_REFSET_FULL_PLUS_DELTA), false);
RF2TableResults tableResults = rf2TableDAO.selectAllOrdered(tableSchema);
// Run target test method
rf2FileWriter.exportFullAndSnapshot(tableResults, tableSchema, RF2Constants.DATE_FORMAT.parse(RELEASE_DATE), fullOutputStream, snapshotOutputStream);
// Assert expectations
StreamTestUtils.assertStreamsEqualLineByLine(getClass().getResourceAsStream(EXPECTED_REFSET_SIMPLE_FULL_20130930), new ByteArrayInputStream(fullOutputStream.toByteArray()));
StreamTestUtils.assertStreamsEqualLineByLine(getClass().getResourceAsStream(EXPECTED_REFSET_SIMPLE_SNAPSHOT_20130930), new ByteArrayInputStream(snapshotOutputStream.toByteArray()));
}
@Test
public void testSimpleRefsetExportDelta() throws Exception {
// Prepare test object for this test
tableSchema = rf2TableDAO.createTable(CURRENT_SIMPLE_REFSET_DELTA, getClass().getResourceAsStream(CURRENT_SIMPLE_REFSET_DELTA), false);
RF2TableResults tableResults = rf2TableDAO.selectAllOrdered(tableSchema);
// Run target test method
rf2FileWriter.exportDelta(tableResults, tableSchema, deltaOutputStream);
// Assert expectations
StreamTestUtils.assertStreamsEqualLineByLine(getClass().getResourceAsStream(CURRENT_SIMPLE_REFSET_DELTA), new ByteArrayInputStream(deltaOutputStream.toByteArray()));
}
/** Testing simple refset export using previous file and delta file
* @throws Exception
*/
@Test
public void testSimpleRefsetExportWithAppendData() throws Exception {
tableSchema = rf2TableDAO.createTable(PREVIOUS_SIMPLE_REFSET_FULL, getClass().getResourceAsStream(PREVIOUS_SIMPLE_REFSET_FULL), false);
rf2TableDAO.appendData(tableSchema, getClass().getResourceAsStream(CURRENT_SIMPLE_REFSET_DELTA), false);
RF2TableResults tableResults = rf2TableDAO.selectAllOrdered(tableSchema);
rf2FileWriter.exportFullAndSnapshot(tableResults, tableSchema, RF2Constants.DATE_FORMAT.parse(RELEASE_DATE), fullOutputStream, snapshotOutputStream);
StreamTestUtils.assertStreamsEqualLineByLine(getClass().getResourceAsStream(EXPECTED_REFSET_SIMPLE_FULL_20130930), new ByteArrayInputStream(fullOutputStream.toByteArray()));
StreamTestUtils.assertStreamsEqualLineByLine(getClass().getResourceAsStream(EXPECTED_REFSET_SIMPLE_SNAPSHOT_20130930), new ByteArrayInputStream(snapshotOutputStream.toByteArray()));
}
/**Snapshot file only contains the most recent entries up to the current release date.
* No history and no future dated entries.
* @throws Exception
*/
@Test
public void testSimpleRefsetSnapshotExportUsingPreviousReleaseDate() throws Exception {
tableSchema = rf2TableDAO.createTable(SIMPLE_REFSET_FULL_PLUS_DELTA, getClass().getResourceAsStream(SIMPLE_REFSET_FULL_PLUS_DELTA), false);
RF2TableResults tableResults = rf2TableDAO.selectAllOrdered(tableSchema);
rf2FileWriter.exportFullAndSnapshot(tableResults, tableSchema, RF2Constants.DATE_FORMAT.parse(PREVIOUS_RELEASE_DATE), fullOutputStream, snapshotOutputStream);
StreamTestUtils.assertStreamsEqualLineByLine(getClass().getResourceAsStream(EXPECTED_SIMPLE_SNAPSHOT_INT_20130630), new ByteArrayInputStream(snapshotOutputStream.toByteArray()));
}
@Test
public void testExtendedMapRefsetExport() throws Exception {
tableSchema = rf2TableDAO.createTable(PREVIOUS_EXTENDED_MAP_REFSET_FULL, getClass().getResourceAsStream(PREVIOUS_EXTENDED_MAP_REFSET_FULL), false);
rf2TableDAO.appendData(tableSchema, getClass().getResourceAsStream(CURRENT_EXTENDED_MAP_REFSET_DELTA), false);
RF2TableResults tableResults = rf2TableDAO.selectAllOrdered(tableSchema);
rf2FileWriter.exportFullAndSnapshot(tableResults, tableSchema, RF2Constants.DATE_FORMAT.parse("20140731"), fullOutputStream, snapshotOutputStream);
StreamTestUtils.assertStreamsEqualLineByLine(getClass().getResourceAsStream(EXPECTED_EXTENDED_MAP_SNAPSHOT_INT), new ByteArrayInputStream(snapshotOutputStream.toByteArray()));
StreamTestUtils.assertStreamsEqualLineByLine(getClass().getResourceAsStream(EXPECTED_EXTENDED_MAP_FULL_20140731), new ByteArrayInputStream(fullOutputStream.toByteArray()));
}
@AfterEach
public void tearDown() throws Exception {
rf2TableDAO.closeConnection();
}
}
| UTF-8 | Java | 6,924 | java | Rf2FileWriterTest.java | Java | [] | null | [] | package org.ihtsdo.buildcloud.core.service.build.database;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import org.ihtsdo.buildcloud.core.service.build.RF2Constants;
import org.ihtsdo.buildcloud.core.service.build.database.map.RF2TableExportDAOImpl;
import org.ihtsdo.buildcloud.test.StreamTestUtils;
import org.ihtsdo.snomed.util.rf2.schema.TableSchema;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class Rf2FileWriterTest {
private static final String PREVIOUS_EXTENDED_MAP_REFSET_FULL = "der2_iisssccRefset_ExtendedMapFull_INT_20140131.txt";
private static final String PREVIOUS_RELEASE_DATE = "20130630";
private static final String RELEASE_DATE = "20130930";
private static final String PREVIOUS_SIMPLE_REFSET_FULL = "der2_Refset_SimpleFull_INT_20130630.txt";
private static final String EXPECTED_SIMPLE_SNAPSHOT_INT_20130630 = "expected-der2_Refset_SimpleSnapshot_INT_20130630.txt";
private static final String EXPECTED_REFSET_SIMPLE_SNAPSHOT_20130930 = "expected-der2_Refset_SimpleSnapshot_INT_20130930.txt";
private static final String EXPECTED_REFSET_SIMPLE_FULL_20130930 = "expected-der2_Refset_SimpleFull_INT_20130930.txt";
private static final String SIMPLE_REFSET_FULL_PLUS_DELTA = "der2_Refset_SimpleFullPlusDelta_INT_20130930.txt";
private static final String CURRENT_SIMPLE_REFSET_DELTA = "der2_Refset_SimpleDelta_INT_20130930.txt";
private static final String CURRENT_EXTENDED_MAP_REFSET_DELTA = "der2_iisssccRefset_ExtendedMapDelta_INT_20140731.txt";
private static final String EXPECTED_EXTENDED_MAP_SNAPSHOT_INT = "expected-der2_iisssccRefset_ExtendedMapSnapshot_INT_20140731.txt";
private static final String EXPECTED_EXTENDED_MAP_FULL_20140731 = "expected-der2_iisssccRefset_ExtendedMapFull_INT_20140731.txt";
private TableSchema tableSchema;
private Rf2FileWriter rf2FileWriter;
private ByteArrayOutputStream fullOutputStream;
private ByteArrayOutputStream snapshotOutputStream;
private ByteArrayOutputStream deltaOutputStream;
private RF2TableExportDAO rf2TableDAO;
@BeforeEach
public void setUp() throws Exception {
rf2TableDAO = new RF2TableExportDAOImpl( null);
rf2FileWriter = new Rf2FileWriter();
fullOutputStream = new ByteArrayOutputStream();
snapshotOutputStream = new ByteArrayOutputStream();
deltaOutputStream = new ByteArrayOutputStream();
}
/** Testing simple refset export using full plus delta file
* @throws Exception
*/
@Test
public void testSimpleRefsetExportFullAndSnapshot() throws Exception {
// Prepare test object for this test
tableSchema = rf2TableDAO.createTable(SIMPLE_REFSET_FULL_PLUS_DELTA, getClass().getResourceAsStream(SIMPLE_REFSET_FULL_PLUS_DELTA), false);
RF2TableResults tableResults = rf2TableDAO.selectAllOrdered(tableSchema);
// Run target test method
rf2FileWriter.exportFullAndSnapshot(tableResults, tableSchema, RF2Constants.DATE_FORMAT.parse(RELEASE_DATE), fullOutputStream, snapshotOutputStream);
// Assert expectations
StreamTestUtils.assertStreamsEqualLineByLine(getClass().getResourceAsStream(EXPECTED_REFSET_SIMPLE_FULL_20130930), new ByteArrayInputStream(fullOutputStream.toByteArray()));
StreamTestUtils.assertStreamsEqualLineByLine(getClass().getResourceAsStream(EXPECTED_REFSET_SIMPLE_SNAPSHOT_20130930), new ByteArrayInputStream(snapshotOutputStream.toByteArray()));
}
@Test
public void testSimpleRefsetExportDelta() throws Exception {
// Prepare test object for this test
tableSchema = rf2TableDAO.createTable(CURRENT_SIMPLE_REFSET_DELTA, getClass().getResourceAsStream(CURRENT_SIMPLE_REFSET_DELTA), false);
RF2TableResults tableResults = rf2TableDAO.selectAllOrdered(tableSchema);
// Run target test method
rf2FileWriter.exportDelta(tableResults, tableSchema, deltaOutputStream);
// Assert expectations
StreamTestUtils.assertStreamsEqualLineByLine(getClass().getResourceAsStream(CURRENT_SIMPLE_REFSET_DELTA), new ByteArrayInputStream(deltaOutputStream.toByteArray()));
}
/** Testing simple refset export using previous file and delta file
* @throws Exception
*/
@Test
public void testSimpleRefsetExportWithAppendData() throws Exception {
tableSchema = rf2TableDAO.createTable(PREVIOUS_SIMPLE_REFSET_FULL, getClass().getResourceAsStream(PREVIOUS_SIMPLE_REFSET_FULL), false);
rf2TableDAO.appendData(tableSchema, getClass().getResourceAsStream(CURRENT_SIMPLE_REFSET_DELTA), false);
RF2TableResults tableResults = rf2TableDAO.selectAllOrdered(tableSchema);
rf2FileWriter.exportFullAndSnapshot(tableResults, tableSchema, RF2Constants.DATE_FORMAT.parse(RELEASE_DATE), fullOutputStream, snapshotOutputStream);
StreamTestUtils.assertStreamsEqualLineByLine(getClass().getResourceAsStream(EXPECTED_REFSET_SIMPLE_FULL_20130930), new ByteArrayInputStream(fullOutputStream.toByteArray()));
StreamTestUtils.assertStreamsEqualLineByLine(getClass().getResourceAsStream(EXPECTED_REFSET_SIMPLE_SNAPSHOT_20130930), new ByteArrayInputStream(snapshotOutputStream.toByteArray()));
}
/**Snapshot file only contains the most recent entries up to the current release date.
* No history and no future dated entries.
* @throws Exception
*/
@Test
public void testSimpleRefsetSnapshotExportUsingPreviousReleaseDate() throws Exception {
tableSchema = rf2TableDAO.createTable(SIMPLE_REFSET_FULL_PLUS_DELTA, getClass().getResourceAsStream(SIMPLE_REFSET_FULL_PLUS_DELTA), false);
RF2TableResults tableResults = rf2TableDAO.selectAllOrdered(tableSchema);
rf2FileWriter.exportFullAndSnapshot(tableResults, tableSchema, RF2Constants.DATE_FORMAT.parse(PREVIOUS_RELEASE_DATE), fullOutputStream, snapshotOutputStream);
StreamTestUtils.assertStreamsEqualLineByLine(getClass().getResourceAsStream(EXPECTED_SIMPLE_SNAPSHOT_INT_20130630), new ByteArrayInputStream(snapshotOutputStream.toByteArray()));
}
@Test
public void testExtendedMapRefsetExport() throws Exception {
tableSchema = rf2TableDAO.createTable(PREVIOUS_EXTENDED_MAP_REFSET_FULL, getClass().getResourceAsStream(PREVIOUS_EXTENDED_MAP_REFSET_FULL), false);
rf2TableDAO.appendData(tableSchema, getClass().getResourceAsStream(CURRENT_EXTENDED_MAP_REFSET_DELTA), false);
RF2TableResults tableResults = rf2TableDAO.selectAllOrdered(tableSchema);
rf2FileWriter.exportFullAndSnapshot(tableResults, tableSchema, RF2Constants.DATE_FORMAT.parse("20140731"), fullOutputStream, snapshotOutputStream);
StreamTestUtils.assertStreamsEqualLineByLine(getClass().getResourceAsStream(EXPECTED_EXTENDED_MAP_SNAPSHOT_INT), new ByteArrayInputStream(snapshotOutputStream.toByteArray()));
StreamTestUtils.assertStreamsEqualLineByLine(getClass().getResourceAsStream(EXPECTED_EXTENDED_MAP_FULL_20140731), new ByteArrayInputStream(fullOutputStream.toByteArray()));
}
@AfterEach
public void tearDown() throws Exception {
rf2TableDAO.closeConnection();
}
}
| 6,924 | 0.820046 | 0.786395 | 121 | 56.223141 | 56.044624 | 186 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.735537 | false | false | 12 |
f3a430dd229b0f78d5d2880735496c5facea3bea | 19,189,913,922,146 | 9e7d9dca2767575a85ee2495a187aba84aaaee87 | /dc3-device/dc3-group/src/main/java/com/pnoker/device/group/receive/wia/WiaReceiveThread.java | 791f88b0b4de51785fbabe0667fdfcc8f3f066b2 | [
"Apache-2.0"
] | permissive | lykknd/iot-dc3 | https://github.com/lykknd/iot-dc3 | f6a8b29ff071e7e40b8ce496a9fda401e91bb674 | be15222340fb466eb34e9d621fc63a5fb7dfb688 | refs/heads/master | 2020-07-18T17:01:13.878000 | 2019-09-02T12:47:19 | 2019-09-02T12:47:19 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.pnoker.device.group.receive.wia;
import com.pnoker.device.group.bean.wia.MyGateway;
import com.pnoker.device.group.util.DatagramUtils;
import com.pnoker.device.group.util.PackageProcessor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
/**
* <p>Copyright(c) 2019. Pnoker All Rights Reserved.
* <p>Author : Pnoker
* <p>Email : pnokers@gmail.com
* <p>Description:
*/
@Data
@Slf4j
public class WiaReceiveThread implements Runnable {
private MyGateway myGateway;
public WiaReceiveThread(MyGateway myGateway) {
this.myGateway = myGateway;
}
@Override
public void run() {
sendDatagram();
try {
myGateway.getDatagramSocket().receive(myGateway.getDatagramReceive());
} catch (IOException e) {
log.error("receive datagram timeout", e);
}
byte[] receive = myGateway.getDatagramReceive().getData();
PackageProcessor processor = new PackageProcessor(receive);
String hexDatagram = DatagramUtils.hexDatagram(receive, receive.length);
String dataHead = processor.bytesToString(0, 1);
switch (dataHead) {
case "0101":
log.info("网络报文:{}", hexDatagram);
break;
case "0111":
log.info("统计报文:{}", hexDatagram);
break;
case "010f":
log.info("健康报文:{}", hexDatagram);
break;
case "0183":
log.info("数据报文:{}", hexDatagram);
break;
default:
log.info("其他报文:{}", hexDatagram);
break;
}
}
public void sendDatagram() {
try {
myGateway.getDatagramSocket().send(myGateway.getDatagramSend());
} catch (IOException e) {
log.error("send datagram fail", e);
}
}
}
| UTF-8 | Java | 1,948 | java | WiaReceiveThread.java | Java | [
{
"context": "19. Pnoker All Rights Reserved.\n * <p>Author : Pnoker\n * <p>Email : pnokers@gmail.com\n * <p>Descri",
"end": 368,
"score": 0.9995930790901184,
"start": 362,
"tag": "USERNAME",
"value": "Pnoker"
},
{
"context": "rved.\n * <p>Author : Pnoker\n * <p>Email ... | null | [] | package com.pnoker.device.group.receive.wia;
import com.pnoker.device.group.bean.wia.MyGateway;
import com.pnoker.device.group.util.DatagramUtils;
import com.pnoker.device.group.util.PackageProcessor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
/**
* <p>Copyright(c) 2019. Pnoker All Rights Reserved.
* <p>Author : Pnoker
* <p>Email : <EMAIL>
* <p>Description:
*/
@Data
@Slf4j
public class WiaReceiveThread implements Runnable {
private MyGateway myGateway;
public WiaReceiveThread(MyGateway myGateway) {
this.myGateway = myGateway;
}
@Override
public void run() {
sendDatagram();
try {
myGateway.getDatagramSocket().receive(myGateway.getDatagramReceive());
} catch (IOException e) {
log.error("receive datagram timeout", e);
}
byte[] receive = myGateway.getDatagramReceive().getData();
PackageProcessor processor = new PackageProcessor(receive);
String hexDatagram = DatagramUtils.hexDatagram(receive, receive.length);
String dataHead = processor.bytesToString(0, 1);
switch (dataHead) {
case "0101":
log.info("网络报文:{}", hexDatagram);
break;
case "0111":
log.info("统计报文:{}", hexDatagram);
break;
case "010f":
log.info("健康报文:{}", hexDatagram);
break;
case "0183":
log.info("数据报文:{}", hexDatagram);
break;
default:
log.info("其他报文:{}", hexDatagram);
break;
}
}
public void sendDatagram() {
try {
myGateway.getDatagramSocket().send(myGateway.getDatagramSend());
} catch (IOException e) {
log.error("send datagram fail", e);
}
}
}
| 1,938 | 0.580713 | 0.568134 | 65 | 28.353846 | 21.799387 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.569231 | false | false | 12 |
2d6f8b0e5354b2e6f4abb7cdaf8464eda12e5d08 | 21,466,246,567,145 | fa3a50066fde4d0ef5e1965838da8159868cee2b | /JPASandbox/src/models/Role.java | e017312d70b2d23d43efc8f78b22c9097a14c8a0 | [] | no_license | noflaxe/JavaEE | https://github.com/noflaxe/JavaEE | c6cb8ad65c30839c88c087beab6b1134180583ce | 75f366b053eeabd8e12697a09b788872ef565c55 | refs/heads/master | 2021-01-19T22:01:34.905000 | 2014-04-01T11:53:41 | 2014-04-01T11:53:41 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package models;
import javax.persistence.*;
/**
* Created with IntelliJ IDEA.
* User: noflaxe
* Date: 20.07.13
* Time: 13:10
* To change this template use File | Settings | File Templates.
*/
@Entity
@Table(name="ROLES")
@NamedQueries({
@NamedQuery(name="Role.findByAll",query = "FROM Role where login =:login")
})
public class Role {
@Id
@GeneratedValue(strategy= GenerationType.SEQUENCE, generator="SEQ_GEN")
@SequenceGenerator(name="SEQ_GEN", sequenceName="ID_SEQ", allocationSize=1)
@Column(name="ROLE_ID")
private long roleId;
@Column(name="LOGIN")
private String login;
@Column(name="PASSWORD")
private String password;
@Column(name="ROLE")
private String role;
@OneToOne(mappedBy="role")
private Worker worker;
public Worker getWorker() {
return worker;
}
public void setWorker(Worker worker) {
this.worker = worker;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Role role = (Role) o;
if (login != null ? !login.equals(role.login) : role.login != null) return false;
if (password != null ? !password.equals(role.password) : role.password != null) return false;
return true;
}
@Override
public int hashCode() {
int result = login != null ? login.hashCode() : 0;
result = 31 * result + (password != null ? password.hashCode() : 0);
return result;
}
public Role() {
}
public long getRoleId() {
return roleId;
}
public void setRoleId(long roleId) {
this.roleId = roleId;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
| UTF-8 | Java | 2,124 | java | Role.java | Java | [
{
"context": "ce.*;\n\n/**\n * Created with IntelliJ IDEA.\n * User: noflaxe\n * Date: 20.07.13\n * Time: 13:10\n * To change thi",
"end": 97,
"score": 0.9996362924575806,
"start": 90,
"tag": "USERNAME",
"value": "noflaxe"
},
{
"context": "assword(String password) {\n this.pas... | null | [] | package models;
import javax.persistence.*;
/**
* Created with IntelliJ IDEA.
* User: noflaxe
* Date: 20.07.13
* Time: 13:10
* To change this template use File | Settings | File Templates.
*/
@Entity
@Table(name="ROLES")
@NamedQueries({
@NamedQuery(name="Role.findByAll",query = "FROM Role where login =:login")
})
public class Role {
@Id
@GeneratedValue(strategy= GenerationType.SEQUENCE, generator="SEQ_GEN")
@SequenceGenerator(name="SEQ_GEN", sequenceName="ID_SEQ", allocationSize=1)
@Column(name="ROLE_ID")
private long roleId;
@Column(name="LOGIN")
private String login;
@Column(name="PASSWORD")
private String password;
@Column(name="ROLE")
private String role;
@OneToOne(mappedBy="role")
private Worker worker;
public Worker getWorker() {
return worker;
}
public void setWorker(Worker worker) {
this.worker = worker;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Role role = (Role) o;
if (login != null ? !login.equals(role.login) : role.login != null) return false;
if (password != null ? !password.equals(role.password) : role.password != null) return false;
return true;
}
@Override
public int hashCode() {
int result = login != null ? login.hashCode() : 0;
result = 31 * result + (password != null ? password.hashCode() : 0);
return result;
}
public Role() {
}
public long getRoleId() {
return roleId;
}
public void setRoleId(long roleId) {
this.roleId = roleId;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
| 2,126 | 0.600282 | 0.59322 | 95 | 21.357895 | 22.007614 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.357895 | false | false | 12 |
6525003fa8cdbaf1eff62dff759996ff768b4ef9 | 22,909,355,589,843 | d1cdcd323c39fc4bbbddaac94cfb0ffa7a5c9990 | /spring-security-core-3.0.5/org/springframework/security/core/userdetails/memory/UserMap.java | b2415d9ad02660dfdd7d63a4dbdec9c2a2b45577 | [] | no_license | ZacharyRLewis/Sources | https://github.com/ZacharyRLewis/Sources | bbd4979e305ecf203dd293f84a0eaefca7617ffb | c9e3ad2c420f61faf863d75e78015f0bb65604dd | refs/heads/master | 2019-08-01T15:44:19.478000 | 2016-11-23T19:07:31 | 2016-11-23T19:07:31 | 74,605,833 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.springframework.security.core.userdetails.memory;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.Assert;
@Deprecated
public class UserMap
{
private static final Log logger = LogFactory.getLog(UserMap.class);
private Map<String, UserDetails> userMap = new HashMap();
public void addUser(UserDetails user)
throws IllegalArgumentException
{
Assert.notNull(user, "Must be a valid User");
logger.info("Adding user [" + user + "]");
this.userMap.put(user.getUsername().toLowerCase(), user);
}
public UserDetails getUser(String username)
throws UsernameNotFoundException
{
UserDetails result = (UserDetails)this.userMap.get(username.toLowerCase());
if (result == null) {
throw new UsernameNotFoundException("Could not find user: " + username, username);
}
return result;
}
public int getUserCount()
{
return this.userMap.size();
}
public void setUsers(Map<String, UserDetails> users)
{
this.userMap = users;
}
}
/* Location: /Users/zachlewis/workspace/collegesource_security_api/src/main/lib/spring-security-core-3.0.5.RELEASE.jar
* Qualified Name: org.springframework.security.core.userdetails.memory.UserMap
* JD-Core Version: 0.6.2
*/ | UTF-8 | Java | 1,563 | java | UserMap.java | Java | [
{
"context": "p = users;\n }\n }\n\n/* Location: /Users/zachlewis/workspace/collegesource_security_api/src/main/lib",
"end": 1357,
"score": 0.9992513656616211,
"start": 1348,
"tag": "USERNAME",
"value": "zachlewis"
}
] | null | [] | package org.springframework.security.core.userdetails.memory;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.Assert;
@Deprecated
public class UserMap
{
private static final Log logger = LogFactory.getLog(UserMap.class);
private Map<String, UserDetails> userMap = new HashMap();
public void addUser(UserDetails user)
throws IllegalArgumentException
{
Assert.notNull(user, "Must be a valid User");
logger.info("Adding user [" + user + "]");
this.userMap.put(user.getUsername().toLowerCase(), user);
}
public UserDetails getUser(String username)
throws UsernameNotFoundException
{
UserDetails result = (UserDetails)this.userMap.get(username.toLowerCase());
if (result == null) {
throw new UsernameNotFoundException("Could not find user: " + username, username);
}
return result;
}
public int getUserCount()
{
return this.userMap.size();
}
public void setUsers(Map<String, UserDetails> users)
{
this.userMap = users;
}
}
/* Location: /Users/zachlewis/workspace/collegesource_security_api/src/main/lib/spring-security-core-3.0.5.RELEASE.jar
* Qualified Name: org.springframework.security.core.userdetails.memory.UserMap
* JD-Core Version: 0.6.2
*/ | 1,563 | 0.714011 | 0.710173 | 53 | 28.490566 | 29.775021 | 128 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.433962 | false | false | 12 |
3b9e42b52d60b50fed9c0053f84c27bfb2b4cc31 | 29,145,648,135,403 | d5b7bc3da01910fbda5bc349a07aaf4d1fb7962b | /Lab 8 - Binary Search Tree/BSTNode.java | f37306cb7798a66d6f96e1ee5aba87ab870bdb04 | [] | no_license | mynameisnhan/CSC-172 | https://github.com/mynameisnhan/CSC-172 | a9d8719f74e1345f9e801adfaf67e4509b6c7b58 | 88a009ef44aba4909d9cbdb0c7253c1436aca89c | refs/heads/master | 2020-12-07T13:34:30.747000 | 2016-11-06T09:49:07 | 2016-11-06T09:49:07 | 68,493,268 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /* Nhan Le
* CSC 172
* Lab 8: Binary Search Tree
*/
public class BSTNode<T extends Comparable<T>>
{
public T data;
public BSTNode<T> leftChild;
public BSTNode<T> rightChild;
public BSTNode<T> parent;
// Method to insert.
public void insert(T x)
{
doInsert(x);
}
// Internal method to insert.
public void doInsert(T x)
{
// If new element is less than node element.
if (x.compareTo(this.data) < 0)
{
if (this.leftChild == null)
{
BSTNode<T> newNode = new BSTNode<>();
newNode.data = x;
newNode.parent = this;
this.leftChild = newNode;
}
else
this.leftChild.insert(x);
}
// If new element is greater than or equal to node element.
else if (x.compareTo(this.data) > 0 || x.compareTo(this.data) == 0)
{
if (this.rightChild == null)
{
BSTNode<T> newNode = new BSTNode<>();
newNode.data = x;
newNode.parent = this;
this.rightChild = newNode;
}
else
this.rightChild.insert(x);
}
}
// Method to delete.
public void delete(T x)
{
doDelete(x);
}
// Internal to delete.
private void doDelete(T x)
{
// If data is found.
if (this.data == x)
{
// If node is leaf.
if (this.leftChild == null && this.rightChild == null)
this.parent = null;
// If parent has one child.
else if ((this.leftChild == null || this.rightChild == null) && !(this.leftChild != null && this.rightChild != null))
this.parent = this;
// If parent has two children.
else
{
BSTNode<T> rightChild = this.rightChild;
BSTNode<T> lmcOfRightChild = rightChild.leftChild;
while (lmcOfRightChild.leftChild != null)
lmcOfRightChild = lmcOfRightChild.leftChild;
this.data = lmcOfRightChild.data;
lmcOfRightChild.parent.leftChild = lmcOfRightChild.rightChild;
}
}
// Keep traversing if data is not found.
else
{
if (x.compareTo(this.data) < 0)
if (this.leftChild != null)
this.leftChild.delete(x);
else
if (this.rightChild != null)
this.rightChild.delete(x);
}
}
// Method to lookup.
public boolean lookup(T x)
{
return doLookup(x);
}
// Internal method to lookup.
private boolean doLookup(T x)
{
// If data is found.
if (this.data == x)
return true;
// If new element is less than node element.
else if (x.compareTo(this.data) < 0)
if (this.leftChild != null)
return this.leftChild.lookup(x);
// If new element is greater than node element.
else // (x.compareTo(this.data) < 0)
if (this.rightChild != null)
return this.rightChild.lookup(x);
return false;
}
// Method to print inorder.
public void printInOrder()
{
doPrintInOrder();
}
// Internal method to print inorder.
private void doPrintInOrder()
{
if (this.leftChild != null)
this.leftChild.doPrintInOrder();
System.out.println(this.data);
if (this.rightChild != null)
this.rightChild.doPrintInOrder();
}
// Method to print preorder.
public void printPreOrder()
{
doPrintPreOrder();
}
// Internal method to print preorder.
private void doPrintPreOrder()
{
System.out.println(this.data);
if (this.leftChild != null)
this.leftChild.doPrintPreOrder();
if (this.rightChild != null)
this.rightChild.doPrintPreOrder();
}
// Method to print postorder.
public void printPostOrder()
{
doPrintPostOrder();
}
// Internal method to print postorder.
private void doPrintPostOrder()
{
if (this.leftChild != null)
this.leftChild.doPrintPostOrder();
if (this.rightChild != null)
this.rightChild.doPrintPostOrder();
System.out.println(this.data);
}
}
| UTF-8 | Java | 3,839 | java | BSTNode.java | Java | [
{
"context": "/* Nhan Le\r\n * CSC 172\r\n * Lab 8: Binary Search Tree \r\n */\r\n",
"end": 10,
"score": 0.9998457431793213,
"start": 3,
"tag": "NAME",
"value": "Nhan Le"
}
] | null | [] | /* <NAME>
* CSC 172
* Lab 8: Binary Search Tree
*/
public class BSTNode<T extends Comparable<T>>
{
public T data;
public BSTNode<T> leftChild;
public BSTNode<T> rightChild;
public BSTNode<T> parent;
// Method to insert.
public void insert(T x)
{
doInsert(x);
}
// Internal method to insert.
public void doInsert(T x)
{
// If new element is less than node element.
if (x.compareTo(this.data) < 0)
{
if (this.leftChild == null)
{
BSTNode<T> newNode = new BSTNode<>();
newNode.data = x;
newNode.parent = this;
this.leftChild = newNode;
}
else
this.leftChild.insert(x);
}
// If new element is greater than or equal to node element.
else if (x.compareTo(this.data) > 0 || x.compareTo(this.data) == 0)
{
if (this.rightChild == null)
{
BSTNode<T> newNode = new BSTNode<>();
newNode.data = x;
newNode.parent = this;
this.rightChild = newNode;
}
else
this.rightChild.insert(x);
}
}
// Method to delete.
public void delete(T x)
{
doDelete(x);
}
// Internal to delete.
private void doDelete(T x)
{
// If data is found.
if (this.data == x)
{
// If node is leaf.
if (this.leftChild == null && this.rightChild == null)
this.parent = null;
// If parent has one child.
else if ((this.leftChild == null || this.rightChild == null) && !(this.leftChild != null && this.rightChild != null))
this.parent = this;
// If parent has two children.
else
{
BSTNode<T> rightChild = this.rightChild;
BSTNode<T> lmcOfRightChild = rightChild.leftChild;
while (lmcOfRightChild.leftChild != null)
lmcOfRightChild = lmcOfRightChild.leftChild;
this.data = lmcOfRightChild.data;
lmcOfRightChild.parent.leftChild = lmcOfRightChild.rightChild;
}
}
// Keep traversing if data is not found.
else
{
if (x.compareTo(this.data) < 0)
if (this.leftChild != null)
this.leftChild.delete(x);
else
if (this.rightChild != null)
this.rightChild.delete(x);
}
}
// Method to lookup.
public boolean lookup(T x)
{
return doLookup(x);
}
// Internal method to lookup.
private boolean doLookup(T x)
{
// If data is found.
if (this.data == x)
return true;
// If new element is less than node element.
else if (x.compareTo(this.data) < 0)
if (this.leftChild != null)
return this.leftChild.lookup(x);
// If new element is greater than node element.
else // (x.compareTo(this.data) < 0)
if (this.rightChild != null)
return this.rightChild.lookup(x);
return false;
}
// Method to print inorder.
public void printInOrder()
{
doPrintInOrder();
}
// Internal method to print inorder.
private void doPrintInOrder()
{
if (this.leftChild != null)
this.leftChild.doPrintInOrder();
System.out.println(this.data);
if (this.rightChild != null)
this.rightChild.doPrintInOrder();
}
// Method to print preorder.
public void printPreOrder()
{
doPrintPreOrder();
}
// Internal method to print preorder.
private void doPrintPreOrder()
{
System.out.println(this.data);
if (this.leftChild != null)
this.leftChild.doPrintPreOrder();
if (this.rightChild != null)
this.rightChild.doPrintPreOrder();
}
// Method to print postorder.
public void printPostOrder()
{
doPrintPostOrder();
}
// Internal method to print postorder.
private void doPrintPostOrder()
{
if (this.leftChild != null)
this.leftChild.doPrintPostOrder();
if (this.rightChild != null)
this.rightChild.doPrintPostOrder();
System.out.println(this.data);
}
}
| 3,838 | 0.606668 | 0.604064 | 180 | 19.327778 | 18.182358 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.2 | false | false | 12 |
751418c1b893f84f8e0f9384ab449c67512ebd1c | 18,442,589,593,641 | aaa6b80a4e551c00d13a48ff5de2a386f0c26598 | /PiggyBit-master/src/main/java/com/yodlee/utils/GetTransactions.java | b188d89274eb0b5b541cbf0276e9beee2c798aba | [] | no_license | danaszapiro/PiggyBit--webApp | https://github.com/danaszapiro/PiggyBit--webApp | 3d4398e7606e2a056ca321a18f5e332997c7325a | 9a4ae20d74ecde8145a83ab169e2641025cb3bcd | refs/heads/master | 2021-08-28T12:03:51.497000 | 2017-12-12T06:24:52 | 2017-12-12T06:24:52 | 110,740,194 | 0 | 2 | null | false | 2017-12-12T05:59:00 | 2017-11-14T20:19:27 | 2017-12-10T22:13:08 | 2017-12-12T05:58:59 | 29,837 | 0 | 1 | 1 | HTML | false | null | package com.yodlee.utils;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.time.LocalDate;
import com.yodlee.beans.CobrandContext;
import com.yodlee.beans.UserContext;
import com.yodlee.parser.GSONParser;
import com.yodlee.utils.HTTP;
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.IOException;
import com.piggybit.models.User;
public class GetTransactions {
private String localURLVer1 = "https://developer.api.yodlee.com/ysl/restserver/";
String cobSession = "";
String userSession = "";
String userAccounts = "";
public String cobrandLogin = "sbCobd74e196a9cfac3ff5c74d3ee313bf2de6a";
public String cobrandPassword = "1734ef64-b099-492c-8797-b0b00c40a495";
//String accountId = "";
String transactions = "";
//String date_str = "2013-12-01";
double investment_total = 0.00;
double margin = 10.00;
Date date = new Date();
String date_str = String.format("%tF", date);
//System.out,println("Current date:");
//System.out.println("Current date: " + date_str);
public String getCobsession(String cobrandjsonResponse) {
return "";
}
public String userLogin(String cobSession, String userName, String password) {
String userSession = null;
try {
Map<String, String> loginTokens = new HashMap<String, String>();
loginTokens.put("cobSession", cobSession);
// User login
String userLoginURL = "https://developer.api.yodlee.com/ysl/restserver/" + "v1/user/login";
//Request Body JSON - refer to full API reference at https://developer.yodlee.com/apidocs/index.php
final String requestBody2 = "{"
+ "\"user\":{"
+ "\"loginName\":\"" + userName + "\"" + ","
+ "\"password\":\"" + password + "\"" + ","
+ "\"locale\": \"en_US\""
+ "}"
+ "}";
String userjsonResponse = HTTP.doPostUser(userLoginURL,
loginTokens, requestBody2, true);
UserContext member = (UserContext) GSONParser.handleJson(
userjsonResponse, com.yodlee.beans.UserContext.class);
if (!userjsonResponse.contains("errorCode")) {
userSession = member.getUser().getSession().getUserSession();
}
} catch (IOException e) {
e.printStackTrace();
}
return userSession;
}
public String getUserAccounts(String cobSession, String userSession) {
String accountURL = "https://developer.api.yodlee.com/ysl/restserver/" + "v1/accounts";
Map<String,String> loginTokens = new HashMap<String,String>();
loginTokens.put("cobSession", cobSession);
loginTokens.put("userSession",userSession);
String accountJsonResponse=null;
try {
accountJsonResponse = HTTP.doGet(accountURL,loginTokens);
} catch (Exception e) {
e.printStackTrace();
}
return accountJsonResponse;
}
public String getTransactions(String cobSession, String userSession,
String accountId, String date) {
String txnJson ="";
String TransactionUrl = "https://developer.api.yodlee.com/ysl/restserver/" + "v1/transactions" + "?fromDate=" + date + "&accountId="+accountId;
try {
Map<String,String> loginTokens = new HashMap<String,String>();
loginTokens.put("cobSession", cobSession);
loginTokens.put("userSession",userSession);
txnJson = HTTP.doGet(TransactionUrl,loginTokens);
} catch (Exception e) {
e.printStackTrace();
}
return txnJson;
}
//Return the investment amount where userAccounts is string obtained from getUserAccounts function
public double getInvestment( String userAccounts, String cobSession, String userSession,
String most_recent_investment, double margin) throws ParseException {
System.out.println("In getInvestment");
Double investment_total = 0.00;
JSONParser parser = new JSONParser();
JSONObject userAccount = (JSONObject) parser.parse(userAccounts);
JSONArray accountList = (JSONArray) userAccount.get("account");
System.out.println("Number of accounts: " + accountList.size());
JSONObject account = (JSONObject) accountList.get(1);
String accountId = Long.toString((long)account.get("id"));
System.out.println(account);
System.out.println(account.get("id"));
//Parsing through each account in Yodlee to retrieve transactions and compute investment amount
int counter = 0; //use for tracking number of transactions;
for(int j = 0; j<accountList.size(); j++) {
JSONObject acc = (JSONObject) accountList.get(j);
System.out.println(acc.get("id"));
String accId = Long.toString((long)acc.get("id"));
//String current_time_str = String.format("%tF", current_time);
//Where the account starts looking for transactions
//Time is being used here
String transactions = getTransactions(cobSession, userSession, accId, most_recent_investment);
System.out.println("transactions: " + transactions);
JSONParser parser2 = new JSONParser();
JSONObject json = (JSONObject) parser2.parse(transactions);
JSONArray transactions_list = (JSONArray) json.get("transaction");
//No recent transactions as of most_recent_investment
if (transactions_list == null){
System.out.println("Account: " + accId + " has no recent transactions");
}
else {
System.out.println("Number of transactions: " + transactions_list.size());
//For loop to parse through all transactions
for (int i = 0; i < transactions_list.size(); i++) {
Double investment = 0.00;
JSONObject amounts = (JSONObject) transactions_list.get(i);
JSONObject amounts2 = (JSONObject) amounts.get("amount");
System.out.println("Transaction " + i + " : " + amounts2.get("amount") + " Transaction type:" + amounts.get("baseType"));
//System.out.println(amounts.get("baseType"));
if (amounts.get("baseType").equals("DEBIT")) {
investment = margin - ((Double.valueOf(amounts2.get("amount").toString()))%margin);
if (investment.equals(margin)) {
investment = 0.00;
counter = counter -1;
}
counter = counter + 1;
System.out.println("investment amount: " + investment);
investment_total = investment + investment_total;
System.out.println("total investment: " + investment_total);
}
}
}
}
//Make sure that the value is in 2 decimal places
investment_total = investment_total * 100;
investment_total = (double) (investment_total);
investment_total = investment_total / 100;
return investment_total;
}
}
| UTF-8 | Java | 6,842 | java | GetTransactions.java | Java | [
{
"context": "313bf2de6a\";\n public String cobrandPassword = \"1734ef64-b099-492c-8797-b0b00c40a495\";\n //String accountId = \"\";\n String transac",
"end": 873,
"score": 0.9993398189544678,
"start": 837,
"tag": "PASSWORD",
"value": "1734ef64-b099-492c-8797-b0b00c40a495"
},
{
... | null | [] | package com.yodlee.utils;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.time.LocalDate;
import com.yodlee.beans.CobrandContext;
import com.yodlee.beans.UserContext;
import com.yodlee.parser.GSONParser;
import com.yodlee.utils.HTTP;
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.IOException;
import com.piggybit.models.User;
public class GetTransactions {
private String localURLVer1 = "https://developer.api.yodlee.com/ysl/restserver/";
String cobSession = "";
String userSession = "";
String userAccounts = "";
public String cobrandLogin = "sbCobd74e196a9cfac3ff5c74d3ee313bf2de6a";
public String cobrandPassword = "<PASSWORD>";
//String accountId = "";
String transactions = "";
//String date_str = "2013-12-01";
double investment_total = 0.00;
double margin = 10.00;
Date date = new Date();
String date_str = String.format("%tF", date);
//System.out,println("Current date:");
//System.out.println("Current date: " + date_str);
public String getCobsession(String cobrandjsonResponse) {
return "";
}
public String userLogin(String cobSession, String userName, String password) {
String userSession = null;
try {
Map<String, String> loginTokens = new HashMap<String, String>();
loginTokens.put("cobSession", cobSession);
// User login
String userLoginURL = "https://developer.api.yodlee.com/ysl/restserver/" + "v1/user/login";
//Request Body JSON - refer to full API reference at https://developer.yodlee.com/apidocs/index.php
final String requestBody2 = "{"
+ "\"user\":{"
+ "\"loginName\":\"" + userName + "\"" + ","
+ "\"password\":\"" + <PASSWORD> + "\"" + ","
+ "\"locale\": \"en_US\""
+ "}"
+ "}";
String userjsonResponse = HTTP.doPostUser(userLoginURL,
loginTokens, requestBody2, true);
UserContext member = (UserContext) GSONParser.handleJson(
userjsonResponse, com.yodlee.beans.UserContext.class);
if (!userjsonResponse.contains("errorCode")) {
userSession = member.getUser().getSession().getUserSession();
}
} catch (IOException e) {
e.printStackTrace();
}
return userSession;
}
public String getUserAccounts(String cobSession, String userSession) {
String accountURL = "https://developer.api.yodlee.com/ysl/restserver/" + "v1/accounts";
Map<String,String> loginTokens = new HashMap<String,String>();
loginTokens.put("cobSession", cobSession);
loginTokens.put("userSession",userSession);
String accountJsonResponse=null;
try {
accountJsonResponse = HTTP.doGet(accountURL,loginTokens);
} catch (Exception e) {
e.printStackTrace();
}
return accountJsonResponse;
}
public String getTransactions(String cobSession, String userSession,
String accountId, String date) {
String txnJson ="";
String TransactionUrl = "https://developer.api.yodlee.com/ysl/restserver/" + "v1/transactions" + "?fromDate=" + date + "&accountId="+accountId;
try {
Map<String,String> loginTokens = new HashMap<String,String>();
loginTokens.put("cobSession", cobSession);
loginTokens.put("userSession",userSession);
txnJson = HTTP.doGet(TransactionUrl,loginTokens);
} catch (Exception e) {
e.printStackTrace();
}
return txnJson;
}
//Return the investment amount where userAccounts is string obtained from getUserAccounts function
public double getInvestment( String userAccounts, String cobSession, String userSession,
String most_recent_investment, double margin) throws ParseException {
System.out.println("In getInvestment");
Double investment_total = 0.00;
JSONParser parser = new JSONParser();
JSONObject userAccount = (JSONObject) parser.parse(userAccounts);
JSONArray accountList = (JSONArray) userAccount.get("account");
System.out.println("Number of accounts: " + accountList.size());
JSONObject account = (JSONObject) accountList.get(1);
String accountId = Long.toString((long)account.get("id"));
System.out.println(account);
System.out.println(account.get("id"));
//Parsing through each account in Yodlee to retrieve transactions and compute investment amount
int counter = 0; //use for tracking number of transactions;
for(int j = 0; j<accountList.size(); j++) {
JSONObject acc = (JSONObject) accountList.get(j);
System.out.println(acc.get("id"));
String accId = Long.toString((long)acc.get("id"));
//String current_time_str = String.format("%tF", current_time);
//Where the account starts looking for transactions
//Time is being used here
String transactions = getTransactions(cobSession, userSession, accId, most_recent_investment);
System.out.println("transactions: " + transactions);
JSONParser parser2 = new JSONParser();
JSONObject json = (JSONObject) parser2.parse(transactions);
JSONArray transactions_list = (JSONArray) json.get("transaction");
//No recent transactions as of most_recent_investment
if (transactions_list == null){
System.out.println("Account: " + accId + " has no recent transactions");
}
else {
System.out.println("Number of transactions: " + transactions_list.size());
//For loop to parse through all transactions
for (int i = 0; i < transactions_list.size(); i++) {
Double investment = 0.00;
JSONObject amounts = (JSONObject) transactions_list.get(i);
JSONObject amounts2 = (JSONObject) amounts.get("amount");
System.out.println("Transaction " + i + " : " + amounts2.get("amount") + " Transaction type:" + amounts.get("baseType"));
//System.out.println(amounts.get("baseType"));
if (amounts.get("baseType").equals("DEBIT")) {
investment = margin - ((Double.valueOf(amounts2.get("amount").toString()))%margin);
if (investment.equals(margin)) {
investment = 0.00;
counter = counter -1;
}
counter = counter + 1;
System.out.println("investment amount: " + investment);
investment_total = investment + investment_total;
System.out.println("total investment: " + investment_total);
}
}
}
}
//Make sure that the value is in 2 decimal places
investment_total = investment_total * 100;
investment_total = (double) (investment_total);
investment_total = investment_total / 100;
return investment_total;
}
}
| 6,818 | 0.662818 | 0.649956 | 196 | 33.908165 | 28.895868 | 145 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.55102 | false | false | 12 |
7c98ae40468708a700684ff15b6950848fdc3255 | 32,418,413,172,135 | 6ced29bee5a40225d4fbc32fe066cd1fa6bbd4c6 | /assignments/ClassWork/Day3/src/com/demo/inheritance/demo2/App.java | 4e9633f9a7f4d16dd72a349f4adbf9d138571d0a | [] | no_license | deep-oxy/hsbc-training | https://github.com/deep-oxy/hsbc-training | bbbdf069a35fb8a68c0a7f485c64a74d2c5666a9 | 323dffcff9168c93eae927ca4b9f64f89c421592 | refs/heads/master | 2022-12-30T15:04:08.853000 | 2020-10-20T11:42:37 | 2020-10-20T11:42:37 | 295,766,731 | 0 | 0 | null | true | 2020-09-15T15:13:43 | 2020-09-15T15:13:42 | 2020-09-15T15:07:47 | 2020-09-15T15:07:45 | 0 | 0 | 0 | 0 | null | false | false | package com.demo.inheritance.demo2;
public class App {
public static void main(String[] args) {
Person p = new Person(100, "Piyush");
Employee e = new Employee(204, "John", 45000);
TraineeEmployee t = new TraineeEmployee(320, "Smith", 55000, "Awesome");
System.out.println(p.getDetails());
System.out.println(e.getDetails());
System.out.println(t.getDetails());
}
}
| UTF-8 | Java | 385 | java | App.java | Java | [
{
"context": "in(String[] args) {\n\t\tPerson p = new Person(100, \"Piyush\");\n\t\tEmployee e = new Employee(204, \"John\", 45000",
"end": 135,
"score": 0.9996992945671082,
"start": 129,
"tag": "NAME",
"value": "Piyush"
},
{
"context": "100, \"Piyush\");\n\t\tEmployee e = new Employ... | null | [] | package com.demo.inheritance.demo2;
public class App {
public static void main(String[] args) {
Person p = new Person(100, "Piyush");
Employee e = new Employee(204, "John", 45000);
TraineeEmployee t = new TraineeEmployee(320, "Smith", 55000, "Awesome");
System.out.println(p.getDetails());
System.out.println(e.getDetails());
System.out.println(t.getDetails());
}
}
| 385 | 0.690909 | 0.638961 | 16 | 23.0625 | 22.5457 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.6875 | false | false | 12 |
30eef993281d3964feb786c248a76e4e3b209f89 | 51,539,623,262 | 832a8b2fb22dc449b158fd14a348553d971980b4 | /src/main/java/br/com/shortener/usecases/RetrieveShortUrlStatistics.java | f2cf87f997cf2ed2ce1d760774d12ee424f6a8c4 | [] | no_license | alanlgoncalves/url-shortener | https://github.com/alanlgoncalves/url-shortener | 512b4432964d843995f92afb0ee64287eb6784d1 | 529028261de3b3f06100696637f30f4d9d0a8e6f | refs/heads/master | 2021-07-19T05:38:52.690000 | 2020-05-30T18:57:50 | 2020-05-30T18:57:50 | 171,021,281 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.shortener.usecases;
import br.com.shortener.domains.ShortUrlStatistics;
import br.com.shortener.domains.builders.ShortUrlStatisticsBuilder;
import br.com.shortener.domains.collections.ShortUrl;
import br.com.shortener.domains.collections.ShortUrlRequest;
import br.com.shortener.exceptions.RecordNotFoundException;
import br.com.shortener.gateways.ShortUrlGateway;
import br.com.shortener.gateways.ShortUrlRequestGateway;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class RetrieveShortUrlStatistics {
private final ShortUrlGateway shortUrlGateway;
private final ShortUrlRequestGateway shortUrlRequestGateway;
public RetrieveShortUrlStatistics(
final ShortUrlGateway shortUrlGateway, final ShortUrlRequestGateway shortUrlRequestGateway) {
this.shortUrlGateway = shortUrlGateway;
this.shortUrlRequestGateway = shortUrlRequestGateway;
}
public ShortUrlStatistics execute(final String shortUrlId) {
Optional<ShortUrl> shortUrlOptional = shortUrlGateway.get(shortUrlId);
if (!shortUrlOptional.isPresent()) {
throw new RecordNotFoundException("Short URL not found");
}
final Long numberOfRequests = shortUrlRequestGateway.countRequests(shortUrlId);
final List<ShortUrlRequest> lastTenRequests =
shortUrlRequestGateway.getLastTenRequests(shortUrlId);
return new ShortUrlStatisticsBuilder()
.setShortUrl(shortUrlOptional.get())
.setNumberOfRequests(numberOfRequests)
.setLastTenRequests(lastTenRequests)
.createShortUrlStatistics();
}
}
| UTF-8 | Java | 1,618 | java | RetrieveShortUrlStatistics.java | Java | [] | null | [] | package br.com.shortener.usecases;
import br.com.shortener.domains.ShortUrlStatistics;
import br.com.shortener.domains.builders.ShortUrlStatisticsBuilder;
import br.com.shortener.domains.collections.ShortUrl;
import br.com.shortener.domains.collections.ShortUrlRequest;
import br.com.shortener.exceptions.RecordNotFoundException;
import br.com.shortener.gateways.ShortUrlGateway;
import br.com.shortener.gateways.ShortUrlRequestGateway;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class RetrieveShortUrlStatistics {
private final ShortUrlGateway shortUrlGateway;
private final ShortUrlRequestGateway shortUrlRequestGateway;
public RetrieveShortUrlStatistics(
final ShortUrlGateway shortUrlGateway, final ShortUrlRequestGateway shortUrlRequestGateway) {
this.shortUrlGateway = shortUrlGateway;
this.shortUrlRequestGateway = shortUrlRequestGateway;
}
public ShortUrlStatistics execute(final String shortUrlId) {
Optional<ShortUrl> shortUrlOptional = shortUrlGateway.get(shortUrlId);
if (!shortUrlOptional.isPresent()) {
throw new RecordNotFoundException("Short URL not found");
}
final Long numberOfRequests = shortUrlRequestGateway.countRequests(shortUrlId);
final List<ShortUrlRequest> lastTenRequests =
shortUrlRequestGateway.getLastTenRequests(shortUrlId);
return new ShortUrlStatisticsBuilder()
.setShortUrl(shortUrlOptional.get())
.setNumberOfRequests(numberOfRequests)
.setLastTenRequests(lastTenRequests)
.createShortUrlStatistics();
}
}
| 1,618 | 0.804079 | 0.804079 | 44 | 35.772728 | 26.90291 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.477273 | false | false | 12 |
a6833672370517202781cbe872eab9698d10e25e | 51,539,625,384 | 470a92fb51651da0975eceddff557e5bad9001b0 | /src/store/model/service/impl/StockServiceImpl.java | 4f2fc03fc2dc43f8bba3adc93902fbb357ab503b | [] | no_license | Frontlook/store-spring | https://github.com/Frontlook/store-spring | 35a3ef0a1b059ca54efa4a666dfbfc0145e32dc2 | 1723f8c4842af158ca4aab2c9da8e930fa9cb8bd | refs/heads/master | 2021-01-15T13:00:20.648000 | 2011-10-05T14:09:35 | 2011-10-05T14:09:35 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package store.model.service.impl;
import store.model.service.StockService;
/**
* Implementation of StockService.
* @author Tarso Bessa
*
*/
public class StockServiceImpl
implements StockService {
@Override
public void checkStock() {
//code for stock checking
System.out.println("Checking stock...");
}
}
| UTF-8 | Java | 344 | java | StockServiceImpl.java | Java | [
{
"context": "**\r\n * Implementation of StockService.\r\n * @author Tarso Bessa\r\n *\r\n */\r\n public class StockServiceImpl \r\n i",
"end": 142,
"score": 0.9998911619186401,
"start": 131,
"tag": "NAME",
"value": "Tarso Bessa"
}
] | null | [] | package store.model.service.impl;
import store.model.service.StockService;
/**
* Implementation of StockService.
* @author <NAME>
*
*/
public class StockServiceImpl
implements StockService {
@Override
public void checkStock() {
//code for stock checking
System.out.println("Checking stock...");
}
}
| 339 | 0.677326 | 0.677326 | 17 | 18.235294 | 15.144517 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.647059 | false | false | 12 |
ef5a3e52108abd33b8d2e0a1c94619d3527cf691 | 9,663,676,420,344 | 47382f1391487596351425649efd4e973b7028bb | /src/ro/ubbcluj/lci/uml/foundation/core/FeatureImpl.java | 2b09c74ef5defe5b17d39ed84afc801f5d81a1aa | [] | no_license | luoyuxia/ocle | https://github.com/luoyuxia/ocle | e6963e7de4fc7537f0ff6d12cd31fa28848b16c0 | a7d60f098ddfa95764a851e781eaaf22cd3add3c | refs/heads/master | 2022-12-11T02:06:00.431000 | 2020-08-18T04:04:27 | 2020-08-18T04:04:27 | 284,402,676 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ro.ubbcluj.lci.uml.foundation.core;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
import ro.ubbcluj.lci.uml.ChangeEventObject;
import ro.ubbcluj.lci.uml.RepositoryChangeAgent;
import ro.ubbcluj.lci.uml.behavioralElements.collaborations.ClassifierRole;
public class FeatureImpl extends ModelElementImpl implements Feature {
protected int theOwnerScope;
protected int theVisibility;
protected Set theClassifierRoleList;
protected Classifier theOwner;
public FeatureImpl() {
}
public int getOwnerScope() {
return this.theOwnerScope;
}
public void setOwnerScope(int ownerScope) {
this.theOwnerScope = ownerScope;
RepositoryChangeAgent agent = RepositoryChangeAgent.getAgent(this);
if (agent != null && agent.firesEvents()) {
agent.fireChangeEvent(new ChangeEventObject(this, "ownerScope", 0));
}
}
public int getVisibility() {
return this.theVisibility;
}
public void setVisibility(int visibility) {
this.theVisibility = visibility;
RepositoryChangeAgent agent = RepositoryChangeAgent.getAgent(this);
if (agent != null && agent.firesEvents()) {
agent.fireChangeEvent(new ChangeEventObject(this, "visibility", 0));
}
}
public Set getCollectionClassifierRoleList() {
return this.theClassifierRoleList == null ? Collections.EMPTY_SET : Collections.unmodifiableSet(this.theClassifierRoleList);
}
public java.util.Enumeration getClassifierRoleList() {
return Collections.enumeration(this.getCollectionClassifierRoleList());
}
public void addClassifierRole(ClassifierRole arg) {
if (arg != null) {
if (this.theClassifierRoleList == null) {
this.theClassifierRoleList = new LinkedHashSet();
}
if (this.theClassifierRoleList.add(arg)) {
arg.addAvailableFeature(this);
RepositoryChangeAgent agent = RepositoryChangeAgent.getAgent(this);
if (agent != null && agent.firesEvents()) {
agent.fireChangeEvent(new ChangeEventObject(this, "classifierRole", 1));
}
}
}
}
public void removeClassifierRole(ClassifierRole arg) {
if (this.theClassifierRoleList != null && arg != null && this.theClassifierRoleList.remove(arg)) {
arg.removeAvailableFeature(this);
RepositoryChangeAgent agent = RepositoryChangeAgent.getAgent(this);
if (agent != null && agent.firesEvents()) {
agent.fireChangeEvent(new ChangeEventObject(this, "classifierRole", 2));
}
}
}
public Classifier getOwner() {
return this.theOwner;
}
public void setOwner(Classifier arg) {
if (this.theOwner != arg) {
Classifier temp = this.theOwner;
this.theOwner = null;
if (temp != null) {
temp.removeFeature(this);
}
if (arg != null) {
this.theOwner = arg;
arg.addFeature(this);
}
RepositoryChangeAgent agent = RepositoryChangeAgent.getAgent(this);
if (agent != null && agent.firesEvents()) {
agent.fireChangeEvent(new ChangeEventObject(this, "owner", 0));
}
}
}
protected void internalRemove() {
java.util.Enumeration tmpClassifierRoleEnum = this.getClassifierRoleList();
ArrayList tmpClassifierRoleList = new ArrayList();
while(tmpClassifierRoleEnum.hasMoreElements()) {
tmpClassifierRoleList.add(tmpClassifierRoleEnum.nextElement());
}
Iterator it = tmpClassifierRoleList.iterator();
while(it.hasNext()) {
ClassifierRole tmpClassifierRole = (ClassifierRole)it.next();
tmpClassifierRole.removeAvailableFeature(this);
}
Classifier tmpOwner = this.getOwner();
if (tmpOwner != null) {
tmpOwner.removeFeature(this);
}
super.internalRemove();
}
}
| UTF-8 | Java | 4,014 | java | FeatureImpl.java | Java | [] | null | [] | package ro.ubbcluj.lci.uml.foundation.core;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
import ro.ubbcluj.lci.uml.ChangeEventObject;
import ro.ubbcluj.lci.uml.RepositoryChangeAgent;
import ro.ubbcluj.lci.uml.behavioralElements.collaborations.ClassifierRole;
public class FeatureImpl extends ModelElementImpl implements Feature {
protected int theOwnerScope;
protected int theVisibility;
protected Set theClassifierRoleList;
protected Classifier theOwner;
public FeatureImpl() {
}
public int getOwnerScope() {
return this.theOwnerScope;
}
public void setOwnerScope(int ownerScope) {
this.theOwnerScope = ownerScope;
RepositoryChangeAgent agent = RepositoryChangeAgent.getAgent(this);
if (agent != null && agent.firesEvents()) {
agent.fireChangeEvent(new ChangeEventObject(this, "ownerScope", 0));
}
}
public int getVisibility() {
return this.theVisibility;
}
public void setVisibility(int visibility) {
this.theVisibility = visibility;
RepositoryChangeAgent agent = RepositoryChangeAgent.getAgent(this);
if (agent != null && agent.firesEvents()) {
agent.fireChangeEvent(new ChangeEventObject(this, "visibility", 0));
}
}
public Set getCollectionClassifierRoleList() {
return this.theClassifierRoleList == null ? Collections.EMPTY_SET : Collections.unmodifiableSet(this.theClassifierRoleList);
}
public java.util.Enumeration getClassifierRoleList() {
return Collections.enumeration(this.getCollectionClassifierRoleList());
}
public void addClassifierRole(ClassifierRole arg) {
if (arg != null) {
if (this.theClassifierRoleList == null) {
this.theClassifierRoleList = new LinkedHashSet();
}
if (this.theClassifierRoleList.add(arg)) {
arg.addAvailableFeature(this);
RepositoryChangeAgent agent = RepositoryChangeAgent.getAgent(this);
if (agent != null && agent.firesEvents()) {
agent.fireChangeEvent(new ChangeEventObject(this, "classifierRole", 1));
}
}
}
}
public void removeClassifierRole(ClassifierRole arg) {
if (this.theClassifierRoleList != null && arg != null && this.theClassifierRoleList.remove(arg)) {
arg.removeAvailableFeature(this);
RepositoryChangeAgent agent = RepositoryChangeAgent.getAgent(this);
if (agent != null && agent.firesEvents()) {
agent.fireChangeEvent(new ChangeEventObject(this, "classifierRole", 2));
}
}
}
public Classifier getOwner() {
return this.theOwner;
}
public void setOwner(Classifier arg) {
if (this.theOwner != arg) {
Classifier temp = this.theOwner;
this.theOwner = null;
if (temp != null) {
temp.removeFeature(this);
}
if (arg != null) {
this.theOwner = arg;
arg.addFeature(this);
}
RepositoryChangeAgent agent = RepositoryChangeAgent.getAgent(this);
if (agent != null && agent.firesEvents()) {
agent.fireChangeEvent(new ChangeEventObject(this, "owner", 0));
}
}
}
protected void internalRemove() {
java.util.Enumeration tmpClassifierRoleEnum = this.getClassifierRoleList();
ArrayList tmpClassifierRoleList = new ArrayList();
while(tmpClassifierRoleEnum.hasMoreElements()) {
tmpClassifierRoleList.add(tmpClassifierRoleEnum.nextElement());
}
Iterator it = tmpClassifierRoleList.iterator();
while(it.hasNext()) {
ClassifierRole tmpClassifierRole = (ClassifierRole)it.next();
tmpClassifierRole.removeAvailableFeature(this);
}
Classifier tmpOwner = this.getOwner();
if (tmpOwner != null) {
tmpOwner.removeFeature(this);
}
super.internalRemove();
}
}
| 4,014 | 0.664175 | 0.66293 | 130 | 29.876923 | 27.996433 | 130 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.438462 | false | false | 12 |
b0d99da02030dcbaa58f682a240ee207d2c095ad | 18,511,309,074,394 | 08e45a04a7e95321c0b85eb5e524ebc3d1028830 | /src/uneedtestingplugin/Achievements/Hardwork/ToughGuy.java | ea9b1cc3dac43cda984156136d0644226ceebea3 | [] | no_license | Dunn2016/UNeedTestingPlugin | https://github.com/Dunn2016/UNeedTestingPlugin | 252d38c51ca4fc7595d1cba898daa2b29abd50ae | 32df0ce7479a9334f87b32d973c051de286aa49d | refs/heads/master | 2021-03-19T11:07:28.934000 | 2017-09-03T15:31:53 | 2017-09-03T15:31:53 | 102,274,007 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Achievement Event: Tough Guy
* Achievement Category: Hard Work
* Details: One test suite contains more than 999 cases.
*/
package uneedtestingplugin.Achievements.Hardwork;
import uneedtestingplugin.Modal.ProcessData;
public class ToughGuy {
public boolean toughGuy (int testCaseNum) {
if (testCaseNum >= 999) {
String event = "Tough Guy";
int[] count_condition = {10, 15, 100};
ProcessData pt1 = new ProcessData();
pt1.processType1(event, count_condition);
return true;
}
return false;
}
} | UTF-8 | Java | 527 | java | ToughGuy.java | Java | [] | null | [] | /**
* Achievement Event: Tough Guy
* Achievement Category: Hard Work
* Details: One test suite contains more than 999 cases.
*/
package uneedtestingplugin.Achievements.Hardwork;
import uneedtestingplugin.Modal.ProcessData;
public class ToughGuy {
public boolean toughGuy (int testCaseNum) {
if (testCaseNum >= 999) {
String event = "Tough Guy";
int[] count_condition = {10, 15, 100};
ProcessData pt1 = new ProcessData();
pt1.processType1(event, count_condition);
return true;
}
return false;
}
} | 527 | 0.711575 | 0.681214 | 23 | 21.956522 | 18.901297 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.521739 | false | false | 12 |
eb007cf53f0ab82c514a5872838137487aa713a3 | 8,985,071,601,427 | 89fdf15fc38ff25b9b8bc53bee8da7b2b627a246 | /APP/app/src/main/java/com/apmuei/findmyrhythm/Model/PersistentOrganizerInfo.java | ba69e880624fbbe21dab0948788e2161becf95e3 | [] | no_license | sandradopi/APM | https://github.com/sandradopi/APM | f9d77d999c724539e17a1149a4fae8aa04426a16 | f6aaefb0580318ffae37f23a372ced4851223a4e | refs/heads/master | 2021-01-01T13:13:50.274000 | 2020-06-11T15:04:40 | 2020-06-11T15:04:40 | 239,290,448 | 0 | 0 | null | false | 2020-04-30T18:33:21 | 2020-02-09T11:08:30 | 2020-04-24T18:47:49 | 2020-04-30T18:33:20 | 144,668 | 0 | 0 | 0 | Java | false | false | package com.apmuei.findmyrhythm.Model;
import android.content.Context;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
public class PersistentOrganizerInfo extends Organizer {
private ArrayList<Event> events;
public PersistentOrganizerInfo(String id, String name, String username, String email, String biography, String rating, String location, ArrayList<Event> events) {
super(id, name, username, email, biography, rating, location);
this.events = events;
}
public void updateInfo(Context context, String name, String username, String email, String biography, String location) {
PersistentOrganizerInfo persistentOrgInfo = (PersistentOrganizerInfo) PersistentOrganizerInfo.getPersistentOrganizerInfo(context);
persistentOrgInfo.setName(name);
persistentOrgInfo.setUsername(username);
persistentOrgInfo.setEmail(email);
persistentOrgInfo.setBiography(biography);
persistentOrgInfo.setLocation(location);
PersistentOrganizerInfo.setPersistentOrganizerInfo(context, persistentOrgInfo);
}
public ArrayList<Event> getEvents() {
return events;
}
public Event getEvent(String id){
//System.out.println(id);
for (Event event:events){
//System.out.println(event.getId());
if(event.getId().equals(id)) return event;
}
return null;
}
public void setEvents(ArrayList<Event> events) {
this.events = events;
}
public static PersistentOrganizerInfo getPersistentOrganizerInfo(Context context) {
Gson gson = new Gson();
PersistentOrganizerInfo persistentOrganizerInfo = null;
try {
persistentOrganizerInfo = gson.fromJson(new FileReader(context.getFilesDir().getPath() + "persistent_info.json"), PersistentOrganizerInfo.class);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return persistentOrganizerInfo;
}
public static void setPersistentOrganizerInfo(Context context, PersistentOrganizerInfo persistentOrganizerInfo) {
try (Writer writer = new FileWriter(context.getFilesDir().getPath() + "persistent_info.json")) {
Gson gson = new GsonBuilder().create();
gson.toJson(persistentOrganizerInfo, writer);
} catch (IOException e) {
e.printStackTrace();
}
}
public void addEvent(Context context, Event event) {
PersistentOrganizerInfo persistentInfo = getPersistentOrganizerInfo(context);
events = persistentInfo.getEvents();
if (!events.contains(event) && event!=null){
events.add(event);
}
persistentInfo.setEvents(events);
setPersistentOrganizerInfo(context, persistentInfo);
}
public Event modifyEvent(Context context,Event eventToModiy, Event eventModified) {
PersistentOrganizerInfo persistentInfo = getPersistentOrganizerInfo(context);
events = persistentInfo.getEvents();
Event tomodify;
if (events.contains(eventToModiy) && eventModified!=null){
int index= events.indexOf(eventToModiy);
tomodify = events.get(index);
tomodify.modify(eventModified);
persistentInfo.setEvents(events);
//System.out.println(events);
setPersistentOrganizerInfo(context, persistentInfo);
return tomodify;
}
return null;
}
public void deleteEvent(Context context, Event event) {
PersistentOrganizerInfo persistentInfo = getPersistentOrganizerInfo(context);
events = persistentInfo.getEvents();
if (events.contains(event) && event!=null){
events.remove(event);
System.out.println(events);
}
persistentInfo.setEvents(events);
setPersistentOrganizerInfo(context, persistentInfo);
}
}
| UTF-8 | Java | 4,095 | java | PersistentOrganizerInfo.java | Java | [
{
"context": "package com.apmuei.findmyrhythm.Model;\n\nimport android.content.Conte",
"end": 18,
"score": 0.804009199142456,
"start": 12,
"tag": "USERNAME",
"value": "apmuei"
},
{
"context": "Name(name);\n persistentOrgInfo.setUsername(username);\n persistentOrgInfo.se... | null | [] | package com.apmuei.findmyrhythm.Model;
import android.content.Context;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
public class PersistentOrganizerInfo extends Organizer {
private ArrayList<Event> events;
public PersistentOrganizerInfo(String id, String name, String username, String email, String biography, String rating, String location, ArrayList<Event> events) {
super(id, name, username, email, biography, rating, location);
this.events = events;
}
public void updateInfo(Context context, String name, String username, String email, String biography, String location) {
PersistentOrganizerInfo persistentOrgInfo = (PersistentOrganizerInfo) PersistentOrganizerInfo.getPersistentOrganizerInfo(context);
persistentOrgInfo.setName(name);
persistentOrgInfo.setUsername(username);
persistentOrgInfo.setEmail(email);
persistentOrgInfo.setBiography(biography);
persistentOrgInfo.setLocation(location);
PersistentOrganizerInfo.setPersistentOrganizerInfo(context, persistentOrgInfo);
}
public ArrayList<Event> getEvents() {
return events;
}
public Event getEvent(String id){
//System.out.println(id);
for (Event event:events){
//System.out.println(event.getId());
if(event.getId().equals(id)) return event;
}
return null;
}
public void setEvents(ArrayList<Event> events) {
this.events = events;
}
public static PersistentOrganizerInfo getPersistentOrganizerInfo(Context context) {
Gson gson = new Gson();
PersistentOrganizerInfo persistentOrganizerInfo = null;
try {
persistentOrganizerInfo = gson.fromJson(new FileReader(context.getFilesDir().getPath() + "persistent_info.json"), PersistentOrganizerInfo.class);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return persistentOrganizerInfo;
}
public static void setPersistentOrganizerInfo(Context context, PersistentOrganizerInfo persistentOrganizerInfo) {
try (Writer writer = new FileWriter(context.getFilesDir().getPath() + "persistent_info.json")) {
Gson gson = new GsonBuilder().create();
gson.toJson(persistentOrganizerInfo, writer);
} catch (IOException e) {
e.printStackTrace();
}
}
public void addEvent(Context context, Event event) {
PersistentOrganizerInfo persistentInfo = getPersistentOrganizerInfo(context);
events = persistentInfo.getEvents();
if (!events.contains(event) && event!=null){
events.add(event);
}
persistentInfo.setEvents(events);
setPersistentOrganizerInfo(context, persistentInfo);
}
public Event modifyEvent(Context context,Event eventToModiy, Event eventModified) {
PersistentOrganizerInfo persistentInfo = getPersistentOrganizerInfo(context);
events = persistentInfo.getEvents();
Event tomodify;
if (events.contains(eventToModiy) && eventModified!=null){
int index= events.indexOf(eventToModiy);
tomodify = events.get(index);
tomodify.modify(eventModified);
persistentInfo.setEvents(events);
//System.out.println(events);
setPersistentOrganizerInfo(context, persistentInfo);
return tomodify;
}
return null;
}
public void deleteEvent(Context context, Event event) {
PersistentOrganizerInfo persistentInfo = getPersistentOrganizerInfo(context);
events = persistentInfo.getEvents();
if (events.contains(event) && event!=null){
events.remove(event);
System.out.println(events);
}
persistentInfo.setEvents(events);
setPersistentOrganizerInfo(context, persistentInfo);
}
}
| 4,095 | 0.684005 | 0.684005 | 112 | 35.5625 | 33.880772 | 166 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.758929 | false | false | 12 |
9c5e077f5b790905ee772525b316427f86cc3d23 | 3,435,973,860,377 | f5faaea2a565d69be257744860c13d52a3fe2b0e | /nerve/converter/converter-lib/src/main/java/network/nerve/converter/heterogeneouschain/lib/helper/HtgParseTxHelper.java | e16a99e063a0c0f70c1aba72f064d36632e5a729 | [
"MIT"
] | permissive | NerveNetwork/nerve | https://github.com/NerveNetwork/nerve | 6e449bc329a649547af85b1e8fa8b104bf10f660 | 7379bdab28f62e1c7be6e9e72dcd55aa670b593a | refs/heads/master | 2023-08-03T14:47:18.894000 | 2023-07-29T11:17:32 | 2023-07-29T11:17:32 | 238,840,114 | 104 | 33 | MIT | false | 2022-06-02T09:51:11 | 2020-02-07T04:01:12 | 2022-01-21T16:13:48 | 2022-06-02T09:51:09 | 60,098 | 86 | 32 | 64 | Java | false | false | /**
* MIT License
* <p>
* Copyright (c) 2019-2022 nerve.network
* <p>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package network.nerve.converter.heterogeneouschain.lib.helper;
import io.nuls.core.log.logback.NulsLogger;
import io.nuls.core.model.StringUtils;
import network.nerve.converter.enums.HeterogeneousChainTxType;
import network.nerve.converter.heterogeneouschain.lib.context.HtgConstant;
import network.nerve.converter.heterogeneouschain.lib.context.HtgContext;
import network.nerve.converter.heterogeneouschain.lib.core.HtgWalletApi;
import network.nerve.converter.heterogeneouschain.lib.listener.HtgListener;
import network.nerve.converter.heterogeneouschain.lib.management.BeanInitial;
import network.nerve.converter.heterogeneouschain.lib.model.HtgInput;
import network.nerve.converter.heterogeneouschain.lib.storage.HtgTxStorageService;
import network.nerve.converter.heterogeneouschain.lib.utils.HtgUtil;
import network.nerve.converter.model.bo.*;
import org.web3j.abi.FunctionReturnDecoder;
import org.web3j.abi.datatypes.Address;
import org.web3j.abi.datatypes.Function;
import org.web3j.abi.datatypes.Type;
import org.web3j.protocol.core.methods.response.Log;
import org.web3j.protocol.core.methods.response.Transaction;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.utils.Numeric;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author: Mimi
* @date: 2020-03-20
*/
public class HtgParseTxHelper implements BeanInitial {
private HtgERC20Helper htgERC20Helper;
private HtgTxStorageService htgTxStorageService;
private HtgWalletApi htgWalletApi;
private HtgListener htgListener;
private HtgContext htgContext;
private NulsLogger logger() {
return htgContext.logger();
}
public boolean isCompletedTransaction(String nerveTxHash) throws Exception {
return isCompletedTransactionByStatus(nerveTxHash, false);
}
public boolean isCompletedTransactionByLatest(String nerveTxHash) throws Exception {
return isCompletedTransactionByStatus(nerveTxHash, true);
}
private boolean isCompletedTransactionByStatus(String nerveTxHash, boolean latest) throws Exception {
Function isCompletedFunction = HtgUtil.getIsCompletedFunction(nerveTxHash);
List<Type> valueTypes = htgWalletApi.callViewFunction(htgContext.MULTY_SIGN_ADDRESS(), isCompletedFunction, latest);
if (valueTypes == null || valueTypes.size() == 0) {
return false;
}
boolean isCompleted = Boolean.parseBoolean(valueTypes.get(0).getValue().toString());
return isCompleted;
}
public boolean isMinterERC20(String erc20) throws Exception {
return isMinterERC20ByStatus(erc20, false);
}
public boolean isMinterERC20ByLatest(String erc20) throws Exception {
return isMinterERC20ByStatus(erc20, true);
}
private boolean isMinterERC20ByStatus(String erc20, boolean latest) throws Exception {
if (StringUtils.isBlank(erc20)) {
return true;
}
Function isMinterERC20Function = HtgUtil.getIsMinterERC20Function(erc20);
List<Type> valueTypes = htgWalletApi.callViewFunction(htgContext.MULTY_SIGN_ADDRESS(), isMinterERC20Function, latest);
boolean isMinterERC20 = Boolean.parseBoolean(valueTypes.get(0).getValue().toString());
return isMinterERC20;
}
/**
* 解析提现交易数据
*/
public HeterogeneousTransactionInfo parseWithdrawTransaction(Transaction tx, TransactionReceipt txReceipt) throws Exception {
if (tx == null) {
logger().warn("解析交易的数据不存在或不完整");
return null;
}
String txHash = tx.getHash();
HeterogeneousTransactionInfo txInfo = HtgUtil.newTransactionInfo(tx, htgContext.NERVE_CHAINID(), this, logger());
boolean isWithdraw;
if (tx.getInput().length() < 10) {
logger().warn("不是提现交易[0]");
return null;
}
String methodNameHash = tx.getInput().substring(0, 10);
// 提现交易的固定地址
if (htgListener.isListeningAddress(tx.getTo()) &&
HtgConstant.METHOD_HASH_CREATEORSIGNWITHDRAW.equals(methodNameHash)) {
if (txReceipt == null) {
txReceipt = htgWalletApi.getTxReceipt(txHash);
}
// 解析交易收据
if (htgContext.getConverterCoreApi().isProtocol21()) {
// 协议v1.21
isWithdraw = this.newParseWithdrawTxReceiptSinceProtocol21(tx, txReceipt, txInfo);
} else if (htgContext.getConverterCoreApi().isSupportProtocol13NewValidationOfERC20()) {
// 协议v1.13
isWithdraw = this.newParseWithdrawTxReceipt(tx, txReceipt, txInfo);
} else {
isWithdraw = this.parseWithdrawTxReceipt(txReceipt, txInfo);
}
if (!isWithdraw) {
logger().warn("不是提现交易[1], hash: {}", txHash);
return null;
}
if (txInfo.isIfContractAsset()) {
htgERC20Helper.loadERC20(txInfo.getContractAddress(), txInfo);
}
} else {
logger().warn("不是提现交易[2], hash: {}, txTo: {}, methodNameHash: {}", txHash, tx.getTo(), methodNameHash);
return null;
}
txInfo.setTxType(HeterogeneousChainTxType.WITHDRAW);
// 解析多签列表
this.loadSigners(txReceipt, txInfo);
return txInfo;
}
public HeterogeneousTransactionInfo parseWithdrawTransaction(Transaction tx) throws Exception {
return this.parseWithdrawTransaction(tx, null);
}
public HeterogeneousTransactionInfo parseWithdrawTransaction(String txHash) throws Exception {
Transaction tx = htgWalletApi.getTransactionByHash(txHash);
if (tx == null) {
logger().warn("交易不存在");
return null;
}
if (tx.getTo() == null) {
logger().warn("不是提现交易");
return null;
}
tx.setFrom(tx.getFrom().toLowerCase());
tx.setTo(tx.getTo().toLowerCase());
return this.parseWithdrawTransaction(tx, null);
}
/**
* 解析直接转账的方式的充值交易数据
*/
private HeterogeneousTransactionInfo parseDepositTransactionByTransferDirectly(Transaction tx, TransactionReceipt txReceipt) throws Exception {
if (tx == null) {
logger().warn("交易不存在");
return null;
}
String txHash = tx.getHash();
HeterogeneousTransactionInfo txInfo = HtgUtil.newTransactionInfo(tx, htgContext.NERVE_CHAINID(), this, logger());
boolean isDeposit = false;
if (txReceipt == null) {
txReceipt = htgWalletApi.getTxReceipt(txHash);
}
do {
// HT充值交易的固定接收地址,金额大于0, 没有input
if (htgListener.isListeningAddress(tx.getTo()) &&
tx.getValue().compareTo(BigInteger.ZERO) > 0 &&
tx.getInput().equals(HtgConstant.HEX_PREFIX)) {
if(!this.validationEthDeposit(tx, txReceipt)) {
logger().error("[{}]不是充值交易[0]", txHash);
return null;
}
isDeposit = true;
txInfo.setDecimals(htgContext.getConfig().getDecimals());
txInfo.setAssetId(htgContext.HTG_ASSET_ID());
txInfo.setValue(tx.getValue());
txInfo.setIfContractAsset(false);
break;
}
// ERC20充值交易
if (htgERC20Helper.isERC20(tx.getTo(), txInfo)) {
if (htgERC20Helper.hasERC20WithListeningAddress(txReceipt, txInfo, address -> htgListener.isListeningAddress(address))) {
// 检查是否是NERVE资产绑定的ERC20,是则检查多签合约内是否已经注册此定制的ERC20,否则充值异常
if (htgContext.getConverterCoreApi().isBoundHeterogeneousAsset(htgContext.getConfig().getChainId(), txInfo.getAssetId())
&& !isMinterERC20(txInfo.getContractAddress())) {
logger().warn("[{}]不合法的{}网络的充值交易[6], ERC20[{}]已绑定NERVE资产,但合约内未注册", txHash, htgContext.getConfig().getSymbol(), txInfo.getContractAddress());
break;
}
isDeposit = true;
break;
}
}
} while (false);
if (!isDeposit) {
logger().error("[{}]不是充值交易[1]", txHash);
return null;
}
txInfo.setTxType(HeterogeneousChainTxType.DEPOSIT);
return txInfo;
}
public BigInteger getTxHeight(NulsLogger logger, Transaction tx) throws Exception {
try {
if (tx == null) {
return null;
}
return tx.getBlockNumber();
} catch (Exception e) {
String txHash = tx.getHash();
logger.error("解析充值交易错误, 区块高度解析失败, 交易hash: {}, BlockNumberRaw: {}, BlockHash: {}", txHash, tx.getBlockNumberRaw(), tx.getBlockHash());
TransactionReceipt txReceipt = null;
try {
txReceipt = htgWalletApi.getTxReceipt(txHash);
return txReceipt.getBlockNumber();
} catch (Exception ex) {
if (txReceipt != null) {
logger.error("再次解析充值交易错误, 区块高度解析失败, 交易hash: {}, BlockNumberRaw: {}, BlockHash: {}", txHash, txReceipt.getBlockNumberRaw(), txReceipt.getBlockHash());
} else {
logger.error("再次解析充值交易错误, 区块高度解析失败, 交易hash: {}, empty txReceipt.", txHash);
}
throw ex;
}
}
}
public HeterogeneousTransactionInfo parseDepositTransaction(Transaction tx) throws Exception {
HtgInput htInput = this.parseInput(tx.getInput());
// 新的充值交易方式,调用多签合约的crossOut函数
if (htInput.isDepositTx()) {
HeterogeneousTransactionInfo po = new HeterogeneousTransactionInfo();
po.setTxHash(tx.getHash());
po.setBlockHeight(getTxHeight(logger(), tx).longValue());
boolean isDepositTx = this.validationEthDepositByCrossOut(tx, po);
if (!isDepositTx) {
return null;
}
po.setTxType(HeterogeneousChainTxType.DEPOSIT);
return po;
}
// 新的充值交易方式II,调用多签合约的crossOutII函数
if (htInput.isDepositIITx()) {
HeterogeneousTransactionInfo po = new HeterogeneousTransactionInfo();
po.setTxHash(tx.getHash());
po.setBlockHeight(getTxHeight(logger(), tx).longValue());
boolean isDepositTx = this.validationEthDepositByCrossOutII(tx, null, po);
if (!isDepositTx) {
return null;
}
po.setTxType(HeterogeneousChainTxType.DEPOSIT);
return po;
}
return this.parseDepositTransactionByTransferDirectly(tx, null);
}
public HeterogeneousTransactionInfo parseDepositTransaction(String txHash) throws Exception {
Transaction tx = htgWalletApi.getTransactionByHash(txHash);
if (tx == null) {
logger().warn("交易不存在");
return null;
}
if (tx.getTo() == null) {
logger().warn("不是充值交易");
return null;
}
tx.setFrom(tx.getFrom().toLowerCase());
tx.setTo(tx.getTo().toLowerCase());
return this.parseDepositTransaction(tx);
}
public boolean validationEthDeposit(Transaction tx) throws Exception {
return this.validationEthDeposit(tx, null);
}
private boolean validationEthDeposit(Transaction tx, TransactionReceipt txReceipt) throws Exception {
if (tx == null) {
logger().warn("交易不存在");
return false;
}
String txHash = tx.getHash();
if (txReceipt == null) {
txReceipt = htgWalletApi.getTxReceipt(txHash);
}
List<Log> logs = txReceipt.getLogs();
if (logs == null || logs.isEmpty()) {
return false;
}
for (Log log : logs) {
List<String> topics = log.getTopics();
if (log.getTopics().size() == 0) {
continue;
}
String eventHash = topics.get(0);
if (!HtgConstant.EVENT_HASH_HT_DEPOSIT_FUNDS.equals(eventHash)) {
continue;
}
List<Object> depositEvent = HtgUtil.parseEvent(log.getData(), HtgConstant.EVENT_DEPOSIT_FUNDS);
if (depositEvent == null && depositEvent.size() != 2) {
return false;
}
String from = depositEvent.get(0).toString();
BigInteger amount = new BigInteger(depositEvent.get(1).toString());
if (tx.getFrom().equals(from) && tx.getValue().compareTo(amount) == 0) {
return true;
}
}
return false;
}
public boolean validationEthDepositByCrossOut(Transaction tx, HeterogeneousTransactionInfo po) throws Exception {
return this.validationEthDepositByCrossOut(tx, null, po);
}
private boolean validationEthDepositByCrossOut(Transaction tx, TransactionReceipt txReceipt, HeterogeneousTransactionInfo po) throws Exception {
if (htgContext.getConverterCoreApi().isProtocol22()) {
return newValidationEthDepositByCrossOutProtocol22(tx, txReceipt, po);
} else if (htgContext.getConverterCoreApi().isSupportProtocol13NewValidationOfERC20()) {
return newValidationEthDepositByCrossOut(tx, txReceipt, po);
} else {
return _validationEthDepositByCrossOut(tx, txReceipt, po);
}
}
private boolean _validationEthDepositByCrossOut(Transaction tx, TransactionReceipt txReceipt, HeterogeneousTransactionInfo po) throws Exception {
if (tx == null) {
logger().warn("交易不存在");
return false;
}
String txHash = tx.getHash();
if (txReceipt == null) {
txReceipt = htgWalletApi.getTxReceipt(txHash);
}
List<Log> logs = txReceipt.getLogs();
if (logs == null || logs.isEmpty()) {
logger().warn("交易[{}]事件为空", txHash);
return false;
}
int logSize = logs.size();
if (logSize == 1) {
// HTG充值交易
Log log = logs.get(0);
List<String> topics = log.getTopics();
if (log.getTopics().size() == 0) {
logger().warn("交易[{}]log未知", txHash);
return false;
}
String eventHash = topics.get(0);
if (!HtgConstant.EVENT_HASH_CROSS_OUT_FUNDS.equals(eventHash)) {
logger().warn("交易[{}]事件未知", txHash);
return false;
}
List<Object> depositEvent = HtgUtil.parseEvent(log.getData(), HtgConstant.EVENT_CROSS_OUT_FUNDS);
if (depositEvent == null && depositEvent.size() != 4) {
logger().warn("交易[{}]CrossOut事件数据不合法[0]", txHash);
return false;
}
String from = depositEvent.get(0).toString();
String to = depositEvent.get(1).toString();
BigInteger amount = new BigInteger(depositEvent.get(2).toString());
String erc20 = depositEvent.get(3).toString();
if (tx.getFrom().equals(from) && tx.getValue().compareTo(amount) == 0 && HtgConstant.ZERO_ADDRESS.equals(erc20)) {
if (po != null) {
po.setIfContractAsset(false);
po.setFrom(from);
po.setTo(tx.getTo());
po.setValue(amount);
po.setDecimals(htgContext.getConfig().getDecimals());
po.setAssetId(htgContext.HTG_ASSET_ID());
po.setNerveAddress(to);
}
return true;
}
} else {
// ERC20充值交易
List<Object> crossOutInput = HtgUtil.parseInput(tx.getInput(), HtgConstant.INPUT_CROSS_OUT);
String _to = crossOutInput.get(0).toString();
BigInteger _amount = new BigInteger(crossOutInput.get(1).toString());
String _erc20 = crossOutInput.get(2).toString().toLowerCase();
if (!htgERC20Helper.isERC20(_erc20, po)) {
logger().warn("erc20[{}]未注册", _erc20);
return false;
}
boolean transferEvent = false;
boolean burnEvent = true;
boolean crossOutEvent = false;
BigInteger actualAmount = _amount;
for (Log log : logs) {
List<String> topics = log.getTopics();
String eventHash = topics.get(0);
String eventContract = log.getAddress().toLowerCase();
if (HtgConstant.EVENT_HASH_ERC20_TRANSFER.equals(eventHash)) {
if (!eventContract.equals(_erc20)) {
logger().warn("交易[{}]的ERC20地址不匹配", txHash);
return false;
}
int length = topics.get(1).length();
String fromAddress = HtgConstant.HEX_PREFIX + topics.get(1).substring(26, length).toString();
String toAddress = HtgConstant.HEX_PREFIX + topics.get(2).substring(26, length).toString();
String data;
if (topics.size() == 3) {
data = log.getData();
} else {
data = topics.get(3);
}
String[] v = data.split("x");
// 转账金额
BigInteger amount = new BigInteger(v[1], 16);
// 当toAddress是0x0时,则说明这是一个从当前多签合约销毁erc20的事件
if (HtgConstant.ZERO_ADDRESS.equals(toAddress)) {
if (!fromAddress.equals(htgContext.MULTY_SIGN_ADDRESS())) {
logger().warn("交易[{}]的销毁地址不匹配", txHash);
burnEvent = false;
break;
}
if (amount.compareTo(_amount) != 0) {
logger().warn("交易[{}]的ERC20销毁金额不匹配", txHash);
burnEvent = false;
break;
}
} else {
// 用户转移token到多签合约的事件
// 必须是用户地址
if (!fromAddress.equals(tx.getFrom())) {
logger().warn("交易[{}]的ERC20用户地址不匹配", txHash);
return false;
}
// 必须是多签合约地址
if (!toAddress.equals(htgContext.MULTY_SIGN_ADDRESS())) {
logger().warn("交易[{}]的ERC20充值地址不匹配", txHash);
return false;
}
// 是否支持转账即销毁部分的ERC20
if (htgContext.getConverterCoreApi().isSupportProtocol12ERC20OfTransferBurn()) {
if (amount.compareTo(_amount) > 0) {
logger().warn("交易[{}]的ERC20充值金额不匹配", txHash);
return false;
}
actualAmount = amount;
} else {
if (amount.compareTo(_amount) != 0) {
logger().warn("交易[{}]的ERC20充值金额不匹配", txHash);
return false;
}
}
transferEvent = true;
}
}
if (HtgConstant.EVENT_HASH_CROSS_OUT_FUNDS.equals(eventHash)) {
List<Object> depositEvent = HtgUtil.parseEvent(log.getData(), HtgConstant.EVENT_CROSS_OUT_FUNDS);
if (depositEvent == null && depositEvent.size() != 4) {
logger().warn("交易[{}]CrossOut事件数据不合法[1]", txHash);
return false;
}
String from = depositEvent.get(0).toString();
String to = depositEvent.get(1).toString();
BigInteger amount = new BigInteger(depositEvent.get(2).toString());
String erc20 = depositEvent.get(3).toString();
if (!tx.getFrom().equals(from)) {
logger().warn("交易[{}]CrossOut事件数据不合法[2]", txHash);
return false;
}
if (!_to.equals(to)) {
logger().warn("交易[{}]CrossOut事件数据不合法[3]", txHash);
return false;
}
if (amount.compareTo(_amount) != 0) {
logger().warn("交易[{}]CrossOut事件数据不合法[4]", txHash);
return false;
}
if (!_erc20.equals(erc20)) {
logger().warn("交易[{}]CrossOut事件数据不合法[5]", txHash);
return false;
}
crossOutEvent = true;
}
}
if (transferEvent && burnEvent && crossOutEvent) {
if (po != null && actualAmount.compareTo(BigInteger.ZERO) > 0) {
po.setIfContractAsset(true);
po.setContractAddress(_erc20);
po.setFrom(tx.getFrom());
po.setTo(tx.getTo());
po.setValue(actualAmount);
po.setNerveAddress(_to);
}
return true;
}
}
return false;
}
/**
* 解析管理员变更交易数据
*/
public HeterogeneousTransactionInfo parseManagerChangeTransaction(Transaction tx, TransactionReceipt txReceipt) throws Exception {
if (tx == null) {
logger().warn("交易不存在");
return null;
}
HeterogeneousTransactionInfo txInfo = HtgUtil.newTransactionInfo(tx, htgContext.NERVE_CHAINID(), this, logger());
boolean isChange = false;
String input, methodHash;
if (htgListener.isListeningAddress(tx.getTo()) && (input = tx.getInput()).length() >= 10) {
methodHash = input.substring(0, 10);
if (methodHash.equals(HtgConstant.METHOD_HASH_CREATEORSIGNMANAGERCHANGE)) {
isChange = true;
List<Object> inputData = HtgUtil.parseInput(input, HtgConstant.INPUT_CHANGE);
List<Address> adds = (List<Address>) inputData.get(1);
List<Address> quits = (List<Address>) inputData.get(2);
if (!adds.isEmpty()) {
txInfo.setAddAddresses(HtgUtil.list2array(adds.stream().map(a -> a.getValue()).collect(Collectors.toList())));
}
if (!quits.isEmpty()) {
txInfo.setRemoveAddresses(HtgUtil.list2array(quits.stream().map(q -> q.getValue()).collect(Collectors.toList())));
}
}
}
if (!isChange) {
logger().warn("不是变更交易");
return null;
}
txInfo.setTxType(HeterogeneousChainTxType.CHANGE);
// 解析多签列表
this.loadSigners(txReceipt, txInfo);
return txInfo;
}
/**
* 解析合约升级授权交易数据
*/
public HeterogeneousTransactionInfo parseUpgradeTransaction(Transaction tx, TransactionReceipt txReceipt) throws Exception {
if (tx == null) {
logger().warn("交易不存在");
return null;
}
HeterogeneousTransactionInfo txInfo = HtgUtil.newTransactionInfo(tx, htgContext.NERVE_CHAINID(), this, logger());
boolean isUpgrade = false;
String input, methodHash;
if (htgListener.isListeningAddress(tx.getTo()) && (input = tx.getInput()).length() >= 10) {
methodHash = input.substring(0, 10);
if (methodHash.equals(HtgConstant.METHOD_HASH_CREATEORSIGNUPGRADE)) {
isUpgrade = true;
}
}
if (!isUpgrade) {
logger().warn("不是合约升级授权交易");
return null;
}
txInfo.setTxType(HeterogeneousChainTxType.UPGRADE);
// 解析多签列表
this.loadSigners(txReceipt, txInfo);
return txInfo;
}
public List<HeterogeneousAddress> parseSigners(TransactionReceipt txReceipt, String txFrom) {
List<Object> eventResult = this.loadDataFromEvent(txReceipt);
if (eventResult == null || eventResult.isEmpty()) {
return null;
}
List<HeterogeneousAddress> signers = new ArrayList<>();
signers.add(new HeterogeneousAddress(htgContext.getConfig().getChainId(), txFrom));
return signers;
}
private void loadSigners(TransactionReceipt txReceipt, HeterogeneousTransactionInfo txInfo) {
List<Object> eventResult = this.loadDataFromEvent(txReceipt);
if (eventResult != null && !eventResult.isEmpty()) {
txInfo.setNerveTxHash(eventResult.get(eventResult.size() - 1).toString());
List<HeterogeneousAddress> signers = new ArrayList<>();
signers.add(new HeterogeneousAddress(htgContext.getConfig().getChainId(), txInfo.getFrom()));
txInfo.setSigners(signers);
}
}
private List<Object> loadDataFromEvent(TransactionReceipt txReceipt) {
List<Log> logs = txReceipt.getLogs();
if (logs == null || logs.isEmpty()) {
return null;
}
Log signerLog = null;
for (Log log : logs) {
List<String> topics = log.getTopics();
if (topics != null && topics.size() > 0) {
String eventHash = topics.get(0);
if (HtgConstant.TRANSACTION_COMPLETED_TOPICS.contains(eventHash)) {
signerLog = log;
break;
}
}
}
if (signerLog == null) {
return null;
}
String eventHash = signerLog.getTopics().get(0);
//// Polygon链,存在erc20转账的合约交易中,会在末尾多出一个未知事件
//if (htgContext.getConfig().getChainId() == 106) {
// if (HtgConstant.EVENT_HASH_UNKNOWN_ON_POLYGON.equals(eventHash)) {
// log = logs.get(logs.size() - 2);
// topics = log.getTopics();
// eventHash = topics.get(0);
// }
//} else if (htgContext.getConfig().getChainId() == 122) {
// // REI链,存在erc20转账的合约交易中,会在末尾多出一个未知事件
// if (HtgConstant.EVENT_HASH_UNKNOWN_ON_REI.equals(eventHash)) {
// log = logs.get(logs.size() - 2);
// topics = log.getTopics();
// eventHash = topics.get(0);
// }
//}
// topics 解析事件名, 签名完成会触发的事件
// 解析事件数据,获得交易的成功事件数据列表
List<Object> eventResult = null;
switch (eventHash) {
case HtgConstant.EVENT_HASH_TRANSACTION_WITHDRAW_COMPLETED:
eventResult = HtgUtil.parseEvent(signerLog.getData(), HtgConstant.EVENT_TRANSACTION_WITHDRAW_COMPLETED);
break;
case HtgConstant.EVENT_HASH_TRANSACTION_MANAGER_CHANGE_COMPLETED:
eventResult = HtgUtil.parseEvent(signerLog.getData(), HtgConstant.EVENT_TRANSACTION_MANAGER_CHANGE_COMPLETED);
break;
case HtgConstant.EVENT_HASH_TRANSACTION_UPGRADE_COMPLETED:
eventResult = HtgUtil.parseEvent(signerLog.getData(), HtgConstant.EVENT_TRANSACTION_UPGRADE_COMPLETED);
break;
}
return eventResult;
}
private boolean parseWithdrawTxReceipt(TransactionReceipt txReceipt, HeterogeneousTransactionBaseInfo po) {
if (txReceipt == null || !txReceipt.isStatusOK()) {
return false;
}
List<Log> logs = txReceipt.getLogs();
if (logs != null && logs.size() > 0) {
for (Log log : logs) {
List<String> topics = log.getTopics();
if (topics.size() == 0) {
continue;
}
// 为ERC20提现
if (topics.get(0).equals(HtgConstant.EVENT_HASH_ERC20_TRANSFER)) {
String toAddress = HtgConstant.HEX_PREFIX + topics.get(2).substring(26, topics.get(1).length()).toString();
String data;
if (topics.size() == 3) {
data = log.getData();
} else {
data = topics.get(3);
}
String[] v = data.split("x");
// 转账金额
BigInteger amount = new BigInteger(v[1], 16);
if (amount.compareTo(BigInteger.ZERO) > 0) {
po.setIfContractAsset(true);
po.setContractAddress(log.getAddress().toLowerCase());
po.setTo(toAddress.toLowerCase());
po.setValue(amount);
return true;
}
return false;
}
// 为HT提现
if (topics.get(0).equals(HtgConstant.EVENT_HASH_TRANSFERFUNDS)) {
String data = log.getData();
String to = HtgConstant.HEX_PREFIX + data.substring(26, 66);
String amountStr = data.substring(66, 130);
// 转账金额
BigInteger amount = new BigInteger(amountStr, 16);
if (amount.compareTo(BigInteger.ZERO) > 0) {
po.setTo(to.toLowerCase());
po.setValue(amount);
po.setDecimals(htgContext.getConfig().getDecimals());
po.setAssetId(htgContext.HTG_ASSET_ID());
return true;
}
return false;
}
}
}
return false;
}
public HtgInput parseInput(String input) {
if (input.length() < 10) {
return HtgInput.empty();
}
String methodHash;
if ((methodHash = input.substring(0, 10)).equals(HtgConstant.METHOD_HASH_CREATEORSIGNWITHDRAW)) {
return new HtgInput(true, HeterogeneousChainTxType.WITHDRAW, HtgUtil.parseInput(input, HtgConstant.INPUT_WITHDRAW).get(0).toString());
}
if (methodHash.equals(HtgConstant.METHOD_HASH_CREATEORSIGNMANAGERCHANGE)) {
return new HtgInput(true, HeterogeneousChainTxType.CHANGE, HtgUtil.parseInput(input, HtgConstant.INPUT_CHANGE).get(0).toString());
}
if (methodHash.equals(HtgConstant.METHOD_HASH_CREATEORSIGNUPGRADE)) {
return new HtgInput(true, HeterogeneousChainTxType.UPGRADE, HtgUtil.parseInput(input, HtgConstant.INPUT_UPGRADE).get(0).toString());
}
if (methodHash.equals(HtgConstant.METHOD_HASH_CROSS_OUT)) {
return new HtgInput(true, HeterogeneousChainTxType.DEPOSIT);
}
if (methodHash.equals(HtgConstant.METHOD_HASH_CROSS_OUT_II)) {
return new HtgInput(true);
}
return HtgInput.empty();
}
public HeterogeneousOneClickCrossChainData parseOneClickCrossChainData(String extend, NulsLogger logger) {
if(StringUtils.isBlank(extend)) {
return null;
}
extend = Numeric.prependHexPrefix(extend);
if(extend.length() < 10) {
return null;
}
String methodHash = extend.substring(0, 10);
if (!HtgConstant.METHOD_HASH_ONE_CLICK_CROSS_CHAIN.equals(methodHash)) {
return null;
}
extend = HtgConstant.HEX_PREFIX + extend.substring(10);
try {
List<Type> typeList = FunctionReturnDecoder.decode(extend, HtgConstant.INPUT_ONE_CLICK_CROSS_CHAIN);
if (typeList == null || typeList.isEmpty()) {
return null;
}
if (typeList.size() < 6) {
return null;
}
int index = 0;
List<Object> list = typeList.stream().map(type -> type.getValue()).collect(Collectors.toList());
BigInteger feeAmount = (BigInteger) list.get(index++);
int desChainId = ((BigInteger) list.get(index++)).intValue();
String desToAddress = (String) list.get(index++);
BigInteger tipping = (BigInteger) list.get(index++);
String tippingAddress = (String) list.get(index++);
String desExtend = Numeric.toHexString((byte[]) list.get(index++));
return new HeterogeneousOneClickCrossChainData(feeAmount, desChainId, desToAddress, tipping == null ? BigInteger.ZERO : tipping, tippingAddress, desExtend);
} catch (Exception e) {
logger.error(e);
return null;
}
}
public HeterogeneousAddFeeCrossChainData parseAddFeeCrossChainData(String extend, NulsLogger logger) {
if(StringUtils.isBlank(extend)) {
return null;
}
extend = Numeric.prependHexPrefix(extend);
if(extend.length() < 10) {
return null;
}
String methodHash = extend.substring(0, 10);
if (!HtgConstant.METHOD_HASH_ADD_FEE_CROSS_CHAIN.equals(methodHash)) {
return null;
}
extend = HtgConstant.HEX_PREFIX + extend.substring(10);
try {
List<Type> typeList = FunctionReturnDecoder.decode(extend, HtgConstant.INPUT_ADD_FEE_CROSS_CHAIN);
if (typeList == null || typeList.isEmpty()) {
return null;
}
if (typeList.size() < 2) {
return null;
}
int index = 0;
List<Object> list = typeList.stream().map(type -> type.getValue()).collect(Collectors.toList());
String nerveTxHash = (String) list.get(index++);
String subExtend = Numeric.toHexString((byte[]) list.get(index++));
return new HeterogeneousAddFeeCrossChainData(nerveTxHash, subExtend);
} catch (Exception e) {
logger.error(e);
return null;
}
}
private boolean newValidationEthDepositByCrossOutProtocol22(Transaction tx, TransactionReceipt txReceipt, HeterogeneousTransactionInfo po) throws Exception {
if (tx == null) {
logger().warn("交易不存在");
return false;
}
String txHash = tx.getHash();
if (txReceipt == null) {
txReceipt = htgWalletApi.getTxReceipt(txHash);
}
List<Log> logs = txReceipt.getLogs();
if (logs == null || logs.isEmpty()) {
logger().warn("交易[{}]事件为空", txHash);
return false;
}
List<Object> crossOutInput = HtgUtil.parseInput(tx.getInput(), HtgConstant.INPUT_CROSS_OUT);
String _to = crossOutInput.get(0).toString();
BigInteger _amount = new BigInteger(crossOutInput.get(1).toString());
String _erc20 = crossOutInput.get(2).toString().toLowerCase();
if (HtgConstant.ZERO_ADDRESS.equals(_erc20)) {
// 主资产充值交易
for (Log log : logs) {
List<String> topics = log.getTopics();
if (log.getTopics().size() == 0) {
continue;
}
String eventHash = topics.get(0);
String eventContract = log.getAddress().toLowerCase();
if (!HtgConstant.EVENT_HASH_CROSS_OUT_FUNDS.equals(eventHash)) {
continue;
}
if (!eventContract.equals(htgContext.MULTY_SIGN_ADDRESS())) {
continue;
}
List<Object> depositEvent = HtgUtil.parseEvent(log.getData(), HtgConstant.EVENT_CROSS_OUT_FUNDS);
if (depositEvent == null && depositEvent.size() != 4) {
logger().warn("交易[{}]CrossOut事件数据不合法[0]", txHash);
return false;
}
String from = depositEvent.get(0).toString();
String to = depositEvent.get(1).toString();
BigInteger amount = new BigInteger(depositEvent.get(2).toString());
String erc20 = depositEvent.get(3).toString();
if (tx.getFrom().equals(from) && tx.getValue().compareTo(amount) == 0 && HtgConstant.ZERO_ADDRESS.equals(erc20)) {
if (po != null) {
po.setIfContractAsset(false);
po.setFrom(from);
po.setTo(tx.getTo());
po.setValue(amount);
po.setDecimals(htgContext.getConfig().getDecimals());
po.setAssetId(htgContext.HTG_ASSET_ID());
po.setNerveAddress(to);
}
return true;
}
}
logger().warn("交易[{}]的主资产[{}]充值事件不匹配", txHash, htgContext.getConfig().getSymbol());
return false;
} else {
// ERC20充值交易
if (!htgERC20Helper.isERC20(_erc20, po)) {
logger().warn("erc20[{}]未注册", _erc20);
return false;
}
boolean transferEvent = false;
boolean burnEvent = true;
boolean crossOutEvent = false;
BigInteger actualAmount;
BigInteger calcAmount = BigInteger.ZERO;
for (Log log : logs) {
List<String> topics = log.getTopics();
if (topics.size() == 0) {
continue;
}
String eventHash = topics.get(0);
String eventContract = log.getAddress().toLowerCase();
if (HtgConstant.EVENT_HASH_ERC20_TRANSFER.equals(eventHash)) {
if (!eventContract.equals(_erc20)) {
continue;
}
int length = topics.get(1).length();
String fromAddress = HtgConstant.HEX_PREFIX + topics.get(1).substring(26, length).toString();
String toAddress = HtgConstant.HEX_PREFIX + topics.get(2).substring(26, length).toString();
String data;
if (topics.size() == 3) {
data = log.getData();
} else {
data = topics.get(3);
}
String[] v = data.split("x");
// 转账金额
BigInteger amount = new BigInteger(v[1], 16);
// 当toAddress是0x0时,则说明这是一个从当前多签合约销毁erc20的transfer事件
if (HtgConstant.ZERO_ADDRESS.equals(toAddress)) {
if (!fromAddress.equals(htgContext.MULTY_SIGN_ADDRESS())) {
continue;
}
if (amount.compareTo(_amount) != 0) {
logger().warn("交易[{}]的ERC20销毁金额不匹配", txHash);
burnEvent = false;
break;
}
} else {
// 用户转移token到多签合约的事件
// 必须是多签合约地址
if (!toAddress.equals(htgContext.MULTY_SIGN_ADDRESS())) {
continue;
}
calcAmount = calcAmount.add(amount);
transferEvent = true;
}
}
if (HtgConstant.EVENT_HASH_CROSS_OUT_FUNDS.equals(eventHash)) {
if (!eventContract.equals(htgContext.MULTY_SIGN_ADDRESS())) {
continue;
}
List<Object> depositEvent = HtgUtil.parseEvent(log.getData(), HtgConstant.EVENT_CROSS_OUT_FUNDS);
if (depositEvent == null && depositEvent.size() != 4) {
logger().warn("交易[{}]CrossOut事件数据不合法[1]", txHash);
return false;
}
String from = depositEvent.get(0).toString();
String to = depositEvent.get(1).toString();
BigInteger amount = new BigInteger(depositEvent.get(2).toString());
String erc20 = depositEvent.get(3).toString();
if (!tx.getFrom().equals(from)) {
logger().warn("交易[{}]CrossOut事件数据不合法[2]", txHash);
return false;
}
if (!_to.equals(to)) {
logger().warn("交易[{}]CrossOut事件数据不合法[3]", txHash);
return false;
}
if (amount.compareTo(_amount) != 0) {
logger().warn("交易[{}]CrossOut事件数据不合法[4]", txHash);
return false;
}
if (!_erc20.equals(erc20)) {
logger().warn("交易[{}]CrossOut事件数据不合法[5]", txHash);
return false;
}
crossOutEvent = true;
}
}
if (transferEvent && burnEvent && crossOutEvent) {
if (calcAmount.compareTo(_amount) > 0) {
logger().warn("交易[{}]的ERC20充值金额不匹配", txHash);
return false;
}
actualAmount = calcAmount;
if (actualAmount.equals(BigInteger.ZERO)) {
logger().warn("交易[{}]的ERC20充值金额为0", txHash);
return false;
}
if (po != null && actualAmount.compareTo(BigInteger.ZERO) > 0) {
po.setIfContractAsset(true);
po.setContractAddress(_erc20);
po.setFrom(tx.getFrom());
po.setTo(tx.getTo());
po.setValue(actualAmount);
po.setNerveAddress(_to);
}
return true;
} else {
logger().warn("交易[{}]的ERC20充值事件不匹配, transferEvent: {}, burnEvent: {}, crossOutEvent: {}",
txHash, transferEvent, burnEvent, crossOutEvent);
return false;
}
}
}
private boolean newValidationEthDepositByCrossOut(Transaction tx, TransactionReceipt txReceipt, HeterogeneousTransactionInfo po) throws Exception {
if (tx == null) {
logger().warn("交易不存在");
return false;
}
String txHash = tx.getHash();
if (txReceipt == null) {
txReceipt = htgWalletApi.getTxReceipt(txHash);
}
List<Log> logs = txReceipt.getLogs();
if (logs == null || logs.isEmpty()) {
logger().warn("交易[{}]事件为空", txHash);
return false;
}
List<Object> crossOutInput = HtgUtil.parseInput(tx.getInput(), HtgConstant.INPUT_CROSS_OUT);
String _to = crossOutInput.get(0).toString();
BigInteger _amount = new BigInteger(crossOutInput.get(1).toString());
String _erc20 = crossOutInput.get(2).toString().toLowerCase();
if (HtgConstant.ZERO_ADDRESS.equals(_erc20)) {
// 主资产充值交易
for (Log log : logs) {
List<String> topics = log.getTopics();
if (log.getTopics().size() == 0) {
continue;
}
String eventHash = topics.get(0);
String eventContract = log.getAddress().toLowerCase();
if (!HtgConstant.EVENT_HASH_CROSS_OUT_FUNDS.equals(eventHash)) {
continue;
}
if (!eventContract.equals(htgContext.MULTY_SIGN_ADDRESS())) {
continue;
}
List<Object> depositEvent = HtgUtil.parseEvent(log.getData(), HtgConstant.EVENT_CROSS_OUT_FUNDS);
if (depositEvent == null && depositEvent.size() != 4) {
logger().warn("交易[{}]CrossOut事件数据不合法[0]", txHash);
return false;
}
String from = depositEvent.get(0).toString();
String to = depositEvent.get(1).toString();
BigInteger amount = new BigInteger(depositEvent.get(2).toString());
String erc20 = depositEvent.get(3).toString();
if (tx.getFrom().equals(from) && tx.getValue().compareTo(amount) == 0 && HtgConstant.ZERO_ADDRESS.equals(erc20)) {
if (po != null) {
po.setIfContractAsset(false);
po.setFrom(from);
po.setTo(tx.getTo());
po.setValue(amount);
po.setDecimals(htgContext.getConfig().getDecimals());
po.setAssetId(htgContext.HTG_ASSET_ID());
po.setNerveAddress(to);
}
return true;
}
}
logger().warn("交易[{}]的主资产[{}]充值事件不匹配", txHash, htgContext.getConfig().getSymbol());
return false;
} else {
// ERC20充值交易
if (!htgERC20Helper.isERC20(_erc20, po)) {
logger().warn("erc20[{}]未注册", _erc20);
return false;
}
boolean transferEvent = false;
boolean burnEvent = true;
boolean crossOutEvent = false;
BigInteger actualAmount;
BigInteger calcAmount = BigInteger.ZERO;
for (Log log : logs) {
List<String> topics = log.getTopics();
if (topics.size() == 0) {
continue;
}
String eventHash = topics.get(0);
String eventContract = log.getAddress().toLowerCase();
if (HtgConstant.EVENT_HASH_ERC20_TRANSFER.equals(eventHash)) {
if (!eventContract.equals(_erc20)) {
continue;
}
int length = topics.get(1).length();
String fromAddress = HtgConstant.HEX_PREFIX + topics.get(1).substring(26, length).toString();
String toAddress = HtgConstant.HEX_PREFIX + topics.get(2).substring(26, length).toString();
String data;
if (topics.size() == 3) {
data = log.getData();
} else {
data = topics.get(3);
}
String[] v = data.split("x");
// 转账金额
BigInteger amount = new BigInteger(v[1], 16);
// 当toAddress是0x0时,则说明这是一个从当前多签合约销毁erc20的transfer事件
if (HtgConstant.ZERO_ADDRESS.equals(toAddress)) {
if (!fromAddress.equals(htgContext.MULTY_SIGN_ADDRESS())) {
logger().warn("交易[{}]的销毁地址不匹配", txHash);
burnEvent = false;
break;
}
if (amount.compareTo(_amount) != 0) {
logger().warn("交易[{}]的ERC20销毁金额不匹配", txHash);
burnEvent = false;
break;
}
} else {
// 用户转移token到多签合约的事件
// 必须是多签合约地址
if (!toAddress.equals(htgContext.MULTY_SIGN_ADDRESS())) {
continue;
}
calcAmount = calcAmount.add(amount);
transferEvent = true;
}
}
if (HtgConstant.EVENT_HASH_CROSS_OUT_FUNDS.equals(eventHash)) {
if (!eventContract.equals(htgContext.MULTY_SIGN_ADDRESS())) {
continue;
}
List<Object> depositEvent = HtgUtil.parseEvent(log.getData(), HtgConstant.EVENT_CROSS_OUT_FUNDS);
if (depositEvent == null && depositEvent.size() != 4) {
logger().warn("交易[{}]CrossOut事件数据不合法[1]", txHash);
return false;
}
String from = depositEvent.get(0).toString();
String to = depositEvent.get(1).toString();
BigInteger amount = new BigInteger(depositEvent.get(2).toString());
String erc20 = depositEvent.get(3).toString();
if (!tx.getFrom().equals(from)) {
logger().warn("交易[{}]CrossOut事件数据不合法[2]", txHash);
return false;
}
if (!_to.equals(to)) {
logger().warn("交易[{}]CrossOut事件数据不合法[3]", txHash);
return false;
}
if (amount.compareTo(_amount) != 0) {
logger().warn("交易[{}]CrossOut事件数据不合法[4]", txHash);
return false;
}
if (!_erc20.equals(erc20)) {
logger().warn("交易[{}]CrossOut事件数据不合法[5]", txHash);
return false;
}
crossOutEvent = true;
}
}
if (transferEvent && burnEvent && crossOutEvent) {
if (calcAmount.compareTo(_amount) > 0) {
logger().warn("交易[{}]的ERC20充值金额不匹配", txHash);
return false;
}
actualAmount = calcAmount;
if (actualAmount.equals(BigInteger.ZERO)) {
logger().warn("交易[{}]的ERC20充值金额为0", txHash);
return false;
}
if (po != null && actualAmount.compareTo(BigInteger.ZERO) > 0) {
po.setIfContractAsset(true);
po.setContractAddress(_erc20);
po.setFrom(tx.getFrom());
po.setTo(tx.getTo());
po.setValue(actualAmount);
po.setNerveAddress(_to);
}
return true;
} else {
logger().warn("交易[{}]的ERC20充值事件不匹配, transferEvent: {}, burnEvent: {}, crossOutEvent: {}",
txHash, transferEvent, burnEvent, crossOutEvent);
return false;
}
}
}
private boolean newParseWithdrawTxReceipt(Transaction tx, TransactionReceipt txReceipt, HeterogeneousTransactionBaseInfo po) {
if (txReceipt == null || !txReceipt.isStatusOK()) {
return false;
}
String txHash = tx.getHash();
List<Object> withdrawInput = HtgUtil.parseInput(tx.getInput(), HtgConstant.INPUT_WITHDRAW);
String receive = withdrawInput.get(1).toString();
Boolean isERC20 = Boolean.parseBoolean(withdrawInput.get(3).toString());
String erc20 = withdrawInput.get(4).toString().toLowerCase();
boolean correctErc20 = false;
boolean correctMainAsset = false;
List<Log> logs = txReceipt.getLogs();
if (logs != null && logs.size() > 0) {
List<String> topics;
String eventHash;
String contract;
// 转账金额
BigInteger amount = BigInteger.ZERO;
for (Log log : logs) {
topics = log.getTopics();
if (topics.size() == 0) {
continue;
}
eventHash = topics.get(0);
contract = log.getAddress().toLowerCase();
// 为ERC20提现
if (eventHash.equals(HtgConstant.EVENT_HASH_ERC20_TRANSFER)) {
int length = topics.get(1).length();
String fromAddress = HtgConstant.HEX_PREFIX + topics.get(1).substring(26, length).toString();
if (isERC20 &&
contract.equalsIgnoreCase(erc20) &&
(fromAddress.equalsIgnoreCase(htgContext.MULTY_SIGN_ADDRESS()) || fromAddress.equalsIgnoreCase(HtgConstant.ZERO_ADDRESS))) {
String toAddress = HtgConstant.HEX_PREFIX + topics.get(2).substring(26, length).toString();
if (!receive.equalsIgnoreCase(toAddress)) {
logger().warn("提现交易[{}]的接收地址不匹配", txHash);
return false;
}
correctErc20 = true;
String data;
if (topics.size() == 3) {
data = log.getData();
} else {
data = topics.get(3);
}
String[] v = data.split("x");
// 转账金额
BigInteger _amount = new BigInteger(v[1], 16);
if (_amount.compareTo(BigInteger.ZERO) > 0) {
amount = amount.add(_amount);
}
}
}
// 为主资产提现
if (eventHash.equals(HtgConstant.EVENT_HASH_TRANSFERFUNDS)) {
if (isERC20 || !contract.equals(htgContext.MULTY_SIGN_ADDRESS())) {
if (isERC20) {
logger().warn("提现交易[{}]的提现类型冲突[0]", txHash);
} else {
logger().warn("提现交易[{}]的多签合约地址不匹配", txHash);
}
return false;
}
correctMainAsset = true;
String data = log.getData();
String toAddress = HtgConstant.HEX_PREFIX + data.substring(26, 66);
if (!receive.equalsIgnoreCase(toAddress)) {
logger().warn("提现交易[{}]的接收地址不匹配[主资产提现]", txHash);
return false;
}
String amountStr = data.substring(66, 130);
// 转账金额
BigInteger _amount = new BigInteger(amountStr, 16);
if (_amount.compareTo(BigInteger.ZERO) > 0) {
amount = amount.add(_amount);
}
}
}
if (correctErc20 && correctMainAsset) {
logger().warn("提现交易[{}]的提现类型冲突[1]", txHash);
return false;
}
if (correctMainAsset) {
po.setTo(receive.toLowerCase());
po.setValue(amount);
po.setDecimals(htgContext.getConfig().getDecimals());
po.setAssetId(htgContext.HTG_ASSET_ID());
return true;
} else if (correctErc20) {
po.setIfContractAsset(true);
po.setContractAddress(erc20);
po.setTo(receive.toLowerCase());
po.setValue(amount);
return true;
}
}
logger().warn("提现交易[{}]解析数据缺失", txHash);
return false;
}
private boolean newParseWithdrawTxReceiptSinceProtocol21(Transaction tx, TransactionReceipt txReceipt, HeterogeneousTransactionBaseInfo po) {
if (txReceipt == null || !txReceipt.isStatusOK()) {
return false;
}
String txHash = tx.getHash();
List<Object> withdrawInput = HtgUtil.parseInput(tx.getInput(), HtgConstant.INPUT_WITHDRAW);
String receive = withdrawInput.get(1).toString();
Boolean isERC20 = Boolean.parseBoolean(withdrawInput.get(3).toString());
String erc20 = withdrawInput.get(4).toString().toLowerCase();
List<Log> logs = txReceipt.getLogs();
if (logs != null && logs.size() > 0) {
boolean correctErc20 = false;
boolean correctMainAsset = false;
boolean hasReceiveAddress = false;
List<String> topics;
String eventHash;
String contract;
// 转账金额
BigInteger amount = BigInteger.ZERO;
for (Log log : logs) {
topics = log.getTopics();
if (topics.size() == 0) {
continue;
}
eventHash = topics.get(0);
contract = log.getAddress().toLowerCase();
// 为ERC20提现
if (eventHash.equals(HtgConstant.EVENT_HASH_ERC20_TRANSFER)) {
int length = topics.get(1).length();
String fromAddress = HtgConstant.HEX_PREFIX + topics.get(1).substring(26, length);
if (isERC20 &&
contract.equalsIgnoreCase(erc20) &&
(fromAddress.equalsIgnoreCase(htgContext.MULTY_SIGN_ADDRESS()) || fromAddress.equalsIgnoreCase(HtgConstant.ZERO_ADDRESS))) {
String toAddress = HtgConstant.HEX_PREFIX + topics.get(2).substring(26, length);
if (!receive.equalsIgnoreCase(toAddress)) {
logger().warn("提现交易[{}]的接收地址不匹配", txHash);
continue;
}
correctErc20 = true;
hasReceiveAddress = true;
String data;
if (topics.size() == 3) {
data = log.getData();
} else {
data = topics.get(3);
}
String[] v = data.split("x");
// 转账金额
BigInteger _amount = new BigInteger(v[1], 16);
if (_amount.compareTo(BigInteger.ZERO) > 0) {
amount = amount.add(_amount);
}
}
}
// 为主资产提现
if (eventHash.equals(HtgConstant.EVENT_HASH_TRANSFERFUNDS)) {
if (isERC20 || !contract.equals(htgContext.MULTY_SIGN_ADDRESS())) {
if (isERC20) {
logger().warn("提现交易[{}]的提现类型冲突[0]", txHash);
} else {
logger().warn("提现交易[{}]的多签合约地址不匹配", txHash);
}
return false;
}
String data = log.getData();
String toAddress = HtgConstant.HEX_PREFIX + data.substring(26, 66);
if (!receive.equalsIgnoreCase(toAddress)) {
logger().warn("提现交易[{}]的接收地址不匹配[主资产提现]", txHash);
return false;
}
correctMainAsset = true;
hasReceiveAddress = true;
String amountStr = data.substring(66, 130);
// 转账金额
BigInteger _amount = new BigInteger(amountStr, 16);
if (_amount.compareTo(BigInteger.ZERO) > 0) {
amount = amount.add(_amount);
}
}
}
if (!hasReceiveAddress) {
logger().warn("提现交易[{}]的接收地址不匹配", txHash);
return false;
}
if (correctErc20 && correctMainAsset) {
logger().warn("提现交易[{}]的提现类型冲突[1]", txHash);
return false;
}
if (correctMainAsset) {
po.setTo(receive.toLowerCase());
po.setValue(amount);
po.setDecimals(htgContext.getConfig().getDecimals());
po.setAssetId(htgContext.HTG_ASSET_ID());
return true;
} else if (correctErc20) {
po.setIfContractAsset(true);
po.setContractAddress(erc20);
po.setTo(receive.toLowerCase());
po.setValue(amount);
return true;
}
}
logger().warn("提现交易[{}]解析数据缺失", txHash);
return false;
}
public boolean validationEthDepositByCrossOutII(Transaction tx, TransactionReceipt txReceipt, HeterogeneousTransactionInfo po) throws Exception {
if (tx == null) {
logger().warn("交易不存在");
return false;
}
String txHash = tx.getHash();
if (txReceipt == null) {
txReceipt = htgWalletApi.getTxReceipt(txHash);
}
List<Log> logs = txReceipt.getLogs();
if (logs == null || logs.isEmpty()) {
logger().warn("交易[{}]事件为空", txHash);
return false;
}
List<Object> crossOutInput = HtgUtil.parseInput(tx.getInput(), HtgConstant.INPUT_CROSS_OUT_II);
String _to = crossOutInput.get(0).toString();
BigInteger _amount = new BigInteger(crossOutInput.get(1).toString());
String _erc20 = crossOutInput.get(2).toString().toLowerCase();
if (HtgConstant.ZERO_ADDRESS.equals(_erc20)) {
// 主资产充值交易
for (Log log : logs) {
List<String> topics = log.getTopics();
String eventHash = topics.get(0);
String eventContract = log.getAddress().toLowerCase();
if (!HtgConstant.EVENT_HASH_CROSS_OUT_II_FUNDS.equals(eventHash)) {
continue;
}
if (!eventContract.equals(htgContext.MULTY_SIGN_ADDRESS())) {
continue;
}
List<Object> depositEvent = HtgUtil.parseEvent(log.getData(), HtgConstant.EVENT_CROSS_OUT_II_FUNDS);
if (depositEvent == null && depositEvent.size() != 6) {
logger().warn("交易[{}]CrossOutII事件数据不合法[0]", txHash);
return false;
}
String from = depositEvent.get(0).toString();
String to = depositEvent.get(1).toString();
String erc20 = depositEvent.get(3).toString();
BigInteger ethAmount = new BigInteger(depositEvent.get(4).toString());
String extend = Numeric.toHexString((byte[]) depositEvent.get(5));
po.setDepositIIExtend(extend);
if (tx.getFrom().equals(from) && tx.getValue().compareTo(ethAmount) == 0 && HtgConstant.ZERO_ADDRESS.equals(erc20)) {
if (po != null) {
po.setIfContractAsset(false);
po.setFrom(from);
po.setTo(tx.getTo());
po.setValue(ethAmount);
po.setDecimals(htgContext.getConfig().getDecimals());
po.setAssetId(htgContext.HTG_ASSET_ID());
po.setNerveAddress(to);
po.setTxType(HeterogeneousChainTxType.DEPOSIT);
}
return true;
}
}
logger().warn("交易[{}]的主资产[{}]充值II事件不匹配", txHash, htgContext.getConfig().getSymbol());
return false;
} else {
// ERC20充值和主资产充值
if (!htgERC20Helper.isERC20(_erc20, po)) {
logger().warn("CrossOutII: erc20[{}]未注册", _erc20);
return false;
}
boolean transferEvent = false;
boolean burnEvent = true;
boolean crossOutEvent = false;
BigInteger erc20Amount = BigInteger.ZERO;
for (Log log : logs) {
List<String> topics = log.getTopics();
String eventHash = topics.get(0);
String eventContract = log.getAddress().toLowerCase();
if (HtgConstant.EVENT_HASH_ERC20_TRANSFER.equals(eventHash)) {
if (!eventContract.equals(_erc20)) {
continue;
}
int length = topics.get(1).length();
String fromAddress = HtgConstant.HEX_PREFIX + topics.get(1).substring(26, length).toString();
String toAddress = HtgConstant.HEX_PREFIX + topics.get(2).substring(26, length).toString();
String data;
if (topics.size() == 3) {
data = log.getData();
} else {
data = topics.get(3);
}
String[] v = data.split("x");
// 转账金额
BigInteger amount = new BigInteger(v[1], 16);
// 当toAddress是0x0时,则说明这是一个从当前多签合约销毁erc20的transfer事件
if (HtgConstant.ZERO_ADDRESS.equals(toAddress)) {
if (!fromAddress.equals(htgContext.MULTY_SIGN_ADDRESS())) {
continue;
}
if (amount.compareTo(_amount) != 0) {
logger().warn("CrossOutII: 交易[{}]的ERC20销毁金额不匹配", txHash);
burnEvent = false;
break;
}
} else {
// 用户转移token到多签合约的事件
// 必须是多签合约地址
if (!toAddress.equals(htgContext.MULTY_SIGN_ADDRESS())) {
continue;
}
erc20Amount = erc20Amount.add(amount);
transferEvent = true;
}
}
if (HtgConstant.EVENT_HASH_CROSS_OUT_II_FUNDS.equals(eventHash)) {
if (!eventContract.equals(htgContext.MULTY_SIGN_ADDRESS())) {
continue;
}
List<Object> depositEvent = HtgUtil.parseEvent(log.getData(), HtgConstant.EVENT_CROSS_OUT_II_FUNDS);
if (depositEvent == null && depositEvent.size() != 6) {
logger().warn("交易[{}]CrossOutII事件数据不合法[1]", txHash);
return false;
}
String from = depositEvent.get(0).toString();
String to = depositEvent.get(1).toString();
BigInteger amount = new BigInteger(depositEvent.get(2).toString());
String erc20 = depositEvent.get(3).toString();
BigInteger ethAmount = new BigInteger(depositEvent.get(4).toString());
String extend = Numeric.toHexString((byte[]) depositEvent.get(5));
if (!tx.getFrom().equals(from)) {
logger().warn("交易[{}]CrossOutII事件数据不合法[2]", txHash);
return false;
}
if (!_to.equals(to)) {
logger().warn("交易[{}]CrossOutII事件数据不合法[3]", txHash);
return false;
}
if (amount.compareTo(_amount) != 0) {
logger().warn("交易[{}]CrossOutII事件数据不合法[4]", txHash);
return false;
}
if (!_erc20.equals(erc20)) {
logger().warn("交易[{}]CrossOutII事件数据不合法[5]", txHash);
return false;
}
if (tx.getFrom().equals(from) && tx.getValue().compareTo(BigInteger.ZERO) > 0 && tx.getValue().compareTo(ethAmount) == 0) {
// 记录主资产充值
po.setDepositIIMainAsset(ethAmount, htgContext.getConfig().getDecimals(), htgContext.HTG_ASSET_ID());
}
po.setDepositIIExtend(extend);
crossOutEvent = true;
}
}
if (transferEvent && burnEvent && crossOutEvent) {
if (erc20Amount.compareTo(_amount) > 0) {
logger().warn("CrossOutII: 交易[{}]的ERC20充值金额不匹配", txHash);
return false;
}
if (erc20Amount.equals(BigInteger.ZERO)) {
logger().warn("CrossOutII: 交易[{}]的ERC20充值金额为0", txHash);
return false;
}
if (po != null && erc20Amount.compareTo(BigInteger.ZERO) > 0) {
po.setIfContractAsset(true);
po.setContractAddress(_erc20);
po.setFrom(tx.getFrom());
po.setTo(tx.getTo());
po.setValue(erc20Amount);
po.setNerveAddress(_to);
po.setTxType(HeterogeneousChainTxType.DEPOSIT);
}
return true;
} else {
logger().warn("交易[{}]的ERC20充值II事件不匹配, transferEvent: {}, burnEvent: {}, crossOutEvent: {}",
txHash, transferEvent, burnEvent, crossOutEvent);
return false;
}
}
}
}
| UTF-8 | Java | 72,857 | java | HtgParseTxHelper.java | Java | [
{
"context": "port java.util.stream.Collectors;\n\n/**\n * @author: Mimi\n * @date: 2020-03-20\n */\npublic class HtgParseTxH",
"end": 2523,
"score": 0.9787013530731201,
"start": 2519,
"tag": "NAME",
"value": "Mimi"
}
] | null | [] | /**
* MIT License
* <p>
* Copyright (c) 2019-2022 nerve.network
* <p>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package network.nerve.converter.heterogeneouschain.lib.helper;
import io.nuls.core.log.logback.NulsLogger;
import io.nuls.core.model.StringUtils;
import network.nerve.converter.enums.HeterogeneousChainTxType;
import network.nerve.converter.heterogeneouschain.lib.context.HtgConstant;
import network.nerve.converter.heterogeneouschain.lib.context.HtgContext;
import network.nerve.converter.heterogeneouschain.lib.core.HtgWalletApi;
import network.nerve.converter.heterogeneouschain.lib.listener.HtgListener;
import network.nerve.converter.heterogeneouschain.lib.management.BeanInitial;
import network.nerve.converter.heterogeneouschain.lib.model.HtgInput;
import network.nerve.converter.heterogeneouschain.lib.storage.HtgTxStorageService;
import network.nerve.converter.heterogeneouschain.lib.utils.HtgUtil;
import network.nerve.converter.model.bo.*;
import org.web3j.abi.FunctionReturnDecoder;
import org.web3j.abi.datatypes.Address;
import org.web3j.abi.datatypes.Function;
import org.web3j.abi.datatypes.Type;
import org.web3j.protocol.core.methods.response.Log;
import org.web3j.protocol.core.methods.response.Transaction;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.utils.Numeric;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author: Mimi
* @date: 2020-03-20
*/
public class HtgParseTxHelper implements BeanInitial {
private HtgERC20Helper htgERC20Helper;
private HtgTxStorageService htgTxStorageService;
private HtgWalletApi htgWalletApi;
private HtgListener htgListener;
private HtgContext htgContext;
private NulsLogger logger() {
return htgContext.logger();
}
public boolean isCompletedTransaction(String nerveTxHash) throws Exception {
return isCompletedTransactionByStatus(nerveTxHash, false);
}
public boolean isCompletedTransactionByLatest(String nerveTxHash) throws Exception {
return isCompletedTransactionByStatus(nerveTxHash, true);
}
private boolean isCompletedTransactionByStatus(String nerveTxHash, boolean latest) throws Exception {
Function isCompletedFunction = HtgUtil.getIsCompletedFunction(nerveTxHash);
List<Type> valueTypes = htgWalletApi.callViewFunction(htgContext.MULTY_SIGN_ADDRESS(), isCompletedFunction, latest);
if (valueTypes == null || valueTypes.size() == 0) {
return false;
}
boolean isCompleted = Boolean.parseBoolean(valueTypes.get(0).getValue().toString());
return isCompleted;
}
public boolean isMinterERC20(String erc20) throws Exception {
return isMinterERC20ByStatus(erc20, false);
}
public boolean isMinterERC20ByLatest(String erc20) throws Exception {
return isMinterERC20ByStatus(erc20, true);
}
private boolean isMinterERC20ByStatus(String erc20, boolean latest) throws Exception {
if (StringUtils.isBlank(erc20)) {
return true;
}
Function isMinterERC20Function = HtgUtil.getIsMinterERC20Function(erc20);
List<Type> valueTypes = htgWalletApi.callViewFunction(htgContext.MULTY_SIGN_ADDRESS(), isMinterERC20Function, latest);
boolean isMinterERC20 = Boolean.parseBoolean(valueTypes.get(0).getValue().toString());
return isMinterERC20;
}
/**
* 解析提现交易数据
*/
public HeterogeneousTransactionInfo parseWithdrawTransaction(Transaction tx, TransactionReceipt txReceipt) throws Exception {
if (tx == null) {
logger().warn("解析交易的数据不存在或不完整");
return null;
}
String txHash = tx.getHash();
HeterogeneousTransactionInfo txInfo = HtgUtil.newTransactionInfo(tx, htgContext.NERVE_CHAINID(), this, logger());
boolean isWithdraw;
if (tx.getInput().length() < 10) {
logger().warn("不是提现交易[0]");
return null;
}
String methodNameHash = tx.getInput().substring(0, 10);
// 提现交易的固定地址
if (htgListener.isListeningAddress(tx.getTo()) &&
HtgConstant.METHOD_HASH_CREATEORSIGNWITHDRAW.equals(methodNameHash)) {
if (txReceipt == null) {
txReceipt = htgWalletApi.getTxReceipt(txHash);
}
// 解析交易收据
if (htgContext.getConverterCoreApi().isProtocol21()) {
// 协议v1.21
isWithdraw = this.newParseWithdrawTxReceiptSinceProtocol21(tx, txReceipt, txInfo);
} else if (htgContext.getConverterCoreApi().isSupportProtocol13NewValidationOfERC20()) {
// 协议v1.13
isWithdraw = this.newParseWithdrawTxReceipt(tx, txReceipt, txInfo);
} else {
isWithdraw = this.parseWithdrawTxReceipt(txReceipt, txInfo);
}
if (!isWithdraw) {
logger().warn("不是提现交易[1], hash: {}", txHash);
return null;
}
if (txInfo.isIfContractAsset()) {
htgERC20Helper.loadERC20(txInfo.getContractAddress(), txInfo);
}
} else {
logger().warn("不是提现交易[2], hash: {}, txTo: {}, methodNameHash: {}", txHash, tx.getTo(), methodNameHash);
return null;
}
txInfo.setTxType(HeterogeneousChainTxType.WITHDRAW);
// 解析多签列表
this.loadSigners(txReceipt, txInfo);
return txInfo;
}
public HeterogeneousTransactionInfo parseWithdrawTransaction(Transaction tx) throws Exception {
return this.parseWithdrawTransaction(tx, null);
}
public HeterogeneousTransactionInfo parseWithdrawTransaction(String txHash) throws Exception {
Transaction tx = htgWalletApi.getTransactionByHash(txHash);
if (tx == null) {
logger().warn("交易不存在");
return null;
}
if (tx.getTo() == null) {
logger().warn("不是提现交易");
return null;
}
tx.setFrom(tx.getFrom().toLowerCase());
tx.setTo(tx.getTo().toLowerCase());
return this.parseWithdrawTransaction(tx, null);
}
/**
* 解析直接转账的方式的充值交易数据
*/
private HeterogeneousTransactionInfo parseDepositTransactionByTransferDirectly(Transaction tx, TransactionReceipt txReceipt) throws Exception {
if (tx == null) {
logger().warn("交易不存在");
return null;
}
String txHash = tx.getHash();
HeterogeneousTransactionInfo txInfo = HtgUtil.newTransactionInfo(tx, htgContext.NERVE_CHAINID(), this, logger());
boolean isDeposit = false;
if (txReceipt == null) {
txReceipt = htgWalletApi.getTxReceipt(txHash);
}
do {
// HT充值交易的固定接收地址,金额大于0, 没有input
if (htgListener.isListeningAddress(tx.getTo()) &&
tx.getValue().compareTo(BigInteger.ZERO) > 0 &&
tx.getInput().equals(HtgConstant.HEX_PREFIX)) {
if(!this.validationEthDeposit(tx, txReceipt)) {
logger().error("[{}]不是充值交易[0]", txHash);
return null;
}
isDeposit = true;
txInfo.setDecimals(htgContext.getConfig().getDecimals());
txInfo.setAssetId(htgContext.HTG_ASSET_ID());
txInfo.setValue(tx.getValue());
txInfo.setIfContractAsset(false);
break;
}
// ERC20充值交易
if (htgERC20Helper.isERC20(tx.getTo(), txInfo)) {
if (htgERC20Helper.hasERC20WithListeningAddress(txReceipt, txInfo, address -> htgListener.isListeningAddress(address))) {
// 检查是否是NERVE资产绑定的ERC20,是则检查多签合约内是否已经注册此定制的ERC20,否则充值异常
if (htgContext.getConverterCoreApi().isBoundHeterogeneousAsset(htgContext.getConfig().getChainId(), txInfo.getAssetId())
&& !isMinterERC20(txInfo.getContractAddress())) {
logger().warn("[{}]不合法的{}网络的充值交易[6], ERC20[{}]已绑定NERVE资产,但合约内未注册", txHash, htgContext.getConfig().getSymbol(), txInfo.getContractAddress());
break;
}
isDeposit = true;
break;
}
}
} while (false);
if (!isDeposit) {
logger().error("[{}]不是充值交易[1]", txHash);
return null;
}
txInfo.setTxType(HeterogeneousChainTxType.DEPOSIT);
return txInfo;
}
public BigInteger getTxHeight(NulsLogger logger, Transaction tx) throws Exception {
try {
if (tx == null) {
return null;
}
return tx.getBlockNumber();
} catch (Exception e) {
String txHash = tx.getHash();
logger.error("解析充值交易错误, 区块高度解析失败, 交易hash: {}, BlockNumberRaw: {}, BlockHash: {}", txHash, tx.getBlockNumberRaw(), tx.getBlockHash());
TransactionReceipt txReceipt = null;
try {
txReceipt = htgWalletApi.getTxReceipt(txHash);
return txReceipt.getBlockNumber();
} catch (Exception ex) {
if (txReceipt != null) {
logger.error("再次解析充值交易错误, 区块高度解析失败, 交易hash: {}, BlockNumberRaw: {}, BlockHash: {}", txHash, txReceipt.getBlockNumberRaw(), txReceipt.getBlockHash());
} else {
logger.error("再次解析充值交易错误, 区块高度解析失败, 交易hash: {}, empty txReceipt.", txHash);
}
throw ex;
}
}
}
public HeterogeneousTransactionInfo parseDepositTransaction(Transaction tx) throws Exception {
HtgInput htInput = this.parseInput(tx.getInput());
// 新的充值交易方式,调用多签合约的crossOut函数
if (htInput.isDepositTx()) {
HeterogeneousTransactionInfo po = new HeterogeneousTransactionInfo();
po.setTxHash(tx.getHash());
po.setBlockHeight(getTxHeight(logger(), tx).longValue());
boolean isDepositTx = this.validationEthDepositByCrossOut(tx, po);
if (!isDepositTx) {
return null;
}
po.setTxType(HeterogeneousChainTxType.DEPOSIT);
return po;
}
// 新的充值交易方式II,调用多签合约的crossOutII函数
if (htInput.isDepositIITx()) {
HeterogeneousTransactionInfo po = new HeterogeneousTransactionInfo();
po.setTxHash(tx.getHash());
po.setBlockHeight(getTxHeight(logger(), tx).longValue());
boolean isDepositTx = this.validationEthDepositByCrossOutII(tx, null, po);
if (!isDepositTx) {
return null;
}
po.setTxType(HeterogeneousChainTxType.DEPOSIT);
return po;
}
return this.parseDepositTransactionByTransferDirectly(tx, null);
}
public HeterogeneousTransactionInfo parseDepositTransaction(String txHash) throws Exception {
Transaction tx = htgWalletApi.getTransactionByHash(txHash);
if (tx == null) {
logger().warn("交易不存在");
return null;
}
if (tx.getTo() == null) {
logger().warn("不是充值交易");
return null;
}
tx.setFrom(tx.getFrom().toLowerCase());
tx.setTo(tx.getTo().toLowerCase());
return this.parseDepositTransaction(tx);
}
public boolean validationEthDeposit(Transaction tx) throws Exception {
return this.validationEthDeposit(tx, null);
}
private boolean validationEthDeposit(Transaction tx, TransactionReceipt txReceipt) throws Exception {
if (tx == null) {
logger().warn("交易不存在");
return false;
}
String txHash = tx.getHash();
if (txReceipt == null) {
txReceipt = htgWalletApi.getTxReceipt(txHash);
}
List<Log> logs = txReceipt.getLogs();
if (logs == null || logs.isEmpty()) {
return false;
}
for (Log log : logs) {
List<String> topics = log.getTopics();
if (log.getTopics().size() == 0) {
continue;
}
String eventHash = topics.get(0);
if (!HtgConstant.EVENT_HASH_HT_DEPOSIT_FUNDS.equals(eventHash)) {
continue;
}
List<Object> depositEvent = HtgUtil.parseEvent(log.getData(), HtgConstant.EVENT_DEPOSIT_FUNDS);
if (depositEvent == null && depositEvent.size() != 2) {
return false;
}
String from = depositEvent.get(0).toString();
BigInteger amount = new BigInteger(depositEvent.get(1).toString());
if (tx.getFrom().equals(from) && tx.getValue().compareTo(amount) == 0) {
return true;
}
}
return false;
}
public boolean validationEthDepositByCrossOut(Transaction tx, HeterogeneousTransactionInfo po) throws Exception {
return this.validationEthDepositByCrossOut(tx, null, po);
}
private boolean validationEthDepositByCrossOut(Transaction tx, TransactionReceipt txReceipt, HeterogeneousTransactionInfo po) throws Exception {
if (htgContext.getConverterCoreApi().isProtocol22()) {
return newValidationEthDepositByCrossOutProtocol22(tx, txReceipt, po);
} else if (htgContext.getConverterCoreApi().isSupportProtocol13NewValidationOfERC20()) {
return newValidationEthDepositByCrossOut(tx, txReceipt, po);
} else {
return _validationEthDepositByCrossOut(tx, txReceipt, po);
}
}
private boolean _validationEthDepositByCrossOut(Transaction tx, TransactionReceipt txReceipt, HeterogeneousTransactionInfo po) throws Exception {
if (tx == null) {
logger().warn("交易不存在");
return false;
}
String txHash = tx.getHash();
if (txReceipt == null) {
txReceipt = htgWalletApi.getTxReceipt(txHash);
}
List<Log> logs = txReceipt.getLogs();
if (logs == null || logs.isEmpty()) {
logger().warn("交易[{}]事件为空", txHash);
return false;
}
int logSize = logs.size();
if (logSize == 1) {
// HTG充值交易
Log log = logs.get(0);
List<String> topics = log.getTopics();
if (log.getTopics().size() == 0) {
logger().warn("交易[{}]log未知", txHash);
return false;
}
String eventHash = topics.get(0);
if (!HtgConstant.EVENT_HASH_CROSS_OUT_FUNDS.equals(eventHash)) {
logger().warn("交易[{}]事件未知", txHash);
return false;
}
List<Object> depositEvent = HtgUtil.parseEvent(log.getData(), HtgConstant.EVENT_CROSS_OUT_FUNDS);
if (depositEvent == null && depositEvent.size() != 4) {
logger().warn("交易[{}]CrossOut事件数据不合法[0]", txHash);
return false;
}
String from = depositEvent.get(0).toString();
String to = depositEvent.get(1).toString();
BigInteger amount = new BigInteger(depositEvent.get(2).toString());
String erc20 = depositEvent.get(3).toString();
if (tx.getFrom().equals(from) && tx.getValue().compareTo(amount) == 0 && HtgConstant.ZERO_ADDRESS.equals(erc20)) {
if (po != null) {
po.setIfContractAsset(false);
po.setFrom(from);
po.setTo(tx.getTo());
po.setValue(amount);
po.setDecimals(htgContext.getConfig().getDecimals());
po.setAssetId(htgContext.HTG_ASSET_ID());
po.setNerveAddress(to);
}
return true;
}
} else {
// ERC20充值交易
List<Object> crossOutInput = HtgUtil.parseInput(tx.getInput(), HtgConstant.INPUT_CROSS_OUT);
String _to = crossOutInput.get(0).toString();
BigInteger _amount = new BigInteger(crossOutInput.get(1).toString());
String _erc20 = crossOutInput.get(2).toString().toLowerCase();
if (!htgERC20Helper.isERC20(_erc20, po)) {
logger().warn("erc20[{}]未注册", _erc20);
return false;
}
boolean transferEvent = false;
boolean burnEvent = true;
boolean crossOutEvent = false;
BigInteger actualAmount = _amount;
for (Log log : logs) {
List<String> topics = log.getTopics();
String eventHash = topics.get(0);
String eventContract = log.getAddress().toLowerCase();
if (HtgConstant.EVENT_HASH_ERC20_TRANSFER.equals(eventHash)) {
if (!eventContract.equals(_erc20)) {
logger().warn("交易[{}]的ERC20地址不匹配", txHash);
return false;
}
int length = topics.get(1).length();
String fromAddress = HtgConstant.HEX_PREFIX + topics.get(1).substring(26, length).toString();
String toAddress = HtgConstant.HEX_PREFIX + topics.get(2).substring(26, length).toString();
String data;
if (topics.size() == 3) {
data = log.getData();
} else {
data = topics.get(3);
}
String[] v = data.split("x");
// 转账金额
BigInteger amount = new BigInteger(v[1], 16);
// 当toAddress是0x0时,则说明这是一个从当前多签合约销毁erc20的事件
if (HtgConstant.ZERO_ADDRESS.equals(toAddress)) {
if (!fromAddress.equals(htgContext.MULTY_SIGN_ADDRESS())) {
logger().warn("交易[{}]的销毁地址不匹配", txHash);
burnEvent = false;
break;
}
if (amount.compareTo(_amount) != 0) {
logger().warn("交易[{}]的ERC20销毁金额不匹配", txHash);
burnEvent = false;
break;
}
} else {
// 用户转移token到多签合约的事件
// 必须是用户地址
if (!fromAddress.equals(tx.getFrom())) {
logger().warn("交易[{}]的ERC20用户地址不匹配", txHash);
return false;
}
// 必须是多签合约地址
if (!toAddress.equals(htgContext.MULTY_SIGN_ADDRESS())) {
logger().warn("交易[{}]的ERC20充值地址不匹配", txHash);
return false;
}
// 是否支持转账即销毁部分的ERC20
if (htgContext.getConverterCoreApi().isSupportProtocol12ERC20OfTransferBurn()) {
if (amount.compareTo(_amount) > 0) {
logger().warn("交易[{}]的ERC20充值金额不匹配", txHash);
return false;
}
actualAmount = amount;
} else {
if (amount.compareTo(_amount) != 0) {
logger().warn("交易[{}]的ERC20充值金额不匹配", txHash);
return false;
}
}
transferEvent = true;
}
}
if (HtgConstant.EVENT_HASH_CROSS_OUT_FUNDS.equals(eventHash)) {
List<Object> depositEvent = HtgUtil.parseEvent(log.getData(), HtgConstant.EVENT_CROSS_OUT_FUNDS);
if (depositEvent == null && depositEvent.size() != 4) {
logger().warn("交易[{}]CrossOut事件数据不合法[1]", txHash);
return false;
}
String from = depositEvent.get(0).toString();
String to = depositEvent.get(1).toString();
BigInteger amount = new BigInteger(depositEvent.get(2).toString());
String erc20 = depositEvent.get(3).toString();
if (!tx.getFrom().equals(from)) {
logger().warn("交易[{}]CrossOut事件数据不合法[2]", txHash);
return false;
}
if (!_to.equals(to)) {
logger().warn("交易[{}]CrossOut事件数据不合法[3]", txHash);
return false;
}
if (amount.compareTo(_amount) != 0) {
logger().warn("交易[{}]CrossOut事件数据不合法[4]", txHash);
return false;
}
if (!_erc20.equals(erc20)) {
logger().warn("交易[{}]CrossOut事件数据不合法[5]", txHash);
return false;
}
crossOutEvent = true;
}
}
if (transferEvent && burnEvent && crossOutEvent) {
if (po != null && actualAmount.compareTo(BigInteger.ZERO) > 0) {
po.setIfContractAsset(true);
po.setContractAddress(_erc20);
po.setFrom(tx.getFrom());
po.setTo(tx.getTo());
po.setValue(actualAmount);
po.setNerveAddress(_to);
}
return true;
}
}
return false;
}
/**
* 解析管理员变更交易数据
*/
public HeterogeneousTransactionInfo parseManagerChangeTransaction(Transaction tx, TransactionReceipt txReceipt) throws Exception {
if (tx == null) {
logger().warn("交易不存在");
return null;
}
HeterogeneousTransactionInfo txInfo = HtgUtil.newTransactionInfo(tx, htgContext.NERVE_CHAINID(), this, logger());
boolean isChange = false;
String input, methodHash;
if (htgListener.isListeningAddress(tx.getTo()) && (input = tx.getInput()).length() >= 10) {
methodHash = input.substring(0, 10);
if (methodHash.equals(HtgConstant.METHOD_HASH_CREATEORSIGNMANAGERCHANGE)) {
isChange = true;
List<Object> inputData = HtgUtil.parseInput(input, HtgConstant.INPUT_CHANGE);
List<Address> adds = (List<Address>) inputData.get(1);
List<Address> quits = (List<Address>) inputData.get(2);
if (!adds.isEmpty()) {
txInfo.setAddAddresses(HtgUtil.list2array(adds.stream().map(a -> a.getValue()).collect(Collectors.toList())));
}
if (!quits.isEmpty()) {
txInfo.setRemoveAddresses(HtgUtil.list2array(quits.stream().map(q -> q.getValue()).collect(Collectors.toList())));
}
}
}
if (!isChange) {
logger().warn("不是变更交易");
return null;
}
txInfo.setTxType(HeterogeneousChainTxType.CHANGE);
// 解析多签列表
this.loadSigners(txReceipt, txInfo);
return txInfo;
}
/**
* 解析合约升级授权交易数据
*/
public HeterogeneousTransactionInfo parseUpgradeTransaction(Transaction tx, TransactionReceipt txReceipt) throws Exception {
if (tx == null) {
logger().warn("交易不存在");
return null;
}
HeterogeneousTransactionInfo txInfo = HtgUtil.newTransactionInfo(tx, htgContext.NERVE_CHAINID(), this, logger());
boolean isUpgrade = false;
String input, methodHash;
if (htgListener.isListeningAddress(tx.getTo()) && (input = tx.getInput()).length() >= 10) {
methodHash = input.substring(0, 10);
if (methodHash.equals(HtgConstant.METHOD_HASH_CREATEORSIGNUPGRADE)) {
isUpgrade = true;
}
}
if (!isUpgrade) {
logger().warn("不是合约升级授权交易");
return null;
}
txInfo.setTxType(HeterogeneousChainTxType.UPGRADE);
// 解析多签列表
this.loadSigners(txReceipt, txInfo);
return txInfo;
}
public List<HeterogeneousAddress> parseSigners(TransactionReceipt txReceipt, String txFrom) {
List<Object> eventResult = this.loadDataFromEvent(txReceipt);
if (eventResult == null || eventResult.isEmpty()) {
return null;
}
List<HeterogeneousAddress> signers = new ArrayList<>();
signers.add(new HeterogeneousAddress(htgContext.getConfig().getChainId(), txFrom));
return signers;
}
private void loadSigners(TransactionReceipt txReceipt, HeterogeneousTransactionInfo txInfo) {
List<Object> eventResult = this.loadDataFromEvent(txReceipt);
if (eventResult != null && !eventResult.isEmpty()) {
txInfo.setNerveTxHash(eventResult.get(eventResult.size() - 1).toString());
List<HeterogeneousAddress> signers = new ArrayList<>();
signers.add(new HeterogeneousAddress(htgContext.getConfig().getChainId(), txInfo.getFrom()));
txInfo.setSigners(signers);
}
}
private List<Object> loadDataFromEvent(TransactionReceipt txReceipt) {
List<Log> logs = txReceipt.getLogs();
if (logs == null || logs.isEmpty()) {
return null;
}
Log signerLog = null;
for (Log log : logs) {
List<String> topics = log.getTopics();
if (topics != null && topics.size() > 0) {
String eventHash = topics.get(0);
if (HtgConstant.TRANSACTION_COMPLETED_TOPICS.contains(eventHash)) {
signerLog = log;
break;
}
}
}
if (signerLog == null) {
return null;
}
String eventHash = signerLog.getTopics().get(0);
//// Polygon链,存在erc20转账的合约交易中,会在末尾多出一个未知事件
//if (htgContext.getConfig().getChainId() == 106) {
// if (HtgConstant.EVENT_HASH_UNKNOWN_ON_POLYGON.equals(eventHash)) {
// log = logs.get(logs.size() - 2);
// topics = log.getTopics();
// eventHash = topics.get(0);
// }
//} else if (htgContext.getConfig().getChainId() == 122) {
// // REI链,存在erc20转账的合约交易中,会在末尾多出一个未知事件
// if (HtgConstant.EVENT_HASH_UNKNOWN_ON_REI.equals(eventHash)) {
// log = logs.get(logs.size() - 2);
// topics = log.getTopics();
// eventHash = topics.get(0);
// }
//}
// topics 解析事件名, 签名完成会触发的事件
// 解析事件数据,获得交易的成功事件数据列表
List<Object> eventResult = null;
switch (eventHash) {
case HtgConstant.EVENT_HASH_TRANSACTION_WITHDRAW_COMPLETED:
eventResult = HtgUtil.parseEvent(signerLog.getData(), HtgConstant.EVENT_TRANSACTION_WITHDRAW_COMPLETED);
break;
case HtgConstant.EVENT_HASH_TRANSACTION_MANAGER_CHANGE_COMPLETED:
eventResult = HtgUtil.parseEvent(signerLog.getData(), HtgConstant.EVENT_TRANSACTION_MANAGER_CHANGE_COMPLETED);
break;
case HtgConstant.EVENT_HASH_TRANSACTION_UPGRADE_COMPLETED:
eventResult = HtgUtil.parseEvent(signerLog.getData(), HtgConstant.EVENT_TRANSACTION_UPGRADE_COMPLETED);
break;
}
return eventResult;
}
private boolean parseWithdrawTxReceipt(TransactionReceipt txReceipt, HeterogeneousTransactionBaseInfo po) {
if (txReceipt == null || !txReceipt.isStatusOK()) {
return false;
}
List<Log> logs = txReceipt.getLogs();
if (logs != null && logs.size() > 0) {
for (Log log : logs) {
List<String> topics = log.getTopics();
if (topics.size() == 0) {
continue;
}
// 为ERC20提现
if (topics.get(0).equals(HtgConstant.EVENT_HASH_ERC20_TRANSFER)) {
String toAddress = HtgConstant.HEX_PREFIX + topics.get(2).substring(26, topics.get(1).length()).toString();
String data;
if (topics.size() == 3) {
data = log.getData();
} else {
data = topics.get(3);
}
String[] v = data.split("x");
// 转账金额
BigInteger amount = new BigInteger(v[1], 16);
if (amount.compareTo(BigInteger.ZERO) > 0) {
po.setIfContractAsset(true);
po.setContractAddress(log.getAddress().toLowerCase());
po.setTo(toAddress.toLowerCase());
po.setValue(amount);
return true;
}
return false;
}
// 为HT提现
if (topics.get(0).equals(HtgConstant.EVENT_HASH_TRANSFERFUNDS)) {
String data = log.getData();
String to = HtgConstant.HEX_PREFIX + data.substring(26, 66);
String amountStr = data.substring(66, 130);
// 转账金额
BigInteger amount = new BigInteger(amountStr, 16);
if (amount.compareTo(BigInteger.ZERO) > 0) {
po.setTo(to.toLowerCase());
po.setValue(amount);
po.setDecimals(htgContext.getConfig().getDecimals());
po.setAssetId(htgContext.HTG_ASSET_ID());
return true;
}
return false;
}
}
}
return false;
}
public HtgInput parseInput(String input) {
if (input.length() < 10) {
return HtgInput.empty();
}
String methodHash;
if ((methodHash = input.substring(0, 10)).equals(HtgConstant.METHOD_HASH_CREATEORSIGNWITHDRAW)) {
return new HtgInput(true, HeterogeneousChainTxType.WITHDRAW, HtgUtil.parseInput(input, HtgConstant.INPUT_WITHDRAW).get(0).toString());
}
if (methodHash.equals(HtgConstant.METHOD_HASH_CREATEORSIGNMANAGERCHANGE)) {
return new HtgInput(true, HeterogeneousChainTxType.CHANGE, HtgUtil.parseInput(input, HtgConstant.INPUT_CHANGE).get(0).toString());
}
if (methodHash.equals(HtgConstant.METHOD_HASH_CREATEORSIGNUPGRADE)) {
return new HtgInput(true, HeterogeneousChainTxType.UPGRADE, HtgUtil.parseInput(input, HtgConstant.INPUT_UPGRADE).get(0).toString());
}
if (methodHash.equals(HtgConstant.METHOD_HASH_CROSS_OUT)) {
return new HtgInput(true, HeterogeneousChainTxType.DEPOSIT);
}
if (methodHash.equals(HtgConstant.METHOD_HASH_CROSS_OUT_II)) {
return new HtgInput(true);
}
return HtgInput.empty();
}
public HeterogeneousOneClickCrossChainData parseOneClickCrossChainData(String extend, NulsLogger logger) {
if(StringUtils.isBlank(extend)) {
return null;
}
extend = Numeric.prependHexPrefix(extend);
if(extend.length() < 10) {
return null;
}
String methodHash = extend.substring(0, 10);
if (!HtgConstant.METHOD_HASH_ONE_CLICK_CROSS_CHAIN.equals(methodHash)) {
return null;
}
extend = HtgConstant.HEX_PREFIX + extend.substring(10);
try {
List<Type> typeList = FunctionReturnDecoder.decode(extend, HtgConstant.INPUT_ONE_CLICK_CROSS_CHAIN);
if (typeList == null || typeList.isEmpty()) {
return null;
}
if (typeList.size() < 6) {
return null;
}
int index = 0;
List<Object> list = typeList.stream().map(type -> type.getValue()).collect(Collectors.toList());
BigInteger feeAmount = (BigInteger) list.get(index++);
int desChainId = ((BigInteger) list.get(index++)).intValue();
String desToAddress = (String) list.get(index++);
BigInteger tipping = (BigInteger) list.get(index++);
String tippingAddress = (String) list.get(index++);
String desExtend = Numeric.toHexString((byte[]) list.get(index++));
return new HeterogeneousOneClickCrossChainData(feeAmount, desChainId, desToAddress, tipping == null ? BigInteger.ZERO : tipping, tippingAddress, desExtend);
} catch (Exception e) {
logger.error(e);
return null;
}
}
public HeterogeneousAddFeeCrossChainData parseAddFeeCrossChainData(String extend, NulsLogger logger) {
if(StringUtils.isBlank(extend)) {
return null;
}
extend = Numeric.prependHexPrefix(extend);
if(extend.length() < 10) {
return null;
}
String methodHash = extend.substring(0, 10);
if (!HtgConstant.METHOD_HASH_ADD_FEE_CROSS_CHAIN.equals(methodHash)) {
return null;
}
extend = HtgConstant.HEX_PREFIX + extend.substring(10);
try {
List<Type> typeList = FunctionReturnDecoder.decode(extend, HtgConstant.INPUT_ADD_FEE_CROSS_CHAIN);
if (typeList == null || typeList.isEmpty()) {
return null;
}
if (typeList.size() < 2) {
return null;
}
int index = 0;
List<Object> list = typeList.stream().map(type -> type.getValue()).collect(Collectors.toList());
String nerveTxHash = (String) list.get(index++);
String subExtend = Numeric.toHexString((byte[]) list.get(index++));
return new HeterogeneousAddFeeCrossChainData(nerveTxHash, subExtend);
} catch (Exception e) {
logger.error(e);
return null;
}
}
private boolean newValidationEthDepositByCrossOutProtocol22(Transaction tx, TransactionReceipt txReceipt, HeterogeneousTransactionInfo po) throws Exception {
if (tx == null) {
logger().warn("交易不存在");
return false;
}
String txHash = tx.getHash();
if (txReceipt == null) {
txReceipt = htgWalletApi.getTxReceipt(txHash);
}
List<Log> logs = txReceipt.getLogs();
if (logs == null || logs.isEmpty()) {
logger().warn("交易[{}]事件为空", txHash);
return false;
}
List<Object> crossOutInput = HtgUtil.parseInput(tx.getInput(), HtgConstant.INPUT_CROSS_OUT);
String _to = crossOutInput.get(0).toString();
BigInteger _amount = new BigInteger(crossOutInput.get(1).toString());
String _erc20 = crossOutInput.get(2).toString().toLowerCase();
if (HtgConstant.ZERO_ADDRESS.equals(_erc20)) {
// 主资产充值交易
for (Log log : logs) {
List<String> topics = log.getTopics();
if (log.getTopics().size() == 0) {
continue;
}
String eventHash = topics.get(0);
String eventContract = log.getAddress().toLowerCase();
if (!HtgConstant.EVENT_HASH_CROSS_OUT_FUNDS.equals(eventHash)) {
continue;
}
if (!eventContract.equals(htgContext.MULTY_SIGN_ADDRESS())) {
continue;
}
List<Object> depositEvent = HtgUtil.parseEvent(log.getData(), HtgConstant.EVENT_CROSS_OUT_FUNDS);
if (depositEvent == null && depositEvent.size() != 4) {
logger().warn("交易[{}]CrossOut事件数据不合法[0]", txHash);
return false;
}
String from = depositEvent.get(0).toString();
String to = depositEvent.get(1).toString();
BigInteger amount = new BigInteger(depositEvent.get(2).toString());
String erc20 = depositEvent.get(3).toString();
if (tx.getFrom().equals(from) && tx.getValue().compareTo(amount) == 0 && HtgConstant.ZERO_ADDRESS.equals(erc20)) {
if (po != null) {
po.setIfContractAsset(false);
po.setFrom(from);
po.setTo(tx.getTo());
po.setValue(amount);
po.setDecimals(htgContext.getConfig().getDecimals());
po.setAssetId(htgContext.HTG_ASSET_ID());
po.setNerveAddress(to);
}
return true;
}
}
logger().warn("交易[{}]的主资产[{}]充值事件不匹配", txHash, htgContext.getConfig().getSymbol());
return false;
} else {
// ERC20充值交易
if (!htgERC20Helper.isERC20(_erc20, po)) {
logger().warn("erc20[{}]未注册", _erc20);
return false;
}
boolean transferEvent = false;
boolean burnEvent = true;
boolean crossOutEvent = false;
BigInteger actualAmount;
BigInteger calcAmount = BigInteger.ZERO;
for (Log log : logs) {
List<String> topics = log.getTopics();
if (topics.size() == 0) {
continue;
}
String eventHash = topics.get(0);
String eventContract = log.getAddress().toLowerCase();
if (HtgConstant.EVENT_HASH_ERC20_TRANSFER.equals(eventHash)) {
if (!eventContract.equals(_erc20)) {
continue;
}
int length = topics.get(1).length();
String fromAddress = HtgConstant.HEX_PREFIX + topics.get(1).substring(26, length).toString();
String toAddress = HtgConstant.HEX_PREFIX + topics.get(2).substring(26, length).toString();
String data;
if (topics.size() == 3) {
data = log.getData();
} else {
data = topics.get(3);
}
String[] v = data.split("x");
// 转账金额
BigInteger amount = new BigInteger(v[1], 16);
// 当toAddress是0x0时,则说明这是一个从当前多签合约销毁erc20的transfer事件
if (HtgConstant.ZERO_ADDRESS.equals(toAddress)) {
if (!fromAddress.equals(htgContext.MULTY_SIGN_ADDRESS())) {
continue;
}
if (amount.compareTo(_amount) != 0) {
logger().warn("交易[{}]的ERC20销毁金额不匹配", txHash);
burnEvent = false;
break;
}
} else {
// 用户转移token到多签合约的事件
// 必须是多签合约地址
if (!toAddress.equals(htgContext.MULTY_SIGN_ADDRESS())) {
continue;
}
calcAmount = calcAmount.add(amount);
transferEvent = true;
}
}
if (HtgConstant.EVENT_HASH_CROSS_OUT_FUNDS.equals(eventHash)) {
if (!eventContract.equals(htgContext.MULTY_SIGN_ADDRESS())) {
continue;
}
List<Object> depositEvent = HtgUtil.parseEvent(log.getData(), HtgConstant.EVENT_CROSS_OUT_FUNDS);
if (depositEvent == null && depositEvent.size() != 4) {
logger().warn("交易[{}]CrossOut事件数据不合法[1]", txHash);
return false;
}
String from = depositEvent.get(0).toString();
String to = depositEvent.get(1).toString();
BigInteger amount = new BigInteger(depositEvent.get(2).toString());
String erc20 = depositEvent.get(3).toString();
if (!tx.getFrom().equals(from)) {
logger().warn("交易[{}]CrossOut事件数据不合法[2]", txHash);
return false;
}
if (!_to.equals(to)) {
logger().warn("交易[{}]CrossOut事件数据不合法[3]", txHash);
return false;
}
if (amount.compareTo(_amount) != 0) {
logger().warn("交易[{}]CrossOut事件数据不合法[4]", txHash);
return false;
}
if (!_erc20.equals(erc20)) {
logger().warn("交易[{}]CrossOut事件数据不合法[5]", txHash);
return false;
}
crossOutEvent = true;
}
}
if (transferEvent && burnEvent && crossOutEvent) {
if (calcAmount.compareTo(_amount) > 0) {
logger().warn("交易[{}]的ERC20充值金额不匹配", txHash);
return false;
}
actualAmount = calcAmount;
if (actualAmount.equals(BigInteger.ZERO)) {
logger().warn("交易[{}]的ERC20充值金额为0", txHash);
return false;
}
if (po != null && actualAmount.compareTo(BigInteger.ZERO) > 0) {
po.setIfContractAsset(true);
po.setContractAddress(_erc20);
po.setFrom(tx.getFrom());
po.setTo(tx.getTo());
po.setValue(actualAmount);
po.setNerveAddress(_to);
}
return true;
} else {
logger().warn("交易[{}]的ERC20充值事件不匹配, transferEvent: {}, burnEvent: {}, crossOutEvent: {}",
txHash, transferEvent, burnEvent, crossOutEvent);
return false;
}
}
}
private boolean newValidationEthDepositByCrossOut(Transaction tx, TransactionReceipt txReceipt, HeterogeneousTransactionInfo po) throws Exception {
if (tx == null) {
logger().warn("交易不存在");
return false;
}
String txHash = tx.getHash();
if (txReceipt == null) {
txReceipt = htgWalletApi.getTxReceipt(txHash);
}
List<Log> logs = txReceipt.getLogs();
if (logs == null || logs.isEmpty()) {
logger().warn("交易[{}]事件为空", txHash);
return false;
}
List<Object> crossOutInput = HtgUtil.parseInput(tx.getInput(), HtgConstant.INPUT_CROSS_OUT);
String _to = crossOutInput.get(0).toString();
BigInteger _amount = new BigInteger(crossOutInput.get(1).toString());
String _erc20 = crossOutInput.get(2).toString().toLowerCase();
if (HtgConstant.ZERO_ADDRESS.equals(_erc20)) {
// 主资产充值交易
for (Log log : logs) {
List<String> topics = log.getTopics();
if (log.getTopics().size() == 0) {
continue;
}
String eventHash = topics.get(0);
String eventContract = log.getAddress().toLowerCase();
if (!HtgConstant.EVENT_HASH_CROSS_OUT_FUNDS.equals(eventHash)) {
continue;
}
if (!eventContract.equals(htgContext.MULTY_SIGN_ADDRESS())) {
continue;
}
List<Object> depositEvent = HtgUtil.parseEvent(log.getData(), HtgConstant.EVENT_CROSS_OUT_FUNDS);
if (depositEvent == null && depositEvent.size() != 4) {
logger().warn("交易[{}]CrossOut事件数据不合法[0]", txHash);
return false;
}
String from = depositEvent.get(0).toString();
String to = depositEvent.get(1).toString();
BigInteger amount = new BigInteger(depositEvent.get(2).toString());
String erc20 = depositEvent.get(3).toString();
if (tx.getFrom().equals(from) && tx.getValue().compareTo(amount) == 0 && HtgConstant.ZERO_ADDRESS.equals(erc20)) {
if (po != null) {
po.setIfContractAsset(false);
po.setFrom(from);
po.setTo(tx.getTo());
po.setValue(amount);
po.setDecimals(htgContext.getConfig().getDecimals());
po.setAssetId(htgContext.HTG_ASSET_ID());
po.setNerveAddress(to);
}
return true;
}
}
logger().warn("交易[{}]的主资产[{}]充值事件不匹配", txHash, htgContext.getConfig().getSymbol());
return false;
} else {
// ERC20充值交易
if (!htgERC20Helper.isERC20(_erc20, po)) {
logger().warn("erc20[{}]未注册", _erc20);
return false;
}
boolean transferEvent = false;
boolean burnEvent = true;
boolean crossOutEvent = false;
BigInteger actualAmount;
BigInteger calcAmount = BigInteger.ZERO;
for (Log log : logs) {
List<String> topics = log.getTopics();
if (topics.size() == 0) {
continue;
}
String eventHash = topics.get(0);
String eventContract = log.getAddress().toLowerCase();
if (HtgConstant.EVENT_HASH_ERC20_TRANSFER.equals(eventHash)) {
if (!eventContract.equals(_erc20)) {
continue;
}
int length = topics.get(1).length();
String fromAddress = HtgConstant.HEX_PREFIX + topics.get(1).substring(26, length).toString();
String toAddress = HtgConstant.HEX_PREFIX + topics.get(2).substring(26, length).toString();
String data;
if (topics.size() == 3) {
data = log.getData();
} else {
data = topics.get(3);
}
String[] v = data.split("x");
// 转账金额
BigInteger amount = new BigInteger(v[1], 16);
// 当toAddress是0x0时,则说明这是一个从当前多签合约销毁erc20的transfer事件
if (HtgConstant.ZERO_ADDRESS.equals(toAddress)) {
if (!fromAddress.equals(htgContext.MULTY_SIGN_ADDRESS())) {
logger().warn("交易[{}]的销毁地址不匹配", txHash);
burnEvent = false;
break;
}
if (amount.compareTo(_amount) != 0) {
logger().warn("交易[{}]的ERC20销毁金额不匹配", txHash);
burnEvent = false;
break;
}
} else {
// 用户转移token到多签合约的事件
// 必须是多签合约地址
if (!toAddress.equals(htgContext.MULTY_SIGN_ADDRESS())) {
continue;
}
calcAmount = calcAmount.add(amount);
transferEvent = true;
}
}
if (HtgConstant.EVENT_HASH_CROSS_OUT_FUNDS.equals(eventHash)) {
if (!eventContract.equals(htgContext.MULTY_SIGN_ADDRESS())) {
continue;
}
List<Object> depositEvent = HtgUtil.parseEvent(log.getData(), HtgConstant.EVENT_CROSS_OUT_FUNDS);
if (depositEvent == null && depositEvent.size() != 4) {
logger().warn("交易[{}]CrossOut事件数据不合法[1]", txHash);
return false;
}
String from = depositEvent.get(0).toString();
String to = depositEvent.get(1).toString();
BigInteger amount = new BigInteger(depositEvent.get(2).toString());
String erc20 = depositEvent.get(3).toString();
if (!tx.getFrom().equals(from)) {
logger().warn("交易[{}]CrossOut事件数据不合法[2]", txHash);
return false;
}
if (!_to.equals(to)) {
logger().warn("交易[{}]CrossOut事件数据不合法[3]", txHash);
return false;
}
if (amount.compareTo(_amount) != 0) {
logger().warn("交易[{}]CrossOut事件数据不合法[4]", txHash);
return false;
}
if (!_erc20.equals(erc20)) {
logger().warn("交易[{}]CrossOut事件数据不合法[5]", txHash);
return false;
}
crossOutEvent = true;
}
}
if (transferEvent && burnEvent && crossOutEvent) {
if (calcAmount.compareTo(_amount) > 0) {
logger().warn("交易[{}]的ERC20充值金额不匹配", txHash);
return false;
}
actualAmount = calcAmount;
if (actualAmount.equals(BigInteger.ZERO)) {
logger().warn("交易[{}]的ERC20充值金额为0", txHash);
return false;
}
if (po != null && actualAmount.compareTo(BigInteger.ZERO) > 0) {
po.setIfContractAsset(true);
po.setContractAddress(_erc20);
po.setFrom(tx.getFrom());
po.setTo(tx.getTo());
po.setValue(actualAmount);
po.setNerveAddress(_to);
}
return true;
} else {
logger().warn("交易[{}]的ERC20充值事件不匹配, transferEvent: {}, burnEvent: {}, crossOutEvent: {}",
txHash, transferEvent, burnEvent, crossOutEvent);
return false;
}
}
}
private boolean newParseWithdrawTxReceipt(Transaction tx, TransactionReceipt txReceipt, HeterogeneousTransactionBaseInfo po) {
if (txReceipt == null || !txReceipt.isStatusOK()) {
return false;
}
String txHash = tx.getHash();
List<Object> withdrawInput = HtgUtil.parseInput(tx.getInput(), HtgConstant.INPUT_WITHDRAW);
String receive = withdrawInput.get(1).toString();
Boolean isERC20 = Boolean.parseBoolean(withdrawInput.get(3).toString());
String erc20 = withdrawInput.get(4).toString().toLowerCase();
boolean correctErc20 = false;
boolean correctMainAsset = false;
List<Log> logs = txReceipt.getLogs();
if (logs != null && logs.size() > 0) {
List<String> topics;
String eventHash;
String contract;
// 转账金额
BigInteger amount = BigInteger.ZERO;
for (Log log : logs) {
topics = log.getTopics();
if (topics.size() == 0) {
continue;
}
eventHash = topics.get(0);
contract = log.getAddress().toLowerCase();
// 为ERC20提现
if (eventHash.equals(HtgConstant.EVENT_HASH_ERC20_TRANSFER)) {
int length = topics.get(1).length();
String fromAddress = HtgConstant.HEX_PREFIX + topics.get(1).substring(26, length).toString();
if (isERC20 &&
contract.equalsIgnoreCase(erc20) &&
(fromAddress.equalsIgnoreCase(htgContext.MULTY_SIGN_ADDRESS()) || fromAddress.equalsIgnoreCase(HtgConstant.ZERO_ADDRESS))) {
String toAddress = HtgConstant.HEX_PREFIX + topics.get(2).substring(26, length).toString();
if (!receive.equalsIgnoreCase(toAddress)) {
logger().warn("提现交易[{}]的接收地址不匹配", txHash);
return false;
}
correctErc20 = true;
String data;
if (topics.size() == 3) {
data = log.getData();
} else {
data = topics.get(3);
}
String[] v = data.split("x");
// 转账金额
BigInteger _amount = new BigInteger(v[1], 16);
if (_amount.compareTo(BigInteger.ZERO) > 0) {
amount = amount.add(_amount);
}
}
}
// 为主资产提现
if (eventHash.equals(HtgConstant.EVENT_HASH_TRANSFERFUNDS)) {
if (isERC20 || !contract.equals(htgContext.MULTY_SIGN_ADDRESS())) {
if (isERC20) {
logger().warn("提现交易[{}]的提现类型冲突[0]", txHash);
} else {
logger().warn("提现交易[{}]的多签合约地址不匹配", txHash);
}
return false;
}
correctMainAsset = true;
String data = log.getData();
String toAddress = HtgConstant.HEX_PREFIX + data.substring(26, 66);
if (!receive.equalsIgnoreCase(toAddress)) {
logger().warn("提现交易[{}]的接收地址不匹配[主资产提现]", txHash);
return false;
}
String amountStr = data.substring(66, 130);
// 转账金额
BigInteger _amount = new BigInteger(amountStr, 16);
if (_amount.compareTo(BigInteger.ZERO) > 0) {
amount = amount.add(_amount);
}
}
}
if (correctErc20 && correctMainAsset) {
logger().warn("提现交易[{}]的提现类型冲突[1]", txHash);
return false;
}
if (correctMainAsset) {
po.setTo(receive.toLowerCase());
po.setValue(amount);
po.setDecimals(htgContext.getConfig().getDecimals());
po.setAssetId(htgContext.HTG_ASSET_ID());
return true;
} else if (correctErc20) {
po.setIfContractAsset(true);
po.setContractAddress(erc20);
po.setTo(receive.toLowerCase());
po.setValue(amount);
return true;
}
}
logger().warn("提现交易[{}]解析数据缺失", txHash);
return false;
}
private boolean newParseWithdrawTxReceiptSinceProtocol21(Transaction tx, TransactionReceipt txReceipt, HeterogeneousTransactionBaseInfo po) {
if (txReceipt == null || !txReceipt.isStatusOK()) {
return false;
}
String txHash = tx.getHash();
List<Object> withdrawInput = HtgUtil.parseInput(tx.getInput(), HtgConstant.INPUT_WITHDRAW);
String receive = withdrawInput.get(1).toString();
Boolean isERC20 = Boolean.parseBoolean(withdrawInput.get(3).toString());
String erc20 = withdrawInput.get(4).toString().toLowerCase();
List<Log> logs = txReceipt.getLogs();
if (logs != null && logs.size() > 0) {
boolean correctErc20 = false;
boolean correctMainAsset = false;
boolean hasReceiveAddress = false;
List<String> topics;
String eventHash;
String contract;
// 转账金额
BigInteger amount = BigInteger.ZERO;
for (Log log : logs) {
topics = log.getTopics();
if (topics.size() == 0) {
continue;
}
eventHash = topics.get(0);
contract = log.getAddress().toLowerCase();
// 为ERC20提现
if (eventHash.equals(HtgConstant.EVENT_HASH_ERC20_TRANSFER)) {
int length = topics.get(1).length();
String fromAddress = HtgConstant.HEX_PREFIX + topics.get(1).substring(26, length);
if (isERC20 &&
contract.equalsIgnoreCase(erc20) &&
(fromAddress.equalsIgnoreCase(htgContext.MULTY_SIGN_ADDRESS()) || fromAddress.equalsIgnoreCase(HtgConstant.ZERO_ADDRESS))) {
String toAddress = HtgConstant.HEX_PREFIX + topics.get(2).substring(26, length);
if (!receive.equalsIgnoreCase(toAddress)) {
logger().warn("提现交易[{}]的接收地址不匹配", txHash);
continue;
}
correctErc20 = true;
hasReceiveAddress = true;
String data;
if (topics.size() == 3) {
data = log.getData();
} else {
data = topics.get(3);
}
String[] v = data.split("x");
// 转账金额
BigInteger _amount = new BigInteger(v[1], 16);
if (_amount.compareTo(BigInteger.ZERO) > 0) {
amount = amount.add(_amount);
}
}
}
// 为主资产提现
if (eventHash.equals(HtgConstant.EVENT_HASH_TRANSFERFUNDS)) {
if (isERC20 || !contract.equals(htgContext.MULTY_SIGN_ADDRESS())) {
if (isERC20) {
logger().warn("提现交易[{}]的提现类型冲突[0]", txHash);
} else {
logger().warn("提现交易[{}]的多签合约地址不匹配", txHash);
}
return false;
}
String data = log.getData();
String toAddress = HtgConstant.HEX_PREFIX + data.substring(26, 66);
if (!receive.equalsIgnoreCase(toAddress)) {
logger().warn("提现交易[{}]的接收地址不匹配[主资产提现]", txHash);
return false;
}
correctMainAsset = true;
hasReceiveAddress = true;
String amountStr = data.substring(66, 130);
// 转账金额
BigInteger _amount = new BigInteger(amountStr, 16);
if (_amount.compareTo(BigInteger.ZERO) > 0) {
amount = amount.add(_amount);
}
}
}
if (!hasReceiveAddress) {
logger().warn("提现交易[{}]的接收地址不匹配", txHash);
return false;
}
if (correctErc20 && correctMainAsset) {
logger().warn("提现交易[{}]的提现类型冲突[1]", txHash);
return false;
}
if (correctMainAsset) {
po.setTo(receive.toLowerCase());
po.setValue(amount);
po.setDecimals(htgContext.getConfig().getDecimals());
po.setAssetId(htgContext.HTG_ASSET_ID());
return true;
} else if (correctErc20) {
po.setIfContractAsset(true);
po.setContractAddress(erc20);
po.setTo(receive.toLowerCase());
po.setValue(amount);
return true;
}
}
logger().warn("提现交易[{}]解析数据缺失", txHash);
return false;
}
public boolean validationEthDepositByCrossOutII(Transaction tx, TransactionReceipt txReceipt, HeterogeneousTransactionInfo po) throws Exception {
if (tx == null) {
logger().warn("交易不存在");
return false;
}
String txHash = tx.getHash();
if (txReceipt == null) {
txReceipt = htgWalletApi.getTxReceipt(txHash);
}
List<Log> logs = txReceipt.getLogs();
if (logs == null || logs.isEmpty()) {
logger().warn("交易[{}]事件为空", txHash);
return false;
}
List<Object> crossOutInput = HtgUtil.parseInput(tx.getInput(), HtgConstant.INPUT_CROSS_OUT_II);
String _to = crossOutInput.get(0).toString();
BigInteger _amount = new BigInteger(crossOutInput.get(1).toString());
String _erc20 = crossOutInput.get(2).toString().toLowerCase();
if (HtgConstant.ZERO_ADDRESS.equals(_erc20)) {
// 主资产充值交易
for (Log log : logs) {
List<String> topics = log.getTopics();
String eventHash = topics.get(0);
String eventContract = log.getAddress().toLowerCase();
if (!HtgConstant.EVENT_HASH_CROSS_OUT_II_FUNDS.equals(eventHash)) {
continue;
}
if (!eventContract.equals(htgContext.MULTY_SIGN_ADDRESS())) {
continue;
}
List<Object> depositEvent = HtgUtil.parseEvent(log.getData(), HtgConstant.EVENT_CROSS_OUT_II_FUNDS);
if (depositEvent == null && depositEvent.size() != 6) {
logger().warn("交易[{}]CrossOutII事件数据不合法[0]", txHash);
return false;
}
String from = depositEvent.get(0).toString();
String to = depositEvent.get(1).toString();
String erc20 = depositEvent.get(3).toString();
BigInteger ethAmount = new BigInteger(depositEvent.get(4).toString());
String extend = Numeric.toHexString((byte[]) depositEvent.get(5));
po.setDepositIIExtend(extend);
if (tx.getFrom().equals(from) && tx.getValue().compareTo(ethAmount) == 0 && HtgConstant.ZERO_ADDRESS.equals(erc20)) {
if (po != null) {
po.setIfContractAsset(false);
po.setFrom(from);
po.setTo(tx.getTo());
po.setValue(ethAmount);
po.setDecimals(htgContext.getConfig().getDecimals());
po.setAssetId(htgContext.HTG_ASSET_ID());
po.setNerveAddress(to);
po.setTxType(HeterogeneousChainTxType.DEPOSIT);
}
return true;
}
}
logger().warn("交易[{}]的主资产[{}]充值II事件不匹配", txHash, htgContext.getConfig().getSymbol());
return false;
} else {
// ERC20充值和主资产充值
if (!htgERC20Helper.isERC20(_erc20, po)) {
logger().warn("CrossOutII: erc20[{}]未注册", _erc20);
return false;
}
boolean transferEvent = false;
boolean burnEvent = true;
boolean crossOutEvent = false;
BigInteger erc20Amount = BigInteger.ZERO;
for (Log log : logs) {
List<String> topics = log.getTopics();
String eventHash = topics.get(0);
String eventContract = log.getAddress().toLowerCase();
if (HtgConstant.EVENT_HASH_ERC20_TRANSFER.equals(eventHash)) {
if (!eventContract.equals(_erc20)) {
continue;
}
int length = topics.get(1).length();
String fromAddress = HtgConstant.HEX_PREFIX + topics.get(1).substring(26, length).toString();
String toAddress = HtgConstant.HEX_PREFIX + topics.get(2).substring(26, length).toString();
String data;
if (topics.size() == 3) {
data = log.getData();
} else {
data = topics.get(3);
}
String[] v = data.split("x");
// 转账金额
BigInteger amount = new BigInteger(v[1], 16);
// 当toAddress是0x0时,则说明这是一个从当前多签合约销毁erc20的transfer事件
if (HtgConstant.ZERO_ADDRESS.equals(toAddress)) {
if (!fromAddress.equals(htgContext.MULTY_SIGN_ADDRESS())) {
continue;
}
if (amount.compareTo(_amount) != 0) {
logger().warn("CrossOutII: 交易[{}]的ERC20销毁金额不匹配", txHash);
burnEvent = false;
break;
}
} else {
// 用户转移token到多签合约的事件
// 必须是多签合约地址
if (!toAddress.equals(htgContext.MULTY_SIGN_ADDRESS())) {
continue;
}
erc20Amount = erc20Amount.add(amount);
transferEvent = true;
}
}
if (HtgConstant.EVENT_HASH_CROSS_OUT_II_FUNDS.equals(eventHash)) {
if (!eventContract.equals(htgContext.MULTY_SIGN_ADDRESS())) {
continue;
}
List<Object> depositEvent = HtgUtil.parseEvent(log.getData(), HtgConstant.EVENT_CROSS_OUT_II_FUNDS);
if (depositEvent == null && depositEvent.size() != 6) {
logger().warn("交易[{}]CrossOutII事件数据不合法[1]", txHash);
return false;
}
String from = depositEvent.get(0).toString();
String to = depositEvent.get(1).toString();
BigInteger amount = new BigInteger(depositEvent.get(2).toString());
String erc20 = depositEvent.get(3).toString();
BigInteger ethAmount = new BigInteger(depositEvent.get(4).toString());
String extend = Numeric.toHexString((byte[]) depositEvent.get(5));
if (!tx.getFrom().equals(from)) {
logger().warn("交易[{}]CrossOutII事件数据不合法[2]", txHash);
return false;
}
if (!_to.equals(to)) {
logger().warn("交易[{}]CrossOutII事件数据不合法[3]", txHash);
return false;
}
if (amount.compareTo(_amount) != 0) {
logger().warn("交易[{}]CrossOutII事件数据不合法[4]", txHash);
return false;
}
if (!_erc20.equals(erc20)) {
logger().warn("交易[{}]CrossOutII事件数据不合法[5]", txHash);
return false;
}
if (tx.getFrom().equals(from) && tx.getValue().compareTo(BigInteger.ZERO) > 0 && tx.getValue().compareTo(ethAmount) == 0) {
// 记录主资产充值
po.setDepositIIMainAsset(ethAmount, htgContext.getConfig().getDecimals(), htgContext.HTG_ASSET_ID());
}
po.setDepositIIExtend(extend);
crossOutEvent = true;
}
}
if (transferEvent && burnEvent && crossOutEvent) {
if (erc20Amount.compareTo(_amount) > 0) {
logger().warn("CrossOutII: 交易[{}]的ERC20充值金额不匹配", txHash);
return false;
}
if (erc20Amount.equals(BigInteger.ZERO)) {
logger().warn("CrossOutII: 交易[{}]的ERC20充值金额为0", txHash);
return false;
}
if (po != null && erc20Amount.compareTo(BigInteger.ZERO) > 0) {
po.setIfContractAsset(true);
po.setContractAddress(_erc20);
po.setFrom(tx.getFrom());
po.setTo(tx.getTo());
po.setValue(erc20Amount);
po.setNerveAddress(_to);
po.setTxType(HeterogeneousChainTxType.DEPOSIT);
}
return true;
} else {
logger().warn("交易[{}]的ERC20充值II事件不匹配, transferEvent: {}, burnEvent: {}, crossOutEvent: {}",
txHash, transferEvent, burnEvent, crossOutEvent);
return false;
}
}
}
}
| 72,857 | 0.512454 | 0.502394 | 1,517 | 45.127224 | 29.859642 | 169 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.735663 | false | false | 12 |
3ef5e633593f14901d4390ad8bcf328f054834b8 | 1,056,561,981,386 | 37a7be7738b039b836761e44f9a93c69e4c99d07 | /Evaluate Expression To True.java | 7b8c2a1ec782b163d09330bc90d517e597362e0d | [
"CC-BY-4.0"
] | permissive | ervaibhavkumar/DSA | https://github.com/ervaibhavkumar/DSA | 43e1158ebb14513efbaa305c70ad322628506d52 | f9a6a60e8396097a200d8704f4b2eeda42d712ae | refs/heads/main | 2023-07-30T21:37:58.358000 | 2022-10-01T06:29:35 | 2022-10-01T06:29:35 | 412,701,816 | 0 | 0 | null | true | 2021-10-02T05:40:54 | 2021-10-02T05:40:53 | 2021-10-02T05:34:46 | 2021-10-02T05:34:44 | 6 | 0 | 0 | 0 | null | false | false | public class Solution {
int [][] DT = new int[151][151];
int [][] DF = new int[151][151];
int mod = 1003;
public int cnttrue(String A) {
for (int[] row: DT) Arrays.fill(row, -1);
for (int[] row: DF) Arrays.fill(row, -1);
return solveTrue(A, 0, A.length()-1)%1003;
}
int solveTrue(String A, int i, int j){
if(i>j) return 0;
if(i==j){
return A.charAt(i)=='T' ? 1 : 0;
}
if(DT[i][j] != -1){
return DT[i][j];
}
int count = 0;
for(int k=i; k<j; k=k+2){
char operator = A.charAt(k+1);
int leftFalse = DF[i][k] != -1 ? DF[i][k] : solveFalse(A, i, k);
int rightFalse = DF[k+2][j] != -1 ? DF[k+2][j] : solveFalse(A, k+2, j);
int leftTrue = DT[i][k] != -1 ? DT[i][k] : solveTrue(A, i, k);
int rightTrue = DT[k+2][j] != -1 ? DT[k+2][j] : solveTrue(A, k+2, j);
if(operator == '&'){
count += leftTrue * rightTrue % mod;
} else if(operator == '^'){
count += leftTrue * rightFalse % mod;
count += leftFalse * rightTrue % mod;
} else if(operator == '|'){
count += leftTrue * rightTrue % mod;
count += leftTrue * rightFalse % mod;
count += leftFalse * rightTrue % mod;
}
}
DT[i][j] = count;
return count;
}
int solveFalse(String A, int i, int j){
if(i>j) return 0;
if(i==j){
return A.charAt(i)=='F' ? 1 : 0;
}
if(DF[i][j] != -1){
return DF[i][j];
}
int count = 0;
for(int k=i; k<j; k=k+2){
char operator = A.charAt(k+1);
int leftFalse = DF[i][k] != -1 ? DF[i][k] : solveFalse(A, i, k);
int rightFalse = DF[k+2][j] != -1 ? DF[k+2][j] : solveFalse(A, k+2, j);
int leftTrue = DT[i][k] != -1 ? DT[i][k] : solveTrue(A, i, k);
int rightTrue = DT[k+2][j] != -1 ? DT[k+2][j] : solveTrue(A, k+2, j);
if(operator == '|'){
count += leftFalse * rightFalse % mod;
} else if(operator == '^'){
count += leftTrue * rightTrue % mod;
count += leftFalse * rightFalse % mod;
} else if(operator == '&'){
count += leftFalse * rightFalse % mod;
count += leftTrue * rightFalse % mod;
count += leftFalse * rightTrue % mod;
}
}
DF[i][j] = count;
return count;
}
}
| UTF-8 | Java | 2,641 | java | Evaluate Expression To True.java | Java | [] | null | [] | public class Solution {
int [][] DT = new int[151][151];
int [][] DF = new int[151][151];
int mod = 1003;
public int cnttrue(String A) {
for (int[] row: DT) Arrays.fill(row, -1);
for (int[] row: DF) Arrays.fill(row, -1);
return solveTrue(A, 0, A.length()-1)%1003;
}
int solveTrue(String A, int i, int j){
if(i>j) return 0;
if(i==j){
return A.charAt(i)=='T' ? 1 : 0;
}
if(DT[i][j] != -1){
return DT[i][j];
}
int count = 0;
for(int k=i; k<j; k=k+2){
char operator = A.charAt(k+1);
int leftFalse = DF[i][k] != -1 ? DF[i][k] : solveFalse(A, i, k);
int rightFalse = DF[k+2][j] != -1 ? DF[k+2][j] : solveFalse(A, k+2, j);
int leftTrue = DT[i][k] != -1 ? DT[i][k] : solveTrue(A, i, k);
int rightTrue = DT[k+2][j] != -1 ? DT[k+2][j] : solveTrue(A, k+2, j);
if(operator == '&'){
count += leftTrue * rightTrue % mod;
} else if(operator == '^'){
count += leftTrue * rightFalse % mod;
count += leftFalse * rightTrue % mod;
} else if(operator == '|'){
count += leftTrue * rightTrue % mod;
count += leftTrue * rightFalse % mod;
count += leftFalse * rightTrue % mod;
}
}
DT[i][j] = count;
return count;
}
int solveFalse(String A, int i, int j){
if(i>j) return 0;
if(i==j){
return A.charAt(i)=='F' ? 1 : 0;
}
if(DF[i][j] != -1){
return DF[i][j];
}
int count = 0;
for(int k=i; k<j; k=k+2){
char operator = A.charAt(k+1);
int leftFalse = DF[i][k] != -1 ? DF[i][k] : solveFalse(A, i, k);
int rightFalse = DF[k+2][j] != -1 ? DF[k+2][j] : solveFalse(A, k+2, j);
int leftTrue = DT[i][k] != -1 ? DT[i][k] : solveTrue(A, i, k);
int rightTrue = DT[k+2][j] != -1 ? DT[k+2][j] : solveTrue(A, k+2, j);
if(operator == '|'){
count += leftFalse * rightFalse % mod;
} else if(operator == '^'){
count += leftTrue * rightTrue % mod;
count += leftFalse * rightFalse % mod;
} else if(operator == '&'){
count += leftFalse * rightFalse % mod;
count += leftTrue * rightFalse % mod;
count += leftFalse * rightTrue % mod;
}
}
DF[i][j] = count;
return count;
}
}
| 2,641 | 0.421053 | 0.399091 | 81 | 31.592592 | 23.608837 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.864198 | false | false | 12 |
be815cb21f8b1dbe3310bff75222c6c47ee859ee | 12,549,894,452,492 | 1729209612875edc1576404f1c807d6e62da1471 | /17-08-2018/src/estruccturasDatos/Main.java | 1b1ee3980155aae2a0fe0a73ba8dc3ef69420e2f | [] | no_license | jorgefdz1209/PracticasCurso | https://github.com/jorgefdz1209/PracticasCurso | 315980d94aaddbc1ae3bce2d34c41049cf5baf19 | 132de558287bd90ae9f000e3e9a1bd33bf77c4a6 | refs/heads/master | 2020-03-27T09:19:35.240000 | 2018-09-18T02:15:10 | 2018-09-18T02:15:10 | 145,577,465 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package estruccturasDatos;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.management.ListenerNotFoundException;
/**
* Clase main utilizada como prueba
* @author Antoinette1
*
*/
public class Main {
public static void main(String[] args) {
System.out.println("Ejemplo de uso de collections");
//Lista
List listaCliente = new ArrayList();
//1.1
Cliente c1 = new Cliente("1","1@mail.com");
Cliente c2 = new Cliente("2","2@mail.com");
Cliente c3 = new Cliente("3","3@mail.com");
listaCliente.add(c1);
listaCliente.add(c2);
listaCliente.add(c3);
for(int i=0; i<listaCliente.size();i++) {
System.out.println("Cliente: "+listaCliente.get(i));
}
//foreach
for(Object o : listaCliente) {
Cliente c = (Cliente) o;
System.out.println("Cliente "+c);
}
System.out.println("#####################################################");
Set clienteSet = new HashSet();
boolean agregado;
agregado=clienteSet.add(c1);
System.out.println(agregado);
agregado=clienteSet.add(c2);
System.out.println(agregado);
agregado=clienteSet.add(c3);
System.out.println(agregado);
agregado=clienteSet.add(c3);
System.out.println(agregado);
for(Object o : clienteSet) {
Cliente c = (Cliente)o;
System.out.println("Cliente set"+c);
}
System.out.println("#####################################################");
Map mapa = new HashMap();
mapa.put(1, c1);
mapa.put(2, c2);
mapa.put(3, c3);
mapa.put(5, 5);
Set llavesMapa = mapa.keySet();
for(Object o : llavesMapa) {
try {
Object clienteDentroMapa = mapa.get(o);
Cliente c = (Cliente) clienteDentroMapa;
System.out.println("Cliente Obtenido "+ c);
}catch (ClassCastException e) {
System.out.println("No se reconoce el tipo de variable");
}
}
}
}
| UTF-8 | Java | 2,005 | java | Main.java | Java | [
{
"context": "*\r\n * Clase main utilizada como prueba\r\n * @author Antoinette1\r\n *\r\n */\r\npublic class Main {\r\n\r\n\tpublic",
"end": 294,
"score": 0.9593174457550049,
"start": 292,
"tag": "USERNAME",
"value": "An"
},
{
"context": " * Clase main utilizada como prueba\r\n * @a... | null | [] | package estruccturasDatos;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.management.ListenerNotFoundException;
/**
* Clase main utilizada como prueba
* @author Antoinette1
*
*/
public class Main {
public static void main(String[] args) {
System.out.println("Ejemplo de uso de collections");
//Lista
List listaCliente = new ArrayList();
//1.1
Cliente c1 = new Cliente("1","<EMAIL>");
Cliente c2 = new Cliente("2","<EMAIL>");
Cliente c3 = new Cliente("3","<EMAIL>");
listaCliente.add(c1);
listaCliente.add(c2);
listaCliente.add(c3);
for(int i=0; i<listaCliente.size();i++) {
System.out.println("Cliente: "+listaCliente.get(i));
}
//foreach
for(Object o : listaCliente) {
Cliente c = (Cliente) o;
System.out.println("Cliente "+c);
}
System.out.println("#####################################################");
Set clienteSet = new HashSet();
boolean agregado;
agregado=clienteSet.add(c1);
System.out.println(agregado);
agregado=clienteSet.add(c2);
System.out.println(agregado);
agregado=clienteSet.add(c3);
System.out.println(agregado);
agregado=clienteSet.add(c3);
System.out.println(agregado);
for(Object o : clienteSet) {
Cliente c = (Cliente)o;
System.out.println("Cliente set"+c);
}
System.out.println("#####################################################");
Map mapa = new HashMap();
mapa.put(1, c1);
mapa.put(2, c2);
mapa.put(3, c3);
mapa.put(5, 5);
Set llavesMapa = mapa.keySet();
for(Object o : llavesMapa) {
try {
Object clienteDentroMapa = mapa.get(o);
Cliente c = (Cliente) clienteDentroMapa;
System.out.println("Cliente Obtenido "+ c);
}catch (ClassCastException e) {
System.out.println("No se reconoce el tipo de variable");
}
}
}
}
| 1,996 | 0.602494 | 0.588529 | 82 | 22.45122 | 18.500595 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.280488 | false | false | 12 |
037c902c14cceb4a37a32479b7efb97ebac64dbc | 21,809,843,957,179 | a505bea9f1ae208de7ab0fb67cc83a3869336fc5 | /daoDemo/src/main/java/com/summerclass/domain/ShowEventsBean.java | 5790044cb10ab5da5711b8fd43eb5ed8db4ca3e7 | [] | no_license | mmaynar1/SummerClass | https://github.com/mmaynar1/SummerClass | 62fafe5a90b3a9487e84995eac81de0fca2210e2 | c55969af5b08f4ba849b327bdab5445dd70d6ec4 | refs/heads/master | 2020-04-06T03:55:19.406000 | 2014-08-17T19:01:01 | 2014-08-17T19:01:01 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.summerclass.domain;
import java.util.List;
public class ShowEventsBean
{
private String securityNotice;
private Selectable employee;
private Club club;
private List<EventType> eventTypes;
private List<Club> clubs;
public ShowEventsBean()
{
}
public ShowEventsBean( Selectable employee, Club club, List<EventType> eventTypes, List<Club> clubs )
{
this.employee = employee;
this.club = club;
this.eventTypes = eventTypes;
this.clubs = clubs;
this.securityNotice = "This page is for internal use only.";
}
public Selectable getEmployee()
{
return employee;
}
public void setEmployee( Selectable employee )
{
this.employee = employee;
}
public Club getClub()
{
return club;
}
public void setClub( Club club )
{
this.club = club;
}
public List<EventType> getEventTypes()
{
return eventTypes;
}
public void setEventTypes( List<EventType> eventTypes )
{
this.eventTypes = eventTypes;
}
public List<Club> getClubs()
{
return clubs;
}
public void setClubs( List<Club> clubs )
{
this.clubs = clubs;
}
public String getSecurityNotice()
{
return securityNotice;
}
public void setSecurityNotice( String securityNotice )
{
this.securityNotice = securityNotice;
}
}
| UTF-8 | Java | 1,461 | java | ShowEventsBean.java | Java | [] | null | [] | package com.summerclass.domain;
import java.util.List;
public class ShowEventsBean
{
private String securityNotice;
private Selectable employee;
private Club club;
private List<EventType> eventTypes;
private List<Club> clubs;
public ShowEventsBean()
{
}
public ShowEventsBean( Selectable employee, Club club, List<EventType> eventTypes, List<Club> clubs )
{
this.employee = employee;
this.club = club;
this.eventTypes = eventTypes;
this.clubs = clubs;
this.securityNotice = "This page is for internal use only.";
}
public Selectable getEmployee()
{
return employee;
}
public void setEmployee( Selectable employee )
{
this.employee = employee;
}
public Club getClub()
{
return club;
}
public void setClub( Club club )
{
this.club = club;
}
public List<EventType> getEventTypes()
{
return eventTypes;
}
public void setEventTypes( List<EventType> eventTypes )
{
this.eventTypes = eventTypes;
}
public List<Club> getClubs()
{
return clubs;
}
public void setClubs( List<Club> clubs )
{
this.clubs = clubs;
}
public String getSecurityNotice()
{
return securityNotice;
}
public void setSecurityNotice( String securityNotice )
{
this.securityNotice = securityNotice;
}
}
| 1,461 | 0.611225 | 0.611225 | 75 | 18.48 | 19.930786 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 12 |
f1ace5fdfe707546622b1a7ed3366b695cbda741 | 22,900,765,680,955 | 41ae558db0931f42adc031796fab624d708dc41c | /src/main/java/dyaniii/co/za/services/EmployeeService.java | 2f7380e36117aefb5b34300ef0e1da4fff28c0aa | [] | no_license | dyaniii/BeYouHairSalonBackendApp | https://github.com/dyaniii/BeYouHairSalonBackendApp | d8e78dd8818bf0e64e670828bc0f611ac8111e25 | 88124d74f7fbd8b8f2362b25054d355a95516357 | refs/heads/master | 2016-09-19T07:27:50.607000 | 2016-09-02T14:37:44 | 2016-09-02T14:37:44 | 67,229,958 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dyaniii.co.za.services;
import dyaniii.co.za.domain.Customer;
import dyaniii.co.za.domain.Employee;
import java.util.Set;
/**
* Created by asiphe.dyani on 2016/08/06.
*/
public interface EmployeeService extends Service<Employee,Long>{
}
| UTF-8 | Java | 251 | java | EmployeeService.java | Java | [
{
"context": "mployee;\n\nimport java.util.Set;\n\n/**\n * Created by asiphe.dyani on 2016/08/06.\n */\npublic interface EmployeeServi",
"end": 163,
"score": 0.9636013507843018,
"start": 151,
"tag": "USERNAME",
"value": "asiphe.dyani"
}
] | null | [] | package dyaniii.co.za.services;
import dyaniii.co.za.domain.Customer;
import dyaniii.co.za.domain.Employee;
import java.util.Set;
/**
* Created by asiphe.dyani on 2016/08/06.
*/
public interface EmployeeService extends Service<Employee,Long>{
}
| 251 | 0.760956 | 0.729084 | 13 | 18.307692 | 20.715601 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.384615 | false | false | 12 |
529fd7181a7f9487f488466453881b1f743899b7 | 1,967,095,030,219 | 49f2e066ade2e8a6734b7b6a53e2f18966c02426 | /src/main/java/tn/esprit/spring/repository/AbonnementRepository.java | cd587c1ef33a626c6d208c520c0a41001636a69b | [] | no_license | Chakib1995/Service-Abonnement-backend | https://github.com/Chakib1995/Service-Abonnement-backend | d2600f93d384ba3d5a1bf78c4814cdfc600c9d4a | 473dd67d9b66b1ce3427724ea10a05e15b96bbeb | refs/heads/main | 2023-04-12T04:25:21.997000 | 2021-04-19T16:47:56 | 2021-04-19T16:47:56 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package tn.esprit.spring.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import tn.esprit.spring.entities.Abonnement;
@Repository
public interface AbonnementRepository extends JpaRepository<Abonnement, Long> {
} | UTF-8 | Java | 292 | java | AbonnementRepository.java | Java | [] | null | [] | package tn.esprit.spring.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import tn.esprit.spring.entities.Abonnement;
@Repository
public interface AbonnementRepository extends JpaRepository<Abonnement, Long> {
} | 292 | 0.842466 | 0.842466 | 11 | 25.636364 | 28.036575 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false | 6 |
9857b1de5eaa8b8c443d5542ed3cc3655f09c403 | 13,142,599,979,359 | b8aa0862428efb42f1cca86cd9cdd85f6c6e1453 | /src/br/imd/ufrn/lpii/model/Site.java | 6a08230ef220734f4d73c975c37f09d85a9f059c | [] | no_license | ritallopes/Detector-de-fake-news | https://github.com/ritallopes/Detector-de-fake-news | 34345d3a892229559007ac7ec7f29d4c51fe8b92 | ea3be4163f86419356f5ff428e435320dde18eb6 | refs/heads/master | 2020-09-09T03:31:53.339000 | 2019-06-18T22:41:29 | 2019-06-18T22:41:29 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.imd.ufrn.lpii.model;
import java.util.ArrayList;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import br.imd.ufrn.lpii.model.abstratics.Externos;
public class Site implements Externos{
@Override
public ArrayList<String> abrir(String url) throws Exception {
ArrayList<String> paragrafos = new ArrayList<String>();
final StringBuilder textoVermelho = new StringBuilder(); // Garanto que o objeto so vai ser istanciado uma unica vez.
Document doc = Jsoup.connect(url).get(); // se conecta ao site da url
Elements element = doc.select("p"); // procurar por todas as tags de paragrafos do HTML
for (Element step : element) {
String temp = step.text(); // coleta o texto dentro da tag
String tempVermelho = step.select("span[style*=#ff0000]").text(); // coleta todo o texto que estiver em vermelho
//filtra os texto com mais de 100 characteres
if(tempVermelho.length() > 100) {
textoVermelho.append(" " + tempVermelho); // une o texto vermelho com mais de 100 caracteres
}
if(temp.length() > 100) {
paragrafos.add(temp); //adiciona o texto com mais de 100 cacarteres em um array
}
}
// se tiver mais de dois caracteres no adiciona o texto vermelho ao array
if(textoVermelho.length() > 2) {
paragrafos.add(0,textoVermelho.toString());
}
return paragrafos;
}
}
| UTF-8 | Java | 1,426 | java | Site.java | Java | [] | null | [] | package br.imd.ufrn.lpii.model;
import java.util.ArrayList;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import br.imd.ufrn.lpii.model.abstratics.Externos;
public class Site implements Externos{
@Override
public ArrayList<String> abrir(String url) throws Exception {
ArrayList<String> paragrafos = new ArrayList<String>();
final StringBuilder textoVermelho = new StringBuilder(); // Garanto que o objeto so vai ser istanciado uma unica vez.
Document doc = Jsoup.connect(url).get(); // se conecta ao site da url
Elements element = doc.select("p"); // procurar por todas as tags de paragrafos do HTML
for (Element step : element) {
String temp = step.text(); // coleta o texto dentro da tag
String tempVermelho = step.select("span[style*=#ff0000]").text(); // coleta todo o texto que estiver em vermelho
//filtra os texto com mais de 100 characteres
if(tempVermelho.length() > 100) {
textoVermelho.append(" " + tempVermelho); // une o texto vermelho com mais de 100 caracteres
}
if(temp.length() > 100) {
paragrafos.add(temp); //adiciona o texto com mais de 100 cacarteres em um array
}
}
// se tiver mais de dois caracteres no adiciona o texto vermelho ao array
if(textoVermelho.length() > 2) {
paragrafos.add(0,textoVermelho.toString());
}
return paragrafos;
}
}
| 1,426 | 0.710379 | 0.695652 | 45 | 30.688889 | 33.03656 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.977778 | false | false | 6 |
a6c2a9edb1c8e060ebfa8b41b08591e9206a0f4f | 15,006,615,801,123 | 65be0fb2d4b1933f3f87f9804b069bf664945c10 | /src/main/java/teamdraco/unnamedanimalmod/common/entity/CapybaraEntity.java | 89b69b431f6217886ba520109ffe1b263de3ed52 | [] | no_license | TeamDraco/UnnamedAnimalMod | https://github.com/TeamDraco/UnnamedAnimalMod | e3a85ef4b03415a690316f5c30b6b2489e72477f | dd5de1746ab69c77a28171ed59992e8c9a18b06a | refs/heads/master | 2023-04-26T05:08:36.563000 | 2022-06-15T16:43:36 | 2022-06-15T16:43:36 | 357,075,153 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package teamdraco.unnamedanimalmod.common.entity;
import net.minecraft.entity.projectile.AbstractArrowEntity;
import net.minecraft.network.datasync.DataParameter;
import net.minecraft.network.datasync.DataSerializers;
import net.minecraft.network.datasync.EntityDataManager;
import teamdraco.unnamedanimalmod.common.entity.util.ai.CapybaraAnimalAttractionGoal;
import teamdraco.unnamedanimalmod.init.UAMEntities;
import teamdraco.unnamedanimalmod.init.UAMItems;
import teamdraco.unnamedanimalmod.init.UAMSounds;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.block.FlowingFluidBlock;
import net.minecraft.entity.*;
import net.minecraft.entity.ai.attributes.AttributeModifierMap;
import net.minecraft.entity.ai.attributes.Attributes;
import net.minecraft.entity.ai.goal.*;
import net.minecraft.entity.passive.TameableEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Inventory;
import net.minecraft.inventory.container.ChestContainer;
import net.minecraft.inventory.container.Container;
import net.minecraft.inventory.container.INamedContainerProvider;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.item.crafting.Ingredient;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.nbt.ListNBT;
import net.minecraft.pathfinding.*;
import net.minecraft.tags.FluidTags;
import net.minecraft.util.*;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.shapes.ISelectionContext;
import net.minecraft.world.DifficultyInstance;
import net.minecraft.world.IServerWorld;
import net.minecraft.world.World;
import net.minecraft.world.server.ServerWorld;
import net.minecraftforge.event.ForgeEventFactory;
import javax.annotation.Nullable;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CapybaraEntity extends TameableEntity implements INamedContainerProvider {
private static final LazyValue<Set<IItemProvider>> TEMPT_ITEMS = new LazyValue<>(() -> {
Stream<IItemProvider> stream = Stream.of(Blocks.MELON, Items.APPLE, Items.SUGAR_CANE, Items.MELON_SLICE, UAMItems.MANGROVE_FRUIT.get());
return stream.map(IItemProvider::asItem).collect(Collectors.toSet());
});
private static final DataParameter<Integer> CHESTS = EntityDataManager.defineId(CapybaraEntity.class, DataSerializers.INT);
public IInventory inventory;
public CapybaraEntity(EntityType<? extends CapybaraEntity> type, World worldIn) {
super(type, worldIn);
}
@Override
protected void registerGoals() {
this.goalSelector.addGoal(1, new PanicGoal(this, 2.0D));
this.goalSelector.addGoal(2, new SitGoal(this));
this.goalSelector.addGoal(3, new BreedGoal(this, 1.0D));
this.goalSelector.addGoal(4, new TemptGoal(this, 1.25D, Ingredient.of(TEMPT_ITEMS.get().toArray(new IItemProvider[0])), false));
this.goalSelector.addGoal(5, new FollowParentGoal(this, 1.25D));
this.goalSelector.addGoal(6, new RandomWalkingGoal(this, 1.0D));
this.goalSelector.addGoal(7, new FollowOwnerGoal(this, 1.0D, 10.0F, 2.0F, false));
this.goalSelector.addGoal(7, new LookAtGoal(this, PlayerEntity.class, 6.0F));
this.goalSelector.addGoal(8, new LookRandomlyGoal(this));
this.goalSelector.addGoal(8, new LookAtGoal(this, PlayerEntity.class, 6.0F));
this.goalSelector.addGoal(9, new LookRandomlyGoal(this));
this.goalSelector.addGoal(10, new CapybaraAnimalAttractionGoal(this));
}
@Override
protected void defineSynchedData() {
super.defineSynchedData();
entityData.define(CHESTS, 0);
}
public static AttributeModifierMap.MutableAttribute createAttributes() {
return MobEntity.createMobAttributes().add(Attributes.MAX_HEALTH, 14.0D).add(Attributes.MOVEMENT_SPEED, 0.2D);
}
@Override
protected float getWaterSlowDown() {
return 0.65f;
}
@Override
public boolean isFood(ItemStack stack) {
return stack.getItem() == Blocks.MELON.asItem();
}
protected SoundEvent getAmbientSound() {
return UAMSounds.CAPYBARA_AMBIENT.get();
}
protected SoundEvent getHurtSound(DamageSource damageSourceIn) {
return UAMSounds.CAPYBARA_HURT.get();
}
protected SoundEvent getDeathSound() {
return UAMSounds.CAPYBARA_DEATH.get();
}
protected void playStepSound(BlockPos pos, BlockState blockIn) {
this.playSound(SoundEvents.COW_STEP, 0.15F, 1.0F);
}
public boolean hurt(DamageSource p_70097_1_, float p_70097_2_) {
if (this.isInvulnerableTo(p_70097_1_)) {
return false;
} else {
Entity entity = p_70097_1_.getEntity();
this.setOrderedToSit(false);
if (entity != null && !(entity instanceof PlayerEntity) && !(entity instanceof AbstractArrowEntity)) {
p_70097_2_ = (p_70097_2_ + 1.0F) / 2.0F;
}
return super.hurt(p_70097_1_, p_70097_2_);
}
}
@Override
public ActionResultType mobInteract(PlayerEntity player, Hand hand) {
final ItemStack stack = player.getItemInHand(hand);
if (player.isShiftKeyDown()) {
if (stack.getItem() == Blocks.CHEST.asItem()) {
if (inventory == null || inventory.getContainerSize() < 27) {
inventory = new Inventory(27);
entityData.set(CHESTS, 1);
if (!player.abilities.instabuild) {
stack.shrink(1);
}
return ActionResultType.sidedSuccess(this.level.isClientSide);
}
else if (inventory.getContainerSize() < 54) {
IInventory inv = new Inventory(54);
for (int i = 0; i < 27; i++) {
inv.setItem(i, inventory.getItem(i));
}
inventory = inv;
entityData.set(CHESTS, 2);
if (!player.abilities.instabuild) {
stack.shrink(1);
}
return ActionResultType.sidedSuccess(this.level.isClientSide);
}
}
if (stack.getItem() == Items.STICK) {
this.setOrderedToSit(!this.isOrderedToSit());
}
else {
player.openMenu(this);
return ActionResultType.SUCCESS;
}
}
else if (TEMPT_ITEMS.get().contains(stack.getItem()) && !isTame()) {
if (this.random.nextInt(3) == 0 && !ForgeEventFactory.onAnimalTame(this, player)) {
this.tame(player);
this.navigation.stop();
this.setTarget(null);
this.setOrderedToSit(true);
this.level.broadcastEntityEvent(this, (byte) 7);
}
if (!player.abilities.instabuild) {
stack.shrink(1);
}
else {
this.level.broadcastEntityEvent(this, (byte) 6);
}
return ActionResultType.sidedSuccess(this.level.isClientSide);
}
else if (!this.isVehicle() && !player.isSecondaryUseActive() && !this.isBaby() && !isInSittingPose()) {
boolean flag = this.isFood(player.getItemInHand(hand));
if (!flag && !this.isVehicle() && !player.isSecondaryUseActive()) {
if (!this.level.isClientSide) {
player.startRiding(this);
}
return ActionResultType.sidedSuccess(this.level.isClientSide);
}
}
else if (!this.getPassengers().isEmpty()) {
ejectPassengers();
}
return super.mobInteract(player, hand);
}
@Override
protected float getSoundVolume() {
return 0.4F;
}
@Override
public CapybaraEntity getBreedOffspring(ServerWorld p_241840_1_, AgeableEntity p_241840_2_) {
return UAMEntities.CAPYBARA.get().create(p_241840_1_);
}
@Override
protected float getStandingEyeHeight(Pose poseIn, EntitySize sizeIn) {
return this.isBaby() ? 0.5F : 0.9F;
}
@Override
public ItemStack getPickedResult(RayTraceResult target) {
return new ItemStack(UAMItems.CAPYBARA_SPAWN_EGG.get());
}
@Override
public void tick() {
super.tick();
this.floatStrider();
this.checkInsideBlocks();
if (getPassengers().isEmpty()) {
for (Entity e : level.getEntities(this, getBoundingBox().inflate(0.5))) {
if (e instanceof MobEntity && e.getBbWidth() <= 0.75f && e.getBbHeight() <= 0.75f && !this.isBaby() && ((MobEntity) e).getMobType() != CreatureAttribute.WATER && !isInWater()) {
e.startRiding(this);
}
}
}
else if (!getPassengers().isEmpty() && isInWater()) {
ejectPassengers();
}
}
@Override
protected PathNavigator createNavigation(World worldIn) {
return new CapybaraEntity.WaterPathNavigator(this, worldIn);
}
@Nullable
public Entity getControllingPassenger() {
return this.getPassengers().isEmpty() ? null : this.getPassengers().get(0);
}
@Override
public boolean canBeControlledByRider() {
return false;
}
@Override
public ILivingEntityData finalizeSpawn(IServerWorld worldIn, DifficultyInstance difficultyIn, SpawnReason reason, @Nullable ILivingEntityData spawnData, @Nullable CompoundNBT dataTag) {
if (spawnData == null) {
spawnData = new AgeableData(1);
}
return super.finalizeSpawn(worldIn, difficultyIn, reason, spawnData, dataTag);
}
private void floatStrider() {
if (this.isInWater()) {
ISelectionContext iselectioncontext = ISelectionContext.of(this);
if (iselectioncontext.isAbove(FlowingFluidBlock.STABLE_SHAPE, this.blockPosition(), true) && !this.level.getFluidState(this.blockPosition().above()).is(FluidTags.WATER)) {
this.onGround = true;
} else {
this.setDeltaMovement(this.getDeltaMovement().scale(0.5D).add(0.0D, 0.05D, 0.0D));
}
}
}
@Override
public void addAdditionalSaveData(CompoundNBT compound) {
super.addAdditionalSaveData(compound);
if (inventory != null) {
final ListNBT inv = new ListNBT();
for (int i = 0; i < this.inventory.getContainerSize(); i++) {
inv.add(inventory.getItem(i).save(new CompoundNBT()));
}
compound.put("Inventory", inv);
}
}
@Override
public void readAdditionalSaveData(CompoundNBT compound) {
super.readAdditionalSaveData(compound);
if (compound.contains("Inventory")) {
final ListNBT inv = compound.getList("Inventory", 10);
inventory = new Inventory(inv.size());
for (int i = 0; i < inv.size(); i++) {
inventory.setItem(i, ItemStack.of(inv.getCompound(i)));
}
entityData.set(CHESTS, inv.size() > 27 ? 2 : 1);
}
}
@Nullable
@Override
public Container createMenu(int p_createMenu_1_, PlayerInventory p_createMenu_2_, PlayerEntity p_createMenu_3_) {
if (inventory == null) {
return null;
}
return inventory.getContainerSize() < 54 ? ChestContainer.threeRows(p_createMenu_1_, p_createMenu_2_, inventory) : ChestContainer.sixRows(p_createMenu_1_, p_createMenu_2_, inventory);
}
public int getChestCount() {
return entityData.get(CHESTS);
}
static class WaterPathNavigator extends GroundPathNavigator {
WaterPathNavigator(CapybaraEntity p_i231565_1_, World p_i231565_2_) {
super(p_i231565_1_, p_i231565_2_);
}
protected PathFinder createPathFinder(int p_179679_1_) {
this.nodeEvaluator = new WalkNodeProcessor();
return new PathFinder(this.nodeEvaluator, p_179679_1_);
}
protected boolean hasValidPathType(PathNodeType p_230287_1_) {
return p_230287_1_ == PathNodeType.WATER || super.hasValidPathType(p_230287_1_);
}
public boolean isStableDestination(BlockPos pos) {
return this.level.getBlockState(pos).is(Blocks.WATER) || super.isStableDestination(pos);
}
}
}
| UTF-8 | Java | 12,669 | java | CapybaraEntity.java | Java | [] | null | [] | package teamdraco.unnamedanimalmod.common.entity;
import net.minecraft.entity.projectile.AbstractArrowEntity;
import net.minecraft.network.datasync.DataParameter;
import net.minecraft.network.datasync.DataSerializers;
import net.minecraft.network.datasync.EntityDataManager;
import teamdraco.unnamedanimalmod.common.entity.util.ai.CapybaraAnimalAttractionGoal;
import teamdraco.unnamedanimalmod.init.UAMEntities;
import teamdraco.unnamedanimalmod.init.UAMItems;
import teamdraco.unnamedanimalmod.init.UAMSounds;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.block.FlowingFluidBlock;
import net.minecraft.entity.*;
import net.minecraft.entity.ai.attributes.AttributeModifierMap;
import net.minecraft.entity.ai.attributes.Attributes;
import net.minecraft.entity.ai.goal.*;
import net.minecraft.entity.passive.TameableEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Inventory;
import net.minecraft.inventory.container.ChestContainer;
import net.minecraft.inventory.container.Container;
import net.minecraft.inventory.container.INamedContainerProvider;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.item.crafting.Ingredient;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.nbt.ListNBT;
import net.minecraft.pathfinding.*;
import net.minecraft.tags.FluidTags;
import net.minecraft.util.*;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.shapes.ISelectionContext;
import net.minecraft.world.DifficultyInstance;
import net.minecraft.world.IServerWorld;
import net.minecraft.world.World;
import net.minecraft.world.server.ServerWorld;
import net.minecraftforge.event.ForgeEventFactory;
import javax.annotation.Nullable;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CapybaraEntity extends TameableEntity implements INamedContainerProvider {
private static final LazyValue<Set<IItemProvider>> TEMPT_ITEMS = new LazyValue<>(() -> {
Stream<IItemProvider> stream = Stream.of(Blocks.MELON, Items.APPLE, Items.SUGAR_CANE, Items.MELON_SLICE, UAMItems.MANGROVE_FRUIT.get());
return stream.map(IItemProvider::asItem).collect(Collectors.toSet());
});
private static final DataParameter<Integer> CHESTS = EntityDataManager.defineId(CapybaraEntity.class, DataSerializers.INT);
public IInventory inventory;
public CapybaraEntity(EntityType<? extends CapybaraEntity> type, World worldIn) {
super(type, worldIn);
}
@Override
protected void registerGoals() {
this.goalSelector.addGoal(1, new PanicGoal(this, 2.0D));
this.goalSelector.addGoal(2, new SitGoal(this));
this.goalSelector.addGoal(3, new BreedGoal(this, 1.0D));
this.goalSelector.addGoal(4, new TemptGoal(this, 1.25D, Ingredient.of(TEMPT_ITEMS.get().toArray(new IItemProvider[0])), false));
this.goalSelector.addGoal(5, new FollowParentGoal(this, 1.25D));
this.goalSelector.addGoal(6, new RandomWalkingGoal(this, 1.0D));
this.goalSelector.addGoal(7, new FollowOwnerGoal(this, 1.0D, 10.0F, 2.0F, false));
this.goalSelector.addGoal(7, new LookAtGoal(this, PlayerEntity.class, 6.0F));
this.goalSelector.addGoal(8, new LookRandomlyGoal(this));
this.goalSelector.addGoal(8, new LookAtGoal(this, PlayerEntity.class, 6.0F));
this.goalSelector.addGoal(9, new LookRandomlyGoal(this));
this.goalSelector.addGoal(10, new CapybaraAnimalAttractionGoal(this));
}
@Override
protected void defineSynchedData() {
super.defineSynchedData();
entityData.define(CHESTS, 0);
}
public static AttributeModifierMap.MutableAttribute createAttributes() {
return MobEntity.createMobAttributes().add(Attributes.MAX_HEALTH, 14.0D).add(Attributes.MOVEMENT_SPEED, 0.2D);
}
@Override
protected float getWaterSlowDown() {
return 0.65f;
}
@Override
public boolean isFood(ItemStack stack) {
return stack.getItem() == Blocks.MELON.asItem();
}
protected SoundEvent getAmbientSound() {
return UAMSounds.CAPYBARA_AMBIENT.get();
}
protected SoundEvent getHurtSound(DamageSource damageSourceIn) {
return UAMSounds.CAPYBARA_HURT.get();
}
protected SoundEvent getDeathSound() {
return UAMSounds.CAPYBARA_DEATH.get();
}
protected void playStepSound(BlockPos pos, BlockState blockIn) {
this.playSound(SoundEvents.COW_STEP, 0.15F, 1.0F);
}
public boolean hurt(DamageSource p_70097_1_, float p_70097_2_) {
if (this.isInvulnerableTo(p_70097_1_)) {
return false;
} else {
Entity entity = p_70097_1_.getEntity();
this.setOrderedToSit(false);
if (entity != null && !(entity instanceof PlayerEntity) && !(entity instanceof AbstractArrowEntity)) {
p_70097_2_ = (p_70097_2_ + 1.0F) / 2.0F;
}
return super.hurt(p_70097_1_, p_70097_2_);
}
}
@Override
public ActionResultType mobInteract(PlayerEntity player, Hand hand) {
final ItemStack stack = player.getItemInHand(hand);
if (player.isShiftKeyDown()) {
if (stack.getItem() == Blocks.CHEST.asItem()) {
if (inventory == null || inventory.getContainerSize() < 27) {
inventory = new Inventory(27);
entityData.set(CHESTS, 1);
if (!player.abilities.instabuild) {
stack.shrink(1);
}
return ActionResultType.sidedSuccess(this.level.isClientSide);
}
else if (inventory.getContainerSize() < 54) {
IInventory inv = new Inventory(54);
for (int i = 0; i < 27; i++) {
inv.setItem(i, inventory.getItem(i));
}
inventory = inv;
entityData.set(CHESTS, 2);
if (!player.abilities.instabuild) {
stack.shrink(1);
}
return ActionResultType.sidedSuccess(this.level.isClientSide);
}
}
if (stack.getItem() == Items.STICK) {
this.setOrderedToSit(!this.isOrderedToSit());
}
else {
player.openMenu(this);
return ActionResultType.SUCCESS;
}
}
else if (TEMPT_ITEMS.get().contains(stack.getItem()) && !isTame()) {
if (this.random.nextInt(3) == 0 && !ForgeEventFactory.onAnimalTame(this, player)) {
this.tame(player);
this.navigation.stop();
this.setTarget(null);
this.setOrderedToSit(true);
this.level.broadcastEntityEvent(this, (byte) 7);
}
if (!player.abilities.instabuild) {
stack.shrink(1);
}
else {
this.level.broadcastEntityEvent(this, (byte) 6);
}
return ActionResultType.sidedSuccess(this.level.isClientSide);
}
else if (!this.isVehicle() && !player.isSecondaryUseActive() && !this.isBaby() && !isInSittingPose()) {
boolean flag = this.isFood(player.getItemInHand(hand));
if (!flag && !this.isVehicle() && !player.isSecondaryUseActive()) {
if (!this.level.isClientSide) {
player.startRiding(this);
}
return ActionResultType.sidedSuccess(this.level.isClientSide);
}
}
else if (!this.getPassengers().isEmpty()) {
ejectPassengers();
}
return super.mobInteract(player, hand);
}
@Override
protected float getSoundVolume() {
return 0.4F;
}
@Override
public CapybaraEntity getBreedOffspring(ServerWorld p_241840_1_, AgeableEntity p_241840_2_) {
return UAMEntities.CAPYBARA.get().create(p_241840_1_);
}
@Override
protected float getStandingEyeHeight(Pose poseIn, EntitySize sizeIn) {
return this.isBaby() ? 0.5F : 0.9F;
}
@Override
public ItemStack getPickedResult(RayTraceResult target) {
return new ItemStack(UAMItems.CAPYBARA_SPAWN_EGG.get());
}
@Override
public void tick() {
super.tick();
this.floatStrider();
this.checkInsideBlocks();
if (getPassengers().isEmpty()) {
for (Entity e : level.getEntities(this, getBoundingBox().inflate(0.5))) {
if (e instanceof MobEntity && e.getBbWidth() <= 0.75f && e.getBbHeight() <= 0.75f && !this.isBaby() && ((MobEntity) e).getMobType() != CreatureAttribute.WATER && !isInWater()) {
e.startRiding(this);
}
}
}
else if (!getPassengers().isEmpty() && isInWater()) {
ejectPassengers();
}
}
@Override
protected PathNavigator createNavigation(World worldIn) {
return new CapybaraEntity.WaterPathNavigator(this, worldIn);
}
@Nullable
public Entity getControllingPassenger() {
return this.getPassengers().isEmpty() ? null : this.getPassengers().get(0);
}
@Override
public boolean canBeControlledByRider() {
return false;
}
@Override
public ILivingEntityData finalizeSpawn(IServerWorld worldIn, DifficultyInstance difficultyIn, SpawnReason reason, @Nullable ILivingEntityData spawnData, @Nullable CompoundNBT dataTag) {
if (spawnData == null) {
spawnData = new AgeableData(1);
}
return super.finalizeSpawn(worldIn, difficultyIn, reason, spawnData, dataTag);
}
private void floatStrider() {
if (this.isInWater()) {
ISelectionContext iselectioncontext = ISelectionContext.of(this);
if (iselectioncontext.isAbove(FlowingFluidBlock.STABLE_SHAPE, this.blockPosition(), true) && !this.level.getFluidState(this.blockPosition().above()).is(FluidTags.WATER)) {
this.onGround = true;
} else {
this.setDeltaMovement(this.getDeltaMovement().scale(0.5D).add(0.0D, 0.05D, 0.0D));
}
}
}
@Override
public void addAdditionalSaveData(CompoundNBT compound) {
super.addAdditionalSaveData(compound);
if (inventory != null) {
final ListNBT inv = new ListNBT();
for (int i = 0; i < this.inventory.getContainerSize(); i++) {
inv.add(inventory.getItem(i).save(new CompoundNBT()));
}
compound.put("Inventory", inv);
}
}
@Override
public void readAdditionalSaveData(CompoundNBT compound) {
super.readAdditionalSaveData(compound);
if (compound.contains("Inventory")) {
final ListNBT inv = compound.getList("Inventory", 10);
inventory = new Inventory(inv.size());
for (int i = 0; i < inv.size(); i++) {
inventory.setItem(i, ItemStack.of(inv.getCompound(i)));
}
entityData.set(CHESTS, inv.size() > 27 ? 2 : 1);
}
}
@Nullable
@Override
public Container createMenu(int p_createMenu_1_, PlayerInventory p_createMenu_2_, PlayerEntity p_createMenu_3_) {
if (inventory == null) {
return null;
}
return inventory.getContainerSize() < 54 ? ChestContainer.threeRows(p_createMenu_1_, p_createMenu_2_, inventory) : ChestContainer.sixRows(p_createMenu_1_, p_createMenu_2_, inventory);
}
public int getChestCount() {
return entityData.get(CHESTS);
}
static class WaterPathNavigator extends GroundPathNavigator {
WaterPathNavigator(CapybaraEntity p_i231565_1_, World p_i231565_2_) {
super(p_i231565_1_, p_i231565_2_);
}
protected PathFinder createPathFinder(int p_179679_1_) {
this.nodeEvaluator = new WalkNodeProcessor();
return new PathFinder(this.nodeEvaluator, p_179679_1_);
}
protected boolean hasValidPathType(PathNodeType p_230287_1_) {
return p_230287_1_ == PathNodeType.WATER || super.hasValidPathType(p_230287_1_);
}
public boolean isStableDestination(BlockPos pos) {
return this.level.getBlockState(pos).is(Blocks.WATER) || super.isStableDestination(pos);
}
}
}
| 12,669 | 0.639198 | 0.619544 | 319 | 38.714733 | 33.753349 | 193 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.714734 | false | false | 6 |
f45e8718b5556aeeb292e88480265c30ecca247e | 32,495,722,580,005 | 42cb2e20cf39a4581da06f4ac2b6d656ad9de781 | /src/main/java/laba/data/Test.java | b7fa02bf634ed4ef8c3a89bbd2183a3a4218f8ed | [] | no_license | powerex/demo | https://github.com/powerex/demo | 12068f35fad249ef94823311661959013fbe29f8 | 29494def3f60cd35a85f74881db5424fb5f523cb | refs/heads/master | 2022-11-28T15:50:16.806000 | 2019-06-18T11:16:39 | 2019-06-18T11:16:39 | 192,524,985 | 0 | 0 | null | false | 2022-11-24T06:23:00 | 2019-06-18T11:16:35 | 2019-06-18T11:16:46 | 2022-11-24T06:22:57 | 299 | 0 | 0 | 1 | Java | false | false | package laba.data;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Table(name = "orders")
public class Test implements Serializable {
@Id
@GeneratedValue
private Long id;
@Column(name = "user_id")
private Long userId;
@Column(name = "subject_id")
private Long subjectId;
@Column(name = "student_id")
private Long studentId;
@Column(name = "mark")
private Long mark;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Long getSubjectId() {
return subjectId;
}
public void setSubjectId(Long subjectId) {
this.subjectId = subjectId;
}
public Long getStudentId() {
return studentId;
}
public void setStudentId(Long studentId) {
this.studentId = studentId;
}
public Long getMark() {
return mark;
}
public void setMark(Long mark) {
this.mark = mark;
}
public static final String DB_NAME = "tests";
public static class Columns {
public static final String ID = "id";
public static final String USER_ID = "user_id";
public static final String SUBJECT_ID = "subject_id";
public static final String STUDENT_ID = "student_id";
public static final String MARK = "mark";
}
}
| UTF-8 | Java | 1,491 | java | Test.java | Java | [] | null | [] | package laba.data;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Table(name = "orders")
public class Test implements Serializable {
@Id
@GeneratedValue
private Long id;
@Column(name = "user_id")
private Long userId;
@Column(name = "subject_id")
private Long subjectId;
@Column(name = "student_id")
private Long studentId;
@Column(name = "mark")
private Long mark;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Long getSubjectId() {
return subjectId;
}
public void setSubjectId(Long subjectId) {
this.subjectId = subjectId;
}
public Long getStudentId() {
return studentId;
}
public void setStudentId(Long studentId) {
this.studentId = studentId;
}
public Long getMark() {
return mark;
}
public void setMark(Long mark) {
this.mark = mark;
}
public static final String DB_NAME = "tests";
public static class Columns {
public static final String ID = "id";
public static final String USER_ID = "user_id";
public static final String SUBJECT_ID = "subject_id";
public static final String STUDENT_ID = "student_id";
public static final String MARK = "mark";
}
}
| 1,491 | 0.604292 | 0.604292 | 70 | 20.285715 | 16.995918 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.342857 | false | false | 6 |
9f6cee663617eac44aa87f7e697b61312d6f57cd | 18,923,625,918,876 | e47064bd09361c0ff60b890173846d11e6fd63fd | /src/main/java/io.github.moulberry.rpg/commands/CommandGotoInstanceWorld.java | 45ce57a997fd8bda145ecc6dab4a28f0c4dd7b94 | [] | no_license | Moulberry/SpigotPlugin | https://github.com/Moulberry/SpigotPlugin | 6e07a5aa7b027c705a67ec34b777f5544864ec65 | 9fb4e1f99c1067c9a8588b7eec7e88834c19104d | refs/heads/master | 2022-11-17T15:19:01.958000 | 2020-07-05T21:42:14 | 2020-07-05T21:42:14 | 277,384,046 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package io.github.moulberry.rpg.commands;
import io.github.moulberry.rpg.world.WorldManager;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class CommandGotoInstanceWorld implements CommandExecutor {
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if(args.length != 1) {
return false;
}
try {
if(sender instanceof Player) {
Player player = (Player) sender;
World instance = WorldManager.getInstance().createInstanceWorldFromTemplate(args[0]);
player.teleport(instance.getSpawnLocation());
return true;
}
} catch(Exception e) {
e.printStackTrace();
}
return false;
}
}
| UTF-8 | Java | 928 | java | CommandGotoInstanceWorld.java | Java | [] | null | [] | package io.github.moulberry.rpg.commands;
import io.github.moulberry.rpg.world.WorldManager;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class CommandGotoInstanceWorld implements CommandExecutor {
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if(args.length != 1) {
return false;
}
try {
if(sender instanceof Player) {
Player player = (Player) sender;
World instance = WorldManager.getInstance().createInstanceWorldFromTemplate(args[0]);
player.teleport(instance.getSpawnLocation());
return true;
}
} catch(Exception e) {
e.printStackTrace();
}
return false;
}
}
| 928 | 0.645474 | 0.643319 | 33 | 27.121212 | 26.501867 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.515152 | false | false | 6 |
de7a218440c3d960dfe81c24cea88dd1fbbea203 | 9,199,819,951,610 | 0a5572ddcdf5f1dd53451e20c1061baecfa2c3d7 | /partten/src/main/java/com/chenrui/partten/delegate/mvc/controller/MemberAction.java | 9444b9484bdfc1aa6bcc2567bd912dc5a31cd1d2 | [] | no_license | lovechenrui/gupaotest | https://github.com/lovechenrui/gupaotest | 52387594a1ca37e37553f2f2bd63ad92da160ee7 | 4c3e1cc5fbc68fa96180a3a2ab7dcb55b4dad90b | refs/heads/master | 2022-12-20T19:32:54.319000 | 2020-03-04T04:19:56 | 2020-03-04T04:19:56 | 162,518,952 | 0 | 0 | null | false | 2022-12-16T05:29:19 | 2018-12-20T03:00:48 | 2020-03-04T04:20:33 | 2022-12-16T05:29:16 | 160 | 0 | 0 | 5 | Java | false | false | package com.chenrui.partten.delegate.mvc.controller;
import org.springframework.web.bind.annotation.RequestMapping;
public class MemberAction {
public void getMemberByid(String memberid){
}
}
| UTF-8 | Java | 202 | java | MemberAction.java | Java | [] | null | [] | package com.chenrui.partten.delegate.mvc.controller;
import org.springframework.web.bind.annotation.RequestMapping;
public class MemberAction {
public void getMemberByid(String memberid){
}
}
| 202 | 0.792079 | 0.792079 | 8 | 24.25 | 24.514027 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 6 |
db8edb97650007da82a7a95339988c7f9b10e85d | 23,046,794,523,874 | c97e347306776f8369040a331caf269d9e52cb64 | /src/main/java/com/lazar/CMSServer/model/CommentPK.java | df0288454c49a01773511e0e147fd351d7d17a02 | [] | no_license | Lazar971/cms-spring | https://github.com/Lazar971/cms-spring | ca88f87ef8f9c98b2bebc924e9841f4914a42d0c | 2c2c94fbf6ea1b922280cc5e07a6305b90c879c3 | refs/heads/master | 2022-12-13T13:57:48.014000 | 2020-09-06T17:01:14 | 2020-09-06T17:01:14 | 292,794,852 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.lazar.CMSServer.model;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
/**
*
* @author Lazar Milosavljević
*/
@Embeddable
public class CommentPK implements Serializable {
@Basic(optional = false)
@Column(name = "comment_id")
private int commentId;
@Basic(optional = false)
@Column(name = "post")
private int post;
public CommentPK() {
}
public CommentPK(int commentId, int post) {
this.commentId = commentId;
this.post = post;
}
public int getCommentId() {
return commentId;
}
public void setCommentId(int commentId) {
this.commentId = commentId;
}
public int getPost() {
return post;
}
public void setPost(int post) {
this.post = post;
}
@Override
public int hashCode() {
int hash = 0;
hash += (int) commentId;
hash += (int) post;
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof CommentPK)) {
return false;
}
CommentPK other = (CommentPK) object;
if (this.commentId != other.commentId) {
return false;
}
if (this.post != other.post) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.lazar.CMSServer.model.CommentPK[ commentId=" + commentId + ", post=" + post + " ]";
}
}
| UTF-8 | Java | 1,912 | java | CommentPK.java | Java | [
{
"context": "vax.persistence.GenerationType;\n\n/**\n *\n * @author Lazar Milosavljević\n */\n@Embeddable\npublic class CommentPK implements",
"end": 472,
"score": 0.9998467564582825,
"start": 453,
"tag": "NAME",
"value": "Lazar Milosavljević"
}
] | null | [] | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.lazar.CMSServer.model;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
/**
*
* @author <NAME>
*/
@Embeddable
public class CommentPK implements Serializable {
@Basic(optional = false)
@Column(name = "comment_id")
private int commentId;
@Basic(optional = false)
@Column(name = "post")
private int post;
public CommentPK() {
}
public CommentPK(int commentId, int post) {
this.commentId = commentId;
this.post = post;
}
public int getCommentId() {
return commentId;
}
public void setCommentId(int commentId) {
this.commentId = commentId;
}
public int getPost() {
return post;
}
public void setPost(int post) {
this.post = post;
}
@Override
public int hashCode() {
int hash = 0;
hash += (int) commentId;
hash += (int) post;
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof CommentPK)) {
return false;
}
CommentPK other = (CommentPK) object;
if (this.commentId != other.commentId) {
return false;
}
if (this.post != other.post) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.lazar.CMSServer.model.CommentPK[ commentId=" + commentId + ", post=" + post + " ]";
}
}
| 1,898 | 0.611722 | 0.611198 | 83 | 22.024096 | 20.400789 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.361446 | false | false | 6 |
34b1cec63d5c3c2dd633fccb10a836ad69e315ec | 2,370,821,957,865 | e920de955e80119e20d9f32deaf9d9df8e736cae | /src/main/java/util/Decode.java | 0918f237452111ed4cdd6e41bca2bbcf1b4264ab | [
"MIT"
] | permissive | kapoorlabs/kamla | https://github.com/kapoorlabs/kamla | 2e695ee63dc6d962ac4be4462b6f4faa619705fd | 353b7e35c6e93a9519257ba27f61489e65557c6d | refs/heads/master | 2022-12-27T03:00:36.126000 | 2019-12-31T05:28:10 | 2019-12-31T05:28:10 | 230,953,077 | 0 | 0 | null | false | 2020-10-13T18:32:27 | 2019-12-30T17:18:11 | 2020-03-16T18:48:46 | 2020-10-13T18:32:26 | 15 | 0 | 0 | 1 | Java | false | false | package util;
import java.lang.reflect.InvocationTargetException;
import java.util.LinkedList;
import java.util.List;
import constants.Delimiters;
import domain.Token;
import domain.URLSafeChar;
import exception.IllegalTokenFormatException;
import exception.UnsupportedVersionException;
public class Decode {
public static Token[] decodeToken(String token) {
Character versionInUse = token.charAt(0);
Token[] tokens = null;
// create instances of version classes
tokens = VersionManager.getTokensForVersion(versionInUse);
if (tokens == null) {
throw new UnsupportedVersionException();
}
token = token.substring(1);
String[] splittedToken = token.split(Character.toString(Delimiters.TOKEN_DELIMITER));
for (int i = 0; i < splittedToken.length && i < tokens.length; i++) {
if (splittedToken[i].length() == 0) {
continue;
}
String[] layerToken = splittedToken[i].split(Character.toString(Delimiters.PAIR_DELIMITER));
for (int j = 0; j < layerToken.length; j++) {
if (layerToken[j] == null || layerToken[j].isEmpty()) {
continue;
}
int fieldIndex = URLSafeChar.getIndex(layerToken[j].charAt(0));
String value = layerToken[j].substring(1);
// If the field is a list then delimited fields are processed separately.
if (tokens[i].fetchFields().get(fieldIndex).getType() == List.class) {
String[] listValues = value.split(Character.toString(Delimiters.LIST_DELIMITER));
List<String> tokenValue = new LinkedList<String>();
for (String listValue : listValues) {
if (tokens[i].getPossibleValuesDecodingMap() != null
&& tokens[i].getPossibleValuesDecodingMap()
.get(tokens[i].fetchFields().get(fieldIndex).getName()) != null
&& tokens[i].getPossibleValuesDecodingMap()
.get(tokens[i].fetchFields().get(fieldIndex).getName())
.get(listValue) != null) {
tokenValue.add(tokens[i].getPossibleValuesDecodingMap()
.get(tokens[i].fetchFields().get(fieldIndex).getName()).get(listValue));
} else {
tokenValue.add(listValue);
}
}
try {
tokens[i].fetchSetters().get(fieldIndex).invoke(tokens[i], tokenValue);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
throw new IllegalTokenFormatException();
}
// If the field is not a list.
} else {
if (tokens[i].getPossibleValuesDecodingMap() != null
&& tokens[i].getPossibleValuesDecodingMap()
.get(tokens[i].fetchFields().get(fieldIndex).getName()) != null
&& tokens[i].getPossibleValuesDecodingMap()
.get(tokens[i].fetchFields().get(fieldIndex).getName()).get(value) != null) {
try {
tokens[i].fetchSetters().get(fieldIndex).invoke(tokens[i],
tokens[i].getPossibleValuesDecodingMap()
.get(tokens[i].fetchFields().get(fieldIndex).getName()).get(value));
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
throw new IllegalTokenFormatException();
}
} else {
try {
tokens[i].fetchSetters().get(fieldIndex).invoke(tokens[i], value);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
throw new IllegalTokenFormatException();
}
}
}
}
}
return tokens;
}
}
| UTF-8 | Java | 3,466 | java | Decode.java | Java | [] | null | [] | package util;
import java.lang.reflect.InvocationTargetException;
import java.util.LinkedList;
import java.util.List;
import constants.Delimiters;
import domain.Token;
import domain.URLSafeChar;
import exception.IllegalTokenFormatException;
import exception.UnsupportedVersionException;
public class Decode {
public static Token[] decodeToken(String token) {
Character versionInUse = token.charAt(0);
Token[] tokens = null;
// create instances of version classes
tokens = VersionManager.getTokensForVersion(versionInUse);
if (tokens == null) {
throw new UnsupportedVersionException();
}
token = token.substring(1);
String[] splittedToken = token.split(Character.toString(Delimiters.TOKEN_DELIMITER));
for (int i = 0; i < splittedToken.length && i < tokens.length; i++) {
if (splittedToken[i].length() == 0) {
continue;
}
String[] layerToken = splittedToken[i].split(Character.toString(Delimiters.PAIR_DELIMITER));
for (int j = 0; j < layerToken.length; j++) {
if (layerToken[j] == null || layerToken[j].isEmpty()) {
continue;
}
int fieldIndex = URLSafeChar.getIndex(layerToken[j].charAt(0));
String value = layerToken[j].substring(1);
// If the field is a list then delimited fields are processed separately.
if (tokens[i].fetchFields().get(fieldIndex).getType() == List.class) {
String[] listValues = value.split(Character.toString(Delimiters.LIST_DELIMITER));
List<String> tokenValue = new LinkedList<String>();
for (String listValue : listValues) {
if (tokens[i].getPossibleValuesDecodingMap() != null
&& tokens[i].getPossibleValuesDecodingMap()
.get(tokens[i].fetchFields().get(fieldIndex).getName()) != null
&& tokens[i].getPossibleValuesDecodingMap()
.get(tokens[i].fetchFields().get(fieldIndex).getName())
.get(listValue) != null) {
tokenValue.add(tokens[i].getPossibleValuesDecodingMap()
.get(tokens[i].fetchFields().get(fieldIndex).getName()).get(listValue));
} else {
tokenValue.add(listValue);
}
}
try {
tokens[i].fetchSetters().get(fieldIndex).invoke(tokens[i], tokenValue);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
throw new IllegalTokenFormatException();
}
// If the field is not a list.
} else {
if (tokens[i].getPossibleValuesDecodingMap() != null
&& tokens[i].getPossibleValuesDecodingMap()
.get(tokens[i].fetchFields().get(fieldIndex).getName()) != null
&& tokens[i].getPossibleValuesDecodingMap()
.get(tokens[i].fetchFields().get(fieldIndex).getName()).get(value) != null) {
try {
tokens[i].fetchSetters().get(fieldIndex).invoke(tokens[i],
tokens[i].getPossibleValuesDecodingMap()
.get(tokens[i].fetchFields().get(fieldIndex).getName()).get(value));
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
throw new IllegalTokenFormatException();
}
} else {
try {
tokens[i].fetchSetters().get(fieldIndex).invoke(tokens[i], value);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
throw new IllegalTokenFormatException();
}
}
}
}
}
return tokens;
}
}
| 3,466 | 0.671091 | 0.669071 | 115 | 29.13913 | 29.61841 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.66087 | false | false | 6 |
fff02e19f6bf70867d2e1fbad9d637a43a59f295 | 30,322,469,128,740 | b7ec8beecdb40e150a869c4db2c5a42489829d45 | /Spring06-JavaCode-Configuration/src/main/java/com/myApp/services/OfficeHours.java | 5accc77b89b226ad2278b1f59296a23a4aacf994 | [] | no_license | katyalisitsa/framework-spring | https://github.com/katyalisitsa/framework-spring | 968c86eb638746e5acd1b328ac8c006e739733f0 | d86990cffd6fdb6b50fd364e7b57d943ca46704d | refs/heads/main | 2023-03-14T09:12:58.627000 | 2021-03-06T18:52:19 | 2021-03-06T18:52:19 | 305,009,731 | 1 | 0 | null | false | 2021-03-06T18:52:20 | 2020-10-18T02:48:24 | 2021-03-06T18:29:59 | 2021-03-06T18:52:20 | 3,764 | 1 | 0 | 0 | Java | false | false | package com.myApp.services;
import com.myApp.interfaces.ExtraSessions;
import lombok.ToString;
@ToString
public class OfficeHours implements ExtraSessions {
@Override
public int getHours() {
return 7;
}
}
| UTF-8 | Java | 227 | java | OfficeHours.java | Java | [] | null | [] | package com.myApp.services;
import com.myApp.interfaces.ExtraSessions;
import lombok.ToString;
@ToString
public class OfficeHours implements ExtraSessions {
@Override
public int getHours() {
return 7;
}
}
| 227 | 0.726872 | 0.722467 | 12 | 17.916666 | 15.981544 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 6 |
14385363c58a7a15f9dc061ea274e02de212aa1a | 33,105,607,932,358 | 67d9aef7efaf0dfd133660b98977b85c26571728 | /src/timetable/student/AddClass.java | cc0332225fde4023954eda312e4752078627ec3b | [] | no_license | matthiasknolli/student-timetable | https://github.com/matthiasknolli/student-timetable | 71ab8a1f2b1a86d2e4c57d5e9edebb53616d8d3d | 5ee322d25fd537fcb7981db9314d8d9a03e34f28 | refs/heads/master | 2021-01-10T07:25:38.216000 | 2011-03-26T17:20:03 | 2011-03-26T17:20:03 | 45,027,611 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package timetable.student;
import static timetable.student.Constants.DAY;
import static timetable.student.Constants.LECTURER;
import static timetable.student.Constants.MODULE;
import static timetable.student.Constants.ROOM;
import static timetable.student.Constants.TABLE_NAME;
import static timetable.student.Constants.TIMEEND;
import static timetable.student.Constants.TIMESTART;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
public class AddClass extends Activity {
private TimeTableData events;
private EditText module;
private int day;
private Spinner spinner;
private EditText room;
private EditText lecturer;
private Button startPicker;
private Button endPicker;
private Button cancelBtn;
private int startHour;
private int startMin;
private int endHour;
private int endMin;
static final int STIME_DIALOG_ID = 0;
static final int ETIME_DIALOG_ID = 1;
private boolean update = false;
private String _id = "-1";
String[] temp = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add);
spinner = (Spinner) findViewById(R.id.spinner);
Button b = (Button)findViewById(R.id.saveBtn);
module = (EditText)findViewById(R.id.module_entry);
room = (EditText)findViewById(R.id.room_entry);
startPicker = (Button)findViewById(R.id.pickStartTime);
endPicker = (Button)findViewById(R.id.pickEndTime);
cancelBtn = (Button)findViewById(R.id.closeBtn);
lecturer = (EditText)findViewById(R.id.lecturer_entry);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.day_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
Intent i = getIntent();
if(i.hasExtra("TDATA"))
{
temp = i.getStringArrayExtra("TDATA");
String day = temp[0];
spinner.setSelection(getDayInt(day));
module.setText(temp[1]);
lecturer.setText(temp[2]);
room.setText(temp[3]);
startPicker.setText(temp[4]);
endPicker.setText(temp[5]);
update = true;
_id = temp[6];
}
if (i.hasExtra("GROUP_NUMBER"))
{
int num = i.getIntExtra("GROUP_NUMBER",0);
spinner.setSelection(num);
}
startPicker.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDialog(STIME_DIALOG_ID);
}
});
endPicker.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDialog(ETIME_DIALOG_ID);
}
});
// get the current time
final Calendar c = Calendar.getInstance();
startHour = c.get(Calendar.HOUR_OF_DAY);
startMin = c.get(Calendar.MINUTE);
cancelBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(module.getText().toString().equals(""))
{
makeAlert("Module");
}
else if(lecturer.getText().toString().equals(""))
{
makeAlert("Lecturer");
}
else if(room.getText().toString().equals(""))
{
makeAlert("Room");
}
else if(startPicker.getText().toString().equals("Start Time"))
{
makeAlert("Start Time");
}else if(endPicker.getText().toString().equals("End Time"))
{
makeAlert("End Time");
}
else
{
events = new TimeTableData(v.getContext());
try {
day = spinner.getSelectedItemPosition()+1;
if(!update)
addEvent(day, module.getText().toString(), lecturer.getText().toString(), room.getText().toString(), startPicker.getText().toString(), endPicker.getText().toString());
else
updateEvent(_id,day, module.getText().toString(), lecturer.getText().toString(), room.getText().toString(), startPicker.getText().toString(), endPicker.getText().toString());
} finally {
events.close();
}
setResult(RESULT_OK);
finish();
}
}
});
}
private void makeAlert(String s)
{
AlertDialog.Builder alertbox = new AlertDialog.Builder(AddClass.this);
alertbox.setTitle("Error");
alertbox.setMessage("Please Enter a Value for "+s);
alertbox.setNeutralButton("Close", new DialogInterface.OnClickListener() {
// Click listener on the neutral button of alert box
public void onClick(DialogInterface arg0, int arg1) {
}
});
alertbox.show();
}
// the callback received when the user "sets" the time in the dialog
private TimePickerDialog.OnTimeSetListener sTimeSetListener =
new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
startHour = hourOfDay;
startMin = minute;
updatedisplay("start");
}
};
private TimePickerDialog.OnTimeSetListener eTimeSetListener =
new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
endHour = hourOfDay;
endMin = minute;
updatedisplay("end");
}
};
private void updatedisplay(String time)
{
if(time == "start")
{
startPicker.setText(new StringBuilder()
.append(pad(startHour))
.append(":")
.append(pad(startMin)));
}
else
endPicker.setText(new StringBuilder()
.append(pad(endHour))
.append(":")
.append(pad(endMin)));
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case STIME_DIALOG_ID:
return new TimePickerDialog(this,
sTimeSetListener, startHour, startMin, false);
case ETIME_DIALOG_ID:
return new TimePickerDialog(this,
eTimeSetListener, endHour, endMin, false);
}
return null;
}
private static String pad(int c) {
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
private void addEvent(int day,String module,String lecturer,String Room,String startTime,String endTime) {
// Insert a new record into the Events data source.
// You would do something similar for delete and update.
SQLiteDatabase db = events.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DAY, day);
values.put(MODULE, module);
values.put(LECTURER, lecturer);
values.put(ROOM,Room);
values.put(TIMESTART,startTime);
values.put(TIMEEND, endTime);
db.insertOrThrow(TABLE_NAME, null, values);
}
private void updateEvent(String id,int day,String module,String lecturer,String Room,String startTime,String endTime) {
SQLiteDatabase db = events.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DAY, day);
values.put(MODULE, module);
values.put(LECTURER, lecturer);
values.put(ROOM,Room);
values.put(TIMESTART,startTime);
values.put(TIMEEND, endTime);
db.update(TABLE_NAME, values, "_ID=?", new String[] {id});
}
private int getDayInt(String day)
{
String[] d = new String[] {"Monday","Tuesday","Wednesday","Thursday","Friday"};
for(int i = 0; i < d.length;++i)
{
if(day.equals(d[i]))
{
return i;
}
}
return 0;
}
}
| UTF-8 | Java | 8,694 | java | AddClass.java | Java | [] | null | [] | package timetable.student;
import static timetable.student.Constants.DAY;
import static timetable.student.Constants.LECTURER;
import static timetable.student.Constants.MODULE;
import static timetable.student.Constants.ROOM;
import static timetable.student.Constants.TABLE_NAME;
import static timetable.student.Constants.TIMEEND;
import static timetable.student.Constants.TIMESTART;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
public class AddClass extends Activity {
private TimeTableData events;
private EditText module;
private int day;
private Spinner spinner;
private EditText room;
private EditText lecturer;
private Button startPicker;
private Button endPicker;
private Button cancelBtn;
private int startHour;
private int startMin;
private int endHour;
private int endMin;
static final int STIME_DIALOG_ID = 0;
static final int ETIME_DIALOG_ID = 1;
private boolean update = false;
private String _id = "-1";
String[] temp = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add);
spinner = (Spinner) findViewById(R.id.spinner);
Button b = (Button)findViewById(R.id.saveBtn);
module = (EditText)findViewById(R.id.module_entry);
room = (EditText)findViewById(R.id.room_entry);
startPicker = (Button)findViewById(R.id.pickStartTime);
endPicker = (Button)findViewById(R.id.pickEndTime);
cancelBtn = (Button)findViewById(R.id.closeBtn);
lecturer = (EditText)findViewById(R.id.lecturer_entry);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.day_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
Intent i = getIntent();
if(i.hasExtra("TDATA"))
{
temp = i.getStringArrayExtra("TDATA");
String day = temp[0];
spinner.setSelection(getDayInt(day));
module.setText(temp[1]);
lecturer.setText(temp[2]);
room.setText(temp[3]);
startPicker.setText(temp[4]);
endPicker.setText(temp[5]);
update = true;
_id = temp[6];
}
if (i.hasExtra("GROUP_NUMBER"))
{
int num = i.getIntExtra("GROUP_NUMBER",0);
spinner.setSelection(num);
}
startPicker.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDialog(STIME_DIALOG_ID);
}
});
endPicker.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDialog(ETIME_DIALOG_ID);
}
});
// get the current time
final Calendar c = Calendar.getInstance();
startHour = c.get(Calendar.HOUR_OF_DAY);
startMin = c.get(Calendar.MINUTE);
cancelBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(module.getText().toString().equals(""))
{
makeAlert("Module");
}
else if(lecturer.getText().toString().equals(""))
{
makeAlert("Lecturer");
}
else if(room.getText().toString().equals(""))
{
makeAlert("Room");
}
else if(startPicker.getText().toString().equals("Start Time"))
{
makeAlert("Start Time");
}else if(endPicker.getText().toString().equals("End Time"))
{
makeAlert("End Time");
}
else
{
events = new TimeTableData(v.getContext());
try {
day = spinner.getSelectedItemPosition()+1;
if(!update)
addEvent(day, module.getText().toString(), lecturer.getText().toString(), room.getText().toString(), startPicker.getText().toString(), endPicker.getText().toString());
else
updateEvent(_id,day, module.getText().toString(), lecturer.getText().toString(), room.getText().toString(), startPicker.getText().toString(), endPicker.getText().toString());
} finally {
events.close();
}
setResult(RESULT_OK);
finish();
}
}
});
}
private void makeAlert(String s)
{
AlertDialog.Builder alertbox = new AlertDialog.Builder(AddClass.this);
alertbox.setTitle("Error");
alertbox.setMessage("Please Enter a Value for "+s);
alertbox.setNeutralButton("Close", new DialogInterface.OnClickListener() {
// Click listener on the neutral button of alert box
public void onClick(DialogInterface arg0, int arg1) {
}
});
alertbox.show();
}
// the callback received when the user "sets" the time in the dialog
private TimePickerDialog.OnTimeSetListener sTimeSetListener =
new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
startHour = hourOfDay;
startMin = minute;
updatedisplay("start");
}
};
private TimePickerDialog.OnTimeSetListener eTimeSetListener =
new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
endHour = hourOfDay;
endMin = minute;
updatedisplay("end");
}
};
private void updatedisplay(String time)
{
if(time == "start")
{
startPicker.setText(new StringBuilder()
.append(pad(startHour))
.append(":")
.append(pad(startMin)));
}
else
endPicker.setText(new StringBuilder()
.append(pad(endHour))
.append(":")
.append(pad(endMin)));
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case STIME_DIALOG_ID:
return new TimePickerDialog(this,
sTimeSetListener, startHour, startMin, false);
case ETIME_DIALOG_ID:
return new TimePickerDialog(this,
eTimeSetListener, endHour, endMin, false);
}
return null;
}
private static String pad(int c) {
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
private void addEvent(int day,String module,String lecturer,String Room,String startTime,String endTime) {
// Insert a new record into the Events data source.
// You would do something similar for delete and update.
SQLiteDatabase db = events.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DAY, day);
values.put(MODULE, module);
values.put(LECTURER, lecturer);
values.put(ROOM,Room);
values.put(TIMESTART,startTime);
values.put(TIMEEND, endTime);
db.insertOrThrow(TABLE_NAME, null, values);
}
private void updateEvent(String id,int day,String module,String lecturer,String Room,String startTime,String endTime) {
SQLiteDatabase db = events.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DAY, day);
values.put(MODULE, module);
values.put(LECTURER, lecturer);
values.put(ROOM,Room);
values.put(TIMESTART,startTime);
values.put(TIMEEND, endTime);
db.update(TABLE_NAME, values, "_ID=?", new String[] {id});
}
private int getDayInt(String day)
{
String[] d = new String[] {"Monday","Tuesday","Wednesday","Thursday","Friday"};
for(int i = 0; i < d.length;++i)
{
if(day.equals(d[i]))
{
return i;
}
}
return 0;
}
}
| 8,694 | 0.626639 | 0.624454 | 281 | 28.939503 | 25.218756 | 186 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.177936 | false | false | 6 |
887be4e0298e6ac779b6cd3ab4c49d488320efdd | 2,276,332,669,487 | 0eff3426edc96a80e2d89e2b23c22d47b59f224f | /LauncherWebApp/src/main/java/it/ciavotta/Launcher/domain/Node.java | 80a8fe400690a4db74f49946a181db7570bb3126 | [] | no_license | miciav/Launcher | https://github.com/miciav/Launcher | 2da8f545be32bc4e981357721d20cc2ac7df4406 | f6d67a2382eea8c71709097ee529689c925720a9 | refs/heads/master | 2020-06-01T09:14:33.815000 | 2013-12-27T21:49:17 | 2013-12-27T21:49:17 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package it.ciavotta.Launcher.domain;
import it.ciavotta.Launcher.messages.NodeInformation;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Id;
import javax.persistence.PrePersist;
import org.hibernate.annotations.NaturalId;
/*
* This class represent the node, each node is a computing unity in a virtual machine
* */
@Entity(name = "Node")
public class Node {
//@Column(nullable = false)
private String nodeId;
@Id
// @GeneratedValue
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@NaturalId
private String nodeIP;
@NaturalId
private String port;
private String operatingSystem;
private String architecture;
private String osVersion;
public static Node fromNodeInformation(NodeInformation nodeInfo){
Node node = new Node();
node.setNodeIP(nodeInfo.getIpAddress());
node.setOperatingSystem(nodeInfo.getOs());
node.setArchitecture(nodeInfo.getOsArch());
node.setPort(nodeInfo.getPort());
node.setId(nodeInfo.getId());
node.setOsVersion(nodeInfo.getOsVersion());
node.setNodeId(nodeInfo.getNodeID());
if (nodeInfo.getState().equals("OK")) {
node.setState(NodeState.OK);
}
else if (nodeInfo.getState().equals("ERROR")) {
node.setState(NodeState.ERROR);
}
return node;
}
@PrePersist
private void createId(){
this.id = this.nodeIP+this.port;
}
@Enumerated(EnumType.STRING)
private NodeState state;
/**
* @return the nodeId
*/
public String getNodeId() {
return nodeId;
}
public NodeState getState() {
return state;
}
public void setState(NodeState state) {
this.state = state;
}
/**
* @param nodeId the nodeId to set
*/
public void setNodeId(String nodeId) {
this.nodeId = nodeId;
}
/**
* @return the nodeIP
*/
public String getNodeIP() {
return nodeIP;
}
/**
* @param nodeIP the nodeIP to set
*/
public void setNodeIP(String nodeIP) {
this.nodeIP = nodeIP;
}
/**
* @return the port
*/
public String getPort() {
return port;
}
/**
* @param port the port to set
*/
public void setPort(String port) {
this.port = port;
}
/**
* @return the operatingSystem
*/
public String getOperatingSystem() {
return operatingSystem;
}
/**
* @param operatingSystem the operatingSystem to set
*/
public void setOperatingSystem(String operatingSystem) {
this.operatingSystem = operatingSystem;
}
/**
* @return the architecture
*/
public String getArchitecture() {
return architecture;
}
/**
* @param architecture the architecture to set
*/
public void setArchitecture(String architecture) {
this.architecture = architecture;
}
/**
* @return the osVersion
*/
public String getOsVersion() {
return osVersion;
}
/**
* @param osVersion the osVersion to set
*/
public void setOsVersion(String osVersion) {
this.osVersion = osVersion;
}
}
| UTF-8 | Java | 2,978 | java | Node.java | Java | [] | null | [] | package it.ciavotta.Launcher.domain;
import it.ciavotta.Launcher.messages.NodeInformation;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Id;
import javax.persistence.PrePersist;
import org.hibernate.annotations.NaturalId;
/*
* This class represent the node, each node is a computing unity in a virtual machine
* */
@Entity(name = "Node")
public class Node {
//@Column(nullable = false)
private String nodeId;
@Id
// @GeneratedValue
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@NaturalId
private String nodeIP;
@NaturalId
private String port;
private String operatingSystem;
private String architecture;
private String osVersion;
public static Node fromNodeInformation(NodeInformation nodeInfo){
Node node = new Node();
node.setNodeIP(nodeInfo.getIpAddress());
node.setOperatingSystem(nodeInfo.getOs());
node.setArchitecture(nodeInfo.getOsArch());
node.setPort(nodeInfo.getPort());
node.setId(nodeInfo.getId());
node.setOsVersion(nodeInfo.getOsVersion());
node.setNodeId(nodeInfo.getNodeID());
if (nodeInfo.getState().equals("OK")) {
node.setState(NodeState.OK);
}
else if (nodeInfo.getState().equals("ERROR")) {
node.setState(NodeState.ERROR);
}
return node;
}
@PrePersist
private void createId(){
this.id = this.nodeIP+this.port;
}
@Enumerated(EnumType.STRING)
private NodeState state;
/**
* @return the nodeId
*/
public String getNodeId() {
return nodeId;
}
public NodeState getState() {
return state;
}
public void setState(NodeState state) {
this.state = state;
}
/**
* @param nodeId the nodeId to set
*/
public void setNodeId(String nodeId) {
this.nodeId = nodeId;
}
/**
* @return the nodeIP
*/
public String getNodeIP() {
return nodeIP;
}
/**
* @param nodeIP the nodeIP to set
*/
public void setNodeIP(String nodeIP) {
this.nodeIP = nodeIP;
}
/**
* @return the port
*/
public String getPort() {
return port;
}
/**
* @param port the port to set
*/
public void setPort(String port) {
this.port = port;
}
/**
* @return the operatingSystem
*/
public String getOperatingSystem() {
return operatingSystem;
}
/**
* @param operatingSystem the operatingSystem to set
*/
public void setOperatingSystem(String operatingSystem) {
this.operatingSystem = operatingSystem;
}
/**
* @return the architecture
*/
public String getArchitecture() {
return architecture;
}
/**
* @param architecture the architecture to set
*/
public void setArchitecture(String architecture) {
this.architecture = architecture;
}
/**
* @return the osVersion
*/
public String getOsVersion() {
return osVersion;
}
/**
* @param osVersion the osVersion to set
*/
public void setOsVersion(String osVersion) {
this.osVersion = osVersion;
}
}
| 2,978 | 0.692747 | 0.692747 | 171 | 16.415205 | 17.12587 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.251462 | false | false | 6 |
9b072aa4dd12c3dda4f96f26d398b411ebb23675 | 23,837,068,533,124 | 13264af8bed9f59b4ee805f3927fab09be413432 | /src/main/java/com/bokaro/service/TestSetService.java | 5dc1da03707dc44da6eba65eb924468905f0e45d | [] | no_license | srivastavapraveen9/dvionlinetest | https://github.com/srivastavapraveen9/dvionlinetest | 55b9844b12b81640ddd47e32dcedb784d3ee0f34 | 53600b57ebcb0a7e0e25eb92d3369ddb35c969b2 | refs/heads/origin | 2019-01-21T07:16:48.874000 | 2017-11-18T21:23:16 | 2017-11-18T21:23:16 | 97,254,985 | 2 | 1 | null | false | 2017-09-11T18:07:22 | 2017-07-14T16:50:00 | 2017-09-06T16:00:25 | 2017-09-11T17:59:13 | 7,104 | 1 | 0 | 0 | JavaScript | null | null | package com.bokaro.service;
import java.util.List;
import java.util.Map;
import com.bokaro.dto.TestSetDTO;
public interface TestSetService {
List<TestSetDTO> findAll();
TestSetDTO updateTime(Long id, Long timeInMin);
void delete(Long id);
TestSetDTO create(TestSetDTO testSetDTO);
List<TestSetDTO> findByUsername(String username);
TestSetDTO findById(Long id);
List<TestSetDTO> findAllByIsEnable();
TestSetDTO update(TestSetDTO testSetDTO);
List<TestSetDTO> findByCandidateId(Long id);
Map<Long, String> findAllTestSet();
}
| UTF-8 | Java | 580 | java | TestSetService.java | Java | [] | null | [] | package com.bokaro.service;
import java.util.List;
import java.util.Map;
import com.bokaro.dto.TestSetDTO;
public interface TestSetService {
List<TestSetDTO> findAll();
TestSetDTO updateTime(Long id, Long timeInMin);
void delete(Long id);
TestSetDTO create(TestSetDTO testSetDTO);
List<TestSetDTO> findByUsername(String username);
TestSetDTO findById(Long id);
List<TestSetDTO> findAllByIsEnable();
TestSetDTO update(TestSetDTO testSetDTO);
List<TestSetDTO> findByCandidateId(Long id);
Map<Long, String> findAllTestSet();
}
| 580 | 0.731034 | 0.731034 | 30 | 17.333334 | 18.336363 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.933333 | false | false | 6 |
434ac120864c55257ede0eaf6f006e6222cb9848 | 5,729,486,416,503 | 867744f9c8d4860cb90857675e7056cf5a636b28 | /src/main/java/java/Test1/AbstractFactory.java | 0cb0329e275432d7337ff04800ae14590089ab90 | [] | no_license | shinevs/IntPrep | https://github.com/shinevs/IntPrep | accb7a309a954e7864aec626bcd492f1009625fb | 464299db1cfaa9346836b959b3110da259a0bf26 | refs/heads/master | 2021-01-20T06:25:03.809000 | 2019-02-10T20:43:39 | 2019-02-10T20:43:39 | 89,874,142 | 0 | 1 | null | false | 2019-09-06T04:08:28 | 2017-04-30T20:06:36 | 2019-02-10T20:43:41 | 2019-02-10T20:43:40 | 60 | 0 | 1 | 1 | Java | false | false | package Test1;
interface shape {
public void draw();
}
class Rectanle implements shape {
@Override
public void draw() {
System.out.println("Rectangle");
}
}
interface colour {
void paint();
}
class Red implements colour {
@Override
public void paint() {
System.out.println("colour");
}
}
abstract class absFactory {
abstract shape getShape(String shape);
abstract colour getColour(String colour);
}
class shapeFactory extends absFactory {
@Override
shape getShape(String shape) {
if (shape == null)
return null;
else if (shape.equals("rectangle"))
return new Rectanle();
return null;
}
@Override
colour getColour(String colour) {
// TODO Auto-generated method stub
return null;
}
}
public class AbstractFactory {
}
| UTF-8 | Java | 764 | java | AbstractFactory.java | Java | [] | null | [] | package Test1;
interface shape {
public void draw();
}
class Rectanle implements shape {
@Override
public void draw() {
System.out.println("Rectangle");
}
}
interface colour {
void paint();
}
class Red implements colour {
@Override
public void paint() {
System.out.println("colour");
}
}
abstract class absFactory {
abstract shape getShape(String shape);
abstract colour getColour(String colour);
}
class shapeFactory extends absFactory {
@Override
shape getShape(String shape) {
if (shape == null)
return null;
else if (shape.equals("rectangle"))
return new Rectanle();
return null;
}
@Override
colour getColour(String colour) {
// TODO Auto-generated method stub
return null;
}
}
public class AbstractFactory {
}
| 764 | 0.701571 | 0.700262 | 53 | 13.415094 | 13.818819 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.886792 | false | false | 6 |
b913f662c24fb37f7e9aa0a58270991cf267c379 | 5,729,486,418,699 | e5df2c8ed2d83ba1dca2aed13f2e502942f14513 | /app/src/main/java/com/example/n_son/roombookingsupport/View/DanhSachDatPhong/PhongDangDuyet/PhongDuyetActivity.java | ba9964ed476214cbb13514ee8df3dc8c3f282e4a | [] | no_license | ngocson710/RoomBookingSupport | https://github.com/ngocson710/RoomBookingSupport | f8f610cefb9d070991611147011da8cfa8ec3e16 | ecb90e4ece9d6aa63e6dbdceff4a490c3e376bb1 | refs/heads/master | 2021-05-06T23:03:42.439000 | 2017-12-03T04:38:53 | 2017-12-03T04:38:53 | 112,900,326 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.n_son.roombookingsupport.View.DanhSachDatPhong.PhongDangDuyet;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.Toast;
import com.example.n_son.roombookingsupport.Adapter.PhongDuyetAdapter;
import com.example.n_son.roombookingsupport.Model.OjectClass.Phong;
import com.example.n_son.roombookingsupport.Model.OjectClass.ThongTinPhong;
import com.example.n_son.roombookingsupport.Model.OjectClass.User;
import com.example.n_son.roombookingsupport.Presenter.PhongDangDuyet.PresentLogicPhongDangDuyet;
import com.example.n_son.roombookingsupport.R;
import com.example.n_son.roombookingsupport.View.DangNhap.DangNhapActivity;
import com.example.n_son.roombookingsupport.View.GoiYPhong.PhongGoiYMainActivity;
import com.example.n_son.roombookingsupport.View.TrangChu.TrangChuActivity;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class PhongDuyetActivity extends AppCompatActivity implements ViewPhongDangDuyet{
PhongDuyetAdapter phongDuyetAdapter;
RecyclerView recyclerView;
List<ThongTinPhong> thongTinPhongs;
PresentLogicPhongDangDuyet presentLogicPhongDangDuyet;
DangNhapActivity dangNhapActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_phong_duyet);
recyclerView= (RecyclerView) findViewById(R.id.rcl_phongduyet);
presentLogicPhongDangDuyet= new PresentLogicPhongDangDuyet(this);
String UserID= dangNhapActivity.thongTinUser().getUserId()+"";
Log.i("PDUserID ",": "+UserID);
presentLogicPhongDangDuyet.xuLyDanhSachPhong(UserID);
}
@Override
public void hienThiPhong() {
thongTinPhongs = presentLogicPhongDangDuyet.getArrayList();
Collections.reverse(thongTinPhongs);
Log.i("HienThi: ", thongTinPhongs.get(0).getIdDangKy()+"--"+ thongTinPhongs.get(0).getIdLoaiPhong()+"- Ten "+ thongTinPhongs.get(0).getTenPhong());
RecyclerView.LayoutManager layoutManager= new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
phongDuyetAdapter= new PhongDuyetAdapter(this, R.layout.custom_layout_phongduyet, thongTinPhongs);
recyclerView.setAdapter(phongDuyetAdapter);
phongDuyetAdapter.notifyDataSetChanged();
}
@Override
public void loiHienThiPhong() {
alertDialogThongBao();
Toast.makeText(this, "Hiện tại không có phòng nào", Toast.LENGTH_SHORT).show();
}
@Override
public void xoaThanhCong() {
Toast.makeText(PhongDuyetActivity.this, "Xóa phòng thành công", Toast.LENGTH_SHORT).show();
}
@Override
public void XoaThatBai() {
Toast.makeText(PhongDuyetActivity.this, "Xóa phòng thất bại", Toast.LENGTH_SHORT).show();
}
@Override
public void chuaDuyet() {
}
@Override
public void daDuyet() {
}
private void alertDialogThongBao(){
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
builder.setTitle("Không Có Phòng");
builder.setIcon(R.drawable.ic_informationbutton_blue);
builder.setMessage("Không có phòng nào được chờ duyệt");
builder.setPositiveButton("Trở Lại", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent= new Intent(PhongDuyetActivity.this, TrangChuActivity.class);
startActivity(intent);
}
});
android.app.AlertDialog alertDialog = builder.create();
alertDialog.show();
}
} | UTF-8 | Java | 3,994 | java | PhongDuyetActivity.java | Java | [] | null | [] | package com.example.n_son.roombookingsupport.View.DanhSachDatPhong.PhongDangDuyet;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.Toast;
import com.example.n_son.roombookingsupport.Adapter.PhongDuyetAdapter;
import com.example.n_son.roombookingsupport.Model.OjectClass.Phong;
import com.example.n_son.roombookingsupport.Model.OjectClass.ThongTinPhong;
import com.example.n_son.roombookingsupport.Model.OjectClass.User;
import com.example.n_son.roombookingsupport.Presenter.PhongDangDuyet.PresentLogicPhongDangDuyet;
import com.example.n_son.roombookingsupport.R;
import com.example.n_son.roombookingsupport.View.DangNhap.DangNhapActivity;
import com.example.n_son.roombookingsupport.View.GoiYPhong.PhongGoiYMainActivity;
import com.example.n_son.roombookingsupport.View.TrangChu.TrangChuActivity;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class PhongDuyetActivity extends AppCompatActivity implements ViewPhongDangDuyet{
PhongDuyetAdapter phongDuyetAdapter;
RecyclerView recyclerView;
List<ThongTinPhong> thongTinPhongs;
PresentLogicPhongDangDuyet presentLogicPhongDangDuyet;
DangNhapActivity dangNhapActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_phong_duyet);
recyclerView= (RecyclerView) findViewById(R.id.rcl_phongduyet);
presentLogicPhongDangDuyet= new PresentLogicPhongDangDuyet(this);
String UserID= dangNhapActivity.thongTinUser().getUserId()+"";
Log.i("PDUserID ",": "+UserID);
presentLogicPhongDangDuyet.xuLyDanhSachPhong(UserID);
}
@Override
public void hienThiPhong() {
thongTinPhongs = presentLogicPhongDangDuyet.getArrayList();
Collections.reverse(thongTinPhongs);
Log.i("HienThi: ", thongTinPhongs.get(0).getIdDangKy()+"--"+ thongTinPhongs.get(0).getIdLoaiPhong()+"- Ten "+ thongTinPhongs.get(0).getTenPhong());
RecyclerView.LayoutManager layoutManager= new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
phongDuyetAdapter= new PhongDuyetAdapter(this, R.layout.custom_layout_phongduyet, thongTinPhongs);
recyclerView.setAdapter(phongDuyetAdapter);
phongDuyetAdapter.notifyDataSetChanged();
}
@Override
public void loiHienThiPhong() {
alertDialogThongBao();
Toast.makeText(this, "Hiện tại không có phòng nào", Toast.LENGTH_SHORT).show();
}
@Override
public void xoaThanhCong() {
Toast.makeText(PhongDuyetActivity.this, "Xóa phòng thành công", Toast.LENGTH_SHORT).show();
}
@Override
public void XoaThatBai() {
Toast.makeText(PhongDuyetActivity.this, "Xóa phòng thất bại", Toast.LENGTH_SHORT).show();
}
@Override
public void chuaDuyet() {
}
@Override
public void daDuyet() {
}
private void alertDialogThongBao(){
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
builder.setTitle("Không Có Phòng");
builder.setIcon(R.drawable.ic_informationbutton_blue);
builder.setMessage("Không có phòng nào được chờ duyệt");
builder.setPositiveButton("Trở Lại", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent= new Intent(PhongDuyetActivity.this, TrangChuActivity.class);
startActivity(intent);
}
});
android.app.AlertDialog alertDialog = builder.create();
alertDialog.show();
}
} | 3,994 | 0.741218 | 0.739449 | 98 | 39.387756 | 32.173519 | 155 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.693878 | false | false | 6 |
5bde04a890c64a817c91d18214cd9df5358e78a7 | 27,642,409,561,347 | 5827680a971ec56d5636d1ee112793b870f91122 | /[FINAL]/[FSXPlanner]/src/flightsim/simconnect/recv/CloudStateHandler.java | f384a1c83014c7b2911d4f4dcd0912e2c6fe6367 | [] | no_license | bily/fsxp | https://github.com/bily/fsxp | 61185fad6d87a1b0bc6d98dbdb8a02bd7e83c0cb | 39f1ff19a2fd5b86e764602baf543298d985b303 | refs/heads/master | 2021-01-20T04:33:10.510000 | 2012-08-12T07:28:23 | 2012-08-12T07:28:23 | 7,416,727 | 3 | 4 | null | null | null | null | null | null | null | null | null | null | null | null | null | package flightsim.simconnect.recv;
import flightsim.simconnect.SimConnect;
/**
*
* @author lc0277
*
*/
public interface CloudStateHandler {
public void handleCloudState(SimConnect sender, RecvCloudState e);
}
| UTF-8 | Java | 218 | java | CloudStateHandler.java | Java | [
{
"context": "ightsim.simconnect.SimConnect;\n\n/**\n * \n * @author lc0277\n *\n */\npublic interface CloudStateHandler {\n\tpubl",
"end": 102,
"score": 0.9995125532150269,
"start": 96,
"tag": "USERNAME",
"value": "lc0277"
}
] | null | [] | package flightsim.simconnect.recv;
import flightsim.simconnect.SimConnect;
/**
*
* @author lc0277
*
*/
public interface CloudStateHandler {
public void handleCloudState(SimConnect sender, RecvCloudState e);
}
| 218 | 0.761468 | 0.743119 | 13 | 15.769231 | 20.662689 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.384615 | false | false | 6 |
ed323b70e5b60564ae727db7643b43018ae8e66d | 22,960,895,225,569 | 2400c3b826f6db927428382e82dd3f6c01cb02f7 | /src/main/java/recursion.java | 32090f798b2415f3d7a44373f08124b911706d8e | [] | no_license | ayush1312/java | https://github.com/ayush1312/java | dd23eedd1677ef5d30a4039f9454bcac1ddd0a76 | 5ac1ef17132b6a39dba8e285c5666a56ae04843b | refs/heads/master | 2020-07-10T23:52:44.365000 | 2020-06-07T10:10:15 | 2020-06-07T10:10:15 | 204,398,624 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class recursion {
public int Print(int n){
if (n == 0) return 0;
else {
System.out.println(n);
return Print(n-1);
}
}
}
| UTF-8 | Java | 183 | java | recursion.java | Java | [] | null | [] | public class recursion {
public int Print(int n){
if (n == 0) return 0;
else {
System.out.println(n);
return Print(n-1);
}
}
}
| 183 | 0.453552 | 0.437158 | 9 | 19.333334 | 11.527744 | 34 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 6 |
173d377b7c7ba5aed00992767e9d0071be583eb9 | 23,167,053,642,254 | 63e0cd899972adbb117a17d8d40eef8fefb56d62 | /lunch_and_learn/lal_springboot/sc10_sb_jpa_relations/src/main/java/com/lal/sb/repository/CustomerOrderRepository.java | 5b09291ad9d85e17b13df480e942b84f153876f9 | [] | no_license | sherazc/playground | https://github.com/sherazc/playground | 8b90e1f7b624a77a3f3e9cf5f71eecf984aa8180 | 7fe926d2564b12d96f237b253511dd7c2a302b64 | refs/heads/master | 2023-08-16T17:22:29.564000 | 2023-08-16T04:34:52 | 2023-08-16T04:34:52 | 87,116,642 | 2 | 1 | null | false | 2023-05-04T18:25:45 | 2017-04-03T20:15:15 | 2023-03-15T13:59:06 | 2023-05-02T23:33:31 | 334,143 | 1 | 1 | 392 | PHP | false | false | package com.lal.sb.repository;
import com.lal.sb.model.CustomerOrder;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CustomerOrderRepository extends JpaRepository<CustomerOrder, Long> {
}
| UTF-8 | Java | 222 | java | CustomerOrderRepository.java | Java | [] | null | [] | package com.lal.sb.repository;
import com.lal.sb.model.CustomerOrder;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CustomerOrderRepository extends JpaRepository<CustomerOrder, Long> {
}
| 222 | 0.837838 | 0.837838 | 7 | 30.714285 | 30.908688 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 6 |
ca2cce206b6e346f88ad3019f38401f7afd7f448 | 7,464,653,206,814 | 23215250ae64742e64cfcb99e7c377c4bda59dc8 | /src/main/java/com/sowells/pay/webapp/gift/domain/GiftInfoResponse.java | 3d7f8d5d43a60c095fc5b84c1398baebac891b03 | [] | no_license | sowells/pay-webapp | https://github.com/sowells/pay-webapp | 689ff8bec73fd33ab93c5308863aad233775279c | 0fed8ee3e9253186bc39ea0407ba0a6a30e2e0fa | refs/heads/master | 2022-11-15T19:34:46.552000 | 2020-06-29T16:39:42 | 2020-06-29T16:39:42 | 275,058,021 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sowells.pay.webapp.gift.domain;
import lombok.Data;
import java.sql.Timestamp;
import java.util.List;
@Data
public class GiftInfoResponse {
Timestamp creationTime; // 뿌린 시각
long totalAmount; // 뿌린 금액
long receivedAmount; // 받기 완료된 금액
List<Receiving> recevings; // 받기 완료된 정보
@Data
public class Receiving {
long receiverId; // 받은 사용자 아이디
long amount; // 받은 금액
}
}
| UTF-8 | Java | 468 | java | GiftInfoResponse.java | Java | [] | null | [] | package com.sowells.pay.webapp.gift.domain;
import lombok.Data;
import java.sql.Timestamp;
import java.util.List;
@Data
public class GiftInfoResponse {
Timestamp creationTime; // 뿌린 시각
long totalAmount; // 뿌린 금액
long receivedAmount; // 받기 완료된 금액
List<Receiving> recevings; // 받기 완료된 정보
@Data
public class Receiving {
long receiverId; // 받은 사용자 아이디
long amount; // 받은 금액
}
}
| 468 | 0.7025 | 0.7025 | 20 | 19 | 14.996666 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 6 |
f27a991d5b418506c45a50a5e59397d81bac9071 | 34,703,335,771,800 | 44b9c54447e8452e63c9f55732216ff00c97c52b | /samples/sample-chat-app/src/main/java/com/azure/android/communication/chat/sampleapp/MainActivity.java | 1cb2c7775ab2e0997c45c43609afcb1f3304ed36 | [
"MIT",
"LicenseRef-scancode-generic-cla"
] | permissive | Azure/azure-sdk-for-android | https://github.com/Azure/azure-sdk-for-android | 21affc77a26de982dd458f9edc91b03137d52180 | a9440299d34c076667e56af1c897dd4eaefc0b69 | refs/heads/main | 2023-08-17T11:15:55.473000 | 2023-08-09T23:29:54 | 2023-08-09T23:29:54 | 123,228,861 | 81 | 83 | MIT | false | 2023-09-13T20:28:55 | 2018-02-28T04:25:35 | 2023-08-24T20:27:40 | 2023-09-13T20:28:54 | 25,509 | 90 | 99 | 53 | Java | false | false | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.android.communication.chat.sampleapp;
import static com.azure.android.communication.chat.models.ChatEventType.CHAT_MESSAGE_DELETED;
import static com.azure.android.communication.chat.models.ChatEventType.CHAT_MESSAGE_EDITED;
import static com.azure.android.communication.chat.models.ChatEventType.CHAT_MESSAGE_RECEIVED;
import static com.azure.android.communication.chat.models.ChatEventType.CHAT_THREAD_CREATED;
import static com.azure.android.communication.chat.models.ChatEventType.CHAT_THREAD_DELETED;
import static com.azure.android.communication.chat.models.ChatEventType.CHAT_THREAD_PROPERTIES_UPDATED;
import static com.azure.android.communication.chat.models.ChatEventType.PARTICIPANTS_ADDED;
import static com.azure.android.communication.chat.models.ChatEventType.PARTICIPANTS_REMOVED;
import static com.azure.android.communication.chat.models.ChatEventType.READ_RECEIPT_RECEIVED;
import static com.azure.android.communication.chat.models.ChatEventType.TYPING_INDICATOR_RECEIVED;
import static com.azure.android.communication.chat.sampleapp.MyAppConfiguration.ACS_ENDPOINT;
import static com.azure.android.communication.chat.sampleapp.ApplicationConstants.APPLICATION_ID;
import static com.azure.android.communication.chat.sampleapp.MyAppConfiguration.FIRST_USER_ID;
import static com.azure.android.communication.chat.sampleapp.ApplicationConstants.SDK_NAME;
import static com.azure.android.communication.chat.sampleapp.ApplicationConstants.SDK_VERSION;
import static com.azure.android.communication.chat.sampleapp.MyAppConfiguration.SECOND_USER_ID;
import static com.azure.android.communication.chat.sampleapp.MyAppConfiguration.COMMUNICATION_TOKEN_CREDENTIAL;
import static com.azure.android.communication.chat.sampleapp.ApplicationConstants.TAG;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import com.azure.android.communication.chat.ChatAsyncClient;
import com.azure.android.communication.chat.ChatClientBuilder;
import com.azure.android.communication.chat.ChatThreadAsyncClient;
import com.azure.android.communication.chat.models.ChatEvent;
import com.azure.android.communication.chat.models.ChatEventType;
import com.azure.android.communication.chat.models.ChatMessageDeletedEvent;
import com.azure.android.communication.chat.models.ChatMessageEditedEvent;
import com.azure.android.communication.chat.models.ChatMessageReadReceipt;
import com.azure.android.communication.chat.models.ChatMessageReceivedEvent;
import com.azure.android.communication.chat.models.ChatMessageType;
import com.azure.android.communication.chat.models.ChatParticipant;
import com.azure.android.communication.chat.models.ChatPushNotification;
import com.azure.android.communication.chat.models.ChatThreadCreatedEvent;
import com.azure.android.communication.chat.models.ChatThreadDeletedEvent;
import com.azure.android.communication.chat.models.ChatThreadProperties;
import com.azure.android.communication.chat.models.ChatThreadPropertiesUpdatedEvent;
import com.azure.android.communication.chat.models.CreateChatThreadOptions;
import com.azure.android.communication.chat.models.CreateChatThreadResult;
import com.azure.android.communication.chat.models.ListParticipantsOptions;
import com.azure.android.communication.chat.models.ListReadReceiptOptions;
import com.azure.android.communication.chat.models.ParticipantsAddedEvent;
import com.azure.android.communication.chat.models.ParticipantsRemovedEvent;
import com.azure.android.communication.chat.models.ReadReceiptReceivedEvent;
import com.azure.android.communication.chat.models.RealTimeNotificationCallback;
import com.azure.android.communication.chat.models.SendChatMessageOptions;
import com.azure.android.communication.chat.models.TypingIndicatorReceivedEvent;
import com.azure.android.communication.chat.models.TypingNotificationOptions;
import com.azure.android.communication.common.CommunicationUserIdentifier;
import com.azure.android.core.http.policy.HttpLogDetailLevel;
import com.azure.android.core.http.policy.HttpLogOptions;
import com.azure.android.core.http.policy.UserAgentPolicy;
import com.azure.android.core.rest.util.paging.PagedAsyncStream;
import com.azure.android.core.util.AsyncStreamHandler;
import com.azure.android.core.util.RequestContext;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.messaging.FirebaseMessaging;
import com.jakewharton.threetenabp.AndroidThreeTen;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Queue;
import java.util.StringJoiner;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java9.util.function.Consumer;
public class MainActivity extends AppCompatActivity {
private ChatAsyncClient chatAsyncClient;
private ChatThreadAsyncClient chatThreadAsyncClient;
private int eventHandlerCalled;
private String threadId = "<to-be-updated-below>";
private String chatMessageId = "<to-be-updated-below>";
private final Queue<String> unreadMessages = new ConcurrentLinkedQueue<>();
private static Map<RealTimeNotificationCallback, ChatEventType> realTimeNotificationCallbacks = new HashMap<>();
private BroadcastReceiver firebaseMessagingReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
ChatPushNotification pushNotification =
(ChatPushNotification) intent.getParcelableExtra("PushNotificationPayload");
Log.d(TAG, "Push Notification received in MainActivity: " + pushNotification.getPayload());
boolean isHandled = chatAsyncClient.handlePushNotification(pushNotification);
if (!isHandled) {
Log.d(TAG, "No listener registered for incoming push notification!");
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AndroidThreeTen.init(this);
createChatAsyncClient();
LocalBroadcastManager
.getInstance(this)
.registerReceiver(
firebaseMessagingReceiver,
new IntentFilter("com.azure.android.communication.chat.sampleapp.pushnotification"));
}
public void createChatAsyncClient() {
try {
chatAsyncClient = new ChatClientBuilder()
.endpoint(ACS_ENDPOINT)
.credential(COMMUNICATION_TOKEN_CREDENTIAL)
.addPolicy(new UserAgentPolicy(APPLICATION_ID, SDK_NAME, SDK_VERSION))
.httpLogOptions(new HttpLogOptions()
.setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)
.addAllowedHeaderName("MS-CV"))
.buildAsyncClient();
Log.d(TAG, "Created ChatAsyncClient");
} catch (Exception e) {
Log.e("ChatAsyncClient creation failed", Objects.requireNonNull(e.getMessage()));
}
}
public void createChatThreadAsyncClient() {
if (chatAsyncClient == null) {
createChatAsyncClient();
}
// A list of participants to start the thread with.
List<ChatParticipant> participants = new ArrayList<>();
// The display name for the thread participant.
String displayName = "First participant";
participants.add(new ChatParticipant()
.setCommunicationIdentifier(new CommunicationUserIdentifier(FIRST_USER_ID))
.setDisplayName(displayName));
// The topic for the thread.
final String topic = "General";
// Optional, set a repeat request ID.
final String repeatabilityRequestID = "";
// Options to pass to the create method.
CreateChatThreadOptions createChatThreadOptions = new CreateChatThreadOptions()
.setTopic(topic)
.setParticipants(participants)
.setIdempotencyToken(repeatabilityRequestID);
try {
CreateChatThreadResult createChatThreadResult =
chatAsyncClient.createChatThread(createChatThreadOptions).get();
ChatThreadProperties chatThreadProperties = createChatThreadResult.getChatThreadProperties();
threadId = chatThreadProperties.getId();
logAndToast("Created thread with ID: " + threadId);
chatThreadAsyncClient = chatAsyncClient.getChatThreadClient(threadId);
Log.d(TAG, "Created ChatThreadAsyncClient");
} catch (InterruptedException | ExecutionException e) {
Log.e("ChatThreadAsyncClient creation failed", Objects.requireNonNull(e.getMessage()));
}
}
private void logAndToast(String msg) {
Log.d(TAG, msg);
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
public void startPushNotification(View view) {
logAndToast( "Start push notification");
try {
startFcmPushNotification();
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
public void registerPushNotificationListener(View view) {
logAndToast("Register push notification listeners");
try {
chatAsyncClient.addPushNotificationHandler(CHAT_MESSAGE_RECEIVED, (ChatEvent payload) -> {
Log.i(TAG, "Push Notification CHAT_MESSAGE_RECEIVED.");
ChatMessageReceivedEvent event = (ChatMessageReceivedEvent) payload;
Log.i(TAG, "Message received!"
+ " ThreadId: " + event.getChatThreadId()
+ " MessageId: " + event.getId()
+ " Content: " + event.getContent()
+ " Priority: " + event.getPriority()
+ " SenderDisplayName: " + event.getSenderDisplayName()
+ " SenderMri: " + ((CommunicationUserIdentifier)event.getSender()).getId()
+ " Version: " + event.getVersion()
+ " CreatedOn: " + event.getCreatedOn()
+ " Type: " + event.getType()
+ " RecipientMri: " + ((CommunicationUserIdentifier)event.getRecipient()).getId()
);
});
chatAsyncClient.addPushNotificationHandler(CHAT_MESSAGE_EDITED, (ChatEvent payload) -> {
Log.i(TAG, "Push Notification CHAT_MESSAGE_EDITED.");
ChatMessageEditedEvent event = (ChatMessageEditedEvent) payload;
Log.i(TAG, "Message edited!"
+ " ThreadId: " + event.getChatThreadId()
+ " MessageId: " + event.getId()
+ " Content: " + event.getContent()
+ " SenderDisplayName: " + event.getSenderDisplayName()
+ " SenderMri: " + ((CommunicationUserIdentifier)event.getSender()).getId()
+ " Version: " + event.getVersion()
+ " CreatedOn: " + event.getCreatedOn()
+ " EditedOn: " + event.getEditedOn()
+ " RecipientMri: " + ((CommunicationUserIdentifier)event.getRecipient()).getId()
);
});
chatAsyncClient.addPushNotificationHandler(CHAT_MESSAGE_DELETED, (ChatEvent payload) -> {
Log.i(TAG, "Push Notification CHAT_MESSAGE_DELETED.");
ChatMessageDeletedEvent event = (ChatMessageDeletedEvent) payload;
Log.i(TAG, "Message deleted!"
+ " ThreadId: " + event.getChatThreadId()
+ " MessageId: " + event.getId()
+ " SenderDisplayName: " + event.getSenderDisplayName()
+ " SenderMri: " + ((CommunicationUserIdentifier)event.getSender()).getId()
+ " Version: " + event.getVersion()
+ " CreatedOn: " + event.getCreatedOn()
+ " DeletedOn: " + event.getDeletedOn()
+ " RecipientMri: " + ((CommunicationUserIdentifier)event.getRecipient()).getId()
);
});
chatAsyncClient.addPushNotificationHandler(CHAT_THREAD_CREATED, (ChatEvent payload) -> {
Log.i(TAG, "Push Notification CHAT_THREAD_CREATED.");
ChatThreadCreatedEvent event = (ChatThreadCreatedEvent) payload;
Log.i(TAG, "Thread Created!"
+ " ThreadId: " + event.getChatThreadId()
+ " Properties_Id: " + event.getProperties().getId()
+ " Properties_Topic: " + event.getProperties().getTopic()
+ " Properties_CreatedOn: " + event.getProperties().getCreatedOn()
+ " Properties_CreatedByMri: " + ((CommunicationUserIdentifier)event.getProperties().getCreatedByCommunicationIdentifier()).getId()
+ " Participants_size: " + event.getParticipants().size()
+ " Version: " + event.getVersion()
+ " CreatedOn: " + event.getCreatedOn()
+ " CreatedBy_DisplayName: " + event.getCreatedBy().getDisplayName()
+ " CreatedBy_Mri: " + ((CommunicationUserIdentifier)event.getCreatedBy().getCommunicationIdentifier()).getId()
);
});
chatAsyncClient.addPushNotificationHandler(CHAT_THREAD_PROPERTIES_UPDATED, (ChatEvent payload) -> {
Log.i(TAG, "Push Notification CHAT_THREAD_PROPERTIES_UPDATED.");
ChatThreadPropertiesUpdatedEvent event = (ChatThreadPropertiesUpdatedEvent) payload;
Log.i(TAG, "Thread Updated!"
+ " ThreadId: " + event.getChatThreadId()
+ " Properties_Id: " + event.getProperties().getId()
+ " Properties_Topic: " + event.getProperties().getTopic()
+ " Version: " + event.getVersion()
+ " UpdatedOn: " + event.getUpdatedOn()
+ " UpdatedBy_DisplayName: " + event.getUpdatedBy().getDisplayName()
+ " UpdatedBy_Mri: " + ((CommunicationUserIdentifier)event.getUpdatedBy().getCommunicationIdentifier()).getId()
);
});
chatAsyncClient.addPushNotificationHandler(CHAT_THREAD_DELETED, (ChatEvent payload) -> {
Log.i(TAG, "Push Notification CHAT_THREAD_DELETED.");
ChatThreadDeletedEvent event = (ChatThreadDeletedEvent) payload;
Log.i(TAG, "Thread Deleted!"
+ " ThreadId: " + event.getChatThreadId()
+ " Version: " + event.getVersion()
+ " DeletedOn: " + event.getDeletedOn()
+ " DeletedBy_DisplayName: " + event.getDeletedBy().getDisplayName()
+ " DeletedBy_Mri: " + ((CommunicationUserIdentifier)event.getDeletedBy().getCommunicationIdentifier()).getId()
);
});
chatAsyncClient.addPushNotificationHandler(PARTICIPANTS_ADDED, (ChatEvent payload) -> {
Log.i(TAG, "Push Notification PARTICIPANTS_ADDED.");
ParticipantsAddedEvent event = (ParticipantsAddedEvent) payload;
Log.i(TAG, "Participant Added!"
+ " ThreadId: " + event.getChatThreadId()
+ " ParticipantsAdded_size: " + event.getParticipantsAdded().size()
+ " Version: " + event.getVersion()
+ " AddedOn: " + event.getAddedOn()
+ " AddedBy_DisplayName: " + event.getAddedBy().getDisplayName()
+ " AddedBy_Mri: " + ((CommunicationUserIdentifier)event.getAddedBy().getCommunicationIdentifier()).getId()
);
});
chatAsyncClient.addPushNotificationHandler(PARTICIPANTS_REMOVED, (ChatEvent payload) -> {
Log.i(TAG, "Push Notification PARTICIPANTS_REMOVED.");
ParticipantsRemovedEvent event = (ParticipantsRemovedEvent) payload;
Log.i(TAG, "Participant Removed!"
+ " ThreadId: " + event.getChatThreadId()
+ " ParticipantsRemoved_size: " + event.getParticipantsRemoved().size()
+ " Version: " + event.getVersion()
+ " RemovedOn: " + event.getRemovedOn()
+ " RemovedBy_DisplayName: " + event.getRemovedBy().getDisplayName()
+ " RemovedBy_Mri: " + ((CommunicationUserIdentifier)event.getRemovedBy().getCommunicationIdentifier()).getId()
);
});
} catch (IllegalStateException error) {
Log.i(TAG, "Push Notification not start yet.");
}
}
public void stopPushNotification(View view) {
logAndToast( "Stop push notification");
try {
stopFcmPushNotification();
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
public void startRealTimeNotification(View view) {
logAndToast( "Starting realtime notification");
try {
chatAsyncClient.startRealtimeNotifications(getApplicationContext(), new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) {
Log.e(TAG, "Renew realtime notification registration failed!", throwable);
}
});
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
public void registerRealTimeNotificationListener(View view) {
logAndToast("Register a test listener");
RealTimeNotificationCallback messageReceivedHandler = (ChatEvent payload) -> {
eventHandlerCalled++;
Log.i(TAG, eventHandlerCalled + " messages handled.");
ChatMessageReceivedEvent event = (ChatMessageReceivedEvent) payload;
Log.i(TAG, "Message created! ThreadId: " + event.getChatThreadId());
};
chatAsyncClient.addEventHandler(CHAT_MESSAGE_RECEIVED, messageReceivedHandler);
realTimeNotificationCallbacks.put(messageReceivedHandler, CHAT_MESSAGE_RECEIVED);
RealTimeNotificationCallback messageEditedHandler = (ChatEvent payload) -> {
eventHandlerCalled++;
Log.i(TAG, eventHandlerCalled + " messages handled.");
ChatMessageEditedEvent event = (ChatMessageEditedEvent) payload;
Log.i(TAG, "Message edited! ThreadId: " + event.getChatThreadId());
};
chatAsyncClient.addEventHandler(CHAT_MESSAGE_EDITED, messageEditedHandler);
realTimeNotificationCallbacks.put(messageEditedHandler, CHAT_MESSAGE_EDITED);
RealTimeNotificationCallback messageDeletedHandler = (ChatEvent payload) -> {
eventHandlerCalled++;
Log.i(TAG, eventHandlerCalled + " messages handled.");
ChatMessageDeletedEvent event = (ChatMessageDeletedEvent) payload;
Log.i(TAG, "Message deleted! ThreadId: " + event.getChatThreadId());
};
chatAsyncClient.addEventHandler(CHAT_MESSAGE_DELETED, messageDeletedHandler);
realTimeNotificationCallbacks.put(messageDeletedHandler, CHAT_MESSAGE_DELETED);
RealTimeNotificationCallback typingIndicatorHandler = (ChatEvent payload) -> {
eventHandlerCalled++;
Log.i(TAG, eventHandlerCalled + " messages handled.");
TypingIndicatorReceivedEvent event = (TypingIndicatorReceivedEvent) payload;
Log.i(TAG, "Typing indicator received! ThreadId: " + event.getChatThreadId());
};
chatAsyncClient.addEventHandler(TYPING_INDICATOR_RECEIVED, typingIndicatorHandler);
realTimeNotificationCallbacks.put(typingIndicatorHandler, TYPING_INDICATOR_RECEIVED);
RealTimeNotificationCallback readReceiptHandler = (ChatEvent payload) -> {
eventHandlerCalled++;
Log.i(TAG, eventHandlerCalled + " messages handled.");
ReadReceiptReceivedEvent event = (ReadReceiptReceivedEvent) payload;
Log.i(TAG, "Read receipt received! ThreadId: " + event.getChatThreadId());
};
chatAsyncClient.addEventHandler(READ_RECEIPT_RECEIVED, readReceiptHandler);
realTimeNotificationCallbacks.put(readReceiptHandler, READ_RECEIPT_RECEIVED);
RealTimeNotificationCallback threadCreatedHandler = (ChatEvent payload) -> {
eventHandlerCalled++;
Log.i(TAG, eventHandlerCalled + " messages handled.");
ChatThreadCreatedEvent event = (ChatThreadCreatedEvent) payload;
Log.i(TAG, "Chat thread created! ThreadId: " + event.getChatThreadId());
};
chatAsyncClient.addEventHandler(CHAT_THREAD_CREATED, threadCreatedHandler);
realTimeNotificationCallbacks.put(threadCreatedHandler, CHAT_THREAD_CREATED);
RealTimeNotificationCallback threadDeletedHandler = (ChatEvent payload) -> {
eventHandlerCalled++;
Log.i(TAG, eventHandlerCalled + " messages handled.");
ChatThreadDeletedEvent event = (ChatThreadDeletedEvent) payload;
Log.i(TAG, "Chat thread deleted! ThreadId: " + event.getChatThreadId());
};
chatAsyncClient.addEventHandler(CHAT_THREAD_DELETED, threadDeletedHandler);
realTimeNotificationCallbacks.put(threadDeletedHandler, CHAT_THREAD_DELETED);
RealTimeNotificationCallback threadUpdatedHandler = (ChatEvent payload) -> {
eventHandlerCalled++;
Log.i(TAG, eventHandlerCalled + " messages handled.");
ChatThreadPropertiesUpdatedEvent event = (ChatThreadPropertiesUpdatedEvent) payload;
Log.i(TAG, "Chat thread properties updated! ThreadId: " + event.getChatThreadId());
};
chatAsyncClient.addEventHandler(CHAT_THREAD_PROPERTIES_UPDATED, threadUpdatedHandler);
realTimeNotificationCallbacks.put(threadUpdatedHandler, CHAT_THREAD_PROPERTIES_UPDATED);
RealTimeNotificationCallback participantAddedHandler = (ChatEvent payload) -> {
eventHandlerCalled++;
Log.i(TAG, eventHandlerCalled + " messages handled.");
ParticipantsAddedEvent event = (ParticipantsAddedEvent) payload;
Log.i(TAG, "Participants added! ThreadId: " + event.getChatThreadId());
};
chatAsyncClient.addEventHandler(PARTICIPANTS_ADDED, participantAddedHandler);
realTimeNotificationCallbacks.put(participantAddedHandler, PARTICIPANTS_ADDED);
RealTimeNotificationCallback participantRemovedHandler = (ChatEvent payload) -> {
eventHandlerCalled++;
Log.i(TAG, eventHandlerCalled + " messages handled.");
ParticipantsRemovedEvent event = (ParticipantsRemovedEvent) payload;
Log.i(TAG, "Participants removed! ThreadId: " + event.getChatThreadId());
};
chatAsyncClient.addEventHandler(PARTICIPANTS_REMOVED, participantRemovedHandler);
realTimeNotificationCallbacks.put(participantRemovedHandler, PARTICIPANTS_REMOVED);
}
public void unregisterRealTimeNotificationListener(View view) {
logAndToast("Unregister realtime notification listeners");
for (Map.Entry<RealTimeNotificationCallback, ChatEventType> entry: realTimeNotificationCallbacks.entrySet()) {
chatAsyncClient.removeEventHandler(entry.getValue(), entry.getKey());
}
realTimeNotificationCallbacks.clear();
}
public void sendChatMessage(View view) {
if (chatThreadAsyncClient == null) {
createChatThreadAsyncClient();
}
if (chatThreadAsyncClient != null) {
// The chat message content, required.
final String content = "Test message 1";
// The display name of the sender, if null (i.e. not specified), an empty name will be set.
final String senderDisplayName = "First participant";
SendChatMessageOptions chatMessageOptions = new SendChatMessageOptions()
.setType(ChatMessageType.TEXT)
.setContent(content)
.setSenderDisplayName(senderDisplayName)
.setMetadata(new HashMap<String, String>() {
{
put("tags", "tag1");
put("deliveryMode", "deliveryMode value");
}
});
// A string is the response returned from sending a message, it is an id, which is the unique ID of the
// message.
try {
chatMessageId = chatThreadAsyncClient.sendMessage(chatMessageOptions).get().getId();
unreadMessages.add(chatMessageId);
logAndToast("Message sent with ID: " + chatMessageId);
} catch (InterruptedException | ExecutionException e) {
logAndToast("Send message failed: " + e.getMessage());
}
} else {
logAndToast("ChatThreadAsyncClient creation failed");
}
}
public void addParticipant(View view) {
if (chatThreadAsyncClient == null) {
createChatThreadAsyncClient();
}
if (chatThreadAsyncClient != null) {
// The display name for the thread participant.
String secondUserDisplayName = "Second participant";
try {
chatThreadAsyncClient.addParticipant(new ChatParticipant().setCommunicationIdentifier(
new CommunicationUserIdentifier(SECOND_USER_ID)).setDisplayName(secondUserDisplayName)).get();
logAndToast("Added chat participant");
} catch (InterruptedException | ExecutionException e) {
logAndToast("Add user failed: " + e.getMessage());
}
} else {
logAndToast("ChatThreadAsyncClient creation failed");
}
}
public void listParticipants(View view) {
if (chatThreadAsyncClient == null) {
createChatThreadAsyncClient();
}
if (chatThreadAsyncClient != null) {
// The maximum number of participants to be returned per page, optional.
int maxPageSize = 10;
// Skips participants up to a specified position in response.
int skip = 0;
// Options to pass to the list method.
ListParticipantsOptions listParticipantsOptions = new ListParticipantsOptions()
.setMaxPageSize(maxPageSize)
.setSkip(skip);
try {
PagedAsyncStream<ChatParticipant> participantPagedAsyncStream
= chatThreadAsyncClient.listParticipants(new ListParticipantsOptions(), null);
StringJoiner participantsStringJoiner =
new StringJoiner(
"\nParticipant: ",
"",
""
);
CountDownLatch latch = new CountDownLatch(1);
participantPagedAsyncStream.forEach(new AsyncStreamHandler<ChatParticipant>() {
@Override
public void onNext(ChatParticipant participant) {
participantsStringJoiner.add(participant.getDisplayName());
}
@Override
public void onError(Throwable throwable) {
latch.countDown();
}
@Override
public void onComplete() {
latch.countDown();
}
});
awaitOnLatch(latch);
logAndToast(participantsStringJoiner.toString());
} catch (Exception e) {
logAndToast("Listing participants failed: " + e.getMessage());
}
} else {
logAndToast("ChatThreadAsyncClient creation failed");
}
}
public void removeParticipant(View view) {
if (chatThreadAsyncClient == null) {
createChatThreadAsyncClient();
}
if (chatThreadAsyncClient != null) {
try {
// Using the unique ID of the participant.
chatThreadAsyncClient.removeParticipant(new CommunicationUserIdentifier(SECOND_USER_ID)).get();
logAndToast("Removed second participant");
} catch (InterruptedException | ExecutionException e) {
logAndToast("Remove user failed: " + e.getMessage());
}
} else {
logAndToast("ChatThreadAsyncClient creation failed");
}
}
public void sendTypingNotification(View view) {
if (chatThreadAsyncClient == null) {
createChatThreadAsyncClient();
}
if (chatThreadAsyncClient != null) {
try {
TypingNotificationOptions options = new TypingNotificationOptions();
options.setSenderDisplayName("Sender Display Name");
chatThreadAsyncClient.sendTypingNotificationWithResponse(options, RequestContext.NONE).get();
logAndToast("Sent a typing notification successfully");
} catch (InterruptedException | ExecutionException e) {
logAndToast("Send typing notification failed: " + e.getMessage());
}
} else {
logAndToast("ChatThreadAsyncClient creation failed");
}
}
public void sendReadReceipts(View view) {
if (chatThreadAsyncClient == null) {
createChatThreadAsyncClient();
}
if (chatThreadAsyncClient != null) {
try {
for (String unreadMessageId : unreadMessages) {
chatThreadAsyncClient.sendReadReceipt(unreadMessageId).get();
unreadMessages.poll();
logAndToast("Sent a read receipt for message with ID: " + unreadMessageId);
}
} catch (InterruptedException | ExecutionException e) {
logAndToast("Send read receipt failed: " + e.getMessage());
}
} else {
logAndToast("ChatThreadAsyncClient creation failed");
}
}
public void listReadReceipts(View view) {
if (chatThreadAsyncClient == null) {
createChatThreadAsyncClient();
}
if (chatThreadAsyncClient != null) {
// The maximum number of read receipts to be returned per page, optional.
int maxPageSize = 10;
// Skips participants up to a specified position in response.
int skip = 0;
// Options to pass to the list method.
ListReadReceiptOptions listReadReceiptOptions = new ListReadReceiptOptions()
.setMaxPageSize(maxPageSize)
.setSkip(skip);
try {
PagedAsyncStream<ChatMessageReadReceipt> readReceipts =
chatThreadAsyncClient.listReadReceipts(listReadReceiptOptions, RequestContext.NONE);
readReceipts.forEach(readReceipt -> {
Log.d(TAG, "Got receipt for participant "
+ ((CommunicationUserIdentifier)readReceipt.getSenderCommunicationIdentifier()).getId()
+ " for message with id: "
+ readReceipt.getChatMessageId());
});
} catch (Exception e) {
logAndToast("Listing read receipts failed: " + e.getMessage());
}
} else {
logAndToast("ChatThreadAsyncClient creation failed");
}
}
private void startFcmPushNotification() {
FirebaseMessaging.getInstance().getToken()
.addOnCompleteListener(new OnCompleteListener<String>() {
@Override
public void onComplete(@NonNull Task<String> task) {
if (!task.isSuccessful()) {
Log.w(TAG, "Fetching FCM registration token failed", task.getException());
return;
}
// Get new FCM registration token
String token = task.getResult();
// Log and toast
Log.d(TAG, "Fcm push token generated:" + token);
Toast.makeText(MainActivity.this, token, Toast.LENGTH_SHORT).show();
chatAsyncClient.startPushNotifications(token);
}
});
}
private void stopFcmPushNotification() {
chatAsyncClient.stopPushNotifications();
}
private static void awaitOnLatch(CountDownLatch latch) {
long timeoutInSec = 2;
try {
latch.await(timeoutInSec, TimeUnit.MINUTES);
} catch (InterruptedException e) {
Log.e(TAG, "List operation didn't complete within " + timeoutInSec + " minutes");
}
}
}
| UTF-8 | Java | 33,538 | java | MainActivity.java | Java | [
{
"context": "thread participant.\n String displayName = \"First participant\";\n participants.add(new ChatPa",
"end": 7989,
"score": 0.9302865266799927,
"start": 7984,
"tag": "NAME",
"value": "First"
},
{
"context": "d participant.\n String displayName = \"First... | null | [] | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.android.communication.chat.sampleapp;
import static com.azure.android.communication.chat.models.ChatEventType.CHAT_MESSAGE_DELETED;
import static com.azure.android.communication.chat.models.ChatEventType.CHAT_MESSAGE_EDITED;
import static com.azure.android.communication.chat.models.ChatEventType.CHAT_MESSAGE_RECEIVED;
import static com.azure.android.communication.chat.models.ChatEventType.CHAT_THREAD_CREATED;
import static com.azure.android.communication.chat.models.ChatEventType.CHAT_THREAD_DELETED;
import static com.azure.android.communication.chat.models.ChatEventType.CHAT_THREAD_PROPERTIES_UPDATED;
import static com.azure.android.communication.chat.models.ChatEventType.PARTICIPANTS_ADDED;
import static com.azure.android.communication.chat.models.ChatEventType.PARTICIPANTS_REMOVED;
import static com.azure.android.communication.chat.models.ChatEventType.READ_RECEIPT_RECEIVED;
import static com.azure.android.communication.chat.models.ChatEventType.TYPING_INDICATOR_RECEIVED;
import static com.azure.android.communication.chat.sampleapp.MyAppConfiguration.ACS_ENDPOINT;
import static com.azure.android.communication.chat.sampleapp.ApplicationConstants.APPLICATION_ID;
import static com.azure.android.communication.chat.sampleapp.MyAppConfiguration.FIRST_USER_ID;
import static com.azure.android.communication.chat.sampleapp.ApplicationConstants.SDK_NAME;
import static com.azure.android.communication.chat.sampleapp.ApplicationConstants.SDK_VERSION;
import static com.azure.android.communication.chat.sampleapp.MyAppConfiguration.SECOND_USER_ID;
import static com.azure.android.communication.chat.sampleapp.MyAppConfiguration.COMMUNICATION_TOKEN_CREDENTIAL;
import static com.azure.android.communication.chat.sampleapp.ApplicationConstants.TAG;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import com.azure.android.communication.chat.ChatAsyncClient;
import com.azure.android.communication.chat.ChatClientBuilder;
import com.azure.android.communication.chat.ChatThreadAsyncClient;
import com.azure.android.communication.chat.models.ChatEvent;
import com.azure.android.communication.chat.models.ChatEventType;
import com.azure.android.communication.chat.models.ChatMessageDeletedEvent;
import com.azure.android.communication.chat.models.ChatMessageEditedEvent;
import com.azure.android.communication.chat.models.ChatMessageReadReceipt;
import com.azure.android.communication.chat.models.ChatMessageReceivedEvent;
import com.azure.android.communication.chat.models.ChatMessageType;
import com.azure.android.communication.chat.models.ChatParticipant;
import com.azure.android.communication.chat.models.ChatPushNotification;
import com.azure.android.communication.chat.models.ChatThreadCreatedEvent;
import com.azure.android.communication.chat.models.ChatThreadDeletedEvent;
import com.azure.android.communication.chat.models.ChatThreadProperties;
import com.azure.android.communication.chat.models.ChatThreadPropertiesUpdatedEvent;
import com.azure.android.communication.chat.models.CreateChatThreadOptions;
import com.azure.android.communication.chat.models.CreateChatThreadResult;
import com.azure.android.communication.chat.models.ListParticipantsOptions;
import com.azure.android.communication.chat.models.ListReadReceiptOptions;
import com.azure.android.communication.chat.models.ParticipantsAddedEvent;
import com.azure.android.communication.chat.models.ParticipantsRemovedEvent;
import com.azure.android.communication.chat.models.ReadReceiptReceivedEvent;
import com.azure.android.communication.chat.models.RealTimeNotificationCallback;
import com.azure.android.communication.chat.models.SendChatMessageOptions;
import com.azure.android.communication.chat.models.TypingIndicatorReceivedEvent;
import com.azure.android.communication.chat.models.TypingNotificationOptions;
import com.azure.android.communication.common.CommunicationUserIdentifier;
import com.azure.android.core.http.policy.HttpLogDetailLevel;
import com.azure.android.core.http.policy.HttpLogOptions;
import com.azure.android.core.http.policy.UserAgentPolicy;
import com.azure.android.core.rest.util.paging.PagedAsyncStream;
import com.azure.android.core.util.AsyncStreamHandler;
import com.azure.android.core.util.RequestContext;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.messaging.FirebaseMessaging;
import com.jakewharton.threetenabp.AndroidThreeTen;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Queue;
import java.util.StringJoiner;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java9.util.function.Consumer;
public class MainActivity extends AppCompatActivity {
private ChatAsyncClient chatAsyncClient;
private ChatThreadAsyncClient chatThreadAsyncClient;
private int eventHandlerCalled;
private String threadId = "<to-be-updated-below>";
private String chatMessageId = "<to-be-updated-below>";
private final Queue<String> unreadMessages = new ConcurrentLinkedQueue<>();
private static Map<RealTimeNotificationCallback, ChatEventType> realTimeNotificationCallbacks = new HashMap<>();
private BroadcastReceiver firebaseMessagingReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
ChatPushNotification pushNotification =
(ChatPushNotification) intent.getParcelableExtra("PushNotificationPayload");
Log.d(TAG, "Push Notification received in MainActivity: " + pushNotification.getPayload());
boolean isHandled = chatAsyncClient.handlePushNotification(pushNotification);
if (!isHandled) {
Log.d(TAG, "No listener registered for incoming push notification!");
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AndroidThreeTen.init(this);
createChatAsyncClient();
LocalBroadcastManager
.getInstance(this)
.registerReceiver(
firebaseMessagingReceiver,
new IntentFilter("com.azure.android.communication.chat.sampleapp.pushnotification"));
}
public void createChatAsyncClient() {
try {
chatAsyncClient = new ChatClientBuilder()
.endpoint(ACS_ENDPOINT)
.credential(COMMUNICATION_TOKEN_CREDENTIAL)
.addPolicy(new UserAgentPolicy(APPLICATION_ID, SDK_NAME, SDK_VERSION))
.httpLogOptions(new HttpLogOptions()
.setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)
.addAllowedHeaderName("MS-CV"))
.buildAsyncClient();
Log.d(TAG, "Created ChatAsyncClient");
} catch (Exception e) {
Log.e("ChatAsyncClient creation failed", Objects.requireNonNull(e.getMessage()));
}
}
public void createChatThreadAsyncClient() {
if (chatAsyncClient == null) {
createChatAsyncClient();
}
// A list of participants to start the thread with.
List<ChatParticipant> participants = new ArrayList<>();
// The display name for the thread participant.
String displayName = "First participant";
participants.add(new ChatParticipant()
.setCommunicationIdentifier(new CommunicationUserIdentifier(FIRST_USER_ID))
.setDisplayName(displayName));
// The topic for the thread.
final String topic = "General";
// Optional, set a repeat request ID.
final String repeatabilityRequestID = "";
// Options to pass to the create method.
CreateChatThreadOptions createChatThreadOptions = new CreateChatThreadOptions()
.setTopic(topic)
.setParticipants(participants)
.setIdempotencyToken(repeatabilityRequestID);
try {
CreateChatThreadResult createChatThreadResult =
chatAsyncClient.createChatThread(createChatThreadOptions).get();
ChatThreadProperties chatThreadProperties = createChatThreadResult.getChatThreadProperties();
threadId = chatThreadProperties.getId();
logAndToast("Created thread with ID: " + threadId);
chatThreadAsyncClient = chatAsyncClient.getChatThreadClient(threadId);
Log.d(TAG, "Created ChatThreadAsyncClient");
} catch (InterruptedException | ExecutionException e) {
Log.e("ChatThreadAsyncClient creation failed", Objects.requireNonNull(e.getMessage()));
}
}
private void logAndToast(String msg) {
Log.d(TAG, msg);
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
public void startPushNotification(View view) {
logAndToast( "Start push notification");
try {
startFcmPushNotification();
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
public void registerPushNotificationListener(View view) {
logAndToast("Register push notification listeners");
try {
chatAsyncClient.addPushNotificationHandler(CHAT_MESSAGE_RECEIVED, (ChatEvent payload) -> {
Log.i(TAG, "Push Notification CHAT_MESSAGE_RECEIVED.");
ChatMessageReceivedEvent event = (ChatMessageReceivedEvent) payload;
Log.i(TAG, "Message received!"
+ " ThreadId: " + event.getChatThreadId()
+ " MessageId: " + event.getId()
+ " Content: " + event.getContent()
+ " Priority: " + event.getPriority()
+ " SenderDisplayName: " + event.getSenderDisplayName()
+ " SenderMri: " + ((CommunicationUserIdentifier)event.getSender()).getId()
+ " Version: " + event.getVersion()
+ " CreatedOn: " + event.getCreatedOn()
+ " Type: " + event.getType()
+ " RecipientMri: " + ((CommunicationUserIdentifier)event.getRecipient()).getId()
);
});
chatAsyncClient.addPushNotificationHandler(CHAT_MESSAGE_EDITED, (ChatEvent payload) -> {
Log.i(TAG, "Push Notification CHAT_MESSAGE_EDITED.");
ChatMessageEditedEvent event = (ChatMessageEditedEvent) payload;
Log.i(TAG, "Message edited!"
+ " ThreadId: " + event.getChatThreadId()
+ " MessageId: " + event.getId()
+ " Content: " + event.getContent()
+ " SenderDisplayName: " + event.getSenderDisplayName()
+ " SenderMri: " + ((CommunicationUserIdentifier)event.getSender()).getId()
+ " Version: " + event.getVersion()
+ " CreatedOn: " + event.getCreatedOn()
+ " EditedOn: " + event.getEditedOn()
+ " RecipientMri: " + ((CommunicationUserIdentifier)event.getRecipient()).getId()
);
});
chatAsyncClient.addPushNotificationHandler(CHAT_MESSAGE_DELETED, (ChatEvent payload) -> {
Log.i(TAG, "Push Notification CHAT_MESSAGE_DELETED.");
ChatMessageDeletedEvent event = (ChatMessageDeletedEvent) payload;
Log.i(TAG, "Message deleted!"
+ " ThreadId: " + event.getChatThreadId()
+ " MessageId: " + event.getId()
+ " SenderDisplayName: " + event.getSenderDisplayName()
+ " SenderMri: " + ((CommunicationUserIdentifier)event.getSender()).getId()
+ " Version: " + event.getVersion()
+ " CreatedOn: " + event.getCreatedOn()
+ " DeletedOn: " + event.getDeletedOn()
+ " RecipientMri: " + ((CommunicationUserIdentifier)event.getRecipient()).getId()
);
});
chatAsyncClient.addPushNotificationHandler(CHAT_THREAD_CREATED, (ChatEvent payload) -> {
Log.i(TAG, "Push Notification CHAT_THREAD_CREATED.");
ChatThreadCreatedEvent event = (ChatThreadCreatedEvent) payload;
Log.i(TAG, "Thread Created!"
+ " ThreadId: " + event.getChatThreadId()
+ " Properties_Id: " + event.getProperties().getId()
+ " Properties_Topic: " + event.getProperties().getTopic()
+ " Properties_CreatedOn: " + event.getProperties().getCreatedOn()
+ " Properties_CreatedByMri: " + ((CommunicationUserIdentifier)event.getProperties().getCreatedByCommunicationIdentifier()).getId()
+ " Participants_size: " + event.getParticipants().size()
+ " Version: " + event.getVersion()
+ " CreatedOn: " + event.getCreatedOn()
+ " CreatedBy_DisplayName: " + event.getCreatedBy().getDisplayName()
+ " CreatedBy_Mri: " + ((CommunicationUserIdentifier)event.getCreatedBy().getCommunicationIdentifier()).getId()
);
});
chatAsyncClient.addPushNotificationHandler(CHAT_THREAD_PROPERTIES_UPDATED, (ChatEvent payload) -> {
Log.i(TAG, "Push Notification CHAT_THREAD_PROPERTIES_UPDATED.");
ChatThreadPropertiesUpdatedEvent event = (ChatThreadPropertiesUpdatedEvent) payload;
Log.i(TAG, "Thread Updated!"
+ " ThreadId: " + event.getChatThreadId()
+ " Properties_Id: " + event.getProperties().getId()
+ " Properties_Topic: " + event.getProperties().getTopic()
+ " Version: " + event.getVersion()
+ " UpdatedOn: " + event.getUpdatedOn()
+ " UpdatedBy_DisplayName: " + event.getUpdatedBy().getDisplayName()
+ " UpdatedBy_Mri: " + ((CommunicationUserIdentifier)event.getUpdatedBy().getCommunicationIdentifier()).getId()
);
});
chatAsyncClient.addPushNotificationHandler(CHAT_THREAD_DELETED, (ChatEvent payload) -> {
Log.i(TAG, "Push Notification CHAT_THREAD_DELETED.");
ChatThreadDeletedEvent event = (ChatThreadDeletedEvent) payload;
Log.i(TAG, "Thread Deleted!"
+ " ThreadId: " + event.getChatThreadId()
+ " Version: " + event.getVersion()
+ " DeletedOn: " + event.getDeletedOn()
+ " DeletedBy_DisplayName: " + event.getDeletedBy().getDisplayName()
+ " DeletedBy_Mri: " + ((CommunicationUserIdentifier)event.getDeletedBy().getCommunicationIdentifier()).getId()
);
});
chatAsyncClient.addPushNotificationHandler(PARTICIPANTS_ADDED, (ChatEvent payload) -> {
Log.i(TAG, "Push Notification PARTICIPANTS_ADDED.");
ParticipantsAddedEvent event = (ParticipantsAddedEvent) payload;
Log.i(TAG, "Participant Added!"
+ " ThreadId: " + event.getChatThreadId()
+ " ParticipantsAdded_size: " + event.getParticipantsAdded().size()
+ " Version: " + event.getVersion()
+ " AddedOn: " + event.getAddedOn()
+ " AddedBy_DisplayName: " + event.getAddedBy().getDisplayName()
+ " AddedBy_Mri: " + ((CommunicationUserIdentifier)event.getAddedBy().getCommunicationIdentifier()).getId()
);
});
chatAsyncClient.addPushNotificationHandler(PARTICIPANTS_REMOVED, (ChatEvent payload) -> {
Log.i(TAG, "Push Notification PARTICIPANTS_REMOVED.");
ParticipantsRemovedEvent event = (ParticipantsRemovedEvent) payload;
Log.i(TAG, "Participant Removed!"
+ " ThreadId: " + event.getChatThreadId()
+ " ParticipantsRemoved_size: " + event.getParticipantsRemoved().size()
+ " Version: " + event.getVersion()
+ " RemovedOn: " + event.getRemovedOn()
+ " RemovedBy_DisplayName: " + event.getRemovedBy().getDisplayName()
+ " RemovedBy_Mri: " + ((CommunicationUserIdentifier)event.getRemovedBy().getCommunicationIdentifier()).getId()
);
});
} catch (IllegalStateException error) {
Log.i(TAG, "Push Notification not start yet.");
}
}
public void stopPushNotification(View view) {
logAndToast( "Stop push notification");
try {
stopFcmPushNotification();
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
public void startRealTimeNotification(View view) {
logAndToast( "Starting realtime notification");
try {
chatAsyncClient.startRealtimeNotifications(getApplicationContext(), new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) {
Log.e(TAG, "Renew realtime notification registration failed!", throwable);
}
});
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
public void registerRealTimeNotificationListener(View view) {
logAndToast("Register a test listener");
RealTimeNotificationCallback messageReceivedHandler = (ChatEvent payload) -> {
eventHandlerCalled++;
Log.i(TAG, eventHandlerCalled + " messages handled.");
ChatMessageReceivedEvent event = (ChatMessageReceivedEvent) payload;
Log.i(TAG, "Message created! ThreadId: " + event.getChatThreadId());
};
chatAsyncClient.addEventHandler(CHAT_MESSAGE_RECEIVED, messageReceivedHandler);
realTimeNotificationCallbacks.put(messageReceivedHandler, CHAT_MESSAGE_RECEIVED);
RealTimeNotificationCallback messageEditedHandler = (ChatEvent payload) -> {
eventHandlerCalled++;
Log.i(TAG, eventHandlerCalled + " messages handled.");
ChatMessageEditedEvent event = (ChatMessageEditedEvent) payload;
Log.i(TAG, "Message edited! ThreadId: " + event.getChatThreadId());
};
chatAsyncClient.addEventHandler(CHAT_MESSAGE_EDITED, messageEditedHandler);
realTimeNotificationCallbacks.put(messageEditedHandler, CHAT_MESSAGE_EDITED);
RealTimeNotificationCallback messageDeletedHandler = (ChatEvent payload) -> {
eventHandlerCalled++;
Log.i(TAG, eventHandlerCalled + " messages handled.");
ChatMessageDeletedEvent event = (ChatMessageDeletedEvent) payload;
Log.i(TAG, "Message deleted! ThreadId: " + event.getChatThreadId());
};
chatAsyncClient.addEventHandler(CHAT_MESSAGE_DELETED, messageDeletedHandler);
realTimeNotificationCallbacks.put(messageDeletedHandler, CHAT_MESSAGE_DELETED);
RealTimeNotificationCallback typingIndicatorHandler = (ChatEvent payload) -> {
eventHandlerCalled++;
Log.i(TAG, eventHandlerCalled + " messages handled.");
TypingIndicatorReceivedEvent event = (TypingIndicatorReceivedEvent) payload;
Log.i(TAG, "Typing indicator received! ThreadId: " + event.getChatThreadId());
};
chatAsyncClient.addEventHandler(TYPING_INDICATOR_RECEIVED, typingIndicatorHandler);
realTimeNotificationCallbacks.put(typingIndicatorHandler, TYPING_INDICATOR_RECEIVED);
RealTimeNotificationCallback readReceiptHandler = (ChatEvent payload) -> {
eventHandlerCalled++;
Log.i(TAG, eventHandlerCalled + " messages handled.");
ReadReceiptReceivedEvent event = (ReadReceiptReceivedEvent) payload;
Log.i(TAG, "Read receipt received! ThreadId: " + event.getChatThreadId());
};
chatAsyncClient.addEventHandler(READ_RECEIPT_RECEIVED, readReceiptHandler);
realTimeNotificationCallbacks.put(readReceiptHandler, READ_RECEIPT_RECEIVED);
RealTimeNotificationCallback threadCreatedHandler = (ChatEvent payload) -> {
eventHandlerCalled++;
Log.i(TAG, eventHandlerCalled + " messages handled.");
ChatThreadCreatedEvent event = (ChatThreadCreatedEvent) payload;
Log.i(TAG, "Chat thread created! ThreadId: " + event.getChatThreadId());
};
chatAsyncClient.addEventHandler(CHAT_THREAD_CREATED, threadCreatedHandler);
realTimeNotificationCallbacks.put(threadCreatedHandler, CHAT_THREAD_CREATED);
RealTimeNotificationCallback threadDeletedHandler = (ChatEvent payload) -> {
eventHandlerCalled++;
Log.i(TAG, eventHandlerCalled + " messages handled.");
ChatThreadDeletedEvent event = (ChatThreadDeletedEvent) payload;
Log.i(TAG, "Chat thread deleted! ThreadId: " + event.getChatThreadId());
};
chatAsyncClient.addEventHandler(CHAT_THREAD_DELETED, threadDeletedHandler);
realTimeNotificationCallbacks.put(threadDeletedHandler, CHAT_THREAD_DELETED);
RealTimeNotificationCallback threadUpdatedHandler = (ChatEvent payload) -> {
eventHandlerCalled++;
Log.i(TAG, eventHandlerCalled + " messages handled.");
ChatThreadPropertiesUpdatedEvent event = (ChatThreadPropertiesUpdatedEvent) payload;
Log.i(TAG, "Chat thread properties updated! ThreadId: " + event.getChatThreadId());
};
chatAsyncClient.addEventHandler(CHAT_THREAD_PROPERTIES_UPDATED, threadUpdatedHandler);
realTimeNotificationCallbacks.put(threadUpdatedHandler, CHAT_THREAD_PROPERTIES_UPDATED);
RealTimeNotificationCallback participantAddedHandler = (ChatEvent payload) -> {
eventHandlerCalled++;
Log.i(TAG, eventHandlerCalled + " messages handled.");
ParticipantsAddedEvent event = (ParticipantsAddedEvent) payload;
Log.i(TAG, "Participants added! ThreadId: " + event.getChatThreadId());
};
chatAsyncClient.addEventHandler(PARTICIPANTS_ADDED, participantAddedHandler);
realTimeNotificationCallbacks.put(participantAddedHandler, PARTICIPANTS_ADDED);
RealTimeNotificationCallback participantRemovedHandler = (ChatEvent payload) -> {
eventHandlerCalled++;
Log.i(TAG, eventHandlerCalled + " messages handled.");
ParticipantsRemovedEvent event = (ParticipantsRemovedEvent) payload;
Log.i(TAG, "Participants removed! ThreadId: " + event.getChatThreadId());
};
chatAsyncClient.addEventHandler(PARTICIPANTS_REMOVED, participantRemovedHandler);
realTimeNotificationCallbacks.put(participantRemovedHandler, PARTICIPANTS_REMOVED);
}
public void unregisterRealTimeNotificationListener(View view) {
logAndToast("Unregister realtime notification listeners");
for (Map.Entry<RealTimeNotificationCallback, ChatEventType> entry: realTimeNotificationCallbacks.entrySet()) {
chatAsyncClient.removeEventHandler(entry.getValue(), entry.getKey());
}
realTimeNotificationCallbacks.clear();
}
public void sendChatMessage(View view) {
if (chatThreadAsyncClient == null) {
createChatThreadAsyncClient();
}
if (chatThreadAsyncClient != null) {
// The chat message content, required.
final String content = "Test message 1";
// The display name of the sender, if null (i.e. not specified), an empty name will be set.
final String senderDisplayName = "First participant";
SendChatMessageOptions chatMessageOptions = new SendChatMessageOptions()
.setType(ChatMessageType.TEXT)
.setContent(content)
.setSenderDisplayName(senderDisplayName)
.setMetadata(new HashMap<String, String>() {
{
put("tags", "tag1");
put("deliveryMode", "deliveryMode value");
}
});
// A string is the response returned from sending a message, it is an id, which is the unique ID of the
// message.
try {
chatMessageId = chatThreadAsyncClient.sendMessage(chatMessageOptions).get().getId();
unreadMessages.add(chatMessageId);
logAndToast("Message sent with ID: " + chatMessageId);
} catch (InterruptedException | ExecutionException e) {
logAndToast("Send message failed: " + e.getMessage());
}
} else {
logAndToast("ChatThreadAsyncClient creation failed");
}
}
public void addParticipant(View view) {
if (chatThreadAsyncClient == null) {
createChatThreadAsyncClient();
}
if (chatThreadAsyncClient != null) {
// The display name for the thread participant.
String secondUserDisplayName = "Second participant";
try {
chatThreadAsyncClient.addParticipant(new ChatParticipant().setCommunicationIdentifier(
new CommunicationUserIdentifier(SECOND_USER_ID)).setDisplayName(secondUserDisplayName)).get();
logAndToast("Added chat participant");
} catch (InterruptedException | ExecutionException e) {
logAndToast("Add user failed: " + e.getMessage());
}
} else {
logAndToast("ChatThreadAsyncClient creation failed");
}
}
public void listParticipants(View view) {
if (chatThreadAsyncClient == null) {
createChatThreadAsyncClient();
}
if (chatThreadAsyncClient != null) {
// The maximum number of participants to be returned per page, optional.
int maxPageSize = 10;
// Skips participants up to a specified position in response.
int skip = 0;
// Options to pass to the list method.
ListParticipantsOptions listParticipantsOptions = new ListParticipantsOptions()
.setMaxPageSize(maxPageSize)
.setSkip(skip);
try {
PagedAsyncStream<ChatParticipant> participantPagedAsyncStream
= chatThreadAsyncClient.listParticipants(new ListParticipantsOptions(), null);
StringJoiner participantsStringJoiner =
new StringJoiner(
"\nParticipant: ",
"",
""
);
CountDownLatch latch = new CountDownLatch(1);
participantPagedAsyncStream.forEach(new AsyncStreamHandler<ChatParticipant>() {
@Override
public void onNext(ChatParticipant participant) {
participantsStringJoiner.add(participant.getDisplayName());
}
@Override
public void onError(Throwable throwable) {
latch.countDown();
}
@Override
public void onComplete() {
latch.countDown();
}
});
awaitOnLatch(latch);
logAndToast(participantsStringJoiner.toString());
} catch (Exception e) {
logAndToast("Listing participants failed: " + e.getMessage());
}
} else {
logAndToast("ChatThreadAsyncClient creation failed");
}
}
public void removeParticipant(View view) {
if (chatThreadAsyncClient == null) {
createChatThreadAsyncClient();
}
if (chatThreadAsyncClient != null) {
try {
// Using the unique ID of the participant.
chatThreadAsyncClient.removeParticipant(new CommunicationUserIdentifier(SECOND_USER_ID)).get();
logAndToast("Removed second participant");
} catch (InterruptedException | ExecutionException e) {
logAndToast("Remove user failed: " + e.getMessage());
}
} else {
logAndToast("ChatThreadAsyncClient creation failed");
}
}
public void sendTypingNotification(View view) {
if (chatThreadAsyncClient == null) {
createChatThreadAsyncClient();
}
if (chatThreadAsyncClient != null) {
try {
TypingNotificationOptions options = new TypingNotificationOptions();
options.setSenderDisplayName("Sender Display Name");
chatThreadAsyncClient.sendTypingNotificationWithResponse(options, RequestContext.NONE).get();
logAndToast("Sent a typing notification successfully");
} catch (InterruptedException | ExecutionException e) {
logAndToast("Send typing notification failed: " + e.getMessage());
}
} else {
logAndToast("ChatThreadAsyncClient creation failed");
}
}
public void sendReadReceipts(View view) {
if (chatThreadAsyncClient == null) {
createChatThreadAsyncClient();
}
if (chatThreadAsyncClient != null) {
try {
for (String unreadMessageId : unreadMessages) {
chatThreadAsyncClient.sendReadReceipt(unreadMessageId).get();
unreadMessages.poll();
logAndToast("Sent a read receipt for message with ID: " + unreadMessageId);
}
} catch (InterruptedException | ExecutionException e) {
logAndToast("Send read receipt failed: " + e.getMessage());
}
} else {
logAndToast("ChatThreadAsyncClient creation failed");
}
}
public void listReadReceipts(View view) {
if (chatThreadAsyncClient == null) {
createChatThreadAsyncClient();
}
if (chatThreadAsyncClient != null) {
// The maximum number of read receipts to be returned per page, optional.
int maxPageSize = 10;
// Skips participants up to a specified position in response.
int skip = 0;
// Options to pass to the list method.
ListReadReceiptOptions listReadReceiptOptions = new ListReadReceiptOptions()
.setMaxPageSize(maxPageSize)
.setSkip(skip);
try {
PagedAsyncStream<ChatMessageReadReceipt> readReceipts =
chatThreadAsyncClient.listReadReceipts(listReadReceiptOptions, RequestContext.NONE);
readReceipts.forEach(readReceipt -> {
Log.d(TAG, "Got receipt for participant "
+ ((CommunicationUserIdentifier)readReceipt.getSenderCommunicationIdentifier()).getId()
+ " for message with id: "
+ readReceipt.getChatMessageId());
});
} catch (Exception e) {
logAndToast("Listing read receipts failed: " + e.getMessage());
}
} else {
logAndToast("ChatThreadAsyncClient creation failed");
}
}
private void startFcmPushNotification() {
FirebaseMessaging.getInstance().getToken()
.addOnCompleteListener(new OnCompleteListener<String>() {
@Override
public void onComplete(@NonNull Task<String> task) {
if (!task.isSuccessful()) {
Log.w(TAG, "Fetching FCM registration token failed", task.getException());
return;
}
// Get new FCM registration token
String token = task.getResult();
// Log and toast
Log.d(TAG, "Fcm push token generated:" + token);
Toast.makeText(MainActivity.this, token, Toast.LENGTH_SHORT).show();
chatAsyncClient.startPushNotifications(token);
}
});
}
private void stopFcmPushNotification() {
chatAsyncClient.stopPushNotifications();
}
private static void awaitOnLatch(CountDownLatch latch) {
long timeoutInSec = 2;
try {
latch.await(timeoutInSec, TimeUnit.MINUTES);
} catch (InterruptedException e) {
Log.e(TAG, "List operation didn't complete within " + timeoutInSec + " minutes");
}
}
}
| 33,538 | 0.639901 | 0.639573 | 701 | 46.843082 | 33.114178 | 151 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.600571 | false | false | 6 |
ec50d06ed5764abd643c29adbb73b83f0f6ba8fe | 22,058,952,092,951 | 276d8c56df58da1b269a7b6109bf112d404cc5d2 | /core/src/main/java/com/company/modules/common/action/PubContractAttachmentAction.java | 58c602abe69c23300922af6b32c05c7f71c1d5ed | [] | no_license | ybak/loan | https://github.com/ybak/loan | b1e2fd92492e7605a56a8e52c5a964ee9ed3be3f | 06ba5276a5bbba577e96942150822a5dbd739a69 | refs/heads/master | 2021-03-24T01:34:02.487000 | 2018-11-03T14:08:32 | 2018-11-03T14:08:32 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.company.modules.common.action;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.alibaba.fastjson.JSONObject;
import com.company.common.context.Constant;
import com.company.common.utils.JsonUtil;
import com.company.common.utils.ServletUtils;
import com.company.common.utils.upload.HttpServletRequestProxy;
import com.company.common.utils.upload.ProgressUtil;
import com.company.common.utils.upload.RenamePolicyCos;
import com.company.common.web.action.BaseAction;
import com.company.modules.common.domain.PubContractAttachment;
import com.company.modules.common.exception.ServiceException;
import com.company.modules.common.service.PubContractAttachmentService;
import com.company.modules.common.utils.ZipUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.oreilly.servlet.MultipartRequest;
/**
* User: wulb DateTime:2016-08-29 10:50:06 details: 合同附件信息,Action请求层 source:
* 代码生成器
*/
@RequestMapping("/modules/common/PubContractAttachmentAction")
@Controller
public class PubContractAttachmentAction extends BaseAction {
private Logger logger = LoggerFactory.getLogger(PubContractAttachmentAction.class);
/**
* 合同附件信息的Service
*/
@Autowired
private PubContractAttachmentService pubContractAttachmentService;
/**
* 分页查询数据
*
* @param request
* 页面的request
* @param response
* 页面的response
* @param currentPage
* 当前页数
* @param pageSize
* 每页限制
* @param searchParams
* 查询条件
* @throws Exception
*/
@SuppressWarnings("unchecked")
@RequestMapping("/query.htm")
public void query(HttpServletResponse response, HttpServletRequest request,
@RequestParam(value = "currentPage") Integer currentPage,
@RequestParam(value = "pageSize") Integer pageSize,
@RequestParam(value = "searchParams", required = false) String searchParams) throws Exception {
// 返回给页面的Map
Map<String, Object> returnMap = new HashMap<String, Object>();
Map<String, Object> paramap = new HashMap<>();
// 对json对象进行转换
if (!StringUtils.isEmpty(searchParams)) {
paramap = JsonUtil.parse(searchParams, Map.class);
}
PageHelper.startPage(currentPage, pageSize);
List<PubContractAttachment> pubContractAttachments = pubContractAttachmentService.getPageListByMap(paramap);
PageInfo<PubContractAttachment> page = new PageInfo<PubContractAttachment>(pubContractAttachments);
returnMap.put(Constant.RESPONSE_DATA, page.getList());
returnMap.put(Constant.RESPONSE_DATA_TOTALCOUNT, page.getTotal());
returnMap.put(Constant.RESPONSE_CODE, Constant.SUCCEED_CODE_VALUE);
returnMap.put(Constant.RESPONSE_CODE_MSG, Constant.OPERATION_SUCCESS);
// 返回给页面
ServletUtils.writeToResponse(response, returnMap);
}
/**
* 查询所有,不包含分页
*
* @param search
* @param request
* @param response
* @throws Exception
*/
@SuppressWarnings("unchecked")
@RequestMapping(value = "/queryAll.htm")
public void query3(@RequestParam(value = "search") String search, HttpServletRequest request,
HttpServletResponse response) throws Exception {
Map<String, Object> params = JsonUtil.parse(search, Map.class);
List<PubContractAttachment> files = pubContractAttachmentService.getPageListByMap(params);
Map<String, Object> res = new HashMap<String, Object>();
res.put(Constant.RESPONSE_CODE, Constant.SUCCEED_CODE_VALUE);
res.put(Constant.RESPONSE_DATA, files);
ServletUtils.writeToResponse(response, res);
}
/**
* 附件上传带进度
*
* @param request
* @param response
* @throws IOException
*/
@RequestMapping(value = "/progress.htm")
public void getProgress(HttpServletRequest request, HttpServletResponse response) throws IOException {
String progressId = request.getParameter("progressId");
Map<String, Object> responseMap = new HashMap<String, Object>();
if (progressId == null || "".equals(progressId)) {
responseMap.put("success", "false");
responseMap.put("progress", "0");
return;
}
String percent = "0";
if (ProgressUtil.progressMap.get(progressId) == null) {
logger.info("progressMethod 未查找到 progressId=" + progressId);
ProgressUtil.progressMap.put(progressId, 0);
} else {
percent = String.valueOf(ProgressUtil.progressMap.get(progressId));
}
responseMap.put("success", "true");
responseMap.put("progress", percent);
com.company.common.utils.ServletUtils.writeToResponse(response, responseMap);
}
@RequestMapping(value = "/getfilesize.htm")
public void getFilesize(HttpServletRequest request, HttpServletResponse response) throws IOException {
Integer filesize = request.getContentLength();
Map<String, Object> responseMap = new HashMap<String, Object>();
responseMap.put("success", "true");
responseMap.put("filesize", String.valueOf(filesize));
com.company.common.utils.ServletUtils.writeToResponse(response, responseMap);
}
/**
* 附件上传
*
* @param request
* @param response
* @throws Exception
*/
@SuppressWarnings({ "unchecked", "deprecation" })
@RequestMapping(value = "/upload.htm")
public void upload(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
// 设置上传文件的大小,超过这个大小 将抛出IOException异常,默认大小是1M。
int inmaxPostSize = 200 * 1024 * 1024;
MultipartRequest multirequest = null;
RenamePolicyCos myRenamePolicyCos = new RenamePolicyCos();
HttpServletRequestProxy srp = new HttpServletRequestProxy(request);
multirequest = new MultipartRequest(srp, getSaveDir(request).getAbsolutePath(), inmaxPostSize, "utf8",
myRenamePolicyCos);
Enumeration<String> filedFileNames = multirequest.getFileNames();
logger.info(" upload:");
logger.info(JsonUtil.toString(multirequest));
// 返回数据
Map<String, Object> result = new HashMap<String, Object>();
if (null != filedFileNames && filedFileNames.hasMoreElements()) {
String fieldName = filedFileNames.nextElement();
File uploadFile = multirequest.getFile(fieldName);
String uri = com.company.common.utils.StringUtil.getRelativePath(uploadFile,
new File(request.getSession().getServletContext().getRealPath("/")));
Map<String, Object> data = JSONObject.parseObject(multirequest.getParameter("data"), Map.class);
PubContractAttachment attachment = new PubContractAttachment();
byte state = 1;
attachment.setState(state);
attachment.setFilePath(uri);
attachment.setFileName(multirequest.getOriginalFileName(fieldName));
attachment.setNewfileName(uploadFile.getName());
attachment.setFileSize(new BigDecimal(uploadFile.length()).divide(new BigDecimal(1024))
.setScale(0, RoundingMode.CEILING).longValue());
attachment.setCreateTime(new Date());
attachment.setCreator(this.getLoginUser(request).getId());
attachment.setEffectiveNode(Long.valueOf(String.valueOf(data.get("effectiveNode"))));
attachment.setName(String.valueOf(data.get("name")));
attachment.setState(Byte.valueOf(String.valueOf(data.get("state"))));
pubContractAttachmentService.insert(attachment);
result.put("id", attachment.getId());
result.put("createtime", attachment.getCreateTime());
result.put("uri", uri);
} else {
throw new RuntimeException("没有文件可上传");
}
Map<String, Object> res = new HashMap<String, Object>();
res.put(Constant.RESPONSE_CODE, Constant.SUCCEED_CODE_VALUE);
res.put(Constant.RESPONSE_DATA, result);
res.put("success", true);
ServletUtils.writeToResponse(response, res);
}
private File getSaveDir(String dirName, HttpServletRequest request) {
if (dirName == null)
dirName = new SimpleDateFormat("yyyy-MM").format(new Date());
final File fileDir = new File(request.getSession().getServletContext().getRealPath("/Contract/" + dirName));
if (!fileDir.exists()) {
fileDir.mkdirs();
}
return fileDir;
}
private File getSaveDir(HttpServletRequest request) {
return getSaveDir(null, request);
}
/**
* 附件批量删除
*
* @param request
* @param response
* @param ids
* @throws Exception
*/
@RequestMapping(value = "/delete.htm")
public void delete(HttpServletRequest request, HttpServletResponse response,
@RequestParam(value = "id", required = true) Long id) throws Exception {
Map<String, Object> res = new HashMap<String, Object>();
int count = 0;
PubContractAttachment pubContractAttachment = pubContractAttachmentService.getItemInfoById(id);
if(pubContractAttachment.getState() == 1){
throw new ServiceException("启用状态下的合同模板不能删除!");
}else{
String path = pubContractAttachment.getFilePath();
if (path != null) {
File f = new File(new File(request.getSession().getServletContext().getRealPath("/")), path.toString());
if (f.exists()) {
f.delete();
}
}
count = pubContractAttachmentService.deleteById(id);
}
if (count > 0) {
res.put(Constant.RESPONSE_CODE, Constant.SUCCEED_CODE_VALUE);
res.put(Constant.RESPONSE_CODE_MSG, Constant.OPERATION_SUCCESS);
} else {
res.put(Constant.RESPONSE_CODE, Constant.FAIL_CODE_VALUE);
res.put(Constant.RESPONSE_CODE_MSG, Constant.OPERATION_FAIL);
}
ServletUtils.writeToResponse(response, res);
}
/**
* 合同模板打包下载
* @param request
* @param response
* @param search
* @param fileExistCheck
* @throws Exception
*/
@SuppressWarnings("all")
@RequestMapping(value = "/downloadZip.htm")
public void downloadZip(HttpServletRequest request, HttpServletResponse response,
@RequestParam(value = "search") String search,
@RequestParam(value = "fileExistCheck", defaultValue = "false") boolean fileExistCheck) throws Exception {
Map<String, Object> param = JsonUtil.parse(search, Map.class);
List<PubContractAttachment> list = pubContractAttachmentService.getPageListByMap(param);
String appDir = request.getSession().getServletContext().getRealPath("/");
if (fileExistCheck) {
List<File> notExists = new ArrayList<File>();
for (PubContractAttachment rec : list) {
File file = new File(appDir, rec.getFilePath());
if (!file.exists())
notExists.add(file);
}
Map result = new HashMap();
result.put("success", list.size() > 0 && notExists.size() == 0);
result.put("fileSurvivalCnt", list.size() - notExists.size());
if (list.size() == 0 || notExists.size() > 0) {
String info = "共<span style='color:red'>" + list.size() + "</span>个文件,有<span style='color:red'>"
+ notExists.size() + "</span>个文件已被删除,";
info += notExists.size() == list.size() ? "没有文件可下载!" : "是否确认下载?";
result.put(Constant.RESPONSE_CODE_MSG, info);
} else {
result.put(Constant.RESPONSE_CODE_MSG, "文件正常");
}
ServletUtils.writeToResponse(response, result);
} else {
String name = new String(("合同.zip").getBytes("gbk"), "iso8859-1");
response.setHeader("Content-Disposition", "attachment;filename=" + name);
List<File> files = new ArrayList<File>();
for (PubContractAttachment rec : list) {
File file = new File(appDir, rec.getFilePath());
if (file.exists()) {
files.add(file);
}
}
ZipUtil.zipFiles4j(files, response.getOutputStream());
}
}
@RequestMapping("/download/isFileExists")
public void isFileExists(String filename, HttpServletRequest request, HttpServletResponse response)
throws Exception {
logger.info(" " + request.getSession().getServletContext().getRealPath("/"));
Map<String, Object> res = new HashMap<String, Object>();
String name = filename.replaceFirst("^/Contract", "");
name = "/Contract/" + name;
File file = new File(request.getSession().getServletContext().getRealPath("/"), name);
boolean exists = file.exists();
res.put(Constant.RESPONSE_CODE, Constant.SUCCEED_CODE_VALUE);
res.put("exists", exists);
if (!exists) {
res.put("filename", file.getName());
res.put(Constant.RESPONSE_CODE_MSG, "文件不存在:" + file.getName());
}
ServletUtils.writeToResponse(response, res);
}
@RequestMapping("/download/{dir}/{fileName}")
public void download(@PathVariable("dir") String dir, @PathVariable("fileName") String fileName,
HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("UTF-8");
java.io.BufferedInputStream bis = null;
java.io.BufferedOutputStream bos = null;
String separator = File.separator;
String webRoot = request.getSession().getServletContext().getRealPath("/Contract").replaceAll(separator + "$",
"");
File downLoadFile = new File(webRoot + separator + dir + separator + fileName);
if (!downLoadFile.exists()) {
JSONObject json = new JSONObject();
json.put("success", false);
json.put("msg", "文件不存在:" + fileName);
com.company.common.utils.ServletUtils.writeToResponse(response, json);
}
try {
long fileLength = downLoadFile.length();
response.setContentType("application/x-msdownload;");
response.setHeader("Content-disposition",
"attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
response.setHeader("Content-Length", String.valueOf(fileLength));
bis = new BufferedInputStream(new FileInputStream(downLoadFile));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[4096];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
bis.close();
}
}
}
/**
* 状态修改 -- 启用及禁用
* @param request
* @param response
* @param status
*/
@RequestMapping("/updateState.htm")
public void updateState(HttpServletRequest request, HttpServletResponse response,
@RequestParam(value = "ids[]", required = false) String ids[],
@RequestParam(value = "status", required = false) String status) throws Exception{
Map<String, Object> returnMap = new HashMap<String, Object>();
int successcount = 0;
for (String id : ids) {
long contractId = Long.parseLong(id);
PubContractAttachment pubContractAttachment = pubContractAttachmentService.getItemInfoById(contractId);
byte state = 0;
if(pubContractAttachment != null){
if ("lock".equals(status)) {
pubContractAttachment.setState(state);
} else if ("unlock".equals(status)) {
state=1;
pubContractAttachment.setState(state);
}
pubContractAttachment.setModifier(this.getLoginUser(request).getId());
pubContractAttachment.setModifyTime(new Date());
long count = pubContractAttachmentService.update(pubContractAttachment);
if(count > 0){
successcount ++;
}
}
}
if (successcount == ids.length) {
returnMap.put(Constant.RESPONSE_CODE, Constant.SUCCEED_CODE_VALUE);
returnMap.put(Constant.RESPONSE_CODE_MSG, "修改成功");
} else {
returnMap.put(Constant.RESPONSE_CODE, Constant.FAIL_CODE_VALUE);
returnMap.put(Constant.RESPONSE_CODE_MSG, "修改失败");
}
ServletUtils.writeToResponse(response, returnMap);
}
}
| UTF-8 | Java | 16,103 | java | PubContractAttachmentAction.java | Java | [
{
"context": "om.oreilly.servlet.MultipartRequest;\n\n/**\n * User: wulb DateTime:2016-08-29 10:50:06 details: 合同附件信息,Acti",
"end": 1725,
"score": 0.9996552467346191,
"start": 1721,
"tag": "USERNAME",
"value": "wulb"
}
] | null | [] | package com.company.modules.common.action;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.alibaba.fastjson.JSONObject;
import com.company.common.context.Constant;
import com.company.common.utils.JsonUtil;
import com.company.common.utils.ServletUtils;
import com.company.common.utils.upload.HttpServletRequestProxy;
import com.company.common.utils.upload.ProgressUtil;
import com.company.common.utils.upload.RenamePolicyCos;
import com.company.common.web.action.BaseAction;
import com.company.modules.common.domain.PubContractAttachment;
import com.company.modules.common.exception.ServiceException;
import com.company.modules.common.service.PubContractAttachmentService;
import com.company.modules.common.utils.ZipUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.oreilly.servlet.MultipartRequest;
/**
* User: wulb DateTime:2016-08-29 10:50:06 details: 合同附件信息,Action请求层 source:
* 代码生成器
*/
@RequestMapping("/modules/common/PubContractAttachmentAction")
@Controller
public class PubContractAttachmentAction extends BaseAction {
private Logger logger = LoggerFactory.getLogger(PubContractAttachmentAction.class);
/**
* 合同附件信息的Service
*/
@Autowired
private PubContractAttachmentService pubContractAttachmentService;
/**
* 分页查询数据
*
* @param request
* 页面的request
* @param response
* 页面的response
* @param currentPage
* 当前页数
* @param pageSize
* 每页限制
* @param searchParams
* 查询条件
* @throws Exception
*/
@SuppressWarnings("unchecked")
@RequestMapping("/query.htm")
public void query(HttpServletResponse response, HttpServletRequest request,
@RequestParam(value = "currentPage") Integer currentPage,
@RequestParam(value = "pageSize") Integer pageSize,
@RequestParam(value = "searchParams", required = false) String searchParams) throws Exception {
// 返回给页面的Map
Map<String, Object> returnMap = new HashMap<String, Object>();
Map<String, Object> paramap = new HashMap<>();
// 对json对象进行转换
if (!StringUtils.isEmpty(searchParams)) {
paramap = JsonUtil.parse(searchParams, Map.class);
}
PageHelper.startPage(currentPage, pageSize);
List<PubContractAttachment> pubContractAttachments = pubContractAttachmentService.getPageListByMap(paramap);
PageInfo<PubContractAttachment> page = new PageInfo<PubContractAttachment>(pubContractAttachments);
returnMap.put(Constant.RESPONSE_DATA, page.getList());
returnMap.put(Constant.RESPONSE_DATA_TOTALCOUNT, page.getTotal());
returnMap.put(Constant.RESPONSE_CODE, Constant.SUCCEED_CODE_VALUE);
returnMap.put(Constant.RESPONSE_CODE_MSG, Constant.OPERATION_SUCCESS);
// 返回给页面
ServletUtils.writeToResponse(response, returnMap);
}
/**
* 查询所有,不包含分页
*
* @param search
* @param request
* @param response
* @throws Exception
*/
@SuppressWarnings("unchecked")
@RequestMapping(value = "/queryAll.htm")
public void query3(@RequestParam(value = "search") String search, HttpServletRequest request,
HttpServletResponse response) throws Exception {
Map<String, Object> params = JsonUtil.parse(search, Map.class);
List<PubContractAttachment> files = pubContractAttachmentService.getPageListByMap(params);
Map<String, Object> res = new HashMap<String, Object>();
res.put(Constant.RESPONSE_CODE, Constant.SUCCEED_CODE_VALUE);
res.put(Constant.RESPONSE_DATA, files);
ServletUtils.writeToResponse(response, res);
}
/**
* 附件上传带进度
*
* @param request
* @param response
* @throws IOException
*/
@RequestMapping(value = "/progress.htm")
public void getProgress(HttpServletRequest request, HttpServletResponse response) throws IOException {
String progressId = request.getParameter("progressId");
Map<String, Object> responseMap = new HashMap<String, Object>();
if (progressId == null || "".equals(progressId)) {
responseMap.put("success", "false");
responseMap.put("progress", "0");
return;
}
String percent = "0";
if (ProgressUtil.progressMap.get(progressId) == null) {
logger.info("progressMethod 未查找到 progressId=" + progressId);
ProgressUtil.progressMap.put(progressId, 0);
} else {
percent = String.valueOf(ProgressUtil.progressMap.get(progressId));
}
responseMap.put("success", "true");
responseMap.put("progress", percent);
com.company.common.utils.ServletUtils.writeToResponse(response, responseMap);
}
@RequestMapping(value = "/getfilesize.htm")
public void getFilesize(HttpServletRequest request, HttpServletResponse response) throws IOException {
Integer filesize = request.getContentLength();
Map<String, Object> responseMap = new HashMap<String, Object>();
responseMap.put("success", "true");
responseMap.put("filesize", String.valueOf(filesize));
com.company.common.utils.ServletUtils.writeToResponse(response, responseMap);
}
/**
* 附件上传
*
* @param request
* @param response
* @throws Exception
*/
@SuppressWarnings({ "unchecked", "deprecation" })
@RequestMapping(value = "/upload.htm")
public void upload(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
// 设置上传文件的大小,超过这个大小 将抛出IOException异常,默认大小是1M。
int inmaxPostSize = 200 * 1024 * 1024;
MultipartRequest multirequest = null;
RenamePolicyCos myRenamePolicyCos = new RenamePolicyCos();
HttpServletRequestProxy srp = new HttpServletRequestProxy(request);
multirequest = new MultipartRequest(srp, getSaveDir(request).getAbsolutePath(), inmaxPostSize, "utf8",
myRenamePolicyCos);
Enumeration<String> filedFileNames = multirequest.getFileNames();
logger.info(" upload:");
logger.info(JsonUtil.toString(multirequest));
// 返回数据
Map<String, Object> result = new HashMap<String, Object>();
if (null != filedFileNames && filedFileNames.hasMoreElements()) {
String fieldName = filedFileNames.nextElement();
File uploadFile = multirequest.getFile(fieldName);
String uri = com.company.common.utils.StringUtil.getRelativePath(uploadFile,
new File(request.getSession().getServletContext().getRealPath("/")));
Map<String, Object> data = JSONObject.parseObject(multirequest.getParameter("data"), Map.class);
PubContractAttachment attachment = new PubContractAttachment();
byte state = 1;
attachment.setState(state);
attachment.setFilePath(uri);
attachment.setFileName(multirequest.getOriginalFileName(fieldName));
attachment.setNewfileName(uploadFile.getName());
attachment.setFileSize(new BigDecimal(uploadFile.length()).divide(new BigDecimal(1024))
.setScale(0, RoundingMode.CEILING).longValue());
attachment.setCreateTime(new Date());
attachment.setCreator(this.getLoginUser(request).getId());
attachment.setEffectiveNode(Long.valueOf(String.valueOf(data.get("effectiveNode"))));
attachment.setName(String.valueOf(data.get("name")));
attachment.setState(Byte.valueOf(String.valueOf(data.get("state"))));
pubContractAttachmentService.insert(attachment);
result.put("id", attachment.getId());
result.put("createtime", attachment.getCreateTime());
result.put("uri", uri);
} else {
throw new RuntimeException("没有文件可上传");
}
Map<String, Object> res = new HashMap<String, Object>();
res.put(Constant.RESPONSE_CODE, Constant.SUCCEED_CODE_VALUE);
res.put(Constant.RESPONSE_DATA, result);
res.put("success", true);
ServletUtils.writeToResponse(response, res);
}
private File getSaveDir(String dirName, HttpServletRequest request) {
if (dirName == null)
dirName = new SimpleDateFormat("yyyy-MM").format(new Date());
final File fileDir = new File(request.getSession().getServletContext().getRealPath("/Contract/" + dirName));
if (!fileDir.exists()) {
fileDir.mkdirs();
}
return fileDir;
}
private File getSaveDir(HttpServletRequest request) {
return getSaveDir(null, request);
}
/**
* 附件批量删除
*
* @param request
* @param response
* @param ids
* @throws Exception
*/
@RequestMapping(value = "/delete.htm")
public void delete(HttpServletRequest request, HttpServletResponse response,
@RequestParam(value = "id", required = true) Long id) throws Exception {
Map<String, Object> res = new HashMap<String, Object>();
int count = 0;
PubContractAttachment pubContractAttachment = pubContractAttachmentService.getItemInfoById(id);
if(pubContractAttachment.getState() == 1){
throw new ServiceException("启用状态下的合同模板不能删除!");
}else{
String path = pubContractAttachment.getFilePath();
if (path != null) {
File f = new File(new File(request.getSession().getServletContext().getRealPath("/")), path.toString());
if (f.exists()) {
f.delete();
}
}
count = pubContractAttachmentService.deleteById(id);
}
if (count > 0) {
res.put(Constant.RESPONSE_CODE, Constant.SUCCEED_CODE_VALUE);
res.put(Constant.RESPONSE_CODE_MSG, Constant.OPERATION_SUCCESS);
} else {
res.put(Constant.RESPONSE_CODE, Constant.FAIL_CODE_VALUE);
res.put(Constant.RESPONSE_CODE_MSG, Constant.OPERATION_FAIL);
}
ServletUtils.writeToResponse(response, res);
}
/**
* 合同模板打包下载
* @param request
* @param response
* @param search
* @param fileExistCheck
* @throws Exception
*/
@SuppressWarnings("all")
@RequestMapping(value = "/downloadZip.htm")
public void downloadZip(HttpServletRequest request, HttpServletResponse response,
@RequestParam(value = "search") String search,
@RequestParam(value = "fileExistCheck", defaultValue = "false") boolean fileExistCheck) throws Exception {
Map<String, Object> param = JsonUtil.parse(search, Map.class);
List<PubContractAttachment> list = pubContractAttachmentService.getPageListByMap(param);
String appDir = request.getSession().getServletContext().getRealPath("/");
if (fileExistCheck) {
List<File> notExists = new ArrayList<File>();
for (PubContractAttachment rec : list) {
File file = new File(appDir, rec.getFilePath());
if (!file.exists())
notExists.add(file);
}
Map result = new HashMap();
result.put("success", list.size() > 0 && notExists.size() == 0);
result.put("fileSurvivalCnt", list.size() - notExists.size());
if (list.size() == 0 || notExists.size() > 0) {
String info = "共<span style='color:red'>" + list.size() + "</span>个文件,有<span style='color:red'>"
+ notExists.size() + "</span>个文件已被删除,";
info += notExists.size() == list.size() ? "没有文件可下载!" : "是否确认下载?";
result.put(Constant.RESPONSE_CODE_MSG, info);
} else {
result.put(Constant.RESPONSE_CODE_MSG, "文件正常");
}
ServletUtils.writeToResponse(response, result);
} else {
String name = new String(("合同.zip").getBytes("gbk"), "iso8859-1");
response.setHeader("Content-Disposition", "attachment;filename=" + name);
List<File> files = new ArrayList<File>();
for (PubContractAttachment rec : list) {
File file = new File(appDir, rec.getFilePath());
if (file.exists()) {
files.add(file);
}
}
ZipUtil.zipFiles4j(files, response.getOutputStream());
}
}
@RequestMapping("/download/isFileExists")
public void isFileExists(String filename, HttpServletRequest request, HttpServletResponse response)
throws Exception {
logger.info(" " + request.getSession().getServletContext().getRealPath("/"));
Map<String, Object> res = new HashMap<String, Object>();
String name = filename.replaceFirst("^/Contract", "");
name = "/Contract/" + name;
File file = new File(request.getSession().getServletContext().getRealPath("/"), name);
boolean exists = file.exists();
res.put(Constant.RESPONSE_CODE, Constant.SUCCEED_CODE_VALUE);
res.put("exists", exists);
if (!exists) {
res.put("filename", file.getName());
res.put(Constant.RESPONSE_CODE_MSG, "文件不存在:" + file.getName());
}
ServletUtils.writeToResponse(response, res);
}
@RequestMapping("/download/{dir}/{fileName}")
public void download(@PathVariable("dir") String dir, @PathVariable("fileName") String fileName,
HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("UTF-8");
java.io.BufferedInputStream bis = null;
java.io.BufferedOutputStream bos = null;
String separator = File.separator;
String webRoot = request.getSession().getServletContext().getRealPath("/Contract").replaceAll(separator + "$",
"");
File downLoadFile = new File(webRoot + separator + dir + separator + fileName);
if (!downLoadFile.exists()) {
JSONObject json = new JSONObject();
json.put("success", false);
json.put("msg", "文件不存在:" + fileName);
com.company.common.utils.ServletUtils.writeToResponse(response, json);
}
try {
long fileLength = downLoadFile.length();
response.setContentType("application/x-msdownload;");
response.setHeader("Content-disposition",
"attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
response.setHeader("Content-Length", String.valueOf(fileLength));
bis = new BufferedInputStream(new FileInputStream(downLoadFile));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[4096];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
bis.close();
}
}
}
/**
* 状态修改 -- 启用及禁用
* @param request
* @param response
* @param status
*/
@RequestMapping("/updateState.htm")
public void updateState(HttpServletRequest request, HttpServletResponse response,
@RequestParam(value = "ids[]", required = false) String ids[],
@RequestParam(value = "status", required = false) String status) throws Exception{
Map<String, Object> returnMap = new HashMap<String, Object>();
int successcount = 0;
for (String id : ids) {
long contractId = Long.parseLong(id);
PubContractAttachment pubContractAttachment = pubContractAttachmentService.getItemInfoById(contractId);
byte state = 0;
if(pubContractAttachment != null){
if ("lock".equals(status)) {
pubContractAttachment.setState(state);
} else if ("unlock".equals(status)) {
state=1;
pubContractAttachment.setState(state);
}
pubContractAttachment.setModifier(this.getLoginUser(request).getId());
pubContractAttachment.setModifyTime(new Date());
long count = pubContractAttachmentService.update(pubContractAttachment);
if(count > 0){
successcount ++;
}
}
}
if (successcount == ids.length) {
returnMap.put(Constant.RESPONSE_CODE, Constant.SUCCEED_CODE_VALUE);
returnMap.put(Constant.RESPONSE_CODE_MSG, "修改成功");
} else {
returnMap.put(Constant.RESPONSE_CODE, Constant.FAIL_CODE_VALUE);
returnMap.put(Constant.RESPONSE_CODE_MSG, "修改失败");
}
ServletUtils.writeToResponse(response, returnMap);
}
}
| 16,103 | 0.729343 | 0.724813 | 407 | 37.508598 | 27.929699 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.685504 | false | false | 6 |
79275b97327b1cc38cb9d3d8e1e03f130809945a | 26,302,379,766,421 | 7d5e7d93ab56b4e95fa30093c6e090bb2b836bfe | /spring06/src/main/java/com/jdbc/Book.java | ffd6e64712f475458ea23fb7516f33e3a7466f19 | [] | no_license | haibao1371/SpringG | https://github.com/haibao1371/SpringG | e52fe6cddc132118efde718932f14829b57bd815 | c42b5de0a06348666d6bf5efa9970eb6fc86becb | refs/heads/master | 2022-12-22T05:20:18.321000 | 2021-07-20T14:06:17 | 2021-07-20T14:06:17 | 196,954,577 | 1 | 0 | null | false | 2022-12-16T04:35:33 | 2019-07-15T08:13:15 | 2021-07-20T14:06:20 | 2022-12-16T04:35:32 | 50 | 1 | 0 | 7 | Java | false | false | package com.jdbc;
/**
* 类注释
*
* @author Lenovo
* @Title: Book
* @ProjectName SpringG
* @Description: TODO 写一个Book对象
* @date 2019/7/318:30
*/
public class Book {
private String name;
private String author;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
@Override
public String toString() {
return "Book:" + "[" + name + "," + author + "]";
}
}
| UTF-8 | Java | 621 | java | Book.java | Java | [
{
"context": "package com.jdbc;\n\n/**\n * 类注释\n *\n * @author Lenovo\n * @Title: Book\n * @ProjectName SpringG\n * @Descr",
"end": 50,
"score": 0.9960469007492065,
"start": 44,
"tag": "USERNAME",
"value": "Lenovo"
}
] | null | [] | package com.jdbc;
/**
* 类注释
*
* @author Lenovo
* @Title: Book
* @ProjectName SpringG
* @Description: TODO 写一个Book对象
* @date 2019/7/318:30
*/
public class Book {
private String name;
private String author;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
@Override
public String toString() {
return "Book:" + "[" + name + "," + author + "]";
}
}
| 621 | 0.563636 | 0.547107 | 35 | 16.285715 | 14.11093 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.257143 | false | false | 6 |
7ed3f2142bb2c563e083bea5cd7626e70ad1f0e1 | 38,998,303,072,981 | 958b081ffe4d1fa24aa7c97177a92ee1d178b4d6 | /springTestProject/src/main/java/com/example/controller/StaffController.java | 356c9a5517dc6825f5fea65cc823d93c616a9f72 | [] | no_license | tw-iii-leader-project/SpringTest | https://github.com/tw-iii-leader-project/SpringTest | debcba24b30421050eb4c5cd643902fe14301562 | 1da614a41f94eed1e3ff2b09006ad1f08b78f82d | refs/heads/master | 2023-02-28T15:35:16.521000 | 2021-02-06T17:30:34 | 2021-02-06T17:30:34 | 330,344,742 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.model.StaffModel;
import com.example.service.StaffService;
@RestController
public class StaffController {
@Autowired
StaffModel staffModel;
@Autowired
StaffService staffService;
@RequestMapping("/addStaff")
public String hello() {
staffModel = new StaffModel();
staffModel.setPassword("1234");
staffModel.setEmail("email@email.com");
staffModel.setPhone("22334455");
staffModel.setPosition("Manager");
staffService.addStaff(staffModel);
return "New Staff added";
}
} | UTF-8 | Java | 763 | java | StaffController.java | Java | [
{
"context": "el = new StaffModel();\r\n\t\tstaffModel.setPassword(\"1234\");\r\n\t\tstaffModel.setEmail(\"email@email.com\");\r\n\t\t",
"end": 567,
"score": 0.9992350935935974,
"start": 563,
"tag": "PASSWORD",
"value": "1234"
},
{
"context": "odel.setPassword(\"1234\");\r\n\t\tstaff... | null | [] | package com.example.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.model.StaffModel;
import com.example.service.StaffService;
@RestController
public class StaffController {
@Autowired
StaffModel staffModel;
@Autowired
StaffService staffService;
@RequestMapping("/addStaff")
public String hello() {
staffModel = new StaffModel();
staffModel.setPassword("<PASSWORD>");
staffModel.setEmail("<EMAIL>");
staffModel.setPhone("22334455");
staffModel.setPosition("Manager");
staffService.addStaff(staffModel);
return "New Staff added";
}
} | 761 | 0.761468 | 0.74574 | 30 | 23.5 | 19.269579 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.2 | false | false | 6 |
4fc330b6b392f946cca5728814944c1347ee7923 | 154,618,880,716 | 7c1b12493ffdc85e34138ce40af6a7cdd8d4101d | /HelloWord/src/practise/Chapter92.java | d1c81a3d0c1efbba3d51e9614b7e76424fe4e213 | [] | no_license | uknowz/My-leetcode | https://github.com/uknowz/My-leetcode | d5da8c9050cdbe0d2a699230d06c04286d47306b | 64f8f496df130bc0472b77c82af99a422d2b33e7 | refs/heads/master | 2020-04-17T22:28:18.885000 | 2018-01-10T03:33:50 | 2018-01-10T03:33:50 | 67,421,937 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package practise;
import javax.swing.*;
public class Chapter92 extends JFrame{
/**
* @param args
*/
JLabel label1 = new JLabel("用户名",SwingConstants.LEFT);
JLabel label2 = new JLabel("密码啊",SwingConstants.LEFT);
JPanel panel = new JPanel();
JButton button1 = new JButton("OK");
JButton button2 = new JButton("Cancel");
//有一点,就是现在还在用纯代码设计界面,而且还没有布局管理器,有直观的UI设计,不用纯代码
public Chapter92(){
super("登录界面");
JTextField text1 = new JTextField(15);
JPasswordField text2 = new JPasswordField(15);
text2.setEchoChar('#');
panel.add(label1);
panel.add(text1);
panel.add(label2);
panel.add(text2);
panel.add(button1);
panel.add(button2);
setSize(240,220);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(panel);
setVisible(true);
}
public static void main(String[] args) {
// TODO 自动生成的方法存根
Chapter92 login = new Chapter92();
}
}
| GB18030 | Java | 997 | java | Chapter92.java | Java | [
{
"context": "\t * @param args\n\t */\n\tJLabel label1 = new JLabel(\"用户名\",SwingConstants.LEFT);\n\tJLabel label2 = new JLabe",
"end": 140,
"score": 0.7046064138412476,
"start": 137,
"tag": "USERNAME",
"value": "用户名"
}
] | null | [] | package practise;
import javax.swing.*;
public class Chapter92 extends JFrame{
/**
* @param args
*/
JLabel label1 = new JLabel("用户名",SwingConstants.LEFT);
JLabel label2 = new JLabel("密码啊",SwingConstants.LEFT);
JPanel panel = new JPanel();
JButton button1 = new JButton("OK");
JButton button2 = new JButton("Cancel");
//有一点,就是现在还在用纯代码设计界面,而且还没有布局管理器,有直观的UI设计,不用纯代码
public Chapter92(){
super("登录界面");
JTextField text1 = new JTextField(15);
JPasswordField text2 = new JPasswordField(15);
text2.setEchoChar('#');
panel.add(label1);
panel.add(text1);
panel.add(label2);
panel.add(text2);
panel.add(button1);
panel.add(button2);
setSize(240,220);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(panel);
setVisible(true);
}
public static void main(String[] args) {
// TODO 自动生成的方法存根
Chapter92 login = new Chapter92();
}
}
| 997 | 0.697143 | 0.661714 | 39 | 21.435898 | 16.712954 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.871795 | false | false | 6 |
088f49a38cbd68aa562002d3e9b73af334a65727 | 29,420,526,006,965 | 8c7953fda1d898236597d1d2d72ef796dfc20223 | /FitnessApp/app/src/main/java/com/example/fitnessapp/diet.java | b3b49ddd26e479ce1f2142692f115218c3ecf97e | [] | no_license | nirpesh23/FitYou | https://github.com/nirpesh23/FitYou | f608200a8fedf0de706aa9ac5d21d5427fbc2e10 | fc63d970b25802c86fd830e0ff469462a28b13ff | refs/heads/master | 2022-11-07T11:35:21.343000 | 2020-06-15T15:48:15 | 2020-06-15T15:48:15 | 272,479,237 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.fitnessapp;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
public class diet extends Fragment implements View.OnClickListener{
Button profile;
RelativeLayout first,low_carb,lunch,Breakfast,dinner,breakfast3,highprotein_chicken,low_carb2,breakfast2,breakfast4;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_diet,container,false);
profile = (Button) v.findViewById(R.id.profile);
profile.setOnClickListener(this);
first = (RelativeLayout) v.findViewById(R.id.top_breakfast);
first.setOnClickListener(this);
low_carb= (RelativeLayout) v.findViewById(R.id.low_carb);
low_carb.setOnClickListener(this);
Breakfast= (RelativeLayout) v.findViewById(R.id.Breakfast);
Breakfast.setOnClickListener(this);
dinner= (RelativeLayout) v.findViewById(R.id.dinner);
dinner.setOnClickListener(this);
breakfast3= (RelativeLayout) v.findViewById(R.id.breakfast3);
breakfast3.setOnClickListener(this);
highprotein_chicken= (RelativeLayout) v.findViewById(R.id.highprotein_chicken);
highprotein_chicken.setOnClickListener(this);
low_carb2= (RelativeLayout) v.findViewById(R.id.low_carb2);
low_carb2.setOnClickListener(this);
breakfast2= (RelativeLayout) v.findViewById(R.id.breakfast2);
breakfast2.setOnClickListener(this);
lunch= (RelativeLayout) v.findViewById(R.id.lunch);
lunch.setOnClickListener(this);
breakfast4= (RelativeLayout) v.findViewById(R.id.breakfast4);
breakfast4.setOnClickListener(this);
return v;
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.profile:
startActivity(new Intent(getActivity(),UserProfile.class));
break;
case R.id.top_breakfast:
startActivity(new Intent(getActivity(),first_recipe.class));
break;
case R.id.low_carb:
startActivity(new Intent(getActivity(),low_carb.class));
break;
case R.id.Breakfast:
startActivity(new Intent(getActivity(),Breakfast.class));
break;
case R.id.dinner:
startActivity(new Intent(getActivity(),dinner.class));
break;
case R.id.breakfast3:
startActivity(new Intent(getActivity(),breakfast3.class));
break;
case R.id.highprotein_chicken:
startActivity(new Intent(getActivity(),highprotein_chicken.class));
break;
case R.id.low_carb2:
startActivity(new Intent(getActivity(),low_carb2.class));
break;
case R.id.breakfast2:
startActivity(new Intent(getActivity(),breakfast2.class));
break;
case R.id.lunch:
startActivity(new Intent(getActivity(),lunch.class));
break;
case R.id.breakfast4:
startActivity(new Intent(getActivity(),breakfast4.class));
break;
}
}
}
| UTF-8 | Java | 3,656 | java | diet.java | Java | [] | null | [] | package com.example.fitnessapp;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
public class diet extends Fragment implements View.OnClickListener{
Button profile;
RelativeLayout first,low_carb,lunch,Breakfast,dinner,breakfast3,highprotein_chicken,low_carb2,breakfast2,breakfast4;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_diet,container,false);
profile = (Button) v.findViewById(R.id.profile);
profile.setOnClickListener(this);
first = (RelativeLayout) v.findViewById(R.id.top_breakfast);
first.setOnClickListener(this);
low_carb= (RelativeLayout) v.findViewById(R.id.low_carb);
low_carb.setOnClickListener(this);
Breakfast= (RelativeLayout) v.findViewById(R.id.Breakfast);
Breakfast.setOnClickListener(this);
dinner= (RelativeLayout) v.findViewById(R.id.dinner);
dinner.setOnClickListener(this);
breakfast3= (RelativeLayout) v.findViewById(R.id.breakfast3);
breakfast3.setOnClickListener(this);
highprotein_chicken= (RelativeLayout) v.findViewById(R.id.highprotein_chicken);
highprotein_chicken.setOnClickListener(this);
low_carb2= (RelativeLayout) v.findViewById(R.id.low_carb2);
low_carb2.setOnClickListener(this);
breakfast2= (RelativeLayout) v.findViewById(R.id.breakfast2);
breakfast2.setOnClickListener(this);
lunch= (RelativeLayout) v.findViewById(R.id.lunch);
lunch.setOnClickListener(this);
breakfast4= (RelativeLayout) v.findViewById(R.id.breakfast4);
breakfast4.setOnClickListener(this);
return v;
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.profile:
startActivity(new Intent(getActivity(),UserProfile.class));
break;
case R.id.top_breakfast:
startActivity(new Intent(getActivity(),first_recipe.class));
break;
case R.id.low_carb:
startActivity(new Intent(getActivity(),low_carb.class));
break;
case R.id.Breakfast:
startActivity(new Intent(getActivity(),Breakfast.class));
break;
case R.id.dinner:
startActivity(new Intent(getActivity(),dinner.class));
break;
case R.id.breakfast3:
startActivity(new Intent(getActivity(),breakfast3.class));
break;
case R.id.highprotein_chicken:
startActivity(new Intent(getActivity(),highprotein_chicken.class));
break;
case R.id.low_carb2:
startActivity(new Intent(getActivity(),low_carb2.class));
break;
case R.id.breakfast2:
startActivity(new Intent(getActivity(),breakfast2.class));
break;
case R.id.lunch:
startActivity(new Intent(getActivity(),lunch.class));
break;
case R.id.breakfast4:
startActivity(new Intent(getActivity(),breakfast4.class));
break;
}
}
}
| 3,656 | 0.646335 | 0.63977 | 86 | 41.511627 | 26.02313 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.976744 | false | false | 6 |
74b9bce8d2d0ccb89a13c11c07e55f6e47462724 | 24,885,040,528,113 | 2fae214de562ad5285f08fd8ff6e03e2781a0bee | /src/main/java/gui/MapVBox.java | 2c6200e4ea258d0656ac19d564cab6e0bd542b61 | [] | no_license | pawlo555/EvolutionarySimulator | https://github.com/pawlo555/EvolutionarySimulator | 6f10698748c8d87663bf8262c57b8b44b5bcea75 | 2cef07c7b177ecc03c701a740d9c1c31d47ea76f | refs/heads/main | 2023-02-04T13:29:20.830000 | 2022-02-18T15:02:13 | 2022-02-18T15:02:13 | 322,887,378 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package gui;
import javafx.scene.layout.VBox;
public class MapVBox extends VBox {
public MapVBox(MapVisualizer visualizer) {
this.setMinSize(400, 400);
this.getChildren().add(visualizer);
}
}
| UTF-8 | Java | 219 | java | MapVBox.java | Java | [] | null | [] | package gui;
import javafx.scene.layout.VBox;
public class MapVBox extends VBox {
public MapVBox(MapVisualizer visualizer) {
this.setMinSize(400, 400);
this.getChildren().add(visualizer);
}
}
| 219 | 0.684932 | 0.657534 | 11 | 18.90909 | 18.108032 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false | 6 |
fa60ab3d5af73050f333ea7d8424f585bccd698d | 10,496,900,131,836 | 33bac5ce5945eee6381c8f16414bbc44e7fd5720 | /src/ec/edu/ups/idao/IFacturaDAO.java | fc1da000195fab534ce61e759d26a372f3a60dc7 | [
"MIT"
] | permissive | DanielLopez651/Proyecto-final- | https://github.com/DanielLopez651/Proyecto-final- | cb96853f36e2a63d451579b12701c03439084e0f | b168a63ab5b763722cccdb9fb8748d2dcc3ca13c | refs/heads/master | 2022-11-25T14:01:16.946000 | 2020-07-31T13:50:35 | 2020-07-31T13:54:00 | 281,802,370 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ec.edu.ups.idao;
import ec.edu.ups.modelo.Factura;
import java.util.List;
public interface IFacturaDAO {
public void create(Factura factura);
public boolean cambiarEstado(String codigo);
public List<Factura> mostrarFacturas();
}
| UTF-8 | Java | 249 | java | IFacturaDAO.java | Java | [] | null | [] | package ec.edu.ups.idao;
import ec.edu.ups.modelo.Factura;
import java.util.List;
public interface IFacturaDAO {
public void create(Factura factura);
public boolean cambiarEstado(String codigo);
public List<Factura> mostrarFacturas();
}
| 249 | 0.763052 | 0.763052 | 8 | 30.125 | 13.887382 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 6 |
b056fdb987d51ac0dfdb9c596bfaf3f324437b3f | 28,338,194,256,762 | a5d01febfd8d45a61f815b6f5ed447e25fad4959 | /Source Code/5.5.1/sources/com/iqoption/view/SelectionButton.java | fad3ae70969583f82b6e037cb0e8bd2df79b93c3 | [] | no_license | kkagill/Decompiler-IQ-Option | https://github.com/kkagill/Decompiler-IQ-Option | 7fe5911f90ed2490687f5d216cb2940f07b57194 | c2a9dbbe79a959aa1ab8bb7a89c735e8f9dbc5a6 | refs/heads/master | 2020-09-14T20:44:49.115000 | 2019-11-04T06:58:55 | 2019-11-04T06:58:55 | 223,236,327 | 1 | 0 | null | true | 2019-11-21T18:17:17 | 2019-11-21T18:17:16 | 2019-11-04T07:03:15 | 2019-11-04T07:02:38 | 104,586 | 0 | 0 | 0 | null | false | false | package com.iqoption.view;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.support.v7.widget.AppCompatButton;
import android.util.AttributeSet;
import com.iqoption.b.b;
public class SelectionButton extends AppCompatButton {
int dDD;
ColorStateList dDE;
public SelectionButton(Context context) {
this(context, null);
}
public SelectionButton(Context context, AttributeSet attributeSet) {
this(context, attributeSet, 0);
}
public SelectionButton(Context context, AttributeSet attributeSet, int i) {
super(context, attributeSet, i);
this.dDD = -1;
d(attributeSet);
}
private void d(AttributeSet attributeSet) {
if (attributeSet != null) {
TypedArray obtainStyledAttributes = getContext().obtainStyledAttributes(attributeSet, b.SelectionButton);
this.dDD = obtainStyledAttributes.getColor(1, -1);
this.dDE = obtainStyledAttributes.getColorStateList(2);
setSelected(obtainStyledAttributes.getBoolean(0, false));
obtainStyledAttributes.recycle();
}
}
public void setSelected(boolean z) {
super.setSelected(z);
if (z) {
setTextColor(this.dDD);
} else {
setTextColor(this.dDE);
}
}
}
| UTF-8 | Java | 1,384 | java | SelectionButton.java | Java | [] | null | [] | package com.iqoption.view;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.support.v7.widget.AppCompatButton;
import android.util.AttributeSet;
import com.iqoption.b.b;
public class SelectionButton extends AppCompatButton {
int dDD;
ColorStateList dDE;
public SelectionButton(Context context) {
this(context, null);
}
public SelectionButton(Context context, AttributeSet attributeSet) {
this(context, attributeSet, 0);
}
public SelectionButton(Context context, AttributeSet attributeSet, int i) {
super(context, attributeSet, i);
this.dDD = -1;
d(attributeSet);
}
private void d(AttributeSet attributeSet) {
if (attributeSet != null) {
TypedArray obtainStyledAttributes = getContext().obtainStyledAttributes(attributeSet, b.SelectionButton);
this.dDD = obtainStyledAttributes.getColor(1, -1);
this.dDE = obtainStyledAttributes.getColorStateList(2);
setSelected(obtainStyledAttributes.getBoolean(0, false));
obtainStyledAttributes.recycle();
}
}
public void setSelected(boolean z) {
super.setSelected(z);
if (z) {
setTextColor(this.dDD);
} else {
setTextColor(this.dDE);
}
}
}
| 1,384 | 0.66763 | 0.662572 | 46 | 29.086956 | 25.507736 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.717391 | false | false | 6 |
92d91987815e7d1a39c8f4d52bc39d405346c32a | 26,079,041,490,232 | 21966e2b7d7533e825703833215f6e384a587dee | /src/test/java/net/indyjug/TestSimpleFormPage.java | 5f0d9f8f46b8962021db7669914a262500c52f01 | [] | no_license | bfritz/wicket-intro | https://github.com/bfritz/wicket-intro | 415d5e2079f8eee8031d88649151f32ad4b246a3 | 68679965223af4064cd1a9391e153a279a39fba0 | refs/heads/master | 2020-05-18T11:20:36.465000 | 2010-09-30T01:57:04 | 2010-09-30T01:57:04 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.indyjug;
import junit.framework.TestCase;
import org.apache.wicket.util.tester.WicketTester;
/**
* Test SimpleFormPage.
*/
public class TestSimpleFormPage extends TestCase {
private WicketTester tester;
@Override
public void setUp() {
tester = new WicketTester(new WicketApplication());
}
public void testRenderSimpleFormPage() {
tester.startPage(SimpleFormPage.class);
tester.assertRenderedPage(SimpleFormPage.class);
}
}
| UTF-8 | Java | 480 | java | TestSimpleFormPage.java | Java | [] | null | [] | package net.indyjug;
import junit.framework.TestCase;
import org.apache.wicket.util.tester.WicketTester;
/**
* Test SimpleFormPage.
*/
public class TestSimpleFormPage extends TestCase {
private WicketTester tester;
@Override
public void setUp() {
tester = new WicketTester(new WicketApplication());
}
public void testRenderSimpleFormPage() {
tester.startPage(SimpleFormPage.class);
tester.assertRenderedPage(SimpleFormPage.class);
}
}
| 480 | 0.729167 | 0.729167 | 24 | 18 | 19.68502 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.791667 | false | false | 6 |
960791f81efb20c48a47e15dfa1b01ff23fd1406 | 33,655,363,733,693 | 3618d367e9b65adc11462b82c775f629a8e56410 | /src/main/java/io/genobank/cryptography/PermitteeSigner.java | c6ae475b1bbd4a9d9aa45a10612af515c07ff48e | [] | no_license | Genobank/genobankj | https://github.com/Genobank/genobankj | a822644933ac49de3384445f01a3c6cb9af80af5 | d330b031507f3f3c09fb2ddc8e0e732c960ea8c8 | refs/heads/master | 2023-03-20T22:30:45.109000 | 2022-05-03T22:50:17 | 2022-05-03T22:50:17 | 340,268,480 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package io.genobank;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import org.web3j.crypto.Bip32ECKeyPair;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.MnemonicUtils;
import org.web3j.crypto.Sign;
import org.web3j.utils.Numeric;
import static org.web3j.crypto.Bip32ECKeyPair.HARDENED_BIT;
public class PermitteeSigner {
public final Credentials credentials;
public final Integer permitteeId;
public byte[] signature;
// Load an Ethereum wallet: https://gitter.im/web3j/web3j?at=5cb437ba31aec969e8aaed08
// Test https://www.trufflesuite.com/docs/truffle/getting-started/using-truffle-develop-and-the-console
// See also https://github.com/web3j/web3j/issues/1369
public PermitteeSigner(String twelveWordPassphrase, Integer permitteeId) {
String mnemonicPassword = null;
Bip32ECKeyPair masterKeyPair = Bip32ECKeyPair.generateKeyPair(MnemonicUtils.generateSeed(twelveWordPassphrase, mnemonicPassword));
int[] path = {44 | HARDENED_BIT, 60 | HARDENED_BIT, 0 | HARDENED_BIT, 0, 0};
Bip32ECKeyPair keyPair = Bip32ECKeyPair.deriveKeyPair(masterKeyPair, path);
credentials = Credentials.create(keyPair);
this.permitteeId = permitteeId;
}
public byte[] sign(PermitteeRepresentations representations) {
byte[] message = representations.getFullSerialization().getBytes(StandardCharsets.UTF_8);
Sign.SignatureData signature = Sign.signPrefixedMessage(message, credentials.getEcKeyPair());
// Match the signature output format as Ethers.js v5.0.31
// https://github.com/ethers-io/ethers.js/blob/v5.0.31/packages/bytes/src.ts/index.ts#L444-L448
byte[] retval = new byte[65];
System.arraycopy(signature.getR(), 0, retval, 0, 32);
System.arraycopy(signature.getS(), 0, retval, 32, 32);
System.arraycopy(signature.getV(), 0, retval, 64, 1);
return retval;
}
}
| UTF-8 | Java | 1,880 | java | PermitteeSigner.java | Java | [
{
"context": "\n\n // Load an Ethereum wallet: https://gitter.im/web3j/web3j?at=5cb437ba31aec969e8aaed08\n // Test https",
"end": 531,
"score": 0.9988164901733398,
"start": 526,
"tag": "USERNAME",
"value": "web3j"
},
{
"context": "-and-the-console\n // See also https://github.com/... | null | [] | package io.genobank;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import org.web3j.crypto.Bip32ECKeyPair;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.MnemonicUtils;
import org.web3j.crypto.Sign;
import org.web3j.utils.Numeric;
import static org.web3j.crypto.Bip32ECKeyPair.HARDENED_BIT;
public class PermitteeSigner {
public final Credentials credentials;
public final Integer permitteeId;
public byte[] signature;
// Load an Ethereum wallet: https://gitter.im/web3j/web3j?at=5cb437ba31aec969e8aaed08
// Test https://www.trufflesuite.com/docs/truffle/getting-started/using-truffle-develop-and-the-console
// See also https://github.com/web3j/web3j/issues/1369
public PermitteeSigner(String twelveWordPassphrase, Integer permitteeId) {
String mnemonicPassword = null;
Bip32ECKeyPair masterKeyPair = Bip32ECKeyPair.generateKeyPair(MnemonicUtils.generateSeed(twelveWordPassphrase, mnemonicPassword));
int[] path = {44 | HARDENED_BIT, 60 | HARDENED_BIT, 0 | HARDENED_BIT, 0, 0};
Bip32ECKeyPair keyPair = Bip32ECKeyPair.deriveKeyPair(masterKeyPair, path);
credentials = Credentials.create(keyPair);
this.permitteeId = permitteeId;
}
public byte[] sign(PermitteeRepresentations representations) {
byte[] message = representations.getFullSerialization().getBytes(StandardCharsets.UTF_8);
Sign.SignatureData signature = Sign.signPrefixedMessage(message, credentials.getEcKeyPair());
// Match the signature output format as Ethers.js v5.0.31
// https://github.com/ethers-io/ethers.js/blob/v5.0.31/packages/bytes/src.ts/index.ts#L444-L448
byte[] retval = new byte[65];
System.arraycopy(signature.getR(), 0, retval, 0, 32);
System.arraycopy(signature.getS(), 0, retval, 32, 32);
System.arraycopy(signature.getV(), 0, retval, 64, 1);
return retval;
}
}
| 1,880 | 0.763298 | 0.723404 | 43 | 42.720932 | 33.576241 | 134 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.116279 | false | false | 6 |
fb8172113021e55ffcc0927020aaf783d63d4eaa | 5,446,018,532,118 | fae36fb4e9f82efbd933e89e472b93e3dbc19b90 | /hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/r4/BaseJpaResourceProviderCodeSystemR4.java | a4074e2a3e099bed738f8da4d2f76437f0b5cb43 | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | trifork/fut-hapi-fhir | https://github.com/trifork/fut-hapi-fhir | a6e93c7f86645bc36fbc98c5dc722bae2355597f | caf370da31cda005c0d5f6a84edb3e12fcff159d | refs/heads/master | 2023-05-12T07:08:15.605000 | 2022-08-24T16:55:00 | 2022-08-24T16:55:00 | 177,019,081 | 1 | 0 | Apache-2.0 | true | 2023-02-27T09:36:32 | 2019-03-21T20:29:11 | 2022-03-24T10:40:24 | 2023-02-27T09:36:32 | 751,336 | 1 | 1 | 8 | Java | false | false | package ca.uhn.fhir.jpa.provider.r4;
import ca.uhn.fhir.context.support.ConceptValidationOptions;
import ca.uhn.fhir.context.support.IValidationSupport;
import ca.uhn.fhir.context.support.ValidationSupportContext;
import ca.uhn.fhir.i18n.Msg;
import ca.uhn.fhir.jpa.api.dao.IFhirResourceDaoCodeSystem;
import ca.uhn.fhir.jpa.config.JpaConfig;
import ca.uhn.fhir.jpa.model.util.JpaConstants;
import ca.uhn.fhir.jpa.provider.BaseJpaResourceProviderValueSetDstu2;
import ca.uhn.fhir.jpa.term.api.ITermReadSvcR4;
import ca.uhn.fhir.rest.annotation.IdParam;
import ca.uhn.fhir.rest.annotation.Operation;
import ca.uhn.fhir.rest.annotation.OperationParam;
import ca.uhn.fhir.rest.api.server.RequestDetails;
import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException;
import org.hl7.fhir.common.hapi.validation.support.ValidationSupportChain;
import org.hl7.fhir.r4.model.BooleanType;
import org.hl7.fhir.r4.model.CodeSystem;
import org.hl7.fhir.r4.model.CodeType;
import org.hl7.fhir.r4.model.CodeableConcept;
import org.hl7.fhir.r4.model.Coding;
import org.hl7.fhir.r4.model.IdType;
import org.hl7.fhir.r4.model.Parameters;
import org.hl7.fhir.r4.model.StringType;
import org.hl7.fhir.r4.model.UriType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/*
* #%L
* HAPI FHIR JPA Server
* %%
* Copyright (C) 2014 - 2022 Smile CDR, Inc.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
public class BaseJpaResourceProviderCodeSystemR4 extends JpaResourceProviderR4<CodeSystem> {
@Autowired
@Qualifier(JpaConfig.JPA_VALIDATION_SUPPORT_CHAIN)
private ValidationSupportChain myValidationSupportChain;
@Autowired
protected ITermReadSvcR4 myTermSvc;
/**
* $lookup operation
*/
@SuppressWarnings("unchecked")
@Operation(name = JpaConstants.OPERATION_LOOKUP, idempotent = true, returnParameters= {
@OperationParam(name="name", type=StringType.class, min=1),
@OperationParam(name="version", type=StringType.class, min=0),
@OperationParam(name="display", type=StringType.class, min=1),
@OperationParam(name="abstract", type=BooleanType.class, min=1),
})
public Parameters lookup(
HttpServletRequest theServletRequest,
@OperationParam(name="code", min=0, max=1) CodeType theCode,
@OperationParam(name="system", min=0, max=1) UriType theSystem,
@OperationParam(name="coding", min=0, max=1) Coding theCoding,
@OperationParam(name="version", min=0, max=1) StringType theVersion,
@OperationParam(name="displayLanguage", min=0, max=1) CodeType theDisplayLanguage,
@OperationParam(name="property", min = 0, max = OperationParam.MAX_UNLIMITED) List<CodeType> theProperties,
RequestDetails theRequestDetails
) {
startRequest(theServletRequest);
try {
IFhirResourceDaoCodeSystem<CodeSystem, Coding, CodeableConcept> dao = (IFhirResourceDaoCodeSystem<CodeSystem, Coding, CodeableConcept>) getDao();
IValidationSupport.LookupCodeResult result;
if (theVersion != null) {
result = dao.lookupCode(theCode, new UriType(theSystem.getValue() + "|" + theVersion), theCoding, theDisplayLanguage, theRequestDetails);
} else {
result = dao.lookupCode(theCode, theSystem, theCoding, theDisplayLanguage, theRequestDetails);
}
result.throwNotFoundIfAppropriate();
return (Parameters) result.toParameters(theRequestDetails.getFhirContext(), theProperties);
} finally {
endRequest(theServletRequest);
}
}
/**
* $subsumes operation
*/
@Operation(name = JpaConstants.OPERATION_SUBSUMES, idempotent = true, returnParameters= {
@OperationParam(name="outcome", type=CodeType.class, min=1),
})
public Parameters subsumes(
HttpServletRequest theServletRequest,
@OperationParam(name="codeA", min=0, max=1) CodeType theCodeA,
@OperationParam(name="codeB", min=0, max=1) CodeType theCodeB,
@OperationParam(name="system", min=0, max=1) UriType theSystem,
@OperationParam(name="codingA", min=0, max=1) Coding theCodingA,
@OperationParam(name="codingB", min=0, max=1) Coding theCodingB,
@OperationParam(name="version", min=0, max=1) StringType theVersion,
RequestDetails theRequestDetails
) {
startRequest(theServletRequest);
try {
IFhirResourceDaoCodeSystem<CodeSystem, Coding, CodeableConcept> dao = (IFhirResourceDaoCodeSystem<CodeSystem, Coding, CodeableConcept>) getDao();
IFhirResourceDaoCodeSystem.SubsumesResult result;
if (theVersion != null) {
theSystem = new UriType(theSystem.asStringValue() + "|" + theVersion.toString());
}
result = dao.subsumes(theCodeA, theCodeB, theSystem, theCodingA, theCodingB, theRequestDetails);
return (Parameters) result.toParameters(theRequestDetails.getFhirContext());
} finally {
endRequest(theServletRequest);
}
}
/**
* $validate-code operation
*/
@SuppressWarnings("unchecked")
@Operation(name = JpaConstants.OPERATION_VALIDATE_CODE, idempotent = true, returnParameters = {
@OperationParam(name = "result", type = BooleanType.class, min = 1),
@OperationParam(name = "message", type = StringType.class),
@OperationParam(name = "display", type = StringType.class)
})
public Parameters validateCode(
HttpServletRequest theServletRequest,
@IdParam(optional = true) IdType theId,
@OperationParam(name = "url", min = 0, max = 1) UriType theCodeSystemUrl,
@OperationParam(name = "version", min = 0, max = 1) StringType theVersion,
@OperationParam(name = "code", min = 0, max = 1) CodeType theCode,
@OperationParam(name = "display", min = 0, max = 1) StringType theDisplay,
@OperationParam(name = "coding", min = 0, max = 1) Coding theCoding,
@OperationParam(name = "codeableConcept", min = 0, max = 1) CodeableConcept theCodeableConcept,
RequestDetails theRequestDetails
) {
IValidationSupport.CodeValidationResult result = null;
startRequest(theServletRequest);
try {
// If a Remote Terminology Server has been configured, use it
if (myValidationSupportChain.isRemoteTerminologyServiceConfigured()) {
String codeSystemUrl = (theCodeSystemUrl != null && theCodeSystemUrl.hasValue()) ?
theCodeSystemUrl.asStringValue() : null;
String code = (theCode != null && theCode.hasValue()) ? theCode.asStringValue() : null;
String display = (theDisplay != null && theDisplay.hasValue()) ? theDisplay.asStringValue() : null;
if (theCoding != null) {
if (theCoding.hasSystem()) {
if (codeSystemUrl != null && !codeSystemUrl.equalsIgnoreCase(theCoding.getSystem())) {
throw new InvalidRequestException(Msg.code(1160) + "Coding.system '" + theCoding.getSystem() + "' does not equal param url '" + theCodeSystemUrl + "'. Unable to validate-code.");
}
codeSystemUrl = theCoding.getSystem();
code = theCoding.getCode();
display = theCoding.getDisplay();
result = myValidationSupportChain.validateCode(
new ValidationSupportContext(myValidationSupportChain), new ConceptValidationOptions(),
codeSystemUrl, code, display, null);
}
}
} else {
// Otherwise, use the local DAO layer to validate the code
IFhirResourceDaoCodeSystem<CodeSystem, Coding, CodeableConcept> dao = (IFhirResourceDaoCodeSystem<CodeSystem, Coding, CodeableConcept>) getDao();
result = dao.validateCode(theId, theCodeSystemUrl, theVersion, theCode, theDisplay, theCoding, theCodeableConcept, theRequestDetails);
}
return (Parameters) BaseJpaResourceProviderValueSetDstu2.toValidateCodeResult(getContext(), result);
} finally {
endRequest(theServletRequest);
}
}
}
| UTF-8 | Java | 8,112 | java | BaseJpaResourceProviderCodeSystemR4.java | Java | [] | null | [] | package ca.uhn.fhir.jpa.provider.r4;
import ca.uhn.fhir.context.support.ConceptValidationOptions;
import ca.uhn.fhir.context.support.IValidationSupport;
import ca.uhn.fhir.context.support.ValidationSupportContext;
import ca.uhn.fhir.i18n.Msg;
import ca.uhn.fhir.jpa.api.dao.IFhirResourceDaoCodeSystem;
import ca.uhn.fhir.jpa.config.JpaConfig;
import ca.uhn.fhir.jpa.model.util.JpaConstants;
import ca.uhn.fhir.jpa.provider.BaseJpaResourceProviderValueSetDstu2;
import ca.uhn.fhir.jpa.term.api.ITermReadSvcR4;
import ca.uhn.fhir.rest.annotation.IdParam;
import ca.uhn.fhir.rest.annotation.Operation;
import ca.uhn.fhir.rest.annotation.OperationParam;
import ca.uhn.fhir.rest.api.server.RequestDetails;
import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException;
import org.hl7.fhir.common.hapi.validation.support.ValidationSupportChain;
import org.hl7.fhir.r4.model.BooleanType;
import org.hl7.fhir.r4.model.CodeSystem;
import org.hl7.fhir.r4.model.CodeType;
import org.hl7.fhir.r4.model.CodeableConcept;
import org.hl7.fhir.r4.model.Coding;
import org.hl7.fhir.r4.model.IdType;
import org.hl7.fhir.r4.model.Parameters;
import org.hl7.fhir.r4.model.StringType;
import org.hl7.fhir.r4.model.UriType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/*
* #%L
* HAPI FHIR JPA Server
* %%
* Copyright (C) 2014 - 2022 Smile CDR, Inc.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
public class BaseJpaResourceProviderCodeSystemR4 extends JpaResourceProviderR4<CodeSystem> {
@Autowired
@Qualifier(JpaConfig.JPA_VALIDATION_SUPPORT_CHAIN)
private ValidationSupportChain myValidationSupportChain;
@Autowired
protected ITermReadSvcR4 myTermSvc;
/**
* $lookup operation
*/
@SuppressWarnings("unchecked")
@Operation(name = JpaConstants.OPERATION_LOOKUP, idempotent = true, returnParameters= {
@OperationParam(name="name", type=StringType.class, min=1),
@OperationParam(name="version", type=StringType.class, min=0),
@OperationParam(name="display", type=StringType.class, min=1),
@OperationParam(name="abstract", type=BooleanType.class, min=1),
})
public Parameters lookup(
HttpServletRequest theServletRequest,
@OperationParam(name="code", min=0, max=1) CodeType theCode,
@OperationParam(name="system", min=0, max=1) UriType theSystem,
@OperationParam(name="coding", min=0, max=1) Coding theCoding,
@OperationParam(name="version", min=0, max=1) StringType theVersion,
@OperationParam(name="displayLanguage", min=0, max=1) CodeType theDisplayLanguage,
@OperationParam(name="property", min = 0, max = OperationParam.MAX_UNLIMITED) List<CodeType> theProperties,
RequestDetails theRequestDetails
) {
startRequest(theServletRequest);
try {
IFhirResourceDaoCodeSystem<CodeSystem, Coding, CodeableConcept> dao = (IFhirResourceDaoCodeSystem<CodeSystem, Coding, CodeableConcept>) getDao();
IValidationSupport.LookupCodeResult result;
if (theVersion != null) {
result = dao.lookupCode(theCode, new UriType(theSystem.getValue() + "|" + theVersion), theCoding, theDisplayLanguage, theRequestDetails);
} else {
result = dao.lookupCode(theCode, theSystem, theCoding, theDisplayLanguage, theRequestDetails);
}
result.throwNotFoundIfAppropriate();
return (Parameters) result.toParameters(theRequestDetails.getFhirContext(), theProperties);
} finally {
endRequest(theServletRequest);
}
}
/**
* $subsumes operation
*/
@Operation(name = JpaConstants.OPERATION_SUBSUMES, idempotent = true, returnParameters= {
@OperationParam(name="outcome", type=CodeType.class, min=1),
})
public Parameters subsumes(
HttpServletRequest theServletRequest,
@OperationParam(name="codeA", min=0, max=1) CodeType theCodeA,
@OperationParam(name="codeB", min=0, max=1) CodeType theCodeB,
@OperationParam(name="system", min=0, max=1) UriType theSystem,
@OperationParam(name="codingA", min=0, max=1) Coding theCodingA,
@OperationParam(name="codingB", min=0, max=1) Coding theCodingB,
@OperationParam(name="version", min=0, max=1) StringType theVersion,
RequestDetails theRequestDetails
) {
startRequest(theServletRequest);
try {
IFhirResourceDaoCodeSystem<CodeSystem, Coding, CodeableConcept> dao = (IFhirResourceDaoCodeSystem<CodeSystem, Coding, CodeableConcept>) getDao();
IFhirResourceDaoCodeSystem.SubsumesResult result;
if (theVersion != null) {
theSystem = new UriType(theSystem.asStringValue() + "|" + theVersion.toString());
}
result = dao.subsumes(theCodeA, theCodeB, theSystem, theCodingA, theCodingB, theRequestDetails);
return (Parameters) result.toParameters(theRequestDetails.getFhirContext());
} finally {
endRequest(theServletRequest);
}
}
/**
* $validate-code operation
*/
@SuppressWarnings("unchecked")
@Operation(name = JpaConstants.OPERATION_VALIDATE_CODE, idempotent = true, returnParameters = {
@OperationParam(name = "result", type = BooleanType.class, min = 1),
@OperationParam(name = "message", type = StringType.class),
@OperationParam(name = "display", type = StringType.class)
})
public Parameters validateCode(
HttpServletRequest theServletRequest,
@IdParam(optional = true) IdType theId,
@OperationParam(name = "url", min = 0, max = 1) UriType theCodeSystemUrl,
@OperationParam(name = "version", min = 0, max = 1) StringType theVersion,
@OperationParam(name = "code", min = 0, max = 1) CodeType theCode,
@OperationParam(name = "display", min = 0, max = 1) StringType theDisplay,
@OperationParam(name = "coding", min = 0, max = 1) Coding theCoding,
@OperationParam(name = "codeableConcept", min = 0, max = 1) CodeableConcept theCodeableConcept,
RequestDetails theRequestDetails
) {
IValidationSupport.CodeValidationResult result = null;
startRequest(theServletRequest);
try {
// If a Remote Terminology Server has been configured, use it
if (myValidationSupportChain.isRemoteTerminologyServiceConfigured()) {
String codeSystemUrl = (theCodeSystemUrl != null && theCodeSystemUrl.hasValue()) ?
theCodeSystemUrl.asStringValue() : null;
String code = (theCode != null && theCode.hasValue()) ? theCode.asStringValue() : null;
String display = (theDisplay != null && theDisplay.hasValue()) ? theDisplay.asStringValue() : null;
if (theCoding != null) {
if (theCoding.hasSystem()) {
if (codeSystemUrl != null && !codeSystemUrl.equalsIgnoreCase(theCoding.getSystem())) {
throw new InvalidRequestException(Msg.code(1160) + "Coding.system '" + theCoding.getSystem() + "' does not equal param url '" + theCodeSystemUrl + "'. Unable to validate-code.");
}
codeSystemUrl = theCoding.getSystem();
code = theCoding.getCode();
display = theCoding.getDisplay();
result = myValidationSupportChain.validateCode(
new ValidationSupportContext(myValidationSupportChain), new ConceptValidationOptions(),
codeSystemUrl, code, display, null);
}
}
} else {
// Otherwise, use the local DAO layer to validate the code
IFhirResourceDaoCodeSystem<CodeSystem, Coding, CodeableConcept> dao = (IFhirResourceDaoCodeSystem<CodeSystem, Coding, CodeableConcept>) getDao();
result = dao.validateCode(theId, theCodeSystemUrl, theVersion, theCode, theDisplay, theCoding, theCodeableConcept, theRequestDetails);
}
return (Parameters) BaseJpaResourceProviderValueSetDstu2.toValidateCodeResult(getContext(), result);
} finally {
endRequest(theServletRequest);
}
}
}
| 8,112 | 0.751479 | 0.741001 | 186 | 42.612904 | 35.711216 | 185 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.725806 | false | false | 6 |
e5a860fb80087f1ad8a2b436e8470b8646b6f651 | 31,456,340,505,270 | 751f787e120e5dfb20eecb7f7312ba7d3cce7bc1 | /src/main/java/sa/tws1/service/wms/RobotSystem.java | 860c4be5d3fa61b7ffd1134afa70cd3c98fdb719 | [] | no_license | ffbt/tws1 | https://github.com/ffbt/tws1 | 2249cb37db644aa689ee2ea0db1dc42b9437abfa | 626e522ed6defd6693acd4755699b2cda4fc35d0 | refs/heads/master | 2020-03-14T16:42:20.496000 | 2018-07-12T05:39:38 | 2018-07-12T05:39:38 | 131,703,480 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package sa.tws1.service.wms;
import sa.tws1.bean.AllTool;
import java.util.Random;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class RobotSystem
{
private ThreadPoolExecutor robots;
private static final int robotNum = 10;
public RobotSystem()
{
this.robots = new ThreadPoolExecutor(robotNum, robotNum, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
}
public void addTask(int toolContainerId, AllTool allTool, ConveyorSystem conveyorSystem)
{
Robot robot = new Robot("robot", this);
robots.execute(new Task(toolContainerId, robot, allTool, conveyorSystem));
}
public void repair(Robot robot)
{
System.out.println("repairing " + robot.getName());
try
{
Thread.sleep(new Random().nextInt(100));
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
| UTF-8 | Java | 1,011 | java | RobotSystem.java | Java | [] | null | [] | package sa.tws1.service.wms;
import sa.tws1.bean.AllTool;
import java.util.Random;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class RobotSystem
{
private ThreadPoolExecutor robots;
private static final int robotNum = 10;
public RobotSystem()
{
this.robots = new ThreadPoolExecutor(robotNum, robotNum, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
}
public void addTask(int toolContainerId, AllTool allTool, ConveyorSystem conveyorSystem)
{
Robot robot = new Robot("robot", this);
robots.execute(new Task(toolContainerId, robot, allTool, conveyorSystem));
}
public void repair(Robot robot)
{
System.out.println("repairing " + robot.getName());
try
{
Thread.sleep(new Random().nextInt(100));
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
| 1,011 | 0.665678 | 0.656775 | 38 | 25.605263 | 27.570522 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.631579 | false | false | 6 |
9c9d97bfd7394ed14c3da236a904c3035310f5b0 | 27,556,510,238,387 | 18ca31a31a3640c9477bb0acf6d05e631d6d87d3 | /Struts2Base/src/main/java/cn/happy/struts07/action/LoginAction.java | e6191f5e391ad614f4fa94b771e605db89105c5a | [] | no_license | sllsllsll/tms | https://github.com/sllsllsll/tms | e9b6b8b40f31282c53c624a011d818f57106cf15 | 5d755a3d893cb53da8e93d9f4e0fc4ec8f7fafc9 | refs/heads/master | 2021-08-16T06:59:38.462000 | 2017-11-19T06:32:14 | 2017-11-19T06:32:14 | 111,270,574 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.happy.struts07.action;
import cn.happy.struts07.entity.UserInfo;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import java.util.Map;
/**
* Created by linlin on 2017/10/25.
*/
public class LoginAction implements Action{
private UserInfo user;
public String execute() throws Exception {
Map<String,Object> session= ActionContext.getContext().getSession();
if(user!=null){
if(user.getUsername().equals("1")&&user.getPassword().equals("1")){
session.put("uname",user.getUsername());
return SUCCESS;
}else{
return LOGIN;
}
}else{
if(session!=null&&session.get("uname")!=null){
return "success";
}else{
System.out.println("action中的自定义代码");
return "login";
}
}
}
public UserInfo getUser() {
return user;
}
public void setUser(UserInfo user) {
this.user = user;
}
}
| UTF-8 | Java | 1,068 | java | LoginAction.java | Java | [
{
"context": "Context;\n\nimport java.util.Map;\n\n/**\n * Created by linlin on 2017/10/25.\n */\npublic class LoginAction imple",
"end": 210,
"score": 0.999599814414978,
"start": 204,
"tag": "USERNAME",
"value": "linlin"
},
{
"context": "sername().equals(\"1\")&&user.getPassword().e... | null | [] | package cn.happy.struts07.action;
import cn.happy.struts07.entity.UserInfo;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import java.util.Map;
/**
* Created by linlin on 2017/10/25.
*/
public class LoginAction implements Action{
private UserInfo user;
public String execute() throws Exception {
Map<String,Object> session= ActionContext.getContext().getSession();
if(user!=null){
if(user.getUsername().equals("1")&&user.getPassword().equals("1")){
session.put("uname",user.getUsername());
return SUCCESS;
}else{
return LOGIN;
}
}else{
if(session!=null&&session.get("uname")!=null){
return "success";
}else{
System.out.println("action中的自定义代码");
return "login";
}
}
}
public UserInfo getUser() {
return user;
}
public void setUser(UserInfo user) {
this.user = user;
}
}
| 1,068 | 0.572106 | 0.556926 | 42 | 24.095238 | 20.880396 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.404762 | false | false | 6 |
a5427712d347973bfaf15b17a4107e31815be410 | 27,599,459,847,380 | cfbd99133ccf99fb089aaedffee14e7d37849ec3 | /app/src/main/java/com/xm6leefun/zll_user/ui_custom/about_scroll/EasySlideInter.java | 674fe1f418c6469b8963807ab77712da55f97d88 | [] | no_license | zllAndroid/BlockUser | https://github.com/zllAndroid/BlockUser | d9d7669b11cf234b88a7500cf6ff9c1996a6ce94 | 7a13f1620fc05117468c049696250e56b2cd85cc | refs/heads/master | 2021-07-24T21:40:53.020000 | 2018-04-16T09:35:03 | 2018-04-16T09:35:03 | 129,715,348 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.xm6leefun.zll_user.ui_custom.about_scroll;
public interface EasySlideInter {
/**
* 内容区域滑动的进度
* @param progress 进度值
*/
public void contentSlide(int progress);
public void resetContent();
}
| UTF-8 | Java | 244 | java | EasySlideInter.java | Java | [] | null | [] | package com.xm6leefun.zll_user.ui_custom.about_scroll;
public interface EasySlideInter {
/**
* 内容区域滑动的进度
* @param progress 进度值
*/
public void contentSlide(int progress);
public void resetContent();
}
| 244 | 0.7 | 0.695455 | 14 | 14.714286 | 17.701609 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.785714 | false | false | 6 |
2e7948f7d6320a334d3ff7e881db1328caf2c76f | 25,211,458,091,003 | 6172b4b31162889ea9e5c3464d722db59ce7e15a | /app/src/main/java/com/app/ace/ui/viewbinders/FollowersCountListBinder.java | 71608c20f481cab847b8395217b4574b7d503383 | [] | no_license | SaeedHyder/ACE_ANDROID- | https://github.com/SaeedHyder/ACE_ANDROID- | c9ca97d2758e052cd16da6a3a7ff6b8093925b27 | 55baa476819ccf1eec07e2ef9eadd5f833f1b46c | refs/heads/master | 2021-11-29T23:13:12.633000 | 2019-01-30T07:53:48 | 2019-01-30T07:53:48 | 168,323,773 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.app.ace.ui.viewbinders;
import android.app.Activity;
import android.view.View;
import com.app.ace.R;
import com.app.ace.activities.DockActivity;
import com.app.ace.entities.FollowersCountDataItem;
import com.app.ace.fragments.TrainerProfileFragment;
import com.app.ace.ui.viewbinders.abstracts.ViewBinder;
import com.app.ace.ui.views.AnyTextView;
import com.nostra13.universalimageloader.core.ImageLoader;
import de.hdodenhof.circleimageview.CircleImageView;
/**
* Created by muniyemiftikhar on 5/2/2017.
*/
public class FollowersCountListBinder extends ViewBinder<FollowersCountDataItem> {
private ImageLoader imageLoader;
DockActivity context;
public FollowersCountListBinder(DockActivity context) {
super(R.layout.followers_count_listitem);
this.context=context;
imageLoader = ImageLoader.getInstance();
}
@Override
public ViewBinder.BaseViewHolder createViewHolder(View view) {
return new FollowersCountListBinder.ViewHolder(view);
}
@Override
public void bindView(final FollowersCountDataItem entity, int position, int grpPosition, View view, Activity activity) {
FollowersCountListBinder.ViewHolder viewHolder = (FollowersCountListBinder.ViewHolder) view.getTag();
imageLoader.displayImage(entity.getUserImage(), viewHolder.userImage);
viewHolder.txtUserName.setText(entity.getUserName());
viewHolder.userImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
context.addDockableFragment(TrainerProfileFragment.newInstance(entity.getId()), "TrainerProfileFragment");
}
});
viewHolder.txtUserName.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
context.addDockableFragment(TrainerProfileFragment.newInstance(entity.getId()), "TrainerProfileFragment");
}
});
}
public static class ViewHolder extends BaseViewHolder {
private CircleImageView userImage;
private AnyTextView txtUserName;
public ViewHolder(View view) {
userImage = (CircleImageView) view.findViewById(R.id.userImageFollowers);
txtUserName = (AnyTextView) view.findViewById(R.id.txtUserNameFollowers);
}
}
}
| UTF-8 | Java | 2,390 | java | FollowersCountListBinder.java | Java | [
{
"context": "ircleimageview.CircleImageView;\n\n/**\n * Created by muniyemiftikhar on 5/2/2017.\n */\n\npublic class FollowersCountList",
"end": 509,
"score": 0.9992765188217163,
"start": 494,
"tag": "USERNAME",
"value": "muniyemiftikhar"
}
] | null | [] | package com.app.ace.ui.viewbinders;
import android.app.Activity;
import android.view.View;
import com.app.ace.R;
import com.app.ace.activities.DockActivity;
import com.app.ace.entities.FollowersCountDataItem;
import com.app.ace.fragments.TrainerProfileFragment;
import com.app.ace.ui.viewbinders.abstracts.ViewBinder;
import com.app.ace.ui.views.AnyTextView;
import com.nostra13.universalimageloader.core.ImageLoader;
import de.hdodenhof.circleimageview.CircleImageView;
/**
* Created by muniyemiftikhar on 5/2/2017.
*/
public class FollowersCountListBinder extends ViewBinder<FollowersCountDataItem> {
private ImageLoader imageLoader;
DockActivity context;
public FollowersCountListBinder(DockActivity context) {
super(R.layout.followers_count_listitem);
this.context=context;
imageLoader = ImageLoader.getInstance();
}
@Override
public ViewBinder.BaseViewHolder createViewHolder(View view) {
return new FollowersCountListBinder.ViewHolder(view);
}
@Override
public void bindView(final FollowersCountDataItem entity, int position, int grpPosition, View view, Activity activity) {
FollowersCountListBinder.ViewHolder viewHolder = (FollowersCountListBinder.ViewHolder) view.getTag();
imageLoader.displayImage(entity.getUserImage(), viewHolder.userImage);
viewHolder.txtUserName.setText(entity.getUserName());
viewHolder.userImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
context.addDockableFragment(TrainerProfileFragment.newInstance(entity.getId()), "TrainerProfileFragment");
}
});
viewHolder.txtUserName.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
context.addDockableFragment(TrainerProfileFragment.newInstance(entity.getId()), "TrainerProfileFragment");
}
});
}
public static class ViewHolder extends BaseViewHolder {
private CircleImageView userImage;
private AnyTextView txtUserName;
public ViewHolder(View view) {
userImage = (CircleImageView) view.findViewById(R.id.userImageFollowers);
txtUserName = (AnyTextView) view.findViewById(R.id.txtUserNameFollowers);
}
}
}
| 2,390 | 0.716736 | 0.713389 | 80 | 28.875 | 33.264988 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4375 | false | false | 6 |
f7ba0fe0c689c8578f85e964aec3319f8b597580 | 5,325,759,493,893 | 80872e3099b4f2d5632a1c3cc5126362f9385471 | /Seeker.java | bffc91da857a425c11b9607c546c0b0c6c156e9b | [] | no_license | DawsonClark/instinct_CTF | https://github.com/DawsonClark/instinct_CTF | d41ac88cf308bf6a135d152d96a9aeeeda05b77c | ce578621177e7bb0e00c9a914b8ef545fe055392 | refs/heads/master | 2021-01-19T01:21:37.706000 | 2016-08-09T21:11:41 | 2016-08-09T21:11:41 | 65,328,550 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | // Skeleton Code Copied from DummyPlayer then modified for question.
public class Seeker extends Player{
@Override
public void update(Field field){}
@Override
public void play(Field field){
if (this.pickUpFlag(field) == false){
// Compute the required x and y speed to move straight to the flag
if (this.getTeam().equals("reds")){ // Entity is on red team and should look for blue flag
double flagX = field.getFlag1Position()[0];
double flagY = field.getFlag1Position()[1];
double distX = (flagX - this.x); // X distance to travel
double distY = (flagY - this.y); // Y Distance to travel
double totalDist =Math.pow(Math.pow(distX,2) + Math.pow(distY,2),0.5);
this.speedX = ((MAX_SPEED*distX)/totalDist); //Determine Speed Ratio based off of 'Cross Multiply and Divide'
this.speedY = ((MAX_SPEED*distY)/totalDist);
// Max Speed X/Y Speed
// --------- = ----------
// TotalDist X/Y Dist
} else { // Entity is on blue team and should look for red flag
double flagX = field.getFlag2Position()[0];
double flagY = field.getFlag2Position()[1];
double distX = (flagX - this.x); // X distance to travel
double distY = (flagY - this.y); // Y Distance to travel
double totalDist =Math.pow(Math.pow(distX,2) + Math.pow(distY,2),0.5);
this.speedX = ((MAX_SPEED*distX)/totalDist); //Determine Speed Ratio based off of 'Cross Multiply and Divide'
this.speedY = ((MAX_SPEED*distY)/totalDist);
// Max Speed X/Y Speed
// --------- = ----------
// TotalDist X/Y Dist
}
} else{
this.speedX = 0;
this.speedY = 0;
}
// Update the player's speed based on their proximity to the border of the field
if ((this.x >= (field.maxX-16)) || (this.x <= (field.minX-16)) || (this.y >= (field.maxY-16)) || (this.y <= (field.minY-16))){
this.speedX = -this.speedX;
this.speedY = -this.speedY;
}
}
/** create a player that has some random motion
* <p>
* the player starts in a random direction
*
* @param f is the field the player will be playing on
* @param side is the side of the field the player will play on
* @param name is this player's name
* @param number is this player's number
* @param team is this player's team's name
* @param symbol is a character representation of this player
* @param x is the initial x position of this player
* @param y is the initial y position of this player
*/
public Seeker(Field f, int side, String name, int number, String team,char symbol, double x, double y){
super(f, side, name, number, team, symbol, x, y);
this.speedX = -1 + Math.random()*(4-2);
this.speedY = -1 + Math.random()*(4-2);
}
} | UTF-8 | Java | 3,346 | java | Seeker.java | Java | [] | null | [] | // Skeleton Code Copied from DummyPlayer then modified for question.
public class Seeker extends Player{
@Override
public void update(Field field){}
@Override
public void play(Field field){
if (this.pickUpFlag(field) == false){
// Compute the required x and y speed to move straight to the flag
if (this.getTeam().equals("reds")){ // Entity is on red team and should look for blue flag
double flagX = field.getFlag1Position()[0];
double flagY = field.getFlag1Position()[1];
double distX = (flagX - this.x); // X distance to travel
double distY = (flagY - this.y); // Y Distance to travel
double totalDist =Math.pow(Math.pow(distX,2) + Math.pow(distY,2),0.5);
this.speedX = ((MAX_SPEED*distX)/totalDist); //Determine Speed Ratio based off of 'Cross Multiply and Divide'
this.speedY = ((MAX_SPEED*distY)/totalDist);
// Max Speed X/Y Speed
// --------- = ----------
// TotalDist X/Y Dist
} else { // Entity is on blue team and should look for red flag
double flagX = field.getFlag2Position()[0];
double flagY = field.getFlag2Position()[1];
double distX = (flagX - this.x); // X distance to travel
double distY = (flagY - this.y); // Y Distance to travel
double totalDist =Math.pow(Math.pow(distX,2) + Math.pow(distY,2),0.5);
this.speedX = ((MAX_SPEED*distX)/totalDist); //Determine Speed Ratio based off of 'Cross Multiply and Divide'
this.speedY = ((MAX_SPEED*distY)/totalDist);
// Max Speed X/Y Speed
// --------- = ----------
// TotalDist X/Y Dist
}
} else{
this.speedX = 0;
this.speedY = 0;
}
// Update the player's speed based on their proximity to the border of the field
if ((this.x >= (field.maxX-16)) || (this.x <= (field.minX-16)) || (this.y >= (field.maxY-16)) || (this.y <= (field.minY-16))){
this.speedX = -this.speedX;
this.speedY = -this.speedY;
}
}
/** create a player that has some random motion
* <p>
* the player starts in a random direction
*
* @param f is the field the player will be playing on
* @param side is the side of the field the player will play on
* @param name is this player's name
* @param number is this player's number
* @param team is this player's team's name
* @param symbol is a character representation of this player
* @param x is the initial x position of this player
* @param y is the initial y position of this player
*/
public Seeker(Field f, int side, String name, int number, String team,char symbol, double x, double y){
super(f, side, name, number, team, symbol, x, y);
this.speedX = -1 + Math.random()*(4-2);
this.speedY = -1 + Math.random()*(4-2);
}
} | 3,346 | 0.518231 | 0.508667 | 78 | 40.923077 | 32.358871 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.602564 | false | false | 6 |
ce0a4728393d05a80e3004c2d0b4561220264383 | 19,670,950,243,072 | cf67e22eebbcd116b7f2286b4eca37936cb88467 | /src/main/java/netherwulf/springframework/knowledgejar/models/Subchapter.java | 7e22c75e43a1989c256fadb92561ce894fa40a14 | [
"MIT"
] | permissive | Netherwulf/knowledge-jar-server | https://github.com/Netherwulf/knowledge-jar-server | 4eb3103a45a92d7bb62fd0241dc9d8d12776bb3b | 9b103b290d51ad57830a219059b270659ceff98e | refs/heads/master | 2020-04-02T22:16:43.716000 | 2018-11-18T20:43:27 | 2018-11-18T20:43:27 | 154,827,826 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package netherwulf.springframework.knowledgejar.models;
import javax.persistence.*;
@Entity
public class Subchapter {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String content;
private String codeLink;
@ManyToOne(cascade = {CascadeType.ALL})
private Chapter chapter;
@OneToOne(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER)
private OpenQuestion openQuestion;
@OneToOne(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER)
private ClosedQuestion closedQuestion;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getCodeLink() {
return codeLink;
}
public void setCodeLink(String codeLink) {
this.codeLink = codeLink;
}
public Chapter getChapter() {
return chapter;
}
public void setChapter(Chapter chapter) {
this.chapter = chapter;
}
public OpenQuestion getOpenQuestion() {
return openQuestion;
}
public void setOpenQuestion(OpenQuestion openQuestion) {
this.openQuestion = openQuestion;
}
public ClosedQuestion getClosedQuestion() {
return closedQuestion;
}
public void setClosedQuestion(ClosedQuestion closedQuestion) {
this.closedQuestion = closedQuestion;
}
}
| UTF-8 | Java | 1,678 | java | Subchapter.java | Java | [] | null | [] | package netherwulf.springframework.knowledgejar.models;
import javax.persistence.*;
@Entity
public class Subchapter {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String content;
private String codeLink;
@ManyToOne(cascade = {CascadeType.ALL})
private Chapter chapter;
@OneToOne(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER)
private OpenQuestion openQuestion;
@OneToOne(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER)
private ClosedQuestion closedQuestion;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getCodeLink() {
return codeLink;
}
public void setCodeLink(String codeLink) {
this.codeLink = codeLink;
}
public Chapter getChapter() {
return chapter;
}
public void setChapter(Chapter chapter) {
this.chapter = chapter;
}
public OpenQuestion getOpenQuestion() {
return openQuestion;
}
public void setOpenQuestion(OpenQuestion openQuestion) {
this.openQuestion = openQuestion;
}
public ClosedQuestion getClosedQuestion() {
return closedQuestion;
}
public void setClosedQuestion(ClosedQuestion closedQuestion) {
this.closedQuestion = closedQuestion;
}
}
| 1,678 | 0.647795 | 0.647795 | 81 | 19.716049 | 19.476631 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.308642 | false | false | 6 |
77ac49fce6d8847758227eca5022144c1e8a61d0 | 6,425,271,075,619 | 76fc424e4068a58b536764d77add05461081b992 | /project/src/main/java/org/softuni/accounting/areas/users/domain/models/binding/UserEditBindingModel.java | ccd36e2d8c150d23a71de7bd1089b161ef66c3b2 | [
"MIT"
] | permissive | martinmihov/JavaWeb | https://github.com/martinmihov/JavaWeb | 9c16886568c0906c2efc2fed80c4f6ff582007dd | c71ed97bebff5db555afe967d4b16af7b13ed345 | refs/heads/master | 2021-09-13T01:42:32.579000 | 2018-04-23T14:49:03 | 2018-04-23T14:49:03 | 118,328,294 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.softuni.accounting.areas.users.domain.models.binding;
import org.softuni.accounting.utils.constants.UserConstants;
import org.softuni.accounting.validations.annotations.password.PasswordMatch;
import org.springframework.web.multipart.MultipartFile;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;
import java.util.Date;
import java.util.Set;
@PasswordMatch
public class UserEditBindingModel {
private String username;
private String password;
private String confirmPassword;
private String email;
private String opinion;
private MultipartFile image;
private Set<Long> rolesIds;
private Date deletedOn;
public UserEditBindingModel() { }
@NotEmpty(message = UserConstants.EMAIL_EMPTY_MESSAGE)
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
@NotEmpty(message = UserConstants.USERNAME_EMPTY_MESSAGE)
@Size(min = UserConstants.USERNAME_MIN_LENGTH,
max = UserConstants.USERNAME_MAX_LENGTH,
message = UserConstants.USERNAME_SIZE_MESSAGE)
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
@Size(min = UserConstants.PASSWORD_AND_CONFIRM_PASSWORD_MIN_LENGTH,
max = UserConstants.PASSWORD_AND_CONFIRM_PASSWORD_MAX_LENGTH,
message = UserConstants.PASSWORD_SIZE_MESSAGE)
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
@Size(min = UserConstants.PASSWORD_AND_CONFIRM_PASSWORD_MIN_LENGTH,
max = UserConstants.PASSWORD_AND_CONFIRM_PASSWORD_MAX_LENGTH,
message = UserConstants.PASSWORD_CONFIRM_SIZE_MESSAGE)
public String getConfirmPassword() {
return this.confirmPassword;
}
public void setConfirmPassword(String confirmPassword) {
this.confirmPassword = confirmPassword;
}
public String getOpinion() {
return this.opinion;
}
public void setOpinion(String opinion) {
this.opinion = opinion;
}
public MultipartFile getImage() {
return this.image;
}
public void setImage(MultipartFile image) {
this.image = image;
}
public Set<Long> getRolesIds() {
return this.rolesIds;
}
public void setRolesIds(Set<Long> rolesIds) {
this.rolesIds = rolesIds;
}
public Date getDeletedOn() {
return this.deletedOn;
}
public void setDeletedOn(Date deletedOn) {
this.deletedOn = deletedOn;
}
}
| UTF-8 | Java | 2,734 | java | UserEditBindingModel.java | Java | [] | null | [] | package org.softuni.accounting.areas.users.domain.models.binding;
import org.softuni.accounting.utils.constants.UserConstants;
import org.softuni.accounting.validations.annotations.password.PasswordMatch;
import org.springframework.web.multipart.MultipartFile;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;
import java.util.Date;
import java.util.Set;
@PasswordMatch
public class UserEditBindingModel {
private String username;
private String password;
private String confirmPassword;
private String email;
private String opinion;
private MultipartFile image;
private Set<Long> rolesIds;
private Date deletedOn;
public UserEditBindingModel() { }
@NotEmpty(message = UserConstants.EMAIL_EMPTY_MESSAGE)
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
@NotEmpty(message = UserConstants.USERNAME_EMPTY_MESSAGE)
@Size(min = UserConstants.USERNAME_MIN_LENGTH,
max = UserConstants.USERNAME_MAX_LENGTH,
message = UserConstants.USERNAME_SIZE_MESSAGE)
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
@Size(min = UserConstants.PASSWORD_AND_CONFIRM_PASSWORD_MIN_LENGTH,
max = UserConstants.PASSWORD_AND_CONFIRM_PASSWORD_MAX_LENGTH,
message = UserConstants.PASSWORD_SIZE_MESSAGE)
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
@Size(min = UserConstants.PASSWORD_AND_CONFIRM_PASSWORD_MIN_LENGTH,
max = UserConstants.PASSWORD_AND_CONFIRM_PASSWORD_MAX_LENGTH,
message = UserConstants.PASSWORD_CONFIRM_SIZE_MESSAGE)
public String getConfirmPassword() {
return this.confirmPassword;
}
public void setConfirmPassword(String confirmPassword) {
this.confirmPassword = confirmPassword;
}
public String getOpinion() {
return this.opinion;
}
public void setOpinion(String opinion) {
this.opinion = opinion;
}
public MultipartFile getImage() {
return this.image;
}
public void setImage(MultipartFile image) {
this.image = image;
}
public Set<Long> getRolesIds() {
return this.rolesIds;
}
public void setRolesIds(Set<Long> rolesIds) {
this.rolesIds = rolesIds;
}
public Date getDeletedOn() {
return this.deletedOn;
}
public void setDeletedOn(Date deletedOn) {
this.deletedOn = deletedOn;
}
}
| 2,734 | 0.683248 | 0.683248 | 107 | 24.551401 | 22.576654 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.35514 | false | false | 6 |
733834ab8b1e71b32ed4d797030c60ccaee72111 | 27,015,344,346,820 | baf8e78e76fa9a1cdffc768f341742583f620b22 | /070_AOP-AspectJ-@AfterReturning/src/main/java/com/mimaraslan/impl/PersonelServisImpl.java | 7ac4802d5c0ce9407f615024878b78f6e1dafc75 | [
"Apache-2.0"
] | permissive | huseyinaydin99/spring-framework | https://github.com/huseyinaydin99/spring-framework | 70b83f8609ce58658e647dd4f809f22a1d639dcb | ad7ee5b23247deb2be159f3b73cba8ffbe539ad5 | refs/heads/master | 2023-02-02T21:00:27.465000 | 2017-07-22T18:34:32 | 2017-07-22T18:34:32 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mimaraslan.impl;
import com.mimaraslan.IPersonelServis;
public class PersonelServisImpl implements IPersonelServis {
private String adi, soyadi;
private int tecrube;
//------------------------------
@Override
public void adiSoyadiKontrolEt() {
System.out.println("Personel servisinin adiSoyadiKontrolEt() metodu");
if (adi.length() < 2 || soyadi.length() < 2) {
throw new IllegalArgumentException();
}
}
/*
@Override
public void selamVer(String mesaj){
System.err.println("Personel servisinin selamVer() metodu "
+ "\nGELEN MESAJ : " + mesaj);
}
*/
@Override
public String selamVer(String mesaj){
System.err.println("Personel servisinin selamVer() metodu "
+ "\nGELEN MESAJ : " + mesaj);
return mesaj;
}
@Override
public void personelBilgisiniVer() {
System.out.println("Personel servisinin personelBilgisiniAl() metodu"
+ "\nADI SOYADI : " + adi + " " + soyadi
+ "\nTECRÜBE : " + tecrube +" yıl");
}
//------------------------------
public String getAdi() {
return adi;
}
public void setAdi(String adi) {
this.adi = adi;
}
//------------------------------
public String getSoyadi() {
return soyadi;
}
public void setSoyadi(String soyadi) {
this.soyadi = soyadi;
}
//------------------------------
public int getTecrube() {
return tecrube;
}
public void setTecrube(int tecrube) {
this.tecrube = tecrube;
}
}
| UTF-8 | Java | 1,493 | java | PersonelServisImpl.java | Java | [] | null | [] | package com.mimaraslan.impl;
import com.mimaraslan.IPersonelServis;
public class PersonelServisImpl implements IPersonelServis {
private String adi, soyadi;
private int tecrube;
//------------------------------
@Override
public void adiSoyadiKontrolEt() {
System.out.println("Personel servisinin adiSoyadiKontrolEt() metodu");
if (adi.length() < 2 || soyadi.length() < 2) {
throw new IllegalArgumentException();
}
}
/*
@Override
public void selamVer(String mesaj){
System.err.println("Personel servisinin selamVer() metodu "
+ "\nGELEN MESAJ : " + mesaj);
}
*/
@Override
public String selamVer(String mesaj){
System.err.println("Personel servisinin selamVer() metodu "
+ "\nGELEN MESAJ : " + mesaj);
return mesaj;
}
@Override
public void personelBilgisiniVer() {
System.out.println("Personel servisinin personelBilgisiniAl() metodu"
+ "\nADI SOYADI : " + adi + " " + soyadi
+ "\nTECRÜBE : " + tecrube +" yıl");
}
//------------------------------
public String getAdi() {
return adi;
}
public void setAdi(String adi) {
this.adi = adi;
}
//------------------------------
public String getSoyadi() {
return soyadi;
}
public void setSoyadi(String soyadi) {
this.soyadi = soyadi;
}
//------------------------------
public int getTecrube() {
return tecrube;
}
public void setTecrube(int tecrube) {
this.tecrube = tecrube;
}
}
| 1,493 | 0.585513 | 0.584172 | 60 | 23.799999 | 21.495581 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.2 | false | false | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.