proj_name
stringclasses
131 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
48
masked_class
stringlengths
78
9.82k
func_body
stringlengths
46
9.61k
len_input
int64
29
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
relevant_context
stringlengths
0
38.4k
jeequan_jeepay
jeepay/jeepay-payment/src/main/java/com/jeequan/jeepay/pay/mq/ResetIsvMchAppInfoMQReceiver.java
ResetIsvMchAppInfoMQReceiver
modifyMchApp
class ResetIsvMchAppInfoMQReceiver implements ResetIsvMchAppInfoConfigMQ.IMQReceiver { @Autowired private ConfigContextService configContextService; @Override public void receive(ResetIsvMchAppInfoConfigMQ.MsgPayload payload) { if(payload.getResetType() == ResetIsvMchAppInfoConfigMQ.RESET_TYPE_ISV_INFO){ this.modifyIsvInfo(payload.getIsvNo()); }else if(payload.getResetType() == ResetIsvMchAppInfoConfigMQ.RESET_TYPE_MCH_INFO){ this.modifyMchInfo(payload.getMchNo()); }else if(payload.getResetType() == ResetIsvMchAppInfoConfigMQ.RESET_TYPE_MCH_APP){ this.modifyMchApp(payload.getMchNo(), payload.getAppId()); } } /** 接收 [商户配置信息] 的消息 **/ private void modifyMchInfo(String mchNo) { log.info("成功接收 [商户配置信息] 的消息, msg={}", mchNo); configContextService.initMchInfoConfigContext(mchNo); log.info(" [商户配置信息] 已重置"); } /** 接收 [商户应用支付参数配置信息] 的消息 **/ private void modifyMchApp(String mchNo, String appId) {<FILL_FUNCTION_BODY>} /** 重置ISV信息 **/ private void modifyIsvInfo(String isvNo) { log.info("成功接收 [ISV信息] 重置, msg={}", isvNo); configContextService.initIsvConfigContext(isvNo); log.info("[ISV信息] 已重置"); } }
log.info("成功接收 [商户应用支付参数配置信息] 的消息, mchNo={}, appId={}", mchNo, appId); configContextService.initMchAppConfigContext(mchNo, appId); log.info(" [商户应用支付参数配置信息] 已重置");
491
83
574
<no_super_class>
jeequan_jeepay
jeepay/jeepay-payment/src/main/java/com/jeequan/jeepay/pay/rqrs/division/DivisionReceiverBindRS.java
DivisionReceiverBindRS
buildByRecord
class DivisionReceiverBindRS extends AbstractRS { /** * 分账接收者ID */ private Long receiverId; /** * 接收者账号别名 */ private String receiverAlias; /** * 组ID(便于商户接口使用) */ private Long receiverGroupId; /** * 商户号 */ private String mchNo; /** * 应用ID */ private String appId; /** * 支付接口代码 */ private String ifCode; /** * 分账接收账号类型: 0-个人(对私) 1-商户(对公) */ private Byte accType; /** * 分账接收账号 */ private String accNo; /** * 分账接收账号名称 */ private String accName; /** * 分账关系类型(参考微信), 如: SERVICE_PROVIDER 服务商等 */ private String relationType; /** * 当选择自定义时,需要录入该字段。 否则为对应的名称 */ private String relationTypeName; /** * 渠道特殊信息 */ private String channelExtInfo; /** * 绑定成功时间 */ private Long bindSuccessTime; /** * 分账比例 */ private BigDecimal divisionProfit; /** * 分账状态 1-绑定成功, 0-绑定异常 */ private Byte bindState; /** * 支付渠道错误码 */ private String errCode; /** * 支付渠道错误信息 */ private String errMsg; public static DivisionReceiverBindRS buildByRecord(MchDivisionReceiver record){<FILL_FUNCTION_BODY>} }
if(record == null){ return null; } DivisionReceiverBindRS result = new DivisionReceiverBindRS(); BeanUtils.copyProperties(record, result); result.setBindSuccessTime(record.getBindSuccessTime() != null ? record.getBindSuccessTime().getTime() : null); return result;
528
89
617
<methods>public non-sealed void <init>() ,public java.lang.String toJSONString() <variables>
jeequan_jeepay
jeepay/jeepay-payment/src/main/java/com/jeequan/jeepay/pay/rqrs/payorder/CommonPayDataRS.java
CommonPayDataRS
buildPayData
class CommonPayDataRS extends UnifiedOrderRS { /** 跳转地址 **/ private String payUrl; /** 二维码地址 **/ private String codeUrl; /** 二维码图片地址 **/ private String codeImgUrl; /** 表单内容 **/ private String formContent; @Override public String buildPayDataType(){ if(StringUtils.isNotEmpty(payUrl)){ return CS.PAY_DATA_TYPE.PAY_URL; } if(StringUtils.isNotEmpty(codeUrl)){ return CS.PAY_DATA_TYPE.CODE_URL; } if(StringUtils.isNotEmpty(codeImgUrl)){ return CS.PAY_DATA_TYPE.CODE_IMG_URL; } if(StringUtils.isNotEmpty(formContent)){ return CS.PAY_DATA_TYPE.FORM; } return CS.PAY_DATA_TYPE.PAY_URL; } @Override public String buildPayData(){<FILL_FUNCTION_BODY>} }
if(StringUtils.isNotEmpty(payUrl)){ return payUrl; } if(StringUtils.isNotEmpty(codeUrl)){ return codeUrl; } if(StringUtils.isNotEmpty(codeImgUrl)){ return codeImgUrl; } if(StringUtils.isNotEmpty(formContent)){ return formContent; } return "";
288
108
396
<methods>public non-sealed void <init>() ,public java.lang.String buildPayData() ,public java.lang.String buildPayDataType() <variables>private com.jeequan.jeepay.pay.rqrs.msg.ChannelRetMsg channelRetMsg,private java.lang.String errCode,private java.lang.String errMsg,private java.lang.String mchOrderNo,private java.lang.Byte orderState,private java.lang.String payData,private java.lang.String payDataType,private java.lang.String payOrderId
jeequan_jeepay
jeepay/jeepay-payment/src/main/java/com/jeequan/jeepay/pay/rqrs/payorder/QueryPayOrderRS.java
QueryPayOrderRS
buildByPayOrder
class QueryPayOrderRS extends AbstractRS { /** * 支付订单号 */ private String payOrderId; /** * 商户号 */ private String mchNo; /** * 商户应用ID */ private String appId; /** * 商户订单号 */ private String mchOrderNo; /** * 支付接口代码 */ private String ifCode; /** * 支付方式代码 */ private String wayCode; /** * 支付金额,单位分 */ private Long amount; /** * 三位货币代码,人民币:cny */ private String currency; /** * 支付状态: 0-订单生成, 1-支付中, 2-支付成功, 3-支付失败, 4-已撤销, 5-已退款, 6-订单关闭 */ private Byte state; /** * 客户端IP */ private String clientIp; /** * 商品标题 */ private String subject; /** * 商品描述信息 */ private String body; /** * 渠道订单号 */ private String channelOrderNo; /** * 渠道支付错误码 */ private String errCode; /** * 渠道支付错误描述 */ private String errMsg; /** * 商户扩展参数 */ private String extParam; /** * 订单支付成功时间 */ private Long successTime; /** * 创建时间 */ private Long createdAt; public static QueryPayOrderRS buildByPayOrder(PayOrder payOrder){<FILL_FUNCTION_BODY>} }
if(payOrder == null){ return null; } QueryPayOrderRS result = new QueryPayOrderRS(); BeanUtils.copyProperties(payOrder, result); result.setSuccessTime(payOrder.getSuccessTime() == null ? null : payOrder.getSuccessTime().getTime()); result.setCreatedAt(payOrder.getCreatedAt() == null ? null : payOrder.getCreatedAt().getTime()); return result;
496
116
612
<methods>public non-sealed void <init>() ,public java.lang.String toJSONString() <variables>
jeequan_jeepay
jeepay/jeepay-payment/src/main/java/com/jeequan/jeepay/pay/rqrs/refund/QueryRefundOrderRS.java
QueryRefundOrderRS
buildByRefundOrder
class QueryRefundOrderRS extends AbstractRS { /** * 退款订单号(支付系统生成订单号) */ private String refundOrderId; /** * 支付订单号(与t_pay_order对应) */ private String payOrderId; /** * 商户号 */ private String mchNo; /** * 应用ID */ private String appId; /** * 商户退款单号(商户系统的订单号) */ private String mchRefundNo; /** * 支付金额,单位分 */ private Long payAmount; /** * 退款金额,单位分 */ private Long refundAmount; /** * 三位货币代码,人民币:cny */ private String currency; /** * 退款状态:0-订单生成,1-退款中,2-退款成功,3-退款失败 */ private Byte state; /** * 渠道订单号 */ private String channelOrderNo; /** * 渠道错误码 */ private String errCode; /** * 渠道错误描述 */ private String errMsg; /** * 扩展参数 */ private String extParam; /** * 订单退款成功时间 */ private Long successTime; /** * 创建时间 */ private Long createdAt; public static QueryRefundOrderRS buildByRefundOrder(RefundOrder refundOrder){<FILL_FUNCTION_BODY>} }
if(refundOrder == null){ return null; } QueryRefundOrderRS result = new QueryRefundOrderRS(); BeanUtils.copyProperties(refundOrder, result); result.setSuccessTime(refundOrder.getSuccessTime() == null ? null : refundOrder.getSuccessTime().getTime()); result.setCreatedAt(refundOrder.getCreatedAt() == null ? null : refundOrder.getCreatedAt().getTime()); return result;
450
121
571
<methods>public non-sealed void <init>() ,public java.lang.String toJSONString() <variables>
jeequan_jeepay
jeepay/jeepay-payment/src/main/java/com/jeequan/jeepay/pay/rqrs/refund/RefundOrderRS.java
RefundOrderRS
buildByRefundOrder
class RefundOrderRS extends AbstractRS { /** 支付系统退款订单号 **/ private String refundOrderId; /** 商户发起的退款订单号 **/ private String mchRefundNo; /** 订单支付金额 **/ private Long payAmount; /** 申请退款金额 **/ private Long refundAmount; /** 退款状态 **/ private Byte state; /** 渠道退款单号 **/ private String channelOrderNo; /** 渠道返回错误代码 **/ private String errCode; /** 渠道返回错误信息 **/ private String errMsg; public static RefundOrderRS buildByRefundOrder(RefundOrder refundOrder){<FILL_FUNCTION_BODY>} }
if(refundOrder == null){ return null; } RefundOrderRS result = new RefundOrderRS(); BeanUtils.copyProperties(refundOrder, result); return result;
209
58
267
<methods>public non-sealed void <init>() ,public java.lang.String toJSONString() <variables>
jeequan_jeepay
jeepay/jeepay-payment/src/main/java/com/jeequan/jeepay/pay/rqrs/transfer/QueryTransferOrderRS.java
QueryTransferOrderRS
buildByRecord
class QueryTransferOrderRS extends AbstractRS { /** * 转账订单号 */ private String transferId; /** * 商户号 */ private String mchNo; /** * 应用ID */ private String appId; /** * 商户订单号 */ private String mchOrderNo; /** * 支付接口代码 */ private String ifCode; /** * 入账方式: WX_CASH-微信零钱; ALIPAY_CASH-支付宝转账; BANK_CARD-银行卡 */ private String entryType; /** * 转账金额,单位分 */ private Long amount; /** * 三位货币代码,人民币:cny */ private String currency; /** * 收款账号 */ private String accountNo; /** * 收款人姓名 */ private String accountName; /** * 收款人开户行名称 */ private String bankName; /** * 转账备注信息 */ private String transferDesc; /** * 支付状态: 0-订单生成, 1-转账中, 2-转账成功, 3-转账失败, 4-订单关闭 */ private Byte state; /** * 特定渠道发起额外参数 */ private String channelExtra; /** * 渠道订单号 */ private String channelOrderNo; /** * 渠道支付错误码 */ private String errCode; /** * 渠道支付错误描述 */ private String errMsg; /** * 商户扩展参数 */ private String extParam; /** * 转账成功时间 */ private Long successTime; /** * 创建时间 */ private Long createdAt; public static QueryTransferOrderRS buildByRecord(TransferOrder record){<FILL_FUNCTION_BODY>} }
if(record == null){ return null; } QueryTransferOrderRS result = new QueryTransferOrderRS(); BeanUtils.copyProperties(record, result); result.setSuccessTime(record.getSuccessTime() == null ? null : record.getSuccessTime().getTime()); result.setCreatedAt(record.getCreatedAt() == null ? null : record.getCreatedAt().getTime()); return result;
573
111
684
<methods>public non-sealed void <init>() ,public java.lang.String toJSONString() <variables>
jeequan_jeepay
jeepay/jeepay-payment/src/main/java/com/jeequan/jeepay/pay/rqrs/transfer/TransferOrderRS.java
TransferOrderRS
buildByRecord
class TransferOrderRS extends AbstractRS { /** 转账单号 **/ private String transferId; /** 商户单号 **/ private String mchOrderNo; /** 转账金额 **/ private Long amount; /** * 收款账号 */ private String accountNo; /** * 收款人姓名 */ private String accountName; /** * 收款人开户行名称 */ private String bankName; /** 状态 **/ private Byte state; /** 渠道退款单号 **/ private String channelOrderNo; /** 渠道返回错误代码 **/ private String errCode; /** 渠道返回错误信息 **/ private String errMsg; public static TransferOrderRS buildByRecord(TransferOrder record){<FILL_FUNCTION_BODY>} }
if(record == null){ return null; } TransferOrderRS result = new TransferOrderRS(); BeanUtils.copyProperties(record, result); return result;
243
52
295
<methods>public non-sealed void <init>() ,public java.lang.String toJSONString() <variables>
jeequan_jeepay
jeepay/jeepay-payment/src/main/java/com/jeequan/jeepay/pay/service/ChannelOrderReissueService.java
ChannelOrderReissueService
processPayOrder
class ChannelOrderReissueService { @Autowired private ConfigContextQueryService configContextQueryService; @Autowired private PayOrderService payOrderService; @Autowired private PayOrderProcessService payOrderProcessService; @Autowired private RefundOrderProcessService refundOrderProcessService; /** 处理订单 **/ public ChannelRetMsg processPayOrder(PayOrder payOrder){<FILL_FUNCTION_BODY>} /** 处理退款订单 **/ public ChannelRetMsg processRefundOrder(RefundOrder refundOrder){ try { String refundOrderId = refundOrder.getRefundOrderId(); //查询支付接口是否存在 IRefundService queryService = SpringBeansUtil.getBean(refundOrder.getIfCode() + "RefundService", IRefundService.class); // 支付通道接口实现不存在 if(queryService == null){ log.error("退款补单:{} interface not exists!", refundOrder.getIfCode()); return null; } //查询出商户应用的配置信息 MchAppConfigContext mchAppConfigContext = configContextQueryService.queryMchInfoAndAppInfo(refundOrder.getMchNo(), refundOrder.getAppId()); ChannelRetMsg channelRetMsg = queryService.query(refundOrder, mchAppConfigContext); if(channelRetMsg == null){ log.error("退款补单:channelRetMsg is null"); return null; } log.info("退款补单:[{}]查询结果为:{}", refundOrderId, channelRetMsg); // 根据渠道返回结果,处理退款订单 refundOrderProcessService.handleRefundOrder4Channel(channelRetMsg, refundOrder); return channelRetMsg; } catch (Exception e) { //继续下一次迭代查询 log.error("退款补单:error refundOrderId = {}", refundOrder.getRefundOrderId(), e); return null; } } }
try { String payOrderId = payOrder.getPayOrderId(); //查询支付接口是否存在 IPayOrderQueryService queryService = SpringBeansUtil.getBean(payOrder.getIfCode() + "PayOrderQueryService", IPayOrderQueryService.class); // 支付通道接口实现不存在 if(queryService == null){ log.error("{} interface not exists!", payOrder.getIfCode()); return null; } //查询出商户应用的配置信息 MchAppConfigContext mchAppConfigContext = configContextQueryService.queryMchInfoAndAppInfo(payOrder.getMchNo(), payOrder.getAppId()); ChannelRetMsg channelRetMsg = queryService.query(payOrder, mchAppConfigContext); if(channelRetMsg == null){ log.error("channelRetMsg is null"); return null; } log.info("补单[{}]查询结果为:{}", payOrderId, channelRetMsg); // 查询成功 if(channelRetMsg.getChannelState() == ChannelRetMsg.ChannelState.CONFIRM_SUCCESS) { if (payOrderService.updateIng2Success(payOrderId, channelRetMsg.getChannelOrderId(), channelRetMsg.getChannelUserId())) { //订单支付成功,其他业务逻辑 payOrderProcessService.confirmSuccess(payOrder); } }else if(channelRetMsg.getChannelState() == ChannelRetMsg.ChannelState.CONFIRM_FAIL){ //确认失败 //1. 更新支付订单表为失败状态 payOrderService.updateIng2Fail(payOrderId, channelRetMsg.getChannelOrderId(), channelRetMsg.getChannelUserId(), channelRetMsg.getChannelErrCode(), channelRetMsg.getChannelErrMsg()); } return channelRetMsg; } catch (Exception e) { //继续下一次迭代查询 log.error("error payOrderId = {}", payOrder.getPayOrderId(), e); return null; }
522
528
1,050
<no_super_class>
jeequan_jeepay
jeepay/jeepay-payment/src/main/java/com/jeequan/jeepay/pay/service/ConfigContextQueryService.java
ConfigContextQueryService
queryIsvParams
class ConfigContextQueryService { @Autowired ConfigContextService configContextService; @Autowired private MchInfoService mchInfoService; @Autowired private MchAppService mchAppService; @Autowired private PayInterfaceConfigService payInterfaceConfigService; private boolean isCache(){ return SysConfigService.IS_USE_CACHE; } public MchApp queryMchApp(String mchNo, String mchAppId){ if(isCache()){ return configContextService.getMchAppConfigContext(mchNo, mchAppId).getMchApp(); } return mchAppService.getOneByMch(mchNo, mchAppId); } public MchAppConfigContext queryMchInfoAndAppInfo(String mchAppId) { return queryMchInfoAndAppInfo(mchAppService.getById(mchAppId).getMchNo(), mchAppId); } public MchAppConfigContext queryMchInfoAndAppInfo(String mchNo, String mchAppId){ if(isCache()){ return configContextService.getMchAppConfigContext(mchNo, mchAppId); } MchInfo mchInfo = mchInfoService.getById(mchNo); MchApp mchApp = queryMchApp(mchNo, mchAppId); if(mchInfo == null || mchApp == null){ return null; } MchAppConfigContext result = new MchAppConfigContext(); result.setMchInfo(mchInfo); result.setMchNo(mchNo); result.setMchType(mchInfo.getType()); result.setMchApp(mchApp); result.setAppId(mchAppId); return result; } public NormalMchParams queryNormalMchParams(String mchNo, String mchAppId, String ifCode){ if(isCache()){ return configContextService.getMchAppConfigContext(mchNo, mchAppId).getNormalMchParamsByIfCode(ifCode); } // 查询商户的所有支持的参数配置 PayInterfaceConfig payInterfaceConfig = payInterfaceConfigService.getOne(PayInterfaceConfig.gw() .select(PayInterfaceConfig::getIfCode, PayInterfaceConfig::getIfParams) .eq(PayInterfaceConfig::getState, CS.YES) .eq(PayInterfaceConfig::getInfoType, CS.INFO_TYPE_MCH_APP) .eq(PayInterfaceConfig::getInfoId, mchAppId) .eq(PayInterfaceConfig::getIfCode, ifCode) ); if(payInterfaceConfig == null){ return null; } return NormalMchParams.factory(payInterfaceConfig.getIfCode(), payInterfaceConfig.getIfParams()); } public IsvsubMchParams queryIsvsubMchParams(String mchNo, String mchAppId, String ifCode){ if(isCache()){ return configContextService.getMchAppConfigContext(mchNo, mchAppId).getIsvsubMchParamsByIfCode(ifCode); } // 查询商户的所有支持的参数配置 PayInterfaceConfig payInterfaceConfig = payInterfaceConfigService.getOne(PayInterfaceConfig.gw() .select(PayInterfaceConfig::getIfCode, PayInterfaceConfig::getIfParams) .eq(PayInterfaceConfig::getState, CS.YES) .eq(PayInterfaceConfig::getInfoType, CS.INFO_TYPE_MCH_APP) .eq(PayInterfaceConfig::getInfoId, mchAppId) .eq(PayInterfaceConfig::getIfCode, ifCode) ); if(payInterfaceConfig == null){ return null; } return IsvsubMchParams.factory(payInterfaceConfig.getIfCode(), payInterfaceConfig.getIfParams()); } public IsvParams queryIsvParams(String isvNo, String ifCode){<FILL_FUNCTION_BODY>} public AlipayClientWrapper getAlipayClientWrapper(MchAppConfigContext mchAppConfigContext){ if(isCache()){ return configContextService.getMchAppConfigContext(mchAppConfigContext.getMchNo(), mchAppConfigContext.getAppId()).getAlipayClientWrapper(); } if(mchAppConfigContext.isIsvsubMch()){ AlipayIsvParams alipayParams = (AlipayIsvParams)queryIsvParams(mchAppConfigContext.getMchInfo().getIsvNo(), CS.IF_CODE.ALIPAY); return AlipayClientWrapper.buildAlipayClientWrapper(alipayParams); }else{ AlipayNormalMchParams alipayParams = (AlipayNormalMchParams)queryNormalMchParams(mchAppConfigContext.getMchNo(), mchAppConfigContext.getAppId(), CS.IF_CODE.ALIPAY); return AlipayClientWrapper.buildAlipayClientWrapper(alipayParams); } } public WxServiceWrapper getWxServiceWrapper(MchAppConfigContext mchAppConfigContext){ if(isCache()){ return configContextService.getMchAppConfigContext(mchAppConfigContext.getMchNo(), mchAppConfigContext.getAppId()).getWxServiceWrapper(); } if(mchAppConfigContext.isIsvsubMch()){ WxpayIsvParams wxParams = (WxpayIsvParams)queryIsvParams(mchAppConfigContext.getMchInfo().getIsvNo(), CS.IF_CODE.WXPAY); return WxServiceWrapper.buildWxServiceWrapper(wxParams); }else{ WxpayNormalMchParams wxParams = (WxpayNormalMchParams)queryNormalMchParams(mchAppConfigContext.getMchNo(), mchAppConfigContext.getAppId(), CS.IF_CODE.WXPAY); return WxServiceWrapper.buildWxServiceWrapper(wxParams); } } public PaypalWrapper getPaypalWrapper(MchAppConfigContext mchAppConfigContext){ if(isCache()){ return configContextService.getMchAppConfigContext(mchAppConfigContext.getMchNo(), mchAppConfigContext.getAppId()).getPaypalWrapper(); } PppayNormalMchParams ppPayNormalMchParams = (PppayNormalMchParams) queryNormalMchParams(mchAppConfigContext.getMchNo(), mchAppConfigContext.getAppId(), CS.IF_CODE.PPPAY);; return PaypalWrapper.buildPaypalWrapper(ppPayNormalMchParams); } }
if(isCache()){ IsvConfigContext isvConfigContext = configContextService.getIsvConfigContext(isvNo); return isvConfigContext == null ? null : isvConfigContext.getIsvParamsByIfCode(ifCode); } // 查询商户的所有支持的参数配置 PayInterfaceConfig payInterfaceConfig = payInterfaceConfigService.getOne(PayInterfaceConfig.gw() .select(PayInterfaceConfig::getIfCode, PayInterfaceConfig::getIfParams) .eq(PayInterfaceConfig::getState, CS.YES) .eq(PayInterfaceConfig::getInfoType, CS.INFO_TYPE_ISV) .eq(PayInterfaceConfig::getInfoId, isvNo) .eq(PayInterfaceConfig::getIfCode, ifCode) ); if(payInterfaceConfig == null){ return null; } return IsvParams.factory(payInterfaceConfig.getIfCode(), payInterfaceConfig.getIfParams());
1,738
249
1,987
<no_super_class>
jeequan_jeepay
jeepay/jeepay-payment/src/main/java/com/jeequan/jeepay/pay/service/PayOrderProcessService.java
PayOrderProcessService
updatePayOrderAutoDivision
class PayOrderProcessService { @Autowired private PayOrderService payOrderService; @Autowired private PayMchNotifyService payMchNotifyService; @Autowired private IMQSender mqSender; /** 明确成功的处理逻辑(除更新订单其他业务) **/ public void confirmSuccess(PayOrder payOrder){ // 查询查询订单详情 payOrder = payOrderService.getById(payOrder.getPayOrderId()); //设置订单状态 payOrder.setState(PayOrder.STATE_SUCCESS); //自动分账 处理逻辑, 不影响主订单任务 this.updatePayOrderAutoDivision(payOrder); //发送商户通知 payMchNotifyService.payOrderNotify(payOrder); } /** 更新订单自动分账业务 **/ private void updatePayOrderAutoDivision(PayOrder payOrder){<FILL_FUNCTION_BODY>} }
try { //默认不分账 || 其他非【自动分账】逻辑时, 不处理 if(payOrder == null || payOrder.getDivisionMode() == null || payOrder.getDivisionMode() != PayOrder.DIVISION_MODE_AUTO){ return ; } //更新订单表分账状态为: 等待分账任务处理 boolean updDivisionState = payOrderService.update(new LambdaUpdateWrapper<PayOrder>() .set(PayOrder::getDivisionState, PayOrder.DIVISION_STATE_WAIT_TASK) .eq(PayOrder::getPayOrderId, payOrder.getPayOrderId()) .eq(PayOrder::getDivisionState, PayOrder.DIVISION_STATE_UNHAPPEN) ); if(updDivisionState){ //推送到分账MQ mqSender.send(PayOrderDivisionMQ.build(payOrder.getPayOrderId(), CS.YES,null), 80); //80s 后执行 } } catch (Exception e) { log.error("订单[{}]自动分账逻辑异常:", payOrder.getPayOrderId(), e); }
260
318
578
<no_super_class>
jeequan_jeepay
jeepay/jeepay-payment/src/main/java/com/jeequan/jeepay/pay/service/RefundOrderProcessService.java
RefundOrderProcessService
handleRefundOrder4Channel
class RefundOrderProcessService { @Autowired private RefundOrderService refundOrderService; @Autowired private PayMchNotifyService payMchNotifyService; /** 根据通道返回的状态,处理退款订单业务 **/ public boolean handleRefundOrder4Channel(ChannelRetMsg channelRetMsg, RefundOrder refundOrder){<FILL_FUNCTION_BODY>} }
boolean updateOrderSuccess = true; //默认更新成功 String refundOrderId = refundOrder.getRefundOrderId(); // 明确退款成功 if(channelRetMsg.getChannelState() == ChannelRetMsg.ChannelState.CONFIRM_SUCCESS) { updateOrderSuccess = refundOrderService.updateIng2Success(refundOrderId, channelRetMsg.getChannelOrderId()); if (updateOrderSuccess) { // 通知商户系统 if(StringUtils.isNotEmpty(refundOrder.getNotifyUrl())){ payMchNotifyService.refundOrderNotify(refundOrderService.getById(refundOrderId)); } } //确认失败 }else if(channelRetMsg.getChannelState() == ChannelRetMsg.ChannelState.CONFIRM_FAIL){ // 更新为失败状态 updateOrderSuccess = refundOrderService.updateIng2Fail(refundOrderId, channelRetMsg.getChannelOrderId(), channelRetMsg.getChannelErrCode(), channelRetMsg.getChannelErrMsg()); // 通知商户系统 if(StringUtils.isNotEmpty(refundOrder.getNotifyUrl())){ payMchNotifyService.refundOrderNotify(refundOrderService.getById(refundOrderId)); } } return updateOrderSuccess;
103
334
437
<no_super_class>
jeequan_jeepay
jeepay/jeepay-payment/src/main/java/com/jeequan/jeepay/pay/service/TransferOrderReissueService.java
TransferOrderReissueService
processOrder
class TransferOrderReissueService { @Autowired private ConfigContextQueryService configContextQueryService; @Autowired private TransferOrderService transferOrderService; @Autowired private PayMchNotifyService payMchNotifyService; /** 处理转账订单 **/ public ChannelRetMsg processOrder(TransferOrder transferOrder){<FILL_FUNCTION_BODY>} /** * 处理返回的渠道信息,并更新订单状态 * TransferOrder将对部分信息进行 赋值操作。 * **/ public void processChannelMsg(ChannelRetMsg channelRetMsg, TransferOrder transferOrder){ //对象为空 || 上游返回状态为空, 则无需操作 if(channelRetMsg == null || channelRetMsg.getChannelState() == null){ return ; } //明确成功 if(ChannelRetMsg.ChannelState.CONFIRM_SUCCESS == channelRetMsg.getChannelState()) { this.updateInitOrderStateThrowException(TransferOrder.STATE_SUCCESS, transferOrder, channelRetMsg); payMchNotifyService.transferOrderNotify(transferOrderService.getById(transferOrder.getTransferId())); //明确失败 }else if(ChannelRetMsg.ChannelState.CONFIRM_FAIL == channelRetMsg.getChannelState()) { this.updateInitOrderStateThrowException(TransferOrder.STATE_FAIL, transferOrder, channelRetMsg); payMchNotifyService.transferOrderNotify(transferOrderService.getById(transferOrder.getTransferId())); // 上游处理中 || 未知 || 上游接口返回异常 订单为支付中状态 }else if( ChannelRetMsg.ChannelState.WAITING == channelRetMsg.getChannelState() || ChannelRetMsg.ChannelState.UNKNOWN == channelRetMsg.getChannelState() || ChannelRetMsg.ChannelState.API_RET_ERROR == channelRetMsg.getChannelState() ){ this.updateInitOrderStateThrowException(TransferOrder.STATE_ING, transferOrder, channelRetMsg); // 系统异常: 订单不再处理。 为: 生成状态 }else if( ChannelRetMsg.ChannelState.SYS_ERROR == channelRetMsg.getChannelState()){ }else{ throw new BizException("ChannelState 返回异常!"); } } /** 更新转账单状态 --》 转账单生成--》 其他状态 (向外抛出异常) **/ private void updateInitOrderStateThrowException(byte orderState, TransferOrder transferOrder, ChannelRetMsg channelRetMsg){ transferOrder.setState(orderState); transferOrder.setChannelOrderNo(channelRetMsg.getChannelOrderId()); transferOrder.setErrCode(channelRetMsg.getChannelErrCode()); transferOrder.setErrMsg(channelRetMsg.getChannelErrMsg()); boolean isSuccess = transferOrderService.updateInit2Ing(transferOrder.getTransferId()); if(!isSuccess){ throw new BizException("更新转账单异常!"); } isSuccess = transferOrderService.updateIng2SuccessOrFail(transferOrder.getTransferId(), transferOrder.getState(), channelRetMsg.getChannelOrderId(), channelRetMsg.getChannelErrCode(), channelRetMsg.getChannelErrMsg()); if(!isSuccess){ throw new BizException("更新转账订单异常!"); } } }
try { String transferId = transferOrder.getTransferId(); // 查询转账接口是否存在 ITransferService transferService = SpringBeansUtil.getBean(transferOrder.getIfCode() + "TransferService", ITransferService.class); // 支付通道转账接口实现不存在 if(transferService == null){ log.error("{} interface not exists!", transferOrder.getIfCode()); return null; } // 查询出商户应用的配置信息 MchAppConfigContext mchAppConfigContext = configContextQueryService.queryMchInfoAndAppInfo(transferOrder.getMchNo(), transferOrder.getAppId()); ChannelRetMsg channelRetMsg = transferService.query(transferOrder, mchAppConfigContext); if(channelRetMsg == null){ log.error("channelRetMsg is null"); return null; } log.info("补单[{}]查询结果为:{}", transferId, channelRetMsg); // 查询成功 if(channelRetMsg.getChannelState() == ChannelRetMsg.ChannelState.CONFIRM_SUCCESS) { // 转账成功 transferOrderService.updateIng2Success(transferId, channelRetMsg.getChannelOrderId()); payMchNotifyService.transferOrderNotify(transferOrderService.getById(transferId)); }else if(channelRetMsg.getChannelState() == ChannelRetMsg.ChannelState.CONFIRM_FAIL){ // 转账失败 transferOrderService.updateIng2Fail(transferId, channelRetMsg.getChannelOrderId(), channelRetMsg.getChannelUserId(), channelRetMsg.getChannelErrCode()); payMchNotifyService.transferOrderNotify(transferOrderService.getById(transferId)); } return channelRetMsg; } catch (Exception e) { //继续下一次迭代查询 log.error("error transferId = {}", transferOrder.getTransferId(), e); return null; }
892
530
1,422
<no_super_class>
jeequan_jeepay
jeepay/jeepay-payment/src/main/java/com/jeequan/jeepay/pay/service/ValidateService.java
ValidateService
validate
class ValidateService { @Autowired private Validator validator; public void validate(Object obj){<FILL_FUNCTION_BODY>} }
Set<ConstraintViolation<Object>> resultSet = validator.validate(obj); if(resultSet == null || resultSet.isEmpty()){ return ; } resultSet.stream().forEach(item -> {throw new BizException(item.getMessage());});
44
71
115
<no_super_class>
jeequan_jeepay
jeepay/jeepay-payment/src/main/java/com/jeequan/jeepay/pay/task/PayOrderDivisionRecordReissueTask.java
PayOrderDivisionRecordReissueTask
start
class PayOrderDivisionRecordReissueTask { private static final int QUERY_PAGE_SIZE = 100; //每次查询数量 @Autowired private PayOrderDivisionRecordService payOrderDivisionRecordService; @Autowired private ConfigContextQueryService configContextQueryService; @Autowired private PayOrderService payOrderService; @Scheduled(cron="0 0/1 * * * ?") // 每分钟执行一次 public void start() {<FILL_FUNCTION_BODY>} }
log.info("处理分账补单任务 开始"); //当前时间 减去5分钟。 Date offsetDate = DateUtil.offsetMinute(new Date(), -5); //查询条件: 受理中的订单 & ( 订单创建时间 + 5分钟 >= 当前时间 ) LambdaQueryWrapper<PayOrderDivisionRecord> lambdaQueryWrapper = PayOrderDivisionRecord.gw(). eq(PayOrderDivisionRecord::getState, PayOrderDivisionRecord.STATE_ACCEPT).le(PayOrderDivisionRecord::getCreatedAt, offsetDate); int currentPageIndex = 1; //当前页码 while(true){ try { IPage<PayOrderDivisionRecord> pageRecordList = payOrderDivisionRecordService.getBaseMapper().distinctBatchOrderIdList(new Page(currentPageIndex, QUERY_PAGE_SIZE), lambdaQueryWrapper); log.info("处理分账补单任务, 共计{}条", pageRecordList.getTotal()); //本次查询无结果, 不再继续查询; if(pageRecordList == null || pageRecordList.getRecords() == null || pageRecordList.getRecords().isEmpty()){ break; } for(PayOrderDivisionRecord batchRecord: pageRecordList.getRecords()){ try { String batchOrderId = batchRecord.getBatchOrderId(); // 通过 batchId 查询出列表( 注意: 需要按照ID 排序!!!! ) List<PayOrderDivisionRecord> recordList = payOrderDivisionRecordService.list(PayOrderDivisionRecord.gw() .eq(PayOrderDivisionRecord::getState, PayOrderDivisionRecord.STATE_ACCEPT) .eq(PayOrderDivisionRecord::getBatchOrderId, batchOrderId) .orderByAsc(PayOrderDivisionRecord::getRecordId) ); if(recordList == null || recordList.isEmpty()){ continue; } // 查询支付订单信息 PayOrder payOrder = payOrderService.getById(batchRecord.getPayOrderId()); if (payOrder == null) { log.error("支付订单记录不存在:{}", batchRecord.getPayOrderId()); continue; } // 查询转账接口是否存在 IDivisionService divisionService = SpringBeansUtil.getBean(payOrder.getIfCode() + "DivisionService", IDivisionService.class); if (divisionService == null) { log.error("查询分账接口不存在:{}", payOrder.getIfCode()); continue; } MchAppConfigContext mchAppConfigContext = configContextQueryService.queryMchInfoAndAppInfo(payOrder.getMchNo(), payOrder.getAppId()); // 调用渠道侧的查单接口: 注意: 渠道内需保证: // 1. 返回的条目 必须全部来自recordList, 可以少于recordList但是不得高于 recordList 数量; // 2. recordList 的记录可能与接口返回的数量不一致, 接口实现不要求对条目数量做验证; // 3. 接口查询的记录若recordList 不存在, 忽略即可。 ( 例如两条相同的accNo, 则可能仅匹配一条。 那么另外一条将在下一次循环中处理。 ) // 4. 仅明确状态的再返回,若不明确则不需返回; HashMap<Long, ChannelRetMsg> queryDivision = divisionService.queryDivision(payOrder, recordList, mchAppConfigContext); // 处理查询结果 recordList.stream().forEach(record -> { ChannelRetMsg channelRetMsg = queryDivision.get(record.getRecordId()); // 响应状态为分账成功或失败时,更新该记录状态 if (ChannelRetMsg.ChannelState.CONFIRM_SUCCESS == channelRetMsg.getChannelState() || ChannelRetMsg.ChannelState.CONFIRM_FAIL == channelRetMsg.getChannelState()) { Byte state = ChannelRetMsg.ChannelState.CONFIRM_SUCCESS == channelRetMsg.getChannelState() ? PayOrderDivisionRecord.STATE_SUCCESS : PayOrderDivisionRecord.STATE_FAIL; // 更新记录状态 payOrderDivisionRecordService.updateRecordSuccessOrFailBySingleItem(record.getRecordId(), state, channelRetMsg.getChannelErrMsg()); } }); } catch (Exception e1) { log.error("处理补单任务单条[{}]异常", batchRecord.getBatchOrderId(), e1); } } //已经到达页码最大量,无需再次查询 if(pageRecordList.getPages() <= currentPageIndex){ break; } currentPageIndex++; } catch (Exception e) { //出现异常,直接退出,避免死循环。 log.error("处理分账补单任务, error", e); break; } }
136
1,298
1,434
<no_super_class>
jeequan_jeepay
jeepay/jeepay-payment/src/main/java/com/jeequan/jeepay/pay/task/PayOrderReissueTask.java
PayOrderReissueTask
start
class PayOrderReissueTask { private static final int QUERY_PAGE_SIZE = 100; //每次查询数量 @Autowired private PayOrderService payOrderService; @Autowired private ChannelOrderReissueService channelOrderReissueService; @Scheduled(cron="0 0/1 * * * ?") // 每分钟执行一次 public void start() {<FILL_FUNCTION_BODY>} }
//当前时间 减去10分钟。 Date offsetDate = DateUtil.offsetMinute(new Date(), -10); //查询条件: 支付中的订单 & ( 订单创建时间 + 10分钟 >= 当前时间 ) LambdaQueryWrapper<PayOrder> lambdaQueryWrapper = PayOrder.gw().eq(PayOrder::getState, PayOrder.STATE_ING).le(PayOrder::getCreatedAt, offsetDate); int currentPageIndex = 1; //当前页码 while(true){ try { IPage<PayOrder> payOrderIPage = payOrderService.page(new Page(currentPageIndex, QUERY_PAGE_SIZE), lambdaQueryWrapper); if(payOrderIPage == null || payOrderIPage.getRecords().isEmpty()){ //本次查询无结果, 不再继续查询; break; } for(PayOrder payOrder: payOrderIPage.getRecords()){ channelOrderReissueService.processPayOrder(payOrder); } //已经到达页码最大量,无需再次查询 if(payOrderIPage.getPages() <= currentPageIndex){ break; } currentPageIndex++; } catch (Exception e) { //出现异常,直接退出,避免死循环。 log.error("error", e); break; } }
117
355
472
<no_super_class>
jeequan_jeepay
jeepay/jeepay-payment/src/main/java/com/jeequan/jeepay/pay/task/RefundOrderReissueTask.java
RefundOrderReissueTask
start
class RefundOrderReissueTask { private static final int QUERY_PAGE_SIZE = 100; //每次查询数量 @Autowired private RefundOrderService refundOrderService; @Autowired private ChannelOrderReissueService channelOrderReissueService; @Scheduled(cron="0 0/1 * * * ?") // 每分钟执行一次 public void start() {<FILL_FUNCTION_BODY>} }
//查询条件: 退款中的订单 LambdaQueryWrapper<RefundOrder> lambdaQueryWrapper = RefundOrder.gw().eq(RefundOrder::getState, RefundOrder.STATE_ING); int currentPageIndex = 1; //当前页码 while(true){ try { IPage<RefundOrder> refundOrderIPage = refundOrderService.page(new Page(currentPageIndex, QUERY_PAGE_SIZE), lambdaQueryWrapper); if(refundOrderIPage == null || refundOrderIPage.getRecords().isEmpty()){ //本次查询无结果, 不再继续查询; break; } for(RefundOrder refundOrder: refundOrderIPage.getRecords()){ channelOrderReissueService.processRefundOrder(refundOrder); } //已经到达页码最大量,无需再次查询 if(refundOrderIPage.getPages() <= currentPageIndex){ break; } currentPageIndex++; } catch (Exception e) { //出现异常,直接退出,避免死循环。 log.error("error", e); break; } }
119
301
420
<no_super_class>
jeequan_jeepay
jeepay/jeepay-payment/src/main/java/com/jeequan/jeepay/pay/task/TransferOrderReissueTask.java
TransferOrderReissueTask
start
class TransferOrderReissueTask { private static final int QUERY_PAGE_SIZE = 100; //每次查询数量 @Autowired private TransferOrderService transferOrderService; @Autowired private TransferOrderReissueService transferOrderReissueService; @Scheduled(cron="0 0/1 * * * ?") // 每分钟执行一次 public void start() {<FILL_FUNCTION_BODY>} }
//查询条件: LambdaQueryWrapper<TransferOrder> lambdaQueryWrapper = TransferOrder.gw() .eq(TransferOrder::getState, TransferOrder.STATE_ING) // 转账中 .ge(TransferOrder::getCreatedAt, DateUtil.offsetDay(new Date(), -1)); // 只查询一天内的转账单; int currentPageIndex = 1; //当前页码 while(true){ try { IPage<TransferOrder> iPage = transferOrderService.page(new Page(currentPageIndex, QUERY_PAGE_SIZE), lambdaQueryWrapper); if(iPage == null || iPage.getRecords().isEmpty()){ //本次查询无结果, 不再继续查询; break; } for(TransferOrder transferOrder: iPage.getRecords()){ transferOrderReissueService.processOrder(transferOrder); } //已经到达页码最大量,无需再次查询 if(iPage.getPages() <= currentPageIndex){ break; } currentPageIndex++; } catch (Exception e) { //出现异常,直接退出,避免死循环。 log.error("error", e); break; } }
117
321
438
<no_super_class>
jeequan_jeepay
jeepay/jeepay-payment/src/main/java/com/jeequan/jeepay/pay/util/ApiResBuilder.java
ApiResBuilder
buildSuccess
class ApiResBuilder { /** 构建自定义响应对象, 默认响应成功 **/ public static <T extends AbstractRS> T buildSuccess(Class<? extends AbstractRS> T){<FILL_FUNCTION_BODY>} }
try { T result = (T)T.newInstance(); return result; } catch (Exception e) { return null; }
66
40
106
<no_super_class>
jeequan_jeepay
jeepay/jeepay-payment/src/main/java/com/jeequan/jeepay/pay/util/ChannelCertConfigKitBean.java
ChannelCertConfigKitBean
downloadFile
class ChannelCertConfigKitBean { @Autowired private OssYmlConfig ossYmlConfig; @Autowired private IOssService ossService; public String getCertFilePath(String certFilePath){ return getCertFile(certFilePath).getAbsolutePath(); } public File getCertFile(String certFilePath){ File certFile = new File(ossYmlConfig.getOss().getFilePrivatePath() + File.separator + certFilePath); if(certFile.exists()){ // 本地存在直接返回 return certFile; } // 以下为 文件不存在的处理方式 // 是否本地存储 boolean isLocalSave = OssServiceTypeEnum.LOCAL.getServiceName().equals(ossYmlConfig.getOss().getServiceType()); // 本地存储 & 文件不存在 if(isLocalSave){ return certFile; } // 已经向oss请求并且返回了空文件时 if(new File(certFile.getAbsolutePath() + ".notexists").exists()){ return certFile; } // 当文件夹不存在时, 需要创建。 if(!certFile.getParentFile().exists()){ certFile.getParentFile().mkdirs(); } // 请求下载并返回 新File return downloadFile(certFilePath, certFile); } /** 下载文件 **/ private synchronized File downloadFile(String dbCertFilePath, File certFile){<FILL_FUNCTION_BODY>} }
//请求文件并写入 boolean isSuccess = ossService.downloadFile(OssSavePlaceEnum.PRIVATE, dbCertFilePath, certFile.getAbsolutePath()); // 下载成功 返回新的File对象 if(isSuccess) { return new File(certFile.getAbsolutePath()); } // 下载失败, 写入.notexists文件, 避免那下次再次下载影响效率。 try { new File(certFile.getAbsolutePath() + ".notexists").createNewFile(); } catch (IOException e) { } return certFile;
409
161
570
<no_super_class>
jeequan_jeepay
jeepay/jeepay-payment/src/main/java/com/jeequan/jeepay/pay/util/PaywayUtil.java
PaywayUtil
getRealPaywayV3Service
class PaywayUtil { private static final String PAYWAY_PACKAGE_NAME = "payway"; private static final String PAYWAYV3_PACKAGE_NAME = "paywayV3"; /** 获取真实的支付方式Service **/ public static IPaymentService getRealPaywayService(Object obj, String wayCode){ try { //下划线转换驼峰 & 首字母大写 String clsName = StrUtil.upperFirst(StrUtil.toCamelCase(wayCode.toLowerCase())); return (IPaymentService) SpringBeansUtil.getBean( Class.forName(obj.getClass().getPackage().getName() + "." + PAYWAY_PACKAGE_NAME + "." + clsName) ); } catch (ClassNotFoundException e) { return null; } } /** 获取微信V3真实的支付方式Service **/ public static IPaymentService getRealPaywayV3Service(Object obj, String wayCode){<FILL_FUNCTION_BODY>} }
try { //下划线转换驼峰 & 首字母大写 String clsName = StrUtil.upperFirst(StrUtil.toCamelCase(wayCode.toLowerCase())); return (IPaymentService) SpringBeansUtil.getBean( Class.forName(obj.getClass().getPackage().getName() + "." + PAYWAYV3_PACKAGE_NAME + "." + clsName) ); } catch (ClassNotFoundException e) { return null; }
279
140
419
<no_super_class>
jeequan_jeepay
jeepay/jeepay-service/src/main/java/com/jeequan/jeepay/service/impl/IsvInfoService.java
IsvInfoService
removeByIsvNo
class IsvInfoService extends ServiceImpl<IsvInfoMapper, IsvInfo> { @Autowired private MchInfoService mchInfoService; @Autowired private IsvInfoService isvInfoService; @Autowired private PayInterfaceConfigService payInterfaceConfigService; @Transactional public void removeByIsvNo(String isvNo) {<FILL_FUNCTION_BODY>} }
// 0.当前服务商是否存在 IsvInfo isvInfo = isvInfoService.getById(isvNo); if (isvInfo == null) { throw new BizException("该服务商不存在"); } // 1.查询当前服务商下是否存在商户 int mchCount = mchInfoService.count(MchInfo.gw().eq(MchInfo::getIsvNo, isvNo).eq(MchInfo::getType, CS.MCH_TYPE_ISVSUB)); if (mchCount > 0) { throw new BizException("该服务商下存在商户,不可删除"); } // 2.删除当前服务商支付接口配置参数 payInterfaceConfigService.remove(PayInterfaceConfig.gw() .eq(PayInterfaceConfig::getInfoId, isvNo) .eq(PayInterfaceConfig::getInfoType, CS.INFO_TYPE_ISV) ); // 3.删除该服务商 boolean remove = isvInfoService.removeById(isvNo); if (!remove) { throw new BizException("删除服务商失败"); }
107
298
405
<no_super_class>
jeequan_jeepay
jeepay/jeepay-service/src/main/java/com/jeequan/jeepay/service/impl/MchAppService.java
MchAppService
selectPage
class MchAppService extends ServiceImpl<MchAppMapper, MchApp> { @Autowired private PayOrderService payOrderService; @Autowired private MchPayPassageService mchPayPassageService; @Autowired private PayInterfaceConfigService payInterfaceConfigService; @Transactional(rollbackFor = Exception.class) public void removeByAppId(String appId) { // 1.查看当前应用是否存在交易数据 int payCount = payOrderService.count(PayOrder.gw().eq(PayOrder::getAppId, appId)); if (payCount > 0) { throw new BizException("该应用已存在交易数据,不可删除"); } // 2.删除应用关联的支付通道 mchPayPassageService.remove(MchPayPassage.gw().eq(MchPayPassage::getAppId, appId)); // 3.删除应用配置的支付参数 payInterfaceConfigService.remove(PayInterfaceConfig.gw() .eq(PayInterfaceConfig::getInfoId, appId) .eq(PayInterfaceConfig::getInfoType, CS.INFO_TYPE_MCH_APP) ); // 4.删除当前应用 if (!removeById(appId)) { throw new BizException(ApiCodeEnum.SYS_OPERATION_FAIL_DELETE); } } public MchApp selectById(String appId) { MchApp mchApp = this.getById(appId); if (mchApp == null) { return null; } mchApp.setAppSecret(StringKit.str2Star(mchApp.getAppSecret(), 6, 6, 6)); return mchApp; } public IPage<MchApp> selectPage(IPage iPage, MchApp mchApp) {<FILL_FUNCTION_BODY>} public MchApp getOneByMch(String mchNo, String appId){ return getOne(MchApp.gw().eq(MchApp::getMchNo, mchNo).eq(MchApp::getAppId, appId)); } }
LambdaQueryWrapper<MchApp> wrapper = MchApp.gw(); if (StringUtils.isNotBlank(mchApp.getMchNo())) { wrapper.eq(MchApp::getMchNo, mchApp.getMchNo()); } if (StringUtils.isNotEmpty(mchApp.getAppId())) { wrapper.eq(MchApp::getAppId, mchApp.getAppId()); } if (StringUtils.isNotEmpty(mchApp.getAppName())) { wrapper.eq(MchApp::getAppName, mchApp.getAppName()); } if (mchApp.getState() != null) { wrapper.eq(MchApp::getState, mchApp.getState()); } wrapper.orderByDesc(MchApp::getCreatedAt); IPage<MchApp> pages = this.page(iPage, wrapper); pages.getRecords().stream().forEach(item -> item.setAppSecret(StringKit.str2Star(item.getAppSecret(), 6, 6, 6))); return pages;
556
289
845
<no_super_class>
jeequan_jeepay
jeepay/jeepay-service/src/main/java/com/jeequan/jeepay/service/impl/MchInfoService.java
MchInfoService
addMch
class MchInfoService extends ServiceImpl<MchInfoMapper, MchInfo> { @Autowired private SysUserService sysUserService; @Autowired private PayOrderService payOrderService; @Autowired private MchPayPassageService mchPayPassageService; @Autowired private PayInterfaceConfigService payInterfaceConfigService; @Autowired private SysUserAuthService sysUserAuthService; @Autowired private IsvInfoService isvInfoService; @Autowired private MchAppService mchAppService; @Transactional(rollbackFor = Exception.class) public void addMch(MchInfo mchInfo, String loginUserName) {<FILL_FUNCTION_BODY>} /** 删除商户 **/ @Transactional(rollbackFor = Exception.class) public List<Long> removeByMchNo(String mchNo) { try { // 0.当前商户是否存在 MchInfo mchInfo = getById(mchNo); if (mchInfo == null) { throw new BizException("该商户不存在"); } // 1.查看当前商户是否存在交易数据 int payCount = payOrderService.count(PayOrder.gw().eq(PayOrder::getMchNo, mchNo)); if (payCount > 0) { throw new BizException("该商户已存在交易数据,不可删除"); } // 2.删除当前商户配置的支付通道 mchPayPassageService.remove(MchPayPassage.gw().eq(MchPayPassage::getMchNo, mchNo)); // 3.删除当前商户支付接口配置参数 List<String> appIdList = new LinkedList<>(); mchAppService.list(MchApp.gw().eq(MchApp::getMchNo, mchNo)).forEach(item -> appIdList.add(item.getAppId())); if (CollectionUtils.isNotEmpty(appIdList)) { payInterfaceConfigService.remove(PayInterfaceConfig.gw() .in(PayInterfaceConfig::getInfoId, appIdList) .eq(PayInterfaceConfig::getInfoType, CS.INFO_TYPE_MCH_APP) ); } List<SysUser> userList = sysUserService.list(SysUser.gw() .eq(SysUser::getBelongInfoId, mchNo) .eq(SysUser::getSysType, CS.SYS_TYPE.MCH) ); // 4.删除当前商户应用信息 if (CollectionUtils.isNotEmpty(appIdList)) { mchAppService.removeByIds(appIdList); } // 返回的用户id List<Long> userIdList = new ArrayList<>(); if (CollectionUtils.isNotEmpty(userList)) { for (SysUser user:userList) { userIdList.add(user.getSysUserId()); } // 5.删除当前商户用户子用户信息 sysUserAuthService.remove(SysUserAuth.gw().in(SysUserAuth::getUserId, userIdList)); } // 6.删除当前商户的登录用户 sysUserService.remove(SysUser.gw() .eq(SysUser::getBelongInfoId, mchNo) .eq(SysUser::getSysType, CS.SYS_TYPE.MCH) ); // 7.删除当前商户 boolean removeMchInfo = removeById(mchNo); if (!removeMchInfo) { throw new BizException("删除当前商户失败"); } return userIdList; }catch (Exception e) { throw new BizException(e.getMessage()); } } }
// 校验特邀商户信息 if (mchInfo.getType() == CS.MCH_TYPE_ISVSUB && StringUtils.isNotEmpty(mchInfo.getIsvNo())) { // 当前服务商状态是否正确 IsvInfo isvInfo = isvInfoService.getById(mchInfo.getIsvNo()); if (isvInfo == null || isvInfo.getState() == CS.NO) { throw new BizException("当前服务商不可用"); } } // 插入商户基本信息 boolean saveResult = save(mchInfo); if (!saveResult) { throw new BizException(ApiCodeEnum.SYS_OPERATION_FAIL_CREATE); } // 插入用户信息 SysUser sysUser = new SysUser(); sysUser.setLoginUsername(loginUserName); sysUser.setRealname(mchInfo.getContactName()); sysUser.setTelphone(mchInfo.getContactTel()); sysUser.setUserNo(mchInfo.getMchNo()); sysUser.setBelongInfoId(mchInfo.getMchNo()); sysUser.setSex(CS.SEX_MALE); sysUser.setIsAdmin(CS.YES); sysUser.setState(mchInfo.getState()); sysUserService.addSysUser(sysUser, CS.SYS_TYPE.MCH); // 插入商户默认应用 MchApp mchApp = new MchApp(); mchApp.setAppId(IdUtil.objectId()); mchApp.setMchNo(mchInfo.getMchNo()); mchApp.setAppName("默认应用"); mchApp.setAppSecret(RandomUtil.randomString(128)); mchApp.setState(CS.YES); mchApp.setCreatedBy(sysUser.getRealname()); mchApp.setCreatedUid(sysUser.getSysUserId()); saveResult = mchAppService.save(mchApp); if (!saveResult) { throw new BizException(ApiCodeEnum.SYS_OPERATION_FAIL_CREATE); } // 存入商户默认用户ID MchInfo updateRecord = new MchInfo(); updateRecord.setMchNo(mchInfo.getMchNo()); updateRecord.setInitUserId(sysUser.getSysUserId()); saveResult = updateById(updateRecord); if (!saveResult) { throw new BizException(ApiCodeEnum.SYS_OPERATION_FAIL_CREATE); }
992
681
1,673
<no_super_class>
jeequan_jeepay
jeepay/jeepay-service/src/main/java/com/jeequan/jeepay/service/impl/MchPayPassageService.java
MchPayPassageService
selectAvailablePayInterfaceList
class MchPayPassageService extends ServiceImpl<MchPayPassageMapper, MchPayPassage> { @Autowired private PayInterfaceDefineService payInterfaceDefineService; /** * @Author: ZhuXiao * @Description: 根据支付方式查询可用的支付接口列表 * @Date: 9:56 2021/5/10 */ public List<JSONObject> selectAvailablePayInterfaceList(String wayCode, String appId, Byte infoType, Byte mchType) {<FILL_FUNCTION_BODY>} @Transactional(rollbackFor = Exception.class) public void saveOrUpdateBatchSelf(List<MchPayPassage> mchPayPassageList, String mchNo) { for (MchPayPassage payPassage : mchPayPassageList) { if (payPassage.getState() == CS.NO && payPassage.getId() == null) { continue; } if (StrUtil.isNotBlank(mchNo)) { // 商户系统配置通道,添加商户号参数 payPassage.setMchNo(mchNo); } if (payPassage.getRate() != null) { payPassage.setRate(payPassage.getRate().divide(new BigDecimal("100"), 6, BigDecimal.ROUND_HALF_UP)); } if (!saveOrUpdate(payPassage)) { throw new BizException("操作失败"); } } } /** 根据应用ID 和 支付方式, 查询出商户可用的支付接口 **/ public MchPayPassage findMchPayPassage(String mchNo, String appId, String wayCode){ List<MchPayPassage> list = list(MchPayPassage.gw() .eq(MchPayPassage::getMchNo, mchNo) .eq(MchPayPassage::getAppId, appId) .eq(MchPayPassage::getState, CS.YES) .eq(MchPayPassage::getWayCode, wayCode) ); if (list.isEmpty()) { return null; }else { // 返回一个可用通道 HashMap<String, MchPayPassage> mchPayPassageMap = new HashMap<>(); for (MchPayPassage mchPayPassage:list) { mchPayPassageMap.put(mchPayPassage.getIfCode(), mchPayPassage); } // 查询ifCode所有接口 PayInterfaceDefine interfaceDefine = payInterfaceDefineService .getOne(PayInterfaceDefine.gw() .select(PayInterfaceDefine::getIfCode, PayInterfaceDefine::getState) .eq(PayInterfaceDefine::getState, CS.YES) .in(PayInterfaceDefine::getIfCode, mchPayPassageMap.keySet()), false); if (interfaceDefine != null) { return mchPayPassageMap.get(interfaceDefine.getIfCode()); } } return null; } }
Map params = new HashMap(); params.put("wayCode", wayCode); params.put("appId", appId); params.put("infoType", infoType); params.put("mchType", mchType); List<JSONObject> list = baseMapper.selectAvailablePayInterfaceList(params); if (CollectionUtils.isEmpty(list)) { return null; } // 添加通道状态 for (JSONObject object : list) { MchPayPassage payPassage = baseMapper.selectOne(MchPayPassage.gw() .eq(MchPayPassage::getAppId, appId) .eq(MchPayPassage::getWayCode, wayCode) .eq(MchPayPassage::getIfCode, object.getString("ifCode")) ); if (payPassage != null) { object.put("passageId", payPassage.getId()); if (payPassage.getRate() != null) { object.put("rate", payPassage.getRate().multiply(new BigDecimal("100"))); } object.put("state", payPassage.getState()); } if(object.getBigDecimal("ifRate") != null) { object.put("ifRate", object.getBigDecimal("ifRate").multiply(new BigDecimal("100"))); } } return list;
810
366
1,176
<no_super_class>
jeequan_jeepay
jeepay/jeepay-service/src/main/java/com/jeequan/jeepay/service/impl/PayInterfaceConfigService.java
PayInterfaceConfigService
selectAllPayIfConfigListByAppId
class PayInterfaceConfigService extends ServiceImpl<PayInterfaceConfigMapper, PayInterfaceConfig> { @Autowired private PayInterfaceDefineService payInterfaceDefineService; @Autowired private MchInfoService mchInfoService; @Autowired private MchAppService mchAppService; /** * @Author: ZhuXiao * @Description: 根据 账户类型、账户号、接口类型 获取支付参数配置 * @Date: 17:20 2021/4/27 */ public PayInterfaceConfig getByInfoIdAndIfCode(Byte infoType, String infoId, String ifCode) { return getOne(PayInterfaceConfig.gw() .eq(PayInterfaceConfig::getInfoType, infoType) .eq(PayInterfaceConfig::getInfoId, infoId) .eq(PayInterfaceConfig::getIfCode, ifCode) ); } /** * @Author: ZhuXiao * @Description: 根据 账户类型、账户号 获取支付参数配置列表 * @Date: 14:19 2021/5/7 */ public List<PayInterfaceDefine> selectAllPayIfConfigListByIsvNo(Byte infoType, String infoId) { // 支付定义列表 LambdaQueryWrapper<PayInterfaceDefine> queryWrapper = PayInterfaceDefine.gw(); queryWrapper.eq(PayInterfaceDefine::getState, CS.YES); queryWrapper.eq(PayInterfaceDefine::getIsIsvMode, CS.YES); // 支持服务商模式 List<PayInterfaceDefine> defineList = payInterfaceDefineService.list(queryWrapper); // 支付参数列表 LambdaQueryWrapper<PayInterfaceConfig> wrapper = PayInterfaceConfig.gw(); wrapper.eq(PayInterfaceConfig::getInfoId, infoId); wrapper.eq(PayInterfaceConfig::getInfoType, infoType); List<PayInterfaceConfig> configList = this.list(wrapper); for (PayInterfaceDefine define : defineList) { for (PayInterfaceConfig config : configList) { if (define.getIfCode().equals(config.getIfCode())) { define.addExt("ifConfigState", config.getState()); // 配置状态 } } } return defineList; } public List<PayInterfaceDefine> selectAllPayIfConfigListByAppId(String appId) {<FILL_FUNCTION_BODY>} /** 查询商户app使用已正确配置了通道信息 */ public boolean mchAppHasAvailableIfCode(String appId, String ifCode){ return this.count( PayInterfaceConfig.gw() .eq(PayInterfaceConfig::getIfCode, ifCode) .eq(PayInterfaceConfig::getState, CS.PUB_USABLE) .eq(PayInterfaceConfig::getInfoId, appId) .eq(PayInterfaceConfig::getInfoType, CS.INFO_TYPE_MCH_APP) ) > 0; } }
MchApp mchApp = mchAppService.getById(appId); if (mchApp == null|| mchApp.getState() != CS.YES) { throw new BizException(ApiCodeEnum.SYS_OPERATION_FAIL_SELETE); } MchInfo mchInfo = mchInfoService.getById(mchApp.getMchNo()); if (mchInfo == null || mchInfo.getState() != CS.YES) { throw new BizException(ApiCodeEnum.SYS_OPERATION_FAIL_SELETE); } // 支付定义列表 LambdaQueryWrapper<PayInterfaceDefine> queryWrapper = PayInterfaceDefine.gw(); queryWrapper.eq(PayInterfaceDefine::getState, CS.YES); Map<String, PayInterfaceConfig> isvPayConfigMap = new HashMap<>(); // 服务商支付参数配置集合 // 根据商户类型,添加接口是否支持该商户类型条件 if (mchInfo.getType() == CS.MCH_TYPE_NORMAL) { queryWrapper.eq(PayInterfaceDefine::getIsMchMode, CS.YES); // 支持普通商户模式 } if (mchInfo.getType() == CS.MCH_TYPE_ISVSUB) { queryWrapper.eq(PayInterfaceDefine::getIsIsvMode, CS.YES); // 支持服务商模式 // 商户类型为特约商户,服务商应已经配置支付参数 List<PayInterfaceConfig> isvConfigList = this.list(PayInterfaceConfig.gw() .eq(PayInterfaceConfig::getInfoId, mchInfo.getIsvNo()) .eq(PayInterfaceConfig::getInfoType, CS.INFO_TYPE_ISV) .eq(PayInterfaceConfig::getState, CS.YES) .ne(PayInterfaceConfig::getIfParams, "") .isNotNull(PayInterfaceConfig::getIfParams)); for (PayInterfaceConfig config : isvConfigList) { config.addExt("mchType", mchInfo.getType()); isvPayConfigMap.put(config.getIfCode(), config); } } List<PayInterfaceDefine> defineList = payInterfaceDefineService.list(queryWrapper); // 支付参数列表 LambdaQueryWrapper<PayInterfaceConfig> wrapper = PayInterfaceConfig.gw(); wrapper.eq(PayInterfaceConfig::getInfoId, appId); wrapper.eq(PayInterfaceConfig::getInfoType, CS.INFO_TYPE_MCH_APP); List<PayInterfaceConfig> configList = this.list(wrapper); for (PayInterfaceDefine define : defineList) { define.addExt("mchType", mchInfo.getType()); // 所属商户类型 for (PayInterfaceConfig config : configList) { if (define.getIfCode().equals(config.getIfCode())) { define.addExt("ifConfigState", config.getState()); // 配置状态 } } if (mchInfo.getType() == CS.MCH_TYPE_ISVSUB && isvPayConfigMap.get(define.getIfCode()) == null) { define.addExt("subMchIsvConfig", CS.NO); // 特约商户,服务商支付参数的配置状态,0表示未配置 } } return defineList;
783
863
1,646
<no_super_class>
jeequan_jeepay
jeepay/jeepay-service/src/main/java/com/jeequan/jeepay/service/impl/PayOrderDivisionRecordService.java
PayOrderDivisionRecordService
updateResendState
class PayOrderDivisionRecordService extends ServiceImpl<PayOrderDivisionRecordMapper, PayOrderDivisionRecord> { @Autowired private PayOrderMapper payOrderMapper; /** 更新分账记录为分账成功 ( 单条 ) 将: 已受理 更新为: 其他状态 **/ public void updateRecordSuccessOrFailBySingleItem(Long recordId, Byte state, String channelRespResult){ PayOrderDivisionRecord updateRecord = new PayOrderDivisionRecord(); updateRecord.setState(state); updateRecord.setChannelRespResult( state == PayOrderDivisionRecord.STATE_SUCCESS ? "" : channelRespResult); // 若明确成功,清空错误信息。 update(updateRecord, PayOrderDivisionRecord.gw().eq(PayOrderDivisionRecord::getRecordId, recordId).eq(PayOrderDivisionRecord::getState, PayOrderDivisionRecord.STATE_ACCEPT)); } /** 更新分账记录为分账成功**/ public void updateRecordSuccessOrFail(List<PayOrderDivisionRecord> records, Byte state, String channelBatchOrderId, String channelRespResult){ if(records == null || records.isEmpty()){ return ; } List<Long> recordIds = new ArrayList<>(); records.stream().forEach(r -> recordIds.add(r.getRecordId())); PayOrderDivisionRecord updateRecord = new PayOrderDivisionRecord(); updateRecord.setState(state); updateRecord.setChannelBatchOrderId(channelBatchOrderId); updateRecord.setChannelRespResult(channelRespResult); update(updateRecord, PayOrderDivisionRecord.gw().in(PayOrderDivisionRecord::getRecordId, recordIds).eq(PayOrderDivisionRecord::getState, PayOrderDivisionRecord.STATE_WAIT)); } /** 更新分账订单为: 等待分账中的状态 **/ @Transactional public void updateResendState(String payOrderId){<FILL_FUNCTION_BODY>} }
PayOrder updateRecord = new PayOrder(); updateRecord.setDivisionState(PayOrder.DIVISION_STATE_WAIT_TASK); // 更新订单 int payOrderUpdateRow = payOrderMapper.update(updateRecord, PayOrder.gw().eq(PayOrder::getPayOrderId, payOrderId).eq(PayOrder::getDivisionState, PayOrder.DIVISION_STATE_FINISH)); if(payOrderUpdateRow <= 0){ throw new BizException("更新订单分账状态失败"); } PayOrderDivisionRecord updateRecordByDiv = new PayOrderDivisionRecord(); updateRecordByDiv.setBatchOrderId(SeqKit.genDivisionBatchId()); // 重新生成batchOrderId, 避免部分失败导致: out_trade_no重复。 updateRecordByDiv.setState(PayOrderDivisionRecord.STATE_WAIT); //待分账 updateRecordByDiv.setChannelRespResult(""); updateRecordByDiv.setChannelBatchOrderId(""); boolean recordUpdateFlag = update(updateRecordByDiv, PayOrderDivisionRecord.gw().eq(PayOrderDivisionRecord::getPayOrderId, payOrderId).eq(PayOrderDivisionRecord::getState, PayOrderDivisionRecord.STATE_FAIL) ); if(!recordUpdateFlag){ throw new BizException("更新分账记录状态失败"); }
519
355
874
<no_super_class>
jeequan_jeepay
jeepay/jeepay-service/src/main/java/com/jeequan/jeepay/service/impl/RefundOrderService.java
RefundOrderService
updateInit2Ing
class RefundOrderService extends ServiceImpl<RefundOrderMapper, RefundOrder> { @Autowired private PayOrderMapper payOrderMapper; /** 查询商户订单 **/ public RefundOrder queryMchOrder(String mchNo, String mchRefundNo, String refundOrderId){ if(StringUtils.isNotEmpty(refundOrderId)){ return getOne(RefundOrder.gw().eq(RefundOrder::getMchNo, mchNo).eq(RefundOrder::getRefundOrderId, refundOrderId)); }else if(StringUtils.isNotEmpty(mchRefundNo)){ return getOne(RefundOrder.gw().eq(RefundOrder::getMchNo, mchNo).eq(RefundOrder::getMchRefundNo, mchRefundNo)); }else{ return null; } } /** 更新退款单状态 【退款单生成】 --》 【退款中】 **/ public boolean updateInit2Ing(String refundOrderId, String channelOrderNo){<FILL_FUNCTION_BODY>} /** 更新退款单状态 【退款中】 --》 【退款成功】 **/ @Transactional public boolean updateIng2Success(String refundOrderId, String channelOrderNo){ RefundOrder updateRecord = new RefundOrder(); updateRecord.setState(RefundOrder.STATE_SUCCESS); updateRecord.setChannelOrderNo(channelOrderNo); updateRecord.setSuccessTime(new Date()); //1. 更新退款订单表数据 if(! update(updateRecord, new LambdaUpdateWrapper<RefundOrder>() .eq(RefundOrder::getRefundOrderId, refundOrderId).eq(RefundOrder::getState, RefundOrder.STATE_ING)) ){ return false; } //2. 更新订单表数据(更新退款次数,退款状态,如全额退款更新支付状态为已退款) RefundOrder refundOrder = getOne(RefundOrder.gw().select(RefundOrder::getPayOrderId, RefundOrder::getRefundAmount).eq(RefundOrder::getRefundOrderId, refundOrderId)); int updateCount = payOrderMapper.updateRefundAmountAndCount(refundOrder.getPayOrderId(), refundOrder.getRefundAmount()); if(updateCount <= 0){ throw new BizException("更新订单数据异常"); } return true; } /** 更新退款单状态 【退款中】 --》 【退款失败】 **/ @Transactional public boolean updateIng2Fail(String refundOrderId, String channelOrderNo, String channelErrCode, String channelErrMsg){ RefundOrder updateRecord = new RefundOrder(); updateRecord.setState(RefundOrder.STATE_FAIL); updateRecord.setErrCode(channelErrCode); updateRecord.setErrMsg(channelErrMsg); updateRecord.setChannelOrderNo(channelOrderNo); return update(updateRecord, new LambdaUpdateWrapper<RefundOrder>() .eq(RefundOrder::getRefundOrderId, refundOrderId).eq(RefundOrder::getState, RefundOrder.STATE_ING)); } /** 更新退款单状态 【退款中】 --》 【退款成功/退款失败】 **/ @Transactional public boolean updateIng2SuccessOrFail(String refundOrderId, Byte updateState, String channelOrderNo, String channelErrCode, String channelErrMsg){ if(updateState == RefundOrder.STATE_ING){ return true; }else if(updateState == RefundOrder.STATE_SUCCESS){ return updateIng2Success(refundOrderId, channelOrderNo); }else if(updateState == RefundOrder.STATE_FAIL){ return updateIng2Fail(refundOrderId, channelOrderNo, channelErrCode, channelErrMsg); } return false; } /** 更新退款单为 关闭状态 **/ public Integer updateOrderExpired(){ RefundOrder refundOrder = new RefundOrder(); refundOrder.setState(RefundOrder.STATE_CLOSED); return baseMapper.update(refundOrder, RefundOrder.gw() .in(RefundOrder::getState, Arrays.asList(RefundOrder.STATE_INIT, RefundOrder.STATE_ING)) .le(RefundOrder::getExpiredTime, new Date()) ); } public IPage<RefundOrder> pageList(IPage iPage, LambdaQueryWrapper<RefundOrder> wrapper, RefundOrder refundOrder, JSONObject paramJSON) { if (StringUtils.isNotEmpty(refundOrder.getRefundOrderId())) { wrapper.eq(RefundOrder::getRefundOrderId, refundOrder.getRefundOrderId()); } if (StringUtils.isNotEmpty(refundOrder.getPayOrderId())) { wrapper.eq(RefundOrder::getPayOrderId, refundOrder.getPayOrderId()); } if (StringUtils.isNotEmpty(refundOrder.getChannelPayOrderNo())) { wrapper.eq(RefundOrder::getChannelPayOrderNo, refundOrder.getChannelPayOrderNo()); } if (StringUtils.isNotEmpty(refundOrder.getMchNo())) { wrapper.eq(RefundOrder::getMchNo, refundOrder.getMchNo()); } if (StringUtils.isNotEmpty(refundOrder.getIsvNo())) { wrapper.eq(RefundOrder::getIsvNo, refundOrder.getIsvNo()); } if (refundOrder.getMchType() != null) { wrapper.eq(RefundOrder::getMchType, refundOrder.getMchType()); } if (StringUtils.isNotEmpty(refundOrder.getMchRefundNo())) { wrapper.eq(RefundOrder::getMchRefundNo, refundOrder.getMchRefundNo()); } if (refundOrder.getState() != null) { wrapper.eq(RefundOrder::getState, refundOrder.getState()); } if (StringUtils.isNotEmpty(refundOrder.getAppId())) { wrapper.eq(RefundOrder::getAppId, refundOrder.getAppId()); } if (paramJSON != null) { if (StringUtils.isNotEmpty(paramJSON.getString("createdStart"))) { wrapper.ge(RefundOrder::getCreatedAt, paramJSON.getString("createdStart")); } if (StringUtils.isNotEmpty(paramJSON.getString("createdEnd"))) { wrapper.le(RefundOrder::getCreatedAt, paramJSON.getString("createdEnd")); } } // 三合一订单 if (paramJSON != null && StringUtils.isNotEmpty(paramJSON.getString("unionOrderId"))) { wrapper.and(wr -> { wr.eq(RefundOrder::getPayOrderId, paramJSON.getString("unionOrderId")) .or().eq(RefundOrder::getRefundOrderId, paramJSON.getString("unionOrderId")) .or().eq(RefundOrder::getChannelPayOrderNo, paramJSON.getString("unionOrderId")) .or().eq(RefundOrder::getMchRefundNo, paramJSON.getString("unionOrderId")); }); } wrapper.orderByDesc(RefundOrder::getCreatedAt); return page(iPage, wrapper); } }
RefundOrder updateRecord = new RefundOrder(); updateRecord.setState(RefundOrder.STATE_ING); updateRecord.setChannelOrderNo(channelOrderNo); return update(updateRecord, new LambdaUpdateWrapper<RefundOrder>() .eq(RefundOrder::getRefundOrderId, refundOrderId).eq(RefundOrder::getState, RefundOrder.STATE_INIT));
1,908
104
2,012
<no_super_class>
jeequan_jeepay
jeepay/jeepay-service/src/main/java/com/jeequan/jeepay/service/impl/SysConfigService.java
SysConfigService
updateByConfigKey
class SysConfigService extends ServiceImpl<SysConfigMapper, SysConfig> implements ISysConfigService { /** 是否启用缓存 * true: 表示将使用内存缓存, 将部分系统配置项 或 商户应用/服务商信息进行缓存并读取 * false: 直接查询DB * **/ public static boolean IS_USE_CACHE = false; @Autowired private SysConfigService sysConfigService; /** 数据库application配置参数 **/ private static MutablePair<String, DBApplicationConfig> APPLICATION_CONFIG = new MutablePair<>("applicationConfig", null); public synchronized void initDBConfig(String groupKey) { // 若当前系统不缓存,则直接返回 if(!IS_USE_CACHE){ return; } if(APPLICATION_CONFIG.getLeft().equalsIgnoreCase(groupKey)){ APPLICATION_CONFIG.right = this.selectByGroupKey(groupKey).toJavaObject(DBApplicationConfig.class); } } /** 获取实际的数据 **/ @Override public DBApplicationConfig getDBApplicationConfig() { // 查询DB if(!IS_USE_CACHE){ return this.selectByGroupKey(APPLICATION_CONFIG.getLeft()).toJavaObject(DBApplicationConfig.class); } // 缓存数据 if(APPLICATION_CONFIG.getRight() == null ){ initDBConfig(APPLICATION_CONFIG.getLeft()); } return APPLICATION_CONFIG.right; } /** 根据分组查询,并返回JSON对象格式的数据 **/ public JSONObject selectByGroupKey(String groupKey){ JSONObject result = new JSONObject(); list(SysConfig.gw().select(SysConfig::getConfigKey, SysConfig::getConfigVal).eq(SysConfig::getGroupKey, groupKey)) .stream().forEach(item -> result.put(item.getConfigKey(), item.getConfigVal())); return result; } public int updateByConfigKey(Map<String, String> updateMap) {<FILL_FUNCTION_BODY>} }
int count = 0; Set<String> set = updateMap.keySet(); for(String k : set) { SysConfig sysConfig = new SysConfig(); sysConfig.setConfigKey(k); sysConfig.setConfigVal(updateMap.get(k)); boolean update = sysConfigService.saveOrUpdate(sysConfig); if (update) { count ++; } } return count;
564
113
677
<no_super_class>
jeequan_jeepay
jeepay/jeepay-service/src/main/java/com/jeequan/jeepay/service/impl/SysRoleEntRelaService.java
SysRoleEntRelaService
resetRela
class SysRoleEntRelaService extends ServiceImpl<SysRoleEntRelaMapper, SysRoleEntRela> { @Autowired private SysEntitlementService sysEntitlementService; /** 根据人查询出所有权限ID集合 */ public List<String> selectEntIdsByUserId(Long userId, Byte isAdmin, String sysType){ if(isAdmin == CS.YES){ List<String> result = new ArrayList<>(); sysEntitlementService.list(SysEntitlement.gw().select(SysEntitlement::getEntId).eq(SysEntitlement::getSysType, sysType).eq(SysEntitlement::getState, CS.PUB_USABLE) ).stream().forEach(r -> result.add(r.getEntId())); return result; }else{ return baseMapper.selectEntIdsByUserId(userId, sysType); } } /** 重置 角色 - 权限 关联关系 **/ @Transactional public void resetRela(String roleId, List<String> entIdList){<FILL_FUNCTION_BODY>} }
//1. 删除 this.remove(SysRoleEntRela.gw().eq(SysRoleEntRela::getRoleId, roleId)); //2. 插入 for (String entId : entIdList) { SysRoleEntRela r = new SysRoleEntRela(); r.setRoleId(roleId); r.setEntId(entId); this.save(r); }
308
116
424
<no_super_class>
jeequan_jeepay
jeepay/jeepay-service/src/main/java/com/jeequan/jeepay/service/impl/SysRoleService.java
SysRoleService
removeRole
class SysRoleService extends ServiceImpl<SysRoleMapper, SysRole> { @Autowired private SysUserRoleRelaService sysUserRoleRelaService; @Autowired private SysRoleEntRelaService sysRoleEntRelaService; /** 根据用户查询全部角色集合 **/ public List<String> findListByUser(Long sysUserId){ List<String> result = new ArrayList<>(); sysUserRoleRelaService.list( SysUserRoleRela.gw().eq(SysUserRoleRela::getUserId, sysUserId) ).stream().forEach(r -> result.add(r.getRoleId())); return result; } @Transactional public void removeRole(String roleId){<FILL_FUNCTION_BODY>} }
if(sysUserRoleRelaService.count(SysUserRoleRela.gw().eq(SysUserRoleRela::getRoleId, roleId)) > 0){ throw new BizException("当前角色已分配到用户, 不可删除!"); } //删除当前表 removeById(roleId); //删除关联表 sysRoleEntRelaService.remove(SysRoleEntRela.gw().eq(SysRoleEntRela::getRoleId, roleId));
213
133
346
<no_super_class>
jeequan_jeepay
jeepay/jeepay-service/src/main/java/com/jeequan/jeepay/service/impl/SysUserAuthService.java
SysUserAuthService
resetAuthInfo
class SysUserAuthService extends ServiceImpl<SysUserAuthMapper, SysUserAuth> { /** 根据登录信息查询用户认证信息 **/ public SysUserAuth selectByLogin(String identifier, Byte identityType, String sysType){ return baseMapper.selectByLogin(identifier, identityType, sysType); } /** 添加用户认证表 **/ @Transactional public void addUserAuthDefault(Long userId, String loginUserName, String telPhone, String pwdRaw, String sysType){ String salt = StringKit.getUUID(6); //6位随机数 String userPwd = new BCryptPasswordEncoder().encode(pwdRaw); /** 用户名登录方式 */ SysUserAuth record = new SysUserAuth(); record.setUserId(userId); record.setCredential(userPwd); record.setSalt(salt);record.setSysType(sysType); record.setIdentityType(CS.AUTH_TYPE.LOGIN_USER_NAME); record.setIdentifier(loginUserName); save(record); /** 手机号登录方式 */ record = new SysUserAuth(); record.setUserId(userId); record.setCredential(userPwd); record.setSalt(salt);record.setSysType(sysType); record.setIdentityType(CS.AUTH_TYPE.TELPHONE); record.setIdentifier(telPhone); save(record); } /** 重置密码 */ @Transactional public void resetAuthInfo(Long resetUserId, String authLoginUserName, String telphone, String newPwd, String sysType){<FILL_FUNCTION_BODY>} /** 查询当前用户密码是否正确 */ public boolean validateCurrentUserPwd(String pwdRaw){ //根据当前用户ID + 认证方式为 登录用户名的方式 查询一条记录 SysUserAuth auth = getOne(SysUserAuth.gw() .eq(SysUserAuth::getUserId, JeeUserDetails.getCurrentUserDetails().getSysUser().getSysUserId()) .eq(SysUserAuth::getIdentityType, CS.AUTH_TYPE.LOGIN_USER_NAME) ); if(auth != null && new BCryptPasswordEncoder().matches(pwdRaw, auth.getCredential())){ return true; } return false; } }
//更改登录用户名 // if(StringKit.isNotEmpty(authLoginUserName)){ // SysUserAuth updateRecord = new SysUserAuth(); // updateRecord.setIdentifier(authLoginUserName); // update(updateRecord, SysUserAuth.gw().eq(SysUserAuth::getSystem, system).eq(SysUserAuth::getUserId, resetUserId).eq(SysUserAuth::getIdentityType, CS.AUTH_TYPE.LOGIN_USER_NAME)); // } //更新手机号认证 // if(StringKit.isNotEmpty(telphone)){ // SysUserAuth updateRecord = new SysUserAuth(); // updateRecord.setIdentifier(telphone); // update(updateRecord, SysUserAuth.gw().eq(SysUserAuth::getSystem, system).eq(SysUserAuth::getUserId, resetUserId).eq(SysUserAuth::getIdentityType, CS.AUTH_TYPE.TELPHONE)); // } //更改密码 if(StringUtils.isNotEmpty(newPwd)){ //根据当前用户ID 查询出用户的所有认证记录 List<SysUserAuth> authList = list(SysUserAuth.gw().eq(SysUserAuth::getSysType, sysType).eq(SysUserAuth::getUserId, resetUserId)); for (SysUserAuth auth : authList) { if(StringUtils.isEmpty(auth.getSalt())){ //可能为其他登录方式, 不存在salt continue; } SysUserAuth updateRecord = new SysUserAuth(); updateRecord.setAuthId(auth.getAuthId()); updateRecord.setCredential(new BCryptPasswordEncoder().encode(newPwd)); updateById(updateRecord); } }
621
462
1,083
<no_super_class>
jeequan_jeepay
jeepay/jeepay-service/src/main/java/com/jeequan/jeepay/service/impl/SysUserService.java
SysUserService
addSysUser
class SysUserService extends ServiceImpl<SysUserMapper, SysUser> { @Autowired private SysUserAuthService sysUserAuthService; @Autowired private SysUserRoleRelaService sysUserRoleRelaService; /** 添加系统用户 **/ @Transactional public void addSysUser(SysUser sysUser, String sysType){<FILL_FUNCTION_BODY>} //修改用户信息 @Transactional public void updateSysUser(SysUser sysUser){ Long sysUserId = sysUser.getSysUserId(); SysUser dbRecord = getById(sysUserId); if (dbRecord == null) { throw new BizException("该用户不存在"); } //修改了手机号, 需要修改auth表信息 if(!dbRecord.getTelphone().equals(sysUser.getTelphone())){ if(count(SysUser.gw().eq(SysUser::getSysType, dbRecord.getSysType()).eq(SysUser::getTelphone, sysUser.getTelphone())) > 0){ throw new BizException("该手机号已关联其他用户!"); } sysUserAuthService.resetAuthInfo(sysUserId, null, sysUser.getTelphone(), null, dbRecord.getSysType()); } //修改了手机号, 需要修改auth表信息 if(!dbRecord.getLoginUsername().equals(sysUser.getLoginUsername())){ if(count(SysUser.gw().eq(SysUser::getSysType, dbRecord.getSysType()).eq(SysUser::getLoginUsername, sysUser.getLoginUsername())) > 0){ throw new BizException("该登录用户名已关联其他用户!"); } sysUserAuthService.resetAuthInfo(sysUserId, sysUser.getLoginUsername(), null, null, dbRecord.getSysType()); } //修改用户主表 baseMapper.updateById(sysUser); } /** 分配用户角色 **/ @Transactional public void saveUserRole(Long userId, List<String> roleIdList) { //删除用户之前的 角色信息 sysUserRoleRelaService.remove(SysUserRoleRela.gw().eq(SysUserRoleRela::getUserId, userId)); for (String roleId : roleIdList) { SysUserRoleRela addRecord = new SysUserRoleRela(); addRecord.setUserId(userId); addRecord.setRoleId(roleId); sysUserRoleRelaService.save(addRecord); } } /** 删除用户 **/ @Transactional public void removeUser(SysUser sysUser, String sysType) { // 1.删除用户登录信息 sysUserAuthService.remove(SysUserAuth.gw() .eq(SysUserAuth::getSysType, sysType) .in(SysUserAuth::getUserId, sysUser.getSysUserId()) ); // 2.删除用户角色信息 sysUserRoleRelaService.removeById(sysUser.getSysUserId()); // 3.删除用户信息 removeById(sysUser.getSysUserId()); } /** 获取到商户的超管用户ID **/ public Long findMchAdminUserId(String mchNo){ return getOne(SysUser.gw().select(SysUser::getSysUserId) .eq(SysUser::getBelongInfoId, mchNo) .eq(SysUser::getSysType, CS.SYS_TYPE.MCH) .eq(SysUser::getIsAdmin, CS.YES)).getSysUserId(); } }
//判断获取到选择的角色集合 // String roleIdListStr = sysUser.extv().getString("roleIdListStr"); // if(StringKit.isEmpty(roleIdListStr)) throw new BizException("请选择角色信息!"); // // List<String> roleIdList = JSONArray.parseArray(roleIdListStr, String.class); // if(roleIdList.isEmpty()) throw new BizException("请选择角色信息!"); // 判断数据来源 if( StringUtils.isEmpty(sysUser.getLoginUsername()) ) { throw new BizException("登录用户名不能为空!"); } if( StringUtils.isEmpty(sysUser.getRealname()) ) { throw new BizException("姓名不能为空!"); } if( StringUtils.isEmpty(sysUser.getTelphone()) ) { throw new BizException("手机号不能为空!"); } if(sysUser.getSex() == null ) { throw new BizException("性别不能为空!"); } //登录用户名不可重复 if( count(SysUser.gw().eq(SysUser::getSysType, sysType).eq(SysUser::getLoginUsername, sysUser.getLoginUsername())) > 0 ){ throw new BizException("登录用户名已存在!"); } //手机号不可重复 if( count(SysUser.gw().eq(SysUser::getSysType, sysType).eq(SysUser::getTelphone, sysUser.getTelphone())) > 0 ){ throw new BizException("手机号已存在!"); } //员工号不可重复 if( count(SysUser.gw().eq(SysUser::getSysType, sysType).eq(SysUser::getUserNo, sysUser.getUserNo())) > 0 ){ throw new BizException("员工号已存在!"); } //女 默认头像 if(sysUser.getSex() != null && CS.SEX_FEMALE == sysUser.getSex()){ sysUser.setAvatarUrl("https://jeequan.oss-cn-beijing.aliyuncs.com/jeepay/img/defava_f.png"); }else{ sysUser.setAvatarUrl("https://jeequan.oss-cn-beijing.aliyuncs.com/jeepay/img/defava_m.png"); } //1. 插入用户主表 sysUser.setSysType(sysType); // 系统类型 this.save(sysUser); Long sysUserId = sysUser.getSysUserId(); //添加到 user_auth表 String authPwd = CS.DEFAULT_PWD; sysUserAuthService.addUserAuthDefault(sysUserId, sysUser.getLoginUsername(), sysUser.getTelphone(), authPwd, sysType); //3. 添加用户角色信息 //saveUserRole(sysUser.getSysUserId(), new ArrayList<>());
987
786
1,773
<no_super_class>
jeequan_jeepay
jeepay/jeepay-service/src/main/java/com/jeequan/jeepay/service/impl/TransferOrderService.java
TransferOrderService
pageList
class TransferOrderService extends ServiceImpl<TransferOrderMapper, TransferOrder> { /** 更新转账订单状态 【转账订单生成】 --》 【转账中】 **/ public boolean updateInit2Ing(String transferId){ TransferOrder updateRecord = new TransferOrder(); updateRecord.setState(TransferOrder.STATE_ING); return update(updateRecord, new LambdaUpdateWrapper<TransferOrder>() .eq(TransferOrder::getTransferId, transferId).eq(TransferOrder::getState, TransferOrder.STATE_INIT)); } /** 更新转账订单状态 【转账中】 --》 【转账成功】 **/ @Transactional public boolean updateIng2Success(String transferId, String channelOrderNo){ TransferOrder updateRecord = new TransferOrder(); updateRecord.setState(TransferOrder.STATE_SUCCESS); updateRecord.setChannelOrderNo(channelOrderNo); updateRecord.setSuccessTime(new Date()); //更新转账订单表数据 if(! update(updateRecord, new LambdaUpdateWrapper<TransferOrder>() .eq(TransferOrder::getTransferId, transferId).eq(TransferOrder::getState, TransferOrder.STATE_ING)) ){ return false; } return true; } /** 更新转账订单状态 【转账中】 --》 【转账失败】 **/ @Transactional public boolean updateIng2Fail(String transferId, String channelOrderNo, String channelErrCode, String channelErrMsg){ TransferOrder updateRecord = new TransferOrder(); updateRecord.setState(TransferOrder.STATE_FAIL); updateRecord.setErrCode(channelErrCode); updateRecord.setErrMsg(channelErrMsg); updateRecord.setChannelOrderNo(channelOrderNo); return update(updateRecord, new LambdaUpdateWrapper<TransferOrder>() .eq(TransferOrder::getTransferId, transferId).eq(TransferOrder::getState, TransferOrder.STATE_ING)); } /** 更新转账订单状态 【转账中】 --》 【转账成功/转账失败】 **/ @Transactional public boolean updateIng2SuccessOrFail(String transferId, Byte updateState, String channelOrderNo, String channelErrCode, String channelErrMsg){ if(updateState == TransferOrder.STATE_ING){ return true; }else if(updateState == TransferOrder.STATE_SUCCESS){ return updateIng2Success(transferId, channelOrderNo); }else if(updateState == TransferOrder.STATE_FAIL){ return updateIng2Fail(transferId, channelOrderNo, channelErrCode, channelErrMsg); } return false; } /** 查询商户订单 **/ public TransferOrder queryMchOrder(String mchNo, String mchOrderNo, String transferId){ if(StringUtils.isNotEmpty(transferId)){ return getOne(TransferOrder.gw().eq(TransferOrder::getMchNo, mchNo).eq(TransferOrder::getTransferId, transferId)); }else if(StringUtils.isNotEmpty(mchOrderNo)){ return getOne(TransferOrder.gw().eq(TransferOrder::getMchNo, mchNo).eq(TransferOrder::getMchOrderNo, mchOrderNo)); }else{ return null; } } public IPage<TransferOrder> pageList(IPage iPage, LambdaQueryWrapper<TransferOrder> wrapper, TransferOrder transferOrder, JSONObject paramJSON) {<FILL_FUNCTION_BODY>} }
if (StringUtils.isNotEmpty(transferOrder.getTransferId())) { wrapper.eq(TransferOrder::getTransferId, transferOrder.getTransferId()); } if (StringUtils.isNotEmpty(transferOrder.getMchOrderNo())) { wrapper.eq(TransferOrder::getMchOrderNo, transferOrder.getMchOrderNo()); } if (StringUtils.isNotEmpty(transferOrder.getChannelOrderNo())) { wrapper.eq(TransferOrder::getChannelOrderNo, transferOrder.getChannelOrderNo()); } if (StringUtils.isNotEmpty(transferOrder.getMchNo())) { wrapper.eq(TransferOrder::getMchNo, transferOrder.getMchNo()); } if (transferOrder.getState() != null) { wrapper.eq(TransferOrder::getState, transferOrder.getState()); } if (StringUtils.isNotEmpty(transferOrder.getAppId())) { wrapper.eq(TransferOrder::getAppId, transferOrder.getAppId()); } if (paramJSON != null) { if (StringUtils.isNotEmpty(paramJSON.getString("createdStart"))) { wrapper.ge(TransferOrder::getCreatedAt, paramJSON.getString("createdStart")); } if (StringUtils.isNotEmpty(paramJSON.getString("createdEnd"))) { wrapper.le(TransferOrder::getCreatedAt, paramJSON.getString("createdEnd")); } } // 三合一订单 if (paramJSON != null && StringUtils.isNotEmpty(paramJSON.getString("unionOrderId"))) { wrapper.and(wr -> { wr.eq(TransferOrder::getTransferId, paramJSON.getString("unionOrderId")) .or().eq(TransferOrder::getMchOrderNo, paramJSON.getString("unionOrderId")) .or().eq(TransferOrder::getChannelOrderNo, paramJSON.getString("unionOrderId")); }); } wrapper.orderByDesc(TransferOrder::getCreatedAt); return page(iPage, wrapper);
945
537
1,482
<no_super_class>
jeequan_jeepay
jeepay/jeepay-z-codegen/src/main/java/com/gen/MainGen.java
MainGen
main
class MainGen { public static final String THIS_MODULE_NAME = "jeepay-z-codegen"; //当前项目名称 public static final String DB_URL = "jdbc:mysql://127.0.0.1:3306/jeepay?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8"; public static final String DB_USERNAME = "root"; public static final String DB_PASSWORD = "root"; // 多个用, 拼接 //public static final String TABLE_NAMES= "t_sys_entitlement,t_sys_role,t_sys_user,t_sys_user_auth"; public static final String TABLE_NAMES= "t_pay_way"; public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
// 代码生成器 AutoGenerator mpg = new AutoGenerator(); // 全局配置 GlobalConfig gc = new GlobalConfig(); String projectPath = System.getProperty("user.dir"); //获取当前项目的 文件夹地址 if(!projectPath.endsWith(THIS_MODULE_NAME)){ //解决IDEA中 项目目录问题 projectPath += File.separator + THIS_MODULE_NAME; } gc.setOutputDir(projectPath + "/src/main/java"); gc.setAuthor("[mybatis plus generator]"); gc.setOpen(false); gc.setBaseResultMap(true); gc.setDateType(DateType.ONLY_DATE); gc.setServiceImplName("%sService"); //不生成 service接口; mpg.setGlobalConfig(gc); // 数据源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl(DB_URL); dsc.setDriverName("com.mysql.jdbc.Driver"); dsc.setUsername(DB_USERNAME); dsc.setPassword(DB_PASSWORD); dsc.setTypeConvert(new MySqlTypeConvert() { @Override public DbColumnType processTypeConvert(GlobalConfig globalConfig, String fieldType) { System.out.println("转换类型:" + fieldType); //tinyint转换成Boolean if (fieldType.toLowerCase().contains("tinyint")) { return DbColumnType.BYTE; } return (DbColumnType) super.processTypeConvert(globalConfig, fieldType); } }); mpg.setDataSource(dsc); // 包配置 PackageConfig pc = new PackageConfig(); pc.setParent("com.jeequan.jeepay"); //根目录 pc.setEntity("core.entity"); //实体目录 pc.setMapper("service.mapper"); //Mapper接口目录 pc.setXml("service.mapper"); //xml目录 pc.setService("delete_delete"); //service目录 不需要,暂时删除 pc.setServiceImpl("service"); //serviceImpl 目录 mpg.setPackageInfo(pc); // 配置模板 TemplateConfig templateConfig = new TemplateConfig(); templateConfig.setController(null); //不生成controller templateConfig.setService(null); //不生成services mpg.setTemplate(templateConfig); // 策略配置 StrategyConfig strategy = new StrategyConfig(); strategy.setNaming(NamingStrategy.underline_to_camel); //no_change原样输出 strategy.setColumnNaming(NamingStrategy.underline_to_camel); //no_change原样输出 strategy.setEntityLombokModel(true); strategy.setInclude(TABLE_NAMES.split(",")); strategy.setTablePrefix("t_"); // strategy.setEntityTableFieldAnnotationEnable(true); //自动添加 field注解 mpg.setStrategy(strategy); mpg.execute();
222
807
1,029
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/org/zeromq/ManagedContext.java
ManagedContext
close
class ManagedContext { static { // Release ManagedSocket resources when catching SIGINT Runtime.getRuntime().addShutdownHook(new Thread(() -> getInstance().close())); } private final Lock lock; private final Ctx ctx; private final Set<SocketBase> sockets; private ManagedContext() { this.ctx = ZMQ.init(ZMQ.ZMQ_IO_THREADS_DFLT); this.lock = new ReentrantLock(); this.sockets = new HashSet<>(); } static ManagedContext getInstance() { return ContextHolder.INSTANCE; } SocketBase createSocket(int type) { final SocketBase base = ctx.createSocket(type); lock.lock(); try { sockets.add(base); } finally { lock.unlock(); } return base; } void destroy(SocketBase socketBase) { socketBase.setSocketOpt(ZMQ.ZMQ_LINGER, 0); socketBase.close(); lock.lock(); try { sockets.remove(socketBase); } finally { lock.unlock(); } } /* * This should only be called when SIGINT is received */ private void close() {<FILL_FUNCTION_BODY>} // Lazy singleton pattern to avoid double lock checking private static class ContextHolder { private static final ManagedContext INSTANCE = new ManagedContext(); } }
lock.lock(); try { for (SocketBase s : sockets) { try { s.setSocketOpt(ZMQ.ZMQ_LINGER, 0); s.close(); } catch (Exception ignore) { } } sockets.clear(); } finally { lock.unlock(); }
416
98
514
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/org/zeromq/ZActor.java
Double
renews
class Double implements EventsHandler, Star { // poller used for the loop private final ZPoller poller; // control pipe for Backstage side private final Socket pipe; // managed sockets private final List<Socket> sockets; // actor responsible for processing messages private final Actor actor; // context used for the closing of the sockets private final ZContext context; // creates a new double public Double(final ZContext ctx, final Socket pipe, final Actor actor, final Object... args) { this.context = ctx; this.pipe = pipe; this.actor = actor; final List<Socket> created = actor.createSockets(ctx, args); assert (created != null); sockets = new ArrayList<>(created); poller = new ZPoller(ctx); poller.setGlobalHandler(this); } // before starting the loops @Override public void prepare() { poller.register(pipe, ZPoller.POLLIN); actor.start(pipe, Collections.unmodifiableList(sockets), poller); } // gives the number of events to process @Override public int breathe() { long timeout = actor.looping(pipe, poller); return poller.poll(timeout); // events have been dispatched, } // acting takes place, return true to continue till the end @Override public boolean act(int events) { // act is actually already finished for handlers return events >= 0; // Context is not shut down } // a loop just finished, return true to continue acting @Override public boolean entract() { return actor.looped(pipe, poller); } // destroys the double @Override public boolean renews() {<FILL_FUNCTION_BODY>} @Override public boolean events(SelectableChannel channel, int events) { // TODO dispatch events from channels return true; } // an event has occurred on a registered socket @Override public boolean events(final Socket socket, final int events) { if (socket != pipe) { // Process a stage message, time to play return actor.stage(socket, pipe, poller, events); } else { // Process a control message, time to update your playing return actor.backstage(pipe, poller, events); } } }
// close every managed sockets Iterator<Socket> iter = sockets.iterator(); while (iter.hasNext()) { final Socket socket = iter.next(); iter.remove(); if (socket != null) { poller.unregister(socket); socket.close(); // call back the actor to inform that a socket has been closed. actor.closed(socket); } } // let the actor decide if the stage restarts a new double return actor.destroyed(context, pipe, poller);
648
138
786
<methods>public transient void <init>(org.zeromq.ZAgent.SelectorCreator, org.zeromq.ZStar.Fortune, java.lang.String, java.lang.Object[]) ,public transient void <init>(org.zeromq.ZStar.Fortune, java.lang.String, java.lang.Object[]) ,public transient void <init>(org.zeromq.ZContext, org.zeromq.ZAgent.SelectorCreator, org.zeromq.ZStar.Fortune, java.lang.String, java.lang.Object[]) ,public transient void <init>(org.zeromq.ZContext, org.zeromq.ZStar.Fortune, java.lang.String, java.lang.Object[]) ,public transient void <init>(org.zeromq.ZContext, org.zeromq.ZAgent.SelectorCreator, org.zeromq.ZStar.Fortune, BiFunction<org.zeromq.ZMQ.Socket,java.lang.String,org.zeromq.ZAgent>, java.lang.String, java.lang.Object[]) ,public transient void <init>(org.zeromq.ZContext, org.zeromq.ZStar.Fortune, BiFunction<org.zeromq.ZMQ.Socket,java.lang.String,org.zeromq.ZAgent>, java.lang.String, java.lang.Object[]) ,public org.zeromq.ZAgent agent() ,public void close() ,public org.zeromq.ZStar.Exit exit() ,public static void party(long, java.util.concurrent.TimeUnit) ,public org.zeromq.ZMQ.Socket pipe() ,public org.zeromq.ZMsg recv() ,public org.zeromq.ZMsg recv(int) ,public org.zeromq.ZMsg recv(boolean) ,public boolean send(org.zeromq.ZMsg) ,public boolean send(org.zeromq.ZMsg, boolean) ,public boolean send(java.lang.String) ,public boolean send(java.lang.String, boolean) ,public boolean sign() <variables>private final non-sealed org.zeromq.ZAgent agent,private final org.zeromq.ZStar.Plateau plateau
zeromq_jeromq
jeromq/jeromq-core/src/main/java/org/zeromq/ZBeacon.java
Builder
build
class Builder { private InetAddress clientHost = DEFAULT_BROADCAST_HOST_ADDRESS; private InetAddress serverAddr = DEFAULT_BROADCAST_ADDRESS; private int port; private long broadcastInterval = DEFAULT_BROADCAST_INTERVAL; private byte[] beacon; private boolean ignoreLocalAddress = true; private boolean blocking = false; // Those arguments are not set using the constructor, so they are optional for backward compatibility private Listener listener = null; private byte[] prefix = null; private Thread.UncaughtExceptionHandler clientExHandler = null; private Thread.UncaughtExceptionHandler serverExHandler = null; public Builder port(int port) { this.port = port; return this; } public Builder beacon(byte[] beacon) { this.beacon = beacon; return this; } @Deprecated public Builder client(String host) { try { this.clientHost = InetAddress.getByName(host); } catch (UnknownHostException e) { throw new IllegalArgumentException("Invalid server address", e); } return this; } public Builder client(InetAddress host) { this.clientHost = host; return this; } @Deprecated public Builder server(byte[] addr) { Utils.checkArgument(addr.length == 4 || addr.length == 16, "Server Address has to be 4 or 16 bytes long"); try { this.serverAddr = InetAddress.getByAddress(addr); } catch (UnknownHostException e) { throw new IllegalArgumentException("Invalid server address", e); } return this; } public Builder server(InetAddress addr) { this.serverAddr = addr; return this; } public Builder ignoreLocalAddress(boolean ignoreLocalAddress) { this.ignoreLocalAddress = ignoreLocalAddress; return this; } /** * @deprecated ignored * @param blocking * @return */ @Deprecated public Builder blocking(boolean blocking) { this.blocking = blocking; return this; } public Builder broadcastInterval(long broadcastInterval) { this.broadcastInterval = broadcastInterval; return this; } public Builder listener(Listener listener) { this.listener = listener; return this; } public Builder prefix(byte[] prefix) { this.prefix = Arrays.copyOf(prefix, prefix.length); return this; } public Builder setClientUncaughtExceptionHandlers(Thread.UncaughtExceptionHandler clientExHandler) { this.clientExHandler = clientExHandler; return this; } public Builder setServerUncaughtExceptionHandlers(Thread.UncaughtExceptionHandler serverExHandler) { this.serverExHandler = serverExHandler; return this; } public ZBeacon build() {<FILL_FUNCTION_BODY>} }
ZBeacon zbeacon = new ZBeacon(clientHost, serverAddr, port, beacon, broadcastInterval, ignoreLocalAddress, blocking); if (listener != null) { zbeacon.setListener(listener); } if (prefix != null) { zbeacon.setPrefix(prefix); } if (this.serverExHandler != null) { zbeacon.serverExHandler.set(this.serverExHandler); } if (this.clientExHandler != null) { zbeacon.clientExHandler.set(this.clientExHandler); } return zbeacon;
816
164
980
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/org/zeromq/ZCert.java
ZCert
publicConfig
class ZCert { private final byte[] publicKey; // Public key in binary private final byte[] secretKey; // Secret key in binary private final String publicTxt; // Public key in Z85 text private final String secretTxt; // Secret key in Z85 text private final ZMetadata metadata = new ZMetadata(); // Certificate metadata public ZCert() { this(ZMQ.Curve.generateKeyPair()); } public ZCert(String publicKey) { this(publicKey, null); } public ZCert(KeyPair keypair) { this(keypair.publicKey, keypair.secretKey); } public ZCert(byte[] publicKey, byte[] secretKey) { Utils.checkArgument(publicKey != null, "Public key has to be provided for a ZCert"); assertKey(publicKey.length, Curve.KEY_SIZE, "Public"); if (secretKey != null) { assertKey(secretKey.length, Curve.KEY_SIZE, "Secret"); } this.publicKey = Arrays.copyOf(publicKey, publicKey.length); this.publicTxt = Curve.z85Encode(this.publicKey); if (secretKey == null) { this.secretKey = null; this.secretTxt = null; } else { this.secretKey = Arrays.copyOf(secretKey, secretKey.length); this.secretTxt = Curve.z85Encode(this.secretKey); } } public ZCert(String publicKey, String secretKey) { Utils.checkArgument(publicKey != null, "Public key has to be provided for a ZCert"); assertKey(publicKey.length(), Curve.KEY_SIZE_Z85, "Public"); if (secretKey != null) { assertKey(secretKey.length(), Curve.KEY_SIZE_Z85, "Secret"); } this.publicKey = Curve.z85Decode(publicKey); this.publicTxt = publicKey; if (secretKey == null) { this.secretKey = null; this.secretTxt = null; } else { this.secretKey = Curve.z85Decode(secretKey); this.secretTxt = secretKey; } } private void assertKey(int length, int expected, String flavour) { Utils.checkArgument(length == expected, flavour + " key shall have a size of " + expected); } public byte[] getPublicKey() { return publicKey; } public byte[] getSecretKey() { return secretKey; } public String getPublicKeyAsZ85() { return publicTxt; } public String getSecretKeyAsZ85() { return secretTxt; } public void apply(ZMQ.Socket socket) { socket.setCurvePublicKey(publicKey); socket.setCurveSecretKey(secretKey); } public ZMetadata getMetadata() { return metadata; } public void setMeta(String key, String value) { metadata.set(key, value); } public void unsetMeta(String key) { metadata.remove(key); } public String getMeta(String key) { return metadata.get(key); } private void add(ZMetadata meta, ZConfig config) { String now = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.ENGLISH).format(new Date()); config.addComment(String.format("** Generated on %1$s by ZCert **", now)); for (Map.Entry<String, String> e : meta.entrySet()) { config.putValue("metadata/" + e.getKey(), e.getValue()); } } /** * Saves the public key to a file. * <p> * <strong>This method will overwrite contents of existing file</strong> * @param filename the path of the file to save the certificate into. * @return the saved file or null if dumped to the standard output * @throws IOException if unable to save the file. */ public File savePublic(String filename) throws IOException { return publicConfig().save(filename); } /** * Saves the public key to a writer. * @param writer the writer to save the certificate into. * @throws IOException if unable to dump the public configuration. */ public void savePublic(Writer writer) throws IOException { publicConfig().save(writer); } private ZConfig publicConfig() {<FILL_FUNCTION_BODY>} /** * Saves the public and secret keys to a file. * <p> * <strong>This method will overwrite contents of existing file</strong> * @param filename the path of the file to save the certificate into. * @return the saved file or null if dumped to the standard output * @throws IOException if unable to save the file. */ public File saveSecret(String filename) throws IOException { return secretConfig().save(filename); } /** * Saves the public and secret keys to a writer. * @param writer the writer to save the certificate into. * @throws IOException if unable to dump the configuration. */ public void saveSecret(Writer writer) throws IOException { secretConfig().save(writer); } private ZConfig secretConfig() { ZConfig conf = new ZConfig("root", null); add(metadata, conf); conf.addComment(" ZeroMQ CURVE **Secret** Certificate"); conf.addComment(" DO NOT PROVIDE THIS FILE TO OTHER USERS nor change its permissions."); conf.putValue("/curve/public-key", publicTxt); conf.putValue("/curve/secret-key", secretTxt); return conf; } }
ZConfig conf = new ZConfig("root", null); add(metadata, conf); conf.addComment(" ZeroMQ CURVE Public Certificate"); conf.addComment(" Exchange securely, or use a secure mechanism to verify the contents"); conf.addComment(" of this file after exchange. Store public certificates in your home"); conf.addComment(" directory, in the .curve subdirectory."); conf.putValue("/curve/public-key", publicTxt); return conf;
1,584
129
1,713
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/org/zeromq/ZCertStore.java
Hasher
visitFile
class Hasher implements Fingerprinter { // temporary buffer used for digest. Instance member for performance reasons. private final byte[] buffer = new byte[8192]; @Override public byte[] print(File path) { InputStream input = stream(path); if (input != null) { try { return new ZDigest(buffer).update(input).data(); } catch (IOException e) { return null; } finally { try { input.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; } private InputStream stream(File path) { if (path.isFile()) { try { return new FileInputStream(path); } catch (FileNotFoundException e) { return null; } } else if (path.isDirectory()) { List<String> list = Arrays.asList(path.list()); Collections.sort(list); return new ByteArrayInputStream(list.toString().getBytes(ZMQ.CHARSET)); } return null; } } private interface IFileVisitor { /** * Visits a file. * @param file the file to visit. * @return true to stop the traversal, false to continue. */ boolean visitFile(File file); /** * Visits a directory. * @param dir the directory to visit. * @return true to stop the traversal, false to continue. */ boolean visitDir(File dir); } // Directory location private final File location; // the scanned files (and directories) along with their fingerprint private final Map<File, byte[]> fingerprints = new HashMap<>(); // collected public keys private final Map<String, ZMetadata> publicKeys = new HashMap<>(); private final Fingerprinter finger; /** * Create a Certificate Store at that file system folder location * @param location */ public ZCertStore(String location) { this(location, new Timestamper()); } public ZCertStore(String location, Fingerprinter fingerprinter) { this.finger = fingerprinter; this.location = new File(location); loadFiles(); } private boolean traverseDirectory(File root, IFileVisitor visitor) { assert (root.exists()); assert (root.isDirectory()); if (visitor.visitDir(root)) { return true; } for (File file : root.listFiles()) { if (file.isFile()) { if (visitor.visitFile(file)) { return true; } } else if (file.isDirectory()) { boolean rc = traverseDirectory(file, visitor); if (rc) { return true; } } else { System.out.printf( "WARNING: %s is neither file nor directory? This shouldn't happen....SKIPPING%n", file.getAbsolutePath()); } } return false; } /** * Check if a public key is in the certificate store. * @param publicKey needs to be a 32 byte array representing the public key */ public boolean containsPublicKey(byte[] publicKey) { Utils.checkArgument( publicKey.length == 32, "publickey needs to have a size of 32 bytes. got only " + publicKey.length); return containsPublicKey(ZMQ.Curve.z85Encode(publicKey)); } /** * check if a z85-based public key is in the certificate store. * This method will scan the folder for changes on every call * @param publicKey */ public boolean containsPublicKey(String publicKey) { Utils.checkArgument( publicKey.length() == 40, "z85 publickeys should have a length of 40 bytes but got " + publicKey.length()); reloadIfNecessary(); return publicKeys.containsKey(publicKey); } public ZMetadata getMetadata(String publicKey) { reloadIfNecessary(); return publicKeys.get(publicKey); } private void loadFiles() { final Map<String, ZMetadata> keys = new HashMap<>(); if (!location.exists()) { location.mkdirs(); } final Map<File, byte[]> collected = new HashMap<>(); traverseDirectory(location, new IFileVisitor() { @Override public boolean visitFile(File file) {<FILL_FUNCTION_BODY>
try { ZConfig zconf = ZConfig.load(file.getAbsolutePath()); String publicKey = zconf.getValue("curve/public-key"); if (publicKey == null) { System.out.printf( "Warning!! File %s has no curve/public-key-element. SKIPPING!%n", file.getAbsolutePath()); return false; } if (publicKey.length() == 32) { // we want to store the public-key as Z85-String publicKey = ZMQ.Curve.z85Encode(publicKey.getBytes(ZMQ.CHARSET)); } assert (publicKey.length() == 40); keys.put(publicKey, ZMetadata.read(zconf)); collected.put(file, finger.print(file)); } catch (IOException e) { e.printStackTrace(); } return false;
1,239
239
1,478
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/org/zeromq/ZEvent.java
ZEvent
equals
class ZEvent { /** * An interface used to consume events in monitor */ public interface ZEventConsummer extends zmq.ZMQ.EventConsummer { void consume(ZEvent ev); default void consume(zmq.ZMQ.Event event) { consume(new ZEvent(event, SelectableChannel.class::cast)); } } private final Event event; // To keep backward compatibility, the old value field only store integer // The resolved value (Error, channel or other) is stored in resolvedValue field. private final Object value; private final String address; private ZEvent(zmq.ZMQ.Event event, Function<Object, SelectableChannel> getResolveChannel) { this.event = ZMonitor.Event.findByCode(event.event); this.address = event.addr; this.value = resolve(this.event, event.arg, getResolveChannel); } static Object resolve(Event event, Object value, Function<Object, SelectableChannel> getResolveChannel) { switch (event) { case HANDSHAKE_FAILED_PROTOCOL: return ZMonitor.ProtocolCode.findByCode((Integer) value); case CLOSE_FAILED: case ACCEPT_FAILED: case BIND_FAILED: case HANDSHAKE_FAILED_NO_DETAIL: case CONNECT_DELAYED: case HANDSHAKE_SUCCEEDED: return ZMQ.Error.findByCode((Integer) value); case HANDSHAKE_FAILED_AUTH: case HANDSHAKE_PROTOCOL: return value; case CONNECTED: case LISTENING: case ACCEPTED: case CLOSED: case DISCONNECTED: return getResolveChannel.apply(value); case CONNECT_RETRIED: return Duration.ofMillis((Integer) value); case MONITOR_STOPPED: return null; default: assert false : "Unhandled event " + event; return null; } } public Event getEvent() { return event; } /** * Return the value of the event as a high level java object. * It returns objects of type: * <ul> * <li> {@link org.zeromq.ZMonitor.ProtocolCode} for a handshake protocol error.</li> * <li> {@link org.zeromq.ZMQ.Error} for any other error.</li> * <li> {@link Duration} when associated with a delay.</li> * <li> null when no relevant value available.</li> * </ul> * @param <M> The expected type of the returned object * @return The resolved value. */ @SuppressWarnings("unchecked") public <M> M getValue() { return (M) value; } public String getAddress() { return address; } /** * Used to check if the event is an error. * <p> * Generally, any event that define the errno is * considered as an error. * @return true if the event was an error */ public boolean isError() { switch (event) { case BIND_FAILED: case ACCEPT_FAILED: case CLOSE_FAILED: case HANDSHAKE_FAILED_NO_DETAIL: case HANDSHAKE_FAILED_PROTOCOL: return true; default: return false; } } /** * Used to check if the event is a warning. * <p> * Generally, any event that return an authentication failure is * considered as a warning. * @return true if the event was a warning */ public boolean isWarn() { return event == Event.HANDSHAKE_FAILED_AUTH; } /** * Used to check if the event is an information. * <p> * Generally, any event that return an authentication failure is * considered as a warning. * @return true if the event was a warning */ public boolean isInformation() { return event == Event.DISCONNECTED; } /** * Used to check if the event is an error. * <p> * Generally, any event that define the errno is * considered as an error. * @return true if the event was an error */ public boolean isDebug() { switch (event) { case CONNECTED: case CONNECT_DELAYED: case CONNECT_RETRIED: case LISTENING: case ACCEPTED: case CLOSED: case MONITOR_STOPPED: case HANDSHAKE_SUCCEEDED: case HANDSHAKE_PROTOCOL: return true; default: return false; } } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(event, value, address); } @Override public String toString() { return "ZEvent{" + "event=" + event + ", value=" + value + ", address='" + address + '\'' + '}'; } /** * Receive an event from a monitor socket. * * @param socket the monitor socket * @param flags the flags to apply to the read operation. * @return the received event or null if no message was received. * @throws ZMQException In case of errors with the monitor socket */ public static ZEvent recv(Socket socket, int flags) { zmq.ZMQ.Event e = zmq.ZMQ.Event.read(socket.base(), flags); if (socket.errno() > 0 && socket.errno() != ZError.EAGAIN) { throw new ZMQException(socket.errno()); } else if (e == null) { return null; } else { return new ZEvent(e, o -> e.getChannel(socket.getCtx())); } } /** * Receive an event from a monitor socket. * Does a blocking recv. * * @param socket the monitor socket * @return the received event or null if no message was received. * @throws ZMQException In case of errors with the monitor socket */ public static ZEvent recv(ZMQ.Socket socket) { return recv(socket, 0); } }
if (this == o) { return true; } else if (o == null || getClass() != o.getClass()) { return false; } else { ZEvent zEvent = (ZEvent) o; return event == zEvent.event && Objects.equals(value, zEvent.value) && address.equals(zEvent.address); }
1,790
100
1,890
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/org/zeromq/ZLoop.java
STimer
addPoller
class STimer { final int delay; int times; final IZLoopHandler handler; final Object arg; long when; // Clock time when alarm goes off public STimer(int delay, int times, IZLoopHandler handler, Object arg) { this.delay = delay; this.times = times; this.handler = handler; this.arg = arg; this.when = -1; } } private final Context context; // Context managing the pollers. private final List<SPoller> pollers; // List of poll items private final List<STimer> timers; // List of timers private int pollSize; // Size of poll set private Poller pollset; // zmq_poll set private SPoller[] pollact; // Pollers for this poll set private boolean dirty; // True if pollset needs rebuilding private boolean verbose; // True if verbose tracing wanted private final List<Object> zombies; // List of timers to kill private final List<STimer> newTimers; // List of timers to add public ZLoop(Context context) { Objects.requireNonNull(context, "Context has to be supplied for ZLoop"); this.context = context; pollers = new ArrayList<>(); timers = new ArrayList<>(); zombies = new ArrayList<>(); newTimers = new ArrayList<>(); } public ZLoop(ZContext ctx) { this(ctx.getContext()); } /** * @deprecated no-op behaviour */ @Deprecated public void destroy() { // do nothing } // We hold an array of pollers that matches the pollset, so we can // register/cancel pollers orthogonally to executing the pollset // activity on pollers. Returns 0 on success, -1 on failure. private void rebuild() { pollact = null; pollSize = pollers.size(); if (pollset != null) { pollset.close(); } pollset = context.poller(pollSize); assert (pollset != null); pollact = new SPoller[pollSize]; int itemNbr = 0; for (SPoller poller : pollers) { pollset.register(poller.item); pollact[itemNbr] = poller; itemNbr++; } dirty = false; } private long ticklessTimer() { // Calculate tickless timer, up to 1 hour long tickless = System.currentTimeMillis() + 1000 * 3600; for (STimer timer : timers) { if (timer.when == -1) { timer.when = timer.delay + System.currentTimeMillis(); } if (tickless > timer.when) { tickless = timer.when; } } long timeout = tickless - System.currentTimeMillis(); if (timeout < 0) { timeout = 0; } if (verbose) { System.out.printf("I: zloop: polling for %d msec\n", timeout); } return timeout; } // -------------------------------------------------------------------------- // Register pollitem with the reactor. When the pollitem is ready, will call // the handler, passing the arg. Returns 0 if OK, -1 if there was an error. // If you register the pollitem more than once, each instance will invoke its // corresponding handler. public int addPoller(PollItem pollItem, IZLoopHandler handler, Object arg) {<FILL_FUNCTION_BODY>
if (pollItem.getRawSocket() == null && pollItem.getSocket() == null) { return -1; } SPoller poller = new SPoller(pollItem, handler, arg); pollers.add(poller); dirty = true; if (verbose) { System.out.printf( "I: zloop: register %s poller (%s, %s)\n", pollItem.getSocket() != null ? pollItem.getSocket().getType() : "RAW", pollItem.getSocket(), pollItem.getRawSocket()); } return 0;
996
166
1,162
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/org/zeromq/ZMonitor.java
MonitorActor
stage
class MonitorActor extends ZActor.SimpleActor { private static final String ERROR = "ERROR"; private static final String OK = "OK"; private final Socket monitored; // the monitored socket private final String address; // the address where events will be collected private Socket monitor; // the monitoring socket private int events; // the events to monitor private boolean verbose; public MonitorActor(ZMQ.Socket socket) { assert (socket != null); this.monitored = socket; this.address = String.format("inproc://zmonitor-%s-%s", socket.hashCode(), UUID.randomUUID()); } @Override public String premiere(Socket pipe) { return "ZMonitor-" + monitored.toString(); } @Override public List<Socket> createSockets(ZContext ctx, Object... args) { monitor = ctx.createSocket(SocketType.PAIR); assert (monitor != null); return Collections.singletonList(monitor); } @Override public void start(Socket pipe, List<Socket> sockets, ZPoller poller) { pipe.send("STARTED"); } @Override public boolean stage(Socket socket, Socket pipe, ZPoller poller, int evts) {<FILL_FUNCTION_BODY>} @Override public boolean backstage(ZMQ.Socket pipe, ZPoller poller, int evts) { final String command = pipe.recvStr(); if (command == null) { System.out.printf("ZMonitor: Closing monitor %s : No command%n", monitored); return false; } switch (command) { case VERBOSE: verbose = Boolean.parseBoolean(pipe.recvStr()); return pipe.send(OK); case ADD_EVENTS: return addEvents(pipe); case REMOVE_EVENTS: return removeEvents(pipe); case START: return start(poller, pipe); case CLOSE: return close(poller, pipe); default: System.out.printf("ZMonitor: Closing monitor %s : Unknown command %s%n", monitored, command); pipe.send(ERROR); return false; } } private boolean addEvents(Socket pipe) { final ZMsg msg = ZMsg.recvMsg(pipe); if (msg == null) { return false; // interrupted } for (ZFrame frame : msg) { final String evt = frame.getString(ZMQ.CHARSET); final Event event = Event.valueOf(evt); if (verbose) { System.out.printf("ZMonitor: Adding" + " event %s%n", event); } events |= event.code; } return pipe.send(OK); } private boolean removeEvents(Socket pipe) { final ZMsg msg = ZMsg.recvMsg(pipe); if (msg == null) { return false; // interrupted } for (ZFrame frame : msg) { final String evt = frame.getString(ZMQ.CHARSET); final Event event = Event.valueOf(evt); if (verbose) { System.out.printf("ZMonitor: Removing" + " event %s%n", event); } events &= ~event.code; } return pipe.send(OK); } private boolean start(ZPoller poller, Socket pipe) { boolean rc = true; String err = ""; if (rc) { rc = monitored.monitor(address, events); err = "Unable to monitor socket " + monitored; } if (rc) { err = "Unable to connect monitoring socket " + monitor; rc = monitor.connect(address); } if (rc) { err = "Unable to poll monitoring socket " + monitor; rc = poller.register(monitor, ZPoller.IN); } log("tart", rc, err); if (rc) { return pipe.send(OK); } pipe.send(ERROR); return false; } private boolean close(ZPoller poller, Socket pipe) { boolean rc = poller.unregister(monitor); String err = "Unable to unregister monitoring socket " + monitor; if (rc) { err = "Unable to stop monitor socket " + monitored; rc = monitored.monitor(null, events); } log("top", rc, err); if (verbose) { System.out.printf("ZMonitor: Closing monitor %s%n", monitored); } pipe.send(rc ? OK : ERROR); return false; } private void log(String action, boolean rc, String err) { if (verbose) { if (rc) { System.out.printf("ZMonitor: S%s monitor for events %s on %s%n", action, events, monitored); } else { System.out.printf( "ZMonitor: Unable to s%s monitor for events %s (%s) on %s%n", action, events, err, monitored); } } } }
final zmq.ZMQ.Event event = zmq.ZMQ.Event.read(socket.base()); assert (event != null); final int code = event.event; final String address = event.addr; assert (address != null); final Event type = Event.findByCode(code); assert (type != null); final ZMsg msg = new ZMsg(); final ZFrame frame = new ZFrame(new byte[1 + 4 + address.length() + 4]); final ZNeedle needle = new ZNeedle(frame); needle.putNumber1(type.ordinal()); needle.putNumber4(code); needle.putString(address); msg.add(frame); final Object value = event.arg; if (value != null) { msg.add(value.toString()); } return msg.send(pipe, true);
1,410
232
1,642
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/org/zeromq/ZProxy.java
State
start
class State { @Override public String toString() { return "State [alive=" + alive + ", started=" + started + ", paused=" + paused + ", restart=" + restart + ", hot=" + hot + "]"; } // are we alive ? private boolean alive = false; // are we started ? private boolean started = false; // are we paused ? private boolean paused = false; // controls creation of a new agent if asked of a cold restart private boolean restart = false; // one-shot configuration for hot restart private ZMsg hot; } // the state of the proxy private final State state = new State(); // used to transfer message from one socket to another private final Pump transport; // the nice name of the proxy private final String name; // the provider of the sockets private Proxy provider; // the sockets creator user arguments private Object[] args; private Socket frontend; private Socket backend; private Socket capture; // creates a new Proxy actor. public ProxyActor(String name, Pump transport, int id) { if (name == null) { // default basic name this.name = String.format("ZProxy-%sd", id); } else { this.name = name; } this.transport = transport; } @Override public String premiere(Socket pipe) { ZMsg reply = new ZMsg(); reply.add(ALIVE); reply.send(pipe); return name; } // creates the sockets before the start of the proxy @Override public List<Socket> createSockets(ZContext ctx, Object... args) { provider = (Proxy) args[0]; this.args = new Object[args.length - 1]; System.arraycopy(args, 1, this.args, 0, this.args.length); frontend = provider.create(ctx, Plug.FRONT, this.args); capture = provider.create(ctx, Plug.CAPTURE, this.args); backend = provider.create(ctx, Plug.BACK, this.args); assert (frontend != null); assert (backend != null); return Arrays.asList(frontend, backend); } @Override public void start(Socket pipe, List<Socket> sockets, ZPoller poller) { // init the state machine state.alive = true; state.restart = false; } // Process a control message @Override public boolean backstage(Socket pipe, ZPoller poller, int events) { assert (state.hot == null); String cmd = pipe.recvStr(); // a message has been received from the API if (START.equals(cmd)) { if (start(poller)) { return status().send(pipe); } // unable to start the proxy, exit state.restart = false; return false; } else if (STOP.equals(cmd)) { stop(); return status().send(pipe); } else if (PAUSE.equals(cmd)) { pause(poller, true); return status().send(pipe); } else if (RESTART.equals(cmd)) { String val = pipe.recvStr(); boolean hot = Boolean.parseBoolean(val); return restart(pipe, hot); } else if (STATUS.equals(cmd)) { return status().send(pipe); } else if (CONFIG.equals(cmd)) { ZMsg cfg = ZMsg.recvMsg(pipe); boolean rc = provider.configure(pipe, cfg, frontend, backend, capture, args); cfg.destroy(); return rc; } else if (EXIT.equals(cmd)) { // stops the proxy and the agent. // the status will be sent at the end of the loop state.restart = false; } else { return provider.custom(pipe, cmd, frontend, backend, capture, args); } return false; } // returns the status private ZMsg status() { ZMsg reply = new ZMsg(); if (!state.alive) { reply.add(EXITED); } else if (state.paused) { reply.add(PAUSED); } else if (state.started) { reply.add(STARTED); } else { reply.add(STOPPED); } return reply; } // starts the proxy sockets private boolean start(ZPoller poller) {<FILL_FUNCTION_BODY>
boolean success = true; if (!state.started) { try { success = false; success |= provider.configure(frontend, Plug.FRONT, args); success |= provider.configure(backend, Plug.BACK, args); success |= provider.configure(capture, Plug.CAPTURE, args); state.started = true; } catch (RuntimeException | IOException e) { e.printStackTrace(); // unable to configure proxy, exit state.restart = false; state.started = false; return false; } } pause(poller, false); return success;
1,247
170
1,417
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/org/zeromq/ZStar.java
SimpleSet
lights
class SimpleSet implements Set { @Override public boolean fire() { return Thread.currentThread().isInterrupted(); } @Override public void lights(String name, int id) {<FILL_FUNCTION_BODY>} public static String createDefaultName(final String format, final int id) { return String.format(format, id); } }
if (name == null) { name = createDefaultName("Star-%d", id); } Thread.currentThread().setName(name);
107
42
149
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/org/zeromq/ZThread.java
ShimThread
fork
class ShimThread extends Thread { private ZContext ctx; private IAttachedRunnable attachedRunnable; private IDetachedRunnable detachedRunnable; private final Object[] args; private Socket pipe; protected ShimThread(ZContext ctx, IAttachedRunnable runnable, Object[] args, Socket pipe) { assert (ctx != null); assert (pipe != null); assert (runnable != null); this.ctx = ctx; this.attachedRunnable = runnable; this.args = args; this.pipe = pipe; this.setUncaughtExceptionHandler(ctx.getUncaughtExceptionHandler()); } public ShimThread(IDetachedRunnable runnable, Object[] args) { assert (runnable != null); this.detachedRunnable = runnable; this.args = args; } @Override public void run() { if (attachedRunnable != null) { try { attachedRunnable.run(args, ctx, pipe); } catch (ZMQException e) { if (e.getErrorCode() != Error.ETERM.getCode()) { throw e; } } ctx.destroy(); } else { detachedRunnable.run(args); } } } // -------------------------------------------------------------------------- // Create a detached thread. A detached thread operates autonomously // and is used to simulate a separate process. It gets no ctx, and no // pipe. public static void start(IDetachedRunnable runnable, Object... args) { // Prepare child thread Thread shim = new ShimThread(runnable, args); shim.setDaemon(true); shim.start(); } // -------------------------------------------------------------------------- // Create an attached thread. An attached thread gets a ctx and a PAIR // pipe back to its parent. It must monitor its pipe, and exit if the // pipe becomes unreadable. Returns pipe, or null if there was an error. public static Socket fork(ZContext ctx, IAttachedRunnable runnable, Object... args) {<FILL_FUNCTION_BODY>
Socket pipe = ctx.createSocket(SocketType.PAIR); assert (pipe != null); pipe.bind(String.format(Locale.ENGLISH, "inproc://zctx-pipe-%d", pipe.hashCode())); // Connect child pipe to our pipe ZContext ccontext = ctx.shadow(); Socket cpipe = ccontext.createSocket(SocketType.PAIR); assert (cpipe != null); cpipe.connect(String.format(Locale.ENGLISH, "inproc://zctx-pipe-%d", pipe.hashCode())); // Prepare child thread Thread shim = new ShimThread(ccontext, runnable, args, cpipe); shim.start(); return pipe;
607
194
801
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/org/zeromq/ZTimer.java
Timer
add
class Timer { private final org.zeromq.timer.ZTimer.Timer delegate; Timer(org.zeromq.timer.ZTimer.Timer delegate) { this.delegate = delegate; } } /** * @deprecated use {@link org.zeromq.timer.TimerHandler} instead */ @Deprecated public interface Handler extends org.zeromq.timer.TimerHandler { } private final org.zeromq.timer.ZTimer timer = new org.zeromq.timer.ZTimer(); /** * Add timer to the set, timer repeats forever, or until cancel is called. * @param interval the interval of repetition in milliseconds. * @param handler the callback called at the expiration of the timer. * @param args the optional arguments for the handler. * @return an opaque handle for further cancel. */ public Timer add(long interval, Handler handler, Object... args) {<FILL_FUNCTION_BODY>
if (handler == null) { return null; } return new Timer(timer.add(interval, handler, args));
267
37
304
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/org/zeromq/proto/ZNeedle.java
ZNeedle
toString
class ZNeedle { private final ByteBuffer needle; // Read/write pointer for serialization public ZNeedle(ZFrame frame) { this(frame.getData()); } private ZNeedle(byte[] data) { needle = ByteBuffer.wrap(data); } private void checkAvailable(int size) { Utils.checkArgument(needle.position() + size <= needle.limit(), () -> "Unable to handle " + size + " bytes"); } private void forward(int size) { needle.position(needle.position() + size); } private <T> T get(BiFunction<ByteBuffer, Integer, T> getter, int size) { T value = getter.apply(needle, needle.position()); forward(size); return value; } // Put a 1-byte number to the frame public void putNumber1(int value) { checkAvailable(1); needle.put((byte) (value & 0xff)); } // Get a 1-byte number to the frame // then make it unsigned public int getNumber1() { checkAvailable(1); int value = needle.get(needle.position()) & 0xff; forward(1); return value; } // Put a 2-byte number to the frame public void putNumber2(int value) { checkAvailable(2); Wire.putUInt16(needle, value); } // Get a 2-byte number to the frame public int getNumber2() { checkAvailable(2); return get(Wire::getUInt16, 2); } // Put a 4-byte number to the frame public void putNumber4(int value) { checkAvailable(4); Wire.putUInt32(needle, value); } // Get a 4-byte number to the frame // then make it unsigned public int getNumber4() { checkAvailable(4); return get(Wire::getUInt32, 4); } // Put a 8-byte number to the frame public void putNumber8(long value) { checkAvailable(8); Wire.putUInt64(needle, value); } // Get a 8-byte number to the frame public long getNumber8() { checkAvailable(8); return get(Wire::getUInt64, 8); } // Put a block to the frame public void putBlock(byte[] value, int size) { needle.put(value, 0, size); } public byte[] getBlock(int size) { checkAvailable(size); byte[] value = new byte[size]; needle.get(value); return value; } // Put a string to the frame public void putShortString(String value) { checkAvailable(value.length() + 1); Wire.putShortString(needle, value); } // Get a string from the frame public String getShortString() { String value = Wire.getShortString(needle, needle.position()); forward(value.length() + 1); return value; } public void putLongString(String value) { checkAvailable(value.length() + 4); Wire.putLongString(needle, value); } // Get a long string from the frame public String getLongString() { String value = Wire.getLongString(needle, needle.position()); forward(value.length() + 4); return value; } // Put a string to the frame public void putString(String value) { if (value.length() > Byte.MAX_VALUE * 2 + 1) { putLongString(value); } else { putShortString(value); } } // Get a short string from the frame public String getString() { return getShortString(); } // Put a collection of strings to the frame public void putList(Collection<String> elements) { if (elements == null) { putNumber1(0); } else { Utils.checkArgument(elements.size() < 256, "Collection has to be smaller than 256 elements"); putNumber1(elements.size()); for (String string : elements) { putString(string); } } } public List<String> getList() { int size = getNumber1(); List<String> list = new ArrayList<>(size); for (int idx = 0; idx < size; ++ idx) { list.add(getString()); } return list; } // Put a map of strings to the frame public void putMap(Map<String, String> map) { if (map == null) { putNumber1(0); } else { Utils.checkArgument(map.size() < 256, "Map has to be smaller than 256 elements"); putNumber1(map.size()); for (Entry<String, String> entry : map.entrySet()) { if (entry.getKey().contains("=")) { throw new IllegalArgumentException("Keys cannot contain '=' sign. " + entry); } if (entry.getValue().contains("=")) { throw new IllegalArgumentException("Values cannot contain '=' sign. " + entry); } String val = entry.getKey() + "=" + entry.getValue(); putString(val); } } } public Map<String, String> getMap() { int size = getNumber1(); Map<String, String> map = new HashMap<>(size); for (int idx = 0; idx < size; ++idx) { String[] kv = getString().split("="); assert (kv.length == 2); map.put(kv[0], kv[1]); } return map; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "ZNeedle [position=" + needle.position() + ", ceiling=" + needle.limit() + "]";
1,654
33
1,687
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/org/zeromq/timer/ZTicker.java
ZTicker
timeout
class ZTicker { private final ZTimer timer; private final ZTicket ticket; public ZTicker() { timer = new ZTimer(); ticket = new ZTicket(); } ZTicker(Supplier<Long> clock) { timer = new ZTimer(clock); ticket = new ZTicket(clock); } public Ticket addTicket(long interval, TimerHandler handler, Object... args) { return ticket.add(interval, handler, args); } public Timer addTimer(long interval, TimerHandler handler, Object... args) { return timer.add(interval, handler, args); } public long timeout() {<FILL_FUNCTION_BODY>} public int execute() { return timer.execute() + ticket.execute(); } }
long timer = this.timer.timeout(); long ticket = this.ticket.timeout(); if (timer < 0 || ticket < 0) { return Math.max(timer, ticket); } else { return Math.min(timer, ticket); }
227
71
298
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/org/zeromq/timer/ZTicket.java
Ticket
add
class Ticket implements Comparable<Ticket> { private final ZTicket parent; private final TimerHandler handler; private final Object[] args; private long start; private long delay; private boolean alive = true; private Ticket(ZTicket parent, long now, long delay, TimerHandler handler, Object... args) { assert (args != null); this.parent = parent; this.start = now; this.delay = delay; this.handler = handler; this.args = args; } /** * Resets the ticket. */ public void reset() { if (alive) { parent.sort = true; start = parent.now(); } } /** * Cancels a ticket. * @return true if cancelled, false if already cancelled. */ public boolean cancel() { if (alive) { alive = false; parent.sort = true; return true; } return false; } /** * Changes the delay of the ticket. * @param delay the new delay of the ticket. */ public void setDelay(long delay) { if (alive) { parent.sort = true; this.delay = delay; } } @Override public int compareTo(Ticket other) { if (alive) { if (other.alive) { return Long.compare(start - other.start, other.delay - delay); } return -1; } return other.alive ? 1 : 0; } } private final List<Ticket> tickets; private final Supplier<Long> clock; private boolean sort; public ZTicket() { this(() -> TimeUnit.NANOSECONDS.toMillis(Clock.nowNS())); } ZTicket(Supplier<Long> clock) { this(clock, new ArrayList<>()); } ZTicket(Supplier<Long> clock, List<Ticket> tickets) { this.clock = clock; this.tickets = tickets; } private long now() { return clock.get(); } private void insert(Ticket ticket) { sort = tickets.add(ticket); } /** * Add ticket to the set. * @param delay the expiration delay in milliseconds. * @param handler the callback called at the expiration of the ticket. * @param args the optional arguments for the handler. * @return an opaque handle for further cancel and reset. */ public Ticket add(long delay, TimerHandler handler, Object... args) {<FILL_FUNCTION_BODY>
if (handler == null) { return null; } Utils.checkArgument(delay > 0, "Delay of a ticket has to be strictly greater than 0"); final Ticket ticket = new Ticket(this, now(), delay, handler, args); insert(ticket); return ticket;
746
79
825
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/org/zeromq/timer/ZTimer.java
Timer
add
class Timer { private final Timers.Timer delegate; Timer(Timers.Timer delegate) { this.delegate = delegate; } /** * Changes the interval of the timer. * <p> * This method is slow, canceling existing and adding a new timer yield better performance. * @param interval the new interval of the time. * @return true if set, otherwise false. */ public boolean setInterval(long interval) { return delegate.setInterval(interval); } /** * Reset the timer. * <p> * This method is slow, canceling existing and adding a new timer yield better performance. * @return true if reset, otherwise false. */ public boolean reset() { return delegate.reset(); } /** * Cancels a timer. * * @return true if cancelled, otherwise false. */ public boolean cancel() { return delegate.cancel(); } } private final Timers timer; public ZTimer() { timer = new Timers(); } ZTimer(Supplier<Long> clock) { timer = new Timers(clock); } /** * Add timer to the set, timer repeats forever, or until cancel is called. * @param interval the interval of repetition in milliseconds. * @param handler the callback called at the expiration of the timer. * @param args the optional arguments for the handler. * @return an opaque handle for further cancel. */ public Timer add(long interval, TimerHandler handler, Object... args) {<FILL_FUNCTION_BODY>
if (handler == null) { return null; } return new Timer(timer.add(interval, handler, args));
445
37
482
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/org/zeromq/util/ZData.java
ZData
toString
class ZData { private static final String HEX_CHAR = "0123456789ABCDEF"; private final byte[] data; public ZData(byte[] data) { this.data = data; } /** * String equals. * Uses String compareTo for the comparison (lexigraphical) * @param str String to compare with data * @return True if data matches given string */ public boolean streq(String str) { return streq(data, str); } /** * String equals. * Uses String compareTo for the comparison (lexigraphical) * @param str String to compare with data * @param data the binary data to compare * @return True if data matches given string */ public static boolean streq(byte[] data, String str) { if (data == null) { return false; } return new String(data, ZMQ.CHARSET).compareTo(str) == 0; } public boolean equals(byte[] that) { return Arrays.equals(data, that); } @Override public boolean equals(Object other) { if (this == other) { return true; } if (other == null) { return false; } if (getClass() != other.getClass()) { return false; } ZData that = (ZData) other; return Arrays.equals(this.data, that.data); } @Override public int hashCode() { return Arrays.hashCode(data); } /** * Returns a human - readable representation of data * @return * A text string or hex-encoded string if data contains any non-printable ASCII characters */ public String toString() { return toString(data); } public static String toString(byte[] data) {<FILL_FUNCTION_BODY>} /** * @return data as a printable hex string */ public String strhex() { return strhex(data); } public static String strhex(byte[] data) { if (data == null) { return ""; } StringBuilder b = new StringBuilder(data.length * 2); for (byte aData : data) { int b1 = aData >>> 4 & 0xf; int b2 = aData & 0xf; b.append(HEX_CHAR.charAt(b1)); b.append(HEX_CHAR.charAt(b2)); } return b.toString(); } public void print(PrintStream out, String prefix) { print(out, prefix, data, data.length); } public static void print(PrintStream out, String prefix, byte[] data, int size) { if (data == null) { return; } if (prefix != null) { out.printf("%s", prefix); } boolean isBin = false; int charNbr; for (charNbr = 0; charNbr < size; charNbr++) { if (data[charNbr] < 9 || data[charNbr] > 127) { isBin = true; } } out.printf("[%03d] ", size); int maxSize = isBin ? 35 : 70; String elipsis = ""; if (size > maxSize) { size = maxSize; elipsis = "..."; } for (charNbr = 0; charNbr < size; charNbr++) { if (isBin) { out.printf("%02X", data[charNbr]); } else { out.printf("%c", data[charNbr]); } } out.printf("%s\n", elipsis); out.flush(); } }
if (data == null) { return ""; } // Dump message as text or hex-encoded string boolean isText = true; for (byte aData : data) { if (aData < 32 || aData > 127) { isText = false; break; } } if (isText) { return new String(data, ZMQ.CHARSET); } else { return strhex(data); }
1,050
128
1,178
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/org/zeromq/util/ZDigest.java
ZDigest
update
class ZDigest { private final byte[] buffer; private final MessageDigest sha1; /** * Creates a new digester. */ public ZDigest() { this(new byte[8192]); } /** * Creates a new digester. * @param buffer the temp buffer used for computation of streams. */ public ZDigest(byte[] buffer) { this.buffer = buffer; try { sha1 = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } public ZDigest update(InputStream input) throws IOException {<FILL_FUNCTION_BODY>} public ZDigest update(byte[] input) { return update(input, 0, input.length); } public ZDigest update(byte[] input, int offset, int length) { sha1.update(input, offset, length); return this; } public byte[] data() { return sha1.digest(); } public int size() { return sha1.digest().length; } public String string() { return ZData.toString(data()); } }
int read = input.read(buffer); while (read != -1) { sha1.update(buffer, 0, read); read = input.read(buffer); } return this;
349
58
407
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/org/zeromq/util/ZMetadata.java
ZMetadata
read
class ZMetadata { private final Metadata metadata; public ZMetadata() { this(new Metadata()); } public ZMetadata(Metadata metadata) { this.metadata = metadata; } public Set<String> keySet() { return metadata.keySet(); } public String get(String key) { return metadata.get(key); } public void set(String key, String value) { metadata.put(key, value); } public void remove(String key) { metadata.remove(key); } public byte[] bytes() { return metadata.bytes(); } public String toString() { return metadata.toString(); } public int hashCode() { return metadata.hashCode(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ZMetadata zMetadata = (ZMetadata) o; return Objects.equals(metadata, zMetadata.metadata); } /** * Returns a {@link Set} view of the properties contained in this metadata. * The set is backed by the metadata, so changes to the metadata are * reflected in the set, and vice-versa. If the metadata is modified * while an iteration over the set is in progress (except through * the iterator's own {@code remove} operation, or through the * {@code setValue} operation on a metadata property returned by the * iterator) the results of the iteration are undefined. The set * supports element removal, which removes the corresponding * mapping from the metadata, via the {@code Iterator.remove}, * {@code Set.remove}, {@code removeAll}, {@code retainAll} and * {@code clear} operations. It does not support the * {@code add} or {@code addAll} operations. * * @return a set view of the properties contained in this metadata */ public Set<Entry<String, String>> entrySet() { return metadata.entrySet(); } /** * Returns a {@link Collection} view of the values contained in this metadata. * The collection is backed by the metadata, so changes to the map are * reflected in the collection, and vice-versa. If the metadata is * modified while an iteration over the collection is in progress * (except through the iterator's own {@code remove} operation), * the results of the iteration are undefined. The collection * supports element removal, which removes the corresponding * property from the metadata, via the {@code Iterator.remove}, * {@code Collection.remove}, {@code removeAll}, * {@code retainAll} and {@code clear} operations. It does not * support the {@code add} or {@code addAll} operations. * * @return a collection view of the values contained in this map */ public Collection<String> values() { return metadata.values(); } public void set(Metadata zapProperties) { metadata.set(zapProperties); } /** * Returns {@code true} if this map contains no key-value mappings. * * @return {@code true} if this map contains no key-value mappings */ public boolean isEmpty() { return metadata.isEmpty(); } /** * Returns {@code true} if this metada contains the property requested * * @param property property the name of the property to be tested. * @return {@code true} if this metada contains the property */ public boolean containsKey(String property) { return metadata.containsKey(property); } /** * Removes all the properties. * The map will be empty after this call returns. */ public void clear() { metadata.clear(); } /** * Returns the number of properties. If it contains more properties * than {@code Integer.MAX_VALUE} elements, returns {@code Integer.MAX_VALUE}. * * @return the number of properties */ public int size() { return metadata.size(); } /** * Serialize metadata to an output stream, using the specifications of the ZMTP protocol * <pre> * property = name value * name = OCTET 1*255name-char * name-char = ALPHA | DIGIT | "-" | "_" | "." | "+" * value = 4OCTET *OCTET ; Size in network byte order * </pre> * * @param stream the output stream * @throws IOException if an I/O error occurs. * @throws IllegalStateException if one of the properties name size is bigger than 255 */ public void write(OutputStream stream) throws IOException { metadata.write(stream); } public static ZMetadata read(String meta) {<FILL_FUNCTION_BODY>} public static ZMetadata read(ZConfig conf) { ZConfig meta = conf.getChild("metadata"); if (meta == null) { return null; } ZMetadata metadata = new ZMetadata(); for (Entry<String, String> entry : meta.getValues().entrySet()) { metadata.set(entry.getKey(), entry.getValue()); } return metadata; } }
if (meta == null || meta.isEmpty()) { return null; } try { ByteBuffer buffer = ZMQ.CHARSET.newEncoder().encode(CharBuffer.wrap(meta)); Metadata data = new Metadata(); data.read(buffer, 0, null); return new ZMetadata(data); } catch (CharacterCodingException e) { throw new IllegalArgumentException("Not a parsable metadata string"); }
1,413
118
1,531
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/Command.java
Command
toString
class Command { // Object to process the command. final ZObject destination; final Type type; final Object arg; public enum Type { // Sent to I/O thread to let it know that it should // terminate itself. STOP, // Sent to I/O object to make it register with its I/O thread PLUG, // Sent to socket to let it know about the newly created object. OWN, // Attach the engine to the session. If engine is NULL, it informs // session that the connection have failed. ATTACH, // Sent from session to socket to establish pipe(s) between them. // Caller have used inc_seqnum beforehand sending the command. BIND, // Sent by pipe writer to inform dormant pipe reader that there // are messages in the pipe. ACTIVATE_READ, // Sent by pipe reader to inform pipe writer about how many // messages it has read so far. ACTIVATE_WRITE, // Sent by pipe reader to writer after creating a new inpipe. // The parameter is actually of type pipe_t::upipe_t, however, // its definition is private so we'll have to do with void*. HICCUP, // Sent by pipe reader to pipe writer to ask it to terminate // its end of the pipe. PIPE_TERM, // Pipe writer acknowledges pipe_term command. PIPE_TERM_ACK, // Sent by I/O object ot the socket to request the shutdown of // the I/O object. TERM_REQ, // Sent by socket to I/O object to start its shutdown. TERM, // Sent by I/O object to the socket to acknowledge it has // shut down. TERM_ACK, // Transfers the ownership of the closed socket // to the reaper thread. REAP, // Sent by non-reaper socket to reaper to check destroy. REAP_ACK, // Closed socket notifies the reaper that it's already deallocated. REAPED, // TODO V4 provide a description for Command#INPROC_CONNECTED INPROC_CONNECTED, // Sent by reaper thread to the term thread when all the sockets // are successfully deallocated. DONE, // Cancel a single pending I/O call CANCEL } Command(ZObject destination, Type type) { this(destination, type, null); } Command(ZObject destination, Type type, Object arg) { this.destination = destination; this.type = type; this.arg = arg; } public final void process() { destination.processCommand(this); } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "Cmd" + "[" + destination + ", " + (destination == null ? "Reaper" : destination.getTid() + ", ") + type + (arg == null ? "" : ", " + arg) + "]";
779
59
838
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/Ctx.java
ChannelForwardHolder
terminate
class ChannelForwardHolder { private final AtomicInteger handleSource = new AtomicInteger(0); private final Map<Integer, WeakReference<SelectableChannel>> map = new ConcurrentHashMap<>(); // The WeakReference is empty when the reference is empty, so keep a reverse empty to clean the direct map. private final Map<WeakReference<SelectableChannel>, Integer> reversemap = new ConcurrentHashMap<>(); private final ReferenceQueue<SelectableChannel> queue = new ReferenceQueue<>(); } private ChannelForwardHolder forwardHolder = null; public Ctx() { active = true; terminating = false; reaper = null; slotCount = 0; slots = null; maxSockets = ZMQ.ZMQ_MAX_SOCKETS_DFLT; ioThreadCount = ZMQ.ZMQ_IO_THREADS_DFLT; threadFactory = this::createThread; ipv6 = false; blocky = true; slotSync = new ReentrantLock(); endpointsSync = new ReentrantLock(); optSync = new ReentrantLock(); termMailbox = new Mailbox(this, "terminater", -1); emptySlots = new ArrayDeque<>(); ioThreads = new ArrayList<>(); sockets = new ArrayList<>(); endpoints = new HashMap<>(); } private void destroy() throws IOException { assert (sockets.isEmpty()); for (IOThread it : ioThreads) { it.stop(); } for (IOThread it : ioThreads) { it.close(); } ioThreads.clear(); selectorSync.lock(); try { for (Selector selector : selectors) { if (selector != null) { selector.close(); } } selectors.clear(); } finally { selectorSync.unlock(); } // Deallocate the reaper thread object. if (reaper != null) { reaper.close(); } // Deallocate the array of mailboxes. No special work is // needed as mailboxes themselves were deallocated with their // corresponding io_thread/socket objects. termMailbox.close(); active = false; } /** * @return false if {@link #terminate()}terminate() has been called. */ public boolean isActive() { return active; } /** * @return false if {@link #terminate()}terminate() has been called. * @deprecated use {@link #isActive()} instead */ @Deprecated public boolean checkTag() { return active; } // This function is called when user invokes zmq_term. If there are // no more sockets open it'll cause all the infrastructure to be shut // down. If there are open sockets still, the deallocation happens // after the last one is closed. public void terminate() {<FILL_FUNCTION_BODY>
slotSync.lock(); try { // Connect up any pending inproc connections, otherwise we will hang for (Entry<PendingConnection, String> pending : pendingConnections.entries()) { SocketBase s = createSocket(ZMQ.ZMQ_PAIR); // create_socket might fail eg: out of memory/sockets limit reached assert (s != null); s.bind(pending.getValue()); s.close(); } if (!starting.get()) { // Check whether termination was already underway, but interrupted and now // restarted. boolean restarted = terminating; terminating = true; // First attempt to terminate the context. if (!restarted) { // First send stop command to sockets so that any blocking calls // can be interrupted. If there are no sockets we can ask reaper // thread to stop. for (SocketBase socket : sockets) { socket.stop(); } if (sockets.isEmpty()) { reaper.stop(); } } } } finally { slotSync.unlock(); } if (!starting.get()) { // Wait till reaper thread closes all the sockets. Command cmd = termMailbox.recv(WAIT_FOREVER); if (cmd == null) { throw new ZMQException(errno.get()); } assert (cmd.type == Command.Type.DONE) : cmd; slotSync.lock(); try { assert (sockets.isEmpty()); } finally { slotSync.unlock(); } } // Deallocate the resources. try { destroy(); } catch (IOException e) { throw new ZError.IOException(e); }
800
472
1,272
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/Mailbox.java
Mailbox
recv
class Mailbox implements IMailbox { // The pipe to store actual commands. private final Deque<Command> cpipe; // Signaler to pass signals from writer thread to reader thread. // kept it although a ConcurrentLinkedDeque, because the signaler channel is used in many places. private final Signaler signaler; // mailbox name, for better debugging private final String name; private final Errno errno; public Mailbox(Ctx ctx, String name, int tid) { this.errno = ctx.errno(); cpipe = new ConcurrentLinkedDeque<>(); signaler = new Signaler(ctx, tid, errno); this.name = name; } public SelectableChannel getFd() { return signaler.getFd(); } @Override public void send(final Command cmd) { cpipe.addLast(cmd); signaler.send(); } @Override public Command recv(long timeout) {<FILL_FUNCTION_BODY>} @Override public void close() throws IOException { signaler.close(); } @Override public String toString() { return super.toString() + "[" + name + "]"; } }
Command cmd = cpipe.pollFirst(); while (cmd == null) { // Wait for signal from the command sender. boolean rc = signaler.waitEvent(timeout); if (!rc) { assert (errno.get() == ZError.EAGAIN || errno.get() == ZError.EINTR) : errno.get(); break; } // Receive the signal. signaler.recv(); if (errno.get() == ZError.EINTR) { break; } // Get a command. // Another thread may already fetch the command, so loop on it cmd = cpipe.pollFirst(); } return cmd;
352
188
540
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/MailboxSafe.java
MailboxSafe
recv
class MailboxSafe implements IMailbox { // The pipe to store actual commands. private final YPipe<Command> cpipe; // Synchronize access to the mailbox from receivers and senders private final ReentrantLock sync; // Condition variable to pass signals from writer thread to reader thread. private final Condition condition; private final ArrayList<Signaler> signalers; // mailbox name, for better debugging private final String name; private final Errno errno; public MailboxSafe(Ctx ctx, ReentrantLock sync, String name) { this.errno = ctx.errno(); this.cpipe = new YPipe<>(Config.COMMAND_PIPE_GRANULARITY.getValue()); this.sync = sync; this.condition = this.sync.newCondition(); this.signalers = new ArrayList<>(10); this.name = name; // Get the pipe into passive state. That way, if the users starts by // polling on the associated file descriptor it will get woken up when // new command is posted. Command cmd = cpipe.read(); assert (cmd == null); } public void addSignaler(Signaler signaler) { this.signalers.add(signaler); } public void removeSignaler(Signaler signaler) { this.signalers.remove(signaler); } public void clearSignalers() { this.signalers.clear(); } @Override public void send(Command cmd) { sync.lock(); try { cpipe.write(cmd, false); boolean ok = cpipe.flush(); if (!ok) { condition.signalAll(); for (Signaler signaler : signalers) { signaler.send(); } } } finally { sync.unlock(); } } @Override public Command recv(long timeout) {<FILL_FUNCTION_BODY>} @Override public void close() { // Work around problem that other threads might still be in our // send() method, by waiting on the mutex before disappearing. sync.lock(); sync.unlock(); } @Override public String toString() { return super.toString() + "[" + name + "]"; } }
Command cmd; // Try to get the command straight away. cmd = cpipe.read(); if (cmd != null) { return cmd; } // If the timeout is zero, it will be quicker to release the lock, giving other a chance to send a command // and immediately relock it. if (timeout == 0) { sync.unlock(); sync.lock(); } else { try { // Wait for signal from the command sender. if (timeout == -1) { condition.await(); } else { condition.await(timeout, TimeUnit.MILLISECONDS); } } catch (InterruptedException e) { // Restore interrupted state... Thread.currentThread().interrupt(); errno.set(ZError.EINTR); return null; } } // Another thread may already fetch the command cmd = cpipe.read(); if (cmd == null) { errno.set(ZError.EAGAIN); return null; } return cmd;
636
289
925
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/Msg.java
Builder
put
class Builder extends Msg { private final ByteArrayOutputStream out = new ByteArrayOutputStream(); public Builder() { super(); } @Override public int size() { return out.size(); } @Override protected Msg put(int index, byte b) { out.write(b); return this; } @Override public Msg put(byte[] src, int off, int len) {<FILL_FUNCTION_BODY>} @Override public Msg put(ByteBuffer src, int off, int len) { if (src == null) { return this; } for (int idx = off; idx < off + len; ++idx) { out.write(src.get(idx)); } setWriteIndex(getWriteIndex() + len); return this; } @Override public Msg putShortString(String data) { if (data == null) { return this; } int length = data.length(); Utils.checkArgument(length < 256, "String must be strictly smaller than 256 characters"); out.write((byte) length); out.write(data.getBytes(ZMQ.CHARSET), 0, length); setWriteIndex(getWriteIndex() + length + 1); return this; } @Override public void setFlags(int flags) { super.setFlags(flags); } public Msg build() { return new Msg(this, out); } }
if (src == null) { return this; } out.write(src, off, len); setWriteIndex(getWriteIndex() + len); return this;
421
50
471
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/Proxy.java
Proxy
start
class Proxy { public static boolean proxy(SocketBase frontend, SocketBase backend, SocketBase capture) { return new Proxy().start(frontend, backend, capture, null); } public static boolean proxy(SocketBase frontend, SocketBase backend, SocketBase capture, SocketBase control) { return new Proxy().start(frontend, backend, capture, control); } public enum State { ACTIVE, PAUSED, TERMINATED } private State state; private Proxy() { state = State.ACTIVE; } private boolean start(SocketBase frontend, SocketBase backend, SocketBase capture, SocketBase control) {<FILL_FUNCTION_BODY>} private boolean process(PollItem read, PollItem write, SocketBase frontend, SocketBase backend) { return state == State.ACTIVE && read.isReadable() && (frontend == backend || write.isWritable()); } private boolean forward(SocketBase from, SocketBase to, SocketBase capture) { int more; boolean success; while (true) { Msg msg = from.recv(0); if (msg == null) { return false; } more = from.getSocketOpt(ZMQ.ZMQ_RCVMORE); if (more < 0) { return false; } // Copy message to capture socket if any success = capture(capture, msg, more); if (!success) { return false; } success = to.send(msg, more > 0 ? ZMQ.ZMQ_SNDMORE : 0); if (!success) { return false; } if (more == 0) { break; } } return true; } private boolean capture(SocketBase capture, Msg msg, int more) { if (capture != null) { Msg ctrl = new Msg(msg); return capture.send(ctrl, more > 0 ? ZMQ.ZMQ_SNDMORE : 0); } return true; } }
// The algorithm below assumes ratio of requests and replies processed // under full load to be 1:1. // TODO: The current implementation drops messages when // any of the pipes becomes full. int rc; int more; Msg msg; int count = control == null ? 2 : 3; PollItem[] items = new PollItem[count]; items[0] = new PollItem(frontend, ZMQ.ZMQ_POLLIN); items[1] = new PollItem(backend, ZMQ.ZMQ_POLLIN); if (control != null) { items[2] = new PollItem(control, ZMQ.ZMQ_POLLIN); } PollItem[] itemsout = new PollItem[2]; itemsout[0] = new PollItem(frontend, ZMQ.ZMQ_POLLOUT); itemsout[1] = new PollItem(backend, ZMQ.ZMQ_POLLOUT); Selector selector = frontend.getCtx().createSelector(); try { while (state != State.TERMINATED) { // Wait while there are either requests or replies to process. rc = ZMQ.poll(selector, items, -1); if (rc < 0) { return false; } // Get the pollout separately because when combining this with pollin it makes the CPU // because pollout shall most of the time return directly. // POLLOUT is only checked when frontend and backend sockets are not the same. if (frontend != backend) { rc = ZMQ.poll(selector, itemsout, 0L); if (rc < 0) { return false; } } // Process a control command if any if (control != null && items[2].isReadable()) { msg = control.recv(0); if (msg == null) { return false; } more = control.getSocketOpt(ZMQ.ZMQ_RCVMORE); if (more < 0) { return false; } // Copy message to capture socket if any boolean success = capture(capture, msg, more); if (!success) { return false; } byte[] command = msg.data(); if (Arrays.equals(command, ZMQ.PROXY_PAUSE)) { state = State.PAUSED; } else if (Arrays.equals(command, ZMQ.PROXY_RESUME)) { state = State.ACTIVE; } else if (Arrays.equals(command, ZMQ.PROXY_TERMINATE)) { state = State.TERMINATED; } else { // This is an API error, we should assert System.out .printf("E: invalid command sent to proxy '%s'%n", new String(command, ZMQ.CHARSET)); assert false; } } // Process a request. if (process(items[0], itemsout[1], frontend, backend)) { if (!forward(frontend, backend, capture)) { return false; } } // Process a reply. if (process(items[1], itemsout[0], frontend, backend)) { if (!forward(backend, frontend, capture)) { return false; } } } } finally { frontend.getCtx().closeSelector(selector); } return true;
578
933
1,511
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/Reaper.java
Reaper
processReaped
class Reaper extends ZObject implements IPollEvents, Closeable { // Reaper thread accesses incoming commands via this mailbox. private final Mailbox mailbox; // Handle associated with mailbox' file descriptor. private final Poller.Handle mailboxHandle; // I/O multiplexing is performed using a poller object. private final Poller poller; // Number of sockets being reaped at the moment. private int socketsReaping; // If true, we were already asked to terminate. private final AtomicBoolean terminating = new AtomicBoolean(); Reaper(Ctx ctx, int tid) { super(ctx, tid); socketsReaping = 0; String name = "reaper-" + tid; poller = new Poller(ctx, name); mailbox = new Mailbox(ctx, name, tid); SelectableChannel fd = mailbox.getFd(); mailboxHandle = poller.addHandle(fd, this); poller.setPollIn(mailboxHandle); } @Override public void close() throws IOException { poller.destroy(); mailbox.close(); } Mailbox getMailbox() { return mailbox; } void start() { poller.start(); } void stop() { if (!terminating.get()) { sendStop(); } } @Override public void inEvent() { while (true) { // Get the next command. If there is none, exit. Command cmd = mailbox.recv(0); if (cmd == null) { break; } // Process the command. cmd.process(); } } @Override protected void processStop() { terminating.set(true); // If there are no sockets being reaped finish immediately. if (socketsReaping == 0) { finishTerminating(); } } @Override protected void processReap(SocketBase socket) { ++socketsReaping; // Add the socket to the poller. socket.startReaping(poller); } @Override protected void processReaped() {<FILL_FUNCTION_BODY>} private void finishTerminating() { sendDone(); poller.removeHandle(mailboxHandle); poller.stop(); } }
--socketsReaping; // If reaped was already asked to terminate and there are no more sockets, // finish immediately. if (socketsReaping == 0 && terminating.get()) { finishTerminating(); }
658
66
724
<methods>public final zmq.Ctx getCtx() ,public final int getTid() <variables>private final non-sealed zmq.Ctx ctx,private int tid
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/Signaler.java
Signaler
recv
class Signaler implements Closeable { private interface IoOperation<O> { O call() throws IOException; } // Underlying write & read file descriptor. private final Pipe.SinkChannel w; private final Pipe.SourceChannel r; private final Selector selector; private final ThreadLocal<ByteBuffer> wdummy = ThreadLocal.withInitial(() -> ByteBuffer.allocate(1)); private final ThreadLocal<ByteBuffer> rdummy = ThreadLocal.withInitial(() -> ByteBuffer.allocate(1)); // Selector.selectNow at every sending message doesn't show enough performance private final AtomicLong wcursor = new AtomicLong(0); private long rcursor = 0; private final Errno errno; private final int pid; private final Ctx ctx; Signaler(Ctx ctx, int pid, Errno errno) { this.ctx = ctx; this.pid = pid; this.errno = errno; // Create the socket pair for signaling. try { Pipe pipe = Pipe.open(); r = pipe.source(); w = pipe.sink(); // Set both fds to non-blocking mode. Utils.unblockSocket(w, r); selector = ctx.createSelector(); r.register(selector, SelectionKey.OP_READ); } catch (IOException e) { throw new ZError.IOException(e); } } private <O> O maksInterrupt(IoOperation<O> operation) throws IOException { // This loop try to protect the current thread from external interruption. // If it happens, it mangles current context internal state. // So it keep trying until it succeed. // This must only be called on internal IO (using Pipe) boolean interrupted = Thread.interrupted(); while (true) { try { return operation.call(); } catch (ClosedByInterruptException e) { interrupted = true; } finally { if (interrupted) { Thread.currentThread().interrupt(); } } } } @Override public void close() throws IOException { IOException exception = null; IoOperation<Object> op1 = () -> { r.close(); return null; }; IoOperation<Object> op2 = () -> { w.close(); return null; }; IoOperation<Object> op3 = () -> { ctx.closeSelector(selector); return null; }; for (IoOperation<?> op : new IoOperation<?>[] {op1, op2, op3}) { try { maksInterrupt(op); } catch (IOException e) { if (exception != null) { e.addSuppressed(exception); } exception = e; } } if (exception != null) { throw exception; } } SelectableChannel getFd() { return r; } void send() { int nbytes = 0; while (nbytes == 0) { try { wdummy.get().clear(); nbytes = maksInterrupt(() -> w.write(wdummy.get())); } catch (IOException e) { throw new ZError.IOException(e); } } wcursor.incrementAndGet(); } boolean waitEvent(long timeout) { // Transform a interrupt signal in an errno EINTR if (Thread.interrupted()) { errno.set(ZError.EINTR); return false; } int rc; boolean brc = (rcursor < wcursor.get()); if (brc) { return true; } try { if (timeout == 0) { // waitEvent(0) is called every read/send of SocketBase // instant readiness is not strictly required // On the other hand, we can save lots of system call and increase performance errno.set(ZError.EAGAIN); return false; } else if (timeout < 0) { rc = selector.select(0); } else { rc = selector.select(timeout); } } catch (ClosedSelectorException e) { errno.set(ZError.EINTR); return false; } catch (IOException e) { errno.set(ZError.exccode(e)); return false; } if (Thread.interrupted() || (rc == 0 && timeout <= 0 && ! selector.keys().isEmpty())) { errno.set(ZError.EINTR); return false; } else if (rc == 0) { errno.set(ZError.EAGAIN); return false; } selector.selectedKeys().clear(); return true; } void recv() {<FILL_FUNCTION_BODY>} @Override public String toString() { return "Signaler[" + pid + "]"; } }
int nbytes = 0; // On windows, there may be a need to try several times until it succeeds while (nbytes == 0) { try { rdummy.get().clear(); nbytes = maksInterrupt(() -> r.read(rdummy.get())); } catch (ClosedChannelException e) { errno.set(ZError.EINTR); return; } catch (IOException e) { throw new ZError.IOException(e); } } assert (nbytes == 1); rcursor++;
1,355
150
1,505
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/ZError.java
IOException
exccode
class IOException extends UncheckedZMQException { private static final long serialVersionUID = 9202470691157986262L; public IOException(java.io.IOException e) { super(e); } } public static final int ENOENT = 2; public static final int EINTR = 4; public static final int EACCESS = 13; public static final int EFAULT = 14; public static final int EINVAL = 22; public static final int EAGAIN = 35; public static final int EINPROGRESS = 36; public static final int EPROTONOSUPPORT = 43; public static final int ENOTSUP = 45; public static final int EADDRINUSE = 48; public static final int EADDRNOTAVAIL = 49; public static final int ENETDOWN = 50; public static final int ENOBUFS = 55; public static final int EISCONN = 56; public static final int ENOTCONN = 57; public static final int ECONNREFUSED = 61; public static final int EHOSTUNREACH = 65; public static final int ECANCELED = 125; private static final int ZMQ_HAUSNUMERO = 156384712; public static final int ENOTSOCK = ZMQ_HAUSNUMERO + 5; public static final int EMSGSIZE = ZMQ_HAUSNUMERO + 10; public static final int EAFNOSUPPORT = ZMQ_HAUSNUMERO + 11; public static final int ENETUNREACH = ZMQ_HAUSNUMERO + 12; public static final int ECONNABORTED = ZMQ_HAUSNUMERO + 13; public static final int ECONNRESET = ZMQ_HAUSNUMERO + 14; public static final int ETIMEDOUT = ZMQ_HAUSNUMERO + 16; public static final int ENETRESET = ZMQ_HAUSNUMERO + 18; public static final int EFSM = ZMQ_HAUSNUMERO + 51; public static final int ENOCOMPATPROTO = ZMQ_HAUSNUMERO + 52; public static final int ETERM = ZMQ_HAUSNUMERO + 53; public static final int EMTHREAD = ZMQ_HAUSNUMERO + 54; public static final int EIOEXC = ZMQ_HAUSNUMERO + 105; public static final int ESOCKET = ZMQ_HAUSNUMERO + 106; public static final int EMFILE = ZMQ_HAUSNUMERO + 107; public static final int EPROTO = ZMQ_HAUSNUMERO + 108; public static int exccode(java.io.IOException e) {<FILL_FUNCTION_BODY>
if (e instanceof SocketException) { return ESOCKET; } else if (e instanceof ClosedByInterruptException) { return EINTR; } else if (e instanceof ClosedChannelException) { return ENOTCONN; } else { return EIOEXC; }
802
89
891
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/io/HelloMsgSession.java
HelloMsgSession
pullMsg
class HelloMsgSession extends SessionBase { boolean newPipe; public HelloMsgSession(IOThread ioThread, boolean connect, SocketBase socket, Options options, Address addr) { super(ioThread, connect, socket, options, addr); newPipe = true; } @Override protected Msg pullMsg() {<FILL_FUNCTION_BODY>} @Override protected void reset() { super.reset(); newPipe = true; } }
if (newPipe) { newPipe = false; return options.helloMsg; } return super.pullMsg();
136
40
176
<methods>public void <init>(zmq.io.IOThread, boolean, zmq.SocketBase, zmq.Options, zmq.io.net.Address) ,public void attachPipe(zmq.pipe.Pipe) ,public void destroy() ,public void engineError(boolean, zmq.io.StreamEngine.ErrorReason) ,public void flush() ,public java.lang.String getEndpoint() ,public zmq.SocketBase getSocket() ,public void hiccuped(zmq.pipe.Pipe) ,public final void incSeqnum() ,public void pipeTerminated(zmq.pipe.Pipe) ,public void readActivated(zmq.pipe.Pipe) ,public zmq.Msg readZapMsg() ,public void timerEvent(int) ,public java.lang.String toString() ,public void writeActivated(zmq.pipe.Pipe) ,public boolean writeZapMsg(zmq.Msg) ,public int zapConnect() <variables>private static final int LINGER_TIMER_ID,private final non-sealed boolean active,private final non-sealed zmq.io.net.Address addr,private zmq.io.IEngine engine,private boolean hasLingerTimer,private boolean incompleteIn,private final non-sealed zmq.io.IOObject ioObject,private final non-sealed zmq.io.IOThread ioThread,private boolean pending,private zmq.pipe.Pipe pipe,protected final non-sealed zmq.SocketBase socket,private final non-sealed Set<zmq.pipe.Pipe> terminatingPipes,private zmq.pipe.Pipe zapPipe
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/io/IOThread.java
IOThread
inEvent
class IOThread extends ZObject implements IPollEvents, Closeable { // I/O thread accesses incoming commands via this mailbox. private final Mailbox mailbox; // Handle associated with mailbox' file descriptor. private final Poller.Handle mailboxHandle; // I/O multiplexing is performed using a poller object. private final Poller poller; public IOThread(Ctx ctx, int tid) { super(ctx, tid); String name = "iothread-" + tid; poller = new Poller(ctx, name); mailbox = new Mailbox(ctx, name, tid); SelectableChannel fd = mailbox.getFd(); mailboxHandle = poller.addHandle(fd, this); poller.setPollIn(mailboxHandle); } public void start() { poller.start(); } @Override public void close() throws IOException { poller.destroy(); mailbox.close(); } public void stop() { sendStop(); } public Mailbox getMailbox() { return mailbox; } public int getLoad() { return poller.getLoad(); } @Override public void inEvent() {<FILL_FUNCTION_BODY>} Poller getPoller() { assert (poller != null); return poller; } @Override protected void processStop() { poller.removeHandle(mailboxHandle); poller.stop(); } }
// TODO: Do we want to limit number of commands I/O thread can // process in a single go? while (true) { // Get the next command. If there is none, exit. Command cmd = mailbox.recv(0); if (cmd == null) { break; } // Process the command. cmd.process(); }
429
103
532
<methods>public final zmq.Ctx getCtx() ,public final int getTid() <variables>private final non-sealed zmq.Ctx ctx,private int tid
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/io/Msgs.java
Msgs
startsWith
class Msgs { private Msgs() { // no possible instantiation } /** * Checks if the message starts with the given string. * * @param msg the message to check. * @param data the string to check the message with. Shall be shorter than 256 characters. * @param includeLength true if the string in the message is prefixed with the length, false if not. * @return true if the message starts with the given string, otherwise false. */ public static boolean startsWith(Msg msg, String data, boolean includeLength) {<FILL_FUNCTION_BODY>} }
final int length = data.length(); assert (length < 256); int start = includeLength ? 1 : 0; if (msg.size() < length + start) { return false; } boolean comparison = !includeLength || length == (msg.get(0) & 0xff); if (comparison) { for (int idx = start; idx < length; ++idx) { comparison = (msg.get(idx) == data.charAt(idx - start)); if (!comparison) { break; } } } return comparison;
163
156
319
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/io/coder/Decoder.java
OneByteSizeReady
sizeReady
class OneByteSizeReady implements Step { @Override public Step.Result apply() { return oneByteSizeReady(); } } protected final long maxmsgsize; // the message decoded so far protected Msg inProgress; protected final Step oneByteSizeReady = new OneByteSizeReady(); protected final Step eightByteSizeReady = new EightByteSizeReady(); protected final Step flagsReady = new FlagsReady(); protected final Step messageReady = new MessageReady(); private final MsgAllocator allocator; public Decoder(Errno errno, int bufsize, long maxmsgsize, MsgAllocator allocator) { super(errno, bufsize); this.maxmsgsize = maxmsgsize; this.allocator = allocator; } protected final Step.Result sizeReady(final long size) {<FILL_FUNCTION_BODY>
// Message size must not exceed the maximum allowed size. if (maxmsgsize >= 0) { if (size > maxmsgsize) { errno(ZError.EMSGSIZE); return Step.Result.ERROR; } } // Message size must fit within range of size_t data type. if (size > Integer.MAX_VALUE) { errno(ZError.EMSGSIZE); return Step.Result.ERROR; } // inProgress is initialized at this point so in theory we should // close it before calling init_size, however, it's a 0-byte // message and thus we can treat it as uninitialized. inProgress = allocate((int) size); return Step.Result.MORE_DATA;
236
203
439
<methods>public void <init>(zmq.util.Errno, int) ,public zmq.io.coder.IDecoder.Step.Result decode(java.nio.ByteBuffer, int, ValueReference<java.lang.Integer>) ,public void destroy() ,public int errno() ,public java.nio.ByteBuffer getBuffer() <variables>private final non-sealed java.nio.ByteBuffer buf,private final non-sealed int bufsize,private final non-sealed zmq.util.Errno errno,private zmq.io.coder.IDecoder.Step next,private java.nio.ByteBuffer readPos,private int toRead,private boolean zeroCopy
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/io/coder/DecoderBase.java
DecoderBase
nextStep
class DecoderBase implements IDecoder { // Where to store the read data. private ByteBuffer readPos; // TODO V4 remove zeroCopy boolean private boolean zeroCopy; // How much data to read before taking next step. private int toRead; // The buffer for data to decode. private final int bufsize; private final ByteBuffer buf; private Step next; private final Errno errno; public DecoderBase(Errno errno, int bufsize) { next = null; readPos = null; toRead = 0; this.bufsize = bufsize; assert (bufsize > 0); buf = ByteBuffer.allocateDirect(bufsize); this.errno = errno; } // Returns a buffer to be filled with binary data. @Override public ByteBuffer getBuffer() { // If we are expected to read large message, we'll opt for zero- // copy, i.e. we'll ask caller to fill the data directly to the // message. Note that subsequent read(s) are non-blocking, thus // each single read reads at most SO_RCVBUF bytes at once not // depending on how large is the chunk returned from here. // As a consequence, large messages being received won't block // other engines running in the same I/O thread for excessive // amounts of time. if (toRead >= bufsize) { zeroCopy = true; return readPos.duplicate(); } else { zeroCopy = false; buf.clear(); return buf; } } // Processes the data in the buffer previously allocated using // get_buffer function. size_ argument specifies number of bytes // actually filled into the buffer. Function returns number of // bytes actually processed. @Override public Step.Result decode(ByteBuffer data, int size, ValueReference<Integer> processed) { processed.set(0); // In case of zero-copy simply adjust the pointers, no copying // is required. Also, run the state machine in case all the data // were processed. if (zeroCopy) { assert (size <= toRead); readPos.position(readPos.position() + size); toRead -= size; processed.set(size); while (readPos.remaining() == 0) { Step.Result result = next.apply(); if (result != Step.Result.MORE_DATA) { return result; } } return Step.Result.MORE_DATA; } while (processed.get() < size) { // Copy the data from buffer to the message. int toCopy = Math.min(toRead, size - processed.get()); int limit = data.limit(); data.limit(data.position() + toCopy); readPos.put(data); data.limit(limit); toRead -= toCopy; processed.set(processed.get() + toCopy); // Try to get more space in the message to fill in. // If none is available, return. while (readPos.remaining() == 0) { Step.Result result = next.apply(); if (result != Step.Result.MORE_DATA) { return result; } } } return Step.Result.MORE_DATA; } protected void nextStep(Msg msg, Step next) { nextStep(msg.buf(), next); } @Deprecated protected void nextStep(byte[] buf, int toRead, Step next) {<FILL_FUNCTION_BODY>} protected void nextStep(ByteBuffer buf, Step next) { readPos = buf; this.toRead = buf.remaining(); this.next = next; } protected void errno(int err) { this.errno.set(err); } public int errno() { return errno.get(); } @Override public void destroy() { } }
readPos = ByteBuffer.wrap(buf); readPos.limit(toRead); this.toRead = toRead; this.next = next;
1,078
43
1,121
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/io/coder/EncoderBase.java
EncoderBase
encode
class EncoderBase implements IEncoder { // Where to get the data to write from. private ByteBuffer writeBuf; // Next step. If set to null, it means that associated data stream // is dead. private Runnable next; // If true, first byte of the message is being written. private boolean newMsgFlag; // How much data to write before next step should be executed. private int toWrite; // The buffer for encoded data. private final ByteBuffer buffer; private final int bufferSize; private boolean error; protected Msg inProgress; private final Errno errno; protected EncoderBase(Errno errno, int bufferSize) { this.errno = errno; this.bufferSize = bufferSize; buffer = ByteBuffer.allocateDirect(bufferSize); error = false; } // Load a new message into encoder. @Override public final void loadMsg(Msg msg) { assert (inProgress == null); inProgress = msg; next(); } // The function returns a batch of binary data. The data // are filled to a supplied buffer. If no buffer is supplied (data // is NULL) encoder will provide buffer of its own. @Override public final int encode(ValueReference<ByteBuffer> data, int size) {<FILL_FUNCTION_BODY>} @Override public void encoded() { buffer.flip(); } protected void encodingError() { error = true; } public final boolean isError() { return error; } protected void next() { if (next != null) { next.run(); } } protected void nextStep(Msg msg, Runnable state, boolean beginning) { if (msg == null) { nextStep((byte[]) null, 0, state, beginning); } else { nextStep(msg.buf(), state, beginning); } } // This function should be called from derived class to write the data // to the buffer and schedule next state machine action. private void nextStep(byte[] buf, int toWrite, Runnable next, boolean newMsgFlag) { if (buf != null) { writeBuf = ByteBuffer.wrap(buf); writeBuf.limit(toWrite); } else { writeBuf = null; } this.toWrite = toWrite; this.next = next; this.newMsgFlag = newMsgFlag; } protected void initStep(Runnable next, boolean newMsgFlag) { nextStep((byte[]) null, 0, next, newMsgFlag); } private void nextStep(ByteBuffer buf, Runnable next, boolean newMsgFlag) { nextStep(buf, buf.limit(), next, newMsgFlag); } protected void nextStep(ByteBuffer buf, int toWrite, Runnable next, boolean newMsgFlag) { buf.limit(toWrite); buf.position(toWrite); buf.flip(); writeBuf = buf; this.toWrite = toWrite; this.next = next; this.newMsgFlag = newMsgFlag; } public int errno() { return errno.get(); } public void errno(int err) { this.errno.set(err); } @Override public void destroy() { } }
int bufferSize = size; ByteBuffer buf = data.get(); if (buf == null) { buf = this.buffer; bufferSize = this.bufferSize; buffer.clear(); } if (inProgress == null) { return 0; } int pos = 0; buf.limit(buf.capacity()); while (pos < bufferSize) { // If there are no more data to return, run the state machine. // If there are still no data, return what we already have // in the buffer. if (toWrite == 0) { if (newMsgFlag) { inProgress = null; break; } next(); } // If there are no data in the buffer yet and we are able to // fill whole buffer in a single go, let's use zero-copy. // There's no disadvantage to it as we cannot stuck multiple // messages into the buffer anyway. Note that subsequent // write(s) are non-blocking, thus each single write writes // at most SO_SNDBUF bytes at once not depending on how large // is the chunk returned from here. // As a consequence, large messages being sent won't block // other engines running in the same I/O thread for excessive // amounts of time. if (pos == 0 && data.get() == null && toWrite >= bufferSize) { writeBuf.limit(writeBuf.capacity()); data.set(writeBuf); pos = toWrite; writeBuf = null; toWrite = 0; return pos; } // Copy data to the buffer. If the buffer is full, return. int toCopy = Math.min(toWrite, bufferSize - pos); int limit = writeBuf.limit(); writeBuf.limit(Math.min(writeBuf.capacity(), writeBuf.position() + toCopy)); int current = buf.position(); buf.put(writeBuf); toCopy = buf.position() - current; writeBuf.limit(limit); pos += toCopy; toWrite -= toCopy; } data.set(buf); return pos;
933
567
1,500
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/io/coder/v1/V1Decoder.java
V1Decoder
oneByteSizeReady
class V1Decoder extends Decoder { private final ByteBuffer tmpbuf; public V1Decoder(Errno errno, int bufsize, long maxmsgsize, MsgAllocator allocator) { super(errno, bufsize, maxmsgsize, allocator); tmpbuf = ByteBuffer.allocate(8); tmpbuf.limit(1); // At the beginning, read one byte and go to ONE_BYTE_SIZE_READY state. nextStep(tmpbuf, oneByteSizeReady); } @Override protected Step.Result oneByteSizeReady() {<FILL_FUNCTION_BODY>} @Override protected Step.Result eightByteSizeReady() { // 8-byte payload length is read. Allocate the buffer // for message body and read the message data into it. tmpbuf.position(0); tmpbuf.limit(8); final long payloadLength = Wire.getUInt64(tmpbuf, 0); if (payloadLength <= 0) { errno(ZError.EPROTO); return Step.Result.ERROR; } tmpbuf.limit(1); Step.Result rc = sizeReady(payloadLength - 1); if (rc != Step.Result.ERROR) { nextStep(tmpbuf, flagsReady); } return rc; } @Override protected Step.Result flagsReady() { // Store the flags from the wire into the message structure. int first = tmpbuf.get(0) & 0xff; if ((first & V1Protocol.MORE_FLAG) > 0) { inProgress.setFlags(Msg.MORE); } nextStep(inProgress, messageReady); return Step.Result.MORE_DATA; } @Override protected Step.Result messageReady() { // Message is completely read. Push it further and start reading // new message. (inProgress is a 0-byte message after this point.) tmpbuf.position(0); tmpbuf.limit(1); nextStep(tmpbuf, oneByteSizeReady); return Step.Result.DECODED; } }
// First byte of size is read. If it is 0xff read 8-byte size. // Otherwise allocate the buffer for message data and read the // message data into it. int size = tmpbuf.get(0) & 0xff; if (size == 0xff) { tmpbuf.position(0); tmpbuf.limit(8); nextStep(tmpbuf, eightByteSizeReady); } else { // There has to be at least one byte (the flags) in the message). if (size == 0) { errno(ZError.EPROTO); return Step.Result.ERROR; } tmpbuf.position(0); tmpbuf.limit(1); Step.Result rc = sizeReady(size - 1); if (rc != Step.Result.ERROR) { nextStep(tmpbuf, flagsReady); } return rc; } return Step.Result.MORE_DATA;
575
256
831
<methods>public void <init>(zmq.util.Errno, int, long, zmq.msg.MsgAllocator) ,public zmq.Msg msg() <variables>private final non-sealed zmq.msg.MsgAllocator allocator,protected final zmq.io.coder.IDecoder.Step eightByteSizeReady,protected final zmq.io.coder.IDecoder.Step flagsReady,protected zmq.Msg inProgress,protected final non-sealed long maxmsgsize,protected final zmq.io.coder.IDecoder.Step messageReady,protected final zmq.io.coder.IDecoder.Step oneByteSizeReady
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/io/coder/v1/V1Encoder.java
V1Encoder
messageReady
class V1Encoder extends Encoder { private final ByteBuffer tmpbufWrap; public V1Encoder(Errno errno, int bufsize) { super(errno, bufsize); tmpbufWrap = ByteBuffer.allocate(10); // Write 0 bytes to the batch and go to messageReady state. initStep(messageReady, true); } @Override protected void sizeReady() { // Write message body into the buffer. nextStep(inProgress.buf(), inProgress.size(), messageReady, true); } @Override protected void messageReady() {<FILL_FUNCTION_BODY>} }
// Get the message size. int size = inProgress.size(); // Account for the 'flags' byte. size++; // For messages less than 255 bytes long, write one byte of message size. // For longer messages write 0xff escape character followed by 8-byte // message size. In both cases 'flags' field follows. tmpbufWrap.position(0); if (size < 255) { tmpbufWrap.limit(2); tmpbufWrap.put((byte) size); } else { tmpbufWrap.limit(10); tmpbufWrap.put((byte) 0xff); Wire.putUInt64(tmpbufWrap, size); } tmpbufWrap.put((byte) (inProgress.flags() & Msg.MORE)); nextStep(tmpbufWrap, tmpbufWrap.limit(), sizeReady, false);
177
240
417
<methods><variables>protected final java.lang.Runnable messageReady,protected final java.lang.Runnable sizeReady
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/io/coder/v2/V2Decoder.java
V2Decoder
flagsReady
class V2Decoder extends Decoder { private final ByteBuffer tmpbuf; private int msgFlags; public V2Decoder(Errno errno, int bufsize, long maxmsgsize, MsgAllocator allocator) { super(errno, bufsize, maxmsgsize, allocator); tmpbuf = ByteBuffer.allocate(8); tmpbuf.limit(1); // At the beginning, read one byte and go to ONE_BYTE_SIZE_READY state. nextStep(tmpbuf, flagsReady); } @Override protected Msg allocate(int size) { Msg msg = super.allocate(size); msg.setFlags(msgFlags); return msg; } @Override protected Step.Result oneByteSizeReady() { int size = tmpbuf.get(0) & 0xff; Step.Result rc = sizeReady(size); if (rc != Step.Result.ERROR) { nextStep(inProgress, messageReady); } return rc; } @Override protected Step.Result eightByteSizeReady() { // The payload size is encoded as 64-bit unsigned integer. // The most significant byte comes first. tmpbuf.position(0); tmpbuf.limit(8); final long size = Wire.getUInt64(tmpbuf, 0); Step.Result rc = sizeReady(size); if (rc != Step.Result.ERROR) { nextStep(inProgress, messageReady); } return rc; } @Override protected Step.Result flagsReady() {<FILL_FUNCTION_BODY>} @Override protected Step.Result messageReady() { // Message is completely read. Signal this to the caller // and prepare to decode next message. tmpbuf.position(0); tmpbuf.limit(1); nextStep(tmpbuf, flagsReady); return Step.Result.DECODED; } }
// Store the flags from the wire into the message structure. this.msgFlags = 0; int first = tmpbuf.get(0) & 0xff; if ((first & V2Protocol.MORE_FLAG) > 0) { this.msgFlags |= Msg.MORE; } if ((first & V2Protocol.COMMAND_FLAG) > 0) { this.msgFlags |= Msg.COMMAND; } // The payload length is either one or eight bytes, // depending on whether the 'large' bit is set. tmpbuf.position(0); if ((first & V2Protocol.LARGE_FLAG) > 0) { tmpbuf.limit(8); nextStep(tmpbuf, eightByteSizeReady); } else { tmpbuf.limit(1); nextStep(tmpbuf, oneByteSizeReady); } return Step.Result.MORE_DATA;
537
241
778
<methods>public void <init>(zmq.util.Errno, int, long, zmq.msg.MsgAllocator) ,public zmq.Msg msg() <variables>private final non-sealed zmq.msg.MsgAllocator allocator,protected final zmq.io.coder.IDecoder.Step eightByteSizeReady,protected final zmq.io.coder.IDecoder.Step flagsReady,protected zmq.Msg inProgress,protected final non-sealed long maxmsgsize,protected final zmq.io.coder.IDecoder.Step messageReady,protected final zmq.io.coder.IDecoder.Step oneByteSizeReady
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/io/coder/v2/V2Encoder.java
V2Encoder
messageReady
class V2Encoder extends Encoder { private final ByteBuffer tmpbufWrap; public V2Encoder(Errno errno, int bufsize) { super(errno, bufsize); tmpbufWrap = ByteBuffer.allocate(9); // Write 0 bytes to the batch and go to messageReady state. initStep(messageReady, true); } @Override protected void messageReady() {<FILL_FUNCTION_BODY>} @Override protected void sizeReady() { // Write message body into the buffer. nextStep(inProgress.buf(), inProgress.size(), messageReady, true); } }
// Encode flags. byte protocolFlags = 0; if (inProgress.hasMore()) { protocolFlags |= V2Protocol.MORE_FLAG; } if (inProgress.size() > 255) { protocolFlags |= V2Protocol.LARGE_FLAG; } if (inProgress.isCommand()) { protocolFlags |= V2Protocol.COMMAND_FLAG; } // Encode the message length. For messages less then 256 bytes, // the length is encoded as 8-bit unsigned integer. For larger // messages, 64-bit unsigned integer in network byte order is used. final int size = inProgress.size(); tmpbufWrap.position(0); tmpbufWrap.put(protocolFlags); if (size > 255) { tmpbufWrap.limit(9); Wire.putUInt64(tmpbufWrap, size); } else { tmpbufWrap.limit(2); tmpbufWrap.put((byte) size); } nextStep(tmpbufWrap, tmpbufWrap.limit(), sizeReady, false);
176
292
468
<methods><variables>protected final java.lang.Runnable messageReady,protected final java.lang.Runnable sizeReady
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/io/mechanism/NullMechanism.java
NullMechanism
nextHandshakeCommand
class NullMechanism extends Mechanism { private static final String OK = "200"; private static final String READY = "READY"; private static final String ERROR = "ERROR"; private boolean readyCommandSent; private boolean errorCommandSent; private boolean readyCommandReceived; private boolean errorCommandReceived; private boolean zapConnected; private boolean zapRequestSent; private boolean zapReplyReceived; NullMechanism(SessionBase session, Address peerAddress, Options options) { super(session, peerAddress, options); // NULL mechanism only uses ZAP if there's a domain defined // This prevents ZAP requests on naive sockets if (options.zapDomain != null && !options.zapDomain.isEmpty() && session.zapConnect() == 0) { zapConnected = true; } } @Override public int nextHandshakeCommand(Msg msg) {<FILL_FUNCTION_BODY>} @Override public int processHandshakeCommand(Msg msg) { if (readyCommandReceived || errorCommandReceived) { session.getSocket().eventHandshakeFailedProtocol(session.getEndpoint(), ZMQ.ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND); return ZError.EPROTO; } int dataSize = msg.size(); int rc; if (dataSize >= 6 && compare(msg, READY, true)) { rc = processReadyCommand(msg); } else if (dataSize >= 6 && compare(msg, ERROR, true)) { rc = processErrorCommand(msg); } else { session.getSocket().eventHandshakeFailedProtocol(session.getEndpoint(), ZMQ.ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND); return ZError.EPROTO; } return rc; } private int processReadyCommand(Msg msg) { readyCommandReceived = true; return parseMetadata(msg, 6, false); } private int processErrorCommand(Msg msg) { errorCommandReceived = true; return parseErrorMessage(msg); } @Override public int zapMsgAvailable() { if (zapReplyReceived) { return ZError.EFSM; } int rc = receiveAndProcessZapReply(); if (rc == 0) { zapReplyReceived = true; } return rc; } @Override public Status status() { boolean commandSent = readyCommandSent || errorCommandSent; boolean commandReceived = readyCommandReceived || errorCommandReceived; if (readyCommandSent && readyCommandReceived) { return Status.READY; } if (commandSent && commandReceived) { return Status.ERROR; } return Status.HANDSHAKING; } }
if (readyCommandSent || errorCommandSent) { return ZError.EAGAIN; } if (zapConnected && !zapReplyReceived) { if (zapRequestSent) { return ZError.EAGAIN; } sendZapRequest(Mechanisms.NULL, false); zapRequestSent = true; int rc = receiveAndProcessZapReply(); if (rc != 0) { return rc; } zapReplyReceived = true; } if (zapReplyReceived && !OK.equals(statusCode)) { msg.putShortString(ERROR); msg.putShortString(statusCode); errorCommandSent = true; return 0; } // Add mechanism string msg.putShortString(READY); // Add socket type property String socketType = socketType(); addProperty(msg, SOCKET_TYPE, socketType); // Add identity property if (options.type == ZMQ.ZMQ_REQ || options.type == ZMQ.ZMQ_DEALER || options.type == ZMQ.ZMQ_ROUTER) { addProperty(msg, IDENTITY, options.identity); } readyCommandSent = true; return 0;
782
350
1,132
<methods>public zmq.Msg decode(zmq.Msg) ,public void destroy() ,public zmq.Msg encode(zmq.Msg) ,public final zmq.util.Blob getUserId() ,public abstract int nextHandshakeCommand(zmq.Msg) ,public final zmq.Msg peerIdentity() ,public abstract int processHandshakeCommand(zmq.Msg) ,public abstract zmq.io.mechanism.Mechanism.Status status() ,public abstract int zapMsgAvailable() <variables>private zmq.util.Blob identity,protected final non-sealed zmq.Options options,private final non-sealed zmq.io.net.Address peerAddress,protected final non-sealed zmq.io.SessionBase session,protected java.lang.String statusCode,private zmq.util.Blob userId,public final zmq.io.Metadata zapProperties,public final zmq.io.Metadata zmtpProperties
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/io/mechanism/curve/Curve.java
Curve
keypair
class Curve { enum Size { NONCE { @Override public int bytes() { return curve25519xsalsa20poly1305.crypto_secretbox_NONCEBYTES; } }, ZERO { @Override public int bytes() { return curve25519xsalsa20poly1305.crypto_secretbox_ZEROBYTES; } }, BOXZERO { @Override public int bytes() { return curve25519xsalsa20poly1305.crypto_secretbox_BOXZEROBYTES; } }, PUBLICKEY { @Override public int bytes() { return curve25519xsalsa20poly1305.crypto_secretbox_PUBLICKEYBYTES; } }, SECRETKEY { @Override public int bytes() { return curve25519xsalsa20poly1305.crypto_secretbox_SECRETKEYBYTES; } }, KEY { @Override public int bytes() { return 32; } }, BEFORENM { @Override public int bytes() { return curve25519xsalsa20poly1305.crypto_secretbox_BEFORENMBYTES; } }; public abstract int bytes(); } public Curve() { } public static String z85EncodePublic(byte[] publicKey) { return Z85.encode(publicKey, Size.PUBLICKEY.bytes()); } /** * Generates a pair of Z85-encoded keys for use with this class. * * @return an array of 2 strings, holding Z85-encoded keys. * The first element of the array is the public key, * the second element is the private (or secret) key. */ public String[] keypairZ85() { String[] pair = new String[2]; byte[] publicKey = new byte[Size.PUBLICKEY.bytes()]; byte[] secretKey = new byte[Size.SECRETKEY.bytes()]; int rc = curve25519xsalsa20poly1305.crypto_box_keypair(publicKey, secretKey); assert (rc == 0); pair[0] = Z85.encode(publicKey, Size.PUBLICKEY.bytes()); pair[1] = Z85.encode(secretKey, Size.SECRETKEY.bytes()); return pair; } /** * Generates a pair of keys for use with this class. * * @return an array of 2 byte arrays, holding keys. * The first element of the array is the public key, * the second element is the private (or secret) key. */ public byte[][] keypair() {<FILL_FUNCTION_BODY>} int beforenm(byte[] outSharedKey, byte[] publicKey, byte[] secretKey) { return curve25519xsalsa20poly1305.crypto_box_beforenm(outSharedKey, publicKey, secretKey); } int afternm(ByteBuffer ciphered, ByteBuffer plaintext, int length, ByteBuffer nonce, byte[] precom) { return afternm(ciphered.array(), plaintext.array(), length, nonce.array(), precom); } int afternm(byte[] ciphered, byte[] plaintext, int length, byte[] nonce, byte[] precomp) { return curve25519xsalsa20poly1305.crypto_box_afternm(ciphered, plaintext, length, nonce, precomp); } int openAfternm(ByteBuffer plaintext, ByteBuffer messagebox, int length, ByteBuffer nonce, byte[] precom) { return openAfternm(plaintext.array(), messagebox.array(), length, nonce.array(), precom); } int openAfternm(byte[] plaintext, byte[] cipher, int length, byte[] nonce, byte[] precom) { return curve25519xsalsa20poly1305.crypto_box_open_afternm(plaintext, cipher, length, nonce, precom); } int open(ByteBuffer plaintext, ByteBuffer messagebox, int length, ByteBuffer nonce, byte[] precom, byte[] secretKey) { return open(plaintext.array(), messagebox.array(), length, nonce.array(), precom, secretKey); } int open(byte[] plaintext, byte[] messagebox, int length, byte[] nonce, byte[] publicKey, byte[] secretKey) { return curve25519xsalsa20poly1305.crypto_box_open(plaintext, messagebox, length, nonce, publicKey, secretKey); } int secretbox(ByteBuffer ciphertext, ByteBuffer plaintext, int length, ByteBuffer nonce, byte[] key) { return secretbox(ciphertext.array(), plaintext.array(), length, nonce.array(), key); } int secretbox(byte[] ciphertext, byte[] plaintext, int length, byte[] nonce, byte[] key) { return xsalsa20poly1305.crypto_secretbox(ciphertext, plaintext, length, nonce, key); } int secretboxOpen(ByteBuffer plaintext, ByteBuffer box, int length, ByteBuffer nonce, byte[] key) { return secretboxOpen(plaintext.array(), box.array(), length, nonce.array(), key); } int secretboxOpen(byte[] plaintext, byte[] box, int length, byte[] nonce, byte[] key) { return xsalsa20poly1305.crypto_secretbox_open(plaintext, box, length, nonce, key); } byte[] random(int length) { return Utils.randomBytes(length); } public int box(ByteBuffer ciphertext, ByteBuffer plaintext, int length, ByteBuffer nonce, byte[] publicKey, byte[] secretKey) { return box(ciphertext.array(), plaintext.array(), length, nonce.array(), publicKey, secretKey); } public int box(byte[] ciphertext, byte[] plaintext, int length, byte[] nonce, byte[] publicKey, byte[] secretKey) { return curve25519xsalsa20poly1305.crypto_box(ciphertext, plaintext, length, nonce, publicKey, secretKey); } }
byte[][] pair = new byte[2][]; byte[] publicKey = new byte[Size.PUBLICKEY.bytes()]; byte[] secretKey = new byte[Size.SECRETKEY.bytes()]; int rc = curve25519xsalsa20poly1305.crypto_box_keypair(publicKey, secretKey); assert (rc == 0); pair[0] = publicKey; pair[1] = secretKey; return pair;
1,773
130
1,903
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/io/mechanism/plain/PlainClientMechanism.java
PlainClientMechanism
nextHandshakeCommand
class PlainClientMechanism extends Mechanism { private enum State { SENDING_HELLO, WAITING_FOR_WELCOME, SENDING_INITIATE, WAITING_FOR_READY, ERROR_COMMAND_RECEIVED, READY } private State state; public PlainClientMechanism(SessionBase session, Options options) { super(session, null, options); this.state = State.SENDING_HELLO; } @Override public int nextHandshakeCommand(Msg msg) {<FILL_FUNCTION_BODY>} @Override public int processHandshakeCommand(Msg msg) { int rc; int dataSize = msg.size(); if (dataSize >= 8 && compare(msg, "WELCOME", true)) { rc = processWelcome(msg); } else if (dataSize >= 6 && compare(msg, "READY", true)) { rc = processReady(msg); } else if (dataSize >= 6 && compare(msg, "ERROR", true)) { rc = processError(msg); } else { // Temporary support for security debugging System.out.println("PLAIN Client I: invalid handshake command"); rc = ZError.EPROTO; } return rc; } @Override public Status status() { if (state == State.READY) { return Status.READY; } else if (state == State.ERROR_COMMAND_RECEIVED) { return Status.ERROR; } else { return Status.HANDSHAKING; } } @Override public int zapMsgAvailable() { return 0; } private int produceHello(Msg msg) { String plainUsername = options.plainUsername; assert (plainUsername.length() < 256); String plainPassword = options.plainPassword; assert (plainPassword.length() < 256); msg.putShortString("HELLO"); msg.putShortString(plainUsername); msg.putShortString(plainPassword); return 0; } private int processWelcome(Msg msg) { if (state != State.WAITING_FOR_WELCOME) { return ZError.EPROTO; } if (msg.size() != 8) { return ZError.EPROTO; } state = State.SENDING_INITIATE; return 0; } private int produceInitiate(Msg msg) { // Add mechanism string msg.putShortString("INITIATE"); // Add socket type property String socketType = socketType(); addProperty(msg, SOCKET_TYPE, socketType); // Add identity property if (options.type == ZMQ.ZMQ_REQ || options.type == ZMQ.ZMQ_DEALER || options.type == ZMQ.ZMQ_ROUTER) { addProperty(msg, IDENTITY, options.identity); } return 0; } private int processReady(Msg msg) { if (state != State.WAITING_FOR_READY) { return ZError.EPROTO; } int rc = parseMetadata(msg, 6, false); if (rc == 0) { state = State.READY; } return rc; } private int processError(Msg msg) { if (state != State.WAITING_FOR_WELCOME && state != State.WAITING_FOR_READY) { session.getSocket().eventHandshakeFailedProtocol(session.getEndpoint(), ZMQ.ZMQ_PROTOCOL_ERROR_ZMTP_UNEXPECTED_COMMAND); return ZError.EPROTO; } state = State.ERROR_COMMAND_RECEIVED; return parseErrorMessage(msg); } }
int rc; switch (state) { case SENDING_HELLO: rc = produceHello(msg); if (rc == 0) { state = State.WAITING_FOR_WELCOME; } break; case SENDING_INITIATE: rc = produceInitiate(msg); if (rc == 0) { state = State.WAITING_FOR_READY; } break; default: rc = ZError.EAGAIN; break; } return rc;
1,087
154
1,241
<methods>public zmq.Msg decode(zmq.Msg) ,public void destroy() ,public zmq.Msg encode(zmq.Msg) ,public final zmq.util.Blob getUserId() ,public abstract int nextHandshakeCommand(zmq.Msg) ,public final zmq.Msg peerIdentity() ,public abstract int processHandshakeCommand(zmq.Msg) ,public abstract zmq.io.mechanism.Mechanism.Status status() ,public abstract int zapMsgAvailable() <variables>private zmq.util.Blob identity,protected final non-sealed zmq.Options options,private final non-sealed zmq.io.net.Address peerAddress,protected final non-sealed zmq.io.SessionBase session,protected java.lang.String statusCode,private zmq.util.Blob userId,public final zmq.io.Metadata zapProperties,public final zmq.io.Metadata zmtpProperties
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/io/mechanism/plain/PlainServerMechanism.java
PlainServerMechanism
produceHello
class PlainServerMechanism extends Mechanism { private enum State { WAITING_FOR_HELLO, SENDING_WELCOME, WAITING_FOR_INITIATE, SENDING_READY, WAITING_FOR_ZAP_REPLY, SENDING_ERROR, ERROR_COMMAND_SENT, READY } private State state; public PlainServerMechanism(SessionBase session, Address peerAddress, Options options) { super(session, peerAddress, options); this.state = State.WAITING_FOR_HELLO; } @Override public int nextHandshakeCommand(Msg msg) { int rc; switch (state) { case SENDING_WELCOME: rc = produceWelcome(msg); if (rc == 0) { state = State.WAITING_FOR_INITIATE; } break; case SENDING_READY: rc = produceReady(msg); if (rc == 0) { state = State.READY; } break; case SENDING_ERROR: rc = produceError(msg); if (rc == 0) { state = State.ERROR_COMMAND_SENT; } break; default: rc = ZError.EAGAIN; break; } return rc; } @Override public int processHandshakeCommand(Msg msg) { int rc; switch (state) { case WAITING_FOR_HELLO: rc = produceHello(msg); break; case WAITING_FOR_INITIATE: rc = produceInitiate(msg); break; default: rc = ZError.EPROTO; break; } return rc; } @Override public Status status() { if (state == State.READY) { return Status.READY; } else if (state == State.ERROR_COMMAND_SENT) { return Status.ERROR; } else { return Status.HANDSHAKING; } } @Override public int zapMsgAvailable() { if (state != State.WAITING_FOR_ZAP_REPLY) { return ZError.EFSM; } int rc = receiveAndProcessZapReply(); if (rc == 0) { state = "200".equals(statusCode) ? State.SENDING_WELCOME : State.SENDING_ERROR; } return rc; } private int produceHello(Msg msg) {<FILL_FUNCTION_BODY>} private int produceWelcome(Msg msg) { msg.putShortString("WELCOME"); return 0; } private int produceInitiate(Msg msg) { int bytesLeft = msg.size(); if (bytesLeft < 9 || !compare(msg, "INITIATE", true)) { return ZError.EPROTO; } int rc = parseMetadata(msg, 9, false); if (rc == 0) { state = State.SENDING_READY; } return rc; } private int produceReady(Msg msg) { // Add command name msg.putShortString("READY"); // Add socket type property String socketType = socketType(); addProperty(msg, SOCKET_TYPE, socketType); // Add identity property if (options.type == ZMQ.ZMQ_REQ || options.type == ZMQ.ZMQ_DEALER || options.type == ZMQ.ZMQ_ROUTER) { addProperty(msg, IDENTITY, options.identity); } return 0; } private int produceError(Msg msg) { assert (statusCode != null && statusCode.length() == 3); msg.putShortString("ERROR"); msg.putShortString(statusCode); return 0; } private void sendZapRequest(byte[] username, byte[] password) { sendZapRequest(Mechanisms.PLAIN, true); // Username frame Msg msg = new Msg(username.length); msg.setFlags(Msg.MORE); msg.put(username); boolean rc = session.writeZapMsg(msg); assert (rc); // Password frame msg = new Msg(password.length); msg.put(password); rc = session.writeZapMsg(msg); assert (rc); } }
int bytesLeft = msg.size(); int index = 0; if (bytesLeft < 6 || !compare(msg, "HELLO", true)) { return ZError.EPROTO; } bytesLeft -= 6; index += 6; if (bytesLeft < 1) { return ZError.EPROTO; } byte length = msg.get(index); bytesLeft -= 1; if (bytesLeft < length) { return ZError.EPROTO; } byte[] tmp = new byte[length]; index += 1; msg.getBytes(index, tmp, 0, length); byte[] username = tmp; bytesLeft -= length; index += length; length = msg.get(index); bytesLeft -= 1; if (bytesLeft < length) { return ZError.EPROTO; } tmp = new byte[length]; index += 1; msg.getBytes(index, tmp, 0, length); byte[] password = tmp; bytesLeft -= length; // index += length; if (bytesLeft > 0) { return ZError.EPROTO; } // Use ZAP protocol (RFC 27) to authenticate the user. int rc = session.zapConnect(); if (rc == 0) { sendZapRequest(username, password); rc = receiveAndProcessZapReply(); if (rc == 0) { state = "200".equals(statusCode) ? State.SENDING_WELCOME : State.SENDING_ERROR; } else if (rc == ZError.EAGAIN) { state = State.WAITING_FOR_ZAP_REPLY; } else { return -1; } } else { state = State.SENDING_WELCOME; } return 0;
1,264
505
1,769
<methods>public zmq.Msg decode(zmq.Msg) ,public void destroy() ,public zmq.Msg encode(zmq.Msg) ,public final zmq.util.Blob getUserId() ,public abstract int nextHandshakeCommand(zmq.Msg) ,public final zmq.Msg peerIdentity() ,public abstract int processHandshakeCommand(zmq.Msg) ,public abstract zmq.io.mechanism.Mechanism.Status status() ,public abstract int zapMsgAvailable() <variables>private zmq.util.Blob identity,protected final non-sealed zmq.Options options,private final non-sealed zmq.io.net.Address peerAddress,protected final non-sealed zmq.io.SessionBase session,protected java.lang.String statusCode,private zmq.util.Blob userId,public final zmq.io.Metadata zapProperties,public final zmq.io.Metadata zmtpProperties
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/io/net/Address.java
Address
toString
class Address { public interface IZAddress { ProtocolFamily family(); String toString(int port); InetSocketAddress resolve(String name, boolean ipv6, boolean local); SocketAddress address(); SocketAddress sourceAddress(); } private final NetProtocol protocol; private final String address; private IZAddress resolved; /** * @param protocol * @param address * @throws IllegalArgumentException if the protocol name can be matched to an actual supported protocol */ @Deprecated public Address(final String protocol, final String address) { this.protocol = NetProtocol.getProtocol(protocol); this.address = address; resolved = null; } /** * @param protocol * @param address */ public Address(final NetProtocol protocol, final String address) { this.protocol = protocol; this.address = address; resolved = null; } /** * @param socketAddress * @throws IllegalArgumentException if the SocketChannel is not an IP socket address */ public Address(SocketAddress socketAddress) { protocol = NetProtocol.findByAddress(socketAddress); address = protocol.formatSocketAddress(socketAddress); resolved = null; } @Override public String toString() {<FILL_FUNCTION_BODY>} public NetProtocol protocol() { return protocol; } public String address() { return address; } public String host() { final int portDelimiter = address.lastIndexOf(':'); if (portDelimiter > 0) { return address.substring(0, portDelimiter); } return address; } public IZAddress resolved() { return resolved; } public boolean isResolved() { return resolved != null; } public IZAddress resolve(boolean ipv6) { resolved = protocol.zresolve(address, ipv6); return resolved; } }
if (isResolved()) { return resolved.toString(); } else if (protocol != null && !address.isEmpty()) { return protocol.name() + "://" + address; } else { return ""; }
544
66
610
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/io/net/ipc/IpcAddress.java
IpcAddressMask
resolve
class IpcAddressMask extends TcpAddress { public IpcAddressMask(String addr, boolean ipv6) { super(addr, ipv6); } public boolean matchAddress(SocketAddress addr) { return address().equals(addr); } } private String name; private final InetSocketAddress address; private final SocketAddress sourceAddress; public IpcAddress(String addr) { String[] strings = addr.split(";"); address = resolve(strings[0], ZMQ.PREFER_IPV6, true); if (strings.length == 2 && !"".equals(strings[1])) { sourceAddress = resolve(strings[1], ZMQ.PREFER_IPV6, true); } else { sourceAddress = null; } } @Override public String toString() { if (name == null) { return ""; } return "ipc://" + name; } @Override public String toString(int port) { if ("*".equals(name)) { String suffix = Utils.unhash(port - 10000); return "ipc://" + suffix; } return toString(); } @Override public InetSocketAddress resolve(String name, boolean ipv6, boolean loopback) {<FILL_FUNCTION_BODY>
this.name = name; int hash = name.hashCode(); if ("*".equals(name)) { hash = 0; } else { if (hash < 0) { hash = -hash; } hash = hash % 55536; hash += 10000; } return new InetSocketAddress(findAddress(ipv6, loopback), hash);
378
113
491
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/io/net/ipc/IpcListener.java
IpcListener
setAddress
class IpcListener extends TcpListener { private IpcAddress address; public IpcListener(IOThread ioThread, SocketBase socket, final Options options) { super(ioThread, socket, options); } // Get the bound address for use with wildcards @Override public String getAddress() { if (((InetSocketAddress) address.address()).getPort() == 0) { return address(address); } return address.toString(); } // Set address to listen on. @Override public boolean setAddress(String addr) {<FILL_FUNCTION_BODY>} }
address = new IpcAddress(addr); InetSocketAddress sock = (InetSocketAddress) address.address(); return super.setAddress(sock);
170
45
215
<methods>public void <init>(zmq.io.IOThread, zmq.SocketBase, zmq.Options) ,public void acceptEvent() ,public void destroy() ,public java.lang.String getAddress() ,public boolean setAddress(java.lang.String) ,public java.lang.String toString() <variables>private zmq.io.net.tcp.TcpAddress address,private java.lang.String endpoint,private java.nio.channels.ServerSocketChannel fd,private zmq.poll.Poller.Handle handle,private final non-sealed zmq.io.IOObject ioObject,private static final non-sealed boolean isWindows
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/io/net/ipc/IpcNetworkProtocolProvider.java
IpcNetworkProtocolProvider
startConnecting
class IpcNetworkProtocolProvider implements NetworkProtocolProvider { @Override public boolean handleProtocol(NetProtocol protocol) { return protocol == NetProtocol.ipc; } @Override public Listener getListener(IOThread ioThread, SocketBase socket, Options options) { return new IpcListener(ioThread, socket, options); } @Override public IZAddress zresolve(String addr, boolean ipv6) { return new IpcAddress(addr); } @Override public void startConnecting(Options options, IOThread ioThread, SessionBase session, Address addr, boolean delayedStart, Consumer<Own> launchChild, BiConsumer<SessionBase, IEngine> sendAttach) {<FILL_FUNCTION_BODY>} @Override public boolean isValid() { return true; } @Override public boolean wantsIOThread() { return true; } }
IpcConnecter connecter = new IpcConnecter(ioThread, session, options, addr, delayedStart); launchChild.accept(connecter);
255
40
295
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/io/net/norm/NormNetworkProtocolProvider.java
NormNetworkProtocolProvider
startConnecting
class NormNetworkProtocolProvider implements NetworkProtocolProvider { @Override public boolean handleProtocol(NetProtocol protocol) { // TODO Auto-generated method stub return false; } @Override public Listener getListener(IOThread ioThread, SocketBase socket, Options options) { // TODO Auto-generated method stub return null; } @Override public IZAddress zresolve(String addr, boolean ipv6) { // TODO Auto-generated method stub return null; } @Override public void startConnecting(Options options, IOThread ioThread, SessionBase session, Address addr, boolean delayedStart, Consumer<Own> launchChild, BiConsumer<SessionBase, IEngine> sendAttach) {<FILL_FUNCTION_BODY>} @Override public boolean wantsIOThread() { return false; } }
// At this point we'll create message pipes to the session straight // away. There's no point in delaying it as no concept of 'connect' // exists with NORM anyway. if (options.type == ZMQ.ZMQ_PUB || options.type == ZMQ.ZMQ_XPUB) { // NORM sender. NormEngine normSender = new NormEngine(ioThread, options); boolean rc = normSender.init(addr, true, false); assert (rc); sendAttach.accept(session, normSender); } else { // NORM receiver. NormEngine normReceiver = new NormEngine(ioThread, options); boolean rc = normReceiver.init(addr, false, true); assert (rc); sendAttach.accept(session, normReceiver); }
239
224
463
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/io/net/pgm/PgmNetworkProtocolProvider.java
PgmNetworkProtocolProvider
startConnecting
class PgmNetworkProtocolProvider implements NetworkProtocolProvider { @Override public boolean handleProtocol(NetProtocol protocol) { return protocol == NetProtocol.pgm; } @Override public Listener getListener(IOThread ioThread, SocketBase socket, Options options) { return null; } @Override public IZAddress zresolve(String addr, boolean ipv6) { return null; } @Override public void startConnecting(Options options, IOThread ioThread, SessionBase session, Address addr, boolean delayedStart, Consumer<Own> launchChild, BiConsumer<SessionBase, IEngine> sendAttach) {<FILL_FUNCTION_BODY>} protected boolean withUdpEncapsulation() { return false; } @Override public boolean wantsIOThread() { return false; } }
assert (options.type == ZMQ.ZMQ_PUB || options.type == ZMQ.ZMQ_XPUB || options.type == ZMQ.ZMQ_SUB || options.type == ZMQ.ZMQ_XSUB); // For EPGM transport with UDP encapsulation of PGM is used. boolean udpEncapsulation = withUdpEncapsulation(); // At this point we'll create message pipes to the session straight // away. There's no point in delaying it as no concept of 'connect' // exists with PGM anyway. if (options.type == ZMQ.ZMQ_PUB || options.type == ZMQ.ZMQ_XPUB) { // PGM sender. PgmSender pgmSender = new PgmSender(ioThread, options); boolean rc = pgmSender.init(udpEncapsulation, addr); assert (rc); sendAttach.accept(session, pgmSender); } else { // PGM receiver. PgmReceiver pgmReceiver = new PgmReceiver(ioThread, options); boolean rc = pgmReceiver.init(udpEncapsulation, addr); assert (rc); sendAttach.accept(session, pgmReceiver); }
241
352
593
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/io/net/tcp/SocksConnecter.java
SocksConnecter
processTerm
class SocksConnecter extends TcpConnecter { private enum Status { UNPLUGGED, WAITING_FOR_RECONNECT_TIME, WAITING_FOR_PROXY_CONNECTION, SENDING_GREETING, WAITING_FOR_CHOICE, SENDING_REQUEST, WAITING_FOR_RESPONSE } Status status; // String representation of endpoint to connect to String endpoint; public SocksConnecter(IOThread ioThread, SessionBase session, final Options options, final Address addr, final Address proxyAddr, boolean delayedStart) { super(ioThread, session, options, addr, delayedStart); assert (NetProtocol.tcp.equals(addr.protocol())); endpoint = proxyAddr.toString(); this.status = Status.UNPLUGGED; throw new UnsupportedOperationException("Socks connecter is not implemented"); } @Override protected void processPlug() { if (delayedStart) { startTimer(); } else { initiateConnect(); } } @Override protected void processTerm(int linger) {<FILL_FUNCTION_BODY>} @Override public void inEvent() { assert (status != Status.UNPLUGGED && status != Status.WAITING_FOR_RECONNECT_TIME); super.inEvent(); } @Override public void outEvent() { super.outEvent(); } @Override public void timerEvent(int id) { super.timerEvent(id); } // Internal function to start the actual connection establishment. void initiateConnect() { } int processServerResponse() { return -1; } void parseAddress(String address, String hostname, int port) { } void connectToProxy() { } void error() { } // Internal function to start reconnect timer void startTimer() { } // Internal function to return a reconnect backoff delay. // Will modify the current_reconnect_ivl used for next call // Returns the currently used interval int getNewReconnectIvl() { return -1; } // Open TCP connecting socket. Returns -1 in case of error, // 0 if connect was successfull immediately. Returns -1 with // EAGAIN errno if async connect was launched. int open() { return -1; } // Get the file descriptor of newly created connection. Returns // retired_fd if the connection was unsuccessfull. void checkProxyConnection() { } }
switch (status) { case UNPLUGGED: break; case WAITING_FOR_RECONNECT_TIME: ioObject.cancelTimer(RECONNECT_TIMER_ID); break; case WAITING_FOR_PROXY_CONNECTION: case SENDING_GREETING: case WAITING_FOR_CHOICE: case SENDING_REQUEST: case WAITING_FOR_RESPONSE: close(); break; default: break; } super.processTerm(linger);
732
156
888
<methods>public void <init>(zmq.io.IOThread, zmq.io.SessionBase, zmq.Options, zmq.io.net.Address, boolean) ,public void connectEvent() ,public void inEvent() ,public void outEvent() ,public void timerEvent(int) ,public java.lang.String toString() <variables>protected static final int RECONNECT_TIMER_ID,private final non-sealed zmq.io.net.Address addr,private int currentReconnectIvl,protected final non-sealed boolean delayedStart,private java.nio.channels.SocketChannel fd,private zmq.poll.Poller.Handle handle,protected final non-sealed zmq.io.IOObject ioObject,private final non-sealed zmq.io.SessionBase session,private final non-sealed zmq.SocketBase socket,private boolean timerStarted
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/io/net/tcp/TcpAddress.java
TcpAddressMask
resolve
class TcpAddressMask extends TcpAddress { public TcpAddressMask(String addr, boolean ipv6) { super(addr, ipv6); } public boolean matchAddress(SocketAddress addr) { return address().equals(addr); } } private final InetSocketAddress address; private final SocketAddress sourceAddress; public TcpAddress(String addr, boolean ipv6) { String[] strings = addr.split(";"); address = resolve(strings[0], ipv6, false); if (strings.length == 2 && !"".equals(strings[1])) { sourceAddress = resolve(strings[1], ipv6, false); } else { sourceAddress = null; } } protected TcpAddress(InetSocketAddress address) { this.address = address; sourceAddress = null; } @Override public ProtocolFamily family() { if (address.getAddress() instanceof Inet6Address) { return StandardProtocolFamily.INET6; } else { return StandardProtocolFamily.INET; } } // The opposite to resolve() @Override public String toString() { return toString(address.getPort()); } // The opposite to resolve() @Override public String toString(int port) { if (address == null) { return ""; } int addressPort = address.getPort(); if (addressPort == 0) { addressPort = port; } if (address.getAddress() instanceof Inet6Address) { return "tcp://[" + address.getAddress().getHostAddress() + "]:" + addressPort; } else { return "tcp://" + address.getAddress().getHostAddress() + ":" + addressPort; } } /** * @param name * @param ipv6 * @param local ignored * @return the resolved address * @see zmq.io.net.Address.IZAddress#resolve(java.lang.String, boolean, boolean) */ @Override public InetSocketAddress resolve(String name, boolean ipv6, boolean local) {<FILL_FUNCTION_BODY>
// Find the ':' at end that separates address from the port number. int delimiter = name.lastIndexOf(':'); if (delimiter < 0) { throw new IllegalArgumentException(name); } // Separate the address/port. String addrStr = name.substring(0, delimiter); String portStr = name.substring(delimiter + 1); // Remove square brackets around the address, if any. if (addrStr.length() >= 2 && addrStr.charAt(0) == '[' && addrStr.charAt(addrStr.length() - 1) == ']') { addrStr = addrStr.substring(1, addrStr.length() - 1); } int port; // Allow 0 specifically, to detect invalid port error in atoi if not if (portStr.equals("*") || portStr.equals("0")) { // Resolve wildcard to 0 to allow autoselection of port port = 0; } else { // Parse the port number (0 is not a valid port). port = Integer.parseInt(portStr); if (port == 0) { throw new IllegalArgumentException(name); } } InetAddress addrNet = null; // '*' as unspecified address is not accepted in Java // '::' for IPv6 is accepted if (addrStr.equals("*")) { addrStr = ipv6 ? "::" : "0.0.0.0"; } try { InetAddress[] addresses = InetAddress.getAllByName(addrStr); if (ipv6) { // prefer IPv6: return the first ipv6 or the first value if not found for (InetAddress addr : addresses) { if (addr instanceof Inet6Address) { addrNet = addr; break; } } if (addrNet == null) { addrNet = addresses[0]; } } else { for (InetAddress addr : addresses) { if (addr instanceof Inet4Address) { addrNet = addr; break; } } } } catch (UnknownHostException e) { throw new ZMQException(e.getMessage(), ZError.EADDRNOTAVAIL, e); } if (addrNet == null) { throw new ZMQException(addrStr + " not found matching IPv4/IPv6 settings", ZError.EADDRNOTAVAIL); } return new InetSocketAddress(addrNet, port);
596
672
1,268
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/io/net/tcp/TcpNetworkProtocolProvider.java
TcpNetworkProtocolProvider
formatSocketAddress
class TcpNetworkProtocolProvider implements NetworkProtocolProvider { @Override public boolean handleProtocol(NetProtocol protocol) { return protocol == NetProtocol.tcp; } @Override public Listener getListener(IOThread ioThread, SocketBase socket, Options options) { return new TcpListener(ioThread, socket, options); } @Override public IZAddress zresolve(String addr, boolean ipv6) { return new TcpAddress(addr, ipv6); } @Override public void startConnecting(Options options, IOThread ioThread, SessionBase session, Address addr, boolean delayedStart, Consumer<Own> launchChild, BiConsumer<SessionBase, IEngine> sendAttach) { if (options.socksProxyAddress != null) { Address proxyAddress = new Address(NetProtocol.tcp, options.socksProxyAddress); SocksConnecter connecter = new SocksConnecter(ioThread, session, options, addr, proxyAddress, delayedStart); launchChild.accept(connecter); } else { TcpConnecter connecter = new TcpConnecter(ioThread, session, options, addr, delayedStart); launchChild.accept(connecter); } } @Override public boolean isValid() { return true; } @Override public boolean handleAdress(SocketAddress socketAddress) { return socketAddress instanceof InetSocketAddress; } @Override public String formatSocketAddress(SocketAddress socketAddress) {<FILL_FUNCTION_BODY>} @Override public boolean wantsIOThread() { return true; } }
InetSocketAddress isa = (InetSocketAddress) socketAddress; return isa.getAddress().getHostAddress() + ":" + isa.getPort();
440
44
484
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/io/net/tcp/TcpUtils.java
TcpUtils
tuneTcpKeepalives
class TcpUtils { private TcpUtils() { } // The explicit IOException is useless, but kept for API compatibility public static void tuneTcpSocket(Channel channel) throws IOException { // Disable Nagle's algorithm. We are doing data batching on 0MQ level, // so using Nagle wouldn't improve throughput in any way, but it would // hurt latency. setOption(channel, StandardSocketOptions.TCP_NODELAY, true); } public static void tuneTcpKeepalives(Channel channel, int tcpKeepAlive, int tcpKeepAliveCnt, int tcpKeepAliveIdle, int tcpKeepAliveIntvl) {<FILL_FUNCTION_BODY>} public static boolean setTcpReceiveBuffer(Channel channel, final int rcvbuf) { setOption(channel, StandardSocketOptions.SO_RCVBUF, rcvbuf); return true; } public static boolean setTcpSendBuffer(Channel channel, final int sndbuf) { setOption(channel, StandardSocketOptions.SO_SNDBUF, sndbuf); return true; } public static boolean setIpTypeOfService(Channel channel, final int tos) { setOption(channel, StandardSocketOptions.IP_TOS, tos); return true; } public static boolean setReuseAddress(Channel channel, final boolean reuse) { setOption(channel, StandardSocketOptions.SO_REUSEADDR, reuse); return true; } private static <T> void setOption(Channel channel, SocketOption<T> option, T value) { try { if (channel instanceof NetworkChannel) { ((NetworkChannel) channel).setOption(option, value); } else { throw new IllegalArgumentException("Channel " + channel + " is not a network channel"); } } catch (IOException e) { throw new ZError.IOException(e); } } public static void unblockSocket(SelectableChannel... channels) throws IOException { for (SelectableChannel ch : channels) { ch.configureBlocking(false); } } public static void enableIpv4Mapping(SelectableChannel channel) { // TODO V4 enable ipv4 mapping } /** * Return the {@link Address} of the channel * @param channel the channel, should be a TCP socket channel * @return The {@link Address} of the channel * @deprecated Use {@link zmq.util.Utils#getPeerIpAddress(SocketChannel)} instead * @throws ZError.IOException if the channel is closed or an I/O errors occurred * @throws IllegalArgumentException if the SocketChannel is not a TCP channel */ @Deprecated public static Address getPeerIpAddress(SocketChannel channel) { return Utils.getPeerIpAddress(channel); } }
if (tcpKeepAlive != -1) { if (channel instanceof SocketChannel) { setOption(channel, StandardSocketOptions.SO_KEEPALIVE, tcpKeepAlive == 1); } if (tcpKeepAlive == 1) { if (tcpKeepAliveCnt > 0) { setOption(channel, ExtendedSocketOptions.TCP_KEEPCOUNT, tcpKeepAliveCnt); } if (tcpKeepAliveIdle > 0) { setOption(channel, ExtendedSocketOptions.TCP_KEEPIDLE, tcpKeepAliveIdle); } if (tcpKeepAliveIntvl > 0) { setOption(channel, ExtendedSocketOptions.TCP_KEEPINTERVAL, tcpKeepAliveIntvl); } } }
758
215
973
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/io/net/tipc/TipcNetworkProtocolProvider.java
TipcNetworkProtocolProvider
startConnecting
class TipcNetworkProtocolProvider implements NetworkProtocolProvider { @Override public boolean handleProtocol(NetProtocol protocol) { // TODO Auto-generated method stub return false; } @Override public Listener getListener(IOThread ioThread, SocketBase socket, Options options) { return new TipcListener(ioThread, socket, options); } @Override public IZAddress zresolve(String addr, boolean ipv6) { // TODO Auto-generated method stub return null; } @Override public void startConnecting(Options options, IOThread ioThread, SessionBase session, Address addr, boolean delayedStart, Consumer<Own> launchChild, BiConsumer<SessionBase, IEngine> sendAttach) {<FILL_FUNCTION_BODY>} @Override public boolean wantsIOThread() { return true; } }
TipcConnecter connecter = new TipcConnecter(ioThread, session, options, addr, delayedStart); launchChild.accept(connecter);
239
40
279
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/msg/MsgAllocatorThreshold.java
MsgAllocatorThreshold
allocate
class MsgAllocatorThreshold implements MsgAllocator { private static final MsgAllocator direct = new MsgAllocatorDirect(); private static final MsgAllocator heap = new MsgAllocatorHeap(); public final int threshold; public MsgAllocatorThreshold() { this(Config.MSG_ALLOCATION_HEAP_THRESHOLD.getValue()); } public MsgAllocatorThreshold(int threshold) { this.threshold = threshold; } @Override public Msg allocate(int size) {<FILL_FUNCTION_BODY>} }
if (threshold > 0 && size > threshold) { return direct.allocate(size); } else { return heap.allocate(size); }
162
47
209
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/pipe/DBuffer.java
DBuffer
read
class DBuffer<T extends Msg> { private T back; private T front; private final Lock sync = new ReentrantLock(); private boolean hasMsg; public T back() { return back; } public T front() { return front; } void write(T msg) { assert (msg.check()); sync.lock(); try { back = front; front = msg; hasMsg = true; } finally { sync.unlock(); } } T read() {<FILL_FUNCTION_BODY>} boolean checkRead() { sync.lock(); try { return hasMsg; } finally { sync.unlock(); } } T probe() { sync.lock(); try { return front; } finally { sync.unlock(); } } }
sync.lock(); try { if (!hasMsg) { return null; } assert (front.check()); // TODO front->init (); // avoid double free hasMsg = false; return front; } finally { sync.unlock(); }
261
82
343
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/pipe/YPipe.java
YPipe
write
class YPipe<T> implements YPipeBase<T> { // Allocation-efficient queue to store pipe items. // Front of the queue points to the first prefetched item, back of // the pipe points to last un-flushed item. Front is used only by // reader thread, while back is used only by writer thread. private final YQueue<T> queue; // Points to the first un-flushed item. This variable is used // exclusively by writer thread. private int w; // Points to the first un-prefetched item. This variable is used // exclusively by reader thread. private int r; // Points to the first item to be flushed in the future. private int f; // The single point of contention between writer and reader thread. // Points past the last flushed item. If it is NULL, // reader is asleep. This pointer should be always accessed using // atomic operations. private final AtomicInteger c; public YPipe(int qsize) { queue = new YQueue<>(qsize); int pos = queue.backPos(); f = pos; r = pos; w = pos; c = new AtomicInteger(pos); } // Write an item to the pipe. Don't flush it yet. If incomplete is // set to true the item is assumed to be continued by items // subsequently written to the pipe. Incomplete items are never // flushed down the stream. @Override public void write(final T value, boolean incomplete) {<FILL_FUNCTION_BODY>} // Pop an incomplete item from the pipe. Returns true is such // item exists, false otherwise. @Override public T unwrite() { if (f == queue.backPos()) { return null; } queue.unpush(); return queue.back(); } // Flush all the completed items into the pipe. Returns false if // the reader thread is sleeping. In that case, caller is obliged to // wake the reader up before using the pipe again. @Override public boolean flush() { // If there are no un-flushed items, do nothing. if (w == f) { return true; } // Try to set 'c' to 'f'. if (!c.compareAndSet(w, f)) { // Compare-and-swap was unsuccessful because 'c' is NULL. // This means that the reader is asleep. Therefore we don't // care about thread-safeness and update c in non-atomic // manner. We'll return false to let the caller know // that reader is sleeping. c.set(f); w = f; return false; } // Reader is alive. Nothing special to do now. Just move // the 'first un-flushed item' pointer to 'f'. w = f; return true; } // Check whether item is available for reading. @Override public boolean checkRead() { // Was the value prefetched already? If so, return. int h = queue.frontPos(); if (h != r && r != -1) { return true; } // There's no prefetched value, so let us prefetch more values. // Prefetching is to simply retrieve the // pointer from c in atomic fashion. If there are no // items to prefetch, set c to -1 (using compare-and-swap). if (c.compareAndSet(h, -1)) { // nothing to read, h == r must be the same } else { // something to have been written r = c.get(); } // If there are no elements prefetched, exit. // During pipe's lifetime r should never be NULL, however, // it can happen during pipe shutdown when items // are being deallocated. return h != r && r != -1; // There was at least one value prefetched. } // Reads an item from the pipe. Returns null if there is no value. // available. @Override public T read() { // Try to prefetch a value. if (!checkRead()) { return null; } // There was at least one value prefetched. // Return it to the caller. return queue.pop(); } // Returns the first element in the pipe without removing it. // The pipe mustn't be empty or the function crashes. @Override public T probe() { boolean rc = checkRead(); assert (rc); return queue.front(); } }
// Place the value to the queue, add new terminator element. queue.push(value); // Move the "flush up to here" pointer. if (!incomplete) { f = queue.backPos(); }
1,253
63
1,316
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/pipe/YPipeConflate.java
YPipeConflate
read
class YPipeConflate<T extends Msg> implements YPipeBase<T> { private boolean readerAwake; private final DBuffer<T> dbuffer = new DBuffer<>(); // Following function (write) deliberately copies uninitialised data // when used with zmq_msg. Initialising the VSM body for // non-VSM messages won't be good for performance. @Override public void write(final T value, boolean incomplete) { dbuffer.write(value); } // There are no incomplete items for conflate ypipe @Override public T unwrite() { return null; } // Flush is no-op for conflate ypipe. Reader asleep behaviour // is as of the usual ypipe. // Returns false if the reader thread is sleeping. In that case, // caller is obliged to wake the reader up before using the pipe again. @Override public boolean flush() { return readerAwake; } // Check whether item is available for reading. @Override public boolean checkRead() { boolean rc = dbuffer.checkRead(); if (!rc) { readerAwake = false; } return rc; } // Reads an item from the pipe. Returns false if there is no value. // available. @Override public T read() {<FILL_FUNCTION_BODY>} // Applies the function fn to the first elemenent in the pipe // and returns the value returned by the fn. // The pipe mustn't be empty or the function crashes. @Override public T probe() { return dbuffer.probe(); } }
// Try to prefetch a value. if (!checkRead()) { return null; } // There was at least one value prefetched. // Return it to the caller. return dbuffer.read();
459
65
524
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/pipe/YQueue.java
Chunk
push
class Chunk<T> { final T[] values; final int[] pos; Chunk<T> prev; Chunk<T> next; @SuppressWarnings("unchecked") public Chunk(int size, int memoryPtr) { values = (T[]) new Object[size]; pos = new int[size]; for (int i = 0; i != values.length; i++) { pos[i] = memoryPtr; memoryPtr++; } } } // Back position may point to invalid memory if the queue is empty, // while begin & end positions are always valid. Begin position is // accessed exclusively be queue reader (front/pop), while back and // end positions are accessed exclusively by queue writer (back/push). private Chunk<T> beginChunk; private int beginPos; private Chunk<T> backChunk; private int backPos; private Chunk<T> endChunk; private int endPos; private volatile Chunk<T> spareChunk; private final int size; // People are likely to produce and consume at similar rates. In // this scenario holding onto the most recently freed chunk saves // us from having to call malloc/free. private int memoryPtr; public YQueue(int size) { this.size = size; memoryPtr = 0; beginChunk = new Chunk<>(size, memoryPtr); memoryPtr += size; beginPos = 0; backPos = 0; backChunk = beginChunk; spareChunk = beginChunk; endChunk = beginChunk; endPos = 1; } public int frontPos() { return beginChunk.pos[beginPos]; } // Returns reference to the front element of the queue. // If the queue is empty, behaviour is undefined. public T front() { return beginChunk.values[beginPos]; } public int backPos() { return backChunk.pos[backPos]; } // Returns reference to the back element of the queue. // If the queue is empty, behaviour is undefined. public T back() { return backChunk.values[backPos]; } // Adds an element to the back end of the queue. public void push(T val) {<FILL_FUNCTION_BODY>
backChunk.values[backPos] = val; backChunk = endChunk; backPos = endPos; if (++endPos != size) { return; } Chunk<T> sc = spareChunk; if (sc != beginChunk) { spareChunk = spareChunk.next; endChunk.next = sc; sc.prev = endChunk; } else { endChunk.next = new Chunk<>(size, memoryPtr); memoryPtr += size; endChunk.next.prev = endChunk; } endChunk = endChunk.next; endPos = 0;
649
181
830
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/poll/PollItem.java
PollItem
getChannel
class PollItem { private final SocketBase socket; private final SelectableChannel channel; private final int zinterest; private final int interest; private int ready; public PollItem(SocketBase socket, int ops) { this(socket, null, ops); } public PollItem(SelectableChannel channel, int ops) { this(null, channel, ops); } private PollItem(SocketBase socket, SelectableChannel channel, int ops) { this.socket = socket; this.channel = channel; this.zinterest = ops; this.interest = init(ops); } private int init(int ops) { int interest = 0; if ((ops & ZMQ.ZMQ_POLLIN) > 0) { interest |= SelectionKey.OP_READ; } if ((ops & ZMQ.ZMQ_POLLOUT) > 0) { if (socket != null) { // ZMQ Socket get readiness from the mailbox interest |= SelectionKey.OP_READ; } else { interest |= SelectionKey.OP_WRITE; } } this.ready = 0; return interest; } public boolean isReadable() { return (ready & ZMQ.ZMQ_POLLIN) > 0; } public boolean isWritable() { return (ready & ZMQ.ZMQ_POLLOUT) > 0; } public boolean isError() { return (ready & ZMQ.ZMQ_POLLERR) > 0; } public SocketBase getSocket() { return socket; } public SelectableChannel getRawSocket() { return channel; } public SelectableChannel getChannel() {<FILL_FUNCTION_BODY>} public int interestOps() { return interest; } public int zinterestOps() { return zinterest; } public boolean hasEvent(int events) { return (zinterest & events) > 0; } public int interestOps(int ops) { init(ops); return interest; } public int readyOps(SelectionKey key, int nevents) { ready = 0; if (socket != null) { // The poll item is a 0MQ socket. Retrieve pending events // using the ZMQ_EVENTS socket option. int events = socket.getSocketOpt(ZMQ.ZMQ_EVENTS); if (events < 0) { return -1; } if ((zinterest & ZMQ.ZMQ_POLLOUT) > 0 && (events & ZMQ.ZMQ_POLLOUT) > 0) { ready |= ZMQ.ZMQ_POLLOUT; } if ((zinterest & ZMQ.ZMQ_POLLIN) > 0 && (events & ZMQ.ZMQ_POLLIN) > 0) { ready |= ZMQ.ZMQ_POLLIN; } } // Else, the poll item is a raw file descriptor, simply convert // the events to zmq_pollitem_t-style format. else if (nevents > 0) { if (key.isReadable()) { ready |= ZMQ.ZMQ_POLLIN; } if (key.isWritable()) { ready |= ZMQ.ZMQ_POLLOUT; } if (!key.isValid() || key.isAcceptable() || key.isConnectable()) { ready |= ZMQ.ZMQ_POLLERR; } } return ready; } public int readyOps() { return ready; } }
if (socket != null) { // If the poll item is a 0MQ socket we are interested in input on the // notification file descriptor retrieved by the ZMQ_FD socket option. return socket.getFD(); } else { // Else, the poll item is a raw file descriptor. Convert the poll item // events to the appropriate fd_sets. return channel; }
1,038
110
1,148
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/poll/Poller.java
Handle
hashCode
class Handle { private final SelectableChannel fd; private final IPollEvents handler; private int ops; private boolean cancelled; public Handle(SelectableChannel fd, IPollEvents handler) { assert (fd != null); assert (handler != null); this.fd = fd; this.handler = handler; } @Override public int hashCode() {<FILL_FUNCTION_BODY>} @Override public boolean equals(Object other) { if (this == other) { return true; } if (other == null) { return false; } if (!(other instanceof Handle)) { return false; } Handle that = (Handle) other; return this.fd.equals(that.fd) && this.handler.equals(that.handler); } @Override public String toString() { return "Handle-" + fd; } }
final int prime = 31; int result = 1; result = prime * result + fd.hashCode(); result = prime * result + handler.hashCode(); return result;
264
51
315
<methods>public void addTimer(long, zmq.poll.IPollEvents, int) ,public void cancelTimer(zmq.poll.IPollEvents, int) ,public final int getLoad() <variables>private boolean changed,private final java.util.concurrent.atomic.AtomicInteger load,private final MultiMap<java.lang.Long,zmq.poll.PollerBase.TimerInfo> timers,protected final non-sealed java.lang.Thread worker
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/poll/PollerBase.java
TimerInfo
toString
class TimerInfo { private final IPollEvents sink; private final int id; private boolean cancelled; public TimerInfo(IPollEvents sink, int id) { assert (sink != null); this.sink = sink; this.id = id; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + id; result = prime * result + sink.hashCode(); return result; } @Override public boolean equals(Object other) { if (this == other) { return true; } if (other == null) { return false; } if (!(other instanceof TimerInfo)) { return false; } TimerInfo that = (TimerInfo) other; return this.id == that.id && this.sink.equals(that.sink); } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "TimerInfo [id=" + id + ", sink=" + sink + "]";
284
26
310
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/socket/Channel.java
Channel
xsend
class Channel extends SocketBase { private Pipe pipe; private Pipe lastIn; private Blob savedCredential; public Channel(Ctx parent, int tid, int sid) { super(parent, tid, sid, true); options.type = ZMQ.ZMQ_CHANNEL; } @Override protected void destroy() { super.destroy(); assert (pipe == null); } @Override protected void xattachPipe(Pipe pipe, boolean subscribe2all, boolean isLocallyInitiated) { assert (pipe != null); // ZMQ_PAIR socket can only be connected to a single peer. // The socket rejects any further connection requests. if (this.pipe == null) { this.pipe = pipe; } else { pipe.terminate(false); } } @Override protected void xpipeTerminated(Pipe pipe) { if (this.pipe == pipe) { if (lastIn == pipe) { savedCredential = lastIn.getCredential(); lastIn = null; } this.pipe = null; } } @Override protected void xreadActivated(Pipe pipe) { // There's just one pipe. No lists of active and inactive pipes. // There's nothing to do here. } @Override protected void xwriteActivated(Pipe pipe) { // There's just one pipe. No lists of active and inactive pipes. // There's nothing to do here. } @Override protected boolean xsend(Msg msg) {<FILL_FUNCTION_BODY>} @Override protected Msg xrecv() { if (pipe == null) { // Initialize the output parameter to be a 0-byte message. errno.set(ZError.EAGAIN); return null; } // Drop any messages with more flag Msg msg = pipe.read(); while (msg != null && msg.hasMore()) { // drop all frames of the current multi-frame message msg = pipe.read(); while (msg != null && msg.hasMore()) { msg = pipe.read(); } // get the new message if (msg != null) { msg = pipe.read(); } } if (msg == null) { errno.set(ZError.EAGAIN); return null; } lastIn = pipe; return msg; } @Override protected boolean xhasIn() { return pipe != null && pipe.checkRead(); } @Override protected boolean xhasOut() { return pipe != null && pipe.checkWrite(); } @Override protected Blob getCredential() { return lastIn != null ? lastIn.getCredential() : savedCredential; } }
// CHANNEL sockets do not allow multipart data (ZMQ_SNDMORE) if (msg.hasMore()) { errno.set(ZError.EINVAL); return false; } if (pipe == null || !pipe.write(msg)) { errno.set(ZError.EAGAIN); return false; } pipe.flush(); return true;
797
113
910
<methods>public final boolean bind(java.lang.String) ,public final void cancel(java.util.concurrent.atomic.AtomicBoolean) ,public final void close() ,public final boolean connect(java.lang.String) ,public final int connectPeer(java.lang.String) ,public boolean disconnectPeer(int) ,public final int errno() ,public final void eventAcceptFailed(java.lang.String, int) ,public final void eventAccepted(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventBindFailed(java.lang.String, int) ,public final void eventCloseFailed(java.lang.String, int) ,public final void eventClosed(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventConnectDelayed(java.lang.String, int) ,public final void eventConnectRetried(java.lang.String, int) ,public final void eventConnected(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventDisconnected(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventHandshakeFailedAuth(java.lang.String, int) ,public final void eventHandshakeFailedNoDetail(java.lang.String, int) ,public final void eventHandshakeFailedProtocol(java.lang.String, int) ,public final void eventHandshakeSucceeded(java.lang.String, int) ,public final void eventHandshaken(java.lang.String, int) ,public final void eventListening(java.lang.String, java.nio.channels.SelectableChannel) ,public final java.nio.channels.SelectableChannel getFD() ,public final int getSocketOpt(int) ,public final java.lang.Object getSocketOptx(int) ,public final void hiccuped(zmq.pipe.Pipe) ,public final void inEvent() ,public final boolean join(java.lang.String) ,public final boolean leave(java.lang.String) ,public final boolean monitor(java.lang.String, int) ,public final void pipeTerminated(zmq.pipe.Pipe) ,public final int poll(int, int, java.util.concurrent.atomic.AtomicBoolean) ,public final void readActivated(zmq.pipe.Pipe) ,public final zmq.Msg recv(int) ,public final zmq.Msg recv(int, java.util.concurrent.atomic.AtomicBoolean) ,public final boolean send(zmq.Msg, int) ,public final boolean send(zmq.Msg, int, java.util.concurrent.atomic.AtomicBoolean) ,public final boolean setEventHook(zmq.ZMQ.EventConsummer, int) ,public final boolean setSocketOpt(int, java.lang.Object) ,public final boolean termEndpoint(java.lang.String) ,public java.lang.String toString() ,public java.lang.String typeString() ,public final void writeActivated(zmq.pipe.Pipe) <variables>private boolean active,protected java.lang.String connectRid,private final non-sealed java.util.concurrent.atomic.AtomicBoolean ctxTerminated,private final non-sealed java.util.concurrent.atomic.AtomicBoolean destroyed,private final non-sealed MultiMap<java.lang.String,zmq.SocketBase.EndpointPipe> endpoints,private java.nio.channels.SocketChannel fileDesc,private zmq.poll.Poller.Handle handle,private final non-sealed MultiMap<java.lang.String,zmq.pipe.Pipe> inprocs,private final non-sealed ThreadLocal<java.lang.Boolean> isInEventThreadLocal,private long lastTsc,private final non-sealed zmq.IMailbox mailbox,private final non-sealed AtomicReference<zmq.ZMQ.EventConsummer> monitor,private int monitorEvents,private final non-sealed Set<zmq.pipe.Pipe> pipes,private zmq.poll.Poller poller,private boolean rcvmore,private final non-sealed boolean threadSafe,private final non-sealed java.util.concurrent.locks.ReentrantLock threadSafeSync,private int ticks
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/socket/FQ.java
FQ
recvPipe
class FQ { // Inbound pipes. private final List<Pipe> pipes; // Number of active pipes. All the active pipes are located at the // beginning of the pipes array. private int active; // the last pipe we received message from. // NULL when no message has been received or the pipe // has terminated. private Pipe lastIn; // Index of the next bound pipe to read a message from. private int current; // If true, part of a multipart message was already received, but // there are following parts still waiting in the current pipe. private boolean more; // Holds credential after the last_acive_pipe has terminated. private Blob savedCredential; public FQ() { active = 0; current = 0; more = false; pipes = new ArrayList<>(); } public void attach(Pipe pipe) { pipes.add(pipe); Collections.swap(pipes, active, pipes.size() - 1); active++; } public void terminated(Pipe pipe) { final int index = pipes.indexOf(pipe); // Remove the pipe from the list; adjust number of active pipes // accordingly. if (index < active) { active--; Collections.swap(pipes, index, active); if (current == active) { current = 0; } } pipes.remove(pipe); if (lastIn == pipe) { savedCredential = lastIn.getCredential(); lastIn = null; } } public void activated(Pipe pipe) { // Move the pipe to the list of active pipes. Collections.swap(pipes, pipes.indexOf(pipe), active); active++; } public Msg recv(Errno errno) { return recvPipe(errno, null); } public Msg recvPipe(Errno errno, ValueReference<Pipe> pipe) {<FILL_FUNCTION_BODY>} public boolean hasIn() { // There are subsequent parts of the partly-read message available. if (more) { return true; } // Note that messing with current doesn't break the fairness of fair // queuing algorithm. If there are no messages available current will // get back to its original value. Otherwise it'll point to the first // pipe holding messages, skipping only pipes with no messages available. while (active > 0) { if (pipes.get(current).checkRead()) { return true; } // Deactivate the pipe. active--; Collections.swap(pipes, current, active); if (current == active) { current = 0; } } return false; } public Blob getCredential() { return lastIn != null ? lastIn.getCredential() : savedCredential; } }
// Round-robin over the pipes to get the next message. while (active > 0) { // Try to fetch new message. If we've already read part of the message // subsequent part should be immediately available. final Pipe currentPipe = pipes.get(current); final Msg msg = currentPipe.read(); final boolean fetched = msg != null; // Note that when message is not fetched, current pipe is deactivated // and replaced by another active pipe. Thus we don't have to increase // the 'current' pointer. if (fetched) { if (pipe != null) { pipe.set(currentPipe); } more = msg.hasMore(); if (!more) { lastIn = currentPipe; assert (active > 0); // happens when multiple threads receive messages current = (current + 1) % active; } return msg; } // Check the atomicity of the message. // If we've already received the first part of the message // we should get the remaining parts without blocking. assert (!more); active--; Collections.swap(pipes, current, active); if (current == active) { current = 0; } } // No message is available. Initialize the output parameter // to be a 0-byte message. errno.set(ZError.EAGAIN); return null;
800
380
1,180
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/socket/LB.java
LB
terminated
class LB { // List of outbound pipes. private final List<Pipe> pipes; // Number of active pipes. All the active pipes are located at the // beginning of the pipes array. private int active; // Points to the last pipe that the most recent message was sent to. private int current; // True if last we are in the middle of a multipart message. private boolean more; // True if we are dropping current message. private boolean dropping; public LB() { active = 0; current = 0; more = false; dropping = false; pipes = new ArrayList<>(); } public void attach(Pipe pipe) { pipes.add(pipe); activated(pipe); } public void terminated(Pipe pipe) {<FILL_FUNCTION_BODY>} public void activated(Pipe pipe) { // Move the pipe to the list of active pipes. Collections.swap(pipes, pipes.indexOf(pipe), active); active++; } public boolean sendpipe(Msg msg, Errno errno, ValueReference<Pipe> pipe) { // Drop the message if required. If we are at the end of the message // switch back to non-dropping mode. if (dropping) { more = msg.hasMore(); dropping = more; // msg_.close(); return true; } while (active > 0) { if (pipes.get(current).write(msg)) { if (pipe != null) { pipe.set(pipes.get(current)); } break; } assert (!more); active--; if (current < active) { Collections.swap(pipes, current, active); } else { current = 0; } } // If there are no pipes we cannot send the message. if (active == 0) { errno.set(ZError.EAGAIN); return false; } // If it's final part of the message we can flush it downstream and // continue round-robining (load balance). more = msg.hasMore(); if (!more) { pipes.get(current).flush(); if (++current >= active) { current = 0; } } return true; } public boolean hasOut() { // If one part of the message was already written we can definitely // write the rest of the message. if (more) { return true; } while (active > 0) { // Check whether a pipe has room for another message. if (pipes.get(current).checkWrite()) { return true; } // Deactivate the pipe. active--; Collections.swap(pipes, current, active); if (current == active) { current = 0; } } return false; } }
final int index = pipes.indexOf(pipe); // If we are in the middle of multipart message and current pipe // have disconnected, we have to drop the remainder of the message. if (index == current && more) { dropping = true; } // Remove the pipe from the list; adjust number of active pipes // accordingly. if (index < active) { active--; Collections.swap(pipes, index, active); if (current == active) { current = 0; } } pipes.remove(pipe);
800
150
950
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/socket/Pair.java
Pair
xreadActivated
class Pair extends SocketBase { private Pipe pipe; private Pipe lastIn; private Blob savedCredential; public Pair(Ctx parent, int tid, int sid) { super(parent, tid, sid); options.type = ZMQ.ZMQ_PAIR; } @Override protected void destroy() { super.destroy(); assert (pipe == null); } @Override protected void xattachPipe(Pipe pipe, boolean subscribe2all, boolean isLocallyInitiated) { assert (pipe != null); // ZMQ_PAIR socket can only be connected to a single peer. // The socket rejects any further connection requests. if (this.pipe == null) { this.pipe = pipe; } else { pipe.terminate(false); } } @Override protected void xpipeTerminated(Pipe pipe) { if (this.pipe == pipe) { if (lastIn == pipe) { savedCredential = lastIn.getCredential(); lastIn = null; } this.pipe = null; } } @Override protected void xreadActivated(Pipe pipe) {<FILL_FUNCTION_BODY>} @Override protected void xwriteActivated(Pipe pipe) { // There's just one pipe. No lists of active and inactive pipes. // There's nothing to do here. } @Override protected boolean xsend(Msg msg) { if (pipe == null || !pipe.write(msg)) { errno.set(ZError.EAGAIN); return false; } if (!msg.hasMore()) { pipe.flush(); } return true; } @Override protected Msg xrecv() { // Deallocate old content of the message. Msg msg; if (pipe == null) { // Initialize the output parameter to be a 0-byte message. errno.set(ZError.EAGAIN); return null; } else { msg = pipe.read(); if (msg == null) { // Initialize the output parameter to be a 0-byte message. errno.set(ZError.EAGAIN); return null; } } lastIn = pipe; return msg; } @Override protected boolean xhasIn() { return pipe != null && pipe.checkRead(); } @Override protected boolean xhasOut() { return pipe != null && pipe.checkWrite(); } @Override protected Blob getCredential() { return lastIn != null ? lastIn.getCredential() : savedCredential; } }
// There's just one pipe. No lists of active and inactive pipes. // There's nothing to do here.
762
35
797
<methods>public final boolean bind(java.lang.String) ,public final void cancel(java.util.concurrent.atomic.AtomicBoolean) ,public final void close() ,public final boolean connect(java.lang.String) ,public final int connectPeer(java.lang.String) ,public boolean disconnectPeer(int) ,public final int errno() ,public final void eventAcceptFailed(java.lang.String, int) ,public final void eventAccepted(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventBindFailed(java.lang.String, int) ,public final void eventCloseFailed(java.lang.String, int) ,public final void eventClosed(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventConnectDelayed(java.lang.String, int) ,public final void eventConnectRetried(java.lang.String, int) ,public final void eventConnected(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventDisconnected(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventHandshakeFailedAuth(java.lang.String, int) ,public final void eventHandshakeFailedNoDetail(java.lang.String, int) ,public final void eventHandshakeFailedProtocol(java.lang.String, int) ,public final void eventHandshakeSucceeded(java.lang.String, int) ,public final void eventHandshaken(java.lang.String, int) ,public final void eventListening(java.lang.String, java.nio.channels.SelectableChannel) ,public final java.nio.channels.SelectableChannel getFD() ,public final int getSocketOpt(int) ,public final java.lang.Object getSocketOptx(int) ,public final void hiccuped(zmq.pipe.Pipe) ,public final void inEvent() ,public final boolean join(java.lang.String) ,public final boolean leave(java.lang.String) ,public final boolean monitor(java.lang.String, int) ,public final void pipeTerminated(zmq.pipe.Pipe) ,public final int poll(int, int, java.util.concurrent.atomic.AtomicBoolean) ,public final void readActivated(zmq.pipe.Pipe) ,public final zmq.Msg recv(int) ,public final zmq.Msg recv(int, java.util.concurrent.atomic.AtomicBoolean) ,public final boolean send(zmq.Msg, int) ,public final boolean send(zmq.Msg, int, java.util.concurrent.atomic.AtomicBoolean) ,public final boolean setEventHook(zmq.ZMQ.EventConsummer, int) ,public final boolean setSocketOpt(int, java.lang.Object) ,public final boolean termEndpoint(java.lang.String) ,public java.lang.String toString() ,public java.lang.String typeString() ,public final void writeActivated(zmq.pipe.Pipe) <variables>private boolean active,protected java.lang.String connectRid,private final non-sealed java.util.concurrent.atomic.AtomicBoolean ctxTerminated,private final non-sealed java.util.concurrent.atomic.AtomicBoolean destroyed,private final non-sealed MultiMap<java.lang.String,zmq.SocketBase.EndpointPipe> endpoints,private java.nio.channels.SocketChannel fileDesc,private zmq.poll.Poller.Handle handle,private final non-sealed MultiMap<java.lang.String,zmq.pipe.Pipe> inprocs,private final non-sealed ThreadLocal<java.lang.Boolean> isInEventThreadLocal,private long lastTsc,private final non-sealed zmq.IMailbox mailbox,private final non-sealed AtomicReference<zmq.ZMQ.EventConsummer> monitor,private int monitorEvents,private final non-sealed Set<zmq.pipe.Pipe> pipes,private zmq.poll.Poller poller,private boolean rcvmore,private final non-sealed boolean threadSafe,private final non-sealed java.util.concurrent.locks.ReentrantLock threadSafeSync,private int ticks