hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
3c564746111e9a01efb64b4d886f3ae7ee1c1eb1
43,643
package com.live.liveteam.entity; import java.util.ArrayList; import java.util.List; public class OrdersExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public OrdersExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andOrderNumIsNull() { addCriterion("order_num is null"); return (Criteria) this; } public Criteria andOrderNumIsNotNull() { addCriterion("order_num is not null"); return (Criteria) this; } public Criteria andOrderNumEqualTo(String value) { addCriterion("order_num =", value, "orderNum"); return (Criteria) this; } public Criteria andOrderNumNotEqualTo(String value) { addCriterion("order_num <>", value, "orderNum"); return (Criteria) this; } public Criteria andOrderNumGreaterThan(String value) { addCriterion("order_num >", value, "orderNum"); return (Criteria) this; } public Criteria andOrderNumGreaterThanOrEqualTo(String value) { addCriterion("order_num >=", value, "orderNum"); return (Criteria) this; } public Criteria andOrderNumLessThan(String value) { addCriterion("order_num <", value, "orderNum"); return (Criteria) this; } public Criteria andOrderNumLessThanOrEqualTo(String value) { addCriterion("order_num <=", value, "orderNum"); return (Criteria) this; } public Criteria andOrderNumLike(String value) { addCriterion("order_num like", value, "orderNum"); return (Criteria) this; } public Criteria andOrderNumNotLike(String value) { addCriterion("order_num not like", value, "orderNum"); return (Criteria) this; } public Criteria andOrderNumIn(List<String> values) { addCriterion("order_num in", values, "orderNum"); return (Criteria) this; } public Criteria andOrderNumNotIn(List<String> values) { addCriterion("order_num not in", values, "orderNum"); return (Criteria) this; } public Criteria andOrderNumBetween(String value1, String value2) { addCriterion("order_num between", value1, value2, "orderNum"); return (Criteria) this; } public Criteria andOrderNumNotBetween(String value1, String value2) { addCriterion("order_num not between", value1, value2, "orderNum"); return (Criteria) this; } public Criteria andOpenIdIsNull() { addCriterion("open_id is null"); return (Criteria) this; } public Criteria andOpenIdIsNotNull() { addCriterion("open_id is not null"); return (Criteria) this; } public Criteria andOpenIdEqualTo(String value) { addCriterion("open_id =", value, "openId"); return (Criteria) this; } public Criteria andOpenIdNotEqualTo(String value) { addCriterion("open_id <>", value, "openId"); return (Criteria) this; } public Criteria andOpenIdGreaterThan(String value) { addCriterion("open_id >", value, "openId"); return (Criteria) this; } public Criteria andOpenIdGreaterThanOrEqualTo(String value) { addCriterion("open_id >=", value, "openId"); return (Criteria) this; } public Criteria andOpenIdLessThan(String value) { addCriterion("open_id <", value, "openId"); return (Criteria) this; } public Criteria andOpenIdLessThanOrEqualTo(String value) { addCriterion("open_id <=", value, "openId"); return (Criteria) this; } public Criteria andOpenIdLike(String value) { addCriterion("open_id like", value, "openId"); return (Criteria) this; } public Criteria andOpenIdNotLike(String value) { addCriterion("open_id not like", value, "openId"); return (Criteria) this; } public Criteria andOpenIdIn(List<String> values) { addCriterion("open_id in", values, "openId"); return (Criteria) this; } public Criteria andOpenIdNotIn(List<String> values) { addCriterion("open_id not in", values, "openId"); return (Criteria) this; } public Criteria andOpenIdBetween(String value1, String value2) { addCriterion("open_id between", value1, value2, "openId"); return (Criteria) this; } public Criteria andOpenIdNotBetween(String value1, String value2) { addCriterion("open_id not between", value1, value2, "openId"); return (Criteria) this; } public Criteria andOrderStatusIsNull() { addCriterion("order_status is null"); return (Criteria) this; } public Criteria andOrderStatusIsNotNull() { addCriterion("order_status is not null"); return (Criteria) this; } public Criteria andOrderStatusEqualTo(Integer value) { addCriterion("order_status =", value, "orderStatus"); return (Criteria) this; } public Criteria andOrderStatusNotEqualTo(Integer value) { addCriterion("order_status <>", value, "orderStatus"); return (Criteria) this; } public Criteria andOrderStatusGreaterThan(Integer value) { addCriterion("order_status >", value, "orderStatus"); return (Criteria) this; } public Criteria andOrderStatusGreaterThanOrEqualTo(Integer value) { addCriterion("order_status >=", value, "orderStatus"); return (Criteria) this; } public Criteria andOrderStatusLessThan(Integer value) { addCriterion("order_status <", value, "orderStatus"); return (Criteria) this; } public Criteria andOrderStatusLessThanOrEqualTo(Integer value) { addCriterion("order_status <=", value, "orderStatus"); return (Criteria) this; } public Criteria andOrderStatusIn(List<Integer> values) { addCriterion("order_status in", values, "orderStatus"); return (Criteria) this; } public Criteria andOrderStatusNotIn(List<Integer> values) { addCriterion("order_status not in", values, "orderStatus"); return (Criteria) this; } public Criteria andOrderStatusBetween(Integer value1, Integer value2) { addCriterion("order_status between", value1, value2, "orderStatus"); return (Criteria) this; } public Criteria andOrderStatusNotBetween(Integer value1, Integer value2) { addCriterion("order_status not between", value1, value2, "orderStatus"); return (Criteria) this; } public Criteria andAddressIdIsNull() { addCriterion("address_id is null"); return (Criteria) this; } public Criteria andAddressIdIsNotNull() { addCriterion("address_id is not null"); return (Criteria) this; } public Criteria andAddressIdEqualTo(Long value) { addCriterion("address_id =", value, "addressId"); return (Criteria) this; } public Criteria andAddressIdNotEqualTo(Long value) { addCriterion("address_id <>", value, "addressId"); return (Criteria) this; } public Criteria andAddressIdGreaterThan(Long value) { addCriterion("address_id >", value, "addressId"); return (Criteria) this; } public Criteria andAddressIdGreaterThanOrEqualTo(Long value) { addCriterion("address_id >=", value, "addressId"); return (Criteria) this; } public Criteria andAddressIdLessThan(Long value) { addCriterion("address_id <", value, "addressId"); return (Criteria) this; } public Criteria andAddressIdLessThanOrEqualTo(Long value) { addCriterion("address_id <=", value, "addressId"); return (Criteria) this; } public Criteria andAddressIdIn(List<Long> values) { addCriterion("address_id in", values, "addressId"); return (Criteria) this; } public Criteria andAddressIdNotIn(List<Long> values) { addCriterion("address_id not in", values, "addressId"); return (Criteria) this; } public Criteria andAddressIdBetween(Long value1, Long value2) { addCriterion("address_id between", value1, value2, "addressId"); return (Criteria) this; } public Criteria andAddressIdNotBetween(Long value1, Long value2) { addCriterion("address_id not between", value1, value2, "addressId"); return (Criteria) this; } public Criteria andIsShowIsNull() { addCriterion("is_show is null"); return (Criteria) this; } public Criteria andIsShowIsNotNull() { addCriterion("is_show is not null"); return (Criteria) this; } public Criteria andIsShowEqualTo(Integer value) { addCriterion("is_show =", value, "isShow"); return (Criteria) this; } public Criteria andIsShowNotEqualTo(Integer value) { addCriterion("is_show <>", value, "isShow"); return (Criteria) this; } public Criteria andIsShowGreaterThan(Integer value) { addCriterion("is_show >", value, "isShow"); return (Criteria) this; } public Criteria andIsShowGreaterThanOrEqualTo(Integer value) { addCriterion("is_show >=", value, "isShow"); return (Criteria) this; } public Criteria andIsShowLessThan(Integer value) { addCriterion("is_show <", value, "isShow"); return (Criteria) this; } public Criteria andIsShowLessThanOrEqualTo(Integer value) { addCriterion("is_show <=", value, "isShow"); return (Criteria) this; } public Criteria andIsShowIn(List<Integer> values) { addCriterion("is_show in", values, "isShow"); return (Criteria) this; } public Criteria andIsShowNotIn(List<Integer> values) { addCriterion("is_show not in", values, "isShow"); return (Criteria) this; } public Criteria andIsShowBetween(Integer value1, Integer value2) { addCriterion("is_show between", value1, value2, "isShow"); return (Criteria) this; } public Criteria andIsShowNotBetween(Integer value1, Integer value2) { addCriterion("is_show not between", value1, value2, "isShow"); return (Criteria) this; } public Criteria andGoodsUrlsIsNull() { addCriterion("goods_urls is null"); return (Criteria) this; } public Criteria andGoodsUrlsIsNotNull() { addCriterion("goods_urls is not null"); return (Criteria) this; } public Criteria andGoodsUrlsEqualTo(String value) { addCriterion("goods_urls =", value, "goodsUrls"); return (Criteria) this; } public Criteria andGoodsUrlsNotEqualTo(String value) { addCriterion("goods_urls <>", value, "goodsUrls"); return (Criteria) this; } public Criteria andGoodsUrlsGreaterThan(String value) { addCriterion("goods_urls >", value, "goodsUrls"); return (Criteria) this; } public Criteria andGoodsUrlsGreaterThanOrEqualTo(String value) { addCriterion("goods_urls >=", value, "goodsUrls"); return (Criteria) this; } public Criteria andGoodsUrlsLessThan(String value) { addCriterion("goods_urls <", value, "goodsUrls"); return (Criteria) this; } public Criteria andGoodsUrlsLessThanOrEqualTo(String value) { addCriterion("goods_urls <=", value, "goodsUrls"); return (Criteria) this; } public Criteria andGoodsUrlsLike(String value) { addCriterion("goods_urls like", value, "goodsUrls"); return (Criteria) this; } public Criteria andGoodsUrlsNotLike(String value) { addCriterion("goods_urls not like", value, "goodsUrls"); return (Criteria) this; } public Criteria andGoodsUrlsIn(List<String> values) { addCriterion("goods_urls in", values, "goodsUrls"); return (Criteria) this; } public Criteria andGoodsUrlsNotIn(List<String> values) { addCriterion("goods_urls not in", values, "goodsUrls"); return (Criteria) this; } public Criteria andGoodsUrlsBetween(String value1, String value2) { addCriterion("goods_urls between", value1, value2, "goodsUrls"); return (Criteria) this; } public Criteria andGoodsUrlsNotBetween(String value1, String value2) { addCriterion("goods_urls not between", value1, value2, "goodsUrls"); return (Criteria) this; } public Criteria andOrderPriceTotalIsNull() { addCriterion("order_price_total is null"); return (Criteria) this; } public Criteria andOrderPriceTotalIsNotNull() { addCriterion("order_price_total is not null"); return (Criteria) this; } public Criteria andOrderPriceTotalEqualTo(Long value) { addCriterion("order_price_total =", value, "orderPriceTotal"); return (Criteria) this; } public Criteria andOrderPriceTotalNotEqualTo(Long value) { addCriterion("order_price_total <>", value, "orderPriceTotal"); return (Criteria) this; } public Criteria andOrderPriceTotalGreaterThan(Long value) { addCriterion("order_price_total >", value, "orderPriceTotal"); return (Criteria) this; } public Criteria andOrderPriceTotalGreaterThanOrEqualTo(Long value) { addCriterion("order_price_total >=", value, "orderPriceTotal"); return (Criteria) this; } public Criteria andOrderPriceTotalLessThan(Long value) { addCriterion("order_price_total <", value, "orderPriceTotal"); return (Criteria) this; } public Criteria andOrderPriceTotalLessThanOrEqualTo(Long value) { addCriterion("order_price_total <=", value, "orderPriceTotal"); return (Criteria) this; } public Criteria andOrderPriceTotalIn(List<Long> values) { addCriterion("order_price_total in", values, "orderPriceTotal"); return (Criteria) this; } public Criteria andOrderPriceTotalNotIn(List<Long> values) { addCriterion("order_price_total not in", values, "orderPriceTotal"); return (Criteria) this; } public Criteria andOrderPriceTotalBetween(Long value1, Long value2) { addCriterion("order_price_total between", value1, value2, "orderPriceTotal"); return (Criteria) this; } public Criteria andOrderPriceTotalNotBetween(Long value1, Long value2) { addCriterion("order_price_total not between", value1, value2, "orderPriceTotal"); return (Criteria) this; } public Criteria andOrderGoodsNumIsNull() { addCriterion("order_goods_num is null"); return (Criteria) this; } public Criteria andOrderGoodsNumIsNotNull() { addCriterion("order_goods_num is not null"); return (Criteria) this; } public Criteria andOrderGoodsNumEqualTo(Long value) { addCriterion("order_goods_num =", value, "orderGoodsNum"); return (Criteria) this; } public Criteria andOrderGoodsNumNotEqualTo(Long value) { addCriterion("order_goods_num <>", value, "orderGoodsNum"); return (Criteria) this; } public Criteria andOrderGoodsNumGreaterThan(Long value) { addCriterion("order_goods_num >", value, "orderGoodsNum"); return (Criteria) this; } public Criteria andOrderGoodsNumGreaterThanOrEqualTo(Long value) { addCriterion("order_goods_num >=", value, "orderGoodsNum"); return (Criteria) this; } public Criteria andOrderGoodsNumLessThan(Long value) { addCriterion("order_goods_num <", value, "orderGoodsNum"); return (Criteria) this; } public Criteria andOrderGoodsNumLessThanOrEqualTo(Long value) { addCriterion("order_goods_num <=", value, "orderGoodsNum"); return (Criteria) this; } public Criteria andOrderGoodsNumIn(List<Long> values) { addCriterion("order_goods_num in", values, "orderGoodsNum"); return (Criteria) this; } public Criteria andOrderGoodsNumNotIn(List<Long> values) { addCriterion("order_goods_num not in", values, "orderGoodsNum"); return (Criteria) this; } public Criteria andOrderGoodsNumBetween(Long value1, Long value2) { addCriterion("order_goods_num between", value1, value2, "orderGoodsNum"); return (Criteria) this; } public Criteria andOrderGoodsNumNotBetween(Long value1, Long value2) { addCriterion("order_goods_num not between", value1, value2, "orderGoodsNum"); return (Criteria) this; } public Criteria andCouponsIdsIsNull() { addCriterion("coupons_ids is null"); return (Criteria) this; } public Criteria andCouponsIdsIsNotNull() { addCriterion("coupons_ids is not null"); return (Criteria) this; } public Criteria andCouponsIdsEqualTo(String value) { addCriterion("coupons_ids =", value, "couponsIds"); return (Criteria) this; } public Criteria andCouponsIdsNotEqualTo(String value) { addCriterion("coupons_ids <>", value, "couponsIds"); return (Criteria) this; } public Criteria andCouponsIdsGreaterThan(String value) { addCriterion("coupons_ids >", value, "couponsIds"); return (Criteria) this; } public Criteria andCouponsIdsGreaterThanOrEqualTo(String value) { addCriterion("coupons_ids >=", value, "couponsIds"); return (Criteria) this; } public Criteria andCouponsIdsLessThan(String value) { addCriterion("coupons_ids <", value, "couponsIds"); return (Criteria) this; } public Criteria andCouponsIdsLessThanOrEqualTo(String value) { addCriterion("coupons_ids <=", value, "couponsIds"); return (Criteria) this; } public Criteria andCouponsIdsLike(String value) { addCriterion("coupons_ids like", value, "couponsIds"); return (Criteria) this; } public Criteria andCouponsIdsNotLike(String value) { addCriterion("coupons_ids not like", value, "couponsIds"); return (Criteria) this; } public Criteria andCouponsIdsIn(List<String> values) { addCriterion("coupons_ids in", values, "couponsIds"); return (Criteria) this; } public Criteria andCouponsIdsNotIn(List<String> values) { addCriterion("coupons_ids not in", values, "couponsIds"); return (Criteria) this; } public Criteria andCouponsIdsBetween(String value1, String value2) { addCriterion("coupons_ids between", value1, value2, "couponsIds"); return (Criteria) this; } public Criteria andCouponsIdsNotBetween(String value1, String value2) { addCriterion("coupons_ids not between", value1, value2, "couponsIds"); return (Criteria) this; } public Criteria andOrderAffirmIsNull() { addCriterion("order_affirm is null"); return (Criteria) this; } public Criteria andOrderAffirmIsNotNull() { addCriterion("order_affirm is not null"); return (Criteria) this; } public Criteria andOrderAffirmEqualTo(Long value) { addCriterion("order_affirm =", value, "orderAffirm"); return (Criteria) this; } public Criteria andOrderAffirmNotEqualTo(Long value) { addCriterion("order_affirm <>", value, "orderAffirm"); return (Criteria) this; } public Criteria andOrderAffirmGreaterThan(Long value) { addCriterion("order_affirm >", value, "orderAffirm"); return (Criteria) this; } public Criteria andOrderAffirmGreaterThanOrEqualTo(Long value) { addCriterion("order_affirm >=", value, "orderAffirm"); return (Criteria) this; } public Criteria andOrderAffirmLessThan(Long value) { addCriterion("order_affirm <", value, "orderAffirm"); return (Criteria) this; } public Criteria andOrderAffirmLessThanOrEqualTo(Long value) { addCriterion("order_affirm <=", value, "orderAffirm"); return (Criteria) this; } public Criteria andOrderAffirmIn(List<Long> values) { addCriterion("order_affirm in", values, "orderAffirm"); return (Criteria) this; } public Criteria andOrderAffirmNotIn(List<Long> values) { addCriterion("order_affirm not in", values, "orderAffirm"); return (Criteria) this; } public Criteria andOrderAffirmBetween(Long value1, Long value2) { addCriterion("order_affirm between", value1, value2, "orderAffirm"); return (Criteria) this; } public Criteria andOrderAffirmNotBetween(Long value1, Long value2) { addCriterion("order_affirm not between", value1, value2, "orderAffirm"); return (Criteria) this; } public Criteria andOrderScoreIsNull() { addCriterion("order_score is null"); return (Criteria) this; } public Criteria andOrderScoreIsNotNull() { addCriterion("order_score is not null"); return (Criteria) this; } public Criteria andOrderScoreEqualTo(Integer value) { addCriterion("order_score =", value, "orderScore"); return (Criteria) this; } public Criteria andOrderScoreNotEqualTo(Integer value) { addCriterion("order_score <>", value, "orderScore"); return (Criteria) this; } public Criteria andOrderScoreGreaterThan(Integer value) { addCriterion("order_score >", value, "orderScore"); return (Criteria) this; } public Criteria andOrderScoreGreaterThanOrEqualTo(Integer value) { addCriterion("order_score >=", value, "orderScore"); return (Criteria) this; } public Criteria andOrderScoreLessThan(Integer value) { addCriterion("order_score <", value, "orderScore"); return (Criteria) this; } public Criteria andOrderScoreLessThanOrEqualTo(Integer value) { addCriterion("order_score <=", value, "orderScore"); return (Criteria) this; } public Criteria andOrderScoreIn(List<Integer> values) { addCriterion("order_score in", values, "orderScore"); return (Criteria) this; } public Criteria andOrderScoreNotIn(List<Integer> values) { addCriterion("order_score not in", values, "orderScore"); return (Criteria) this; } public Criteria andOrderScoreBetween(Integer value1, Integer value2) { addCriterion("order_score between", value1, value2, "orderScore"); return (Criteria) this; } public Criteria andOrderScoreNotBetween(Integer value1, Integer value2) { addCriterion("order_score not between", value1, value2, "orderScore"); return (Criteria) this; } public Criteria andOrderCouponsPriceIsNull() { addCriterion("order_coupons_price is null"); return (Criteria) this; } public Criteria andOrderCouponsPriceIsNotNull() { addCriterion("order_coupons_price is not null"); return (Criteria) this; } public Criteria andOrderCouponsPriceEqualTo(Long value) { addCriterion("order_coupons_price =", value, "orderCouponsPrice"); return (Criteria) this; } public Criteria andOrderCouponsPriceNotEqualTo(Long value) { addCriterion("order_coupons_price <>", value, "orderCouponsPrice"); return (Criteria) this; } public Criteria andOrderCouponsPriceGreaterThan(Long value) { addCriterion("order_coupons_price >", value, "orderCouponsPrice"); return (Criteria) this; } public Criteria andOrderCouponsPriceGreaterThanOrEqualTo(Long value) { addCriterion("order_coupons_price >=", value, "orderCouponsPrice"); return (Criteria) this; } public Criteria andOrderCouponsPriceLessThan(Long value) { addCriterion("order_coupons_price <", value, "orderCouponsPrice"); return (Criteria) this; } public Criteria andOrderCouponsPriceLessThanOrEqualTo(Long value) { addCriterion("order_coupons_price <=", value, "orderCouponsPrice"); return (Criteria) this; } public Criteria andOrderCouponsPriceIn(List<Long> values) { addCriterion("order_coupons_price in", values, "orderCouponsPrice"); return (Criteria) this; } public Criteria andOrderCouponsPriceNotIn(List<Long> values) { addCriterion("order_coupons_price not in", values, "orderCouponsPrice"); return (Criteria) this; } public Criteria andOrderCouponsPriceBetween(Long value1, Long value2) { addCriterion("order_coupons_price between", value1, value2, "orderCouponsPrice"); return (Criteria) this; } public Criteria andOrderCouponsPriceNotBetween(Long value1, Long value2) { addCriterion("order_coupons_price not between", value1, value2, "orderCouponsPrice"); return (Criteria) this; } public Criteria andOrderCancelCauseIsNull() { addCriterion("order_cancel_cause is null"); return (Criteria) this; } public Criteria andOrderCancelCauseIsNotNull() { addCriterion("order_cancel_cause is not null"); return (Criteria) this; } public Criteria andOrderCancelCauseEqualTo(String value) { addCriterion("order_cancel_cause =", value, "orderCancelCause"); return (Criteria) this; } public Criteria andOrderCancelCauseNotEqualTo(String value) { addCriterion("order_cancel_cause <>", value, "orderCancelCause"); return (Criteria) this; } public Criteria andOrderCancelCauseGreaterThan(String value) { addCriterion("order_cancel_cause >", value, "orderCancelCause"); return (Criteria) this; } public Criteria andOrderCancelCauseGreaterThanOrEqualTo(String value) { addCriterion("order_cancel_cause >=", value, "orderCancelCause"); return (Criteria) this; } public Criteria andOrderCancelCauseLessThan(String value) { addCriterion("order_cancel_cause <", value, "orderCancelCause"); return (Criteria) this; } public Criteria andOrderCancelCauseLessThanOrEqualTo(String value) { addCriterion("order_cancel_cause <=", value, "orderCancelCause"); return (Criteria) this; } public Criteria andOrderCancelCauseLike(String value) { addCriterion("order_cancel_cause like", value, "orderCancelCause"); return (Criteria) this; } public Criteria andOrderCancelCauseNotLike(String value) { addCriterion("order_cancel_cause not like", value, "orderCancelCause"); return (Criteria) this; } public Criteria andOrderCancelCauseIn(List<String> values) { addCriterion("order_cancel_cause in", values, "orderCancelCause"); return (Criteria) this; } public Criteria andOrderCancelCauseNotIn(List<String> values) { addCriterion("order_cancel_cause not in", values, "orderCancelCause"); return (Criteria) this; } public Criteria andOrderCancelCauseBetween(String value1, String value2) { addCriterion("order_cancel_cause between", value1, value2, "orderCancelCause"); return (Criteria) this; } public Criteria andOrderCancelCauseNotBetween(String value1, String value2) { addCriterion("order_cancel_cause not between", value1, value2, "orderCancelCause"); return (Criteria) this; } public Criteria andOrderPayTimeIsNull() { addCriterion("order_pay_time is null"); return (Criteria) this; } public Criteria andOrderPayTimeIsNotNull() { addCriterion("order_pay_time is not null"); return (Criteria) this; } public Criteria andOrderPayTimeEqualTo(Long value) { addCriterion("order_pay_time =", value, "orderPayTime"); return (Criteria) this; } public Criteria andOrderPayTimeNotEqualTo(Long value) { addCriterion("order_pay_time <>", value, "orderPayTime"); return (Criteria) this; } public Criteria andOrderPayTimeGreaterThan(Long value) { addCriterion("order_pay_time >", value, "orderPayTime"); return (Criteria) this; } public Criteria andOrderPayTimeGreaterThanOrEqualTo(Long value) { addCriterion("order_pay_time >=", value, "orderPayTime"); return (Criteria) this; } public Criteria andOrderPayTimeLessThan(Long value) { addCriterion("order_pay_time <", value, "orderPayTime"); return (Criteria) this; } public Criteria andOrderPayTimeLessThanOrEqualTo(Long value) { addCriterion("order_pay_time <=", value, "orderPayTime"); return (Criteria) this; } public Criteria andOrderPayTimeIn(List<Long> values) { addCriterion("order_pay_time in", values, "orderPayTime"); return (Criteria) this; } public Criteria andOrderPayTimeNotIn(List<Long> values) { addCriterion("order_pay_time not in", values, "orderPayTime"); return (Criteria) this; } public Criteria andOrderPayTimeBetween(Long value1, Long value2) { addCriterion("order_pay_time between", value1, value2, "orderPayTime"); return (Criteria) this; } public Criteria andOrderPayTimeNotBetween(Long value1, Long value2) { addCriterion("order_pay_time not between", value1, value2, "orderPayTime"); return (Criteria) this; } public Criteria andCreateTimeIsNull() { addCriterion("create_time is null"); return (Criteria) this; } public Criteria andCreateTimeIsNotNull() { addCriterion("create_time is not null"); return (Criteria) this; } public Criteria andCreateTimeEqualTo(Long value) { addCriterion("create_time =", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotEqualTo(Long value) { addCriterion("create_time <>", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThan(Long value) { addCriterion("create_time >", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThanOrEqualTo(Long value) { addCriterion("create_time >=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThan(Long value) { addCriterion("create_time <", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThanOrEqualTo(Long value) { addCriterion("create_time <=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeIn(List<Long> values) { addCriterion("create_time in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotIn(List<Long> values) { addCriterion("create_time not in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeBetween(Long value1, Long value2) { addCriterion("create_time between", value1, value2, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotBetween(Long value1, Long value2) { addCriterion("create_time not between", value1, value2, "createTime"); return (Criteria) this; } public Criteria andOrderUpdateIsNull() { addCriterion("order_update is null"); return (Criteria) this; } public Criteria andOrderUpdateIsNotNull() { addCriterion("order_update is not null"); return (Criteria) this; } public Criteria andOrderUpdateEqualTo(Long value) { addCriterion("order_update =", value, "orderUpdate"); return (Criteria) this; } public Criteria andOrderUpdateNotEqualTo(Long value) { addCriterion("order_update <>", value, "orderUpdate"); return (Criteria) this; } public Criteria andOrderUpdateGreaterThan(Long value) { addCriterion("order_update >", value, "orderUpdate"); return (Criteria) this; } public Criteria andOrderUpdateGreaterThanOrEqualTo(Long value) { addCriterion("order_update >=", value, "orderUpdate"); return (Criteria) this; } public Criteria andOrderUpdateLessThan(Long value) { addCriterion("order_update <", value, "orderUpdate"); return (Criteria) this; } public Criteria andOrderUpdateLessThanOrEqualTo(Long value) { addCriterion("order_update <=", value, "orderUpdate"); return (Criteria) this; } public Criteria andOrderUpdateIn(List<Long> values) { addCriterion("order_update in", values, "orderUpdate"); return (Criteria) this; } public Criteria andOrderUpdateNotIn(List<Long> values) { addCriterion("order_update not in", values, "orderUpdate"); return (Criteria) this; } public Criteria andOrderUpdateBetween(Long value1, Long value2) { addCriterion("order_update between", value1, value2, "orderUpdate"); return (Criteria) this; } public Criteria andOrderUpdateNotBetween(Long value1, Long value2) { addCriterion("order_update not between", value1, value2, "orderUpdate"); return (Criteria) this; } public Criteria andOrderCancelTimeIsNull() { addCriterion("order_cancel_time is null"); return (Criteria) this; } public Criteria andOrderCancelTimeIsNotNull() { addCriterion("order_cancel_time is not null"); return (Criteria) this; } public Criteria andOrderCancelTimeEqualTo(Long value) { addCriterion("order_cancel_time =", value, "orderCancelTime"); return (Criteria) this; } public Criteria andOrderCancelTimeNotEqualTo(Long value) { addCriterion("order_cancel_time <>", value, "orderCancelTime"); return (Criteria) this; } public Criteria andOrderCancelTimeGreaterThan(Long value) { addCriterion("order_cancel_time >", value, "orderCancelTime"); return (Criteria) this; } public Criteria andOrderCancelTimeGreaterThanOrEqualTo(Long value) { addCriterion("order_cancel_time >=", value, "orderCancelTime"); return (Criteria) this; } public Criteria andOrderCancelTimeLessThan(Long value) { addCriterion("order_cancel_time <", value, "orderCancelTime"); return (Criteria) this; } public Criteria andOrderCancelTimeLessThanOrEqualTo(Long value) { addCriterion("order_cancel_time <=", value, "orderCancelTime"); return (Criteria) this; } public Criteria andOrderCancelTimeIn(List<Long> values) { addCriterion("order_cancel_time in", values, "orderCancelTime"); return (Criteria) this; } public Criteria andOrderCancelTimeNotIn(List<Long> values) { addCriterion("order_cancel_time not in", values, "orderCancelTime"); return (Criteria) this; } public Criteria andOrderCancelTimeBetween(Long value1, Long value2) { addCriterion("order_cancel_time between", value1, value2, "orderCancelTime"); return (Criteria) this; } public Criteria andOrderCancelTimeNotBetween(Long value1, Long value2) { addCriterion("order_cancel_time not between", value1, value2, "orderCancelTime"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
34.364567
102
0.601104
e35d126a68326b43de0eb60eb0bce62ee2b000da
27,465
/* * Copyright 2016-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.vault.core; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.vault.VaultException; import org.springframework.vault.support.*; import org.springframework.vault.util.IntegrationTestSupport; import org.springframework.vault.util.RequiresVaultVersion; import org.springframework.vault.util.Version; import static org.assertj.core.api.Assertions.*; /** * Integration tests for {@link VaultTransitTemplate} through * {@link VaultTransitOperations}. * * @author Mark Paluch * @author Praveendra Singh * @author Luander Ribeiro * @author Mikko Koli */ @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = VaultIntegrationTestConfiguration.class) class VaultTransitTemplateIntegrationTests extends IntegrationTestSupport { static final String KEY_EXPORT_INTRODUCED_IN_VERSION = "0.6.5"; static final String BATCH_INTRODUCED_IN_VERSION = "0.6.5"; static final String SIGN_VERIFY_INTRODUCED_IN_VERSION = "0.6.2"; static final String ED25519_INTRODUCED_IN_VERSION = "0.7.3"; static final String RSA3072_INTRODUCED_IN_VERSION = "1.4.0"; static final String ECDSA521_INTRODUCED_IN_VERSION = "1.4.0"; static final String AES256_GCM96_INTRODUCED_IN_VERSION = "1.4.0"; @Autowired VaultOperations vaultOperations; VaultTransitOperations transitOperations; Version vaultVersion; @BeforeEach void before() { this.transitOperations = this.vaultOperations.opsForTransit(); if (!this.vaultOperations.opsForSys().getMounts().containsKey("transit/")) { this.vaultOperations.opsForSys().mount("transit", VaultMount.create("transit")); } this.vaultVersion = prepare().getVersion(); removeKeys(); } @AfterEach void tearDown() { removeKeys(); } private void deleteKey(String keyName) { try { this.transitOperations.configureKey(keyName, VaultTransitKeyConfiguration.builder().deletionAllowed(true).build()); } catch (Exception e) { } try { this.transitOperations.deleteKey(keyName); } catch (Exception e) { } } private void removeKeys() { if (this.vaultVersion.isGreaterThanOrEqualTo(Version.parse("0.6.4"))) { List<String> keys = this.vaultOperations.opsForTransit().getKeys(); for (String keyName : keys) { deleteKey(keyName); } } else { deleteKey("mykey"); deleteKey("export"); deleteKey("ecdsa-key"); deleteKey("ed-key"); deleteKey("rsa-3072-key"); deleteKey("ecdsa-p521-key"); deleteKey("aes256-gcm96-key"); } } @Test void createKeyShouldCreateKey() { this.transitOperations.createKey("mykey"); VaultTransitKey mykey = this.transitOperations.getKey("mykey"); assertThat(mykey.getType()).startsWith("aes"); assertThat(mykey.getName()).isEqualTo("mykey"); assertThat(mykey.isDeletionAllowed()).isFalse(); assertThat(mykey.isDerived()).isFalse(); assertThat(mykey.getMinDecryptionVersion()).isEqualTo(1); assertThat(mykey.getLatestVersion()).isEqualTo(1); if (this.vaultVersion.isGreaterThanOrEqualTo(Version.parse("0.7.0"))) { assertThat(mykey.supportsDecryption()).isTrue(); assertThat(mykey.supportsEncryption()).isTrue(); assertThat(mykey.supportsDerivation()).isTrue(); assertThat(mykey.supportsSigning()).isFalse(); } } @Test @RequiresVaultVersion("0.6.4") void createKeyShouldCreateEcDsaKey() { String keyName = createEcdsaP256Key(); VaultTransitKey mykey = this.transitOperations.getKey(keyName); assertThat(mykey.getType()).startsWith("ecdsa"); assertThat(mykey.getKeys()).isNotEmpty(); } @Test @RequiresVaultVersion(ED25519_INTRODUCED_IN_VERSION) void createKeyShouldCreateEdKey() { VaultTransitKeyCreationRequest request = VaultTransitKeyCreationRequest.ofKeyType("ed25519"); this.transitOperations.createKey("ed-key", request); VaultTransitKey mykey = this.transitOperations.getKey("ed-key"); assertThat(mykey.getType()).startsWith("ed"); assertThat(mykey.getKeys()).isNotEmpty(); } @Test @RequiresVaultVersion(ECDSA521_INTRODUCED_IN_VERSION) void createKeyShouldCreateEcdsaKey() { VaultTransitKeyCreationRequest request = VaultTransitKeyCreationRequest.ofKeyType("ecdsa-p521"); this.transitOperations.createKey("ecdsa-p521-key", request); VaultTransitKey mykey = this.transitOperations.getKey("ecdsa-p521-key"); assertThat(mykey.getType()).isEqualTo("ecdsa-p521"); assertThat(mykey.getKeys()).isNotEmpty(); } @Test @RequiresVaultVersion(RSA3072_INTRODUCED_IN_VERSION) void createKeyShouldCreateRsa3072Key() { VaultTransitKeyCreationRequest request = VaultTransitKeyCreationRequest.ofKeyType("rsa-3072"); this.transitOperations.createKey("rsa-3072-key", request); VaultTransitKey mykey = this.transitOperations.getKey("rsa-3072-key"); assertThat(mykey.getType()).isEqualTo("rsa-3072"); assertThat(mykey.getKeys()).isNotEmpty(); } @Test @RequiresVaultVersion(AES256_GCM96_INTRODUCED_IN_VERSION) void createKeyShouldCreateAes256Gcm96Key() { VaultTransitKeyCreationRequest request = VaultTransitKeyCreationRequest.ofKeyType("aes256-gcm96"); this.transitOperations.createKey("aes256-gcm96-key", request); VaultTransitKey mykey = this.transitOperations.getKey("aes256-gcm96-key"); assertThat(mykey.getType()).isEqualTo("aes256-gcm96"); assertThat(mykey.getKeys()).isNotEmpty(); } @Test void createKeyShouldCreateKeyWithOptions() { VaultTransitKeyCreationRequest request = VaultTransitKeyCreationRequest.builder() // .convergentEncryption(true) // .derived(true) // .build(); this.transitOperations.createKey("mykey", request); VaultTransitKey mykey = this.transitOperations.getKey("mykey"); assertThat(mykey.getName()).isEqualTo("mykey"); assertThat(mykey.isDeletionAllowed()).isFalse(); assertThat(mykey.isDerived()).isTrue(); assertThat(mykey.getMinDecryptionVersion()).isEqualTo(1); assertThat(mykey.getLatestVersion()).isEqualTo(1); } @Test void shouldConfigureKey() { this.transitOperations.createKey("mykey"); this.transitOperations.rotate("mykey"); this.transitOperations.rotate("mykey"); VaultTransitKeyConfiguration configuration = VaultTransitKeyConfiguration.builder().deletionAllowed(true) .minDecryptionVersion(1).minEncryptionVersion(2).build(); this.transitOperations.configureKey("mykey", configuration); VaultTransitKey mykey = this.transitOperations.getKey("mykey"); assertThat(mykey.getMinDecryptionVersion()).isEqualTo(1); if (this.vaultVersion.isGreaterThanOrEqualTo(Version.parse("0.8.0"))) { assertThat(mykey.getMinEncryptionVersion()).isEqualTo(2); } else { assertThat(mykey.getMinEncryptionVersion()).isEqualTo(0); } } @Test @RequiresVaultVersion("0.6.4") void shouldEnumerateKey() { assertThat(this.transitOperations.getKeys()).isEmpty(); this.transitOperations.createKey("mykey"); assertThat(this.transitOperations.getKeys()).contains("mykey"); } @Test void getKeyShouldReturnNullIfKeyNotExists() { VaultTransitKey key = this.transitOperations.getKey("hello-world"); assertThat(key).isNull(); } @Test void deleteKeyShouldFailIfKeyNotExists() { try { this.transitOperations.deleteKey("hello-world"); fail("Missing VaultException"); } catch (VaultException e) { assertThat(e).hasMessageContaining("Status 400"); } } @Test void deleteKeyShouldDeleteKey() { this.transitOperations.createKey("mykey"); this.transitOperations.configureKey("mykey", VaultTransitKeyConfiguration.builder().deletionAllowed(true).build()); this.transitOperations.deleteKey("mykey"); assertThat(this.transitOperations.getKey("mykey")).isNull(); } @Test void encryptShouldCreateCiphertext() { this.transitOperations.createKey("mykey"); String ciphertext = this.transitOperations.encrypt("mykey", "hello-world"); assertThat(ciphertext).startsWith("vault:v"); } @Test void encryptShouldCreateCiphertextWithNonceAndContext() { this.transitOperations.createKey("mykey", VaultTransitKeyCreationRequest.builder().convergentEncryption(true).derived(true).build()); VaultTransitContext transitRequest = VaultTransitContext.builder().context("blubb".getBytes()) // .nonce("123456789012".getBytes()) // .build(); String ciphertext = this.transitOperations.encrypt("mykey", "hello-world".getBytes(), transitRequest); assertThat(ciphertext).startsWith("vault:v1:"); } @Test @RequiresVaultVersion(BATCH_INTRODUCED_IN_VERSION) void encryptShouldEncryptEmptyValues() { this.transitOperations.createKey("mykey", VaultTransitKeyCreationRequest.builder().convergentEncryption(true).derived(true).build()); VaultTransitContext context = VaultTransitContext.builder().context("blubb".getBytes()) // .nonce("123456789012".getBytes()) // .build(); Ciphertext ciphertext = this.transitOperations.encrypt("mykey", Plaintext.of("").with(context)); assertThat(ciphertext.getCiphertext()).startsWith("vault:v1:"); assertThat(ciphertext.getContext()).isEqualTo(context); } @Test void encryptShouldCreateWrappedCiphertextWithNonceAndContext() { this.transitOperations.createKey("mykey", VaultTransitKeyCreationRequest.builder().convergentEncryption(true).derived(true).build()); VaultTransitContext context = VaultTransitContext.builder().context("blubb".getBytes()) // .nonce("123456789012".getBytes()) // .build(); Ciphertext ciphertext = this.transitOperations.encrypt("mykey", Plaintext.of("hello-world").with(context)); assertThat(ciphertext.getCiphertext()).startsWith("vault:v1:"); assertThat(ciphertext.getContext()).isEqualTo(context); } @Test void decryptShouldCreatePlaintext() { this.transitOperations.createKey("mykey"); String ciphertext = this.transitOperations.encrypt("mykey", "hello-world"); String plaintext = this.transitOperations.decrypt("mykey", ciphertext); assertThat(plaintext).isEqualTo("hello-world"); } @Test void decryptShouldCreatePlaintextWithNonceAndContext() { this.transitOperations.createKey("mykey", VaultTransitKeyCreationRequest.builder().convergentEncryption(true).derived(true).build()); VaultTransitContext transitRequest = VaultTransitContext.builder() // .context("blubb".getBytes()) // .nonce("123456789012".getBytes()) // .build(); String ciphertext = this.transitOperations.encrypt("mykey", "hello-world".getBytes(), transitRequest); byte[] plaintext = this.transitOperations.decrypt("mykey", ciphertext, transitRequest); assertThat(new String(plaintext)).isEqualTo("hello-world"); } @Test void decryptShouldCreateWrappedPlaintextWithNonceAndContext() { this.transitOperations.createKey("mykey", VaultTransitKeyCreationRequest.builder().convergentEncryption(true).derived(true).build()); VaultTransitContext context = VaultTransitContext.builder() // .context("blubb".getBytes()) // .nonce("123456789012".getBytes()) // .build(); Ciphertext ciphertext = this.transitOperations.encrypt("mykey", Plaintext.of("hello-world").with(context)); Plaintext plaintext = this.transitOperations.decrypt("mykey", ciphertext); assertThat(plaintext.asString()).isEqualTo("hello-world"); assertThat(plaintext.getContext()).isEqualTo(context); } @Test void encryptAndRewrapShouldCreateCiphertext() { this.transitOperations.createKey("mykey"); String ciphertext = this.transitOperations.encrypt("mykey", "hello-world"); this.transitOperations.rotate("mykey"); String rewrapped = this.transitOperations.rewrap("mykey", ciphertext); assertThat(rewrapped).startsWith("vault:v2:"); } @Test void shouldEncryptBinaryPlaintext() { this.transitOperations.createKey("mykey"); byte[] plaintext = new byte[] { 1, 2, 3, 4, 5 }; String ciphertext = this.transitOperations.encrypt("mykey", plaintext, VaultTransitContext.empty()); byte[] decrypted = this.transitOperations.decrypt("mykey", ciphertext, VaultTransitContext.empty()); assertThat(decrypted).isEqualTo(plaintext); } @Test void encryptAndRewrapShouldCreateCiphertextWithNonceAndContext() { this.transitOperations.createKey("mykey", VaultTransitKeyCreationRequest.builder().convergentEncryption(true).derived(true).build()); VaultTransitContext transitRequest = VaultTransitContext.builder() // .context("blubb".getBytes()) // .nonce("123456789012".getBytes()) // .build(); String ciphertext = this.transitOperations.encrypt("mykey", "hello-world".getBytes(), transitRequest); this.transitOperations.rotate("mykey"); String rewrapped = this.transitOperations.rewrap("mykey", ciphertext, transitRequest); assertThat(rewrapped).startsWith("vault:v2"); } @Test @RequiresVaultVersion(BATCH_INTRODUCED_IN_VERSION) void shouldBatchEncrypt() { this.transitOperations.createKey("mykey"); List<VaultEncryptionResult> encrypted = this.transitOperations.encrypt("mykey", Arrays.asList(Plaintext.of("one"), Plaintext.of("two"))); assertThat(encrypted.get(0).get().getCiphertext()).startsWith("vault:"); assertThat(encrypted.get(1).get().getCiphertext()).startsWith("vault:"); } @Test @RequiresVaultVersion(BATCH_INTRODUCED_IN_VERSION) void shouldBatchDecrypt() { this.transitOperations.createKey("mykey"); Ciphertext one = this.transitOperations.encrypt("mykey", Plaintext.of("one")); Ciphertext two = this.transitOperations.encrypt("mykey", Plaintext.of("two")); Plaintext plainOne = this.transitOperations.decrypt("mykey", one); Plaintext plainTwo = this.transitOperations.decrypt("mykey", two); List<VaultDecryptionResult> decrypted = this.transitOperations.decrypt("mykey", Arrays.asList(one, two)); assertThat(decrypted.get(0).get()).isEqualTo(plainOne); assertThat(decrypted.get(0).getAsString()).isEqualTo("one"); assertThat(decrypted.get(1).get()).isEqualTo(plainTwo); assertThat(decrypted.get(1).getAsString()).isEqualTo("two"); } @Test @RequiresVaultVersion(BATCH_INTRODUCED_IN_VERSION) void shouldBatchEncryptWithContext() { VaultTransitKeyCreationRequest request = VaultTransitKeyCreationRequest.builder() // .derived(true) // .build(); this.transitOperations.createKey("mykey", request); Plaintext one = Plaintext.of("one") .with(VaultTransitContext.builder().context("oneContext".getBytes()).build()); Plaintext two = Plaintext.of("two") .with(VaultTransitContext.builder().context("twoContext".getBytes()).build()); List<VaultEncryptionResult> encrypted = this.transitOperations.encrypt("mykey", Arrays.asList(one, two)); assertThat(encrypted.get(0).get().getContext()).isEqualTo(one.getContext()); assertThat(encrypted.get(1).get().getContext()).isEqualTo(two.getContext()); } @Test @RequiresVaultVersion(BATCH_INTRODUCED_IN_VERSION) void shouldBatchDecryptWithContext() { VaultTransitKeyCreationRequest request = VaultTransitKeyCreationRequest.builder() // .derived(true) // .build(); this.transitOperations.createKey("mykey", request); Plaintext one = Plaintext.of("one") .with(VaultTransitContext.builder().context("oneContext".getBytes()).build()); Plaintext two = Plaintext.of("two") .with(VaultTransitContext.builder().context("twoContext".getBytes()).build()); List<VaultEncryptionResult> encrypted = this.transitOperations.encrypt("mykey", Arrays.asList(one, two)); List<VaultDecryptionResult> decrypted = this.transitOperations.decrypt("mykey", Arrays.asList(encrypted.get(0).get(), encrypted.get(1).get())); assertThat(decrypted.get(0).get()).isEqualTo(one); assertThat(decrypted.get(1).get()).isEqualTo(two); } @Test @RequiresVaultVersion(BATCH_INTRODUCED_IN_VERSION) void shouldBatchDecryptWithWrongContext() { VaultTransitKeyCreationRequest request = VaultTransitKeyCreationRequest.builder() // .derived(true) // .build(); this.transitOperations.createKey("mykey", request); Plaintext one = Plaintext.of("one") .with(VaultTransitContext.builder().context("oneContext".getBytes()).build()); Plaintext two = Plaintext.of("two") .with(VaultTransitContext.builder().context("twoContext".getBytes()).build()); List<VaultEncryptionResult> encrypted = this.transitOperations.encrypt("mykey", Arrays.asList(one, two)); Ciphertext encryptedOne = encrypted.get(0).get(); Ciphertext decryptedTwo = encrypted.get(1).get(); Ciphertext tampered = decryptedTwo.with(encryptedOne.getContext()); try { List<VaultDecryptionResult> decrypted = this.transitOperations.decrypt("mykey", Arrays.asList(encryptedOne, tampered)); assertThat(decrypted.get(0).get()).isEqualTo(one); assertThat(decrypted.get(1).isSuccessful()).isEqualTo(false); assertThat(decrypted.get(1).getCause()).isInstanceOf(VaultException.class); } catch (VaultException e) { assertThat(e).hasMessageContaining("error"); // Vault 1.6 behavior is // different } } @Test @RequiresVaultVersion(BATCH_INTRODUCED_IN_VERSION) void shouldBatchDecryptEmptyPlaintext() { this.transitOperations.createKey("mykey"); Ciphertext empty = this.transitOperations.encrypt("mykey", Plaintext.empty()); List<VaultDecryptionResult> decrypted = this.transitOperations.decrypt("mykey", Collections.singletonList(empty)); assertThat(decrypted.get(0).getAsString()).isEqualTo(""); } @Test @RequiresVaultVersion(BATCH_INTRODUCED_IN_VERSION) void shouldBatchDecryptEmptyPlaintextWithContext() { VaultTransitKeyCreationRequest request = VaultTransitKeyCreationRequest.builder() // .derived(true) // .build(); this.transitOperations.createKey("mykey", request); Plaintext empty = Plaintext.empty() .with(VaultTransitContext.builder().context("oneContext".getBytes()).build()); List<VaultEncryptionResult> encrypted = this.transitOperations.encrypt("mykey", Collections.singletonList(empty)); List<VaultDecryptionResult> decrypted = this.transitOperations.decrypt("mykey", Collections.singletonList(encrypted.get(0).get())); assertThat(decrypted.get(0).get()).isEqualTo(empty); } @Test @RequiresVaultVersion(SIGN_VERIFY_INTRODUCED_IN_VERSION) void generateHmacShouldCreateHmac() { String keyName = createEcdsaP256Key(); Hmac hmac = this.transitOperations.getHmac(keyName, Plaintext.of("hello-world")); assertThat(hmac.getHmac()).isNotEmpty(); } @Test @RequiresVaultVersion(SIGN_VERIFY_INTRODUCED_IN_VERSION) void generateHmacShouldCreateHmacForRotatedKey() { String keyName = createEcdsaP256Key(); this.transitOperations.rotate(keyName); VaultHmacRequest request = VaultHmacRequest.builder().plaintext(Plaintext.of("hello-world")).keyVersion(2) .build(); Hmac hmac = this.transitOperations.getHmac(keyName, request); assertThat(hmac.getHmac()).isNotEmpty(); } @Test @RequiresVaultVersion(SIGN_VERIFY_INTRODUCED_IN_VERSION) void generateHmacWithCustomAlgorithmShouldCreateHmac() { String keyName = createEcdsaP256Key(); VaultHmacRequest request = VaultHmacRequest.builder().plaintext(Plaintext.of("hello-world")) .algorithm("sha2-512").build(); Hmac hmac = this.transitOperations.getHmac(keyName, request); assertThat(hmac.getHmac()).isNotEmpty(); } @Test void generateHmacWithInvalidAlgorithmShouldFail() { String keyName = createEcdsaP256Key(); VaultHmacRequest request = VaultHmacRequest.builder().plaintext(Plaintext.of("hello-world")) .algorithm("blah-512").build(); assertThatExceptionOfType(VaultException.class) .isThrownBy(() -> this.transitOperations.getHmac(keyName, request)); } @Test @RequiresVaultVersion(SIGN_VERIFY_INTRODUCED_IN_VERSION) void signShouldCreateSignature() { String keyName = createEcdsaP256Key(); Signature signature = this.transitOperations.sign(keyName, Plaintext.of("hello-world")); assertThat(signature.getSignature()).isNotEmpty(); } @Test @RequiresVaultVersion(ED25519_INTRODUCED_IN_VERSION) void signShouldCreateSignatureUsingEd25519() { VaultTransitKeyCreationRequest keyCreationRequest = VaultTransitKeyCreationRequest.ofKeyType("ed25519"); this.transitOperations.createKey("ed-key", keyCreationRequest); Signature signature = this.transitOperations.sign("ed-key", Plaintext.of("hello-world")); assertThat(signature.getSignature()).isNotEmpty(); } @Test void signWithInvalidKeyFormatShouldFail() { this.transitOperations.createKey("mykey"); assertThatExceptionOfType(VaultException.class) .isThrownBy(() -> this.transitOperations.sign("mykey", Plaintext.of("hello-world"))); } @Test @RequiresVaultVersion(SIGN_VERIFY_INTRODUCED_IN_VERSION) void signWithCustomAlgorithmShouldCreateSignature() { String keyName = createEcdsaP256Key(); Plaintext plaintext = Plaintext.of("hello-world"); VaultSignRequest request = VaultSignRequest.builder().plaintext(plaintext).hashAlgorithm("sha2-512").build(); Signature signature = this.transitOperations.sign(keyName, request); assertThat(signature.getSignature()).isNotEmpty(); } @Test @RequiresVaultVersion(SIGN_VERIFY_INTRODUCED_IN_VERSION) void shouldVerifyValidSignature() { String keyName = createEcdsaP256Key(); Plaintext plaintext = Plaintext.of("hello-world"); Signature signature = this.transitOperations.sign(keyName, plaintext); boolean valid = this.transitOperations.verify(keyName, plaintext, signature); assertThat(valid).isTrue(); } @Test @RequiresVaultVersion(SIGN_VERIFY_INTRODUCED_IN_VERSION) void shouldVerifyValidHmac() { String keyName = createEcdsaP256Key(); Plaintext plaintext = Plaintext.of("hello-world"); Hmac hmac = this.transitOperations.getHmac(keyName, plaintext); SignatureValidation valid = this.transitOperations.verify(keyName, VaultSignatureVerificationRequest.create(plaintext, hmac)); assertThat(valid).isEqualTo(SignatureValidation.valid()); } @Test @RequiresVaultVersion(SIGN_VERIFY_INTRODUCED_IN_VERSION) void shouldVerifyValidSignatureWithCustomAlgorithm() { String keyName = createEcdsaP256Key(); Plaintext plaintext = Plaintext.of("hello-world"); VaultSignRequest request = VaultSignRequest.builder().plaintext(plaintext).hashAlgorithm("sha2-512").build(); Signature signature = this.transitOperations.sign(keyName, request); VaultSignatureVerificationRequest verificationRequest = VaultSignatureVerificationRequest.builder() .hashAlgorithm("sha2-512").plaintext(plaintext).signature(signature).build(); SignatureValidation valid = this.transitOperations.verify(keyName, verificationRequest); assertThat(valid).isEqualTo(SignatureValidation.valid()); } @Test @RequiresVaultVersion(KEY_EXPORT_INTRODUCED_IN_VERSION) void shouldCreateNewExportableKey() { VaultTransitOperations vaultTransitOperations = this.vaultOperations.opsForTransit(); VaultTransitKeyCreationRequest vaultTransitKeyCreationRequest = VaultTransitKeyCreationRequest.builder() .exportable(true).derived(true).build(); vaultTransitOperations.createKey("export-test", vaultTransitKeyCreationRequest); VaultTransitKey vaultTransitKey = vaultTransitOperations.getKey("export-test"); assertThat(vaultTransitKey.getName()).isEqualTo("export-test"); assertThat(vaultTransitKey.isExportable()).isTrue(); } @Test @RequiresVaultVersion(KEY_EXPORT_INTRODUCED_IN_VERSION) void shouldCreateNotExportableKeyByDefault() { VaultTransitOperations vaultTransitOperations = this.vaultOperations.opsForTransit(); vaultTransitOperations.createKey("no-export"); VaultTransitKey vaultTransitKey = vaultTransitOperations.getKey("no-export"); assertThat(vaultTransitKey.getName()).isEqualTo("no-export"); assertThat(vaultTransitKey.isExportable()).isFalse(); } @Test @RequiresVaultVersion(KEY_EXPORT_INTRODUCED_IN_VERSION) void shouldExportEncryptionKey() { this.vaultOperations.write("transit/keys/export", Collections.singletonMap("exportable", true)); RawTransitKey rawTransitKey = this.transitOperations.exportKey("export", TransitKeyType.ENCRYPTION_KEY); assertThat(rawTransitKey.getName()).isEqualTo("export"); assertThat(rawTransitKey.getKeys()).isNotEmpty(); assertThat(rawTransitKey.getKeys().get("1")).isNotBlank(); } @Test @RequiresVaultVersion(KEY_EXPORT_INTRODUCED_IN_VERSION) void shouldNotAllowExportSigningKey() { this.vaultOperations.write("transit/keys/export", Collections.singletonMap("exportable", true)); assertThatExceptionOfType(VaultException.class) .isThrownBy(() -> this.transitOperations.exportKey("export", TransitKeyType.SIGNING_KEY)); } @Test @RequiresVaultVersion(KEY_EXPORT_INTRODUCED_IN_VERSION) void shouldExportHmacKey() { this.vaultOperations.write("transit/keys/export", Collections.singletonMap("exportable", true)); RawTransitKey rawTransitKey = this.transitOperations.exportKey("export", TransitKeyType.HMAC_KEY); assertThat(rawTransitKey.getName()).isEqualTo("export"); assertThat(rawTransitKey.getKeys()).isNotEmpty(); assertThat(rawTransitKey.getKeys().get("1")).isNotBlank(); } @Test @RequiresVaultVersion(KEY_EXPORT_INTRODUCED_IN_VERSION) void shouldExportEcDsaKey() { VaultTransitOperations transitOperations = this.vaultOperations.opsForTransit(); VaultTransitKeyCreationRequest request = VaultTransitKeyCreationRequest.builder().type("ecdsa-p256") .exportable(true).build(); transitOperations.createKey("ecdsa-key", request); RawTransitKey hmacKey = transitOperations.exportKey("ecdsa-key", TransitKeyType.HMAC_KEY); RawTransitKey signingKey = transitOperations.exportKey("ecdsa-key", TransitKeyType.SIGNING_KEY); assertThat(hmacKey.getKeys()).isNotEmpty(); assertThat(signingKey.getKeys()).isNotEmpty(); } @Test @RequiresVaultVersion(ED25519_INTRODUCED_IN_VERSION) void shouldExportEdKey() { VaultTransitOperations transitOperations = this.vaultOperations.opsForTransit(); VaultTransitKeyCreationRequest request = VaultTransitKeyCreationRequest.builder().type("ed25519") .exportable(true).build(); transitOperations.createKey("ed-key", request); RawTransitKey hmacKey = transitOperations.exportKey("ed-key", TransitKeyType.HMAC_KEY); RawTransitKey signingKey = transitOperations.exportKey("ed-key", TransitKeyType.SIGNING_KEY); assertThat(hmacKey.getKeys()).isNotEmpty(); assertThat(signingKey.getKeys()).isNotEmpty(); } private String createEcdsaP256Key() { String keyName = "ecdsa-key"; VaultTransitKeyCreationRequest keyCreationRequest = VaultTransitKeyCreationRequest.ofKeyType("ecdsa-p256"); this.transitOperations.createKey(keyName, keyCreationRequest); return keyName; } }
32.349823
111
0.766066
3bb321b96d89075ebdb2bf4fd9f14ea34fcb1380
6,211
package com.consol.citrus.simulator.ws; import org.mockito.Mockito; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.core.io.ClassPathResource; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import static org.mockito.Mockito.*; /** * @author Christoph Deppisch */ public class WsdlScenarioGeneratorTest { private ConfigurableListableBeanFactory beanFactory = Mockito.mock(ConfigurableListableBeanFactory.class); private DefaultListableBeanFactory beanRegistry = Mockito.mock(DefaultListableBeanFactory.class); private String input = String.format("<v1:TestRequest name=\"string\" id=\"100\" flag=\"false\" xmlns:v1=\"http://www.citrusframework.org/schema/samples/TestService/v1\">%n" + " <v1:name>string</v1:name>%n" + " <v1:id>100</v1:id>%n" + " <v1:flag>true</v1:flag>%n" + " <v1:restricted>stringstri</v1:restricted>%n" + "</v1:TestRequest>"); private String output = String.format("<v1:TestResponse name=\"string\" id=\"100\" flag=\"false\" xmlns:v1=\"http://www.citrusframework.org/schema/samples/TestService/v1\">%n" + " <v1:name>string</v1:name>%n" + " <v1:id>100</v1:id>%n" + " <v1:flag>true</v1:flag>%n" + " <v1:restricted>stringstri</v1:restricted>%n" + "</v1:TestResponse>"); @Test(dataProvider = "wsdlDataProvider") public void testGenerateScenarios(String scenarioName, WsdlScenarioGenerator.WsdlScenarioNamingStrategy namingStrategy, String soapAction, String input, String output) { WsdlScenarioGenerator scenarioGenerator = new WsdlScenarioGenerator(new ClassPathResource("schema/TestService.wsdl")); reset(beanFactory); scenarioGenerator.setNamingStrategy(namingStrategy); doAnswer(invocation -> { WsdlOperationScenario scenario = (WsdlOperationScenario) invocation.getArguments()[1]; Assert.assertEquals(scenario.getSoapAction(), soapAction); Assert.assertEquals(scenario.getInput(), input); Assert.assertEquals(scenario.getOutput(), output); return null; }).when(beanFactory).registerSingleton(eq(scenarioName), any(WsdlOperationScenario.class)); scenarioGenerator.postProcessBeanFactory(beanFactory); verify(beanFactory).registerSingleton(eq(scenarioName), any(WsdlOperationScenario.class)); } @Test(dataProvider = "wsdlDataProvider") public void testGenerateScenariosWithRegistry(String scenarioName, WsdlScenarioGenerator.WsdlScenarioNamingStrategy namingStrategy, String soapAction, String input, String output) { WsdlScenarioGenerator scenarioGenerator = new WsdlScenarioGenerator(new ClassPathResource("schema/TestService.wsdl")); reset(beanRegistry); scenarioGenerator.setNamingStrategy(namingStrategy); doAnswer(invocation -> { BeanDefinition scenario = (BeanDefinition) invocation.getArguments()[1]; Assert.assertEquals(scenario.getPropertyValues().get("soapAction"), soapAction); Assert.assertEquals(scenario.getPropertyValues().get("input"), input); Assert.assertEquals(scenario.getPropertyValues().get("output"), output); Assert.assertNull(scenario.getPropertyValues().get("inboundDataDictionary")); Assert.assertNull(scenario.getPropertyValues().get("outboundDataDictionary")); return null; }).when(beanRegistry).registerBeanDefinition(eq(scenarioName), any(BeanDefinition.class)); scenarioGenerator.postProcessBeanFactory(beanRegistry); verify(beanRegistry).registerBeanDefinition(eq(scenarioName), any(BeanDefinition.class)); } @Test public void testGenerateScenariosWithDataDictionaries() { WsdlScenarioGenerator scenarioGenerator = new WsdlScenarioGenerator(new ClassPathResource("schema/TestService.wsdl")); reset(beanRegistry); BeanDefinition inboundXmlDataDictionary = Mockito.mock(BeanDefinition.class); BeanDefinition outboundXmlDataDictionary = Mockito.mock(BeanDefinition.class); when(beanRegistry.containsBeanDefinition("inboundXmlDataDictionary")).thenReturn(true); when(beanRegistry.containsBeanDefinition("outboundXmlDataDictionary")).thenReturn(true); when(beanRegistry.getBeanDefinition("inboundXmlDataDictionary")).thenReturn(inboundXmlDataDictionary); when(beanRegistry.getBeanDefinition("outboundXmlDataDictionary")).thenReturn(outboundXmlDataDictionary); doAnswer(invocation -> { BeanDefinition scenario = (BeanDefinition) invocation.getArguments()[1]; Assert.assertEquals(scenario.getPropertyValues().get("soapAction"), "/TestService/test"); Assert.assertEquals(scenario.getPropertyValues().get("input"), input); Assert.assertEquals(scenario.getPropertyValues().get("output"), output); Assert.assertNotNull(scenario.getPropertyValues().get("inboundDataDictionary")); Assert.assertNotNull(scenario.getPropertyValues().get("outboundDataDictionary")); return null; }).when(beanRegistry).registerBeanDefinition(eq("TestRequest"), any(BeanDefinition.class)); scenarioGenerator.postProcessBeanFactory(beanRegistry); verify(beanRegistry).registerBeanDefinition(eq("TestRequest"), any(BeanDefinition.class)); } @DataProvider public Object[][] wsdlDataProvider() { return new Object[][] { new Object[] { "TestRequest", WsdlScenarioGenerator.WsdlScenarioNamingStrategy.INPUT, "/TestService/test", input, output }, new Object[] { "test", WsdlScenarioGenerator.WsdlScenarioNamingStrategy.OPERATION, "/TestService/test", input, output }, new Object[] { "/TestService/test", WsdlScenarioGenerator.WsdlScenarioNamingStrategy.SOAP_ACTION, "/TestService/test", input, output } }; } }
49.688
185
0.718242
73e33ea3a0b29690acf0fc574b0fe8719213b077
2,792
/*-------------------------------------------------------------------------+ | | | Copyright 2005-2011 The ConQAT Project | | | | Licensed under the Apache License, Version 2.0 (the "License"); | | you may not use this file except in compliance with the License. | | You may obtain a copy of the License at | | | | http://www.apache.org/licenses/LICENSE-2.0 | | | | Unless required by applicable law or agreed to in writing, software | | distributed under the License is distributed on an "AS IS" BASIS, | | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | | See the License for the specific language governing permissions and | | limitations under the License. | +-------------------------------------------------------------------------*/ package org.conqat.engine.java.javadoc; import org.conqat.engine.core.core.ConQATException; import org.conqat.engine.java.resource.IJavaElement; import com.sun.javadoc.ClassDoc; import com.sun.javadoc.FieldDoc; import com.sun.javadoc.MethodDoc; import com.sun.javadoc.ProgramElementDoc; /** * Base class for analyzer that work for all comment types. * * @author $Author: kinnen $ * @version $Rev: 41751 $ * @ConQAT.Rating GREEN Hash: EE7F495ACF50F38C5B8C9E5411D4093A */ /* package */abstract class ProgramElementDocAnalyzerBase extends CommentAnalyzerBase implements IProgramElementDocAnalyzer { /** {@inheritDoc} */ @Override public IProgramElementDocAnalyzer process() { return this; } /** Forwards to {@link #analyze(ProgramElementDoc, IJavaElement)}. */ @Override public void analyze(MethodDoc docElement, IJavaElement element) throws ConQATException { analyze((ProgramElementDoc) docElement, element); } /** Forwards to {@link #analyze(ProgramElementDoc, IJavaElement)}. */ @Override public void analyze(ClassDoc docElement, IJavaElement element) throws ConQATException { analyze((ProgramElementDoc) docElement, element); } /** Forwards to {@link #analyze(ProgramElementDoc, IJavaElement)}. */ @Override public void analyze(FieldDoc docElement, IJavaElement element) throws ConQATException { analyze((ProgramElementDoc) docElement, element); } /** Template method for analyzing a comment. */ public abstract void analyze(ProgramElementDoc docElement, IJavaElement element) throws ConQATException; }
40.463768
76
0.590258
cd808bdf6a43d5343b1706eaf1dac5ae8b262cba
1,713
package cn.rkang.wxgate.ctrl.wxacc; import org.apache.log4j.Logger; import org.springframework.data.mongodb.core.MongoTemplate; import org.zkoss.bind.BindUtils; import org.zkoss.bind.annotation.AfterCompose; import org.zkoss.bind.annotation.Command; import org.zkoss.bind.annotation.ContextParam; import org.zkoss.bind.annotation.ContextType; import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.event.Event; import org.zkoss.zk.ui.event.EventListener; import org.zkoss.zk.ui.select.Selectors; import org.zkoss.zk.ui.select.annotation.VariableResolver; import org.zkoss.zk.ui.select.annotation.WireVariable; import org.zkoss.zkplus.spring.DelegatingVariableResolver; import org.zkoss.zul.Messagebox; import org.zkoss.zul.Window; import cn.rkang.wxgate.model.WxAcc; @VariableResolver(DelegatingVariableResolver.class) public class AddAccDialogCtrl { static Logger logger = Logger.getLogger(AddAccDialogCtrl.class); @WireVariable private MongoTemplate mongoTemplate; private WxAcc form; Window thisWin; @AfterCompose public void afterCompose(@ContextParam(ContextType.VIEW) Component view) { thisWin = (Window) view; Selectors.wireComponents(view, this, false); Selectors.wireEventListeners(view, this); form = new WxAcc(); } @Command public void onSave() { mongoTemplate.save(form); Messagebox.show("保存成功", "提示", Messagebox.OK, Messagebox.INFORMATION, new EventListener<Event>() { @Override public void onEvent(Event event) throws Exception { BindUtils.postGlobalCommand(null, null, "wxAccCtrlRefreshAccList", null); thisWin.detach(); } }); } @Command public void onCancel() { thisWin.detach(); } public WxAcc getForm() { return form; } }
26.765625
99
0.772329
887ab3606535693c0bdd04c923bfd49bf7161bf1
11,681
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.reactive.result.condition; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import org.springframework.http.MediaType; import org.springframework.web.accept.ContentNegotiationManager; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.cors.reactive.CorsUtils; import org.springframework.web.reactive.accept.HeaderContentTypeResolver; import org.springframework.web.reactive.accept.RequestedContentTypeResolver; import org.springframework.web.reactive.accept.RequestedContentTypeResolverBuilder; import org.springframework.web.server.NotAcceptableStatusException; import org.springframework.web.server.ServerWebExchange; /** * A logical disjunction (' || ') request condition to match a request's 'Accept' header * to a list of media type expressions. Two kinds of media type expressions are * supported, which are described in {@link RequestMapping#produces()} and * {@link RequestMapping#headers()} where the header name is 'Accept'. * Regardless of which syntax is used, the semantics are the same. * * @author Rossen Stoyanchev * @since 5.0 */ public final class ProducesRequestCondition extends AbstractRequestCondition<ProducesRequestCondition> { private final static ProducesRequestCondition PRE_FLIGHT_MATCH = new ProducesRequestCondition(); private final List<ProduceMediaTypeExpression> MEDIA_TYPE_ALL_LIST = Collections.singletonList(new ProduceMediaTypeExpression("*/*")); private final List<ProduceMediaTypeExpression> expressions; private final RequestedContentTypeResolver contentTypeResolver; /** * Creates a new instance from "produces" expressions. If 0 expressions * are provided in total, this condition will match to any request. * @param produces expressions with syntax defined by {@link RequestMapping#produces()} */ public ProducesRequestCondition(String... produces) { this(produces, null); } /** * Creates a new instance with "produces" and "header" expressions. "Header" * expressions where the header name is not 'Accept' or have no header value * defined are ignored. If 0 expressions are provided in total, this condition * will match to any request. * @param produces expressions with syntax defined by {@link RequestMapping#produces()} * @param headers expressions with syntax defined by {@link RequestMapping#headers()} */ public ProducesRequestCondition(String[] produces, String[] headers) { this(produces, headers, null); } /** * Same as {@link #ProducesRequestCondition(String[], String[])} but also * accepting a {@link ContentNegotiationManager}. * @param produces expressions with syntax defined by {@link RequestMapping#produces()} * @param headers expressions with syntax defined by {@link RequestMapping#headers()} * @param resolver used to determine requested content type */ public ProducesRequestCondition(String[] produces, String[] headers, RequestedContentTypeResolver resolver) { this.expressions = new ArrayList<>(parseExpressions(produces, headers)); Collections.sort(this.expressions); this.contentTypeResolver = (resolver != null ? resolver : new HeaderContentTypeResolver()); } /** * Private constructor with already parsed media type expressions. */ private ProducesRequestCondition(Collection<ProduceMediaTypeExpression> expressions, RequestedContentTypeResolver resolver) { this.expressions = new ArrayList<>(expressions); Collections.sort(this.expressions); this.contentTypeResolver = (resolver != null ? resolver : new RequestedContentTypeResolverBuilder().build()); } private Set<ProduceMediaTypeExpression> parseExpressions(String[] produces, String[] headers) { Set<ProduceMediaTypeExpression> result = new LinkedHashSet<>(); if (headers != null) { for (String header : headers) { HeadersRequestCondition.HeaderExpression expr = new HeadersRequestCondition.HeaderExpression(header); if ("Accept".equalsIgnoreCase(expr.name)) { for (MediaType mediaType : MediaType.parseMediaTypes(expr.value)) { result.add(new ProduceMediaTypeExpression(mediaType, expr.isNegated)); } } } } if (produces != null) { for (String produce : produces) { result.add(new ProduceMediaTypeExpression(produce)); } } return result; } /** * Return the contained "produces" expressions. */ public Set<MediaTypeExpression> getExpressions() { return new LinkedHashSet<>(this.expressions); } /** * Return the contained producible media types excluding negated expressions. */ public Set<MediaType> getProducibleMediaTypes() { Set<MediaType> result = new LinkedHashSet<>(); for (ProduceMediaTypeExpression expression : this.expressions) { if (!expression.isNegated()) { result.add(expression.getMediaType()); } } return result; } /** * Whether the condition has any media type expressions. */ public boolean isEmpty() { return this.expressions.isEmpty(); } @Override protected List<ProduceMediaTypeExpression> getContent() { return this.expressions; } @Override protected String getToStringInfix() { return " || "; } /** * Returns the "other" instance if it has any expressions; returns "this" * instance otherwise. Practically that means a method-level "produces" * overrides a type-level "produces" condition. */ @Override public ProducesRequestCondition combine(ProducesRequestCondition other) { return (!other.expressions.isEmpty() ? other : this); } /** * Checks if any of the contained media type expressions match the given * request 'Content-Type' header and returns an instance that is guaranteed * to contain matching expressions only. The match is performed via * {@link MediaType#isCompatibleWith(MediaType)}. * @param exchange the current exchange * @return the same instance if there are no expressions; * or a new condition with matching expressions; * or {@code null} if no expressions match. */ @Override public ProducesRequestCondition getMatchingCondition(ServerWebExchange exchange) { if (CorsUtils.isPreFlightRequest(exchange.getRequest())) { return PRE_FLIGHT_MATCH; } if (isEmpty()) { return this; } Set<ProduceMediaTypeExpression> result = new LinkedHashSet<>(expressions); for (Iterator<ProduceMediaTypeExpression> iterator = result.iterator(); iterator.hasNext();) { ProduceMediaTypeExpression expression = iterator.next(); if (!expression.match(exchange)) { iterator.remove(); } } return (result.isEmpty()) ? null : new ProducesRequestCondition(result, this.contentTypeResolver); } /** * Compares this and another "produces" condition as follows: * <ol> * <li>Sort 'Accept' header media types by quality value via * {@link MediaType#sortByQualityValue(List)} and iterate the list. * <li>Get the first index of matching media types in each "produces" * condition first matching with {@link MediaType#equals(Object)} and * then with {@link MediaType#includes(MediaType)}. * <li>If a lower index is found, the condition at that index wins. * <li>If both indexes are equal, the media types at the index are * compared further with {@link MediaType#SPECIFICITY_COMPARATOR}. * </ol> * <p>It is assumed that both instances have been obtained via * {@link #getMatchingCondition(ServerWebExchange)} and each instance * contains the matching producible media type expression only or * is otherwise empty. */ @Override public int compareTo(ProducesRequestCondition other, ServerWebExchange exchange) { try { List<MediaType> acceptedMediaTypes = getAcceptedMediaTypes(exchange); for (MediaType acceptedMediaType : acceptedMediaTypes) { int thisIndex = this.indexOfEqualMediaType(acceptedMediaType); int otherIndex = other.indexOfEqualMediaType(acceptedMediaType); int result = compareMatchingMediaTypes(this, thisIndex, other, otherIndex); if (result != 0) { return result; } thisIndex = this.indexOfIncludedMediaType(acceptedMediaType); otherIndex = other.indexOfIncludedMediaType(acceptedMediaType); result = compareMatchingMediaTypes(this, thisIndex, other, otherIndex); if (result != 0) { return result; } } return 0; } catch (NotAcceptableStatusException ex) { // should never happen throw new IllegalStateException("Cannot compare without having any requested media types", ex); } } private List<MediaType> getAcceptedMediaTypes(ServerWebExchange exchange) throws NotAcceptableStatusException { List<MediaType> mediaTypes = this.contentTypeResolver.resolveMediaTypes(exchange); return mediaTypes.isEmpty() ? Collections.singletonList(MediaType.ALL) : mediaTypes; } private int indexOfEqualMediaType(MediaType mediaType) { for (int i = 0; i < getExpressionsToCompare().size(); i++) { MediaType currentMediaType = getExpressionsToCompare().get(i).getMediaType(); if (mediaType.getType().equalsIgnoreCase(currentMediaType.getType()) && mediaType.getSubtype().equalsIgnoreCase(currentMediaType.getSubtype())) { return i; } } return -1; } private int indexOfIncludedMediaType(MediaType mediaType) { for (int i = 0; i < getExpressionsToCompare().size(); i++) { if (mediaType.includes(getExpressionsToCompare().get(i).getMediaType())) { return i; } } return -1; } private int compareMatchingMediaTypes(ProducesRequestCondition condition1, int index1, ProducesRequestCondition condition2, int index2) { int result = 0; if (index1 != index2) { result = index2 - index1; } else if (index1 != -1) { ProduceMediaTypeExpression expr1 = condition1.getExpressionsToCompare().get(index1); ProduceMediaTypeExpression expr2 = condition2.getExpressionsToCompare().get(index2); result = expr1.compareTo(expr2); result = (result != 0) ? result : expr1.getMediaType().compareTo(expr2.getMediaType()); } return result; } /** * Return the contained "produces" expressions or if that's empty, a list * with a {@code MediaType_ALL} expression. */ private List<ProduceMediaTypeExpression> getExpressionsToCompare() { return (this.expressions.isEmpty() ? MEDIA_TYPE_ALL_LIST : this.expressions); } /** * Parses and matches a single media type expression to a request's 'Accept' header. */ class ProduceMediaTypeExpression extends AbstractMediaTypeExpression { ProduceMediaTypeExpression(MediaType mediaType, boolean negated) { super(mediaType, negated); } ProduceMediaTypeExpression(String expression) { super(expression); } @Override protected boolean matchMediaType(ServerWebExchange exchange) throws NotAcceptableStatusException { List<MediaType> acceptedMediaTypes = getAcceptedMediaTypes(exchange); for (MediaType acceptedMediaType : acceptedMediaTypes) { if (getMediaType().isCompatibleWith(acceptedMediaType)) { return true; } } return false; } } }
36.276398
111
0.750193
2e6602ca86a5229652d77fb0f4232491b384e4fd
4,736
package eu.bcvsolutions.idm.connector.salesforce; import org.identityconnectors.common.StringUtil; import org.identityconnectors.common.security.GuardedString; import org.identityconnectors.framework.common.exceptions.ConfigurationException; import org.identityconnectors.framework.spi.AbstractConfiguration; import org.identityconnectors.framework.spi.ConfigurationProperty; /** * @author Roman Kucera */ public class SalesforceConfiguration extends AbstractConfiguration { private String url; private String authUrl; private String grandType; private GuardedString clientId; private GuardedString clientSecret; private String username; private GuardedString password; private GuardedString token; private int validity; private Boolean newTokenBeforeRequest; @ConfigurationProperty(displayMessageKey = "salesforce.url.display", helpMessageKey = "salesforce.url.help", order = 1, required = true) public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } @ConfigurationProperty(displayMessageKey = "salesforce.auth.display", helpMessageKey = "salesforce.auth.help", order = 2, required = true) public String getAuthUrl() { return authUrl; } public void setAuthUrl(String authUrl) { this.authUrl = authUrl; } @ConfigurationProperty(displayMessageKey = "salesforce.grant.type.display", helpMessageKey = "salesforce.grant.type.help", order = 3, required = true) public String getGrandType() { return grandType; } public void setGrandType(String grandType) { this.grandType = grandType; } @ConfigurationProperty(displayMessageKey = "salesforce.client.id.display", helpMessageKey = "salesforce.client.id.help", order = 4, confidential = true, required = true) public GuardedString getClientId() { return clientId; } public void setClientId(GuardedString clientId) { this.clientId = clientId; } @ConfigurationProperty(displayMessageKey = "salesforce.client.secret.display", helpMessageKey = "salesforce.client.secret.help", order = 5, confidential = true, required = true) public GuardedString getClientSecret() { return clientSecret; } public void setClientSecret(GuardedString clientSecret) { this.clientSecret = clientSecret; } @ConfigurationProperty(displayMessageKey = "salesforce.username.display", helpMessageKey = "salesforce.username.help", order = 6, required = true) public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @ConfigurationProperty(displayMessageKey = "salesforce.password.display", helpMessageKey = "salesforce.password.help", order = 7, confidential = true, required = true) public GuardedString getPassword() { return password; } public void setPassword(GuardedString password) { this.password = password; } @ConfigurationProperty(displayMessageKey = "salesforce.password.token.display", helpMessageKey = "salesforce.password.token.help", order = 8, confidential = true, required = true) public GuardedString getToken() { return token; } public void setToken(GuardedString token) { this.token = token; } @ConfigurationProperty(displayMessageKey = "salesforce.validity.display", helpMessageKey = "salesforce.validity.help", order = 9, required = true) public int getValidity() { return validity; } public void setValidity(int validity) { this.validity = validity; } @ConfigurationProperty(displayMessageKey = "salesforce.new.token.display", helpMessageKey = "salesforce.new.token.help", order = 10) public Boolean getNewTokenBeforeRequest() { return newTokenBeforeRequest; } public void setNewTokenBeforeRequest(Boolean newTokenBeforeRequest) { this.newTokenBeforeRequest = newTokenBeforeRequest; } @Override public void validate() { if (StringUtil.isBlank(url)) { throw new ConfigurationException("URL must not be blank!"); } if (StringUtil.isBlank(authUrl)) { throw new ConfigurationException("Auth URL must not be blank!"); } if (StringUtil.isBlank(grandType)) { throw new ConfigurationException("Grand type must not be blank!"); } if (clientId == null) { throw new ConfigurationException("Client id must not be blank!"); } if (clientSecret == null) { throw new ConfigurationException("Client secret must not be blank!"); } if (StringUtil.isBlank(username)) { throw new ConfigurationException("Username must not be blank!"); } if (password == null) { throw new ConfigurationException("Password must not be blank!"); } if (token == null) { throw new ConfigurationException("Token must not be blank!"); } } public String getMessage(String key) { return getConnectorMessages().format(key, key); } }
30.165605
102
0.755068
4f227ccb6d476661303147592fa107d8d6ed1a34
3,770
// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.hosted.node.admin.task.util.file; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.time.Instant; import java.util.Optional; /** * A snapshot of the attributes of the file for a given path, and file content if it is a regular file. * * @author hakonhall */ public class FileSnapshot { private final Path path; private final Optional<FileAttributes> attributes; private final Optional<byte[]> content; public static FileSnapshot forPath(Path path) { return forNonExistingFile(path).snapshot(); } /** Guaranteed to not throw any exceptions. */ public static FileSnapshot forNonExistingFile(Path path) { return new FileSnapshot(path, Optional.empty(), Optional.empty()); } private static FileSnapshot forRegularFile(Path path, FileAttributes attributes, byte[] content) { if (!attributes.isRegularFile()) throw new IllegalArgumentException(path + " is not a regular file"); return new FileSnapshot(path, Optional.of(attributes), Optional.of(content)); } private static FileSnapshot forOtherFile(Path path, FileAttributes attributes) { if (attributes.isRegularFile()) throw new IllegalArgumentException(path + " is a regular file"); return new FileSnapshot(path, Optional.of(attributes), Optional.empty()); } private FileSnapshot(Path path, Optional<FileAttributes> attributes, Optional<byte[]> content) { this.path = path; this.attributes = attributes; this.content = content; } public Path path() { return path; } /** Whether there was a file (or directory) at path. */ public boolean exists() { return attributes.isPresent(); } /** Returns the file attributes if the file exists. */ public Optional<FileAttributes> attributes() { return attributes; } /** Returns the file content if the file exists and is a regular file. */ public Optional<byte[]> content() { return content; } /** Returns the file UTF-8 content if it exists and is a regular file. */ public Optional<String> utf8Content() { return content.map(c -> new String(c, StandardCharsets.UTF_8)); } /** Returns an up-to-date snapshot of the path, possibly {@code this} if last modified time has not changed. */ public FileSnapshot snapshot() { Optional<FileAttributes> currentAttributes = new UnixPath(path).getAttributesIfExists(); if (currentAttributes.isPresent()) { // 'this' may still be valid, depending on last modified times. if (attributes.isPresent()) { Instant previousModifiedTime = attributes.get().lastModifiedTime(); Instant currentModifiedTime = currentAttributes.get().lastModifiedTime(); if (currentModifiedTime.compareTo(previousModifiedTime) <= 0) { return this; } } if (currentAttributes.get().isRegularFile()) { Optional<byte[]> content = IOExceptionUtil.ifExists(() -> Files.readAllBytes(path)); return content.map(bytes -> FileSnapshot.forRegularFile(path, currentAttributes.get(), bytes)) // File was removed after getting attributes and before getting content. .orElseGet(() -> FileSnapshot.forNonExistingFile(path)); } else { return FileSnapshot.forOtherFile(path, currentAttributes.get()); } } else { return attributes.isPresent() ? FileSnapshot.forNonExistingFile(path) : this /* avoid allocation */; } } }
44.880952
115
0.669761
90d829338c529b67413c64654d8de7ede7177a01
3,587
package streams; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collection; import java.util.IntSummaryStatistics; import java.util.List; import java.util.Map; import java.util.Random; import java.util.function.Function; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.LongStream; import java.util.stream.Stream; import invoicing.utils.Tuple; public class StreamDemo { public static void main(String[] args) throws IOException { // Creating streams Stream<String> streamEmpty = Stream.empty(); // streamEmpty.forEach(System.out::println); Collection<String> collection = Arrays.asList("a", "b", "c"); Stream<String> streamOfCollection = collection.parallelStream().sequential(); // streamOfCollection.forEach(System.out::println); Stream<String> streamOfArray = Stream.of("a", "b", "c", "d"); // streamOfArray.forEach(System.out::println); Stream<String> streamBuilder = Stream.<String>builder().add("a").add("b").add("c").build(); // streamBuilder.forEach(System.out::println); IntStream intStream = IntStream.range(1, 10); LongStream longStream = LongStream.rangeClosed(1, 15).limit(5); // intStream.forEach(System.out::println); System.out.println(); // longStream.forEach(System.out::println); Stream<Integer> streamIterated = Stream.iterate(40, n -> n + 2).limit(10); // streamIterated.forEach(System.out::println); Random rand = new Random(); Stream<String> streamGenerated = Stream.generate( () -> String.format("Element %d", rand.nextInt(100))).limit(10); // streamGenerated.forEach(System.out::println); IntStream streamOfChars = "IntStream is used".chars(); String result = streamOfChars.mapToObj(c -> String.valueOf((char)c)) .collect(Collectors.joining(", ")); // System.out.println(result); Stream<String> streamOfString = Pattern.compile(", ").splitAsStream(result); // System.out.println( streamOfString.collect(Collectors.joining()) ); Path path = Paths.get("src/streams/StreamDemo.java"); String fResult = Files.lines(path) // .map(l -> new Tuple<String, Integer>(l, 0)) .reduce(new Tuple<>("", 1), (acc, line) -> // accumulator new Tuple<>(acc.getProp1() + acc.getProp2() + ": " + line + "\n", acc.getProp2() + 1), (acc1, acc2) -> // combimner new Tuple<>(acc1.getProp1() + "\n" + acc2.getProp2(), 0) ).getProp1(); // System.out.println(fResult); StringBuilder resBuilder = Files.lines(path, Charset.forName("UTF-8")) // .collect(ArrayList::new, ArrayList::add, ArrayList::addAll); .map(String::toUpperCase) .collect(StringBuilder::new, (sb, line) -> sb.append(line).append(System.lineSeparator()), (sb1, sb2) -> sb1.append(sb2)); // StringBuilder sb = new StringBuilder(); // for(int i = 0; i < lines.size(); i++) { // sb.append(i + 1).append(": ").append(lines.get(i)).append(System.lineSeparator()); // } // System.out.println(resBuilder); List<String> listWithDuplicates = Arrays.asList("a", "bb", "ccccc", "d", "bb"); Map<String, Integer> mapResult = listWithDuplicates.stream().collect(Collectors.toMap(Function.identity(), String::length, (e1, e2) -> e2)); System.out.println(mapResult); IntSummaryStatistics stat = listWithDuplicates.stream().collect( Collectors.summarizingInt(s -> s.length())); System.out.println(stat); } }
34.490385
92
0.683858
4e13164cce7c8cd55cc90a5c0fb88a1ed63d2915
2,570
package net.kedare.iot.leds; import com.mashape.unirest.http.JsonNode; import com.mashape.unirest.http.exceptions.UnirestException; import net.kedare.iot.particle.ParticleException; import net.kedare.iot.particle.ParticleObject; import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; public class LedStrip extends ParticleObject { public static final int MAX_POWER = 100; public static final int MIN_POWER = 0; public static final int MAX_DELAY = 1000; public static final int MIN_DELAY = 0; public static Map<String, String> PROGRAMS = new HashMap<>(); LedStrip(String token, String deviceId, Logger logger) throws ParticleException { super(token, deviceId, logger); PROGRAMS.put("colorWipe", "Fixed custom color"); PROGRAMS.put("fadeCycle", "Cycle between 2 colors"); PROGRAMS.put("gradient", "Gradient between 2 colors"); PROGRAMS.put("rainbow", "Short color spectrum"); PROGRAMS.put("rainbowCycle", "Large color spectrum"); PROGRAMS.put("fullColorCycle", "Cycle between all colors"); PROGRAMS.put("randomDots", "Random dots (colors and positions)"); PROGRAMS.put("frozen", "Freeze to current state"); PROGRAMS.put("off", "Turn off"); } public JsonNode getMode() throws UnirestException { return this.get("mode"); } public JsonNode setMode(String program) throws UnirestException { HashMap<String, Object> params = new HashMap<>(); params.put("mode", program); return this.call("setMode", params); } public JsonNode getDelay() throws UnirestException { return this.get("wait"); } public JsonNode setDelay(int delay) throws UnirestException { HashMap<String, Object> params = new HashMap<>(); params.put("wait", delay); return this.call("setWait", params); } public JsonNode getPower() throws UnirestException { return this.get("power"); } public JsonNode setPower(int power) throws UnirestException { HashMap<String, Object> params = new HashMap<>(); params.put("power", power); return this.call("setPower", params); } public JsonNode getColor(int index) throws UnirestException { return this.get("color" + index); } public JsonNode setColor(int index, String color) throws UnirestException { HashMap<String, Object> params = new HashMap<>(); params.put("color" + index, color); return this.call("setColor" + index, params); } }
35.694444
85
0.670817
1c257034f60bc69dc0e69e900a91cfc238169404
263
package com.lxzh123.secrashapp; import android.app.Application; import com.lxzh123.secrash.SeCrash; public class MainApp extends Application { @Override public void onCreate() { super.onCreate(); SeCrash.install(); } }
18.785714
43
0.657795
860c8077cd71b3b4bb258857fe0625659e483c89
2,019
package dao; import bean.Endereco; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class EnderecoDAO { private Connection conexao; public EnderecoDAO(Connection conexao){ this.conexao=conexao; } public int create(Endereco end) throws SQLException { Statement stm = this.conexao.createStatement(); ResultSet rs; int fk=0; String sql = "INSERT INTO ENDERECO (FK_CIDADE,RUA,NUMERO,COMPLEMENTO,CEP,BAIRRO) VALUES ("+end.getFk_cidade()+",'"+end.getRua()+"',"+end.getNumero()+",'"+end.getComplemento()+"','"+end.getCep()+"','"+end.getBairro()+"')"; stm.executeUpdate(sql); sql = "SELECT ID FROM ENDERECO ORDER BY ID DESC"; rs = stm.executeQuery(sql); while(rs.next()){ fk = rs.getInt("id"); break;} return fk; } public ResultSet retrive (int id) throws SQLException{ Statement stm = this.conexao.createStatement(); ResultSet rs; String sql = "SELECT * FROM ENDERECO WHERE ID='"+id+"'"; rs = stm.executeQuery(sql); return rs; } public void update (Endereco end,int id) throws SQLException{ String sql = "UPDATE ENDERECO SET FK_CIDADE="+end.getFk_cidade()+", RUA='"+end.getRua()+"', NUMERO="+end.getNumero()+", COMPLEMENTO='"+end.getComplemento()+"', CEP='"+end.getCep()+"', BAIRRO='"+end.getBairro()+"' WHERE ID="+id; Statement stm = conexao.createStatement(); stm.executeUpdate(sql); } public void delete(int id) throws SQLException { System.out.println(id); String sql = "DELETE FROM ENDERECO WHERE ID="+id; Statement stm= conexao.createStatement(); stm.executeUpdate(sql); } }
34.810345
247
0.573056
d553bcfdfe3bf64f7fa8ac00edfd8acb7f72907a
1,270
// This entity is for Java. package hu.bme.mit.inf.gs.AppStore.CreditManager.model; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @Entity @XmlRootElement public class CreditAccountEntity { private java.util.List<CreditTransactionEntity> transactions = new java.util.ArrayList<CreditTransactionEntity>(); private java.lang.String userName; @Id @GeneratedValue private int creditAccountID; @XmlElement @OneToMany (cascade=CascadeType.ALL) public java.util.List<CreditTransactionEntity> getTransactions() { return transactions; } public void setTransactions(java.util.List<CreditTransactionEntity> arg) { transactions = arg; } @XmlElement public java.lang.String getUserName() { return userName; } public void setUserName(java.lang.String arg) { userName = arg; } @XmlElement public int getCreditAccountID() { return creditAccountID; } public void setCreditAccountID(int arg) { creditAccountID = arg; } }
20.483871
116
0.724409
e6ab3d5ef9f68ec62f87552add6b9fcfa9f28522
3,112
package com.simibubi.create.content.contraptions.relays.elementary; import com.jozufozu.flywheel.api.Instancer; import com.jozufozu.flywheel.api.MaterialManager; import com.jozufozu.flywheel.util.transform.TransformStack; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.math.Vector3f; import com.simibubi.create.AllBlockPartials; import com.simibubi.create.content.contraptions.base.KineticTileEntity; import com.simibubi.create.content.contraptions.base.KineticTileEntityRenderer; import com.simibubi.create.content.contraptions.base.SingleRotatingInstance; import com.simibubi.create.content.contraptions.base.flwdata.RotatingData; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.Direction.Axis; import net.minecraft.core.Direction.AxisDirection; public class BracketedKineticTileInstance extends SingleRotatingInstance { protected RotatingData additionalShaft; public BracketedKineticTileInstance(MaterialManager modelManager, KineticTileEntity tile) { super(modelManager, tile); } @Override public void init() { super.init(); if (!ICogWheel.isLargeCog(blockEntity.getBlockState())) return; // Large cogs sometimes have to offset their teeth by 11.25 degrees in order to // mesh properly float speed = blockEntity.getSpeed(); Axis axis = KineticTileEntityRenderer.getRotationAxisOf(blockEntity); BlockPos pos = blockEntity.getBlockPos(); float offset = BracketedKineticTileRenderer.getShaftAngleOffset(axis, pos); Direction facing = Direction.fromAxisAndDirection(axis, AxisDirection.POSITIVE); Instancer<RotatingData> half = getRotatingMaterial().getModel(AllBlockPartials.COGWHEEL_SHAFT, blockState, facing, () -> this.rotateToAxis(axis)); additionalShaft = setup(half.createInstance(), speed); additionalShaft.setRotationOffset(offset); } @Override protected Instancer<RotatingData> getModel() { if (!ICogWheel.isLargeCog(blockEntity.getBlockState())) return super.getModel(); Axis axis = KineticTileEntityRenderer.getRotationAxisOf(blockEntity); Direction facing = Direction.fromAxisAndDirection(axis, AxisDirection.POSITIVE); return getRotatingMaterial().getModel(AllBlockPartials.SHAFTLESS_LARGE_COGWHEEL, blockState, facing, () -> this.rotateToAxis(axis)); } private PoseStack rotateToAxis(Axis axis) { Direction facing = Direction.fromAxisAndDirection(axis, AxisDirection.POSITIVE); PoseStack poseStack = new PoseStack(); TransformStack.cast(poseStack) .centre() .rotateToFace(facing) .multiply(Vector3f.XN.rotationDegrees(-90)) .unCentre(); return poseStack; } @Override public void update() { super.update(); if (additionalShaft != null) { updateRotation(additionalShaft); additionalShaft.setRotationOffset(BracketedKineticTileRenderer.getShaftAngleOffset(axis, pos)); } } @Override public void updateLight() { super.updateLight(); if (additionalShaft != null) relight(pos, additionalShaft); } @Override public void remove() { super.remove(); if (additionalShaft != null) additionalShaft.delete(); } }
33.106383
108
0.787918
d24bbddb85ef7ddb881807ecd8cde38a0ffe343d
4,612
package org.folio.oaipmh.dao; import io.github.jklingsporn.vertx.jooq.classic.reactivepg.ReactiveClassicGenericQueryExecutor; import io.vertx.core.Context; import io.vertx.core.Promise; import io.vertx.core.Vertx; import io.vertx.core.json.JsonObject; import io.vertx.pgclient.PgConnectOptions; import io.vertx.pgclient.PgPool; import io.vertx.sqlclient.PoolOptions; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.folio.oaipmh.Request; import org.folio.rest.persist.PostgresClient; import org.jooq.Configuration; import org.jooq.SQLDialect; import org.jooq.impl.DefaultConfiguration; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PreDestroy; import java.util.HashMap; import java.util.Map; @Component public class PostgresClientFactory { private static final Logger logger = LogManager.getLogger(PostgresClientFactory.class); public static final Configuration configuration = new DefaultConfiguration().set(SQLDialect.POSTGRES); private static final String HOST = "host"; private static final String PORT = "port"; private static final String DATABASE = "database"; private static final String PASSWORD = "password"; private static final String USERNAME = "username"; private static final String DEFAULT_SCHEMA_PROPERTY = "search_path"; private static final int POOL_SIZE = 20; /** * Such field is temporary solution which is used to allow resetting the pool in tests. * In future the {@link org.folio.oaipmh.processors.MarcWithHoldingsRequestHelper#getNextBatch(String, Request, int, Promise, Context, Long)} * should be canceled when response with failure already responded. */ private static boolean shouldResetPool = false; private static final Map<String, PgPool> POOL_CACHE = new HashMap<>(); private Vertx vertx; @Autowired public PostgresClientFactory(Vertx vertx) { this.vertx = vertx; } @PreDestroy public void preDestory() { closeAll(); } /** * Get {@link ReactiveClassicGenericQueryExecutor} * * @param tenantId tenant id * @return reactive query executor */ public ReactiveClassicGenericQueryExecutor getQueryExecutor(String tenantId) { return new ReactiveClassicGenericQueryExecutor(configuration, getCachedPool(this.vertx, tenantId)); } public static void closeAll() { POOL_CACHE.values().forEach(PostgresClientFactory::close); POOL_CACHE.clear(); } private static PgPool getCachedPool(Vertx vertx, String tenantId) { // assumes a single thread Vert.x model so no synchronized needed if (POOL_CACHE.containsKey(tenantId) && !shouldResetPool) { logger.debug("Using existing database connection pool for tenant {}.", tenantId); return POOL_CACHE.get(tenantId); } if (shouldResetPool) { POOL_CACHE.remove(tenantId); shouldResetPool = false; } logger.info("Creating new database connection pool for tenant {}.", tenantId); PgConnectOptions connectOptions = getConnectOptions(vertx, tenantId); PoolOptions poolOptions = new PoolOptions().setMaxSize(POOL_SIZE); PgPool client = PgPool.pool(vertx, connectOptions, poolOptions); POOL_CACHE.put(tenantId, client); return client; } public static PgPool getPool(Vertx vertx, String tenantId) { return getCachedPool(vertx, tenantId); } // NOTE: This should be able to get database configuration without PostgresClient. // Additionally, with knowledge of tenant at this time, we are not confined to // schema isolation and can provide database isolation. private static PgConnectOptions getConnectOptions(Vertx vertx, String tenantId) { PostgresClient postgresClient = PostgresClient.getInstance(vertx, tenantId); JsonObject postgreSQLClientConfig = postgresClient.getConnectionConfig(); postgresClient.closeClient(); return new PgConnectOptions() .setHost(postgreSQLClientConfig.getString(HOST)) .setPort(postgreSQLClientConfig.getInteger(PORT)) .setDatabase(postgreSQLClientConfig.getString(DATABASE)) .setUser(postgreSQLClientConfig.getString(USERNAME)) .setPassword(postgreSQLClientConfig.getString(PASSWORD)) // using RMB convention driven tenant to schema name .addProperty(DEFAULT_SCHEMA_PROPERTY, PostgresClient.convertToPsqlStandard(tenantId)); } private static void close(PgPool client) { client.close(); } public static void setShouldResetPool(boolean shouldResetPool) { PostgresClientFactory.shouldResetPool = shouldResetPool; } }
36.896
143
0.766262
2b30d8e66dce136f08e45b066b8a7c0da961d383
1,155
package com.gentics.changelogmanager.changelog; import static org.junit.Assert.assertTrue; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import org.junit.Test; import com.gentics.changelogmanager.AbstractChangelogTest; import com.gentics.changelogmanager.ChangelogManagerException; import com.gentics.changelogmanager.entry.ChangelogEntry; import com.gentics.changelogmanager.entry.ChangelogEntryUtils; public class ChangelogEntryTest extends AbstractChangelogTest { @Test public void testChangelogEntryRendering() throws ChangelogManagerException, UnsupportedEncodingException { List<String> entryFileNames = new ArrayList<String>(); entryFileNames.add("5.bugfix"); List<ChangelogEntry> entryList = ChangelogEntryUtils.getChangelogEntryFiles(testBaseDirectory, entryFileNames); ChangelogEntry entry = entryList.get(0); String text = entry.getHTML(); String encodedText = URLEncoder.encode(text, "UTF-8"); System.out.println(encodedText); assertTrue("The pattern could not be found in the outputtext.", encodedText.contains("asdgadg%3EAdded+g")); } }
36.09375
113
0.818182
1e174fffb783dc4ebc6733334ae5d285bc3f83c7
3,440
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ package org.apache.poi.hslf.record; import junit.framework.TestCase; import java.io.ByteArrayOutputStream; import java.util.Arrays; /** * Tests <code>FontCollection</code> and <code>FontEntityAtom</code> records * * @author Yegor Kozlov */ public class TestFontCollection extends TestCase { // From a real file private byte[] data = new byte[] { 0x0F, 0x00, 0xD5-256, 0x07, 0x4C, 0x00, 0x00, 0x00, 0x00, 0x00, 0xB7-256, 0x0F, 0x44, 0x00, 0x00, 0x00, 0x54, 0x00, 0x69, 0x00, 0x6D, 0x00, 0x65, 0x00, 0x73, 0x00, 0x20, 0x00, 0x4E, 0x00, 0x65, 0x00, 0x77, 0x00, 0x20, 0x00, 0x52, 0x00, 0x6F, 0x00, 0x6D, 0x00, 0x61, 0x00, 0x6E, 0x00, 0x00, 0x00, 0x74, 0x34, 0xB8-256, 0x00, 0x7C, 0xDA-256, 0x12, 0x00, 0x64, 0xDA-256, 0x12, 0x00, 0x76, 0xC7-256, 0x0B, 0x30, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xDA-256, 0x12, 0x00, 0x28, 0xDD-256, 0x0D, 0x30, 0x00, 0x00, 0x04, 0x00 }; public void testFonts() throws Exception { FontCollection fonts = new FontCollection(data, 0, data.length); Record[] child = fonts.getChildRecords(); assertEquals(child.length, 1); FontEntityAtom fnt = (FontEntityAtom)child[0]; assertEquals(fnt.getFontName(), "Times New Roman"); } public void testAddFont() throws Exception { FontCollection fonts = new FontCollection(data, 0, data.length); int idx = fonts.addFont("Times New Roman"); assertEquals(idx, 0); idx = fonts.addFont("Helvetica"); assertEquals(idx, 1); idx = fonts.addFont("Arial"); assertEquals(idx, 2); idx = fonts.addFont("Arial"); //the font being added twice assertEquals(idx, 2); // Font collection should contain 3 fonts Record[] child = fonts.getChildRecords(); assertEquals(child.length, 3); // Check we get the right font name for the indicies assertEquals("Times New Roman", fonts.getFontWithId(0)); assertEquals("Helvetica", fonts.getFontWithId(1)); assertEquals("Arial", fonts.getFontWithId(2)); assertNull(fonts.getFontWithId(3)); } public void testWrite() throws Exception { FontCollection fonts = new FontCollection(data, 0, data.length); ByteArrayOutputStream out = new ByteArrayOutputStream(); fonts.writeOut(out); byte[] recdata = out.toByteArray(); assertTrue(Arrays.equals(recdata, data)); } }
41.445783
76
0.639535
748f098430a6f92d945ba3dabc4abd61fa88dc36
2,688
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.jerm.cargadorexcel.controller; import com.jerm.cargadorexcel.resources.Herramientas; import java.io.File; import java.io.FileOutputStream; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; /** * * @author Jymmy */ public class CrearExcel { public void crear() { //Crear libro de trabajo en blanco Workbook workbook = new HSSFWorkbook(); //Crea hoja nueva Sheet sheet = workbook.createSheet("Hoja de datos"); //Por cada línea se crea un arreglo de objetos (Object[]) Map<String, Object[]> datos = new TreeMap<String, Object[]>(); datos.put("1", new Object[]{"Identificador", "Nombre", "Apellidos"}); datos.put("2", new Object[]{1, "María", "Remen"}); datos.put("3", new Object[]{2, "David", "Allos"}); datos.put("4", new Object[]{3, "Carlos", "Caritas"}); datos.put("5", new Object[]{4, "Luisa", "Vitz"}); //Iterar sobre datos para escribir en la hoja Set keyset = datos.keySet(); int numeroRenglon = 0; for (Object key : keyset) { Row row = sheet.createRow(numeroRenglon++); Object[] arregloObjetos = datos.get(key); int numeroCelda = 0; for (Object obj : arregloObjetos) { Cell cell = row.createCell(numeroCelda++); if (obj instanceof String) { cell.setCellValue((String) obj); } else if (obj instanceof Integer) { cell.setCellValue((Integer) obj); } } } try { //Se genera el documento //FileOutputStream out = new FileOutputStream(new File("C:\\Users\\Jymmy\\Desktop\\reporte.xlsx".trim())); //FileOutputStream out = new FileOutputStream(new File("reporte.xlsx")); String user= System.getProperty("user.name"); FileOutputStream out = new FileOutputStream( new File("/Users/"+user+"/Downloads/reporte.csv")); workbook.write(out); out.close(); } catch (Exception e) { Herramientas.mensaje(" "+e, 1); } finally { Herramientas.mensaje("Creado exitosamente", 0); } } }
35.84
130
0.595238
90589ce1167ee3f23c885f748d0ddb93bf97494b
6,154
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/asset/v1p2beta1/assets.proto package com.google.cloud.asset.v1p2beta1; public final class AssetProto { private AssetProto() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions( (com.google.protobuf.ExtensionRegistryLite) registry); } static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_asset_v1p2beta1_TemporalAsset_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_asset_v1p2beta1_TemporalAsset_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_asset_v1p2beta1_TimeWindow_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_asset_v1p2beta1_TimeWindow_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_asset_v1p2beta1_Asset_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_asset_v1p2beta1_Asset_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_asset_v1p2beta1_Resource_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_asset_v1p2beta1_Resource_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n)google/cloud/asset/v1p2beta1/assets.pr" + "oto\022\034google.cloud.asset.v1p2beta1\032\034googl" + "e/api/annotations.proto\032\032google/iam/v1/p" + "olicy.proto\032\031google/protobuf/any.proto\032\034" + "google/protobuf/struct.proto\032\037google/pro" + "tobuf/timestamp.proto\"\216\001\n\rTemporalAsset\022" + "8\n\006window\030\001 \001(\0132(.google.cloud.asset.v1p" + "2beta1.TimeWindow\022\017\n\007deleted\030\002 \001(\010\0222\n\005as" + "set\030\003 \001(\0132#.google.cloud.asset.v1p2beta1" + ".Asset\"j\n\nTimeWindow\022.\n\nstart_time\030\001 \001(\013" + "2\032.google.protobuf.Timestamp\022,\n\010end_time" + "\030\002 \001(\0132\032.google.protobuf.Timestamp\"\241\001\n\005A" + "sset\022\014\n\004name\030\001 \001(\t\022\022\n\nasset_type\030\002 \001(\t\0228" + "\n\010resource\030\003 \001(\0132&.google.cloud.asset.v1" + "p2beta1.Resource\022)\n\niam_policy\030\004 \001(\0132\025.g" + "oogle.iam.v1.Policy\022\021\n\tancestors\030\006 \003(\t\"\240" + "\001\n\010Resource\022\017\n\007version\030\001 \001(\t\022\036\n\026discover" + "y_document_uri\030\002 \001(\t\022\026\n\016discovery_name\030\003" + " \001(\t\022\024\n\014resource_url\030\004 \001(\t\022\016\n\006parent\030\005 \001" + "(\t\022%\n\004data\030\006 \001(\0132\027.google.protobuf.Struc" + "tB\264\001\n com.google.cloud.asset.v1p2beta1B\n" + "AssetProtoP\001ZAgoogle.golang.org/genproto" + "/googleapis/cloud/asset/v1p2beta1;asset\370" + "\001\001\252\002\034Google.Cloud.Asset.v1p2beta1\312\002\034Goog" + "le\\Cloud\\Asset\\V1p2beta1b\006proto3" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { com.google.api.AnnotationsProto.getDescriptor(), com.google.iam.v1.PolicyProto.getDescriptor(), com.google.protobuf.AnyProto.getDescriptor(), com.google.protobuf.StructProto.getDescriptor(), com.google.protobuf.TimestampProto.getDescriptor(), }); internal_static_google_cloud_asset_v1p2beta1_TemporalAsset_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_google_cloud_asset_v1p2beta1_TemporalAsset_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_asset_v1p2beta1_TemporalAsset_descriptor, new java.lang.String[] { "Window", "Deleted", "Asset", }); internal_static_google_cloud_asset_v1p2beta1_TimeWindow_descriptor = getDescriptor().getMessageTypes().get(1); internal_static_google_cloud_asset_v1p2beta1_TimeWindow_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_asset_v1p2beta1_TimeWindow_descriptor, new java.lang.String[] { "StartTime", "EndTime", }); internal_static_google_cloud_asset_v1p2beta1_Asset_descriptor = getDescriptor().getMessageTypes().get(2); internal_static_google_cloud_asset_v1p2beta1_Asset_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_asset_v1p2beta1_Asset_descriptor, new java.lang.String[] { "Name", "AssetType", "Resource", "IamPolicy", "Ancestors", }); internal_static_google_cloud_asset_v1p2beta1_Resource_descriptor = getDescriptor().getMessageTypes().get(3); internal_static_google_cloud_asset_v1p2beta1_Resource_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_asset_v1p2beta1_Resource_descriptor, new java.lang.String[] { "Version", "DiscoveryDocumentUri", "DiscoveryName", "ResourceUrl", "Parent", "Data", }); com.google.api.AnnotationsProto.getDescriptor(); com.google.iam.v1.PolicyProto.getDescriptor(); com.google.protobuf.AnyProto.getDescriptor(); com.google.protobuf.StructProto.getDescriptor(); com.google.protobuf.TimestampProto.getDescriptor(); } // @@protoc_insertion_point(outer_class_scope) }
53.982456
121
0.758369
5b7a8fb1d140ed4a90862f350ce07eb16393058f
13,223
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.utils.obs; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.Arrays; import java.util.BitSet; /** An "open" BitSet implementation that allows direct access to the array of words * storing the bits. * <p/> * Unlike java.util.bitset, the fact that bits are packed into an array of longs * is part of the interface. This allows efficient implementation of other algorithms * by someone other than the author. It also allows one to efficiently implement * alternate serialization or interchange formats. * <p/> * <code>OpenBitSet</code> is faster than <code>java.util.BitSet</code> in most operations * and *much* faster at calculating cardinality of sets and results of set operations. * It can also handle sets of larger cardinality (up to 64 * 2**32-1) * <p/> * The goals of <code>OpenBitSet</code> are the fastest implementation possible, and * maximum code reuse. Extra safety and encapsulation * may always be built on top, but if that's built in, the cost can never be removed (and * hence people re-implement their own version in order to get better performance). * If you want a "safe", totally encapsulated (and slower and limited) BitSet * class, use <code>java.util.BitSet</code>. */ public class OpenBitSet implements IBitSet { protected long[][] bits; protected int wlen; // number of words (elements) used in the array /** * length of bits[][] page in long[] elements. * Choosing unform size for all sizes of bitsets fight fragmentation for very large * bloom filters (2G and more) */ protected static final int PAGE_SIZE= 4096; /** Constructs an OpenBitSet large enough to hold numBits. * * @param numBits */ public OpenBitSet(long numBits) { this(numBits,true); } public OpenBitSet(long numBits, boolean allocatePages) { wlen= BitUtil.bits2words(numBits); bits = new long[getPageCount()][]; if (allocatePages) { for (int allocated=0,i=0;allocated<wlen;allocated+=PAGE_SIZE,i++) bits[i]=new long[PAGE_SIZE]; } } public OpenBitSet() { this(64); } /** * @return the pageSize */ public int getPageSize() { return PAGE_SIZE; } public int getPageCount() { return wlen / PAGE_SIZE + 1; } public long[] getPage(int pageIdx) { return bits[pageIdx]; } public void setPage(int pageIdx, long[] page) { bits[pageIdx] = page; } /** Contructs an OpenBitset from a BitSet */ public OpenBitSet(BitSet bits) { this(bits.length()); } /** Returns the current capacity in bits (1 greater than the index of the last bit) */ public long capacity() { return ((long)wlen) << 6; } /** * Returns the current capacity of this set. Included for * compatibility. This is *not* equal to {@link #cardinality} */ public long size() { return capacity(); } // @Override -- not until Java 1.6 public long length() { return capacity(); } /** Expert: gets the number of longs in the array that are in use */ public long sizeInWords() { return wlen; } /** Returns true or false for the specified bit index */ public boolean get(long index) { int i = (int)(index >> 6); // div 64 if (i>=wlen) return false; int bit = (int)index & 0x3f; // mod 64 long bitmask = 1L << bit; // TODO perfectionist one can implement this using bit operations return (bits[i / PAGE_SIZE][i % PAGE_SIZE ] & bitmask) != 0; } /** sets a bit, expanding the set size if necessary */ public void set(long index) { int wordNum = expandingWordNum(index); int bit = (int)index & 0x3f; long bitmask = 1L << bit; bits[ wordNum / PAGE_SIZE ][ wordNum % PAGE_SIZE ] |= bitmask; } /** Sets a range of bits, expanding the set size if necessary * * @param startIndex lower index * @param endIndex one-past the last bit to set */ public void set(long startIndex, long endIndex) { if (endIndex <= startIndex) return; int startWord = (int)(startIndex>>6); // since endIndex is one past the end, this is index of the last // word to be changed. int endWord = expandingWordNum(endIndex-1); long startmask = -1L << startIndex; long endmask = -1L >>> -endIndex; // 64-(endIndex&0x3f) is the same as -endIndex due to wrap if (startWord == endWord) { bits[startWord / PAGE_SIZE][startWord % PAGE_SIZE] |= (startmask & endmask); return; } assert startWord / PAGE_SIZE == endWord / PAGE_SIZE : "cross page sets not suppotred at all - they are not used"; bits[startWord / PAGE_SIZE][startWord % PAGE_SIZE] |= startmask; Arrays.fill(bits[ startWord / PAGE_SIZE], (startWord+1) % PAGE_SIZE , endWord % PAGE_SIZE , -1L); bits[endWord / PAGE_SIZE][endWord % PAGE_SIZE] |= endmask; } protected int expandingWordNum(long index) { int wordNum = (int)(index >> 6); if (wordNum>=wlen) { throw new IndexOutOfBoundsException( wordNum+">"+wlen ); } return wordNum; } /** clears a bit. * The index should be less than the OpenBitSet size. */ public void fastClear(int index) { int wordNum = index >> 6; int bit = index & 0x03f; long bitmask = 1L << bit; bits[wordNum / PAGE_SIZE][wordNum % PAGE_SIZE] &= ~bitmask; // hmmm, it takes one more instruction to clear than it does to set... any // way to work around this? If there were only 63 bits per word, we could // use a right shift of 10111111...111 in binary to position the 0 in the // correct place (using sign extension). // Could also use Long.rotateRight() or rotateLeft() *if* they were converted // by the JVM into a native instruction. // bits[word] &= Long.rotateLeft(0xfffffffe,bit); } /** clears a bit. * The index should be less than the OpenBitSet size. */ public void fastClear(long index) { int wordNum = (int)(index >> 6); // div 64 int bit = (int)index & 0x3f; // mod 64 long bitmask = 1L << bit; bits[wordNum / PAGE_SIZE][wordNum % PAGE_SIZE] &= ~bitmask; } /** clears a bit, allowing access beyond the current set size without changing the size.*/ public void clear(long index) { int wordNum = (int)(index >> 6); // div 64 if (wordNum>=wlen) return; int bit = (int)index & 0x3f; // mod 64 long bitmask = 1L << bit; bits[wordNum / PAGE_SIZE][wordNum % PAGE_SIZE] &= ~bitmask; } /** Clears a range of bits. Clearing past the end does not change the size of the set. * * @param startIndex lower index * @param endIndex one-past the last bit to clear */ public void clear(int startIndex, int endIndex) { if (endIndex <= startIndex) return; int startWord = (startIndex>>6); if (startWord >= wlen) return; // since endIndex is one past the end, this is index of the last // word to be changed. int endWord = ((endIndex-1)>>6); long startmask = -1L << startIndex; long endmask = -1L >>> -endIndex; // 64-(endIndex&0x3f) is the same as -endIndex due to wrap // invert masks since we are clearing startmask = ~startmask; endmask = ~endmask; if (startWord == endWord) { bits[startWord / PAGE_SIZE][startWord % PAGE_SIZE] &= (startmask | endmask); return; } bits[startWord / PAGE_SIZE][startWord % PAGE_SIZE] &= startmask; int middle = Math.min(wlen, endWord); if (startWord / PAGE_SIZE == middle / PAGE_SIZE) { Arrays.fill(bits[startWord/PAGE_SIZE], (startWord+1) % PAGE_SIZE, middle % PAGE_SIZE, 0L); } else { while (++startWord<middle) bits[startWord / PAGE_SIZE][startWord % PAGE_SIZE] = 0L; } if (endWord < wlen) { bits[endWord / PAGE_SIZE][endWord % PAGE_SIZE] &= endmask; } } /** Clears a range of bits. Clearing past the end does not change the size of the set. * * @param startIndex lower index * @param endIndex one-past the last bit to clear */ public void clear(long startIndex, long endIndex) { if (endIndex <= startIndex) return; int startWord = (int)(startIndex>>6); if (startWord >= wlen) return; // since endIndex is one past the end, this is index of the last // word to be changed. int endWord = (int)((endIndex-1)>>6); long startmask = -1L << startIndex; long endmask = -1L >>> -endIndex; // 64-(endIndex&0x3f) is the same as -endIndex due to wrap // invert masks since we are clearing startmask = ~startmask; endmask = ~endmask; if (startWord == endWord) { bits[startWord / PAGE_SIZE][startWord % PAGE_SIZE] &= (startmask | endmask); return; } bits[startWord / PAGE_SIZE][startWord % PAGE_SIZE] &= startmask; int middle = Math.min(wlen, endWord); if (startWord / PAGE_SIZE == middle / PAGE_SIZE) { Arrays.fill(bits[startWord/PAGE_SIZE], (startWord+1) % PAGE_SIZE, middle % PAGE_SIZE, 0L); } else { while (++startWord<middle) bits[startWord / PAGE_SIZE][startWord % PAGE_SIZE] = 0L; } if (endWord < wlen) { bits[endWord / PAGE_SIZE][endWord % PAGE_SIZE] &= endmask; } } /** @return the number of set bits */ public long cardinality() { long bitCount = 0L; for (int i=getPageCount();i-->0;) bitCount+=BitUtil.pop_array(bits[i],0,wlen); return bitCount; } /** returns true if both sets have the same bits set */ @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof OpenBitSet)) return false; OpenBitSet a; OpenBitSet b = (OpenBitSet)o; // make a the larger set. if (b.wlen > this.wlen) { a = b; b=this; } else { a=this; } int aPageSize = PAGE_SIZE; int bPageSize = PAGE_SIZE; // check for any set bits out of the range of b for (int i=a.wlen-1; i>=b.wlen; i--) { if (a.bits[i/aPageSize][i % aPageSize]!=0) return false; } for (int i=b.wlen-1; i>=0; i--) { if (a.bits[i/aPageSize][i % aPageSize] != b.bits[i/bPageSize][i % bPageSize]) return false; } return true; } @Override public int hashCode() { // Start with a zero hash and use a mix that results in zero if the input is zero. // This effectively truncates trailing zeros without an explicit check. long h = 0; for (int i = wlen; --i>=0;) { h ^= bits[i / PAGE_SIZE][i % PAGE_SIZE]; h = (h << 1) | (h >>> 63); // rotate left } // fold leftmost bits into right and add a constant to prevent // empty sets from returning 0, which is too common. return (int)((h>>32) ^ h) + 0x98761234; } @Override public void close() { } @Override public void serialize( DataOutput dos ) throws IOException { int pageCount = getPageCount(); long wordsLength = sizeInWords(); for (int p = 0;p<pageCount;p++) { long[] bits = getPage(p); for ( int i = 0; i < PAGE_SIZE && wordsLength-- > 0; i++ ) dos.writeLong(bits[i]); } } public void deserialize( DataInput dis ) throws IOException { int pageCount = getPageCount(); long words = sizeInWords(); for (int p = 0;p<pageCount;p++) { long[] bits = getPage(p); for ( int i = 0; i < PAGE_SIZE && words-- > 0; i++ ) bits[i] = dis.readLong(); } } }
32.730198
121
0.59215
e16160eb35751f4f1be07b010c74235199d40fef
4,717
package rb.popview; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Rect; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.view.Window; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Created by rb on 18/6/16. */ public class PopField extends View { private List<PopAnimator> mPopViews = new ArrayList<>(); private int[] mExpandInset = new int[2]; public PopField(Context context) { super(context); init(); } public PopField(Context context, AttributeSet attrs) { super(context, attrs); init(); } public PopField(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { Arrays.fill(mExpandInset, PopUtils.dp2Px(32)); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); for (PopAnimator popView : mPopViews) { popView.draw(canvas); } } private void popView(final Bitmap bitmap, final Rect bound , final long startDelay, final long duration) { final PopAnimator pop = new PopAnimator(this, bitmap, bound); pop.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mPopViews.remove(animation); } }); pop.setStartDelay(startDelay); pop.setDuration(duration); mPopViews.add(pop); pop.start(); } private void popView(final Bitmap bitmap, final Bitmap addBitmap , final View view, final View addView, final Rect bound , final long startDelay, final long duration) { final PopAnimator pop = new PopAnimator(this, bitmap, bound); final View currentView = this; pop.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { PopAnimator popNext = new PopAnimator(currentView, addBitmap, bound, pop.getParticleValues()); popNext.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { ViewGroup parentViewGroup = (ViewGroup) view.getParent(); int index = parentViewGroup.indexOfChild(view); parentViewGroup.removeView(view); parentViewGroup.addView(addView, index); } }); popNext.setStartDelay(startDelay); popNext.setDuration(duration); mPopViews.add(popNext); popNext.start(); mPopViews.remove(animation); } }); pop.setStartDelay(startDelay); pop.setDuration(duration); mPopViews.add(pop); pop.start(); } public void popView (final View view) { Rect r = new Rect(); view.getGlobalVisibleRect(r); int[] location = new int[2]; getLocationOnScreen(location); r.offset(-location[0], -location[1]); int startDelay = 0; view.animate().setDuration(150).setStartDelay(startDelay) .scaleX(0f).scaleY(0f).alpha(0f).start(); popView(PopUtils.createBitmapFromView(view), r, startDelay, PopAnimator.DEFAULT_DURATION); } public void popView (final View view, View addView) { Rect r = new Rect(); view.getGlobalVisibleRect(r); int[] location = new int[2]; getLocationOnScreen(location); r.offset(-location[0], -location[1]); int startDelay = 0; view.animate().setDuration(150).setStartDelay(startDelay) .scaleX(0f).scaleY(0f).alpha(0f).start(); popView(PopUtils.createBitmapFromView(view), r, startDelay, PopAnimator.DEFAULT_DURATION); ViewGroup parentViewGroup = (ViewGroup) view.getParent(); int index = parentViewGroup.indexOfChild(view); parentViewGroup.removeView(view); parentViewGroup.addView(addView, index); } public void popView (final View view, View addView, boolean isAnimated) { if(isAnimated) { Rect r = new Rect(); view.getGlobalVisibleRect(r); int[] location = new int[2]; getLocationOnScreen(location); r.offset(-location[0], -location[1]); long startDelay = 0; view.animate().setDuration(150).setStartDelay(startDelay) .scaleX(0f).scaleY(0f).alpha(0f).start(); popView(PopUtils.createBitmapFromView(view), PopUtils.createBitmapFromView(addView) , view, addView, r, startDelay, PopAnimator.DEFAULT_DURATION); } } public void clear() { mPopViews.clear(); invalidate(); } public static PopField attach2Window(Activity activity) { ViewGroup rootView = (ViewGroup) activity.findViewById(Window.ID_ANDROID_CONTENT); PopField explosionField = new PopField(activity); rootView.addView(explosionField, new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); return explosionField; } }
30.044586
98
0.735001
1ee956f2c2bc991f5f8a7826e78f49097ebc2809
5,648
package com.example.diamondchatbenchmark; import android.support.v7.app.ActionBarActivity; import android.util.Log; import java.util.ArrayList; import java.util.List; import android.app.AlertDialog; import android.graphics.Color; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; import edu.washington.cs.diamond.Diamond; public class MainActivity extends ActionBarActivity { static final int MESSAGE_LIST_SIZE = 100; static final int NUM_ACTIONS = 100; static final String MESSAGE = "Help, I'm trapped in a Diamond benchmark"; static final int INITIAL_CAPACITY = NUM_ACTIONS; static String chatroomName = "androidbenchmark"; static String userName = "android"; static String serverName = "104.197.217.104"; static final int PORT = 12345; private Diamond.DStringList messageList; public double[] writeMessageTransaction(String msg) { String fullMsg = userName + ": " + msg; int committed = 0; int numAborts = 0; long writeTimeStart = 0; long writeTimeEnd = 1000 * 1000 * 1000; while(committed == 0) { writeTimeStart = System.nanoTime(); Diamond.DObject.TransactionBegin(); messageList.Append(fullMsg); if (messageList.Size() > MESSAGE_LIST_SIZE) { messageList.Erase(0); } committed = Diamond.DObject.TransactionCommit(); if (committed == 0) { numAborts++; } } writeTimeEnd = System.nanoTime(); double time = ((double)(writeTimeEnd - writeTimeStart)) / (1000 * 1000); double[] ret = new double[2]; ret[0] = time; ret[1] = numAborts; return ret; } public double[] readMessagesTransaction() { List<String> result = null; int committed = 0; int numAborts = 0; long readTimeStart = 0; long readTimeEnd = 1000 * 1000 * 1000; while (committed == 0) { readTimeStart = System.nanoTime(); Diamond.DObject.BeginRO(); result = messageList.Members(); committed = Diamond.DObject.TransactionCommit(); if (committed == 0) { numAborts++; } } readTimeEnd = System.nanoTime(); if (result.get(0).indexOf(MESSAGE) == -1) { Log.i("BENCHMARK", "Error: first item of chat log is " + result.get(0)); } double time = ((double)(readTimeEnd - readTimeStart)) / (1000 * 1000); double[] ret = new double[2]; ret[0] = time; ret[1] = numAborts; return ret; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.activity_main); TextView textBox = new TextView(this.getBaseContext()); textBox.setTextColor(Color.BLACK); setContentView(textBox); Diamond.DiamondInit(serverName, String.valueOf(PORT)); String chatLogKey = "dimessage:" + chatroomName + ":chatlog"; messageList = new Diamond.DStringList(); Diamond.DObject.Map(messageList, chatLogKey); // Warm up JVM and fill chat log Log.i("BENCHMARK", "Progress: warming up JVM"); for (int i = 0; i < NUM_ACTIONS; i++) { writeMessageTransaction(MESSAGE); } // Transactional reads Log.i("BENCHMARK", "Progress: starting transactional reads"); double totalTimeReadTrans = 0; double totalNumAbortsReadTrans = 0; List<Double> timesReadTrans = new ArrayList<Double>(INITIAL_CAPACITY); List<Double> numAbortsReadTrans = new ArrayList<Double>(INITIAL_CAPACITY); for (int i = 0; i < NUM_ACTIONS; i++) { double[] ret = readMessagesTransaction(); totalTimeReadTrans += ret[0]; timesReadTrans.add(ret[0]); totalNumAbortsReadTrans += ret[1]; numAbortsReadTrans.add(ret[1]); } double averageTimeReadTrans = ((double)totalTimeReadTrans) / NUM_ACTIONS; double averageAbortsReadTrans = ((double)totalNumAbortsReadTrans) / NUM_ACTIONS; // Transactional writes Log.i("BENCHMARK", "Progress: starting transactional writes"); double totalTimeWriteTrans = 0; double totalNumAbortsWriteTrans = 0; List<Double> timesWriteTrans = new ArrayList<Double>(INITIAL_CAPACITY); List<Double> numAbortsWriteTrans = new ArrayList<Double>(INITIAL_CAPACITY); for (int i = 0; i < NUM_ACTIONS; i++) { double[] ret = writeMessageTransaction(MESSAGE); totalTimeWriteTrans += ret[0]; timesWriteTrans.add(ret[0]); totalNumAbortsWriteTrans += ret[1]; numAbortsWriteTrans.add(ret[1]); } double averageTimeWriteTrans = ((double)totalTimeWriteTrans) / NUM_ACTIONS; double averageAbortsWriteTrans = ((double)totalNumAbortsWriteTrans) / NUM_ACTIONS; for (int i = 0; i < timesWriteTrans.size(); i++) { Log.i("BENCHMARK", "data:\twrite\ttransaction\t" + timesWriteTrans.get(i)); try {Thread.sleep(1);} catch (InterruptedException e) {} } for (int i = 0; i < timesReadTrans.size(); i++) { Log.i("BENCHMARK", "data:\tread\ttransaction\t" + timesReadTrans.get(i)); try {Thread.sleep(1);} catch (InterruptedException e) {} } Log.i("BENCHMARK", "Done with Diamond experiment"); textBox.setText("Transaction read: " + averageTimeReadTrans + "\n" + "Transaction write: " + averageTimeWriteTrans + "\n"); Log.i("BENCHMARK", "Why doesn't this show up"); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
32.647399
84
0.708038
3799bd309651a39b7cbeff830201d9aeda2f5ad7
1,486
package io.nanodbc.impl; import java.time.LocalTime; import org.bytedeco.javacpp.Loader; import org.bytedeco.javacpp.Pointer; import org.bytedeco.javacpp.annotation.MemberGetter; import org.bytedeco.javacpp.annotation.MemberSetter; import org.bytedeco.javacpp.annotation.Name; import org.bytedeco.javacpp.annotation.Namespace; import org.bytedeco.javacpp.annotation.Platform; @Platform(include = "nanodbc_ext.h", library = "jninanodbc") @Namespace("nanodbc") @Name("time") class NativeTime extends Pointer { static { Loader.load(); } public NativeTime() { allocate(); } private native void allocate(); @MemberGetter @Name("hour") public native int getHour(); @MemberSetter @Name("hour") public native void setHour(int hour); @MemberGetter @Name("min") public native int getMinute(); @MemberSetter @Name("min") public native void setMinute(int minute); @MemberGetter @Name("sec") public native int getSecond(); @MemberSetter @Name("sec") public native void setSecond(int second); public LocalTime toLocalTime() { return LocalTime.of(getHour(), getMinute(), getSecond()); } public static NativeTime fromLocalTime(LocalTime localTime) { NativeTime time = new NativeTime(); time.setHour(localTime.getHour()); time.setMinute(localTime.getMinute()); time.setSecond(localTime.getSecond()); return time; } }
23.21875
65
0.681023
9de2e1307d5a11113037cd90d9e06205f475cbf0
10,906
/* * This is the source code of DMPLayer for Android v. 1.0.0. * You should have received a copy of the license in this archive (see LICENSE). * Copyright @Dibakar_Mistry, 2015. */ package com.dmplayer.childfragment; import android.app.Activity; import android.content.AsyncQueryHandler; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.provider.MediaStore; import android.support.v4.app.Fragment; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AlphabetIndexer; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.TextView; import com.dmplayer.R; import com.dmplayer.activities.AlbumAndArtisDetailsActivity; import com.dmplayer.adapter.CursorRecyclerViewAdapter; import com.dmplayer.utility.LogWriter; import com.dmplayer.phonemidea.DMPlayerUtility; import com.dmplayer.phonemidea.MusicAlphabetIndexer; import com.dmplayer.phonemidea.PhoneMediaControl; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; public class ChildFragmentAlbum extends Fragment { private static final String TAG = "ChildFragmentAlbum"; private static Context context; private RecyclerView recyclerView; boolean mIsUnknownArtist; boolean mIsUnknownAlbum; private AlbumRecyclerAdapter mAdapter; private Cursor mAlbumCursor; private String mArtistId; public static ChildFragmentAlbum newInstance(int position, Context mContext) { ChildFragmentAlbum f = new ChildFragmentAlbum(); context = mContext; return f; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragmentchild_album, null); setupView(view, savedInstanceState); return view; } private void setupView(View v, Bundle icicle) { recyclerView = (RecyclerView) v.findViewById(R.id.recyclerview_grid); recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2)); populateData(icicle); } public void resetView() { recyclerView.scrollToPosition(0); } private void populateData(Bundle icicle) { mAdapter = (AlbumRecyclerAdapter) getActivity().getLastNonConfigurationInstance(); if (mAdapter == null) { mAdapter = new AlbumRecyclerAdapter(getActivity(), null); recyclerView.setAdapter(mAdapter); getAlbumCursor(mAdapter.getQueryHandler(), null); } else { recyclerView.setAdapter(mAdapter); mAlbumCursor = mAdapter.getCursor(); if (mAlbumCursor != null) { init(mAlbumCursor); } else { getAlbumCursor(mAdapter.getQueryHandler(), null); } } } public void init(Cursor c) { if (mAdapter == null) { return; } mAdapter.changeCursor(c); // also sets mAlbumCursor if (mAlbumCursor == null) { DMPlayerUtility.displayDatabaseError(getActivity()); mReScanHandler.sendEmptyMessageDelayed(0, 1000); return; } } private Handler mReScanHandler = new Handler() { @Override public void handleMessage(Message msg) { if (mAdapter != null) { getAlbumCursor(mAdapter.getQueryHandler(), null); } } }; private Cursor getAlbumCursor(AsyncQueryHandler async, String filter) { String[] cols = new String[]{MediaStore.Audio.Albums._ID, MediaStore.Audio.Albums.ARTIST, MediaStore.Audio.Albums.ALBUM, MediaStore.Audio.Albums.ALBUM_ART}; Cursor ret = null; Uri uri = MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI; if (!TextUtils.isEmpty(filter)) { uri = uri.buildUpon().appendQueryParameter("filter", Uri.encode(filter)).build(); } if (async != null) { async.startQuery(0, null, uri, cols, null, null, MediaStore.Audio.Albums.DEFAULT_SORT_ORDER); } else { ret = DMPlayerUtility.query(getActivity(), uri, cols, null, null, MediaStore.Audio.Albums.DEFAULT_SORT_ORDER); } return ret; } public class AlbumRecyclerAdapter extends CursorRecyclerViewAdapter<AlbumRecyclerAdapter.ViewHolder> { private int mAlbumIdx; private int mArtistIdx; private final Resources mResources; private final String mUnknownAlbum; private final String mUnknownArtist; private AlphabetIndexer mIndexer; private AsyncQueryHandler mQueryHandler; private String mConstraint = null; private boolean mConstraintIsValid = false; private DisplayImageOptions options; private ImageLoader imageLoader = ImageLoader.getInstance(); protected AlbumRecyclerAdapter(Context context, Cursor cursor) { super(context, cursor); this.mQueryHandler = new QueryHandler(context.getContentResolver()); this.mUnknownAlbum = context.getString(R.string.unknown_album_name); this.mUnknownArtist = context.getString(R.string.unknown_artist_name); this.mResources = context.getResources(); this.options = new DisplayImageOptions.Builder().showImageOnLoading(R.drawable.bg_default_album_art) .showImageForEmptyUri(R.drawable.bg_default_album_art).showImageOnFail(R.drawable.bg_default_album_art).cacheInMemory(true) .cacheOnDisk(true).considerExifParams(true).bitmapConfig(Bitmap.Config.RGB_565).build(); getColumnIndices(cursor); } private class QueryHandler extends AsyncQueryHandler { QueryHandler(ContentResolver res) { super(res); } @Override protected void onQueryComplete(int token, Object cookie, Cursor cursor) { init(cursor); } } public AsyncQueryHandler getQueryHandler() { return mQueryHandler; } @Override public void changeCursor(Cursor cursor) { if (getActivity().isFinishing() && cursor != null) { cursor.close(); cursor = null; } if (cursor != mAlbumCursor) { mAlbumCursor = cursor; getColumnIndices(cursor); super.changeCursor(cursor); } } public Cursor runQueryOnBackgroundThread(CharSequence constraint) { String s = constraint.toString(); if (mConstraintIsValid && ((s == null && mConstraint == null) || (s != null && s.equals(mConstraint)))) { return getCursor(); } Cursor c = getAlbumCursor(null, s); mConstraint = s; mConstraintIsValid = true; return c; } private void getColumnIndices(Cursor cursor) { if (cursor != null) { mAlbumIdx = cursor.getColumnIndexOrThrow(MediaStore.Audio.Albums.ALBUM); mArtistIdx = cursor.getColumnIndexOrThrow(MediaStore.Audio.Albums.ARTIST); if (mIndexer != null) { mIndexer.setCursor(cursor); } else { mIndexer = new MusicAlphabetIndexer(cursor, mAlbumIdx, mResources.getString(R.string.fast_scroll_alphabet)); } } } @Override public void onBindViewHolder(ViewHolder viewHolder, Cursor cursor) { String displayname = cursor.getString(mAlbumIdx); String artistname = cursor.getString(mArtistIdx); boolean unknown = displayname == null || displayname.equals(MediaStore.UNKNOWN_STRING); viewHolder.albumName.setText(unknown ? mUnknownAlbum : displayname); viewHolder.albumName.setTag(mAlbumIdx); unknown = (artistname == null || artistname.equals(MediaStore.UNKNOWN_STRING)); viewHolder.artistName.setText(unknown ? mUnknownArtist : artistname); viewHolder.artistName.setTag(mArtistIdx); String contentURI = "content://media/external/audio/albumart/" + cursor.getLong(0); imageLoader.displayImage(contentURI, viewHolder.icon, options); } @Override public ViewHolder onCreateViewHolder(ViewGroup viewgroup, int position) { return new ViewHolder(LayoutInflater.from(viewgroup.getContext()).inflate(R.layout.inflate_grid_item, viewgroup, false)); } protected class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { TextView albumName; TextView artistName; ImageView icon; public ViewHolder(View itemView) { super(itemView); albumName = (TextView) itemView.findViewById(R.id.line1); artistName = (TextView) itemView.findViewById(R.id.line2); icon = (ImageView) itemView.findViewById(R.id.icon); icon.setScaleType(ScaleType.CENTER_CROP); itemView.setOnClickListener(this); } @Override public void onClick(View view) { try { long albumID = getAlbumID(getPosition()); Intent mIntent = new Intent(context, AlbumAndArtisDetailsActivity.class); Bundle mBundle = new Bundle(); mBundle.putLong("id", albumID); mBundle.putLong("tagfor", PhoneMediaControl.SonLoadFor.Album.ordinal()); mBundle.putString("albumname", ((TextView) view.findViewById(R.id.line1)).getText().toString().trim()); mBundle.putString("title_one", ((TextView) view.findViewById(R.id.line2)).getText().toString().trim()); mBundle.putString("title_sec", ""); mIntent.putExtras(mBundle); ((Activity) context).startActivity(mIntent); ((Activity) context).overridePendingTransition(0, 0); } catch (Exception e) { e.printStackTrace(); LogWriter.info(TAG, e.toString()); } } } private long getAlbumID(int position) { return getItemId(position); } } }
38.811388
143
0.641298
0b411de70cd514db692e9c20cc45eb29189f1dd1
992
package org.museautomation.selenium.providers; import org.museautomation.core.*; import org.museautomation.selenium.*; import org.openqa.selenium.*; import org.openqa.selenium.remote.*; import org.openqa.selenium.safari.*; /** * @author Christopher L Merrill (see LICENSE.txt for license details) */ @MuseTypeId("safaridriver-provider") public class SafariDriverProvider extends BaseLocalDriverProvider { @Override public WebDriver getDriver(SeleniumBrowserCapabilities capabilities, MuseExecutionContext context) { if (!capabilities.getName().equals(BrowserType.SAFARI)) return null; synchronized (SafariDriverProvider.class) { return new SafariDriver(capabilities.toDesiredCapabilities()); } } @Override public String getName() { return "Safari (local)"; } @Override public String toString() { return "SafariDriver"; } }
24.195122
102
0.664315
ba2407445bc9888e407db3417ab63c50193ce908
1,488
package com.example.shixian; import android.app.Application; import android.content.Context; import android.content.Intent; import com.example.shixian.bean.User; import com.example.shixian.utils.UserLocalData; /** * Created by admin on 2017/12/27. */ public class ShiXianApplication extends Application{ private static ShiXianApplication shiXianApplication; private User mUser; private Intent mIntent; private boolean isChangeUser = false; public static ShiXianApplication getInstance(){ return shiXianApplication; } @Override public void onCreate() { super.onCreate(); shiXianApplication = this; initUser(); } private void initUser() { this.mUser = UserLocalData.getUser(this); } public User getUser() { return mUser; } public void putUser(User user) { this.mUser = user; UserLocalData.putUser(this, user); } public void cleanUser() { this.mUser = null; isChangeUser = true; UserLocalData.cleanUser(this); } public boolean isChangeUser() { return isChangeUser; } public void putIntent(Intent intent) { this.mIntent = intent; } public Intent getIntent() { return mIntent; } public void jumpToTargetActivity(Context context){ if (mIntent != null){ context.startActivity(this.mIntent); this.mIntent = null; } } }
19.076923
57
0.635081
5fef39217591885d355ee7bfea1385edef838397
3,703
/******************************************************************************* * This file is part of the Symfony eclipse plugin. * * (c) Robert Gruendler <r.gruendler@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. ******************************************************************************/ package com.dubture.symfony.index.dao.sql; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import org.eclipse.core.runtime.IPath; import org.eclipse.osgi.util.NLS; import com.dubture.symfony.index.Schema; import com.dubture.symfony.index.dao.IResourceDao; import com.dubture.symfony.index.handler.IResourceHandler; import com.dubture.symfony.index.log.Logger; import com.dubture.symfony.index.model.RoutingResource; public class ResourceDao extends BaseDao implements IResourceDao { public ResourceDao(Connection connection) { super(connection); } private static final String TABLENAME = "RESOURCE"; private static final String Q_INSERT_DECL = Schema .readSqlFile("Resources/index/resources/insert_decl.sql"); //$NON-NLS-1$ @Override public void insert(String path, String type, String prefix, IPath fullPath) throws Exception { if (type == null) type = ""; if (prefix == null) prefix = ""; String tableName = TABLENAME; String query; query = D_INSERT_QUERY_CACHE.get(tableName); if (query == null) { query = NLS.bind(Q_INSERT_DECL, tableName); D_INSERT_QUERY_CACHE.put(tableName, query); } synchronized (batchStatements) { PreparedStatement statement = batchStatements.get(query); if (statement == null) { statement = connection.prepareStatement(query); batchStatements.put(query, statement); } insertBatch(statement, path, type, prefix, fullPath); } } private void insertBatch(PreparedStatement statement, String resourcePath, String type, String prefix, IPath path) throws SQLException { int param = 0; statement.setString(++param, resourcePath); statement.setString(++param, type); statement.setString(++param, prefix); statement.setString(++param, path.toString()); statement.addBatch(); // // if (!isReference) { // H2Cache.addElement(new Element(type, flags, offset, length, // nameOffset, nameLength, name, camelCaseName, metadata, doc, // qualifier, parent, fileId, isReference)); // } } @Override public void findResource(IPath path, IResourceHandler iResourceHandler) { try { String sql = "SELECT RESOURCEPATH, TYPE, PREFIX FROM RESOURCE WHERE PATH = '" + path.toString() + "'"; Statement statement = connection.createStatement(); ResultSet result = statement.executeQuery(sql); while (result.next()) { int columnIndex = 0; String resourcePath = result.getString(++columnIndex); String type = result.getString(++columnIndex); String prefix = result.getString(++columnIndex); RoutingResource resource = new RoutingResource(type, resourcePath, prefix); iResourceHandler.handle(resource); } } catch(Exception e) { Logger.logException(e); } } }
35.605769
114
0.603565
b62d226ec64336d4d234eb51c074999aee6c1aa3
1,445
/* * Copyright 2015, The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.testing.espresso.intents.AdvancedSample; import android.support.test.espresso.matcher.BoundedMatcher; import android.view.View; import android.widget.ImageView; import org.hamcrest.Description; /** * A Matcher for Espresso that checks if an ImageView has a drawable applied to it. */ public class ImageViewHasDrawableMatcher { public static BoundedMatcher<View, ImageView> hasDrawable() { return new BoundedMatcher<View, ImageView>(ImageView.class) { @Override public void describeTo(Description description) { description.appendText("has drawable"); } @Override public boolean matchesSafely(ImageView imageView) { return imageView.getDrawable() != null; } }; } }
32.840909
83
0.701038
793fa5fd1d607a37de879969bab67a13ca5c6dae
2,158
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.bval.jsr.xml; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.Unmarshaller; import javax.xml.bind.UnmarshallerHandler; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.junit.Test; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; public class Demo { @Test public void test1() throws Exception { JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class); // Set the parent XMLReader on the XMLFilter SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); // Set UnmarshallerHandler as ContentHandler on XMLFilter Unmarshaller unmarshaller = jc.createUnmarshaller(); UnmarshallerHandler unmarshallerHandler = unmarshaller.getUnmarshallerHandler(); xr.setContentHandler(unmarshallerHandler); // Parse the XML InputSource xml = new InputSource(getClass().getResourceAsStream("/sample-validation2.xml")); xr.parse(xml); JAXBElement<ValidationConfigType> result = (JAXBElement<ValidationConfigType>) unmarshallerHandler.getResult(); System.out.println(result.getValue()); } }
38.535714
119
0.730306
893828d4cdd395cb9f08998ea9bfb55ffc72fb81
5,518
package francis.kylintest.modules; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.StringTokenizer; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.media.MediaPlayer; import android.os.Bundle; import android.view.View; import android.widget.MediaController; import android.widget.Toast; import android.widget.VideoView; import francis.kylintest.MainActivity; import francis.kylintest.R; import francis.kylintest.utils.Common; import francis.kylintest.utils.Result; import francis.kylintest.utils.SystemUtil; public class VideoActivity extends Activity { private static final String TAG = "VideoActivity"; private Context context = VideoActivity.this; private VideoView vv; private File videoFile, txtFile; private MediaController mc; private boolean fulltest = false, haveNoScreen = false; private Bundle extras; private String videoPath, txtPath; private USBBroadCastReceiver mBroadcastReceiver; SharedPreferences preferences; SharedPreferences.Editor editor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_video); preferences = getSharedPreferences("state", MODE_PRIVATE); editor = preferences.edit(); IntentFilter iFilter = new IntentFilter(); iFilter.addAction(Intent.ACTION_MEDIA_EJECT); iFilter.addAction(Intent.ACTION_MEDIA_MOUNTED); iFilter.addAction(Intent.ACTION_MEDIA_REMOVED); iFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED); iFilter.addDataScheme("file"); mBroadcastReceiver = new USBBroadCastReceiver(); registerReceiver(mBroadcastReceiver, iFilter); extras = getIntent().getExtras(); if (extras != null) { haveNoScreen = extras.getBoolean("haveNoScreen"); } Toast.makeText(getApplicationContext(), getResources().getText(R.string.video_test_on), Toast.LENGTH_SHORT).show(); vv = (VideoView) findViewById(R.id.vv); // videoPath = SystemUtil.getSDPath() + "/system/media/test.mp4"; videoPath = "/system/media/test"; videoFile = new File(videoPath); if (haveNoScreen) { String s = SystemUtil.getOutSDPath(); int i = s.lastIndexOf("*"); int k = s.lastIndexOf("\n"); s = s.substring(i + 1, k); txtPath = s + "/videoLog.txt"; } else { txtPath = SystemUtil.getSDPath() + "/tmp/timelog.txt"; } txtFile = new File(txtPath); if (txtFile.exists()) { txtFile.delete(); } try { txtFile.createNewFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } mc = new MediaController(context); if (videoFile.exists()) { // vv.setVideoURI(Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.test)); vv.setVideoPath(videoPath); vv.setMediaController(mc); vv.requestFocus(); SystemUtil.writeToTxt(txtPath, getResources().getString(R.string.video_start)); vv.start(); vv.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer arg) { String time = SystemUtil.getTime(); SystemUtil.writeToTxt(txtPath, time.toString()); // vv.setVideoURI(Uri.parse("android.resource://"+ // getPackageName() + "/" + R.raw.test)); vv.setVideoPath(videoPath); vv.setMediaController(mc); vv.requestFocus(); vv.start(); } }); } else { Toast.makeText(getApplicationContext(), getResources().getString(R.string.no_video), Toast.LENGTH_SHORT).show(); } } private class USBBroadCastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_MEDIA_REMOVED)) { if (haveNoScreen) { unregisterReceiver(mBroadcastReceiver); Common.gotoActivity(context, MainActivity.class); } } } } public void videoClick(View target) { unregisterReceiver(mBroadcastReceiver); switch (target.getId()) { case R.id.video_pass: editor.putString("video", "1"); editor.commit(); fulltestGoActivity(); break; case R.id.video_fail: editor.putString("video", "0"); editor.commit(); fulltestGoActivity(); break; case R.id.video_back: if (vv.isPlaying()) { vv.stopPlayback(); } Common.gotoActivity(context, MainActivity.class); break; } } public void fulltestGoActivity() { if (vv.isPlaying()) { vv.stopPlayback(); } if (extras != null) { fulltest = extras.getBoolean("fulltest"); if (fulltest) { Common.gotoActivity(context, MainActivity.class); } else { Result r = ((Result) getApplicationContext()); ArrayList<Class> classes = new ArrayList<Class>(); classes = r.getClasses(); classes.remove(0); r.setClasses(classes); if (classes.size() > 0) { Common.gotoActivity(context, classes.get(0), "fulltest", fulltest); } else { Common.gotoActivity(context, MainActivity.class); } } } else { Common.gotoActivity(context, MainActivity.class); } } /** * 监听Back键按下事件 注意: super.onBackPressed()会自动调用finish()方法,关闭当前Activity * 若要屏蔽Back键盘,注释该行代码即可 */ @Override public void onBackPressed() { super.onBackPressed(); if (vv.isPlaying()) { vv.stopPlayback(); } unregisterReceiver(mBroadcastReceiver); Common.gotoActivity(context, MainActivity.class); } }
28.590674
87
0.715295
181c1c8f44c758f6edd06d2a71133c1db504b04f
13,094
/* */ package c.a.j.a; /* */ /* */ import c.a.d; /* */ import c.a.g.c; /* */ import com.github.jaiimageio.jpeg2000.impl.J2KImageWriteParamJava; /* */ import java.util.StringTokenizer; /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public class f /* */ extends d /* */ { /* */ private static final String a = "w5x3"; /* */ private static final String r = "w9x7"; /* */ /* */ public f(int nt, int nc, byte type, c qts, J2KImageWriteParamJava wp, String values) { /* 82 */ super(nt, nc, type); /* */ /* */ /* */ /* */ /* */ /* 88 */ this.q = values; /* 89 */ String param = this.q; /* 90 */ boolean isFilterSpecified = true; /* */ /* */ /* 93 */ if (values == null) { /* 94 */ isFilterSpecified = false; /* */ /* 96 */ if (wp.getLossless()) { /* 97 */ a(a("w5x3")); /* */ /* */ /* */ return; /* */ } /* */ /* */ /* 104 */ for (int i = nt - 1; i >= 0; i--) { /* 105 */ for (int j = nc - 1; j >= 0; j--) { /* 106 */ switch (qts.c(i, j)) { /* */ case 0: /* 108 */ if (d() == null) { /* 109 */ if (wp.getLossless()) /* 110 */ a(a("w5x3")); /* 111 */ if (((String)qts.d()) /* 112 */ .equals("reversible")) { /* 113 */ a(a("w5x3")); /* */ } else { /* */ /* 116 */ a(a("w9x7")); /* */ } /* */ } /* 119 */ this.l[i][j] = 0; /* */ break; /* */ case 1: /* 122 */ if (!g(j)) { /* 123 */ if (((String)qts.e(j)) /* 124 */ .equals("reversible")) { /* 125 */ a(j, a("w5x3")); /* */ } else { /* */ /* 128 */ a(j, a("w9x7")); /* */ } /* */ } /* 131 */ this.l[i][j] = 1; /* */ break; /* */ case 2: /* 134 */ if (!h(i)) { /* 135 */ if (((String)qts.f(i)) /* 136 */ .equals("reversible")) { /* 137 */ b(i, a("w5x3")); /* */ } else { /* */ /* 140 */ b(i, a("w9x7")); /* */ } /* */ } /* 143 */ this.l[i][j] = 2; /* */ break; /* */ case 3: /* 146 */ if (!d(i, j)) { /* 147 */ if (((String)qts.a(i, j)) /* 148 */ .equals("reversible")) { /* 149 */ a(i, j, a("w5x3")); /* */ } else { /* */ /* 152 */ a(i, j, /* 153 */ a("w9x7")); /* */ } /* */ } /* 156 */ this.l[i][j] = 3; /* */ break; /* */ default: /* 159 */ throw new IllegalArgumentException("Unsupported specification type"); /* */ } /* */ /* */ /* */ /* */ /* */ } /* */ } /* */ return; /* */ } /* 169 */ StringTokenizer stk = new StringTokenizer(param); /* */ /* 171 */ byte curSpecType = 0; /* */ /* 173 */ boolean[] tileSpec = null; /* 174 */ boolean[] compSpec = null; /* */ /* */ /* 177 */ while (stk.hasMoreTokens()) { /* 178 */ a[][] filter; String word = stk.nextToken(); /* */ /* 180 */ switch (word.charAt(0)) { /* */ case 'T': /* */ case 't': /* 183 */ tileSpec = a(word, this.j); /* 184 */ if (curSpecType == 1) { /* 185 */ curSpecType = 3; continue; /* */ } /* 187 */ curSpecType = 2; /* */ continue; /* */ case 'C': /* */ case 'c': /* 191 */ compSpec = a(word, this.k); /* 192 */ if (curSpecType == 2) { /* 193 */ curSpecType = 3; continue; /* */ } /* 195 */ curSpecType = 1; /* */ continue; /* */ case 'W': /* */ case 'w': /* 199 */ if (wp.getLossless() && word /* 200 */ .equalsIgnoreCase("w9x7")) { /* 201 */ throw new IllegalArgumentException("Cannot use non reversible wavelet transform with '-lossless' option"); /* */ } /* */ /* */ /* */ /* */ /* */ /* 208 */ filter = a(word); /* 209 */ if (curSpecType == 0) { /* 210 */ a(filter); /* */ } /* 212 */ else if (curSpecType == 2) { /* 213 */ for (int i = tileSpec.length - 1; i >= 0; i--) { /* 214 */ if (tileSpec[i]) { /* 215 */ b(i, filter); /* */ } /* */ } /* 218 */ } else if (curSpecType == 1) { /* 219 */ for (int i = compSpec.length - 1; i >= 0; i--) { /* 220 */ if (compSpec[i]) { /* 221 */ a(i, filter); /* */ } /* */ } /* */ } else { /* 225 */ for (int i = tileSpec.length - 1; i >= 0; i--) { /* 226 */ for (int j = compSpec.length - 1; j >= 0; j--) { /* 227 */ if (tileSpec[i] && compSpec[j]) { /* 228 */ a(i, j, filter); /* */ } /* */ } /* */ } /* */ } /* */ /* */ /* 235 */ curSpecType = 0; /* 236 */ tileSpec = null; /* 237 */ compSpec = null; /* */ continue; /* */ } /* */ /* 241 */ throw new IllegalArgumentException("Bad construction for parameter: " + word); /* */ } /* */ /* */ /* */ /* */ /* 247 */ if (d() == null) { /* 248 */ int ndefspec = 0; /* 249 */ for (int i = nt - 1; i >= 0; i--) { /* 250 */ for (int j = nc - 1; j >= 0; j--) { /* 251 */ if (this.l[i][j] == 0) { /* 252 */ ndefspec++; /* */ } /* */ } /* */ } /* */ /* */ /* */ /* 259 */ if (ndefspec != 0) { /* 260 */ if (((String)qts.d()).equals("reversible")) { /* 261 */ a(a("w5x3")); /* */ } else { /* 263 */ a(a("w9x7")); /* */ } /* */ } else { /* */ int k, j; /* */ /* 268 */ a(a(0, 0)); /* 269 */ switch (this.l[0][0]) { /* */ case 2: /* 271 */ for (k = nc - 1; k >= 0; k--) { /* 272 */ if (this.l[0][k] == 2) /* 273 */ this.l[0][k] = 0; /* */ } /* 275 */ this.o[0] = null; /* */ break; /* */ case 1: /* 278 */ for (j = nt - 1; j >= 0; j--) { /* 279 */ if (this.l[j][0] == 1) /* 280 */ this.l[j][0] = 0; /* */ } /* 282 */ this.n[0] = null; /* */ break; /* */ case 3: /* 285 */ this.l[0][0] = 0; /* 286 */ this.p.put("t0c0", null); /* */ break; /* */ } /* */ /* */ /* */ /* */ } /* */ } /* 294 */ for (int t = nt - 1; t >= 0; t--) { /* 295 */ for (int i = nc - 1; i >= 0; i--) { /* */ /* 297 */ if (((String)qts.a(t, i)).equals("reversible")) { /* */ /* 299 */ if (!h(t, i)) /* */ { /* */ /* 302 */ if (!isFilterSpecified) { /* 303 */ a(t, i, a("w5x3")); /* */ } /* */ else { /* */ /* 307 */ throw new IllegalArgumentException("Filter of tile-component (" + t + "," + i + ") does" + " not allow " + "reversible " + "quantization. " + "Specify '-Qtype " + "expounded' or " + "'-Qtype derived'" + "in " + "the command line."); /* */ /* */ /* */ /* */ /* */ } /* */ /* */ /* */ /* */ /* */ } /* */ /* */ /* */ /* */ } /* 322 */ else if (h(t, i)) { /* */ /* */ /* */ /* 326 */ if (!isFilterSpecified) { /* 327 */ a(t, i, a("w9x7")); /* */ } /* */ else { /* */ /* 331 */ throw new IllegalArgumentException("Filter of tile-component (" + t + "," + i + ") does" + " not allow " + "non-reversible " + "quantization. " + "Specify '-Qtype " + "reversible' in " + "the command line"); /* */ } /* */ } /* */ } /* */ } /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ private a[][] a(String word) { /* 355 */ a[][] filt = new a[2][1]; /* 356 */ if (word.equalsIgnoreCase("w5x3")) { /* 357 */ filt[0][0] = new e(); /* 358 */ filt[1][0] = new e(); /* 359 */ return filt; /* */ } /* 361 */ if (word.equalsIgnoreCase("w9x7")) { /* 362 */ filt[0][0] = new c(); /* 363 */ filt[1][0] = new c(); /* 364 */ return filt; /* */ } /* */ /* 367 */ throw new IllegalArgumentException("Non JPEG 2000 part I filter: " + word); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public int e(int t, int c) { /* 386 */ a[][] an = (a[][])b(t, c); /* 387 */ return an[0][0].j(); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public a[] f(int t, int c) { /* 409 */ a[][] an = (a[][])b(t, c); /* 410 */ return an[0]; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public a[] g(int t, int c) { /* 432 */ a[][] an = (a[][])b(t, c); /* 433 */ return an[1]; /* */ } /* */ /* */ /* */ public String toString() { /* 438 */ String str = ""; /* */ /* */ /* 441 */ str = str + "nTiles=" + this.j + "\nnComp=" + this.k + "\n\n"; /* */ /* 443 */ for (int t = 0; t < this.j; t++) { /* 444 */ for (int c = 0; c < this.k; c++) { /* 445 */ a[][] an = (a[][])b(t, c); /* */ /* 447 */ str = str + "(t:" + t + ",c:" + c + ")\n"; /* */ /* */ /* 450 */ str = str + "\tH:"; int i; /* 451 */ for (i = 0; i < (an[0]).length; i++) { /* 452 */ str = str + " " + an[0][i]; /* */ } /* 454 */ str = str + "\n\tV:"; /* 455 */ for (i = 0; i < (an[1]).length; i++) /* 456 */ str = str + " " + an[1][i]; /* 457 */ str = str + "\n"; /* */ } /* */ } /* */ /* 461 */ return str; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public boolean h(int t, int c) { /* 476 */ a[] hfilter = f(t, c); /* 477 */ a[] vfilter = g(t, c); /* */ /* */ /* 480 */ for (int i = hfilter.length - 1; i >= 0; i--) { /* 481 */ if (!hfilter[i].k() || !vfilter[i].k()) /* 482 */ return false; /* 483 */ } return true; /* */ } /* */ } /* Location: /mnt/r/ConTenDoViewer.jar!/c/a/j/a/f.class * Java compiler version: 5 (49.0) * JD-Core Version: 1.1.3 */
26.668024
256
0.259432
8f34f2ec435b2161c54ef91e3261484d7aa9b21d
3,429
package io.quarkus.arc.test.defaultbean; import static org.junit.jupiter.api.Assertions.assertEquals; import io.quarkus.arc.Arc; import io.quarkus.arc.DefaultBean; import io.quarkus.arc.test.ArcTestContainer; import java.util.Set; import java.util.stream.Collectors; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Instance; import javax.enterprise.inject.Produces; import javax.enterprise.inject.spi.CDI; import javax.inject.Inject; import javax.inject.Singleton; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; public class DefaultClassBeanTest { @RegisterExtension public ArcTestContainer container = new ArcTestContainer(Producer.class, GreetingBean.class, Hello.class, PingBean.class, Author.class, SciFi.class, Fantasy.class, Detective.class); @Test public void testInjection() { Hello hello = Arc.container().instance(Hello.class).get(); assertEquals("hello", hello.hello()); assertEquals("pong", hello.ping()); var result = hello.instance(); StringBuilder sb = new StringBuilder(); for (var i : result) { i.write(sb); } Assertions.assertTrue(sb.toString().contains("SciFi")); Assertions.assertTrue(sb.toString().contains("Fantasy")); Assertions.assertFalse(sb.toString().contains("Detective")); Set<Detective> detectives = Arc.container().beanManager().createInstance().select(Detective.class).stream() .collect(Collectors.toSet()); Assertions.assertEquals(1, detectives.size()); } @Test public void testSelect() { assertEquals("hello", CDI.current().select(GreetingBean.class).get().greet()); } @ApplicationScoped static class Hello { @Inject GreetingBean bean; @Inject PingBean ping; @Inject Instance<Author> instance; String hello() { return bean.greet(); } String ping() { return ping.ping(); } Instance<Author> instance() { return instance; } } @DefaultBean // This one is overriden by Producer.greetingBean() @Singleton static class GreetingBean { String greet() { return "hola"; } } @DefaultBean @Singleton static class PingBean { String ping() { return "pong"; } } @Singleton static class Producer { @Produces GreetingBean greetingBean() { return new GreetingBean() { @Override String greet() { return "hello"; } }; } } interface Author { void write(StringBuilder sb); } @Singleton static class SciFi implements Author { @Override public void write(StringBuilder sb) { sb.append("SciFi"); } } @Singleton static class Fantasy implements Author { @Override public void write(StringBuilder sb) { sb.append("Fantasy"); } } @Singleton @DefaultBean static class Detective implements Author { @Override public void write(StringBuilder sb) { sb.append("Detective"); } } }
24.319149
120
0.608049
995ceaab63f6063f2ecefe848adffafc46522a1e
9,305
/** * */ package org.pimslims.servlet.tag; import java.io.IOException; import java.util.Collection; import java.util.TreeMap; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.Tag; import org.apache.commons.lang.StringEscapeUtils; import org.pimslims.dao.ReadableVersion; import org.pimslims.metamodel.MetaClass; import org.pimslims.metamodel.ModelObject; /** * Tag for generating drop down list from records of type metaclass where labels are the values of attributes * delimited by delimiter * * @param version - ReadbleVersion * @param attributes - list of meta attributes names separated by commas (spaces should not be used) * @param metaClass - MetaClass - type of object to look for values * @param controls (optional) - this gets recorded as it is (without processing) in the top select statement * before values this allow to specify the class, name, style, id, multiple and the number of rows * displayed (!)if controls has not been defined only options will be generated (no start and end * of select tag) * @param emptyValue - Boolean true or false, (optional) if true empty value will be generated in the list as * default, value for this option is set to MetaClassName * @param delimiter String (optional)- value which is used to separate values of different attributes in the * label * @author Peter Troshin Usage example: <pims:list version="${modelObject.version}" * attributes="name,possibleValues" metaClass="${modelObject.metaClass}" controls="name='select' * style='width: 300px;' id='test' size='10' multiple " delimiter=" " emptyValue="true"/> * * This generate a list which allows multiple selection out of * org.pimslims.model.protocol.ParameterDefinition assuming that version is available and metaclass is * org.pimslims.model.protocol.ParameterDefinition */ @Deprecated // obsolete public class List extends PIMSTag { private String delimiter = null; private String metaClassName = null; private String selected = null; private String attributes = null; private boolean emptyValue = false; private ReadableVersion version = null; private String controls = null; private Collection<ModelObject> objectList = null; /* * (non-Javadoc) * * @see javax.servlet.jsp.tagext.TagSupport#doStartTag() */ @Override public int doStartTag() throws JspException { String select = ""; String selectEnd = ""; if (this.controls != null) { select = "<select " + this.controls + " >"; selectEnd = "</select>"; } MetaClass metaClass = null; if (this.objectList == null && this.metaClassName != null) { metaClass = this.version.getModel().getMetaClass(this.metaClassName); this.objectList = this.version.getAll(metaClass.getJavaClass(), 0, 1000); if (1000 <= this.objectList.size()) { throw new JspException("Too many records to list"); } } else { if (this.objectList == null || this.objectList.size() == 0) { // If object list was passed but it was empty try { final javax.servlet.jsp.JspWriter writer = this.pageContext.getOut(); // PiMS 1551 </select> // there may be more than 1 list - don't include the </select> tag //writer.print(select + "<option value=\"\" >none recorded</option></select>"); writer.print(select + "<option value=\"\" >none recorded</option>" + selectEnd); } catch (final IOException e) { throw new JspException(e); } this.objectList = null; // nullify the object list so that the next // call does not use them return Tag.SKIP_BODY; } metaClass = this.objectList.iterator().next().get_MetaClass(); } if (this.emptyValue) { select += "<option value=\"\" selected ></option>"; } String val = ""; this.delimiter = (this.delimiter == null) ? "" : this.delimiter; final TreeMap<String, String> sortedValues = new TreeMap<String, String>(); for (final ModelObject mobj : this.objectList) { val = ""; for (final String attributeName : this.parseAttributes()) { final Object value = mobj.get_Value(attributeName); if (value == null) { continue; } if (value instanceof String) { val += (String) value + this.delimiter; } else if (value instanceof Collection) { final Collection values = (Collection) value; for (final Object strValue : values) { val += strValue + this.delimiter; } } else { // Do not know how to handle -> skip continue; } } sortedValues.put(val, mobj.get_Hook()); } // boolean sel = false; for (String fval : sortedValues.keySet()) { final String hook = sortedValues.get(fval); // delete delimeter from the end of the label if (fval.length() > 0 && this.delimiter.length() > 0) { fval = fval.substring(0, fval.length() - this.delimiter.length()); } fval = StringEscapeUtils.escapeXml(fval); if (this.selected != null && hook.equals(this.selected)) { select += "<option value=\"" + hook + "\" selected>" + fval + "</option>" + "\n"; // sel=true; } else { select += "<option value=\"" + hook + "\">" + fval + "</option>" + "\n"; } } // if(! sel) System.out.println("hook to select " + selected); select += selectEnd; try { final javax.servlet.jsp.JspWriter writer = this.pageContext.getOut(); writer.print(select); } catch (final IOException e) { throw new JspException(e); } this.objectList = null; // nullify the object list so that the next call // does not use them return Tag.SKIP_BODY; } public void setDelimiter(final String delimiter) { this.delimiter = delimiter; } public void setMetaClassName(final String metaClassName) { this.metaClassName = metaClassName; } public void setAttributes(final String attributes) { this.attributes = attributes; } public void setSelected(final String selected) { this.selected = selected; } public void setVersion(final ReadableVersion version) { this.version = version; } public void setControls(final String controls) { this.controls = controls; } public void setObjectList(final Collection<ModelObject> objectList) { this.objectList = objectList; } public void setEmptyValue(final Boolean emptyValue) { this.emptyValue = (emptyValue != null) ? emptyValue.booleanValue() : false; } private String[] parseAttributes() { assert this.attributes != null : "Please specify the name of attributes for List tag"; return this.attributes.split(","); } /* private String getOnMouseOver() { <option value="${sample.hook}" onmouseover="experimentGroup='${sample}'; thisSample={name:'<c:out value="${sample.name}" />', details:'<c:out value="${sample.details}" />', componentsnumber:'${sample.sampleComponentsLength}', components:'<c:out value="${sample.sampleComponentsString}" />', hazardsnumber:'${sample.hazardPhasesLength}', hazards:'<c:out value="${sample.hazardPhasesString}" />', column:'${sample.colPosition}', row:'${sample.rowPosition}', subposition:'${sample.subPosition}', amount:'${sample.currentAmount}', units:'${sample.amountDisplayUnit}', specification:'${sample.refSample}', holder:'<c:out value="${sample.holderName}" />'}; showSampleToolTip(event, thisSample);" onmouseout="hideSampleToolTip();"> } */ }
40.811404
116
0.537775
40dc4caded12df6ce0b0c6c6cbd8cccae07d1251
1,581
package pool; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * Class EmailNotification - Отправка почты. */ public class EmailNotification { ExecutorService pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); /** * Метод emailTo. Постановка задания на отправку емейл. * @param user Пользователь. */ public void emailTo(User user) { pool.submit(() -> { String subject = String.format("Notification %s to email: %s", user.getUserName(), user.getEmail()); String body = String.format("Add a new event to: %s", user.getUserName()); System.out.println(Thread.currentThread().getName()); send(subject, body, user.getEmail()); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } }); } /** * Метод send. Отправка емейл. * @param subject Тема. * @param body Тело письма. * @param email Адрес. */ private void send(String subject, String body, String email) { System.out.format("%s.\n%s\n\n", subject, body); } /** * Метод close. Остановка пула. */ public void close() { pool.shutdown(); try { Thread.sleep(1000); if (pool.isShutdown()) { System.out.println("pool is SHUTDOWN"); } } catch (InterruptedException e) { e.printStackTrace(); } } }
30.403846
116
0.562935
9eabfac1bccd7f3db1b20c1aa7162861a0409a0d
3,185
package com.example.aws.v1.kinesis.producer; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import com.amazonaws.services.kinesis.AmazonKinesis; import com.amazonaws.services.kinesis.AmazonKinesisClientBuilder; import com.amazonaws.services.kinesis.model.DescribeStreamRequest; import com.amazonaws.services.kinesis.model.DescribeStreamResult; import com.amazonaws.services.kinesis.model.PutRecordsRequest; import com.amazonaws.services.kinesis.model.PutRecordsRequestEntry; import com.amazonaws.services.kinesis.model.PutRecordsResult; import com.amazonaws.services.kinesis.model.Shard; import com.example.aws.util.Config; import com.example.aws.util.RecordObject; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; public class DistributedExplicitHashKeyStreamsProducer { public static void main(String[] args) { final ObjectMapper mapper = new ObjectMapper(); AmazonKinesis kinesisClient = AmazonKinesisClientBuilder.standard().withRegion(Config.REGION).build(); // Prepare distributed ExplicitHashKey DescribeStreamRequest describeStreamRequest = new DescribeStreamRequest(); describeStreamRequest.setStreamName(Config.STREAM_NAME); DescribeStreamResult describeStreamResult = kinesisClient.describeStream(describeStreamRequest); List<Shard> shardList = describeStreamResult.getStreamDescription().getShards(); List<String> explicitHashKeyList = new ArrayList<>(); while (explicitHashKeyList.size() < Config.RECORD_COUNT) { for (Shard shard : shardList) { explicitHashKeyList.add(shard.getHashKeyRange().getStartingHashKey()); if (explicitHashKeyList.size() >= Config.RECORD_COUNT) { break; } } } PutRecordsRequest putRecordsRequest = new PutRecordsRequest(); putRecordsRequest.setStreamName(Config.STREAM_NAME); List<RecordObject> recordObjects = new ArrayList<>(); for (int i = 0; i < Config.RECORD_COUNT; i++) { RecordObject recordObject = new RecordObject(String.valueOf(i)); recordObjects.add(recordObject); } while (true) { List<PutRecordsRequestEntry> putRecordsRequestEntryList = new ArrayList<>(); for (int i = 0; i < Config.RECORD_COUNT; i++) { RecordObject recordObject = recordObjects.get(i); recordObject.incrementRecordCount(); recordObject.setTimestampToNow(); PutRecordsRequestEntry putRecordsRequestEntry = new PutRecordsRequestEntry(); try { putRecordsRequestEntry.setData(ByteBuffer.wrap(mapper.writeValueAsString(recordObject).getBytes())); } catch (JsonProcessingException e) { e.printStackTrace(); } putRecordsRequestEntry.setPartitionKey(recordObject.partitionKey); putRecordsRequestEntry.setExplicitHashKey(explicitHashKeyList.get(i)); putRecordsRequestEntryList.add(putRecordsRequestEntry); } putRecordsRequest.setRecords(putRecordsRequestEntryList); PutRecordsResult putRecordsResult = kinesisClient.putRecords(putRecordsRequest); System.out.println("Put Result : " + putRecordsResult); try { Thread.sleep(Config.RECORD_INTERVAL_MILLIS); } catch (InterruptedException e) { e.printStackTrace(); } } } }
39.8125
105
0.787441
e96ef3ea75256810809b65542571f11671140edd
1,062
package com.example.listviewsqlite2; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * sqlite database helper to create table into SQLite database * @author ketan(Visit my <a * href="http://androidsolution4u.blogspot.in/">blog</a>) */ public class DbHelper extends SQLiteOpenHelper { static String DATABASE_NAME="userdata"; public static final String TABLE_NAME="user"; public static final String KEY_FNAME="fname"; public static final String KEY_LNAME="lname"; public static final String KEY_ID="id"; public DbHelper(Context context) { super(context, DATABASE_NAME, null, 1); } @Override public void onCreate(SQLiteDatabase db) { String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_FNAME+" TEXT, "+KEY_LNAME+" TEXT)"; db.execSQL(CREATE_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME); onCreate(db); } }
28.702703
125
0.747646
3020f28a6e269b0b8bc30400b1bcdb90767acf41
68
package org.slcloud.dt.service; public interface MainService { }
9.714286
31
0.764706
dbef23de1fa9e51d1ec08950dab36596412a61ab
2,027
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.execution.configurations; import com.intellij.util.ArrayUtil; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import javax.swing.*; /** * @author yole */ public abstract class ConfigurationTypeBase implements ConfigurationType { private static final ConfigurationFactory[] EMPTY_FACTORIES = new ConfigurationFactory[0]; private final String myId; private final String myDisplayName; private final String myDescription; private final Icon myIcon; private ConfigurationFactory[] myFactories; protected ConfigurationTypeBase(@NotNull @NonNls String id, @Nls String displayName, @Nls String description, Icon icon) { myId = id; myDisplayName = displayName; myDescription = description; myIcon = icon; myFactories = EMPTY_FACTORIES; } protected void addFactory(ConfigurationFactory factory) { myFactories = ArrayUtil.append(myFactories, factory); } @Override @Nls public String getDisplayName() { return myDisplayName; } @Override @Nls public String getConfigurationTypeDescription() { return myDescription; } @Override public Icon getIcon() { return myIcon; } @Override @NotNull @NonNls public String getId() { return myId; } @Override public ConfigurationFactory[] getConfigurationFactories() { return myFactories; } }
25.658228
124
0.74297
885cb9ca45d558513d958531ae31c063e54b02f6
4,478
/* * Copyright 2016 Martin Winandy * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package org.tinylog.provider; import java.io.IOException; import java.util.Collection; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.tinylog.Level; import org.tinylog.rules.SystemStreamCollector; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link InternalLogger}. */ @RunWith(Parameterized.class) public final class InternalLoggerTest { /** * Redirects and collects system output streams. */ @Rule public final SystemStreamCollector systemStream = new SystemStreamCollector(true); private final Level severityLevel; private final String outputLevel; /** * @param severityLevel * Severity level for issuing log entry * @param outputLevel * Expected severity level text in outputs */ public InternalLoggerTest(final Level severityLevel, final String outputLevel) { this.severityLevel = severityLevel; this.outputLevel = outputLevel; } /** * Returns all severity levels that are relevant for testing. * * @return Each object array contains the severity level for issuing log entries and the expected severity level * text in outputs */ @Parameters(name = "{1}") public static Collection<Object[]> getLevels() { return asList(new Object[][] { { Level.WARN, "WARN" }, { Level.ERROR, "ERROR" } }); } /** * Verifies that plain text messages will be output correctly. */ @Test public void textMessage() { InternalLogger.log(severityLevel, "Hello World!"); assertThat(systemStream.consumeErrorOutput()) .startsWith("LOGGER ") .containsOnlyOnce(outputLevel) .containsOnlyOnce("Hello World!") .endsWith(System.lineSeparator()) .hasLineCount(1); } /** * Verifies that exceptions that don't provide a detail message will be output correctly. */ @Test public void exception() { InternalLogger.log(severityLevel, new NullPointerException()); assertThat(systemStream.consumeErrorOutput()) .startsWith("LOGGER ") .containsOnlyOnce(outputLevel) .containsOnlyOnce(NullPointerException.class.getName()) .endsWith(System.lineSeparator()) .hasLineCount(1); } /** * Verifies that exceptions that provide a detail message will be output correctly. */ @Test public void exceptionWithDescription() { InternalLogger.log(severityLevel, new IOException("File not found")); assertThat(systemStream.consumeErrorOutput()) .startsWith("LOGGER ") .containsOnlyOnce(outputLevel) .containsOnlyOnce(IOException.class.getName()) .containsOnlyOnce("File not found") .endsWith(System.lineSeparator()) .hasLineCount(1); } /** * Verifies that exceptions that don't provide a detail message will be output correctly in combination with a * custom text message. */ @Test public void exceptionAndTextMessage() { InternalLogger.log(severityLevel, new NullPointerException(), "Hello World!"); assertThat(systemStream.consumeErrorOutput()) .startsWith("LOGGER ") .containsOnlyOnce(outputLevel) .containsOnlyOnce(NullPointerException.class.getName()) .containsOnlyOnce("Hello World!") .endsWith(System.lineSeparator()) .hasLineCount(1); } /** * Verifies that exceptions that provide a detail message will be output correctly in combination with a custom text * message. */ @Test public void exceptionWithDescriptionAndTextMessage() { InternalLogger.log(severityLevel, new IOException("File not found"), "Hello World!"); assertThat(systemStream.consumeErrorOutput()) .startsWith("LOGGER ") .containsOnlyOnce(outputLevel) .containsOnlyOnce(IOException.class.getName()) .containsOnlyOnce("File not found") .containsOnlyOnce("Hello World!") .endsWith(System.lineSeparator()) .hasLineCount(1); } }
30.053691
118
0.739839
299013e27bc37e8b611e0e1e2c220cd091678bd6
3,842
package com.cool.model; import java.util.Date; import com.alibaba.fastjson.annotation.JSONField; import com.cool.base.BaseModel; /** * * @ClassName: Scheduler * @Description: 定时任务 * @author panlei * @date 2017年8月10日 上午10:56:15 * */ public class TaskScheduler extends BaseModel { private static final long serialVersionUID = 1L; /** * 所属分组ID */ private Long groupId; /** * 任务名称 */ private String taskName; /** * 任务描述 */ private String taskDesc; /** * 任务类型 */ private String taskType; /** * 时间策略 */ private String timeConfig; /** * 状态,0:停用;1:启用 */ private Integer status; /** * 任务最后执行时间 */ @JSONField(format = "yyyy-MM-dd HH:mm:ss") private Date taskLastExecTime; /** * 任务最近一次执行时长 */ private Long taskLastExecTimes; /** * 任务下次执行时间 */ @JSONField(format = "yyyy-MM-dd HH:mm:ss") private Date taskNextExecTime; /** * 生效时间 */ @JSONField(format = "yyyy-MM-dd HH:mm:ss") private Date effectTime; /** * 自动随系统启动 */ private Integer autoStart; /** * @param groupId * the groupId to set */ public void setGroupId(Long groupId) { this.groupId = groupId; } /** * @return the groupId */ public Long getGroupId() { return this.groupId; } /** * @param taskName * the taskName to set */ public void setTaskName(String taskName) { this.taskName = taskName; } /** * @return the taskName */ public String getTaskName() { return this.taskName; } /** * @param taskDesc * the taskDesc to set */ public void setTaskDesc(String taskDesc) { this.taskDesc = taskDesc; } /** * @return the taskDesc */ public String getTaskDesc() { return this.taskDesc; } /** * @param taskType * the taskType to set */ public void setTaskType(String taskType) { this.taskType = taskType; } /** * @return the taskType */ public String getTaskType() { return this.taskType; } /** * @param timeConfig * the timeConfig to set */ public void setTimeConfig(String timeConfig) { this.timeConfig = timeConfig; } /** * @return the timeConfig */ public String getTimeConfig() { return this.timeConfig; } /** * @param status * the status to set */ public void setStatus(Integer status) { this.status = status; } /** * @return the status */ public Integer getStatus() { return this.status; } /** * @param taskLastExecTime * the taskLastExecTime to set */ public void setTaskLastExecTime(Date taskLastExecTime) { this.taskLastExecTime = taskLastExecTime; } /** * @return the taskLastExecTime */ public Date getTaskLastExecTime() { return this.taskLastExecTime; } /** * @param taskLastExecTimes * the taskLastExecTimes to set */ public void setTaskLastExecTimes(Long taskLastExecTimes) { this.taskLastExecTimes = taskLastExecTimes; } /** * @return the taskLastExecTimes */ public Long getTaskLastExecTimes() { return this.taskLastExecTimes; } /** * @param taskNextExecTime * the taskNextExecTime to set */ public void setTaskNextExecTime(Date taskNextExecTime) { this.taskNextExecTime = taskNextExecTime; } /** * @return the taskNextExecTime */ public Date getTaskNextExecTime() { return this.taskNextExecTime; } /** * @param effectTime * the effectTime to set */ public void setEffectTime(Date effectTime) { this.effectTime = effectTime; } /** * @return the effectTime */ public Date getEffectTime() { return this.effectTime; } /** * @return property value of autoStart */ public Integer getAutoStart() { return autoStart; } /** * @param autoStart value to be assigned to property autoStart */ public void setAutoStart(Integer autoStart) { this.autoStart = autoStart; } }
16.560345
63
0.643675
ee1cd69cbcf3a405d80259832161681b7afc5a9c
7,195
/* * Copyright 2012-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.autoconfigure.security.oauth2.client; import java.util.HashMap; import java.util.Map; import org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientProperties.Provider; import org.springframework.boot.context.properties.PropertyMapper; import org.springframework.boot.convert.ApplicationConversionService; import org.springframework.core.convert.ConversionException; import org.springframework.security.config.oauth2.client.CommonOAuth2Provider; import org.springframework.security.oauth2.client.registration.ClientRegistration; import org.springframework.security.oauth2.client.registration.ClientRegistration.Builder; import org.springframework.security.oauth2.client.registration.ClientRegistrations; import org.springframework.security.oauth2.core.AuthenticationMethod; import org.springframework.security.oauth2.core.AuthorizationGrantType; import org.springframework.security.oauth2.core.ClientAuthenticationMethod; import org.springframework.util.StringUtils; /** * Adapter class to convert {@link OAuth2ClientProperties} to a * {@link ClientRegistration}. * * @author Phillip Webb * @author Thiago Hirata * @author Madhura Bhave * @author MyeongHyeon Lee * @since 2.1.0 */ public final class OAuth2ClientPropertiesRegistrationAdapter { private OAuth2ClientPropertiesRegistrationAdapter() { } public static Map<String, ClientRegistration> getClientRegistrations( OAuth2ClientProperties properties) { Map<String, ClientRegistration> clientRegistrations = new HashMap<>(); properties.getRegistration().getLogin() .forEach((key, value) -> clientRegistrations.put(key, getLoginClientRegistration(key, value, properties.getProvider()))); properties.getRegistration().getAuthorizationCode() .forEach((key, value) -> clientRegistrations.put(key, getAuthorizationCodeClientRegistration(key, value, properties.getProvider()))); return clientRegistrations; } private static ClientRegistration getAuthorizationCodeClientRegistration( String registrationId, OAuth2ClientProperties.AuthorizationCodeClientRegistration properties, Map<String, Provider> providers) { PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); Builder builder = getBuilder(map, registrationId, properties, providers); map.from(properties::getRedirectUri).to(builder::redirectUriTemplate); return builder.build(); } private static Builder getBuilder(PropertyMapper map, String registrationId, OAuth2ClientProperties.BaseClientRegistration properties, Map<String, Provider> providers) { Builder builder = getBuilderFromIssuerIfPossible(registrationId, properties.getProvider(), providers); if (builder == null) { builder = getBuilder(registrationId, properties.getProvider(), providers); } map.from(properties::getClientId).to(builder::clientId); map.from(properties::getClientSecret).to(builder::clientSecret); map.from(properties::getClientAuthenticationMethod) .as(ClientAuthenticationMethod::new) .to(builder::clientAuthenticationMethod); map.from(properties::getAuthorizationGrantType).as(AuthorizationGrantType::new) .to(builder::authorizationGrantType); map.from(properties::getScope).as((scope) -> StringUtils.toStringArray(scope)) .to(builder::scope); map.from(properties::getClientName).to(builder::clientName); return builder; } private static ClientRegistration getLoginClientRegistration(String registrationId, OAuth2ClientProperties.LoginClientRegistration properties, Map<String, Provider> providers) { PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); Builder builder = getBuilder(map, registrationId, properties, providers); map.from(properties::getRedirectUri).to(builder::redirectUriTemplate); return builder.build(); } private static Builder getBuilderFromIssuerIfPossible(String registrationId, String configuredProviderId, Map<String, Provider> providers) { String providerId = (configuredProviderId != null) ? configuredProviderId : registrationId; if (providers.containsKey(providerId)) { Provider provider = providers.get(providerId); String issuer = provider.getIssuerUri(); if (issuer != null) { String cleanedIssuer = cleanIssuerPath(issuer); Builder builder = ClientRegistrations .fromOidcIssuerLocation(cleanedIssuer) .registrationId(registrationId); return getBuilder(builder, provider); } } return null; } private static String cleanIssuerPath(String issuer) { if (issuer.endsWith("/")) { return issuer.substring(0, issuer.length() - 1); } return issuer; } private static Builder getBuilder(String registrationId, String configuredProviderId, Map<String, Provider> providers) { String providerId = (configuredProviderId != null) ? configuredProviderId : registrationId; CommonOAuth2Provider provider = getCommonProvider(providerId); if (provider == null && !providers.containsKey(providerId)) { throw new IllegalStateException( getErrorMessage(configuredProviderId, registrationId)); } Builder builder = (provider != null) ? provider.getBuilder(registrationId) : ClientRegistration.withRegistrationId(registrationId); if (providers.containsKey(providerId)) { return getBuilder(builder, providers.get(providerId)); } return builder; } private static String getErrorMessage(String configuredProviderId, String registrationId) { return ((configuredProviderId != null) ? "Unknown provider ID '" + configuredProviderId + "'" : "Provider ID must be specified for client registration '" + registrationId + "'"); } private static Builder getBuilder(Builder builder, Provider provider) { PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); map.from(provider::getAuthorizationUri).to(builder::authorizationUri); map.from(provider::getTokenUri).to(builder::tokenUri); map.from(provider::getUserInfoUri).to(builder::userInfoUri); map.from(provider::getUserInfoAuthenticationMethod).as(AuthenticationMethod::new) .to(builder::userInfoAuthenticationMethod); map.from(provider::getJwkSetUri).to(builder::jwkSetUri); map.from(provider::getUserNameAttribute).to(builder::userNameAttributeName); return builder; } private static CommonOAuth2Provider getCommonProvider(String providerId) { try { return ApplicationConversionService.getSharedInstance().convert(providerId, CommonOAuth2Provider.class); } catch (ConversionException ex) { return null; } } }
40.649718
101
0.779986
e6ff5d587d64a73f7b4d34f6a4651895d09b23e8
32
// int.apply(abc, int, abc); //
8
25
0.53125
6740c16c487be3a50f6dd238e9826de1b8598e8b
402
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package sandesh.launcher; import sandesh.gui.GUIHandler; /** * * @author victory */ public class SandeshLauncher { public static void main(String...s) { GUIHandler.getInstance().start(); } }
19.142857
79
0.689055
bd2a1e556a06c1087c4b8dffc10f461ca8f812ae
704
/** * Copyright (c) The openTCS Authors. * * This program is free software and subject to the MIT license. (For details, * see the licensing information (LICENSE.txt) you should have received with * this copy of the software.) */ package org.opentcs.virtualvehicle.inputcomponents; import java.util.EventListener; /** * A listener interface for {@link ValidationEvent ValidationEvents}. * * @author Tobias Marquardt (Fraunhofer IML) */ public interface ValidationListener extends EventListener { /** * Should be called when the state of validation changed. * * @param e The ValidationEvent containing validation information. */ void validityChanged(ValidationEvent e); }
26.074074
78
0.738636
ecb2132ffb8dfd91e35b1f7846e3a9e371b749c3
6,455
package org.gertje.abacus; import org.gertje.abacus.functions.RandFunction; import org.gertje.abacus.symboltable.NoSuchVariableException; import org.gertje.abacus.symboltable.SimpleSymbolTable; import org.gertje.abacus.symboltable.SymbolTable; import org.gertje.abacus.symboltable.Variable; import org.gertje.abacus.types.Type; import org.gertje.abacus.util.JavaTypeHelper; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Array; import java.math.BigDecimal; import java.sql.Date; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Abstract class to run a test case. */ public abstract class AbstractTestCaseRunner { /** * The current test case. */ protected AbacusTestCase abacusTestCase; /** * Runs the test case. */ public abstract void runTestCase(); /** * Creates the symbol table from the {@link AbacusTestCase#variableListBefore}. * @return the symbol table. */ protected SimpleSymbolTable createSymbolTable() { SimpleSymbolTable symbolTable = new SimpleSymbolTable(); symbolTable.registerFunction(new RandFunction()); List<AbacusTestCase.Value> valueList = abacusTestCase.variableListBefore; if (valueList == null) { return symbolTable; } Map<String, Variable> variableMap = new HashMap<>(valueList.size()); Map<String, Object> valueMap = new HashMap<>(valueList.size()); for (AbacusTestCase.Value value : valueList) { variableMap.put(value.name, new Variable(value.name, value.type)); valueMap.put(value.name, convertToType(value.value, value.type)); } symbolTable.setVariables(variableMap, valueMap); return symbolTable; } /** * Converts the given value to the given type. * @param value The value in String representation. * @param type The type to convert the value to. * @return The converted value. */ protected Object convertToType(Object value, Type type) { if (value == null || "null".equals(value)) { return null; } if (type.isArray()) { List valueList = (List) value; Type componentType = type.determineComponentType(); Object[] array = (Object[]) Array.newInstance(JavaTypeHelper.determineJavaType(componentType), valueList.size()); for (int i = 0; i < array.length; i++) { array[i] = convertToType(valueList.get(i), componentType); } return array; } switch (type.getBaseType()) { case DECIMAL: return new BigDecimal(value.toString()); case INTEGER: return value instanceof Double ? (long) ((double) value) : Long.valueOf(value.toString()); case BOOLEAN: return Boolean.valueOf(value.toString()); case DATE: return Date.valueOf(value.toString()); case STRING: return value; } throw new IllegalArgumentException("Could not convert the string to the correct type."); } /** * Controleert of de return-waarde klopt met de verwachtte-return-waarde. * @param value De return-waarde. * @return {@code true} wanneer de return-waarde correct was, anders {@code false}. */ protected boolean checkReturnValue(Object value) { return checkValues(value, determineExpectedValue()); } /** * Bepaalt de verwachtte waarde. * @return De verwachtte waarde. */ protected Object determineExpectedValue() { return convertToType(abacusTestCase.returnValue.value, abacusTestCase.returnValue.type); } /** * Controleert of het type gelijk is aan het verwachtte type. * @param type Het type. * @return {@code true} wanneer beide types overeenkomen, anders {@code false}. */ protected boolean checkReturnType(Type type) { return type == abacusTestCase.returnValue.type; } /** * Checks if the resulting symbol table corresponds to what is expected. * @param symbolTable The resulting symbol table. * @return {@code true} if it corresponds, {@code false} otherwise. */ protected boolean checkSymbolTable(SymbolTable symbolTable) { List<AbacusTestCase.Value> valueAfterList = abacusTestCase.variableListAfter; if (valueAfterList == null) { return true; } try { for (AbacusTestCase.Value value : valueAfterList) { Object variableValue = symbolTable.getVariableValue(value.name); Object expectedValue = convertToType(value.value, value.type); Type variableType = symbolTable.getVariableType(value.name); if (!Type.equals(variableType, value.type)) { return false; } if (!checkValues(variableValue, expectedValue)) { return false; } } } catch (NoSuchVariableException e) { return false; } return true; } private boolean checkValues(Object variableValue, Object expectedValue) { // If they are both null, they are equal. if (variableValue == null && expectedValue == null) { return true; } // If one is null, they are not equal (since they are not both null). if (variableValue == null || expectedValue == null) { return false; } // If either of one is an array, but the other is not, they are not equal. if (variableValue instanceof Object[] && !(expectedValue instanceof Object[]) || !(variableValue instanceof Object[]) && expectedValue instanceof Object[]) { return false; } if (variableValue instanceof Object[]) { return Arrays.deepEquals((Object[]) variableValue, (Object[]) expectedValue); } if (((Comparable) variableValue).compareTo(expectedValue) != 0) { return false; } return true; } /** * Creates a message for when the Assert failes. * @param message The basis of the message. * @return The message with extra information. */ protected String createMessage(String message) { return createMessage(message, null); } /** * Creates a message for when the Assert failes. * @param message The basis of the message. * @param e The exception thrown by Abacus. * @return The message with extra information. */ protected String createMessage(String message, Exception e) { String exceptionStackTrace = null; if (e != null) { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); e.printStackTrace(printWriter); exceptionStackTrace = stringWriter.toString(); } return "Test file: '" + abacusTestCase.getFilename() + " Expression: '" + abacusTestCase.expression + "' - " + message + (exceptionStackTrace == null ? "" : "\n" + exceptionStackTrace); } public void setAbacusTestCase(AbacusTestCase abacusTestCase) { this.abacusTestCase = abacusTestCase; } }
29.746544
110
0.718358
4cebf5ac19947f34c4fb1a1a52e2876b01cc52bc
1,234
package cn.jeeweb.bbs.modules.front.constant; /** * All rights Reserved, Designed By www.jeeweb.cn * * @version V1.0 * @package cn.jeeweb.bbs.modules.front.constant * @title: * @description: Cache工具类 * @author: 王存见 * @date: 2018/9/3 16:24 * @copyright: 2017 www.jeeweb.cn Inc. All rights reserved. */ public class FrontConstant { //消息模板 public final static String MESSAGE_COMMENT_REPLY_TEMPLATE_CODE = "iheyj2har8"; //回答了求解 public final static String MESSAGE_COMMENT_REPLY_AT_TEMPLATE_CODE = "yfsidsne12"; //回复中AT了你 public final static String MESSAGE_COMMENT_PRODUCT_ORDDER_SUCCESS_TEMPLATE_CODE = "ur780e3fjt"; //付款成功 //邮件模板 public final static String EMAIL_ACTIVATE_EMAIL_TEMPLATE_CODE = "l2g4ywbs0l"; //激活邮箱 public final static String EMAIL_FORGET_PASS_TEMPLATE_CODE = "7e6cww7l5t"; //找回密码 public final static String EMAIL_COMMENT_PRODUCT_ORDDER_SUCCESS_TEMPLATE_CODE = "yfsidsne12"; //付款成功 //短信模板 public final static String SMS_REGISTER_TEMPLATE_CODE = "7hch8lsi8w"; //用户注册 public final static String SMS_FORGET_PASS_TEMPLATE_CODE = "oal0up6qo2"; //找回密码 public final static String SMS_COMMENT_PRODUCT_ORDDER_SUCCESS_TEMPLATE_CODE = "yfsidsne12"; //付款成功 }
33.351351
107
0.754457
3b2043f15316838d2a1f297aa381cccd3bc34791
4,598
package mage.cards.h; import mage.ObjectColor; import mage.abilities.Ability; import mage.abilities.common.SimpleActivatedAbility; import mage.abilities.costs.Cost; import mage.abilities.costs.common.SacrificeTargetCost; import mage.abilities.costs.mana.ManaCostsImpl; import mage.abilities.effects.ContinuousEffect; import mage.abilities.effects.OneShotEffect; import mage.abilities.effects.common.PreventDamageByTargetEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Duration; import mage.constants.Outcome; import mage.constants.Zone; import mage.filter.common.FilterAttackingCreature; import mage.filter.common.FilterControlledCreaturePermanent; import mage.filter.predicate.mageobject.ColorPredicate; import mage.game.Game; import mage.game.permanent.Permanent; import mage.players.Player; import mage.target.common.TargetControlledCreaturePermanent; import mage.target.targetpointer.FixedTarget; import java.util.ArrayList; import java.util.List; import java.util.UUID; /** * @author L_J */ public final class Heroism extends CardImpl { private static final FilterControlledCreaturePermanent filter = new FilterControlledCreaturePermanent("a white creature"); static { filter.add(new ColorPredicate(ObjectColor.WHITE)); } public Heroism(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT}, "{2}{W}"); // Sacrifice a white creature: For each attacking red creature, prevent all combat damage that would be dealt by that creature this turn unless its controller pays {2}{R}. this.addAbility(new SimpleActivatedAbility(Zone.BATTLEFIELD, new HeroismEffect(), new SacrificeTargetCost(new TargetControlledCreaturePermanent(1, 1, filter, true)))); } private Heroism(final Heroism card) { super(card); } @Override public Heroism copy() { return new Heroism(this); } } class HeroismEffect extends OneShotEffect { private static final FilterAttackingCreature filter = new FilterAttackingCreature("attacking red creature"); static { filter.add(new ColorPredicate(ObjectColor.RED)); } public HeroismEffect() { super(Outcome.Benefit); this.staticText = "For each attacking red creature, prevent all combat damage that would be dealt by that creature this turn unless its controller pays {2}{R}"; } public HeroismEffect(final HeroismEffect effect) { super(effect); } @Override public HeroismEffect copy() { return new HeroismEffect(this); } @Override public boolean apply(Game game, Ability source) { Player controller = game.getPlayer(source.getControllerId()); if (controller != null) { Player player = game.getPlayer(game.getActivePlayerId()); Cost cost = new ManaCostsImpl<>("{2}{R}"); List<Permanent> permanentsToPrevent = new ArrayList<>(); for (Permanent permanent : game.getState().getBattlefield().getAllActivePermanents(filter, game.getActivePlayerId(), game)) { cost.clearPaid(); String message = "Pay " + cost.getText() + "? If you don't, " + permanent.getLogName() + "'s combat damage will be prevented this turn."; if (player != null) { if (player.chooseUse(Outcome.Neutral, message, source, game)) { if (cost.pay(source, game, source, player.getId(), false, null)) { game.informPlayers(player.getLogName() + " paid " + cost.getText() + " for " + permanent.getLogName()); } else { game.informPlayers(player.getLogName() + " didn't pay " + cost.getText() + " for " + permanent.getLogName()); permanentsToPrevent.add(permanent); } } else{ game.informPlayers(player.getLogName() + " didn't pay " + cost.getText() + " for " + permanent.getLogName()); permanentsToPrevent.add(permanent); } } } for (Permanent permanent : permanentsToPrevent) { ContinuousEffect effect = new PreventDamageByTargetEffect(Duration.EndOfTurn, Integer.MAX_VALUE, true); effect.setTargetPointer(new FixedTarget(permanent, game)); game.addEffect(effect, source); } return true; } return false; } }
38.966102
179
0.663984
e46a2b626212f4e869010ab68525eb1d04a09d5d
293
/** * Closer to actual tests (in the more traditional software engineering sense). However, this * is still not automated.<br> * All the classes here are accessible through the {@link com.payne.games.piemenu.testMenu.core.TestsMenu}. */ package com.payne.games.piemenu.testMenu.otherTests;
48.833333
107
0.767918
2c55731cd38765873366286397eec9386ec7285a
928
package com.yxb.tinylove.netty; import com.yxb.tinylove.config.queue.MsgQueueHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; /** * @author yxb * @since 2021/12/30 */ @Component public class NettyServerListener implements ServletContextListener { @Autowired private WsStarter wsStarter; @Value("${websocket.port}") private int port; @Autowired private MsgQueueHandler msgQueueHandler; @Override public void contextInitialized(ServletContextEvent sce) { wsStarter.start(port); msgQueueHandler.start(); } @Override public void contextDestroyed(ServletContextEvent sce) { wsStarter.destroy(); msgQueueHandler.stop(); } }
23.2
68
0.743534
929d8d912395c472bf295b1ca39c5320710d825c
2,656
package lecho.lib.hellocharts.samples.lib.animation; import android.animation.Animator; import android.animation.Animator.AnimatorListener; import android.animation.ValueAnimator; import android.animation.ValueAnimator.AnimatorUpdateListener; import android.annotation.SuppressLint; import lecho.lib.hellocharts.samples.lib.view.PieChartView; @SuppressLint("NewApi") public class PieChartRotationAnimatorV14 implements PieChartRotationAnimator, AnimatorListener, AnimatorUpdateListener { private final PieChartView chart; private ValueAnimator animator; private float startRotation = 0; private float targetRotation = 0; private ChartAnimationListener animationListener = new DummyChartAnimationListener(); public PieChartRotationAnimatorV14(PieChartView chart) { this(chart, FAST_ANIMATION_DURATION); } public PieChartRotationAnimatorV14(PieChartView chart, long duration) { this.chart = chart; animator = ValueAnimator.ofFloat(0.0f, 1.0f); animator.setDuration(duration); animator.addListener(this); animator.addUpdateListener(this); } @Override public void startAnimation(float startRotation, float targetRotation) { this.startRotation = (startRotation % 360 + 360) % 360; this.targetRotation = (targetRotation % 360 + 360) % 360; animator.start(); } @Override public void cancelAnimation() { animator.cancel(); } @Override public void onAnimationUpdate(ValueAnimator animation) { float scale = animation.getAnimatedFraction(); float rotation = startRotation + (targetRotation - startRotation) * scale; rotation = (rotation % 360 + 360) % 360; chart.setChartRotation((int) rotation, false); } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { chart.setChartRotation((int) targetRotation, false); animationListener.onAnimationFinished(); } @Override public void onAnimationRepeat(Animator animation) { } @Override public void onAnimationStart(Animator animation) { animationListener.onAnimationStarted(); } @Override public boolean isAnimationStarted() { return animator.isStarted(); } @Override public void setChartAnimationListener(ChartAnimationListener animationListener) { if (null == animationListener) { this.animationListener = new DummyChartAnimationListener(); } else { this.animationListener = animationListener; } } }
31.247059
120
0.71009
17407b0d703d900ecd5680174699a1beff1150ca
443
package com.jukusoft.rpgcreator.server.common.database; import java.io.File; /** * Created by Justin on 31.05.2017. */ public interface Database { /** * connect to database * * @param configFile path to configuration file * * @return true, if client could connect to database */ public boolean connect (File configFile); /** * disconnect from database */ public void disconnect (); }
17.72
56
0.638826
2a22e23e16db73f29fefdc66e1f2ec97523d8b42
4,029
// Generated code from Butter Knife. Do not modify! package com.murainy.safeexam.activitis; import android.support.annotation.CallSuper; import android.support.annotation.UiThread; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import butterknife.Unbinder; import butterknife.internal.DebouncingOnClickListener; import butterknife.internal.Utils; import com.murainy.safeexam.R; import java.lang.IllegalStateException; import java.lang.Override; public class LauncherActivity_ViewBinding implements Unbinder { private LauncherActivity target; private View view2131296750; private View view2131296784; private View view2131296756; private View view2131296765; private View view2131296709; private View view2131296592; @UiThread public LauncherActivity_ViewBinding(LauncherActivity target) { this(target, target.getWindow().getDecorView()); } @UiThread public LauncherActivity_ViewBinding(final LauncherActivity target, View source) { this.target = target; View view; view = Utils.findRequiredView(source, R.id.tv_apple, "field 'ta' and method 'next'"); target.ta = Utils.castView(view, R.id.tv_apple, "field 'ta'", TextView.class); view2131296750 = view; view.setOnClickListener(new DebouncingOnClickListener() { @Override public void doClick(View p0) { target.next(p0); } }); view = Utils.findRequiredView(source, R.id.tv_set, "field 'ts' and method 'man'"); target.ts = Utils.castView(view, R.id.tv_set, "field 'ts'", TextView.class); view2131296784 = view; view.setOnClickListener(new DebouncingOnClickListener() { @Override public void doClick(View p0) { target.man(p0); } }); view = Utils.findRequiredView(source, R.id.tv_git, "field 'tg' and method 'setup'"); target.tg = Utils.castView(view, R.id.tv_git, "field 'tg'", TextView.class); view2131296756 = view; view.setOnClickListener(new DebouncingOnClickListener() { @Override public void doClick(View p0) { target.setup(p0); } }); view = Utils.findRequiredView(source, R.id.tv_let, "field 'tl' and method 'know'"); target.tl = Utils.castView(view, R.id.tv_let, "field 'tl'", TextView.class); view2131296765 = view; view.setOnClickListener(new DebouncingOnClickListener() { @Override public void doClick(View p0) { target.know(p0); } }); view = Utils.findRequiredView(source, R.id.support_me, "field 'supportMe' and method 'onViewClicked'"); target.supportMe = Utils.castView(view, R.id.support_me, "field 'supportMe'", TextView.class); view2131296709 = view; view.setOnClickListener(new DebouncingOnClickListener() { @Override public void doClick(View p0) { target.onViewClicked(); } }); view = Utils.findRequiredView(source, R.id.news, "field 'NewMe' and method 'newsonClicked'"); target.NewMe = Utils.castView(view, R.id.news, "field 'NewMe'", ImageView.class); view2131296592 = view; view.setOnClickListener(new DebouncingOnClickListener() { @Override public void doClick(View p0) { target.newsonClicked(); } }); } @Override @CallSuper public void unbind() { LauncherActivity target = this.target; if (target == null) throw new IllegalStateException("Bindings already cleared."); this.target = null; target.ta = null; target.ts = null; target.tg = null; target.tl = null; target.supportMe = null; target.NewMe = null; view2131296750.setOnClickListener(null); view2131296750 = null; view2131296784.setOnClickListener(null); view2131296784 = null; view2131296756.setOnClickListener(null); view2131296756 = null; view2131296765.setOnClickListener(null); view2131296765 = null; view2131296709.setOnClickListener(null); view2131296709 = null; view2131296592.setOnClickListener(null); view2131296592 = null; } }
32.232
107
0.700422
c4f88c317c4b6616b211bc416845ab30d107fd5c
99,512
package builder; import client.*; import monster.*; import ui.*; //import java.lang.Math; import java.util.ArrayList; import java.io.File; import java.awt.event.*; import java.awt.*; import javax.swing.*; import javax.swing.event.*; public class MonsterBuilder extends JSplitPane { private JList list; private DNDClientProxy proxy; private ArrayList<String> monList; private Monster monster; private ArrayList<Ability> abilityList; private ArrayList<monster.Action> actionList; private ArrayList<LegendaryAction> legendaryList; private final int HEIGHT = 550; private final int LEFT_WIDTH = 150; private final int RIGHT_WIDTH = 1075; private final int INNER_WIDTH = 1050; private final int INNER_HEIGHT = 20; private final Dimension scorePanelSize = new Dimension(175, 220); private final Dimension VERTICAL_GAP = new Dimension(0, 5); private final Dimension HORIZONTAL_GAP = new Dimension(5, 0); /** * Builds the MonsterBuilder tab */ MonsterBuilder(DNDClientProxy proxy) { monster = new Monster(); this.proxy = proxy; initialize(); } /** * Initializes the inital layout of the MonsterBuilder tab */ private void initialize() { setOrientation(JSplitPane.HORIZONTAL_SPLIT); setContinuousLayout(true); setLeftComponent(getLeft()); refreshRight(); setEnabled(false); setVisible(true); } /** * Refreshes the monster list */ public void refresh() { refreshLeft(); refreshRight(); setVisible(true); } private void refreshLeft() { setLeftComponent(getLeft()); } private void refreshRight() { setRightComponent(getRight()); } /** * Populates the right panel with the selected monster's information */ private void getMonster(String name) { monster = proxy.getMonster(name); refreshRight(); } /** * Sets up and returns the JScrollPane used in the left side of the JSplitPane */ private JScrollPane getLeft() { JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(LEFT_WIDTH, HEIGHT)); scroll.setPreferredSize(new Dimension(LEFT_WIDTH, HEIGHT)); list = new JList(); monList = proxy.getMonsterList(); list.setModel(new AbstractListModel() { public int getSize() { return monList.size(); } public Object getElementAt(int i) { return monList.get(i); } }); list.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent event) { listValueChanged(event); } }); scroll.setViewportView(list); return scroll; } /** * Sets up and returns the JPanel used in the right side of the JSplitPane */ private JScrollPane getRight() { //set up pane that houses monster info JScrollPane scroll = new JScrollPane(); scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scroll.getVerticalScrollBar().setUnitIncrement(20); JPanel panel = new JPanel(); scroll.setMinimumSize(new Dimension(RIGHT_WIDTH, HEIGHT)); scroll.setPreferredSize(new Dimension(RIGHT_WIDTH, HEIGHT)); scroll.setMaximumSize(new Dimension(RIGHT_WIDTH, HEIGHT)); panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); //name panel.add(getNameLabel()); panel.add(Box.createRigidArea(VERTICAL_GAP)); if (monster.getName().equals("select a monster")) { scroll.setViewportView(panel); return scroll; } //size panel.add(getSizePanel()); panel.add(Box.createRigidArea(VERTICAL_GAP)); //type panel.add(getTypePanel()); panel.add(Box.createRigidArea(VERTICAL_GAP)); //alignment panel.add(getAlignmentPanel()); panel.add(Box.createRigidArea(VERTICAL_GAP)); //ac panel.add(getACPanel()); panel.add(Box.createRigidArea(VERTICAL_GAP)); //hp panel.add(getHPPanel()); panel.add(Box.createRigidArea(VERTICAL_GAP)); //speed panel.add(getSpeedPanel()); panel.add(Box.createRigidArea(VERTICAL_GAP)); //panel for ability scores panel.add(getScorePanel()); panel.add(Box.createRigidArea(VERTICAL_GAP)); //senses panel.add(getSensesPanel()); panel.add(Box.createRigidArea(VERTICAL_GAP)); //languages panel.add(getLanguagePanel()); panel.add(Box.createRigidArea(VERTICAL_GAP)); //Challenge/XP panel.add(getChallengePanel()); panel.add(Box.createRigidArea(VERTICAL_GAP)); //Abilities panel.add(getAbilityLabel()); panel.add(Box.createRigidArea(VERTICAL_GAP)); abilityList = monster.getAbilities(); for (int i = 0; i < abilityList.size(); i++) { panel.add(getAbilityPanel(i, scroll)); panel.add(Box.createRigidArea(VERTICAL_GAP)); } JButton addAbility = new JButton("Add Ability"); addAbility.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { monster.addAbility(new Ability()); refreshRight(); } }); panel.add(addAbility); panel.add(Box.createRigidArea(VERTICAL_GAP)); //Actions panel.add(getActionLabel()); panel.add(Box.createRigidArea(VERTICAL_GAP)); actionList = monster.getActions(); for (int i = 0; i < actionList.size(); i++) { panel.add(getActionPanel(i, scroll)); panel.add(Box.createRigidArea(VERTICAL_GAP)); } JButton addAction = new JButton("Add Action"); addAction.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { monster.addAction(new monster.Action()); refreshRight(); } }); panel.add(addAction); panel.add(Box.createRigidArea(VERTICAL_GAP)); //Legendary Actions panel.add(getLegendaryLabel()); panel.add(Box.createRigidArea(VERTICAL_GAP)); panel.add(getCountPanel()); panel.add(Box.createRigidArea(VERTICAL_GAP)); legendaryList = monster.getLegendaryActions(); for (int i = 0; i < legendaryList.size(); i++) { panel.add(getLegendaryPanel(i, scroll)); panel.add(Box.createRigidArea(VERTICAL_GAP)); } JButton addLegendary = new JButton("Add Legendary Action"); addLegendary.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { monster.addLegendaryAction(new LegendaryAction()); refreshRight(); } }); panel.add(addLegendary); panel.add(Box.createRigidArea(VERTICAL_GAP)); scroll.setViewportView(panel); return scroll; } private JLabel getNameLabel() { JLabel name = new JLabel(monster.getName()); name.setFont(new Font(name.getFont().getName(), Font.BOLD, 20)); name.setAlignmentX(Component.LEFT_ALIGNMENT); return name; } //size private JPanel getSizePanel() { JPanel sizePanel = new JPanel(); sizePanel.setLayout(new BoxLayout(sizePanel, BoxLayout.X_AXIS)); sizePanel.setAlignmentX(Component.LEFT_ALIGNMENT); sizePanel.setMaximumSize(new Dimension(INNER_WIDTH, INNER_HEIGHT)); JLabel sizeLabel = new JLabel("Size"); sizeLabel.setFont(new Font(sizeLabel.getFont().getName(), Font.BOLD, sizeLabel.getFont().getSize())); JTextField size = new JTextField(monster.getSize()); DeferredDocumentListener listener = new DeferredDocumentListener (new ActionListener() { @Override public void actionPerformed(ActionEvent e) { monster.setSize(size.getText()); } }); size.getDocument().addDocumentListener(listener); size.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { listener.start(); } @Override public void focusLost(FocusEvent e) { listener.stop(); } }); sizePanel.add(sizeLabel); sizePanel.add(Box.createRigidArea(HORIZONTAL_GAP)); sizePanel.add(size); return sizePanel; } //type private JPanel getTypePanel() { JPanel typePanel = new JPanel(); typePanel.setLayout(new BoxLayout(typePanel, BoxLayout.X_AXIS)); typePanel.setAlignmentX(Component.LEFT_ALIGNMENT); typePanel.setMaximumSize(new Dimension(INNER_WIDTH, INNER_HEIGHT)); JLabel typeLabel = new JLabel("Type"); typeLabel.setFont(new Font(typeLabel.getFont().getName(), Font.BOLD, typeLabel.getFont().getSize())); JTextField type = new JTextField(monster.getType()); DeferredDocumentListener listener = new DeferredDocumentListener (new ActionListener() { @Override public void actionPerformed(ActionEvent e) { monster.setType(type.getText()); } }); type.getDocument().addDocumentListener(listener); type.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { listener.start(); } @Override public void focusLost(FocusEvent e) { listener.stop(); } }); typePanel.add(typeLabel); typePanel.add(Box.createRigidArea(HORIZONTAL_GAP)); typePanel.add(type); return typePanel; } //alignment private JPanel getAlignmentPanel() { JPanel alignPanel = new JPanel(); alignPanel.setLayout(new BoxLayout(alignPanel, BoxLayout.X_AXIS)); alignPanel.setAlignmentX(Component.LEFT_ALIGNMENT); alignPanel.setMaximumSize(new Dimension(INNER_WIDTH, INNER_HEIGHT)); JLabel alignLabel = new JLabel("Alignment"); alignLabel.setFont(new Font(alignLabel.getFont().getName(), Font.BOLD, alignLabel.getFont().getSize())); JTextField alignment = new JTextField(monster.getAlignment()); DeferredDocumentListener listener = new DeferredDocumentListener (new ActionListener() { @Override public void actionPerformed(ActionEvent e) { monster.setAlignment(alignment.getText()); } }); alignment.getDocument().addDocumentListener(listener); alignment.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { listener.start(); } @Override public void focusLost(FocusEvent e) { listener.stop(); } }); alignPanel.add(alignLabel); alignPanel.add(Box.createRigidArea(HORIZONTAL_GAP)); alignPanel.add(alignment); return alignPanel; } //ac private JPanel getACPanel() { JPanel acPanel = new JPanel(); acPanel.setLayout(new BoxLayout(acPanel, BoxLayout.X_AXIS)); acPanel.setAlignmentX(Component.LEFT_ALIGNMENT); acPanel.setMaximumSize(new Dimension(INNER_WIDTH, INNER_HEIGHT)); JLabel acLabel = new JLabel("Armor Class"); acLabel.setFont(new Font(acLabel.getFont().getName(), Font.BOLD, acLabel.getFont().getSize())); JTextField ac = new JTextField(monster.getAC()); DeferredDocumentListener listener = new DeferredDocumentListener (new ActionListener() { @Override public void actionPerformed(ActionEvent e) { monster.setAC(ac.getText()); } }); ac.getDocument().addDocumentListener(listener); ac.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { listener.start(); } @Override public void focusLost(FocusEvent e) { listener.stop(); } }); acPanel.add(acLabel); acPanel.add(Box.createRigidArea(HORIZONTAL_GAP)); acPanel.add(ac); return acPanel; } //hp private JPanel getHPPanel() { JPanel hpPanel = new JPanel(); hpPanel.setLayout(new BoxLayout(hpPanel, BoxLayout.X_AXIS)); hpPanel.setAlignmentX(Component.LEFT_ALIGNMENT); hpPanel.setMaximumSize(new Dimension(INNER_WIDTH, INNER_HEIGHT)); JLabel hpLabel = new JLabel("Hit Points"); hpLabel.setFont(new Font(hpLabel.getFont().getName(), Font.BOLD, hpLabel.getFont().getSize())); JTextField hp = new JTextField(monster.getHP()); DeferredDocumentListener listener = new DeferredDocumentListener (new ActionListener() { @Override public void actionPerformed(ActionEvent e) { monster.setHP(hp.getText()); } }); hp.getDocument().addDocumentListener(listener); hp.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { listener.start(); } @Override public void focusLost(FocusEvent e) { listener.stop(); } }); hpPanel.add(hpLabel); hpPanel.add(Box.createRigidArea(HORIZONTAL_GAP)); hpPanel.add(hp); return hpPanel; } //speed private JPanel getSpeedPanel() { JPanel speedPanel = new JPanel(); speedPanel.setLayout(new BoxLayout(speedPanel, BoxLayout.X_AXIS)); speedPanel.setAlignmentX(Component.LEFT_ALIGNMENT); speedPanel.setMaximumSize(new Dimension(INNER_WIDTH, INNER_HEIGHT)); JLabel speedLabel = new JLabel("Speed"); speedLabel.setFont(new Font(speedLabel.getFont().getName(), Font.BOLD, speedLabel.getFont().getSize())); JTextField speed = new JTextField(monster.getSpeed()); DeferredDocumentListener listener = new DeferredDocumentListener (new ActionListener() { @Override public void actionPerformed(ActionEvent e) { monster.setSpeed(speed.getText()); } }); speed.getDocument().addDocumentListener(listener); speed.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { listener.start(); } @Override public void focusLost(FocusEvent e) { listener.stop(); } }); speedPanel.add(speedLabel); speedPanel.add(Box.createRigidArea(HORIZONTAL_GAP)); speedPanel.add(speed); return speedPanel; } private JPanel getScorePanel() { JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); panel.setAlignmentX(Component.LEFT_ALIGNMENT); JPanel profPanel = new JPanel(); profPanel.setLayout(new BoxLayout(profPanel, BoxLayout.X_AXIS)); profPanel.setAlignmentX(Component.LEFT_ALIGNMENT); profPanel.setMaximumSize(new Dimension(INNER_WIDTH, INNER_HEIGHT)); JLabel profLabel = new JLabel("Proficiency Bonus"); profLabel.setFont(new Font(profLabel.getFont().getName(), Font.BOLD, profLabel.getFont().getSize())); JTextField proficiency = new JTextField(Integer.toString(monster.getProficiency())); JPanel scorePanel = new JPanel(); scorePanel.setMinimumSize(new Dimension(INNER_WIDTH, 210)); scorePanel.setMaximumSize(new Dimension(INNER_WIDTH, 210)); scorePanel.setAlignmentX(Component.LEFT_ALIGNMENT); scorePanel.setLayout(new BoxLayout(scorePanel, BoxLayout.X_AXIS)); proficiency.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyChar() >= '0' && e.getKeyChar() <= '9' || (e.getKeyCode() == KeyEvent.VK_BACK_SPACE || e.getKeyCode() == KeyEvent.VK_DELETE)) proficiency.setEditable(true); else proficiency.setEditable(false); } @Override public void keyReleased(KeyEvent e) { if (proficiency.getText().equals("")) proficiency.setText("0"); if (proficiency.getText().length() > 1 && proficiency.getText().charAt(0) == '0') proficiency.setText(proficiency.getText().substring(1)); monster.setProficiency(Integer.parseInt(proficiency.getText())); } }); //TODO: add Proficiency panel here? pass to all ability score panels so that //changes are reflected in each one //or pass proficiency to this panel, then pass again to each score profPanel.add(profLabel); profPanel.add(Box.createRigidArea(HORIZONTAL_GAP)); profPanel.add(proficiency); panel.add(profPanel); panel.add(Box.createRigidArea(VERTICAL_GAP)); scorePanel.add(getStr(proficiency)); scorePanel.add(getDex(proficiency)); scorePanel.add(getCon(proficiency)); scorePanel.add(getInt(proficiency)); scorePanel.add(getWis(proficiency)); scorePanel.add(getCha(proficiency)); panel.add(scorePanel); return panel; } /** * STR information, including labels, score, mod, saving throws, and skills * consider creating proficiency jtextfield in getScorePanel, passing to this, * then adding listener here to that changing proficiency will automatically update * skills and saves */ private JPanel getStr(JTextField proficiency) { final String STR = "STR"; int strScore = monster.getAbilityScore(STR); int strMod = Math.floorDiv(strScore - 10, 2); JPanel strPanel = new JPanel(); strPanel.setMinimumSize(scorePanelSize); strPanel.setPreferredSize(scorePanelSize); strPanel.setMaximumSize(scorePanelSize); strPanel.setLayout(new BoxLayout(strPanel, BoxLayout.Y_AXIS)); strPanel.setAlignmentX(Component.CENTER_ALIGNMENT); strPanel.setAlignmentY(Component.CENTER_ALIGNMENT); JLabel str = new JLabel(STR); str.setAlignmentX(Component.CENTER_ALIGNMENT); str.setFont(new Font(str.getFont().getName(), Font.BOLD, 15)); JTextField score = new JTextField(Integer.toString(strScore)); score.setMinimumSize(new Dimension(30, 20)); score.setPreferredSize(new Dimension(30, 20)); score.setMaximumSize(new Dimension(30, 20)); score.setHorizontalAlignment(JTextField.CENTER); JLabel mod = new JLabel("(" + signBonus(strMod) + ")"); mod.setAlignmentX(Component.CENTER_ALIGNMENT); mod.setFont(new Font(mod.getFont().getName(), Font.PLAIN, mod.getFont().getSize())); JPanel savePanel = new JPanel(); savePanel.setLayout(new BoxLayout(savePanel, BoxLayout.X_AXIS)); JCheckBox saveBox = new JCheckBox(); saveBox.setSelected(monster.getAbilityProficiency(STR)); JLabel save = new JLabel("Saving Throws: " + signBonus(calcBonus(strMod, monster.getProficiency(), monster.getAbilityProficiency(STR), false))); save.setFont(new Font(save.getFont().getName(), Font.PLAIN, save.getFont().getSize())); final String ATH = "athletics"; JPanel athPanel = new JPanel(); athPanel.setLayout(new BoxLayout(athPanel, BoxLayout.X_AXIS)); JLabel athletics = new JLabel("Athletics: " + signBonus(calcBonus(strMod, monster.getProficiency(), monster.getSkillProficienct(ATH), monster.getSkillExpertise(ATH)))); athletics.setFont(new Font(athletics.getFont().getName(), Font.PLAIN, athletics.getFont().getSize())); JCheckBox athProfBox = new JCheckBox(); JCheckBox athExpBox = new JCheckBox(); athProfBox.setSelected(monster.getSkillProficienct(ATH)); athExpBox.setSelected(monster.getSkillExpertise(ATH)); //listeners for Score text field score.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyChar() >= '0' && e.getKeyChar() <= '9' || (e.getKeyCode() == KeyEvent.VK_BACK_SPACE || e.getKeyCode() == KeyEvent.VK_DELETE)) score.setEditable(true); else score.setEditable(false); } @Override public void keyReleased(KeyEvent e) { if (score.getText().equals("")) score.setText("0"); if (score.getText().length() > 1 && score.getText().charAt(0) == '0') score.setText(score.getText().substring(1)); int num = Integer.parseInt(score.getText()); monster.setAbilityScore(STR, num); int scoreMod = Math.floorDiv(num - 10, 2); mod.setText("(" + signBonus(scoreMod) + ")"); save.setText("Saving Throws: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getAbilityProficiency(STR), false))); athletics.setText("Athletics: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(ATH), monster.getSkillExpertise(ATH)))); } }); //saving throw checkbox listener saveBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == 1) monster.setAbilityProficiency(STR, true); else monster.setAbilityProficiency(STR, false); int scoreMod = Math.floorDiv(Integer.parseInt(score.getText()) - 10, 2); save.setText("Saving Throws: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getAbilityProficiency(STR), false))); } }); //athletics checkbox listeners athProfBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == 1) monster.setSkillProficiency(ATH, true); else { monster.setSkillProficiency(ATH, false); athExpBox.setSelected(false); } int scoreMod = Math.floorDiv(Integer.parseInt(score.getText()) - 10, 2); athletics.setText("Athletics: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(ATH), monster.getSkillExpertise(ATH)))); } }); athExpBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == 1) { monster.setSkillExpertise(ATH, true); athProfBox.setSelected(true); } else monster.setSkillExpertise(ATH, false); int scoreMod = Math.floorDiv(Integer.parseInt(score.getText()) - 10, 2); athletics.setText("Athletics: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(ATH), monster.getSkillExpertise(ATH)))); } }); DeferredDocumentListener listener = new DeferredDocumentListener (new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int num = Integer.parseInt(score.getText()); monster.setAbilityScore(STR, num); int scoreMod = Math.floorDiv(num - 10, 2); mod.setText("(" + signBonus(scoreMod) + ")"); save.setText("Saving Throws: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getAbilityProficiency(STR), false))); athletics.setText("Athletics: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(ATH), monster.getSkillExpertise(ATH)))); } }); proficiency.getDocument().addDocumentListener(listener); proficiency.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { listener.start(); } @Override public void focusLost(FocusEvent e) { listener.stop(); } }); strPanel.add(str); strPanel.add(Box.createRigidArea(VERTICAL_GAP)); strPanel.add(score); strPanel.add(Box.createRigidArea(VERTICAL_GAP)); strPanel.add(mod); savePanel.add(saveBox); savePanel.add(save); strPanel.add(savePanel); athPanel.add(athExpBox); athPanel.add(athProfBox); athPanel.add(athletics); strPanel.add(athPanel); return strPanel; } /** * DEX information, including labels, score, mod, saving throws, and skills * consider creating proficiency jtextfield in getScorePanel, passing to this, * then adding listener here to that changing proficiency will automatically update * skills and saves */ private JPanel getDex(JTextField proficiency) { final String DEX = "DEX"; int dexScore = monster.getAbilityScore(DEX); int dexMod = Math.floorDiv(dexScore - 10, 2); JPanel dexPanel = new JPanel(); dexPanel.setMinimumSize(scorePanelSize); dexPanel.setPreferredSize(scorePanelSize); dexPanel.setMaximumSize(scorePanelSize); dexPanel.setLayout(new BoxLayout(dexPanel, BoxLayout.Y_AXIS)); dexPanel.setAlignmentX(Component.CENTER_ALIGNMENT); dexPanel.setAlignmentY(Component.CENTER_ALIGNMENT); JLabel dex = new JLabel(DEX); dex.setAlignmentX(Component.CENTER_ALIGNMENT); dex.setFont(new Font(dex.getFont().getName(), Font.BOLD, 15)); JTextField score = new JTextField(Integer.toString(dexScore)); score.setMinimumSize(new Dimension(30, 20)); score.setPreferredSize(new Dimension(30, 20)); score.setMaximumSize(new Dimension(30, 20)); score.setHorizontalAlignment(JTextField.CENTER); String modifier = signBonus(dexMod); JLabel mod = new JLabel("(" + modifier + ")"); mod.setAlignmentX(Component.CENTER_ALIGNMENT); mod.setFont(new Font(mod.getFont().getName(), Font.PLAIN, mod.getFont().getSize())); JPanel savePanel = new JPanel(); savePanel.setLayout(new BoxLayout(savePanel, BoxLayout.X_AXIS)); JCheckBox saveBox = new JCheckBox(); saveBox.setSelected(monster.getAbilityProficiency(DEX)); JLabel save = new JLabel("Saving Throws: " + signBonus(calcBonus(dexMod, monster.getProficiency(), monster.getAbilityProficiency(DEX), false))); save.setFont(new Font(save.getFont().getName(), Font.PLAIN, save.getFont().getSize())); final String ACRO = "acrobatics"; JPanel acroPanel = new JPanel(); acroPanel.setLayout(new BoxLayout(acroPanel, BoxLayout.X_AXIS)); JLabel acrobatics = new JLabel("Acrobatics: " + signBonus(calcBonus(dexMod, monster.getProficiency(), monster.getSkillProficienct(ACRO), monster.getSkillExpertise(ACRO)))); acrobatics.setFont(new Font(acrobatics.getFont().getName(), Font.PLAIN, acrobatics.getFont().getSize())); JCheckBox acroProfBox = new JCheckBox(); JCheckBox acroExpBox = new JCheckBox(); acroProfBox.setSelected(monster.getSkillProficienct(ACRO)); acroExpBox.setSelected(monster.getSkillExpertise(ACRO)); final String HAND = "sleight of hand"; JPanel handPanel = new JPanel(); handPanel.setLayout(new BoxLayout(handPanel, BoxLayout.X_AXIS)); JLabel hand = new JLabel("Sleight of Hand: " + signBonus(calcBonus(dexMod, monster.getProficiency(), monster.getSkillProficienct(HAND), monster.getSkillExpertise(HAND)))); hand.setFont(new Font(hand.getFont().getName(), Font.PLAIN, hand.getFont().getSize())); JCheckBox handProfBox = new JCheckBox(); JCheckBox handExpBox = new JCheckBox(); handProfBox.setSelected(monster.getSkillProficienct(HAND)); handExpBox.setSelected(monster.getSkillExpertise(HAND)); final String STE = "stealth"; JPanel stePanel = new JPanel(); stePanel.setLayout(new BoxLayout(stePanel, BoxLayout.X_AXIS)); JLabel stealth = new JLabel("Stealth: " + signBonus(calcBonus(dexMod, monster.getProficiency(), monster.getSkillProficienct(STE), monster.getSkillExpertise(STE)))); stealth.setFont(new Font(stealth.getFont().getName(), Font.PLAIN, stealth.getFont().getSize())); JCheckBox steProfBox = new JCheckBox(); JCheckBox steExpBox = new JCheckBox(); steProfBox.setSelected(monster.getSkillProficienct(STE)); steExpBox.setSelected(monster.getSkillExpertise(STE)); //listeners for Score text field score.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyChar() >= '0' && e.getKeyChar() <= '9' || (e.getKeyCode() == KeyEvent.VK_BACK_SPACE || e.getKeyCode() == KeyEvent.VK_DELETE)) score.setEditable(true); else score.setEditable(false); } @Override public void keyReleased(KeyEvent e) { if (score.getText().equals("")) score.setText("0"); if (score.getText().length() > 1 && score.getText().charAt(0) == '0') score.setText(score.getText().substring(1)); int num = Integer.parseInt(score.getText()); monster.setAbilityScore(DEX, num); int scoreMod = Math.floorDiv(num - 10, 2); mod.setText("(" + signBonus(scoreMod) + ")"); save.setText("Saving Throws: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getAbilityProficiency(DEX), false))); acrobatics.setText("Acrobatics: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(ACRO), monster.getSkillExpertise(ACRO)))); hand.setText("Sleight of Hand: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(HAND), monster.getSkillExpertise(HAND)))); stealth.setText("Stealth: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(STE), monster.getSkillExpertise(STE)))); } }); //saving throw checkbox listener saveBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == 1) monster.setAbilityProficiency(DEX, true); else monster.setAbilityProficiency(DEX, false); int scoreMod = Math.floorDiv(Integer.parseInt(score.getText()) - 10, 2); save.setText("Saving Throws: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getAbilityProficiency(DEX), false))); } }); //acrobatics checkbox listeners acroProfBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == 1) monster.setSkillProficiency(ACRO, true); else { monster.setSkillProficiency(ACRO, false); acroExpBox.setSelected(false); } int scoreMod = Math.floorDiv(Integer.parseInt(score.getText()) - 10, 2); acrobatics.setText("Acrobatics: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(ACRO), monster.getSkillExpertise(ACRO)))); } }); acroExpBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == 1) { monster.setSkillExpertise(ACRO, true); acroProfBox.setSelected(true); } else monster.setSkillExpertise(ACRO, false); int scoreMod = Math.floorDiv(Integer.parseInt(score.getText()) - 10, 2); acrobatics.setText("Acrobatics: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(ACRO), monster.getSkillExpertise(ACRO)))); } }); //sleight of hand checkbox listeners handProfBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == 1) monster.setSkillProficiency(HAND, true); else { monster.setSkillProficiency(HAND, false); handExpBox.setSelected(false); } int scoreMod = Math.floorDiv(Integer.parseInt(score.getText()) - 10, 2); hand.setText("Sleight of Hand: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(HAND), monster.getSkillExpertise(HAND)))); } }); handExpBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == 1) { monster.setSkillExpertise(HAND, true); handProfBox.setSelected(true); } else monster.setSkillExpertise(HAND, false); int scoreMod = Math.floorDiv(Integer.parseInt(score.getText()) - 10, 2); hand.setText("Sleight of Hand: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(HAND), monster.getSkillExpertise(HAND)))); } }); //stealth checkbox listeners steProfBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == 1) monster.setSkillProficiency(STE, true); else { monster.setSkillProficiency(STE, false); steExpBox.setSelected(false); } int scoreMod = Math.floorDiv(Integer.parseInt(score.getText()) - 10, 2); stealth.setText("Stealth: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(STE), monster.getSkillExpertise(STE)))); } }); steExpBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == 1) { monster.setSkillExpertise(STE, true); steProfBox.setSelected(true); } else monster.setSkillExpertise(STE, false); int scoreMod = Math.floorDiv(Integer.parseInt(score.getText()) - 10, 2); stealth.setText("Stealth: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(STE), monster.getSkillExpertise(STE)))); } }); DeferredDocumentListener listener = new DeferredDocumentListener (new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int num = Integer.parseInt(score.getText()); monster.setAbilityScore(DEX, num); int scoreMod = Math.floorDiv(num - 10, 2); mod.setText("(" + signBonus(scoreMod) + ")"); save.setText("Saving Throws: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getAbilityProficiency(DEX), false))); acrobatics.setText("Acrobatics: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(ACRO), monster.getSkillExpertise(ACRO)))); hand.setText("Sleight of Hand: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(HAND), monster.getSkillExpertise(HAND)))); stealth.setText("Stealth: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(STE), monster.getSkillExpertise(STE)))); } }); proficiency.getDocument().addDocumentListener(listener); proficiency.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { listener.start(); } @Override public void focusLost(FocusEvent e) { listener.stop(); } }); dexPanel.add(dex); dexPanel.add(Box.createRigidArea(VERTICAL_GAP)); dexPanel.add(score); dexPanel.add(Box.createRigidArea(VERTICAL_GAP)); dexPanel.add(mod); savePanel.add(saveBox); savePanel.add(save); dexPanel.add(savePanel); acroPanel.add(acroExpBox); acroPanel.add(acroProfBox); acroPanel.add(acrobatics); dexPanel.add(acroPanel); dexPanel.add(Box.createRigidArea(VERTICAL_GAP)); handPanel.add(handExpBox); handPanel.add(handProfBox); handPanel.add(hand); dexPanel.add(handPanel); dexPanel.add(Box.createRigidArea(VERTICAL_GAP)); stePanel.add(steExpBox); stePanel.add(steProfBox); stePanel.add(stealth); dexPanel.add(stePanel); return dexPanel; } /** * CON information, including labels, score, mod, saving throws, and skills * consider creating proficiency jtextfield in getScorePanel, passing to this, * then adding listener here to that changing proficiency will automatically update * skills and saves */ private JPanel getCon(JTextField proficiency) { final String CON = "CON"; int conScore = monster.getAbilityScore(CON); int conMod = Math.floorDiv(conScore - 10, 2); JPanel conPanel = new JPanel(); conPanel.setMinimumSize(scorePanelSize); conPanel.setPreferredSize(scorePanelSize); conPanel.setMaximumSize(scorePanelSize); conPanel.setLayout(new BoxLayout(conPanel, BoxLayout.Y_AXIS)); conPanel.setAlignmentX(Component.CENTER_ALIGNMENT); conPanel.setAlignmentY(Component.CENTER_ALIGNMENT); JLabel con = new JLabel(CON); con.setAlignmentX(Component.CENTER_ALIGNMENT); con.setFont(new Font(con.getFont().getName(), Font.BOLD, 15)); JTextField score = new JTextField(Integer.toString(conScore)); score.setMinimumSize(new Dimension(30, 20)); score.setPreferredSize(new Dimension(30, 20)); score.setMaximumSize(new Dimension(30, 20)); score.setHorizontalAlignment(JTextField.CENTER); String modifier = signBonus(conMod); JLabel mod = new JLabel("(" + modifier + ")"); mod.setAlignmentX(Component.CENTER_ALIGNMENT); mod.setFont(new Font(mod.getFont().getName(), Font.PLAIN, mod.getFont().getSize())); JPanel savePanel = new JPanel(); savePanel.setLayout(new BoxLayout(savePanel, BoxLayout.X_AXIS)); JCheckBox saveBox = new JCheckBox(); saveBox.setSelected(monster.getAbilityProficiency(CON)); JLabel save = new JLabel("Saving Throws: " + signBonus(calcBonus(conMod, monster.getProficiency(), monster.getAbilityProficiency(CON), false))); save.setFont(new Font(save.getFont().getName(), Font.PLAIN, save.getFont().getSize())); //listeners for Score text field score.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyChar() >= '0' && e.getKeyChar() <= '9' || (e.getKeyCode() == KeyEvent.VK_BACK_SPACE || e.getKeyCode() == KeyEvent.VK_DELETE)) score.setEditable(true); else score.setEditable(false); } @Override public void keyReleased(KeyEvent e) { if (score.getText().equals("")) score.setText("0"); if (score.getText().length() > 1 && score.getText().charAt(0) == '0') score.setText(score.getText().substring(1)); int num = Integer.parseInt(score.getText()); monster.setAbilityScore(CON, num); int scoreMod = Math.floorDiv(num - 10, 2); mod.setText("(" + signBonus(scoreMod) + ")"); save.setText("Saving Throws: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getAbilityProficiency(CON), false))); } }); //saving throw checkbox listener saveBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == 1) monster.setAbilityProficiency(CON, true); else monster.setAbilityProficiency(CON, false); int scoreMod = Math.floorDiv(Integer.parseInt(score.getText()) - 10, 2); save.setText("Saving Throws: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getAbilityProficiency(CON), false))); } }); DeferredDocumentListener listener = new DeferredDocumentListener (new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int num = Integer.parseInt(score.getText()); monster.setAbilityScore(CON, num); int scoreMod = Math.floorDiv(num - 10, 2); mod.setText("(" + signBonus(scoreMod) + ")"); save.setText("Saving Throws: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getAbilityProficiency(CON), false))); } }); proficiency.getDocument().addDocumentListener(listener); proficiency.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { listener.start(); } @Override public void focusLost(FocusEvent e) { listener.stop(); } }); conPanel.add(con); conPanel.add(Box.createRigidArea(VERTICAL_GAP)); conPanel.add(score); conPanel.add(Box.createRigidArea(VERTICAL_GAP)); conPanel.add(mod); savePanel.add(saveBox); savePanel.add(save); conPanel.add(savePanel); return conPanel; } /** * INT information, including labels, score, mod, saving throws, and skills * consider creating proficiency jtextfield in getScorePanel, passing to this, * then adding listener here to that changing proficiency will automatically update * skills and saves */ private JPanel getInt(JTextField proficiency) { final String INT = "INT"; int intScore = monster.getAbilityScore(INT); int intMod = Math.floorDiv(intScore - 10, 2); JPanel intPanel = new JPanel(); intPanel.setMinimumSize(scorePanelSize); intPanel.setPreferredSize(scorePanelSize); intPanel.setMaximumSize(scorePanelSize); intPanel.setLayout(new BoxLayout(intPanel, BoxLayout.Y_AXIS)); intPanel.setAlignmentX(Component.CENTER_ALIGNMENT); intPanel.setAlignmentY(Component.CENTER_ALIGNMENT); JLabel inte = new JLabel(INT); inte.setAlignmentX(Component.CENTER_ALIGNMENT); inte.setFont(new Font(inte.getFont().getName(), Font.BOLD, 15)); JTextField score = new JTextField(Integer.toString(intScore)); score.setMinimumSize(new Dimension(30, 20)); score.setPreferredSize(new Dimension(30, 20)); score.setMaximumSize(new Dimension(30, 20)); score.setHorizontalAlignment(JTextField.CENTER); String modifier = signBonus(intMod); JLabel mod = new JLabel("(" + modifier + ")"); mod.setAlignmentX(Component.CENTER_ALIGNMENT); mod.setFont(new Font(mod.getFont().getName(), Font.PLAIN, mod.getFont().getSize())); JPanel savePanel = new JPanel(); savePanel.setLayout(new BoxLayout(savePanel, BoxLayout.X_AXIS)); JCheckBox saveBox = new JCheckBox(); saveBox.setSelected(monster.getAbilityProficiency(INT)); JLabel save = new JLabel("Saving Throws: " + signBonus(calcBonus(intMod, monster.getProficiency(), monster.getAbilityProficiency(INT), false))); save.setFont(new Font(save.getFont().getName(), Font.PLAIN, save.getFont().getSize())); final String ARC = "arcana"; JPanel arcPanel = new JPanel(); arcPanel.setLayout(new BoxLayout(arcPanel, BoxLayout.X_AXIS)); JLabel arcana = new JLabel("Arcana: " + signBonus(calcBonus(intMod, monster.getProficiency(), monster.getSkillProficienct(ARC), monster.getSkillExpertise(ARC)))); arcana.setFont(new Font(arcana.getFont().getName(), Font.PLAIN, arcana.getFont().getSize())); JCheckBox arcProfBox = new JCheckBox(); JCheckBox arcExpBox = new JCheckBox(); arcProfBox.setSelected(monster.getSkillProficienct(ARC)); arcExpBox.setSelected(monster.getSkillExpertise(ARC)); final String HIS = "history"; JPanel hisPanel = new JPanel(); hisPanel.setLayout(new BoxLayout(hisPanel, BoxLayout.X_AXIS)); JLabel history = new JLabel("History: " + signBonus(calcBonus(intMod, monster.getProficiency(), monster.getSkillProficienct(HIS), monster.getSkillExpertise(HIS)))); history.setFont(new Font(history.getFont().getName(), Font.PLAIN, history.getFont().getSize())); JCheckBox hisProfBox = new JCheckBox(); JCheckBox hisExpBox = new JCheckBox(); hisProfBox.setSelected(monster.getSkillProficienct(HIS)); hisExpBox.setSelected(monster.getSkillExpertise(HIS)); final String INV = "investigation"; JPanel invPanel = new JPanel(); invPanel.setLayout(new BoxLayout(invPanel, BoxLayout.X_AXIS)); JLabel investigation = new JLabel("Investigation: " + signBonus(calcBonus(intMod, monster.getProficiency(), monster.getSkillProficienct(INV), monster.getSkillExpertise(INV)))); investigation.setFont(new Font(investigation.getFont().getName(), Font.PLAIN, investigation.getFont().getSize())); JCheckBox invProfBox = new JCheckBox(); JCheckBox invExpBox = new JCheckBox(); invProfBox.setSelected(monster.getSkillProficienct(INV)); invExpBox.setSelected(monster.getSkillExpertise(INV)); final String NAT = "nature"; JPanel natPanel = new JPanel(); natPanel.setLayout(new BoxLayout(natPanel, BoxLayout.X_AXIS)); JLabel nature = new JLabel("Nature: " + signBonus(calcBonus(intMod, monster.getProficiency(), monster.getSkillProficienct(NAT), monster.getSkillExpertise(NAT)))); nature.setFont(new Font(nature.getFont().getName(), Font.PLAIN, nature.getFont().getSize())); JCheckBox natProfBox = new JCheckBox(); JCheckBox natExpBox = new JCheckBox(); natProfBox.setSelected(monster.getSkillProficienct(NAT)); natExpBox.setSelected(monster.getSkillExpertise(NAT)); final String REL = "religion"; JPanel relPanel = new JPanel(); relPanel.setLayout(new BoxLayout(relPanel, BoxLayout.X_AXIS)); JLabel religion = new JLabel("Religion: " + signBonus(calcBonus(intMod, monster.getProficiency(), monster.getSkillProficienct(REL), monster.getSkillExpertise(REL)))); religion.setFont(new Font(religion.getFont().getName(), Font.PLAIN, religion.getFont().getSize())); JCheckBox relProfBox = new JCheckBox(); JCheckBox relExpBox = new JCheckBox(); relProfBox.setSelected(monster.getSkillProficienct(REL)); relExpBox.setSelected(monster.getSkillExpertise(REL)); //listeners for Score text field score.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyChar() >= '0' && e.getKeyChar() <= '9' || (e.getKeyCode() == KeyEvent.VK_BACK_SPACE || e.getKeyCode() == KeyEvent.VK_DELETE)) score.setEditable(true); else score.setEditable(false); } @Override public void keyReleased(KeyEvent e) { if (score.getText().equals("")) score.setText("0"); if (score.getText().length() > 1 && score.getText().charAt(0) == '0') score.setText(score.getText().substring(1)); int num = Integer.parseInt(score.getText()); monster.setAbilityScore(INT, num); int scoreMod = Math.floorDiv(num - 10, 2); mod.setText("(" + signBonus(scoreMod) + ")"); save.setText("Saving Throws: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getAbilityProficiency(INT), false))); arcana.setText("Arcana: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(ARC), monster.getSkillExpertise(ARC)))); history.setText("History: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(HIS), monster.getSkillExpertise(HIS)))); investigation.setText("Investigation: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(INV), monster.getSkillExpertise(INV)))); nature.setText("Nature: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(NAT), monster.getSkillExpertise(NAT)))); religion.setText("Religion: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(REL), monster.getSkillExpertise(REL)))); } }); //saving throw checkbox listener saveBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == 1) monster.setAbilityProficiency(INT, true); else monster.setAbilityProficiency(INT, false); int scoreMod = Math.floorDiv(Integer.parseInt(score.getText()) - 10, 2); save.setText("Saving Throws: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getAbilityProficiency(INT), false))); } }); //arcana checkbox listeners arcProfBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == 1) monster.setSkillProficiency(ARC, true); else { monster.setSkillProficiency(ARC, false); arcExpBox.setSelected(false); } int scoreMod = Math.floorDiv(Integer.parseInt(score.getText()) - 10, 2); arcana.setText("Arcana: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(ARC), monster.getSkillExpertise(ARC)))); } }); arcExpBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == 1) { monster.setSkillExpertise(ARC, true); arcProfBox.setSelected(true); } else monster.setSkillExpertise(ARC, false); int scoreMod = Math.floorDiv(Integer.parseInt(score.getText()) - 10, 2); arcana.setText("Arcana: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(ARC), monster.getSkillExpertise(ARC)))); } }); //history checkbox listeners hisProfBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == 1) monster.setSkillProficiency(HIS, true); else { monster.setSkillProficiency(HIS, false); hisExpBox.setSelected(false); } int scoreMod = Math.floorDiv(Integer.parseInt(score.getText()) - 10, 2); history.setText("History: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(HIS), monster.getSkillExpertise(HIS)))); } }); hisExpBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == 1) { monster.setSkillExpertise(HIS, true); hisProfBox.setSelected(true); } else monster.setSkillExpertise(HIS, false); int scoreMod = Math.floorDiv(Integer.parseInt(score.getText()) - 10, 2); history.setText("History: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(HIS), monster.getSkillExpertise(HIS)))); } }); //investigation checkbox listeners invProfBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == 1) monster.setSkillProficiency(INV, true); else { monster.setSkillProficiency(INV, false); invExpBox.setSelected(false); } int scoreMod = Math.floorDiv(Integer.parseInt(score.getText()) - 10, 2); investigation.setText("Investigation: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(INV), monster.getSkillExpertise(INV)))); } }); invExpBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == 1) { monster.setSkillExpertise(INV, true); invProfBox.setSelected(true); } else monster.setSkillExpertise(INV, false); int scoreMod = Math.floorDiv(Integer.parseInt(score.getText()) - 10, 2); investigation.setText("Investigation: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(INT), monster.getSkillExpertise(INV)))); } }); //nature checkbox listeners natProfBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == 1) monster.setSkillProficiency(NAT, true); else { monster.setSkillProficiency(NAT, false); natExpBox.setSelected(false); } int scoreMod = Math.floorDiv(Integer.parseInt(score.getText()) - 10, 2); nature.setText("Nature: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(NAT), monster.getSkillExpertise(NAT)))); } }); natExpBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == 1) { monster.setSkillExpertise(NAT, true); natProfBox.setSelected(true); } else monster.setSkillExpertise(NAT, false); int scoreMod = Math.floorDiv(Integer.parseInt(score.getText()) - 10, 2); nature.setText("Nature: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(NAT), monster.getSkillExpertise(NAT)))); } }); //religion checkbox listeners relProfBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == 1) monster.setSkillProficiency(REL, true); else { monster.setSkillProficiency(REL, false); relExpBox.setSelected(false); } int scoreMod = Math.floorDiv(Integer.parseInt(score.getText()) - 10, 2); religion.setText("Religion: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(REL), monster.getSkillExpertise(REL)))); } }); relExpBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == 1) { monster.setSkillExpertise(REL, true); relProfBox.setSelected(true); } else monster.setSkillExpertise(REL, false); int scoreMod = Math.floorDiv(Integer.parseInt(score.getText()) - 10, 2); religion.setText("Religion: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(REL), monster.getSkillExpertise(REL)))); } }); DeferredDocumentListener listener = new DeferredDocumentListener (new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int num = Integer.parseInt(score.getText()); monster.setAbilityScore(INT, num); int scoreMod = Math.floorDiv(num - 10, 2); mod.setText("(" + signBonus(scoreMod) + ")"); save.setText("Saving Throws: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getAbilityProficiency(INT), false))); arcana.setText("Arcana: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(ARC), monster.getSkillExpertise(ARC)))); history.setText("History: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(HIS), monster.getSkillExpertise(HIS)))); investigation.setText("Investigation: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(INV), monster.getSkillExpertise(INV)))); nature.setText("Nature: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(NAT), monster.getSkillExpertise(NAT)))); religion.setText("Religion: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(REL), monster.getSkillExpertise(REL)))); } }); proficiency.getDocument().addDocumentListener(listener); proficiency.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { listener.start(); } @Override public void focusLost(FocusEvent e) { listener.stop(); } }); intPanel.add(inte); intPanel.add(Box.createRigidArea(VERTICAL_GAP)); intPanel.add(score); intPanel.add(Box.createRigidArea(VERTICAL_GAP)); intPanel.add(mod); savePanel.add(saveBox); savePanel.add(save); intPanel.add(savePanel); arcPanel.add(arcExpBox); arcPanel.add(arcProfBox); arcPanel.add(arcana); intPanel.add(arcPanel); intPanel.add(Box.createRigidArea(VERTICAL_GAP)); hisPanel.add(hisExpBox); hisPanel.add(hisProfBox); hisPanel.add(history); intPanel.add(hisPanel); intPanel.add(Box.createRigidArea(VERTICAL_GAP)); invPanel.add(invExpBox); invPanel.add(invProfBox); invPanel.add(investigation); intPanel.add(invPanel); intPanel.add(Box.createRigidArea(VERTICAL_GAP)); natPanel.add(natExpBox); natPanel.add(natProfBox); natPanel.add(nature); intPanel.add(natPanel); intPanel.add(Box.createRigidArea(VERTICAL_GAP)); relPanel.add(relExpBox); relPanel.add(relProfBox); relPanel.add(religion); intPanel.add(relPanel); return intPanel; } /** * WIS information, including labels, score, mod, saving throws, and skills * consider creating proficiency jtextfield in getScorePanel, passing to this, * then adding listener here to that changing proficiency will automatically update * skills and saves */ private JPanel getWis(JTextField proficiency) { final String WIS = "WIS"; int wisScore = monster.getAbilityScore(WIS); int wisMod = Math.floorDiv(wisScore - 10, 2); JPanel wisPanel = new JPanel(); wisPanel.setMinimumSize(scorePanelSize); wisPanel.setPreferredSize(scorePanelSize); wisPanel.setMaximumSize(scorePanelSize); wisPanel.setLayout(new BoxLayout(wisPanel, BoxLayout.Y_AXIS)); wisPanel.setAlignmentX(Component.CENTER_ALIGNMENT); wisPanel.setAlignmentY(Component.CENTER_ALIGNMENT); JLabel wis = new JLabel(WIS); wis.setAlignmentX(Component.CENTER_ALIGNMENT); wis.setFont(new Font(wis.getFont().getName(), Font.BOLD, 15)); JTextField score = new JTextField(Integer.toString(wisScore)); score.setMinimumSize(new Dimension(30, 20)); score.setPreferredSize(new Dimension(30, 20)); score.setMaximumSize(new Dimension(30, 20)); score.setHorizontalAlignment(JTextField.CENTER); String modifier = signBonus(wisMod); JLabel mod = new JLabel("(" + modifier + ")"); mod.setAlignmentX(Component.CENTER_ALIGNMENT); mod.setFont(new Font(mod.getFont().getName(), Font.PLAIN, mod.getFont().getSize())); JPanel savePanel = new JPanel(); savePanel.setLayout(new BoxLayout(savePanel, BoxLayout.X_AXIS)); JCheckBox saveBox = new JCheckBox(); saveBox.setSelected(monster.getAbilityProficiency(WIS)); JLabel save = new JLabel("Saving Throws: " + signBonus(calcBonus(wisMod, monster.getProficiency(), monster.getAbilityProficiency(WIS), false))); save.setFont(new Font(save.getFont().getName(), Font.PLAIN, save.getFont().getSize())); final String ANI = "animal handling"; JPanel aniPanel = new JPanel(); aniPanel.setLayout(new BoxLayout(aniPanel, BoxLayout.X_AXIS)); JLabel animal = new JLabel("Animal Handling: " + signBonus(calcBonus(wisMod, monster.getProficiency(), monster.getSkillProficienct(ANI), monster.getSkillExpertise(ANI)))); animal.setFont(new Font(animal.getFont().getName(), Font.PLAIN, animal.getFont().getSize())); JCheckBox aniProfBox = new JCheckBox(); JCheckBox aniExpBox = new JCheckBox(); aniProfBox.setSelected(monster.getSkillProficienct(ANI)); aniExpBox.setSelected(monster.getSkillExpertise(ANI)); final String INS = "insight"; JPanel insPanel = new JPanel(); insPanel.setLayout(new BoxLayout(insPanel, BoxLayout.X_AXIS)); JLabel insight = new JLabel("Insight: " + signBonus(calcBonus(wisMod, monster.getProficiency(), monster.getSkillProficienct(INS), monster.getSkillExpertise(INS)))); insight.setFont(new Font(insight.getFont().getName(), Font.PLAIN, insight.getFont().getSize())); JCheckBox insProfBox = new JCheckBox(); JCheckBox insExpBox = new JCheckBox(); insProfBox.setSelected(monster.getSkillProficienct(INS)); insExpBox.setSelected(monster.getSkillExpertise(INS)); final String MED = "medicine"; JPanel medPanel = new JPanel(); medPanel.setLayout(new BoxLayout(medPanel, BoxLayout.X_AXIS)); JLabel medicine = new JLabel("Medicine: " + signBonus(calcBonus(wisMod, monster.getProficiency(), monster.getSkillProficienct(MED), monster.getSkillExpertise(MED)))); medicine.setFont(new Font(medicine.getFont().getName(), Font.PLAIN, medicine.getFont().getSize())); JCheckBox medProfBox = new JCheckBox(); JCheckBox medExpBox = new JCheckBox(); medProfBox.setSelected(monster.getSkillProficienct(MED)); medExpBox.setSelected(monster.getSkillExpertise(MED)); final String PER = "perception"; JPanel perPanel = new JPanel(); perPanel.setLayout(new BoxLayout(perPanel, BoxLayout.X_AXIS)); JLabel perception = new JLabel("Perception: " + signBonus(calcBonus(wisMod, monster.getProficiency(), monster.getSkillProficienct(PER), monster.getSkillExpertise(PER)))); perception.setFont(new Font(perception.getFont().getName(), Font.PLAIN, perception.getFont().getSize())); JCheckBox perProfBox = new JCheckBox(); JCheckBox perExpBox = new JCheckBox(); perProfBox.setSelected(monster.getSkillProficienct(PER)); perExpBox.setSelected(monster.getSkillExpertise(PER)); final String SUR = "survival"; JPanel surPanel = new JPanel(); surPanel.setLayout(new BoxLayout(surPanel, BoxLayout.X_AXIS)); JLabel survival = new JLabel("Survival: " + signBonus(calcBonus(wisMod, monster.getProficiency(), monster.getSkillProficienct(SUR), monster.getSkillExpertise(SUR)))); survival.setFont(new Font(survival.getFont().getName(), Font.PLAIN, survival.getFont().getSize())); JCheckBox surProfBox = new JCheckBox(); JCheckBox surExpBox = new JCheckBox(); surProfBox.setSelected(monster.getSkillProficienct(SUR)); surExpBox.setSelected(monster.getSkillExpertise(SUR)); //listeners for Score text field score.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyChar() >= '0' && e.getKeyChar() <= '9' || (e.getKeyCode() == KeyEvent.VK_BACK_SPACE || e.getKeyCode() == KeyEvent.VK_DELETE)) score.setEditable(true); else score.setEditable(false); } @Override public void keyReleased(KeyEvent e) { if (score.getText().equals("")) score.setText("0"); if (score.getText().length() > 1 && score.getText().charAt(0) == '0') score.setText(score.getText().substring(1)); int num = Integer.parseInt(score.getText()); monster.setAbilityScore(WIS, num); int scoreMod = Math.floorDiv(num - 10, 2); mod.setText("(" + signBonus(scoreMod) + ")"); save.setText("Saving Throws: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getAbilityProficiency(WIS), false))); animal.setText("Animal Handling: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(ANI), monster.getSkillExpertise(ANI)))); insight.setText("Insight: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(INS), monster.getSkillExpertise(INS)))); medicine.setText("Medicine: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(MED), monster.getSkillExpertise(MED)))); perception.setText("Perception: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(PER), monster.getSkillExpertise(PER)))); survival.setText("Survival: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(SUR), monster.getSkillExpertise(SUR)))); } }); //saving throw checkbox listener saveBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == 1) monster.setAbilityProficiency(WIS, true); else monster.setAbilityProficiency(WIS, false); int scoreMod = Math.floorDiv(Integer.parseInt(score.getText()) - 10, 2); save.setText("Saving Throws: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getAbilityProficiency(WIS), false))); } }); //animal handling checkbox listeners aniProfBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == 1) monster.setSkillProficiency(ANI, true); else { monster.setSkillProficiency(ANI, false); aniExpBox.setSelected(false); } int scoreMod = Math.floorDiv(Integer.parseInt(score.getText()) - 10, 2); animal.setText("Animal Handling: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(ANI), monster.getSkillExpertise(ANI)))); } }); aniExpBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == 1) { monster.setSkillExpertise(ANI, true); aniProfBox.setSelected(true); } else monster.setSkillExpertise(ANI, false); int scoreMod = Math.floorDiv(Integer.parseInt(score.getText()) - 10, 2); animal.setText("Animal Handling: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(ANI), monster.getSkillExpertise(ANI)))); } }); //insight checkbox listeners insProfBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == 1) monster.setSkillProficiency(INS, true); else { monster.setSkillProficiency(INS, false); insExpBox.setSelected(false); } int scoreMod = Math.floorDiv(Integer.parseInt(score.getText()) - 10, 2); insight.setText("Insight: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(INS), monster.getSkillExpertise(INS)))); } }); insExpBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == 1) { monster.setSkillExpertise(INS, true); insProfBox.setSelected(true); } else monster.setSkillExpertise(INS, false); int scoreMod = Math.floorDiv(Integer.parseInt(score.getText()) - 10, 2); insight.setText("Insight: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(INS), monster.getSkillExpertise(INS)))); } }); //medicine checkbox listeners medProfBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == 1) monster.setSkillProficiency(MED, true); else { monster.setSkillProficiency(MED, false); medExpBox.setSelected(false); } int scoreMod = Math.floorDiv(Integer.parseInt(score.getText()) - 10, 2); medicine.setText("Medicine: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(MED), monster.getSkillExpertise(MED)))); } }); medExpBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == 1) { monster.setSkillExpertise(MED, true); medProfBox.setSelected(true); } else monster.setSkillExpertise(MED, false); int scoreMod = Math.floorDiv(Integer.parseInt(score.getText()) - 10, 2); medicine.setText("Medicine: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(MED), monster.getSkillExpertise(MED)))); } }); //perception checkbox listeners perProfBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == 1) monster.setSkillProficiency(PER, true); else { monster.setSkillProficiency(PER, false); perExpBox.setSelected(false); } int scoreMod = Math.floorDiv(Integer.parseInt(score.getText()) - 10, 2); perception.setText("Perception: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(PER), monster.getSkillExpertise(PER)))); } }); perExpBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == 1) { monster.setSkillExpertise(PER, true); perProfBox.setSelected(true); } else monster.setSkillExpertise(PER, false); int scoreMod = Math.floorDiv(Integer.parseInt(score.getText()) - 10, 2); perception.setText("Perception: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(PER), monster.getSkillExpertise(PER)))); } }); //survival checkbox listeners surProfBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == 1) monster.setSkillProficiency(SUR, true); else { monster.setSkillProficiency(SUR, false); surExpBox.setSelected(false); } int scoreMod = Math.floorDiv(Integer.parseInt(score.getText()) - 10, 2); survival.setText("Survival: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(SUR), monster.getSkillExpertise(SUR)))); } }); surExpBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == 1) { monster.setSkillExpertise(SUR, true); surProfBox.setSelected(true); } else monster.setSkillExpertise(SUR, false); int scoreMod = Math.floorDiv(Integer.parseInt(score.getText()) - 10, 2); survival.setText("Survival: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(SUR), monster.getSkillExpertise(SUR)))); } }); DeferredDocumentListener listener = new DeferredDocumentListener (new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int num = Integer.parseInt(score.getText()); monster.setAbilityScore(WIS, num); int scoreMod = Math.floorDiv(num - 10, 2); mod.setText("(" + signBonus(scoreMod) + ")"); save.setText("Saving Throws: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getAbilityProficiency(WIS), false))); animal.setText("Animal Handling: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(ANI), monster.getSkillExpertise(ANI)))); insight.setText("Insight: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(INS), monster.getSkillExpertise(INS)))); medicine.setText("Medicine: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(MED), monster.getSkillExpertise(MED)))); perception.setText("Perception: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(PER), monster.getSkillExpertise(PER)))); survival.setText("Survival: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(SUR), monster.getSkillExpertise(SUR)))); } }); proficiency.getDocument().addDocumentListener(listener); proficiency.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { listener.start(); } @Override public void focusLost(FocusEvent e) { listener.stop(); } }); wisPanel.add(wis); wisPanel.add(Box.createRigidArea(VERTICAL_GAP)); wisPanel.add(score); wisPanel.add(Box.createRigidArea(VERTICAL_GAP)); wisPanel.add(mod); savePanel.add(saveBox); savePanel.add(save); wisPanel.add(savePanel); aniPanel.add(aniExpBox); aniPanel.add(aniProfBox); aniPanel.add(animal); wisPanel.add(aniPanel); wisPanel.add(Box.createRigidArea(VERTICAL_GAP)); insPanel.add(insExpBox); insPanel.add(insProfBox); insPanel.add(insight); wisPanel.add(insPanel); wisPanel.add(Box.createRigidArea(VERTICAL_GAP)); medPanel.add(medExpBox); medPanel.add(medProfBox); medPanel.add(medicine); wisPanel.add(medPanel); wisPanel.add(Box.createRigidArea(VERTICAL_GAP)); perPanel.add(perExpBox); perPanel.add(perProfBox); perPanel.add(perception); wisPanel.add(perPanel); wisPanel.add(Box.createRigidArea(VERTICAL_GAP)); surPanel.add(surExpBox); surPanel.add(surProfBox); surPanel.add(survival); wisPanel.add(surPanel); return wisPanel; } /** * CHA information, including labels, score, mod, saving throws, and skills * consider creating proficiency jtextfield in getScorePanel, passing to this, * then adding listener here to that changing proficiency will automatically update * skills and saves */ private JPanel getCha(JTextField proficiency) { final String CHA = "CHA"; int chaScore = monster.getAbilityScore(CHA); int chaMod = Math.floorDiv(chaScore - 10, 2); JPanel chaPanel = new JPanel(); chaPanel.setMinimumSize(scorePanelSize); chaPanel.setPreferredSize(scorePanelSize); chaPanel.setMaximumSize(scorePanelSize); chaPanel.setLayout(new BoxLayout(chaPanel, BoxLayout.Y_AXIS)); chaPanel.setAlignmentX(Component.CENTER_ALIGNMENT); chaPanel.setAlignmentY(Component.CENTER_ALIGNMENT); JLabel cha = new JLabel(CHA); cha.setAlignmentX(Component.CENTER_ALIGNMENT); cha.setFont(new Font(cha.getFont().getName(), Font.BOLD, 15)); JTextField score = new JTextField(Integer.toString(chaScore)); score.setMinimumSize(new Dimension(30, 20)); score.setPreferredSize(new Dimension(30, 20)); score.setMaximumSize(new Dimension(30, 20)); score.setHorizontalAlignment(JTextField.CENTER); String modifier = signBonus(chaMod); JLabel mod = new JLabel("(" + modifier + ")"); mod.setAlignmentX(Component.CENTER_ALIGNMENT); mod.setFont(new Font(mod.getFont().getName(), Font.PLAIN, mod.getFont().getSize())); JPanel savePanel = new JPanel(); savePanel.setLayout(new BoxLayout(savePanel, BoxLayout.X_AXIS)); JCheckBox saveBox = new JCheckBox(); saveBox.setSelected(monster.getAbilityProficiency(CHA)); JLabel save = new JLabel("Saving Throws: " + signBonus(calcBonus(chaMod, monster.getProficiency(), monster.getAbilityProficiency(CHA), false))); save.setFont(new Font(save.getFont().getName(), Font.PLAIN, save.getFont().getSize())); final String DEC = "deception"; JPanel decPanel = new JPanel(); decPanel.setLayout(new BoxLayout(decPanel, BoxLayout.X_AXIS)); JLabel deception = new JLabel("Deception: " + signBonus(calcBonus(chaMod, monster.getProficiency(), monster.getSkillProficienct(DEC), monster.getSkillExpertise(DEC)))); deception.setFont(new Font(deception.getFont().getName(), Font.PLAIN, deception.getFont().getSize())); JCheckBox decProfBox = new JCheckBox(); JCheckBox decExpBox = new JCheckBox(); decProfBox.setSelected(monster.getSkillProficienct(DEC)); decExpBox.setSelected(monster.getSkillExpertise(DEC)); final String INT = "intimidation"; JPanel intPanel = new JPanel(); intPanel.setLayout(new BoxLayout(intPanel, BoxLayout.X_AXIS)); JLabel intimidation = new JLabel("Intimidation: " + signBonus(calcBonus(chaMod, monster.getProficiency(), monster.getSkillProficienct(INT), monster.getSkillExpertise(INT)))); intimidation.setFont(new Font(intimidation.getFont().getName(), Font.PLAIN, intimidation.getFont().getSize())); JCheckBox intProfBox = new JCheckBox(); JCheckBox intExpBox = new JCheckBox(); intProfBox.setSelected(monster.getSkillProficienct(INT)); intExpBox.setSelected(monster.getSkillExpertise(INT)); final String PERF = "performance"; JPanel perfPanel = new JPanel(); perfPanel.setLayout(new BoxLayout(perfPanel, BoxLayout.X_AXIS)); JLabel performance = new JLabel("Performance: " + signBonus(calcBonus(chaMod, monster.getProficiency(), monster.getSkillProficienct(PERF), monster.getSkillExpertise(PERF)))); performance.setFont(new Font(performance.getFont().getName(), Font.PLAIN, performance.getFont().getSize())); JCheckBox perfProfBox = new JCheckBox(); JCheckBox perfExpBox = new JCheckBox(); perfProfBox.setSelected(monster.getSkillProficienct(PERF)); perfExpBox.setSelected(monster.getSkillExpertise(PERF)); final String PERS = "persuasion"; JPanel persPanel = new JPanel(); persPanel.setLayout(new BoxLayout(persPanel, BoxLayout.X_AXIS)); JLabel persuasion = new JLabel("Persuasion: " + signBonus(calcBonus(chaMod, monster.getProficiency(), monster.getSkillProficienct(PERS), monster.getSkillExpertise(PERS)))); persuasion.setFont(new Font(persuasion.getFont().getName(), Font.PLAIN, persuasion.getFont().getSize())); JCheckBox persProfBox = new JCheckBox(); JCheckBox persExpBox = new JCheckBox(); persProfBox.setSelected(monster.getSkillProficienct(PERS)); persExpBox.setSelected(monster.getSkillExpertise(PERS)); //listeners for Score text field score.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyChar() >= '0' && e.getKeyChar() <= '9' || (e.getKeyCode() == KeyEvent.VK_BACK_SPACE || e.getKeyCode() == KeyEvent.VK_DELETE)) score.setEditable(true); else score.setEditable(false); } @Override public void keyReleased(KeyEvent e) { if (score.getText().equals("")) score.setText("0"); if (score.getText().length() > 1 && score.getText().charAt(0) == '0') score.setText(score.getText().substring(1)); int num = Integer.parseInt(score.getText()); monster.setAbilityScore(CHA, num); int scoreMod = Math.floorDiv(num - 10, 2); mod.setText("(" + signBonus(scoreMod) + ")"); save.setText("Saving Throws: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getAbilityProficiency(CHA), false))); deception.setText("Deception: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(DEC), monster.getSkillExpertise(DEC)))); intimidation.setText("Intimidation: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(INT), monster.getSkillExpertise(INT)))); performance.setText("Performance: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(PERF), monster.getSkillExpertise(PERF)))); persuasion.setText("Persuasion: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(PERS), monster.getSkillExpertise(PERS)))); } }); //saving throw checkbox listener saveBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == 1) monster.setAbilityProficiency(CHA, true); else monster.setAbilityProficiency(CHA, false); int scoreMod = Math.floorDiv(Integer.parseInt(score.getText()) - 10, 2); save.setText("Saving Throws: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getAbilityProficiency(CHA), false))); } }); //deception checkbox listeners decProfBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == 1) monster.setSkillProficiency(DEC, true); else { monster.setSkillProficiency(DEC, false); decExpBox.setSelected(false); } int scoreMod = Math.floorDiv(Integer.parseInt(score.getText()) - 10, 2); deception.setText("Deception: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(DEC), monster.getSkillExpertise(DEC)))); } }); decExpBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == 1) { monster.setSkillExpertise(DEC, true); decProfBox.setSelected(true); } else monster.setSkillExpertise(DEC, false); int scoreMod = Math.floorDiv(Integer.parseInt(score.getText()) - 10, 2); deception.setText("Deception: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(DEC), monster.getSkillExpertise(DEC)))); } }); //intimidation checkbox listeners intProfBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == 1) monster.setSkillProficiency(INT, true); else { monster.setSkillProficiency(INT, false); intExpBox.setSelected(false); } int scoreMod = Math.floorDiv(Integer.parseInt(score.getText()) - 10, 2); intimidation.setText("Intimidation: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(INT), monster.getSkillExpertise(INT)))); } }); intExpBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == 1) { monster.setSkillExpertise(INT, true); intProfBox.setSelected(true); } else monster.setSkillExpertise(INT, false); int scoreMod = Math.floorDiv(Integer.parseInt(score.getText()) - 10, 2); intimidation.setText("Intimidation: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(INT), monster.getSkillExpertise(INT)))); } }); //performance checkbox listeners perfProfBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == 1) monster.setSkillProficiency(PERF, true); else { monster.setSkillProficiency(PERF, false); perfExpBox.setSelected(false); } int scoreMod = Math.floorDiv(Integer.parseInt(score.getText()) - 10, 2); performance.setText("Performance: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(PERF), monster.getSkillExpertise(PERF)))); } }); perfExpBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == 1) { monster.setSkillExpertise(PERF, true); perfProfBox.setSelected(true); } else monster.setSkillExpertise(PERF, false); int scoreMod = Math.floorDiv(Integer.parseInt(score.getText()) - 10, 2); performance.setText("Performance: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(PERF), monster.getSkillExpertise(PERF)))); } }); //persuasion checkbox listeners persProfBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == 1) monster.setSkillProficiency(PERS, true); else { monster.setSkillProficiency(PERS, false); persExpBox.setSelected(false); } int scoreMod = Math.floorDiv(Integer.parseInt(score.getText()) - 10, 2); persuasion.setText("Persuasion: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(PERS), monster.getSkillExpertise(PERS)))); } }); persExpBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == 1) { monster.setSkillExpertise(PERS, true); persProfBox.setSelected(true); } else monster.setSkillExpertise(PERS, false); int scoreMod = Math.floorDiv(Integer.parseInt(score.getText()) - 10, 2); persuasion.setText("Persuasion: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(PERS), monster.getSkillExpertise(PERS)))); } }); DeferredDocumentListener listener = new DeferredDocumentListener (new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int num = Integer.parseInt(score.getText()); monster.setAbilityScore(CHA, num); int scoreMod = Math.floorDiv(num - 10, 2); mod.setText("(" + signBonus(scoreMod) + ")"); save.setText("Saving Throws: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getAbilityProficiency(CHA), false))); deception.setText("Deception: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(DEC), monster.getSkillExpertise(DEC)))); intimidation.setText("Intimidation: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(INT), monster.getSkillExpertise(INT)))); performance.setText("Performance: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(PERF), monster.getSkillExpertise(PERF)))); persuasion.setText("Persuasion: " + signBonus(calcBonus(scoreMod, monster.getProficiency(), monster.getSkillProficienct(PERS), monster.getSkillExpertise(PERS)))); } }); proficiency.getDocument().addDocumentListener(listener); proficiency.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { listener.start(); } @Override public void focusLost(FocusEvent e) { listener.stop(); } }); chaPanel.add(cha); chaPanel.add(Box.createRigidArea(VERTICAL_GAP)); chaPanel.add(score); chaPanel.add(Box.createRigidArea(VERTICAL_GAP)); chaPanel.add(mod); savePanel.add(saveBox); savePanel.add(save); chaPanel.add(savePanel); decPanel.add(decExpBox); decPanel.add(decProfBox); decPanel.add(deception); chaPanel.add(decPanel); chaPanel.add(Box.createRigidArea(VERTICAL_GAP)); intPanel.add(intExpBox); intPanel.add(intProfBox); intPanel.add(intimidation); chaPanel.add(intPanel); chaPanel.add(Box.createRigidArea(VERTICAL_GAP)); perfPanel.add(perfExpBox); perfPanel.add(perfProfBox); perfPanel.add(performance); chaPanel.add(perfPanel); chaPanel.add(Box.createRigidArea(VERTICAL_GAP)); persPanel.add(persExpBox); persPanel.add(persProfBox); persPanel.add(persuasion); chaPanel.add(persPanel); return chaPanel; } private JPanel getSensesPanel() { JPanel sensePanel = new JPanel(); sensePanel.setLayout(new BoxLayout(sensePanel, BoxLayout.X_AXIS)); sensePanel.setAlignmentX(Component.LEFT_ALIGNMENT); sensePanel.setMinimumSize(new Dimension(INNER_WIDTH, 35)); sensePanel.setMaximumSize(new Dimension(INNER_WIDTH, 35)); sensePanel.setPreferredSize(new Dimension(INNER_WIDTH, 35)); JLabel senseLabel = new JLabel("Senses"); senseLabel.setFont(new Font(senseLabel.getFont().getName(), Font.BOLD, senseLabel.getFont().getSize())); JTextArea senses = new JTextArea(monster.getSenses()); JScrollPane scrollSenses = new JScrollPane(senses); scrollSenses.addMouseWheelListener(new MouseWheelScrollListener(scrollSenses)); senses.setLineWrap(true); senses.setWrapStyleWord(true); senseLabel.setAlignmentY(Box.TOP_ALIGNMENT); scrollSenses.setAlignmentY(Box.TOP_ALIGNMENT); DeferredDocumentListener listener = new DeferredDocumentListener (new ActionListener() { @Override public void actionPerformed(ActionEvent e) { monster.setSenses(senses.getText()); } }); senses.getDocument().addDocumentListener(listener); senses.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { listener.start(); } @Override public void focusLost(FocusEvent e) { listener.stop(); } }); sensePanel.add(senseLabel); sensePanel.add(Box.createRigidArea(HORIZONTAL_GAP)); sensePanel.add(scrollSenses); return sensePanel; } private JPanel getLanguagePanel() { JPanel languagePanel = new JPanel(); languagePanel.setLayout(new BoxLayout(languagePanel, BoxLayout.X_AXIS)); languagePanel.setAlignmentX(Component.LEFT_ALIGNMENT); languagePanel.setMinimumSize(new Dimension(INNER_WIDTH, 35)); languagePanel.setMaximumSize(new Dimension(INNER_WIDTH, 35)); languagePanel.setPreferredSize(new Dimension(INNER_WIDTH, 35)); JLabel languageLabel = new JLabel("Languages"); languageLabel.setFont(new Font(languageLabel.getFont().getName(), Font.BOLD, languageLabel.getFont().getSize())); JTextArea languages = new JTextArea(monster.getLanguages()); JScrollPane scrollLanguages = new JScrollPane(languages); scrollLanguages.addMouseWheelListener(new MouseWheelScrollListener(scrollLanguages)); languages.setLineWrap(true); languages.setWrapStyleWord(true); languageLabel.setAlignmentY(Box.TOP_ALIGNMENT); scrollLanguages.setAlignmentY(Box.TOP_ALIGNMENT); DeferredDocumentListener listener = new DeferredDocumentListener (new ActionListener() { @Override public void actionPerformed(ActionEvent e) { monster.setLanguages(languages.getText()); } }); languages.getDocument().addDocumentListener(listener); languages.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { listener.start(); } @Override public void focusLost(FocusEvent e) { listener.stop(); } }); languagePanel.add(languageLabel); languagePanel.add(Box.createRigidArea(HORIZONTAL_GAP)); languagePanel.add(scrollLanguages); return languagePanel; } private JPanel getChallengePanel() { JPanel challengePanel = new JPanel(); challengePanel.setLayout(new BoxLayout(challengePanel, BoxLayout.X_AXIS)); challengePanel.setAlignmentX(Component.LEFT_ALIGNMENT); challengePanel.setMaximumSize(new Dimension(INNER_WIDTH, INNER_HEIGHT)); JLabel challengeLabel = new JLabel("Challenge"); challengeLabel.setFont(new Font(challengeLabel.getFont().getName(), Font.BOLD, challengeLabel.getFont().getSize())); JTextField challenge = new JTextField(monster.getChallenge()); challenge.setMaximumSize(new Dimension(30, INNER_HEIGHT)); JLabel xpLabel = new JLabel("(" + monster.getXP() + " XP)"); xpLabel.setFont(new Font(xpLabel.getFont().getName(), Font.ITALIC, xpLabel.getFont().getSize())); DeferredDocumentListener listener = new DeferredDocumentListener (new ActionListener() { @Override public void actionPerformed(ActionEvent e) { monster.setChallenge(challenge.getText()); xpLabel.setText("(" + monster.getXP() + " XP)"); proxy.updateMonster(monster); //updates xp values on server for enc builder } }); challenge.getDocument().addDocumentListener(listener); challenge.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { listener.start(); } @Override public void focusLost(FocusEvent e) { listener.stop(); } }); challengePanel.add(challengeLabel); challengePanel.add(Box.createRigidArea(HORIZONTAL_GAP)); challengePanel.add(challenge); challengePanel.add(Box.createRigidArea(HORIZONTAL_GAP)); challengePanel.add(xpLabel); return challengePanel; } private JLabel getAbilityLabel() { JLabel abilityLabel = new JLabel("Abilities"); abilityLabel.setFont(new Font(abilityLabel.getFont().getName(), Font.BOLD, 15)); abilityLabel.setAlignmentX(Component.LEFT_ALIGNMENT); return abilityLabel; } private JPanel getAbilityPanel(int i, JScrollPane scroll) { final int index = i; JPanel abilityPanel = new JPanel(); abilityPanel.setLayout(new BoxLayout(abilityPanel, BoxLayout.X_AXIS)); abilityPanel.setAlignmentX(Component.LEFT_ALIGNMENT); abilityPanel.setMaximumSize(new Dimension(INNER_WIDTH, 65)); JPanel innerPanel = new JPanel(); innerPanel.setLayout(new BoxLayout(innerPanel, BoxLayout.Y_AXIS)); JLabel abilityName = new JLabel(abilityList.get(i).getName()); abilityName.setFont(new Font(abilityName.getFont().getName(), Font.BOLD, abilityName.getFont().getSize())); JButton renameAbility = new JButton("Rename"); renameAbility.setMinimumSize(new Dimension(100, 25)); renameAbility.setMaximumSize(new Dimension(100, 25)); renameAbility.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String message = "Enter the new name for the ability:"; String name = (String) JOptionPane.showInputDialog(scroll, message, "Rename Ability", JOptionPane.QUESTION_MESSAGE); System.out.println(name); if (name == null || name.equals("")) return; monster.renameAbility(name, index); refreshRight(); } }); JButton deleteAbility = new JButton("Delete"); deleteAbility.setMinimumSize(new Dimension(100, 25)); deleteAbility.setMaximumSize(new Dimension(100, 25)); deleteAbility.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int yesNo = (int) JOptionPane.showConfirmDialog(scroll, "Are you sure you wish to delete " + abilityName.getText() + "?", "Delete Ability", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if (yesNo == JOptionPane.YES_OPTION) { monster.deleteAbility(index); refreshRight(); } } }); innerPanel.setAlignmentY(Box.CENTER_ALIGNMENT); innerPanel.add(abilityName); innerPanel.add(Box.createRigidArea(HORIZONTAL_GAP)); innerPanel.add(renameAbility); innerPanel.add(Box.createRigidArea(HORIZONTAL_GAP)); innerPanel.add(deleteAbility); innerPanel.add(Box.createRigidArea(HORIZONTAL_GAP)); JTextArea abilityDesc = new JTextArea(abilityList.get(i).getDescription()); abilityDesc.setAlignmentY(Box.CENTER_ALIGNMENT); abilityDesc.setLineWrap(true); abilityDesc.setWrapStyleWord(true); JScrollPane scrollDesc = new JScrollPane(abilityDesc); scrollDesc.addMouseWheelListener(new MouseWheelScrollListener(scrollDesc)); DeferredDocumentListener listener = new DeferredDocumentListener (new ActionListener() { @Override public void actionPerformed(ActionEvent e) { monster.setAbilityDescription(abilityDesc.getText(), i); } }); abilityDesc.getDocument().addDocumentListener(listener); abilityDesc.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { listener.start(); } @Override public void focusLost(FocusEvent e) { listener.stop(); } }); abilityPanel.add(innerPanel); abilityPanel.add(Box.createRigidArea(HORIZONTAL_GAP)); abilityPanel.add(scrollDesc); return abilityPanel; } private JLabel getActionLabel() { JLabel actionLabel = new JLabel("Actions"); actionLabel.setFont(new Font(actionLabel.getFont().getName(), Font.BOLD, 15)); actionLabel.setAlignmentX(Component.LEFT_ALIGNMENT); return actionLabel; } private JPanel getActionPanel(int i, JScrollPane scroll) { final int index = i; JPanel actionPanel = new JPanel(); actionPanel.setLayout(new BoxLayout(actionPanel, BoxLayout.X_AXIS)); actionPanel.setAlignmentX(Component.LEFT_ALIGNMENT); actionPanel.setMaximumSize(new Dimension(INNER_WIDTH, 65)); JPanel innerPanel = new JPanel(); innerPanel.setLayout(new BoxLayout(innerPanel, BoxLayout.Y_AXIS)); JLabel actionName = new JLabel(actionList.get(i).getName()); actionName.setFont(new Font(actionName.getFont().getName(), Font.BOLD, actionName.getFont().getSize())); JButton renameAction = new JButton("Rename"); renameAction.setMinimumSize(new Dimension(100, 25)); renameAction.setMaximumSize(new Dimension(100, 25)); renameAction.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String message = "Enter the new name for the action:"; String name = (String) JOptionPane.showInputDialog(scroll, message, "Rename Action", JOptionPane.QUESTION_MESSAGE); if (name == null) return; monster.renameAction(name, index); refreshRight(); } }); JButton deleteAction = new JButton("Delete"); deleteAction.setMinimumSize(new Dimension(100, 25)); deleteAction.setMaximumSize(new Dimension(100, 25)); deleteAction.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int yesNo = (int) JOptionPane.showConfirmDialog(scroll, "Are you sure you wish to delete " + actionName.getText() + "?", "Delete Action", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if (yesNo == JOptionPane.YES_OPTION) { monster.deleteAction(index); refreshRight(); } } }); innerPanel.setAlignmentY(Box.CENTER_ALIGNMENT); innerPanel.add(actionName); innerPanel.add(Box.createRigidArea(HORIZONTAL_GAP)); innerPanel.add(renameAction); innerPanel.add(Box.createRigidArea(HORIZONTAL_GAP)); innerPanel.add(deleteAction); innerPanel.add(Box.createRigidArea(HORIZONTAL_GAP)); JTextArea actionDesc = new JTextArea(actionList.get(i).getDescription()); actionDesc.setAlignmentY(Box.CENTER_ALIGNMENT); actionDesc.setLineWrap(true); actionDesc.setWrapStyleWord(true); JScrollPane scrollDesc = new JScrollPane(actionDesc); scrollDesc.addMouseWheelListener(new MouseWheelScrollListener(scrollDesc)); DeferredDocumentListener listener = new DeferredDocumentListener (new ActionListener() { @Override public void actionPerformed(ActionEvent e) { monster.setActionDescription(actionDesc.getText(), i); } }); actionDesc.getDocument().addDocumentListener(listener); actionDesc.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { listener.start(); } @Override public void focusLost(FocusEvent e) { listener.stop(); } }); actionPanel.add(innerPanel); actionPanel.add(Box.createRigidArea(HORIZONTAL_GAP)); actionPanel.add(scrollDesc); return actionPanel; } private JLabel getLegendaryLabel() { JLabel legendaryLabel = new JLabel("Legendary Actions"); legendaryLabel.setFont(new Font(legendaryLabel.getFont().getName(), Font.BOLD, 15)); legendaryLabel.setAlignmentX(Component.LEFT_ALIGNMENT); return legendaryLabel; } private JPanel getCountPanel() { JPanel countPanel = new JPanel(); countPanel.setLayout(new BoxLayout(countPanel, BoxLayout.X_AXIS)); countPanel.setAlignmentX(Component.LEFT_ALIGNMENT); countPanel.setMaximumSize(new Dimension(INNER_WIDTH, INNER_HEIGHT)); JLabel countLabel = new JLabel("Legendary Action Count"); countLabel.setFont(new Font(countLabel.getFont().getName(), Font.BOLD, countLabel.getFont().getSize())); JTextField count = new JTextField(monster.getLegendaryActionCount()); DeferredDocumentListener listener = new DeferredDocumentListener (new ActionListener() { @Override public void actionPerformed(ActionEvent e) { monster.setLegendaryActionCount(count.getText()); } }); count.getDocument().addDocumentListener(listener); count.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { listener.start(); } @Override public void focusLost(FocusEvent e) { listener.stop(); } }); countPanel.add(countLabel); countPanel.add(Box.createRigidArea(HORIZONTAL_GAP)); countPanel.add(count); return countPanel; } private JPanel getLegendaryPanel(int i, JScrollPane scroll) { JPanel legendaryPanel = new JPanel(); legendaryPanel.setLayout(new BoxLayout(legendaryPanel, BoxLayout.X_AXIS)); legendaryPanel.setAlignmentX(Component.LEFT_ALIGNMENT); legendaryPanel.setMaximumSize(new Dimension(INNER_WIDTH, 65)); JPanel innerPanel = new JPanel(); innerPanel.setLayout(new BoxLayout(innerPanel, BoxLayout.Y_AXIS)); JLabel legendaryName = new JLabel(legendaryList.get(i).getName()); legendaryName.setFont(new Font(legendaryName.getFont().getName(), Font.BOLD, legendaryName.getFont().getSize())); final int index = i; JButton renameLegendary = new JButton("Rename"); renameLegendary.setMinimumSize(new Dimension(100, 25)); renameLegendary.setMaximumSize(new Dimension(100, 25)); renameLegendary.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String message = "Enter the new name for the legendary action:"; String name; name = (String) JOptionPane.showInputDialog(scroll, message, "Rename Legendary Action", JOptionPane.QUESTION_MESSAGE); if (name == null) return; monster.renameLegendaryAction(name, index); refreshRight(); } }); JButton deleteLegendary = new JButton("Delete"); deleteLegendary.setMinimumSize(new Dimension(100, 25)); deleteLegendary.setMaximumSize(new Dimension(100, 25)); deleteLegendary.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int yesNo = (int) JOptionPane.showConfirmDialog(scroll, "Are you sure you wish to delete " + legendaryName.getText() + "?", "Delete Legendary Action", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if (yesNo == JOptionPane.YES_OPTION) { monster.deleteLegendaryAction(index); refreshRight(); } } }); innerPanel.setAlignmentY(Box.CENTER_ALIGNMENT); innerPanel.add(legendaryName); innerPanel.add(Box.createRigidArea(HORIZONTAL_GAP)); innerPanel.add(renameLegendary); innerPanel.add(Box.createRigidArea(HORIZONTAL_GAP)); innerPanel.add(deleteLegendary); innerPanel.add(Box.createRigidArea(HORIZONTAL_GAP)); JTextArea legendaryDesc = new JTextArea(legendaryList.get(i).getDescription()); legendaryDesc.setAlignmentY(Box.CENTER_ALIGNMENT); legendaryDesc.setLineWrap(true); legendaryDesc.setWrapStyleWord(true); JScrollPane scrollDesc = new JScrollPane(legendaryDesc); scrollDesc.addMouseWheelListener(new MouseWheelScrollListener(scrollDesc)); DeferredDocumentListener listener = new DeferredDocumentListener (new ActionListener() { @Override public void actionPerformed(ActionEvent e) { monster.setLegendaryDescription(legendaryDesc.getText(), i); } }); legendaryDesc.getDocument().addDocumentListener(listener); legendaryDesc.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { listener.start(); } @Override public void focusLost(FocusEvent e) { listener.stop(); } }); legendaryPanel.add(innerPanel); legendaryPanel.add(Box.createRigidArea(HORIZONTAL_GAP)); legendaryPanel.add(scrollDesc); return legendaryPanel; } /** * Defines what will happen when an item in the JList is selected */ private void listValueChanged(ListSelectionEvent event) { if (event.getValueIsAdjusting()) return; //update current monster on server before getting new monster info if (!list.isSelectionEmpty()) proxy.updateMonster(monster); getMonster(getLastSelected()); } //Stringify last selected value of JList public String getLastSelected() { if (list.isSelectionEmpty()) return "select a monster"; return list.getSelectedValue().toString(); } //gets currently selected monster public Monster getMonster() { return monster; } /** * Sets the currently selected value in the JList. After saving or updating * some things (such as adding an ability, action, etc, the current * selection seems to be lost, preventing back to back saving without * re-selecting the monster */ public void setSelection() { list.setSelectedValue(monster.getName(), true); //updates current monster info, needed for restoring monster = proxy.getMonster(monster.getName()); } /** * cals bonus for any skill/saving throw * expertise should always be false for saving throws */ private int calcBonus(int mod, int profBonus, boolean proficient, boolean expertise) { if (proficient) mod += profBonus; if (expertise) mod += profBonus; return mod; } /** * stringifies bonus and signs it */ private String signBonus(int mod) { String signed; if (mod < 0) signed = Integer.toString(mod); else signed = "+" + Integer.toString(mod); return signed; } }
35.950867
118
0.71935
a8efc326ce28c22bd58968f85f47c1308df22875
1,393
package cn.org.hentai.squeeze.sender.worker; import cn.org.hentai.squeeze.common.compress.CompressUtil; import cn.org.hentai.squeeze.sender.util.PipedReader; /** * Created by matrixy on 2019/3/11. */ public class FileCompressor extends Thread { String method; int level; int index; CompressorManager manager; PipedReader pipedReader; public FileCompressor(int index, CompressorManager manager, String method, int level) { this.index = index; this.manager = manager; this.method = method; this.level = level; this.setName("compressor-" + index); } public void run() { while (!this.isInterrupted()) { try { CompressorManager.DataFile file = manager.getFile(); // System.out.println(String.format("Compressor[%6d - %6d]: %s", index, file.id, file.path)); pipedReader = new PipedReader(40960); manager.watchStream(index, file.id, pipedReader); CompressUtil.compressAndConvertTo(file.basePath, file.path, level, method, pipedReader); pipedReader.waitForClose(); pipedReader = null; manager.unwatchStream(index); } catch(Exception ex) { ex.printStackTrace(); } } } }
27.86
109
0.582915
2364cbc8cafab5e4349e78c6fd5d2493719a3f6b
7,085
package no.nav.melosys.eessi.service.behandling; import lombok.extern.slf4j.Slf4j; import no.nav.melosys.eessi.identifisering.PersonIdentifisering; import no.nav.melosys.eessi.integration.PersonFasade; import no.nav.melosys.eessi.integration.journalpostapi.SedAlleredeJournalførtException; import no.nav.melosys.eessi.kafka.consumers.SedHendelse; import no.nav.melosys.eessi.kafka.producers.MelosysEessiProducer; import no.nav.melosys.eessi.models.SedKontekst; import no.nav.melosys.eessi.models.SedMottatt; import no.nav.melosys.eessi.models.SedType; import no.nav.melosys.eessi.models.sed.SED; import no.nav.melosys.eessi.models.vedlegg.SedMedVedlegg; import no.nav.melosys.eessi.service.eux.EuxService; import no.nav.melosys.eessi.service.joark.OpprettInngaaendeJournalpostService; import no.nav.melosys.eessi.service.joark.SakInformasjon; import no.nav.melosys.eessi.service.oppgave.OppgaveService; import no.nav.melosys.eessi.service.sed.mapper.fra_sed.melosys_eessi_melding.MelosysEessiMeldingMapper; import no.nav.melosys.eessi.service.sed.mapper.fra_sed.melosys_eessi_melding.MelosysEessiMeldingMapperFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Slf4j @Service @Deprecated(forRemoval = true) public class BehandleSedMottattService { private final OpprettInngaaendeJournalpostService opprettInngaaendeJournalpostService; private final EuxService euxService; private final PersonFasade personFasade; private final MelosysEessiProducer melosysEessiProducer; private final PersonIdentifisering personIdentifisering; private final OppgaveService oppgaveService; private final MelosysEessiMeldingMapperFactory melosysEessiMeldingMapperFactory; @Autowired public BehandleSedMottattService( OpprettInngaaendeJournalpostService opprettInngaaendeJournalpostService, EuxService euxService, PersonFasade personFasade, MelosysEessiProducer melosysEessiProducer, PersonIdentifisering personIdentifisering, OppgaveService oppgaveService, MelosysEessiMeldingMapperFactory melosysEessiMeldingMapperFactory) { this.opprettInngaaendeJournalpostService = opprettInngaaendeJournalpostService; this.euxService = euxService; this.personFasade = personFasade; this.melosysEessiProducer = melosysEessiProducer; this.personIdentifisering = personIdentifisering; this.oppgaveService = oppgaveService; this.melosysEessiMeldingMapperFactory = melosysEessiMeldingMapperFactory; } public void behandleSed(SedMottatt sedMottatt) { SedKontekst kontekst = sedMottatt.getSedKontekst(); SED sed = euxService.hentSed(sedMottatt.getSedHendelse().getRinaSakId(), sedMottatt.getSedHendelse().getRinaDokumentId()); if (!kontekst.isForsoktIdentifisert()) { identifiserPerson(sedMottatt, sed); } if (!kontekst.journalpostOpprettet()) { try { opprettJournalpost(sedMottatt); } catch (SedAlleredeJournalførtException e) { log.info("Inngående SED {} allerede journalført", e.getSedID()); sedMottatt.setFerdig(true); return; } } if (kontekst.personErIdentifisert()) { if (!kontekst.isPublisertKafka()) { publiserMelding(sedMottatt, sed); } } else { if (!kontekst.identifiseringsOppgaveOpprettet()) { opprettOppgaveIdentifisering(sedMottatt); } } } private void identifiserPerson(SedMottatt sedMottatt, SED sed) { log.info("Søker etter person for SED {}", sedMottatt.getSedHendelse().getRinaDokumentId()); personIdentifisering.identifiserPerson(sedMottatt.getSedHendelse().getRinaSakId(), sed) .ifPresent(s -> sedMottatt.getSedKontekst().setNavIdent(s)); sedMottatt.getSedKontekst().setForsoktIdentifisert(true); sedMottatt.getSedHendelse().setNavBruker(sedMottatt.getSedKontekst().getNavIdent()); } private void opprettJournalpost(SedMottatt sedMottatt) { log.info("Oppretter journalpost for SED {}", sedMottatt.getSedHendelse().getRinaDokumentId()); SedMedVedlegg sedMedVedlegg = euxService.hentSedMedVedlegg( sedMottatt.getSedHendelse().getRinaSakId(), sedMottatt.getSedHendelse().getRinaDokumentId() ); if (sedMottatt.getSedKontekst().personErIdentifisert()) { SakInformasjon sakInformasjon = opprettInngaaendeJournalpostService.arkiverInngaaendeSedHentSakinformasjon( sedMottatt.getSedHendelse(), sedMedVedlegg, sedMottatt.getSedKontekst().getNavIdent()); sedMottatt.getSedKontekst().setJournalpostID(sakInformasjon.getJournalpostId()); sedMottatt.getSedKontekst().setDokumentID(sakInformasjon.getDokumentId()); } else { String journalpostID = opprettInngaaendeJournalpostService.arkiverInngaaendeSedUtenBruker( sedMottatt.getSedHendelse(), sedMedVedlegg, null); sedMottatt.getSedKontekst().setJournalpostID(journalpostID); } } private void opprettOppgaveIdentifisering(SedMottatt sedMottatt) { log.info("Oppretter oppgave til ID og fordeling for SED {}", sedMottatt.getSedHendelse().getRinaDokumentId()); String oppgaveID = oppgaveService.opprettOppgaveTilIdOgFordeling( sedMottatt.getSedKontekst().getJournalpostID(), sedMottatt.getSedHendelse().getSedType(), sedMottatt.getSedHendelse().getRinaSakId() ); sedMottatt.getSedKontekst().setOppgaveID(oppgaveID); } private void publiserMelding(SedMottatt sedMottatt, SED sed) { log.info("Publiserer melding om mottatt sed på kafka for SED {}", sedMottatt.getSedHendelse().getRinaDokumentId()); MelosysEessiMeldingMapper mapper = melosysEessiMeldingMapperFactory.getMapper(SedType.valueOf(sed.getSedType())); if (mapper == null) { throw new IllegalStateException("Mapper for kafka-publisering er null!"); } SedHendelse sedHendelse = sedMottatt.getSedHendelse(); String aktoerID = personFasade.hentAktoerId(sedMottatt.getSedKontekst().getNavIdent()); boolean sedErEndring = euxService.sedErEndring(sedHendelse.getRinaDokumentId(), sedHendelse.getRinaSakId()); melosysEessiProducer.publiserMelding( mapper.map(aktoerID, sed, sedHendelse.getRinaDokumentId(), sedHendelse.getRinaSakId(), sedHendelse.getSedType(), sedHendelse.getBucType(), sedHendelse.getAvsenderId(), sedHendelse.getLandkode(), sedMottatt.getSedKontekst().getJournalpostID(), sedMottatt.getSedKontekst().getDokumentID(), sedMottatt.getSedKontekst().getGsakSaksnummer(), sedErEndring, sedHendelse.getRinaDokumentVersjon()) ); sedMottatt.getSedKontekst().setPublisertKafka(Boolean.TRUE); } }
51.34058
148
0.729711
1ef4bdd1dbe9b023afd655f59e070aa3640a0700
4,437
/* * Copyright 2016 Open Networking Laboratory * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.ospf.controller; /** * Representation of a wrapper object to store LSA and associated metadata. * Metadata consists about the origination of LSA, age of LSA when received etc. */ public interface LsaWrapper { /** * Gets the type of LSA, it can be a router,network,summary,external. * * @return lsa type */ public OspfLsaType lsaType(); /** * Sets the LSA type during the initialization of wrapper. * * @param lsaType lsa type */ public void setLsaType(OspfLsaType lsaType); /** * Determines the origination of LSA , this is called during ls refresh interval. * * @return true if self originated else false */ public boolean isSelfOriginated(); /** * Sets is self originated or not. * * @param isSelfOriginated true if self originated else false */ public void setIsSelfOriginated(boolean isSelfOriginated); /** * Age of LSA when received during the adjacency formation. * * @return Age of LSA when received */ public int lsaAgeReceived(); /** * Sets the Age of LSA when received during the adjacency formation. * * @param lsaAgeReceived Age of LSA when received */ public void setLsaAgeReceived(int lsaAgeReceived); /** * Gets the LSA present in the wrapper instance. * * @return LSA instance */ public OspfLsa ospfLsa(); /** * Sets the LSA instance to the wrapper. * * @param ospfLsa LSA instance */ public void setOspfLsa(OspfLsa ospfLsa); /** * Gets the current LSA Age, using this we calculate current age. * It is done against the age counter which is incremented every second. * * @return lsa age */ public int currentAge(); /** * Gets the age counter when received. * * @return the age counter when received */ public int ageCounterWhenReceived(); /** * Sets the age counter when received. * * @param ageCounterWhenReceived the age counter when received */ public void setAgeCounterWhenReceived(int ageCounterWhenReceived); /** * Gets the LSA process command, like max age, ls refresh, based on the command set. * The queue consumer will pick the LSA and start performing the actions, like flooding * out of the domain or generating a new LSA and flooding. * * @return lsa process command */ public String lsaProcessing(); /** * Sets the LSA process command, like max age , ls refresh , based on the command set. * The queue consumer will pick the LSA and start performing the actions, like flooding * out of the domain or generating a new LSA and flooding. * * @param lsaProcessing lsa process command */ public void setLsaProcessing(String lsaProcessing); /** * Gets bin number into which the LSA wrapper is put for aging process. * * @return bin number */ public int binNumber(); /** * Sets bin number into which the LSA wrapper is put for aging process. * * @param binNumber bin number */ public void setBinNumber(int binNumber); /** * Gets the interface on which the LSA was received. * * @return the interface instance */ public OspfInterface ospfInterface(); /** * Sets the interface on which the LSA was received, this is used later to flood the information. * * @param ospfInterface interface instance */ public void setOspfInterface(OspfInterface ospfInterface); /** * Sets the LSDB age. * Using LSDB age we are calculating age of a particular LSA. * * @param lsdbAge lsdbAge instance */ public void setLsdbAge(LsdbAge lsdbAge); }
28.625806
101
0.656525
eef8299ca5103a656203d2f05f77379a19ce703b
344
package com.pigmo.gbms.enums; /** * 消息上下架状态 */ public enum MessageStatus { PUBLISH("1","消息上架"), WITHDRAW("0","消息下架"); private String code; private String text; public String getCode() { return code; } MessageStatus(String code,String text){ this.code = code; this.text = text; } }
14.956522
43
0.578488
7ec5fa1765c89ce9780da2f822347147f2494518
1,470
public class _112PathSum { public static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public boolean hasPathSum(TreeNode root, int sum) { return JudgeIfHas(root, 0, sum); } private boolean JudgeIfHas(TreeNode root, int cur, int sum) { // TODO Auto-generated method stub if (root == null) return false; cur += root.val; if (root.left == null && root.right == null && cur == sum) return true; return JudgeIfHas(root.left, cur, sum) || JudgeIfHas(root.right, cur, sum); } public static void main(String[] args) { // TODO Auto-generated method TreeNode root = new TreeNode(-2); TreeNode node1 = new TreeNode(-3); TreeNode node2 = new TreeNode(3); TreeNode node3 = new TreeNode(6); TreeNode node4 = new TreeNode(2); root.right = node1; //root.right = node3; //node1.left = node2; node3.right = node4; _112PathSum A = new _112PathSum (); System.out.println(A.hasPathSum(root, -5)); } } //question: //Given a binary tree and a sum, determine if the tree has a root-to-leaf path such //that adding up all the values along the path equals the given sum. // //For example: //Given the below binary tree and sum = 22, // 5 // / \ // 4 8 // / / \ // 11 13 4 // / \ \ // 7 2 1 //return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
28.269231
84
0.602041
165ace998e913149e2cf376439eb9096bc087300
2,961
package com.watermark.androidwm.sample.watermark.wmutils; import android.text.TextUtils; import android.widget.EditText; import com.watermark.androidwm.sample.watermark.param.base.WMAlign; /** * @Author: wangsengren * @Description: EditText数据获取工具 * @Date: 2020-02-21 * @Version: 1.0 */ public class EditTextUtils { /** * 获取一个float文本,如果为空或者格式失败返回默认值 * * @param editText * @param def * @return */ public static float getOptFloat(EditText editText, float def) { String editString = editText.getText().toString(); return getOptFloat(editString, def); } /** * 获取一个float文本,如果为空或者格式失败返回默认值 * * @param editString * @param def * @return */ public static float getOptFloat(String editString, float def) { if (TextUtils.isEmpty(editString)) { return def; } try { Float aFloat = Float.valueOf(editString); return aFloat; } catch (Exception e) { return def; } } /** * 获取一个int文本,如果为空或者格式失败返回默认值 * * @param editText * @param def * @return */ public static int getOptInt(EditText editText, int def) { String editString = editText.getText().toString(); if (TextUtils.isEmpty(editString)) { return def; } try { Integer value = Integer.valueOf(editString); return value; } catch (Exception e) { return def; } } /** * 获取一个editString,如果为空或者格式失败返回默认值 * * @param editString * @param def * @return */ public static String getOptString(String editString, String def) { if (TextUtils.isEmpty(editString)) { return def; } return editString; } /** * 获取一个String文本,如果为空或者格式失败返回默认值 * * @param editText * @param def * @return */ public static String getOptString(EditText editText, String def) { String editString = editText.getText().toString(); return getOptString(editString, def); } /** * 获取Align,如果为空或者格式失败返回默认值 * * @param editText * @param def * @return */ public static String getAlign(EditText editText, String def) { String editString = editText.getText().toString(); if (WMAlign.CENTER.equals(editString)) { return WMAlign.CENTER; } if (WMAlign.START.equals(editString)) { return WMAlign.START; } if (WMAlign.END.equals(editString)) { return WMAlign.END; } if (TextUtils.isEmpty(def)) { return WMAlign.CENTER; } return def; } /** * 获取Align,如果为空或者格式失败返回默认值 * * @param editText * @return */ public static String getAlign(EditText editText) { return getAlign(editText, WMAlign.CENTER); } }
22.603053
70
0.5667
d418fd3a6542ecbb986e5cc3c659ec18f95bdc57
429
package com.lzf.flyingsocks; /** * 表示组件中的模块,相当于微型的组件 * @see com.lzf.flyingsocks.Named * @see com.lzf.flyingsocks.Component * @see com.lzf.flyingsocks.AbstractComponent * @param <T> 组件类型 */ public interface Module<T extends Component<?>> extends Named { /** * 设置模块名称 * @param name 模块名称 */ void setName(String name); /** * 获取这个模块被哪个组件持有 * @return 组件对象 */ T getComponent(); }
17.16
63
0.622378
42575f9bcdb4051ec589c0c4e8bd0f77e4a662c3
292
package io.falu.models.transfers; import com.google.gson.annotations.SerializedName; /** * The purpose of a transfer. */ public enum TransferPurpose { @SerializedName("business") BUSINESS, @SerializedName("salary") SALARY, @SerializedName("promotion") PROMOTION }
18.25
50
0.705479
d830bf4a7c3d28d8f25ada7ae387412fa941dfff
1,045
package com.twu.biblioteca.products; public class Movie extends Product { private final String director; private final int yearPublished; private final int rating; public Movie(String title, int yearPublished, String director, int rating) { super(title, String.format("| %7s | %-70s| %-30s| %-12s | %7s |", "ID", "MOVIE", "DIRECTOR", "YEAR", "RATING")); this.yearPublished = yearPublished; this.director = director; this.rating = rating; } public Movie(String title, int yearPublished, String director) { this(title, yearPublished, director, -1); } public String getDirector() { return director; } public int getYearPublished() { return yearPublished; } public String getRating() { return rating < 1 ? "Unrated" : String.valueOf(rating); } @Override public String toString() { return String.format("| %7s | %-70s| %-30s| %-12s | %7s |", getId(), getTitle(), director, yearPublished, getRating()); } }
28.243243
127
0.621053
a3291ee8de759a64fa50626eb90daf99b386a6d4
14,591
package net.ossrs.yasea.demo.faceserver; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.ImageFormat; import android.graphics.Rect; import android.graphics.YuvImage; import android.util.Log; import com.arcsoft.face.ErrorInfo; import com.arcsoft.face.FaceEngine; import com.arcsoft.face.FaceFeature; import com.arcsoft.face.FaceInfo; import com.arcsoft.face.FaceSimilar; import net.ossrs.yasea.demo.bean.FaceRegisterInfo; import net.ossrs.yasea.demo.util.ImageUtil; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * 人脸库操作类,包含注册和搜索 */ public class FaceServer { private static final String TAG = "FaceServer"; public static final String IMG_SUFFIX = ".jpg"; private static FaceEngine faceEngine = null; private static FaceServer faceServer = null; private static List<FaceRegisterInfo> faceRegisterInfoList; public static String ROOT_PATH; public static final String SAVE_IMG_DIR = "register" + File.separator + "imgs"; private static final String SAVE_FEATURE_DIR = "register" + File.separator + "features"; /** * 是否正在搜索人脸,保证搜索操作单线程进行 */ private boolean isProcessing = false; public static FaceServer getInstance() { if (faceServer == null) { synchronized (FaceServer.class) { if (faceServer == null) { faceServer = new FaceServer(); } } } return faceServer; } /** * 初始化 * * @param context 上下文对象 * @return 是否初始化成功 */ public boolean init(Context context) { synchronized (this) { if (faceEngine == null && context != null) { faceEngine = new FaceEngine(); int engineCode = faceEngine.init(context, FaceEngine.ASF_DETECT_MODE_VIDEO, FaceEngine.ASF_OP_0_ONLY, 16, 1, FaceEngine.ASF_FACE_RECOGNITION | FaceEngine.ASF_FACE_DETECT); if (engineCode == ErrorInfo.MOK) { initFaceList(context); return true; } else { faceEngine = null; Log.e(TAG, "init: failed! code = " + engineCode); return false; } } return false; } } /** * 销毁 */ public void unInit() { synchronized (this) { if (faceRegisterInfoList != null) { faceRegisterInfoList.clear(); faceRegisterInfoList = null; } if (faceEngine != null) { faceEngine.unInit(); faceEngine = null; } } } /** * 初始化人脸特征数据以及人脸特征数据对应的注册图 * * @param context 上下文对象 */ private void initFaceList(Context context) { synchronized (this) { if (ROOT_PATH == null) { ROOT_PATH = context.getFilesDir().getAbsolutePath(); } File featureDir = new File(ROOT_PATH + File.separator + SAVE_FEATURE_DIR); if (!featureDir.exists() || !featureDir.isDirectory()) { return; } File[] featureFiles = featureDir.listFiles(); if (featureFiles == null || featureFiles.length == 0) { return; } faceRegisterInfoList = new ArrayList<>(); for (File featureFile : featureFiles) { try { FileInputStream fis = new FileInputStream(featureFile); byte[] feature = new byte[FaceFeature.FEATURE_SIZE]; fis.read(feature); fis.close(); faceRegisterInfoList.add(new FaceRegisterInfo(feature, featureFile.getName())); } catch (IOException e) { e.printStackTrace(); } } } } public int getFaceNumber(Context context) { synchronized (this) { if (context == null) { return 0; } if (ROOT_PATH == null) { ROOT_PATH = context.getFilesDir().getAbsolutePath(); } File featureFileDir = new File(ROOT_PATH + File.separator + SAVE_FEATURE_DIR); int featureCount = 0; if (featureFileDir.exists() && featureFileDir.isDirectory()) { String[] featureFiles = featureFileDir.list(); featureCount = featureFiles == null ? 0 : featureFiles.length; } int imageCount = 0; File imgFileDir = new File(ROOT_PATH + File.separator + SAVE_IMG_DIR); if (imgFileDir.exists() && imgFileDir.isDirectory()) { String[] imageFiles = imgFileDir.list(); imageCount = imageFiles == null ? 0 : imageFiles.length; } return featureCount > imageCount ? imageCount : featureCount; } } public int clearAllFaces(Context context) { synchronized (this) { if (context == null) { return 0; } if (ROOT_PATH == null) { ROOT_PATH = context.getFilesDir().getAbsolutePath(); } if (faceRegisterInfoList != null) { faceRegisterInfoList.clear(); } File featureFileDir = new File(ROOT_PATH + File.separator + SAVE_FEATURE_DIR); int deletedFeatureCount = 0; if (featureFileDir.exists() && featureFileDir.isDirectory()) { File[] featureFiles = featureFileDir.listFiles(); if (featureFiles != null && featureFiles.length > 0) { for (File featureFile : featureFiles) { if (featureFile.delete()) { deletedFeatureCount++; } } } } int deletedImageCount = 0; File imgFileDir = new File(ROOT_PATH + File.separator + SAVE_IMG_DIR); if (imgFileDir.exists() && imgFileDir.isDirectory()) { File[] imgFiles = imgFileDir.listFiles(); if (imgFiles != null && imgFiles.length > 0) { for (File imgFile : imgFiles) { if (imgFile.delete()) { deletedImageCount++; } } } } return deletedFeatureCount > deletedImageCount ? deletedImageCount : deletedFeatureCount; } } /** * 注册人脸 * * @param context 上下文对象 * @param nv21 NV21数据 * @param width NV21宽度 * @param height NV21高度 * @param name 保存的名字,可为空 * @return 是否注册成功 */ public boolean register(Context context, byte[] nv21, int width, int height, String name) { synchronized (this) { if (faceEngine == null || context == null || nv21 == null || width % 4 != 0 || nv21.length != width * height * 3 / 2) { return false; } if (ROOT_PATH == null) { ROOT_PATH = context.getFilesDir().getAbsolutePath(); } boolean dirExists = true; //特征存储的文件夹 File featureDir = new File(ROOT_PATH + File.separator + SAVE_FEATURE_DIR); if (!featureDir.exists()) { dirExists = featureDir.mkdirs(); } if (!dirExists) { return false; } //图片存储的文件夹 File imgDir = new File(ROOT_PATH + File.separator + SAVE_IMG_DIR); if (!imgDir.exists()) { dirExists = imgDir.mkdirs(); } if (!dirExists) { return false; } //1.人脸检测 List<FaceInfo> faceInfoList = new ArrayList<>(); int code = faceEngine.detectFaces(nv21, width, height, FaceEngine.CP_PAF_NV21, faceInfoList); if (code == ErrorInfo.MOK && faceInfoList.size() > 0) { FaceFeature faceFeature = new FaceFeature(); //2.特征提取 code = faceEngine.extractFaceFeature(nv21, width, height, FaceEngine.CP_PAF_NV21, faceInfoList.get(0), faceFeature); String userName = name == null ? String.valueOf(System.currentTimeMillis()) : name; try { //3.保存注册结果(注册图、特征数据) if (code == ErrorInfo.MOK) { YuvImage yuvImage = new YuvImage(nv21, ImageFormat.NV21, width, height, null); //为了美观,扩大rect截取注册图 Rect cropRect = getBestRect(width, height, faceInfoList.get(0).getRect()); if (cropRect == null) { return false; } File file = new File(imgDir + File.separator + userName + IMG_SUFFIX); FileOutputStream fosImage = new FileOutputStream(file); yuvImage.compressToJpeg(cropRect, 100, fosImage); fosImage.close(); Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath()); //判断人脸旋转角度,若不为0度则旋转注册图 boolean needAdjust = false; if (bitmap != null) { switch (faceInfoList.get(0).getOrient()) { case FaceEngine.ASF_OC_0: break; case FaceEngine.ASF_OC_90: bitmap = ImageUtil.getRotateBitmap(bitmap, 90); needAdjust = true; break; case FaceEngine.ASF_OC_180: bitmap = ImageUtil.getRotateBitmap(bitmap, 180); needAdjust = true; break; case FaceEngine.ASF_OC_270: bitmap = ImageUtil.getRotateBitmap(bitmap, 270); needAdjust = true; break; default: break; } } if (needAdjust) { fosImage = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fosImage); fosImage.close(); } FileOutputStream fosFeature = new FileOutputStream(featureDir + File.separator + userName); fosFeature.write(faceFeature.getFeatureData()); fosFeature.close(); //内存中的数据同步 if (faceRegisterInfoList == null) { faceRegisterInfoList = new ArrayList<>(); } faceRegisterInfoList.add(new FaceRegisterInfo(faceFeature.getFeatureData(), userName)); return true; } } catch (IOException e) { e.printStackTrace(); } } return false; } } /** * 在特征库中搜索 * * @param faceFeature 传入特征数据 * @return 比对结果 */ public CompareResult getTopOfFaceLib(FaceFeature faceFeature) { if (faceEngine == null || isProcessing || faceFeature == null || faceRegisterInfoList == null || faceRegisterInfoList.size() == 0) { return null; } FaceFeature tempFaceFeature = new FaceFeature(); FaceSimilar faceSimilar = new FaceSimilar(); float maxSimilar = 0; int maxSimilarIndex = -1; isProcessing = true; for (int i = 0; i < faceRegisterInfoList.size(); i++) { tempFaceFeature.setFeatureData(faceRegisterInfoList.get(i).getFeatureData()); faceEngine.compareFaceFeature(faceFeature, tempFaceFeature, faceSimilar); if (faceSimilar.getScore() > maxSimilar) { maxSimilar = faceSimilar.getScore(); maxSimilarIndex = i; } } isProcessing = false; if (maxSimilarIndex != -1) { return new CompareResult(faceRegisterInfoList.get(maxSimilarIndex).getName(), maxSimilar); } return null; } /** * 将图像中需要截取的Rect向外扩张一倍,若扩张一倍会溢出,则扩张到边界,若Rect已溢出,则收缩到边界 * * @param width 图像宽度 * @param height 图像高度 * @param srcRect 原Rect * @return 调整后的Rect */ private static Rect getBestRect(int width, int height, Rect srcRect) { if (srcRect == null) { return null; } Rect rect = new Rect(srcRect); //1.原rect边界已溢出宽高的情况 int maxOverFlow = 0; int tempOverFlow = 0; if (rect.left < 0) { maxOverFlow = -rect.left; } if (rect.top < 0) { tempOverFlow = -rect.top; if (tempOverFlow > maxOverFlow) { maxOverFlow = tempOverFlow; } } if (rect.right > width) { tempOverFlow = rect.right - width; if (tempOverFlow > maxOverFlow) { maxOverFlow = tempOverFlow; } } if (rect.bottom > height) { tempOverFlow = rect.bottom - height; if (tempOverFlow > maxOverFlow) { maxOverFlow = tempOverFlow; } } if (maxOverFlow != 0) { rect.left += maxOverFlow; rect.top += maxOverFlow; rect.right -= maxOverFlow; rect.bottom -= maxOverFlow; return rect; } //2.原rect边界未溢出宽高的情况 int padding = rect.height() / 2; //若以此padding扩张rect会溢出,取最大padding为四个边距的最小值 if (!(rect.left - padding > 0 && rect.right + padding < width && rect.top - padding > 0 && rect.bottom + padding < height)) { padding = Math.min(Math.min(Math.min(rect.left, width - rect.right), height - rect.bottom), rect.top); } rect.left -= padding; rect.top -= padding; rect.right += padding; rect.bottom += padding; return rect; } }
37.508997
187
0.508601
39fbbbe17b2d48ae4c41229198b44710bbfbd552
1,529
package com.xoptimal.interaction.helper; import com.xoptimal.interaction.BuildConfig; import java.util.concurrent.TimeUnit; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; /** * Created by Freddie on 2017/8/14 0014 . * Description: */ public class RetrofitHelper { public static <T> T newInstance(String baseUrl, Class<T> aClass) { OkHttpClient.Builder builder = new OkHttpClient.Builder(); if (BuildConfig.DEBUG) { // Log信息拦截器 HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); //设置 Debug Log 模式 builder.addInterceptor(loggingInterceptor); } //设置超时 builder.connectTimeout(15, TimeUnit.SECONDS); builder.readTimeout(20, TimeUnit.SECONDS); builder.writeTimeout(20, TimeUnit.SECONDS); //错误重连 builder.retryOnConnectionFailure(true); OkHttpClient okHttpClient = builder.build(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(baseUrl) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .client(okHttpClient) .build(); return retrofit.create(aClass); } }
30.58
85
0.681491
7ffa5081abd810f9ee1d336934dca2c9c913a3fe
245
package applications.lectred; // Time-stamp: <24 fév 2010 09:41 queinnec@enseeiht.fr> public enum LectRedEtat { Redacteur_Demande, Redacteur_Ecrit, Redacteur_Rien, Lecteur_Demande, Lecteur_Lit, Lecteur_Rien }
20.416667
55
0.697959
1d002f4f668f30cce8bfb41bce0a11cef0898f5c
1,471
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package app10; import java.util.Scanner; /** * * @author felipehernandez */ public class App10 { //Constantes public static final int LUNES = 1; public static final int MARTES = 2; public static final int MIERCOLES = 3; public static final int JUEVES = 4; public static final int VIERNES = 5; public static final int SABADO = 6; public static final int DOMINGO = 7; public static int DIA = 1; /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Scanner scanner = new Scanner(System.in); System.out.println("Ingrese el dia de la semana: (Numero): "); int valor = scanner.nextInt(); String dia = ""; switch(valor){ case LUNES: dia = "LUNES"; break; case MARTES: dia = "MARTES"; break; case MIERCOLES: dia = "MIERCOLES"; break; default: dia = "día incorrecto"; } System.out.println("El dia de la semana ingresada es: "+dia); } }
22.984375
79
0.530931
bc97035183c6b38e72bf39fd6406c96f35bef0d1
448
package tudelft.blackjack; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class BlackJackLineCoverageTest { @Test public void bothPlayersGoTooHigh() { int result = new BlackJack().play(30, 30); Assertions.assertEquals(0, result); } @Test public void leftPlayerWins() { int result = new BlackJack().play(10, 9); Assertions.assertEquals(10, result); } }
22.4
50
0.667411
70bf7767099de721b3408e57fa6a8a68d4f396c9
1,887
package com.xuxd.baishun.beans; import javax.persistence.*; import java.io.Serializable; import java.math.BigDecimal; /** * @Auther: 许晓东 * @Date: 20-3-6 10:07 * @Description: */ @Entity @Table(name = "t_vip_users") public class VipUser implements Serializable { private static final long serialVersionUID = -2663252230706657072L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) String id; String name; BigDecimal money; String tel; String updateTime; int type; String remarks; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public BigDecimal getMoney() { return money; } public void setMoney(BigDecimal money) { this.money = money; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } public String getUpdateTime() { return updateTime; } public void setUpdateTime(String updateTime) { this.updateTime = updateTime; } public int getType() { return type; } public void setType(int type) { this.type = type; } public String getRemarks() { return remarks; } public void setRemarks(String remarks) { this.remarks = remarks; } @Override public String toString() { return "VipUser{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", money=" + money + ", tel='" + tel + '\'' + ", updateTime='" + updateTime + '\'' + ", type=" + type + ", remarks='" + remarks + '\'' + '}'; } }
19.453608
71
0.533651
82d6e97b5acd938257c5eaf2b70f5e380b4e340b
2,547
/* Copyright 2008-2019 Douglas Wikstrom * * This file is part of Verificatum Mix-Net (VMN). * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.verificatum.protocol.elgamal; /** * Container class identifying a component of a group element (or * array of group elements) within a list of group elements (or list * of arrays of group elements). This is used by {@link * ProtocolElGamalRearTool}. Two indexes are used: one for identifying * a group element (or group element array) within a list of group * elements (or group element arrays) and a second index to identify a * component thereof. * * @author Douglas Wikstrom */ class ProtocolElGamalRearPosition { /** * Index identifying a source group element (or array of group * elements). */ final int source; /** * Index identifying a component within a source group element (or * array of group elements). */ final int index; /** * Container class identifying a subarray within a list of source * arrays. * * @param source Index identifying a source group element (or * array of group elements). * @param index Index identifying a component of a group element * (or an array of group elements). */ ProtocolElGamalRearPosition(final int source, final int index) { this.source = source; this.index = index; } @Override public String toString() { return String.format("(%d,%d)", source, index); } }
34.890411
70
0.708677
3028c98ecbe5289aec9b21fd4f9fef767c1791ba
96
package cn.gyw.corejava.effective.third; public enum Color { RED, BLACK, GREEN; }
10.666667
40
0.645833
719ae0ae91f2a491f50fbcca71fca9b3f5fa8f17
39,125
/* FRODO: a FRamework for Open/Distributed Optimization Copyright (C) 2008-2013 Thomas Leaute, Brammert Ottens & Radoslaw Szymanek FRODO is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. FRODO is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. How to contact the authors: <http://frodo2.sourceforge.net/> */ package frodo2.algorithms.dpop.privacy; import java.lang.reflect.Array; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import org.jdom2.Element; import frodo2.algorithms.AgentInterface; import frodo2.algorithms.StatsReporter; import frodo2.algorithms.dpop.UTILmsg; import frodo2.algorithms.dpop.UTILpropagation; import frodo2.algorithms.dpop.VALUEmsg; import frodo2.algorithms.dpop.VALUEpropagation; import frodo2.algorithms.dpop.UTILpropagation.OptUtilMessage; import frodo2.algorithms.dpop.VALUEpropagation.AssignmentsMessage; import frodo2.algorithms.varOrdering.dfs.DFSgeneration; import frodo2.algorithms.varOrdering.dfs.DFSgeneration.DFSview; import frodo2.communication.Message; import frodo2.communication.OutgoingMsgPolicyInterface; import frodo2.communication.Queue; import frodo2.solutionSpaces.Addable; import frodo2.solutionSpaces.BasicUtilitySolutionSpace; import frodo2.solutionSpaces.DCOPProblemInterface; import frodo2.solutionSpaces.UtilitySolutionSpace; import frodo2.solutionSpaces.crypto.AddableBigInteger; import frodo2.solutionSpaces.hypercube.BasicHypercube; import frodo2.solutionSpaces.hypercube.Hypercube; /** * * Module that intercepts messages during UTIL and VALUE propagation and obfuscates the variable names, variable domains, and utility values * @param <V> the type used for variable values * @param <U> the type used for utility values, in stats gatherer mode only (in normal mode, AddableBigInteger is used) * @author Eric Zbinden, Thomas Leaute * */ public class VariableObfuscation < V extends Addable<V>, U extends Addable<U> > implements OutgoingMsgPolicyInterface<String>, StatsReporter { /** A random Stream */ private Random rand = new SecureRandom(); /** The type of the messages containing code names */ public static final String CODE_NAME_TYPE = "Code_Name"; /** The type of obfuscated VALUE messages */ public static final String OBFUSCATED_VALUE_TYPE = "OBFUSCATED_VALUE"; /** The type of obfuscated UTIL messages */ public static final String OBFUSCATED_UTIL_TYPE = "OBFUSCATED_UTIL"; /** A Map containing assignments variable-codeName with mergeBack * @note must be used only when codeName are generated or to send codeNameMsg when mergeBack=true*/ private Map<String, String> codeNamesMerged = new HashMap<String, String>(); /** A Map containing assignment variable-codeName without mergeBack: * (Pseudo-)Parent - Child - CodeName * @note must be used only when codeName are generated or to send codeNameMsg when mergeBack=false*/ private Map<String, Map<String, String>> codeNamesUnique = new HashMap<String, Map<String, String>>(); /** A Map containing assignments variable-domain with mergeBack * @note must be used only when domains are generated or to send codeNameMsg when mergeBack=true*/ private Map<String, V[]> obfuscatedMergedDomains = new HashMap<String, V[]>(); /** A Map containing assignments variable-domain without mergeBack: * (Pseudo-)Parent - Child - Domain * @note must be used only when domains are generated or to send codeNameMsg when mergeBack=false*/ private Map<String, Map<String, V[]>> obfuscatedUniqueDomains = new HashMap<String, Map<String, V[]>>(); /** A Map containing assignments of obfuscation keys to all variables of this agent * @note must be used only when domains are generated or to send utilKey when mergeBack=true*/ private Map<String, AddableBigInteger[]> utilKeyMerged = new HashMap<String, AddableBigInteger[]>(); /** A Map containing assignments of obfuscation keys without mergeBack: * (Pseudo-)Parent - Child - UtilKey * @note must be used only when domains are generated or to send utilKey when mergeBack=false*/ private Map<String, Map<String, AddableBigInteger[]>> utilKeyUnique = new HashMap<String, Map<String, AddableBigInteger[]>>(); /** Map for all variables of this agent of reverse map assignment codeName-variable of their (pseudo-)parents: * Child - Parents' CodeName - (Pseudo-)Parent */ private Map<String, Map<String, String>> decodeCodeName = new HashMap<String, Map<String, String>>(); /** Map for all variables of this agent of map assignment variable-codeName of their (pseudo-)parents: * Child - (Pseudo-)Parent - Parents' CodeName */ private Map<String, Map<String, String>> encodeParent = new HashMap<String, Map<String, String>>(); /** Map for all variables of this agent of map assignment variable-domain of their (pseudo-)parents: * Child - (Pseudo-)Parent - Domain. Cleartext domain in [0], obfuscated domain in [1]*/ private Map<String, Map< String, List<V[]> >> decodeDomains = new HashMap<String, Map< String, List<V[]> >>(); /** Map for all variables of this agent of maps of variable-utility obfuscation key assignments * Child - (Pseudo-)Parent - Utility key */ private Map<String, Map<String, AddableBigInteger[]>> receivedUtilKey = new HashMap<String, Map<String, AddableBigInteger[]>>(); /** own - (myChild OR myCodeName sent to myChild) - myUTIL */ private Map<String, Map<String, AddableBigInteger[]>> ownUtilKey = new HashMap<String, Map<String, AddableBigInteger[]>>(); /** Map with : Parent - Number of time utilities in UTILmsg must be decrypted */ private Map<String, Integer> numDecrypt = new HashMap<String, Integer>(); /** The true parent of each of this agent's variables in the DFS */ private Map<String, String> parents = new HashMap<String, String>(); /** If mergeBackEdges are allowed */ private final boolean mergeBack; /** Long.MIN_VALUE if the problem is a maximization problem, Long.MAX_VALUE otherwise */ private final AddableBigInteger infeasibleUtil; /** The size of the BigInteger for the utility obfuscation */ private final int numBits; /** The size by default of the BigInteger used for utility obfuscation*/ private final int default_numBits = 128; /** For each internal variable, the number of codeName messages it is still expecting */ private Map<String, Integer> incomingExpected = new HashMap<String, Integer>(); /** Set of all waiting msg */ private Map<String, ArrayList<UTILmsg<V, AddableBigInteger>>> waitingMsg = new HashMap<String, ArrayList<UTILmsg<V, AddableBigInteger>>>(); /** Map that says if a variable has decoded a UTIL */ private Map<String, Boolean> hasDecoded = new HashMap<String, Boolean>(); /** Map with the UTIL codeNames received (used without mergeBack). * Variable X - Children of X - CodeName(s) of X * @note used only without mergeBack */ private Map<String, Map<String, ArrayList<String>>> utilContent = new HashMap<String, Map<String, ArrayList<String>>>(); /** The agent's queue */ private Queue queue; /** Whether the algorithm has already started */ private boolean started = false; /** Problem description */ private DCOPProblemInterface<V, U> problem; /** The number of variables for which the stats gatherer is still waiting for an assignment */ private int remainingVars; /** The solution found to the problem */ private HashMap<String, V> solution; /** Whether the stats reporter should print its stats */ private boolean silent = false; /** * Constructor * @param problem problem description * @param parameters if mergeBackEdges feature is used or not */ @SuppressWarnings("unchecked") public VariableObfuscation(DCOPProblemInterface<V, U> problem, Element parameters){ this.problem = problem; if (problem.maximize()) infeasibleUtil = new AddableBigInteger ("-infinity"); else infeasibleUtil = new AddableBigInteger ("infinity"); String mergeArg = parameters.getAttributeValue("mergeBack"); if (mergeArg == null) mergeBack = false; else mergeBack = Boolean.parseBoolean(mergeArg); String numBitArg = parameters.getAttributeValue("numBits"); if (numBitArg == null) numBits = default_numBits; else numBits = Integer.parseInt(numBitArg); this.problem.setUtilClass((Class<U>) AddableBigInteger.class); } /** Constructor in stats gatherer mode * @param params the parameters of this module * @param problem the overall problem */ public VariableObfuscation (Element params, DCOPProblemInterface<V, U> problem) { this.problem = problem; this.remainingVars = problem.getVariables().size(); this.solution = new HashMap<String, V> (); this.infeasibleUtil = null; // Not used: this.numBits = 0; this.mergeBack = false; } /** * In mergeBack mode: Generates one codeName for the input variable \a * Without mergeBack mode: Initiate general codeName map only. * @param var the variable */ private void generateCodeName(String var){ if (mergeBack){ //create codeName in with mergeBack String codeName; do{ codeName = randomCodeName(); } while(codeNamesMerged.values().contains(codeName)); //avoid collision codeNamesMerged.put(var, codeName); } else { //without mergeBack, codeName are generated when a dfs msg is received codeNamesUnique.put(var, new HashMap<String, String>()); //initiate the map to avoid nullPointerException } } /** * In mergeBack mode: Generates a range of utilityKey for the input variable \a * Without mergeBack mode: Initiate general utilityKey map only * @param var the variable */ private void generateUtilObfuscKeys(String var){ if(mergeBack){ int sizeOfArray = problem.getDomainSize(var); AddableBigInteger[] list = new AddableBigInteger[sizeOfArray]; for(int i=0; i<sizeOfArray; i++){ list[i] = new AddableBigInteger(numBits, rand); } utilKeyMerged.put(var, list); } else { //without mergeBack, codeName are generated when a dfs msg is received utilKeyUnique.put(var, new HashMap<String, AddableBigInteger[]>()); //initiate the map to avoid nullPointerException } } /** * Generates a new codeName and new utility keys for the couple myVar-child and add it in the corresponding generals tables * @param myVar the var that generates the codeName * @param child the child who will receive msg that contains myVar's codeName * @warning to use only without mergeBack mode */ private void generateNewCodeName(String myVar, String child){ assert !mergeBack : "This method can not be called with mergeBack mode"; //generate unique codeName String codeName; ext: while (true) { codeName = this.randomCodeName(); // Check if this codename already exists for(Map<String, String> assign : codeNamesUnique.values()) if (assign.values().contains(codeName)) continue ext; break; } //add it to codeNames map codeNamesUnique.get(myVar).put(child, codeName); //generate and store obfuscated domains obfuscatedUniqueDomains.get(myVar).put(child, randomDomain(problem.getDomain(myVar))); //generate new utility key int sizeOfArray = problem.getDomainSize(myVar); AddableBigInteger[] list = new AddableBigInteger[sizeOfArray]; for(int i=0; i<sizeOfArray; i++){ list[i] = new AddableBigInteger(numBits, rand); } //store generated utility keys utilKeyUnique.get(myVar).put(child, list); } /** Initiates all maps for the input variable * @param var the variable */ private void initiateAllMaps(String var){ decodeCodeName.put(var, new HashMap<String, String>()); decodeDomains.put(var, new HashMap< String, List<V[]> >()); receivedUtilKey.put(var, new HashMap<String, AddableBigInteger[]>()); encodeParent.put(var, new HashMap<String, String>()); waitingMsg.put(var, new ArrayList<UTILmsg<V, AddableBigInteger>>()); incomingExpected.put(var, -1); //integer initialized at -1, but will be assigned to true value after received DFS output if(!mergeBack) { utilContent.put(var, new HashMap<String, ArrayList<String>>()); ownUtilKey.put(var, new HashMap<String, AddableBigInteger[]>()); } } /** * Create a random integer of 32 bits and return it in hex-decimal string form. * @return a randomCodeName */ private String randomCodeName(){ Integer randInt = rand.nextInt(); String randString = Integer.toHexString(randInt); return randString; } /** Generates a domain of random numbers * @param initDom the initial domain * @return a random domain of values in form of a array of size specified * @todo Make all obfuscated domains with the same size (given as a parameter in the XML file). */ @SuppressWarnings("unchecked") private V[] randomDomain(V[] initDom){ final int size = initDom.length; V valInstance = initDom[0]; V[] values = (V[]) Array.newInstance(valInstance.getClass(), size); HashSet<Integer> tempVal = new HashSet<Integer>(); for( int i =0; i<size;i++){ int obfucatedVal; do{ obfucatedVal = rand.nextInt(); } while (! tempVal.add(obfucatedVal)); // loop as long as adding obfuscatedVal to tempVal does not change tempVal values[i] = valInstance.fromString(Integer.toString(obfucatedVal)); } return values; } /** * Translates (decodes or encodes) a specified value of the domain of variable \a other * @param myVar the variable who calls this method * @param other the variable who owns the value to translate * @param value the value to be translated * @param decode \c true if myVar wants to decode the value, \c false if myVar wants to encode the value * @return the specified value translated (decoded or encoded) if myVar knows the translation, else returns \c null */ private V getTranslatedValue(String myVar, String other, V value, boolean decode){ if (decode){ //decode the value V[] obfuscVals = this.encodeDomain(myVar, other); if(obfuscVals != null){ int index = -1; for(int i=0;i<obfuscVals.length;i++){ if (obfuscVals[i].equals(value)) { index = i; break; } } return this.decodeDomain(myVar, other)[index]; } else return null; //don't know the values for "other" } else { //encode the value V[] vals = this.decodeDomain(myVar, other); if(vals != null){ int index = -1; for(int i=0;i<vals.length;i++){ if (vals[i].equals(value)) { index = i; break; } } return this.encodeDomain(myVar, other)[index]; } else return null; //don't know the values for "other" } } /** Initiates the variableObfuscation module */ private void init(){ for (String var : this.problem.getMyVars()) this.init(var); for(String var : problem.getAllVars()) hasDecoded.put(var, false); this.started = true; } /** Initiates all datastructures related to the input variable * @param var the variable */ private void init (String var) { //initiate the codeName and this.generateCodeName(var); //initiate the obfuscated domains this.generateObfuscatedDomains(var); //initiate the obfuscation key this.generateUtilObfuscKeys(var); //initiate reverse map for decode and other maps used in variableObfuscation this.initiateAllMaps(var); } /** * In mergeBack mode: Generates an obfuscated domain for the input variable. * Without mergeBack mode: Only initiates the table * @param var the variable */ private void generateObfuscatedDomains(String var){ if(mergeBack) obfuscatedMergedDomains.put(var, randomDomain(problem.getDomain(var))); else { //Domains are generated after, when a dfs msg is received obfuscatedUniqueDomains.put(var, new HashMap<String, V[]>()); //initiate the map to avoid nullPointerException } } /** Send the delayed UTILmsg * @param myVar the var who can send its UTILmsg */ private void sendDelayedMsg(String myVar){ for(Message msg : waitingMsg.get(myVar)){ String msgType = msg.getType(); if(msgType.equals(UTILpropagation.UTIL_MSG_TYPE)){ notifyOut(msg); } else if (msgType.equals(VariableObfuscation.OBFUSCATED_UTIL_TYPE)){ notifyIn(msg); } } waitingMsg.put(myVar, new ArrayList<UTILmsg<V, AddableBigInteger>>()); } /** * @see frodo2.communication.OutgoingMsgPolicyInterface#notifyOut(frodo2.communication.Message) */ @SuppressWarnings("unchecked") public Decision notifyOut(Message msg) { String msgType = msg.getType(); /************************* DFS MSG *************************/ if (msgType.equals(DFSgeneration.OUTPUT_MSG_TYPE)){ //Cast DFSgeneration.MessageDFSoutput<V, U> msgCast = (DFSgeneration.MessageDFSoutput<V, U>) msg; //content String myVar = msgCast.getVar(); DFSview<V, U> relations = msgCast.getNeighbors(); if (relations == null) { // DFS reset message this.init(myVar); return Decision.DONTCARE; } boolean added = false; //For all child and pseudo child, send the code name Set<String> below = new HashSet<String> (relations.getChildren()); below.addAll(relations.getAllPseudoChildren()); for (String child : below){ /***** GENERATE OR GET ALL CODENAMES FOR THIS RELATION *****/ if(!mergeBack) generateNewCodeName(myVar, child); //in mergeBack mode, codeName and domain are already generated String codeName; V[] dom = problem.getDomain(myVar); V[] obfusDom; AddableBigInteger[] utilityKey; if(mergeBack) { codeName = codeNamesMerged.get(myVar); obfusDom = this.obfuscatedMergedDomains.get(myVar); utilityKey = this.utilKeyMerged.get(myVar); } else { codeName = codeNamesUnique.get(myVar).get(child); obfusDom = this.obfuscatedUniqueDomains.get(myVar).get(child); utilityKey = this.utilKeyUnique.get(myVar).get(child); } /***** SEND CODENAMES *****/ CodeNameMsg<V> oMsg = new CodeNameMsg<V> (myVar, child, codeName, dom, obfusDom, utilityKey); queue.sendMessage(problem.getOwner(child), oMsg); //send to child /***** ADD OWN REFERENCES IN THE DIFFERENT MAPS *****/ if (relations.getChildren().contains(child)) { parents.put(child, myVar); if(!mergeBack)utilContent.get(myVar).put(child, new ArrayList<String>()); } if(!mergeBack){ //without mergeBack //add all own key (one key per children) this.decodeCodeName.get(myVar).put(codeName, myVar); //Trick to store all own obfuscated domains referred to the codeName of its child this.decodeDomains.get(myVar).put(codeName, Arrays.asList(dom, obfusDom)); if(!added){ //Store once the domain for myVar this.decodeDomains.get(myVar).put(myVar, Arrays.asList(dom, obfusDom)); added = true; } ownUtilKey.get(myVar).put(child, utilityKey); //trick to store the link between its own codeName and the utility keys ownUtilKey.get(myVar).put(codeName, utilityKey); } else if (!added){ //with mergeBack //add key only once ('cause key is unique for every variables) this.addReverseMap(myVar, myVar, codeName, dom, obfusDom, utilityKey); added = true; } } //Note how many times utilities must be decrypted if (mergeBack) { numDecrypt.put(myVar, relations.getAllPseudoChildren().size() + relations.getChildren().size()); } //Note how many (pseudo-)parents this var has (to know how many CodeName messages must be received before UTIL propagation) int parentRelation = (relations.getParent() == null ? 0 : 1) + relations.getPseudoParents().size(); int temp = parentRelation+1+incomingExpected.get(myVar); //1+incomingExpected = nb CodeNameMsg already received incomingExpected.put(myVar, temp); //Send delayed msg if the expected incoming codeName msg is reached if(temp == 0) this.sendDelayedMsg(myVar); /************************* UTIL MSG *************************/ } else if (msgType.equals(UTILpropagation.UTIL_MSG_TYPE)){ //cast UTILmsg<V, AddableBigInteger> msgCast = (UTILmsg<V, AddableBigInteger>) msg; //content String myParent = msgCast.getDestination(); String myVar = msgCast.getSender(); Integer expected = incomingExpected.get(myVar); if (expected == null){ //This message is a UTIL that has just been decoded //Sender and receiver are owned by two different agents hasDecoded.put(myParent, false); return Decision.DONTCARE; } else if (expected == 0){ // we have received all expected codeNames if(hasDecoded.get(myParent)){ //true if myParent = me && this msg has been decoded //This message is a UTIL that has just been decoded //Sender and receiver are owned by a common agent hasDecoded.put(myParent, false); return Decision.DONTCARE; } Hypercube<V, AddableBigInteger> space = msgCast.getSpace().toHypercube(); //encode content for (String parent : space.getVariables()){ String parentCodeName = this.encodeCodeName(myVar, parent); if (parentCodeName != null) { V[] dom = space.getDomain(parent); V[][] doms = (V[][]) Array.newInstance(dom.getClass(), 1); doms[0] = dom; Hypercube<V, AddableBigInteger> e_p = new Hypercube<V,AddableBigInteger> (new String[]{parent}, doms, this.encryptUtility(myVar, parent), infeasibleUtil ); space = (Hypercube<V, AddableBigInteger>) space.join(e_p); //set utility space.setDomain(parent, this.encodeDomain(myVar, parent)); //set domain space.renameVariable(parent, parentCodeName); //set name } } //send obfuscated msg hasDecoded.put(myVar, false); ObsfUTILmsg<V> oMsg = new ObsfUTILmsg<V> (myVar, this.problem.getAgent(), myParent, space); this.queue.sendMessage(problem.getOwner(myParent), oMsg); } else { //CodeName msg are not already all received waitingMsg.get(myVar).add((msgCast)); } //discard the not obfuscated message return Decision.DISCARD; /************************* VALUE MSG *************************/ } else if (msgType.equals(VALUEpropagation.VALUE_MSG_TYPE)){ //Cast VALUEmsg<V> msgCast = (VALUEmsg<V>) msg; //content String child = msgCast.getDest(); String x = parents.get(child); //x = Current Variable if(x == null) { //This message is a VALUE that has just been decoded //Sender and receiver are owned by two different agents return Decision.DONTCARE; } else if (hasDecoded.get(child)){ //This message is a VALUE that has just been decoded //Sender and receiver are owned by the same agent hasDecoded.put(child, false); return Decision.DONTCARE; } else { //This message needs to be encoded String[] vars = msgCast.getVariables(); V[] values = msgCast.getValues(); ArrayList<String> codeNames = null; ArrayList<String> varsInCodeNames = new ArrayList<String>(); ArrayList<V> obfuscVals = new ArrayList<V>(); if(!mergeBack) { codeNames = utilContent.get(x).get(child); //codeNames to send to x's child assert codeNames.size()!=0 : "Values for itself was not recorded from UTIL message"; } for (int i=0; i < vars.length; i++){ if (!mergeBack && vars[i].equals(x)){ //without mergeBack and variable x //Add all necessary codeNames for (String c_x : codeNames){ varsInCodeNames.add(c_x); obfuscVals.add(this.getTranslatedValue(x, c_x, values[i], false)); } } else { //with mergeBack or without mergBack but with !x String codeName = this.encodeCodeName(parents.get(child), vars[i]); //CodeName for this variable is known if (codeName != null) { varsInCodeNames.add(codeName); V value = this.getTranslatedValue(x, vars[i], values[i], false); obfuscVals.add(value); //Unknown variable => This is already an obfuscated CodeName } else { varsInCodeNames.add(vars[i]); obfuscVals.add(values[i]); } } } String[] cns = new String[varsInCodeNames.size()]; cns = varsInCodeNames.toArray(cns); V[] vs = (V[]) Array.newInstance(obfuscVals.get(0).getClass(), obfuscVals.size()); vs = obfuscVals.toArray(vs); //send obfuscated message ObfsVALUEmsg<V> oMsg = new ObfsVALUEmsg<V> (child, cns, vs); queue.sendMessage(problem.getOwner(child), oMsg); //discard the not obfuscated message return Decision.DISCARD; } } else if (msgType.equals(UTILpropagation.OPT_UTIL_MSG_TYPE)) { // the optimal utility for a constraint graph component OptUtilMessage<AddableBigInteger> msgCast = (OptUtilMessage<AddableBigInteger>) msg; AddableBigInteger util = msgCast.getUtility(); // Replace large numbers by true infinities if necessary if (this.problem.maximize()) { if (util.compareTo(util.fromString(Integer.toString(Integer.MIN_VALUE))) <= 0) msgCast.setPayload1(AddableBigInteger.MinInfinity.MIN_INF); } else if (util.compareTo(util.fromString(Integer.toString(Integer.MAX_VALUE))) >= 0) msgCast.setPayload1(AddableBigInteger.PlusInfinity.PLUS_INF); return Decision.DONTCARE; } //else, we don't care return Decision.DONTCARE; } /** * @see frodo2.communication.MessageListener#getMsgTypes() */ public Collection<String> getMsgTypes() { ArrayList <String> msgTypes = new ArrayList <String> (8); msgTypes.add(AgentInterface.START_AGENT); msgTypes.add(UTILpropagation.UTIL_MSG_TYPE); msgTypes.add(UTILpropagation.OPT_UTIL_MSG_TYPE); msgTypes.add(DFSgeneration.OUTPUT_MSG_TYPE); msgTypes.add(VALUEpropagation.VALUE_MSG_TYPE); msgTypes.add(CODE_NAME_TYPE); msgTypes.add(OBFUSCATED_VALUE_TYPE); msgTypes.add(OBFUSCATED_UTIL_TYPE); return msgTypes; } /** * @see frodo2.communication.MessageListener#setQueue(frodo2.communication.Queue) */ public void setQueue(Queue queue) { this.queue = queue; } /** * @see frodo2.communication.IncomingMsgPolicyInterface#notifyIn(frodo2.communication.Message) */ @SuppressWarnings("unchecked") public void notifyIn(Message msg) { String msgType = msg.getType(); if (msgType.equals(VALUEpropagation.OUTPUT_MSG_TYPE)) { // we are in stats gatherer mode AssignmentsMessage<V> msgCast = (AssignmentsMessage<V>) msg; String[] vars = msgCast.getVariables(); ArrayList<V> vals = msgCast.getValues(); for (int i = 0; i < vars.length; i++) { String var = vars[i]; V val = vals.get(i); if (!silent) System.out.println("var `" + var + "' = " + val); solution.put(var, val); } // When we have received all messages, print out the corresponding utility. if (!silent && --this.remainingVars <= 0) { U util = this.problem.getUtility(this.solution, false).getUtility(0); // Fix the utility for infeasible problems if (this.problem.maximize()) { if (util.compareTo(util.fromString(Integer.toString(Integer.MIN_VALUE))) <= 0) util = this.problem.getMinInfUtility(); } else if (util.compareTo(util.fromString(Integer.toString(Integer.MAX_VALUE))) >= 0) util = this.problem.getPlusInfUtility(); if (this.problem.maximize()) System.out.println("Total optimal utility: " + util); else System.out.println("Total optimal cost: " + util); } return; } if (! this.started) this.init(); /************************* CODE NAME MSG *************************/ if (msgType.equals(CODE_NAME_TYPE)){ //cast CodeNameMsg<V> msgCast = (CodeNameMsg<V>) msg; String dest = msgCast.getReceiver(); //add content in the reverse maps addReverseMap(msgCast.getSender(), dest, msgCast.getCodeName(), msgCast.getCleartextDomain(), msgCast.getOfuscatedDomain(), msgCast.getOfuscatedUtility()); //send delayed UTILmsg incomingExpected.put(dest, incomingExpected.get(dest)-1); if (incomingExpected.get(dest)==0) this.sendDelayedMsg(dest); /************************* OBFUSC UTIL MSG *************************/ } else if (msgType.equals(OBFUSCATED_UTIL_TYPE)){ //Cast ObsfUTILmsg<V> msgCast = (ObsfUTILmsg<V>) msg; String myVar = msgCast.getDestination(); if (incomingExpected.get(myVar) == 0){ // we have already received all codeNames //content String sender = msgCast.getSender(); UtilitySolutionSpace<V, AddableBigInteger> space = msgCast.getSpace(); // Decode the variables ArrayList<Integer> indexes = new ArrayList<Integer>(); // indexes of variables in the space corresponding to myself for( String codeName : space.getVariables()){ // Check whether I know this codeName String var = this.decodeCodeName(myVar, codeName); if (var != null){ // Check whether this codeName refers to myself or to another variable higher in the DFS if(var.equals(myVar)){ indexes.add(space.getIndex(codeName)); if(!mergeBack) { utilContent.get(myVar).get(sender).add(codeName); } } else { V[] decodedDomain = this.decodeDomain(myVar, var); space.renameVariable(codeName, var); //set name space.setDomain(var, decodedDomain); //set domain } } } assert ! indexes.isEmpty() : "Received obfuscated UTIL message does not contain the codename of the destination variable"; int indexSize = indexes.size(); if (indexSize == 1) { //Current variable is only once in the space String codeName = space.getVariable(indexes.get(0)); space.renameVariable(codeName, myVar); //set name V[] decodedDomain = this.decodeDomain(myVar, myVar); space.setDomain(myVar, decodedDomain); //set domain //decrypt utilities AddableBigInteger[] decryptedUtil; if(mergeBack) decryptedUtil = this.decryptUtility(myVar, myVar); else decryptedUtil = this.decryptMySelfUtility(myVar, codeName); V[][] doms = (V[][]) Array.newInstance(decodedDomain.getClass(), 1); doms[0] = decodedDomain; UtilitySolutionSpace<V, AddableBigInteger> e_p = new Hypercube<V, AddableBigInteger> (new String[]{myVar}, doms, decryptedUtil, null); if (mergeBack){ /* Decrypt utility X times where X is the number of (pseudo-)children * Because the join operation is commutative, the decryption will be done on only one UTILmsg. * The join of all UTILmsg will be in this manner decrypted. */ for (int i=0; i<numDecrypt.get(myVar);i++){ space = space.join(e_p); } numDecrypt.put(myVar, 0); //set numDecrypt to 0. All other UTIL won't be decrypted (the join of all UTIL will) } else space = space.join(e_p); //set utility without mergeBack } else { //Current variable is several times in the space String[] codeNames = new String[indexSize]; V[] domain = this.decodeDomain(myVar, myVar); for(int i=0; i<indexSize;i++){ codeNames[i] = space.getVariable(indexes.get(i)); } for(String mySelf : codeNames){ V[] dom = space.getDomain(mySelf); V[][] doms = (V[][]) Array.newInstance(dom.getClass(), 1); doms[0] = dom; UtilitySolutionSpace<V, AddableBigInteger> e_x = new Hypercube<V, AddableBigInteger> (new String[] {mySelf}, doms, this.decryptMySelfUtility(myVar, mySelf), infeasibleUtil); space = space.join(e_x); //set utility } int size = domain.length; ArrayList<V>[] arrays = new ArrayList [size]; for(int i=0;i<size;i++){ ArrayList<V> array = new ArrayList<V>(); for(String cx : codeNames){ array.add(space.getDomain(cx)[i]); } arrays[i] = array; } V[][] doms = (V[][]) Array.newInstance(domain.getClass(), 1); doms[0] = domain; BasicUtilitySolutionSpace<V, ArrayList<V>> sub = new BasicHypercube<V, ArrayList<V>>(new String[]{myVar}, doms, arrays, null); space = space.compose(codeNames, sub); //set name & domain } //send decoded msg hasDecoded.put(myVar, true); UTILmsg<V, AddableBigInteger> iMsg = new UTILmsg<V, AddableBigInteger>(sender, this.problem.getAgent(), myVar, space); this.queue.sendMessageToSelf(iMsg); } else { //All codeName are not already received waitingMsg.get(myVar).add(msgCast); } /************************* OBFUSC VALUE MSG *************************/ } else if (msgType.equals(OBFUSCATED_VALUE_TYPE)){ //cast ObfsVALUEmsg<V> msgCast = (ObfsVALUEmsg<V>) msg; //content String myVar = msgCast.getDest(); String[] varsCoded = msgCast.getVariables(); V[] obfuscVals = msgCast.getValues(); //Decode int size = varsCoded.length; String[] vars = new String[size]; V[] vals = (V[]) Array.newInstance(obfuscVals.getClass().getComponentType(), size); for( int i=0; i<size;i++){ String var = this.decodeCodeName(myVar, varsCoded[i]); if(var != null) { vars[i] = var; vals[i] = this.getTranslatedValue(myVar, vars[i], obfuscVals[i], true); } else { vars[i] = varsCoded[i]; vals[i] = obfuscVals[i]; } } //send hasDecoded.put(myVar, true); VALUEmsg<V> iMsg = new VALUEmsg<V>(myVar, vars, vals); this.queue.sendMessageToSelf(iMsg); } } /** Puts in the reverse maps the assignment codeName-variable and parent-domain for a given child variable * @param parent the parent that sent this message * @param myVar the given child variable that received the assignment codeName-variable from its parent * @param codeName The code name of the parent * @param domain the domain of the parent variable, in cleartext * @param obfuscatedDomain the obfuscated domain of the parent * @param utilityKeys the utility obfuscation keys of the parent */ private void addReverseMap(String parent, String myVar, String codeName, V[] domain, V[] obfuscatedDomain, AddableBigInteger[] utilityKeys){ decodeCodeName.get(myVar).put(codeName, parent); encodeParent.get(myVar).put(parent, codeName); decodeDomains.get(myVar).put(parent, Arrays.asList(domain, obfuscatedDomain)); receivedUtilKey.get(myVar).put(parent, utilityKeys); } /** * Returns the variable assigned with the given codeName if and only if the variable who want to decode is a child * or a pseudo child of the coded variable. Else, return null * @param myVar the variable who want to decode the codeName * @param codeName the codeName to decode * @return the variable which correspond to the code name or null if this knowledge is unknown */ private String decodeCodeName(String myVar, String codeName){ return decodeCodeName.get(myVar).get(codeName); } /** * Returns the codeName assigned with the given parent if and only if the variable who wants to decode is a child * or a pseudo child of the coded variable. Else, returns null * @param myVar the variable who wants to decode the codeName * @param parent the parent to encode * @return the codeName which corresponds to the parent or null if this codename is unknown */ private String encodeCodeName(String myVar, String parent){ return encodeParent.get(myVar).get(parent); } /** * Returns the parent's cleartext domain if and only if the variable who wants to decode is a child * or wants to decode its own domain. Else, returns null * @param myVar the variable who want to decode the domain * @param parent the parent whose domain has to be decoded * @return The parent's cleartext domain. Or null if this parent's cleartext domain is unknown. */ private V[] decodeDomain(String myVar, String parent){ List<V[]> temp = decodeDomains.get(myVar).get(parent); if (temp != null) return temp.get(0); return null; } /** * Returns the parent's obfuscated domain if and only if * the variable who wants to obfuscate is a child or wants to obfuscate its own domain. Else, returns null * @param myVar the variable who wants to obfuscate the domain * @param parent the parent whose domain has to be obfuscated * @return The parent's obfuscated domain. Or \c null if this parent's domain is unknown. */ private V[] encodeDomain(String myVar, String parent){ List<V[]> temp = decodeDomains.get(myVar).get(parent); if (temp != null) return temp.get(1); return null; } /** * * @param myVar the variable that called this method * @param parent the variable whose utility keys we want * @return the tab of the utility keys */ private AddableBigInteger[] encryptUtility(String myVar, String parent){ return this.receivedUtilKey.get(myVar).get(parent); } /** * * @param myVar the variable that called this method * @param child the variable whose utility keys we want * @return the tab of the utility keys of inverse sign */ private AddableBigInteger[] decryptUtility(String myVar, String child){ AddableBigInteger[] received = this.receivedUtilKey.get(myVar).get(child); AddableBigInteger[] result = new AddableBigInteger[received.length]; for(int i=0; i<result.length; i++){ result[i] = received[i].flipSign(); } return result; } /** * * @param myVar the variable that wants to decrypt its own utility keys * @param child the child to whom myVar has sent this utilityKey * @return a tab with the utility keys of inverse sign */ private AddableBigInteger[] decryptMySelfUtility(String myVar, String child){ AddableBigInteger[] received = this.ownUtilKey.get(myVar).get(child); AddableBigInteger[] result = new AddableBigInteger[received.length]; for(int i=0; i<result.length; i++){ result[i] = received[i].flipSign(); } return result; } /** @see StatsReporter#getStatsFromQueue(Queue) */ public void getStatsFromQueue(Queue queue) { queue.addIncomingMessagePolicy(VALUEpropagation.OUTPUT_MSG_TYPE, this); } /** @see StatsReporter#reset() */ public void reset() { this.remainingVars = problem.getVariables().size(); } /** @see StatsReporter#setSilent(boolean) */ public void setSilent(boolean silent) { this.silent = silent; } }
37.050189
142
0.689022
0d7f9f6db50e857c0f14a7f292342e07ba2b2a2e
19,565
/* * Copyright (C) 2012 DataStax Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.datastax.driver.core; import java.net.InetAddress; import java.util.*; import org.testng.annotations.Test; import static org.testng.Assert.*; import com.datastax.driver.core.exceptions.*; import com.datastax.driver.core.policies.*; import static com.datastax.driver.core.TestUtils.*; public class RetryPolicyTest extends AbstractPoliciesTest { /** * Test RetryPolicy to ensure the basic unit get tests for the RetryDecisions. */ public static class TestRetryPolicy implements RetryPolicy { public RetryDecision onReadTimeout(Query query, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataRetrieved, int nbRetry) { return RetryDecision.rethrow(); } public RetryDecision onWriteTimeout(Query query, ConsistencyLevel cl, WriteType writeType, int requiredAcks, int receivedAcks, int nbRetry) { return RetryDecision.rethrow(); } public RetryDecision onUnavailable(Query query, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) { return RetryDecision.rethrow(); } public static void testRetryDecision() { assertEquals(RetryDecision.retry(ConsistencyLevel.ONE).getType(), RetryDecision.Type.RETRY); assertEquals(RetryDecision.retry(ConsistencyLevel.ONE).getRetryConsistencyLevel(), ConsistencyLevel.ONE); assertEquals(RetryDecision.rethrow().getType(), RetryDecision.Type.RETHROW); assertEquals(RetryDecision.ignore().getType(), RetryDecision.Type.IGNORE); assertEquals(RetryDecision.retry(ConsistencyLevel.ONE).toString(), "Retry at " + ConsistencyLevel.ONE); assertEquals(RetryDecision.rethrow().toString(), "Rethrow"); assertEquals(RetryDecision.ignore().toString(), "Ignore"); } } /** * Test RetryDecision get variables and defaults are correct. */ @Test(groups = "unit") public void RetryDecisionTest() throws Throwable { TestRetryPolicy.testRetryDecision(); } /* * Test the DefaultRetryPolicy. */ @Test(groups = "long") public void defaultRetryPolicy() throws Throwable { Cluster.Builder builder = Cluster.builder(); defaultPolicyTest(builder); } /* * Test the DefaultRetryPolicy with Logging enabled. */ @Test(groups = "long") public void defaultLoggingPolicy() throws Throwable { Cluster.Builder builder = Cluster.builder().withRetryPolicy(new LoggingRetryPolicy(DefaultRetryPolicy.INSTANCE)); defaultPolicyTest(builder); } /* * Test the FallthroughRetryPolicy. * Uses the same code that DefaultRetryPolicy uses. */ @Test(groups = "long") public void fallthroughRetryPolicy() throws Throwable { Cluster.Builder builder = Cluster.builder().withRetryPolicy(FallthroughRetryPolicy.INSTANCE); defaultPolicyTest(builder); } /* * Test the FallthroughRetryPolicy with Logging enabled. * Uses the same code that DefaultRetryPolicy uses. */ @Test(groups = "long") public void fallthroughLoggingPolicy() throws Throwable { Cluster.Builder builder = Cluster.builder().withRetryPolicy(new LoggingRetryPolicy(FallthroughRetryPolicy.INSTANCE)); defaultPolicyTest(builder); } public void defaultPolicyTest(Cluster.Builder builder) throws Throwable { CCMBridge.CCMCluster c = CCMBridge.buildCluster(2, builder); createSchema(c.session); // FIXME: Race condition where the nodes are not fully up yet and assertQueried reports slightly different numbers with fallthrough*Policy Thread.sleep(5000); try { init(c, 12); query(c, 12); assertQueried(CCMBridge.IP_PREFIX + "1", 6); assertQueried(CCMBridge.IP_PREFIX + "2", 6); resetCoordinators(); // Test reads boolean successfulQuery = false; boolean readTimeoutOnce = false; boolean unavailableOnce = false; boolean restartOnce = false; for (int i = 0; i < 100; ++i) { try { // Force a ReadTimeoutException to be performed once if (!readTimeoutOnce) { c.cassandraCluster.forceStop(2); } // Force an UnavailableException to be performed once if (readTimeoutOnce && !unavailableOnce) { waitForDownWithWait(CCMBridge.IP_PREFIX + "2", c.cluster, 5); } // Bring back node to ensure other errors are not thrown on restart if (unavailableOnce && !restartOnce) { c.cassandraCluster.start(2); restartOnce = true; } query(c, 12); if (restartOnce) successfulQuery = true; } catch (UnavailableException e) { assertEquals("Not enough replica available for query at consistency ONE (1 required but only 0 alive)", e.getMessage()); unavailableOnce = true; } catch (ReadTimeoutException e) { assertEquals("Cassandra timeout during read query at consistency ONE (1 responses were required but only 0 replica responded)", e.getMessage()); readTimeoutOnce = true; } } // Ensure the full cycle was completed assertTrue(successfulQuery, "Hit testing race condition. [Never completed successfully.] (Shouldn't be an issue.):\n"); assertTrue(readTimeoutOnce, "Hit testing race condition. [Never encountered a ReadTimeoutException.] (Shouldn't be an issue.):\n"); assertTrue(unavailableOnce, "Hit testing race condition. [Never encountered an UnavailableException.] (Shouldn't be an issue.):\n"); // A weak test to ensure that the nodes were contacted assertQueriedAtLeast(CCMBridge.IP_PREFIX + "1", 1); assertQueriedAtLeast(CCMBridge.IP_PREFIX + "2", 1); resetCoordinators(); // Test writes successfulQuery = false; boolean writeTimeoutOnce = false; unavailableOnce = false; restartOnce = false; for (int i = 0; i < 100; ++i) { try { // Force a WriteTimeoutException to be performed once if (!writeTimeoutOnce) { c.cassandraCluster.forceStop(2); } // Force an UnavailableException to be performed once if (writeTimeoutOnce && !unavailableOnce) { waitForDownWithWait(CCMBridge.IP_PREFIX + "2", c.cluster, 5); } // Bring back node to ensure other errors are not thrown on restart if (unavailableOnce && !restartOnce) { c.cassandraCluster.start(2); restartOnce = true; } init(c, 12); if (restartOnce) successfulQuery = true; } catch (UnavailableException e) { assertEquals("Not enough replica available for query at consistency ONE (1 required but only 0 alive)", e.getMessage()); unavailableOnce = true; } catch (WriteTimeoutException e) { assertEquals("Cassandra timeout during write query at consistency ONE (1 replica were required but only 0 acknowledged the write)", e.getMessage()); writeTimeoutOnce = true; } } // Ensure the full cycle was completed assertTrue(successfulQuery, "Hit testing race condition. [Never completed successfully.] (Shouldn't be an issue.):\n"); assertTrue(writeTimeoutOnce, "Hit testing race condition. [Never encountered a ReadTimeoutException.] (Shouldn't be an issue.):\n"); assertTrue(unavailableOnce, "Hit testing race condition. [Never encountered an UnavailableException.] (Shouldn't be an issue.):\n"); // TODO: Missing test to see if nodes were written to // Test batch writes successfulQuery = false; writeTimeoutOnce = false; unavailableOnce = false; restartOnce = false; for (int i = 0; i < 100; ++i) { try { // Force a WriteTimeoutException to be performed once if (!writeTimeoutOnce) { c.cassandraCluster.forceStop(2); } // Force an UnavailableException to be performed once if (writeTimeoutOnce && !unavailableOnce) { waitForDownWithWait(CCMBridge.IP_PREFIX + "2", c.cluster, 5); } // Bring back node to ensure other errors are not thrown on restart if (unavailableOnce && !restartOnce) { c.cassandraCluster.start(2); restartOnce = true; } init(c, 12, true); if (restartOnce) successfulQuery = true; } catch (UnavailableException e) { assertEquals("Not enough replica available for query at consistency ONE (1 required but only 0 alive)", e.getMessage()); unavailableOnce = true; } catch (WriteTimeoutException e) { assertEquals("Cassandra timeout during write query at consistency ONE (1 replica were required but only 0 acknowledged the write)", e.getMessage()); writeTimeoutOnce = true; } } // Ensure the full cycle was completed assertTrue(successfulQuery, "Hit testing race condition. [Never completed successfully.] (Shouldn't be an issue.):\n"); assertTrue(writeTimeoutOnce, "Hit testing race condition. [Never encountered a ReadTimeoutException.] (Shouldn't be an issue.):\n"); assertTrue(unavailableOnce, "Hit testing race condition. [Never encountered an UnavailableException.] (Shouldn't be an issue.):\n"); // TODO: Missing test to see if nodes were written to } catch (Throwable e) { c.errorOut(); throw e; } finally { resetCoordinators(); c.discard(); } } /** * Tests DowngradingConsistencyRetryPolicy */ @Test(groups = "long") public void downgradingConsistencyRetryPolicy() throws Throwable { Cluster.Builder builder = Cluster.builder().withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE); downgradingConsistencyRetryPolicy(builder); } /** * Tests DowngradingConsistencyRetryPolicy with LoggingRetryPolicy */ @Test(groups = "long") public void downgradingConsistencyLoggingPolicy() throws Throwable { Cluster.Builder builder = Cluster.builder().withRetryPolicy(new LoggingRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE)); downgradingConsistencyRetryPolicy(builder); } /** * Tests DowngradingConsistencyRetryPolicy */ public void downgradingConsistencyRetryPolicy(Cluster.Builder builder) throws Throwable { CCMBridge.CCMCluster c = CCMBridge.buildCluster(3, builder); createSchema(c.session, 3); // FIXME: Race condition where the nodes are not fully up yet and assertQueried reports slightly different numbers Thread.sleep(5000); try { init(c, 12, ConsistencyLevel.ALL); query(c, 12, ConsistencyLevel.ALL); assertQueried(CCMBridge.IP_PREFIX + "1", 4); assertQueried(CCMBridge.IP_PREFIX + "2", 4); assertQueried(CCMBridge.IP_PREFIX + "3", 4); resetCoordinators(); c.cassandraCluster.forceStop(2); waitForDownWithWait(CCMBridge.IP_PREFIX + "2", c.cluster, 10); query(c, 12, ConsistencyLevel.ALL); assertQueried(CCMBridge.IP_PREFIX + "1", 6); assertQueried(CCMBridge.IP_PREFIX + "2", 0); assertQueried(CCMBridge.IP_PREFIX + "3", 6); resetCoordinators(); c.cassandraCluster.forceStop(1); waitForDownWithWait(CCMBridge.IP_PREFIX + "1", c.cluster, 5); Thread.sleep(5000); try { query(c, 12, ConsistencyLevel.ALL); } catch (ReadTimeoutException e) { assertEquals("Cassandra timeout during read query at consistency TWO (2 responses were required but only 1 replica responded)", e.getMessage()); } query(c, 12, ConsistencyLevel.QUORUM); assertQueried(CCMBridge.IP_PREFIX + "1", 0); assertQueried(CCMBridge.IP_PREFIX + "2", 0); assertQueried(CCMBridge.IP_PREFIX + "3", 12); resetCoordinators(); query(c, 12, ConsistencyLevel.TWO); assertQueried(CCMBridge.IP_PREFIX + "1", 0); assertQueried(CCMBridge.IP_PREFIX + "2", 0); assertQueried(CCMBridge.IP_PREFIX + "3", 12); resetCoordinators(); query(c, 12, ConsistencyLevel.ONE); assertQueried(CCMBridge.IP_PREFIX + "1", 0); assertQueried(CCMBridge.IP_PREFIX + "2", 0); assertQueried(CCMBridge.IP_PREFIX + "3", 12); } catch (Throwable e) { c.errorOut(); throw e; } finally { resetCoordinators(); c.discard(); } } /* * Test the AlwaysIgnoreRetryPolicy with Logging enabled. */ @Test(groups = "long") public void alwaysIgnoreRetryPolicyTest() throws Throwable { Cluster.Builder builder = Cluster.builder().withRetryPolicy(new LoggingRetryPolicy(AlwaysIgnoreRetryPolicy.INSTANCE)); CCMBridge.CCMCluster c = CCMBridge.buildCluster(2, builder); createSchema(c.session); try { init(c, 12); query(c, 12); assertQueried(CCMBridge.IP_PREFIX + "1", 6); assertQueried(CCMBridge.IP_PREFIX + "2", 6); resetCoordinators(); // Test failed reads c.cassandraCluster.forceStop(2); for (int i = 0; i < 10; ++i) { query(c, 12); } // A weak test to ensure that the nodes were contacted assertQueried(CCMBridge.IP_PREFIX + "1", 120); assertQueried(CCMBridge.IP_PREFIX + "2", 0); resetCoordinators(); c.cassandraCluster.start(2); waitFor(CCMBridge.IP_PREFIX + "2", c.cluster); // Test successful reads for (int i = 0; i < 10; ++i) { query(c, 12); } // A weak test to ensure that the nodes were contacted assertQueriedAtLeast(CCMBridge.IP_PREFIX + "1", 1); assertQueriedAtLeast(CCMBridge.IP_PREFIX + "2", 1); resetCoordinators(); // Test writes for (int i = 0; i < 100; ++i) { init(c, 12); } // TODO: Missing test to see if nodes were written to // Test failed writes c.cassandraCluster.forceStop(2); for (int i = 0; i < 100; ++i) { init(c, 12); } // TODO: Missing test to see if nodes were written to } catch (Throwable e) { c.errorOut(); throw e; } finally { resetCoordinators(); c.discard(); } } private class QueryRunnable implements Runnable { private CCMBridge.CCMCluster c; private int i; public QueryRunnable(CCMBridge.CCMCluster c, int i) { this.c = c; this.i = i; } public void run(){ query(c, i); } } private class InitRunnable implements Runnable { private CCMBridge.CCMCluster c; private int i; public InitRunnable(CCMBridge.CCMCluster c, int i) { this.c = c; this.i = i; } public void run(){ try { init(c, i); fail(); } catch (DriverInternalError e) { } catch (NoHostAvailableException e) { } } } /* * Test the AlwaysIgnoreRetryPolicy with Logging enabled. */ @Test(groups = "long") public void alwaysRetryRetryPolicyTest() throws Throwable { Cluster.Builder builder = Cluster.builder().withRetryPolicy(new LoggingRetryPolicy(AlwaysRetryRetryPolicy.INSTANCE)); CCMBridge.CCMCluster c = CCMBridge.buildCluster(2, builder); createSchema(c.session); try { init(c, 12); query(c, 12); assertQueried(CCMBridge.IP_PREFIX + "1", 6); assertQueried(CCMBridge.IP_PREFIX + "2", 6); resetCoordinators(); // Test failed reads c.cassandraCluster.forceStop(2); Thread t1 = new Thread(new QueryRunnable(c, 12)); t1.start(); t1.join(10000); if (t1.isAlive()) t1.interrupt(); // A weak test to ensure that the nodes were contacted assertQueried(CCMBridge.IP_PREFIX + "1", 0); assertQueried(CCMBridge.IP_PREFIX + "2", 0); resetCoordinators(); c.cassandraCluster.start(2); waitFor(CCMBridge.IP_PREFIX + "2", c.cluster); // Test successful reads for (int i = 0; i < 10; ++i) { query(c, 12); } // A weak test to ensure that the nodes were contacted assertQueriedAtLeast(CCMBridge.IP_PREFIX + "1", 1); assertQueriedAtLeast(CCMBridge.IP_PREFIX + "2", 1); resetCoordinators(); // Test writes for (int i = 0; i < 100; ++i) { init(c, 12); } // TODO: Missing test to see if nodes were written to // Test failed writes c.cassandraCluster.forceStop(2); Thread t2 = new Thread(new InitRunnable(c, 12)); t2.start(); t2.join(10000); if (t2.isAlive()) t2.interrupt(); // TODO: Missing test to see if nodes were written to } catch (Throwable e) { c.errorOut(); throw e; } finally { resetCoordinators(); c.discard(); } } }
37.625
168
0.578533
5ad85365252c2c839e720cdce7609bf64b25403f
1,027
package com.github.anilople.javajvm.classfile.constantinfo; import com.github.anilople.javajvm.classfile.ClassFile; import com.github.anilople.javajvm.constants.ConstantPoolTags; import com.github.anilople.javajvm.utils.ByteUtils; public class ConstantDoubleInfo extends ConstantPoolInfo { public static final byte TAG = ConstantPoolTags.CONSTANT_Double; private int highBytes; private int lowBytes; public ConstantDoubleInfo(ClassFile classFile, ClassFile.ClassReader classReader) { super(classFile); this.highBytes = classReader.readU4(); this.lowBytes = classReader.readU4(); } @Override public byte getTag() { return TAG; } @Override public String toString() { return "ConstantDoubleInfo{" + "highBytes=" + highBytes + ", lowBytes=" + lowBytes + '}'; } public int getHighBytes() { return highBytes; } public int getLowBytes() { return lowBytes; } }
24.452381
87
0.660175
54b322938c41098a78dc861effe9130888c9356c
12,927
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2020.06.08 at 09:30:35 PM EDT // package com.tracelink.prodsec.plugin.veracode.sast.api.data.detailedreport; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * For each analysis (static or dynamic), there is a list of modules. If this * element is for static analysis, there is one module element per module * analyzed. If this element is for dynamic analysis, there is exactly one * module element. * <p> * Each static or dynamic analysis has these attribute values: * * rating: A letter grade. * * score: A numeric score. * * mitigated_rating: A letter grade, taking into account flaws that are mitigated. * * mitigated_score: A numeric score, taking into account flaws that are mitigated. * * submitted_date: The date that this analysis was submitted to Veracode. * * published_date: The date that this analysis was published by Veracode. * * next_scan_due: The date that the active policy for this application requests the next scan by. * * analysis_size_bytes: Optional (Static Analysis Only) size of modules scanned in bytes. * * engine_version: The version of the engine that this scan was run against. Static only. * * dynamic_scan_type: Optional (Dynamic Analysis Only) indicates whether the build is MP or DS. * * scan_exit_status_id: Optional (Dynamic Analysis Only) A numeric code for scan exit status. * * scan_exit_status_desc: Optional (Dynamic Analysis Only) The description corresponds to the * status id. * * version: Optional scan name. * * * <p>Java class for AnalysisType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="AnalysisType"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="modules"&gt; * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="module" type="{https://www.veracode.com/schema/reports/export/1.0}ModuleType" maxOccurs="unbounded" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * &lt;/element&gt; * &lt;/sequence&gt; * &lt;attribute name="rating" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /&gt; * &lt;attribute name="score" use="required" type="{http://www.w3.org/2001/XMLSchema}integer" /&gt; * &lt;attribute name="mitigated_rating" type="{http://www.w3.org/2001/XMLSchema}string" /&gt; * &lt;attribute name="mitigated_score" type="{http://www.w3.org/2001/XMLSchema}integer" /&gt; * &lt;attribute name="submitted_date" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /&gt; * &lt;attribute name="published_date" type="{http://www.w3.org/2001/XMLSchema}string" /&gt; * &lt;attribute name="next_scan_due" type="{http://www.w3.org/2001/XMLSchema}string" /&gt; * &lt;attribute name="analysis_size_bytes" type="{http://www.w3.org/2001/XMLSchema}long" /&gt; * &lt;attribute name="engine_version" type="{http://www.w3.org/2001/XMLSchema}string" /&gt; * &lt;attribute name="dynamic_scan_type" type="{https://www.veracode.com/schema/reports/export/1.0}DynamicScanType" /&gt; * &lt;attribute name="scan_exit_status_id" type="{http://www.w3.org/2001/XMLSchema}integer" /&gt; * &lt;attribute name="scan_exit_status_desc" type="{http://www.w3.org/2001/XMLSchema}string" /&gt; * &lt;attribute name="version" type="{http://www.w3.org/2001/XMLSchema}string" /&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "AnalysisType", namespace = "https://www.veracode.com/schema/reports/export/1.0", propOrder = {"modules"}) public class AnalysisType { @XmlElement(namespace = "https://www.veracode.com/schema/reports/export/1.0", required = true) private AnalysisType.Modules modules; @XmlAttribute(name = "rating", required = true) private String rating; @XmlAttribute(name = "score", required = true) private BigInteger score; @XmlAttribute(name = "mitigated_rating") private String mitigatedRating; @XmlAttribute(name = "mitigated_score") private BigInteger mitigatedScore; @XmlAttribute(name = "submitted_date", required = true) private String submittedDate; @XmlAttribute(name = "published_date") private String publishedDate; @XmlAttribute(name = "next_scan_due") private String nextScanDue; @XmlAttribute(name = "analysis_size_bytes") private Long analysisSizeBytes; @XmlAttribute(name = "engine_version") private String engineVersion; @XmlAttribute(name = "dynamic_scan_type") private DynamicScanType dynamicScanType; @XmlAttribute(name = "scan_exit_status_id") private BigInteger scanExitStatusId; @XmlAttribute(name = "scan_exit_status_desc") private String scanExitStatusDesc; @XmlAttribute(name = "version") private String version; /** * Gets the value of the modules property. * * @return possible object is * {@link AnalysisType.Modules } */ public AnalysisType.Modules getModules() { return modules; } /** * Sets the value of the modules property. * * @param value allowed object is * {@link AnalysisType.Modules } */ public void setModules(AnalysisType.Modules value) { this.modules = value; } /** * Gets the value of the rating property. * * @return possible object is * {@link String } */ public String getRating() { return rating; } /** * Sets the value of the rating property. * * @param value allowed object is * {@link String } */ public void setRating(String value) { this.rating = value; } /** * Gets the value of the score property. * * @return possible object is * {@link BigInteger } */ public BigInteger getScore() { return score; } /** * Sets the value of the score property. * * @param value allowed object is * {@link BigInteger } */ public void setScore(BigInteger value) { this.score = value; } /** * Gets the value of the mitigatedRating property. * * @return possible object is * {@link String } */ public String getMitigatedRating() { return mitigatedRating; } /** * Sets the value of the mitigatedRating property. * * @param value allowed object is * {@link String } */ public void setMitigatedRating(String value) { this.mitigatedRating = value; } /** * Gets the value of the mitigatedScore property. * * @return possible object is * {@link BigInteger } */ public BigInteger getMitigatedScore() { return mitigatedScore; } /** * Sets the value of the mitigatedScore property. * * @param value allowed object is * {@link BigInteger } */ public void setMitigatedScore(BigInteger value) { this.mitigatedScore = value; } /** * Gets the value of the submittedDate property. * * @return possible object is * {@link String } */ public String getSubmittedDate() { return submittedDate; } /** * Sets the value of the submittedDate property. * * @param value allowed object is * {@link String } */ public void setSubmittedDate(String value) { this.submittedDate = value; } /** * Gets the value of the publishedDate property. * * @return possible object is * {@link String } */ public String getPublishedDate() { return publishedDate; } /** * Sets the value of the publishedDate property. * * @param value allowed object is * {@link String } */ public void setPublishedDate(String value) { this.publishedDate = value; } /** * Gets the value of the nextScanDue property. * * @return possible object is * {@link String } */ public String getNextScanDue() { return nextScanDue; } /** * Sets the value of the nextScanDue property. * * @param value allowed object is * {@link String } */ public void setNextScanDue(String value) { this.nextScanDue = value; } /** * Gets the value of the analysisSizeBytes property. * * @return possible object is * {@link Long } */ public Long getAnalysisSizeBytes() { return analysisSizeBytes; } /** * Sets the value of the analysisSizeBytes property. * * @param value allowed object is * {@link Long } */ public void setAnalysisSizeBytes(Long value) { this.analysisSizeBytes = value; } /** * Gets the value of the engineVersion property. * * @return possible object is * {@link String } */ public String getEngineVersion() { return engineVersion; } /** * Sets the value of the engineVersion property. * * @param value allowed object is * {@link String } */ public void setEngineVersion(String value) { this.engineVersion = value; } /** * Gets the value of the dynamicScanType property. * * @return possible object is * {@link DynamicScanType } */ public DynamicScanType getDynamicScanType() { return dynamicScanType; } /** * Sets the value of the dynamicScanType property. * * @param value allowed object is * {@link DynamicScanType } */ public void setDynamicScanType(DynamicScanType value) { this.dynamicScanType = value; } /** * Gets the value of the scanExitStatusId property. * * @return possible object is * {@link BigInteger } */ public BigInteger getScanExitStatusId() { return scanExitStatusId; } /** * Sets the value of the scanExitStatusId property. * * @param value allowed object is * {@link BigInteger } */ public void setScanExitStatusId(BigInteger value) { this.scanExitStatusId = value; } /** * Gets the value of the scanExitStatusDesc property. * * @return possible object is * {@link String } */ public String getScanExitStatusDesc() { return scanExitStatusDesc; } /** * Sets the value of the scanExitStatusDesc property. * * @param value allowed object is * {@link String } */ public void setScanExitStatusDesc(String value) { this.scanExitStatusDesc = value; } /** * Gets the value of the version property. * * @return possible object is * {@link String } */ public String getVersion() { return version; } /** * Sets the value of the version property. * * @param value allowed object is * {@link String } */ public void setVersion(String value) { this.version = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="module" type="{https://www.veracode.com/schema/reports/export/1.0}ModuleType" maxOccurs="unbounded" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"module"}) public static class Modules { @XmlElement(namespace = "https://www.veracode.com/schema/reports/export/1.0") private List<ModuleType> module; /** * Gets the value of the module property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the module property. * * <p> * For example, to add a new item, do as follows: * <pre> * getModule().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ModuleType } * * @return value of the module property, or an empty list if the module property is null */ public List<ModuleType> getModule() { if (module == null) { module = new ArrayList<>(); } return this.module; } } }
28.536424
157
0.67154
984277dd0ad55cce2d520dff679112f2db8d0851
1,736
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.scala.ast; import java.io.File; import java.io.StringReader; import net.sourceforge.pmd.PMD; import net.sourceforge.pmd.PMDException; import net.sourceforge.pmd.Report; import net.sourceforge.pmd.Rule; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.RuleSet; import net.sourceforge.pmd.RuleSets; import net.sourceforge.pmd.lang.ast.test.BaseParsingHelper; import net.sourceforge.pmd.lang.scala.ScalaLanguageModule; public final class ScalaParsingHelper extends BaseParsingHelper<ScalaParsingHelper, ASTSource> { public static final ScalaParsingHelper DEFAULT = new ScalaParsingHelper(Params.getDefaultProcess()); private ScalaParsingHelper(Params params) { super(ScalaLanguageModule.NAME, ASTSource.class, params); } @Override protected ScalaParsingHelper clone(Params params) { return new ScalaParsingHelper(params); } public Report getReportForTestString(Rule rule, String testSourceCode) { PMD p = new PMD(); RuleContext ctx = new RuleContext(); Report report = new Report(); ctx.setReport(report); ctx.setSourceCodeFile(new File("test.scala")); RuleSet rules = RuleSet.forSingleRule(rule); try { p.getSourceCodeProcessor().processSourceCode(new StringReader(testSourceCode), new RuleSets(rules), ctx); } catch (PMDException e) { throw new AssertionError(e); } return report; } public Report getReportForResource(Rule rule, String resourcePath) { return getReportForTestString(rule, readResource(resourcePath)); } }
32.754717
117
0.726382
6a2be2b7f3c4097e37bbe245234704e38d9a4e25
1,885
/* * Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved. */ package org.training.core.actions.quote; import static com.google.common.collect.Sets.newHashSet; import java.util.Set; import org.springframework.beans.factory.annotation.Required; import de.hybris.platform.commerceservices.enums.QuoteNotificationType; import de.hybris.platform.commerceservices.model.process.QuoteProcessModel; import de.hybris.platform.core.model.order.QuoteModel; import de.hybris.platform.order.QuoteService; import de.hybris.platform.processengine.action.AbstractProceduralAction; /** * A generic quote process action used to mark a specific notification type {set in quoteNotificationType} as generated * for the quote. */ public class MarkQuoteNotificationAsSentAction extends AbstractProceduralAction<QuoteProcessModel> { private QuoteService quoteService; private QuoteNotificationType quoteNotificationType; @Override public void executeAction(final QuoteProcessModel quoteProcessModel) throws Exception { final QuoteModel quoteModel = getQuoteService().getCurrentQuoteForCode(quoteProcessModel.getQuoteCode()); final Set<QuoteNotificationType> generatedQuoteNotifications = newHashSet(quoteModel.getGeneratedNotifications()); generatedQuoteNotifications.add(getQuoteNotificationType()); quoteModel.setGeneratedNotifications(generatedQuoteNotifications); getModelService().save(quoteModel); } protected QuoteService getQuoteService() { return quoteService; } @Required public void setQuoteService(final QuoteService quoteService) { this.quoteService = quoteService; } protected QuoteNotificationType getQuoteNotificationType() { return quoteNotificationType; } @Required public void setQuoteNotificationType(final QuoteNotificationType quoteNotificationType) { this.quoteNotificationType = quoteNotificationType; } }
30.403226
119
0.825464
9c27a9b02b827cfe3234f62a80411e8a9e2d4311
204
package oiasso.system.examples.data.facades; import java.util.List; import oiasso.system.examples.data.dtos.UsuarioDTO; public interface UsuarioFacade { public List<UsuarioDTO> findAllWithRoles(); }
18.545455
51
0.803922
0e9da83eea93eebb33334360f06f175c3b6cdd63
315
import section_02.Holder3; import typeinfo.pets.Mouse; import typeinfo.pets.Pet; /** * @Author ZhangGJ * @Date 2019/07/22 */ public class E01_PetsHolder { public static void main(String[] args) { Holder3<Pet> h3 = new Holder3<Pet>(new Mouse("Mickey")); System.out.println(h3.get()); } }
21
64
0.657143
68d243a2dc6b997e25e8070ee8c820f12f5730f7
7,127
package com.xyh.easywashcar.activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentTransaction; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.widget.Button; import android.widget.ListView; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.SimpleAdapter; import com.baidu.mapapi.SDKInitializer; import com.xyh.easywashcar.R; import com.xyh.easywashcar.base.MyAppcation; import com.xyh.easywashcar.fragment.HomePageFragment; import com.xyh.easywashcar.fragment.InformationFragment; import com.xyh.easywashcar.fragment.MarketFragment; import com.xyh.easywashcar.fragment.MineFragment; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; //记得继承FragmentActivity public class MainActivity extends FragmentActivity implements View.OnClickListener { private static final String TAG = "MainActivity"; @Bind(R.id.radiogroup_id) RadioGroup radioGroup; @Bind(R.id.market_id) RadioButton market; @Bind(R.id.resource_id) RadioButton my_order; @Bind(R.id.home_id) RadioButton home; @Bind(R.id.mine_id) RadioButton contact; @Bind(R.id.left_login_id) Button login; //绑定左拉菜单 @Bind(R.id.left_menu_listView_id) ListView left_menu_listView; private long exitTime; private List<Fragment> fragments = new ArrayList<>(); //左拉菜单listview适配器 private SimpleAdapter leftMenuAdapter; private int[] imgs; private String[] imgNames; private ArrayList<HashMap<String, Object>> leftMenuDatas = new ArrayList<>(); private String[] from; private int[] to; private android.support.v4.app.FragmentTransaction mFragmentTransaction; private android.support.v4.app.FragmentManager mFragmentManager; private HomePageFragment homePageFragment; private MarketFragment marketFragment; private InformationFragment messageFragment; private MineFragment mineFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SDKInitializer.initialize(MyAppcation.getContext()); setContentView(R.layout.activity_main); ButterKnife.bind(this); initData(); initLeftMenuData(); //按钮选中时候,界面也被滑动 radioGroup.setOnCheckedChangeListener(new CheckedChangeListener()); leftMenuAdapter = new SimpleAdapter(this, leftMenuDatas, R.layout.item_listview, from, to); left_menu_listView.setAdapter(leftMenuAdapter); setOnClickListener(); } private void setOnClickListener() { login.setOnClickListener(this); } //初始化左拉菜单数据 private void initLeftMenuData() { imgs = new int[]{R.mipmap.activity, R.mipmap.collect}; imgNames = new String[]{"活动", "收藏"}; from = new String[]{"img", "imgName"}; to = new int[]{R.id.left_menu_img_id, R.id.left_menu_imgName_id}; for (int i = 0; i < imgs.length; i++) { HashMap<String, Object> hashmap = new HashMap<>(); hashmap.put("img", imgs[i]); hashmap.put("imgName", imgNames[i]); leftMenuDatas.add(hashmap); } } //设置结束页面动画 @Override public void finish() { super.finish(); overridePendingTransition(R.anim.anim_none, R.anim.anim_main_out); } //两秒内按两次及以上返回就退出 @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) { long secondExitTime = System.currentTimeMillis(); if ((secondExitTime - exitTime) > 2000) { // Snackbar sb = Snackbar.make(radioGroup, "再按一次退出", Snackbar.LENGTH_SHORT); // sb.getView().setBackgroundColor(getResources().getColor(android.R.color.holo_blue_dark)); // sb.show(); MyAppcation.myToast("再按一次退出程序"); exitTime = secondExitTime; } else { finish(); } //不返回true, 按一次就退出.因为它会执行下面的return super.onKeyDown(keyCode, event); return true; } return super.onKeyDown(keyCode, event); } @Override public void onClick(View v) { Intent intent = new Intent(this, LoginActivity.class); switch (v.getId()) { case R.id.left_login_id: startActivity(intent); break; } } //按钮点击时候绑定滑动 class CheckedChangeListener implements RadioGroup.OnCheckedChangeListener { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { FragmentTransaction mFragmentTransaction = mFragmentManager.beginTransaction(); switch (checkedId) { case R.id.home_id: hideAllFragment(mFragmentTransaction); mFragmentTransaction.show(homePageFragment); break; case R.id.market_id: hideAllFragment(mFragmentTransaction); mFragmentTransaction.show(marketFragment); Log.i(TAG, "onCheckedChanged: 门店按钮执行了吗"); break; case R.id.resource_id: hideAllFragment(mFragmentTransaction); mFragmentTransaction.show(messageFragment); break; case R.id.mine_id: hideAllFragment(mFragmentTransaction); mFragmentTransaction.show(mineFragment); break; default: break; } mFragmentTransaction.commit(); } } //初始化四个碎片数据 private void initData() { homePageFragment = new HomePageFragment(MainActivity.this); marketFragment = new MarketFragment(MainActivity.this); mineFragment = new MineFragment(MainActivity.this); messageFragment = new InformationFragment(MainActivity.this); mFragmentManager = getSupportFragmentManager(); mFragmentTransaction = mFragmentManager.beginTransaction(); mFragmentTransaction.add(R.id.main_fragment_id, homePageFragment); mFragmentTransaction.add(R.id.main_fragment_id, marketFragment); mFragmentTransaction.add(R.id.main_fragment_id, messageFragment); mFragmentTransaction.add(R.id.main_fragment_id, mineFragment); mFragmentTransaction.hide(marketFragment); mFragmentTransaction.hide(messageFragment); mFragmentTransaction.hide(mineFragment); mFragmentTransaction.commit(); } private void hideAllFragment(FragmentTransaction mFragmentTransaction) { mFragmentTransaction.hide(homePageFragment); mFragmentTransaction.hide(marketFragment); mFragmentTransaction.hide(messageFragment); mFragmentTransaction.hide(mineFragment); } }
35.108374
107
0.665357
53d544efdc1703cebddaa91f4bb1c93be0f5bd14
3,560
/* * jGnash, a personal finance application * Copyright (C) 2001-2018 Craig Cavanaugh * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jgnash.util; import org.junit.jupiter.api.Test; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import static org.junit.jupiter.api.Assertions.*; /** * File utilities test. * * @author Craig Cavanaugh */ class FileUtilsTest { private static void checkTestData(final String testdata, final String absolutepath) throws IOException { final char[] buffer = new char[testdata.length()]; try (final Reader reader = Files.newBufferedReader(Paths.get(absolutepath))) { final int read = reader.read(buffer); assertEquals(testdata.length(), read); } assertEquals(testdata, new String(buffer)); } private static void writeTestData(final String testdata, final Path tempfile) throws IOException { try (final Writer os = Files.newBufferedWriter(tempfile)) { os.write(testdata); } } @Test void testFileLock() throws IOException { final Path tempFile = Files.createTempFile("temp", null); try (final Writer writer = Files.newBufferedWriter(tempFile)) { writer.write("test"); } catch (Exception e) { fail(); } assertTrue(Files.isWritable(tempFile)); assertTrue(Files.isReadable(tempFile)); final FileLocker filelocker = new FileLocker(); filelocker.acquireLock(tempFile); assertTrue(FileUtils.isFileLocked(tempFile.toString())); filelocker.release(); assertFalse(FileUtils.isFileLocked(tempFile.toString())); assertTrue(Files.deleteIfExists(tempFile)); } @Test void fileExtensionStripTest() { assertTrue(FileUtils.fileHasExtension("text.txt")); assertTrue(FileUtils.fileHasExtension("text.txt.txt")); assertFalse(FileUtils.fileHasExtension("test")); } @Test void strip() { assertEquals("database", FileUtils.stripFileExtension("database.h2.db")); assertEquals("database", FileUtils.stripFileExtension("database.db")); } @Test void fileExtensionText() { assertEquals(FileUtils.getFileExtension("test.txt"), "txt"); } @Test void fileCopyToSelf() throws IOException { Path tempFile = Files.createTempFile("jgnash-test", ".jdb"); String absolutePath = tempFile.toString(); String testData = "42fd;lgkjsgj;gfj;slfkgj;"; // Write the data to a file writeTestData(testData, tempFile); checkTestData(testData, absolutePath); // Copy the file to itself: the file should not be emptied :) assertFalse(FileUtils.copyFile(Paths.get(absolutePath), Paths.get(absolutePath))); Files.delete(tempFile); } }
30.956522
108
0.676124
20be4526396a770b0def22b6079ae87a42c6b1e2
2,625
package org.springframework.scripting.config; import java.lang.reflect.Field; import org.junit.Test; import org.springframework.aop.framework.Advised; import org.springframework.aop.support.AopUtils; import org.springframework.aop.target.dynamic.AbstractRefreshableTargetSource; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import static org.junit.Assert.*; /** * @author Mark Fisher * @author Dave Syer */ @SuppressWarnings("resource") public class ScriptingDefaultsTests { private static final String CONFIG = "org/springframework/scripting/config/scriptingDefaultsTests.xml"; private static final String PROXY_CONFIG = "org/springframework/scripting/config/scriptingDefaultsProxyTargetClassTests.xml"; @Test public void defaultRefreshCheckDelay() throws Exception { ApplicationContext context = new ClassPathXmlApplicationContext(CONFIG); Advised advised = (Advised) context.getBean("testBean"); AbstractRefreshableTargetSource targetSource = ((AbstractRefreshableTargetSource) advised.getTargetSource()); Field field = AbstractRefreshableTargetSource.class.getDeclaredField("refreshCheckDelay"); field.setAccessible(true); long delay = ((Long) field.get(targetSource)).longValue(); assertEquals(5000L, delay); } @Test public void defaultInitMethod() { ApplicationContext context = new ClassPathXmlApplicationContext(CONFIG); ITestBean testBean = (ITestBean) context.getBean("testBean"); assertTrue(testBean.isInitialized()); } @Test public void nameAsAlias() { ApplicationContext context = new ClassPathXmlApplicationContext(CONFIG); ITestBean testBean = (ITestBean) context.getBean("/url"); assertTrue(testBean.isInitialized()); } @Test public void defaultDestroyMethod() { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(CONFIG); ITestBean testBean = (ITestBean) context.getBean("nonRefreshableTestBean"); assertFalse(testBean.isDestroyed()); context.close(); assertTrue(testBean.isDestroyed()); } @Test public void defaultAutowire() { ApplicationContext context = new ClassPathXmlApplicationContext(CONFIG); ITestBean testBean = (ITestBean) context.getBean("testBean"); ITestBean otherBean = (ITestBean) context.getBean("otherBean"); assertEquals(otherBean, testBean.getOtherBean()); } @Test public void defaultProxyTargetClass() { ApplicationContext context = new ClassPathXmlApplicationContext(PROXY_CONFIG); Object testBean = context.getBean("testBean"); assertTrue(AopUtils.isCglibProxy(testBean)); } }
32.012195
92
0.793143
b1c63c8fd9e1328da03936f93bcbdc5369d8d78e
607
package com.nostalgia.menu.settings; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; /** * Created by alex on 12/25/15. */ public class AppSettingsFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = super.onCreateView(inflater, container, savedInstanceState); View myView = inflater.inflate(R.layout.app_settings_frag, container, false); return myView; } }
25.291667
103
0.749588
c53ee92971d8ed80571d7fe2d1d50276b5ee0afe
6,780
package dao.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import dao.OrganizationDAOI; import entity.Dept; import entity.DeptDiv; import entity.GovofcDiv; import entity.HgdeptDiv; import entity.Organization; import jdbc.ConnectionProvider; public class OrganizationDAO implements OrganizationDAOI { private static final String ORGANIZATION_QUERY = "select dept_div_nm,\n" + "DD.dept_div_cd,\n" + "govofc_div_nm,\n" + "GD.govofc_div_cd,\n" + "hgdept_div_nm,\n" + "HD.hgdept_div_cd,\n" + "dept_nm,\n" + "D.dept_cd_nm\n" + "from \"OrganizationChart\"\n" + "join \"DeptDiv\" DD on DD.dept_div_cd = \"OrganizationChart\".dept_div_cd\n" + "join \"GovofcDiv\" GD on GD.govofc_div_cd = \"OrganizationChart\".govofc_div_cd\n" + "join \"HgdeptDiv\" HD on HD.hgdept_div_cd = \"OrganizationChart\".hgdept_div_cd\n" + "join \"Dept\" D on D.dept_cd_nm = \"OrganizationChart\".dept_cd_nm\n" + "where dept_div_nm like ?\n" + " and govofc_div_nm like ?\n" + " and hgdept_div_nm like ?\n" + " and dept_nm like ?"; private OrganizationDAO() { } public static OrganizationDAO getInstance() { return InstHolder.INSTANCE; } private static class InstHolder { public static final OrganizationDAO INSTANCE = new OrganizationDAO(); } @Override public List<Organization> getAllOrganization(Class<? extends Organization> organizationClass) { if (organizationClass.equals(DeptDiv.class)) { // DeptDiv 부서구분 전체 가져오기 List<Organization> deptDivList = new ArrayList<>(); try (Connection conn = ConnectionProvider.getJDBCConnection(); PreparedStatement pstmt = conn.prepareStatement("select * from \"DeptDiv\""); ResultSet rs = pstmt.executeQuery();) { while (rs.next()) { deptDivList.add(new DeptDiv(rs.getString("dept_div_cd"), rs.getString("dept_div_nm"))); } return deptDivList; } catch (SQLException e) { e.printStackTrace(); } } else if (organizationClass.equals(GovofcDiv.class)) { // GovofcDiv 관서 전체 가져오기 List<Organization> govofcDivList = new ArrayList<>(); try (Connection conn = ConnectionProvider.getJDBCConnection(); PreparedStatement pstmt = conn.prepareStatement("select * from \"GovofcDiv\""); ResultSet rs = pstmt.executeQuery();) { while (rs.next()) { govofcDivList.add(new GovofcDiv(rs.getString("govofc_div_cd"), rs.getString("govofc_div_nm"))); } return govofcDivList; } catch (SQLException e) { e.printStackTrace(); } } else if (organizationClass.equals(HgdeptDiv.class)) { // HgdeptDiv 실국 전체 가져오기 List<Organization> hgdeptDivList = new ArrayList<>(); try (Connection conn = ConnectionProvider.getJDBCConnection(); PreparedStatement pstmt = conn.prepareStatement("select * from \"HgdeptDiv\""); ResultSet rs = pstmt.executeQuery();) { while (rs.next()) { hgdeptDivList.add(new HgdeptDiv(rs.getString("hgdept_div_cd"), rs.getString("hgdept_div_nm"))); } return hgdeptDivList; } catch (SQLException e) { e.printStackTrace(); } } else if (organizationClass.equals(Dept.class)) { // Dept 부서 전체 가져오기 List<Organization> deptList = new ArrayList<>(); try (Connection conn = ConnectionProvider.getJDBCConnection(); PreparedStatement pstmt = conn.prepareStatement("select * from \"Dept\""); ResultSet rs = pstmt.executeQuery();) { while (rs.next()) { deptList.add(new Dept(rs.getString("dept_cd_nm"), rs.getString("dept_nm"))); } return deptList; } catch (SQLException e) { e.printStackTrace(); } } return new ArrayList<>(); } @Override public List<Organization> getChildrenOf(Organization deptDiv, Organization govofcDiv, Organization hgdeptDiv, Organization dept) { String deptDivName = deptDiv == null ? "%" : deptDiv.getOrganizationName(); String govofcDivName = govofcDiv == null ? "%" : govofcDiv.getOrganizationName(); String hgdeptDivName = hgdeptDiv == null ? "%" : hgdeptDiv.getOrganizationName(); String deptName = dept == null ? "%" : dept.getOrganizationName(); List<Organization> children = new ArrayList<>(); try (Connection conn = ConnectionProvider.getJDBCConnection(); PreparedStatement organizationPstmt = conn.prepareStatement(ORGANIZATION_QUERY);) { organizationPstmt.setString(1, deptDivName); organizationPstmt.setString(2, govofcDivName); organizationPstmt.setString(3, hgdeptDivName); organizationPstmt.setString(4, deptName); ResultSet rs = organizationPstmt.executeQuery(); while (rs.next()) { Organization element = null; if (deptDiv == null) { throw new RuntimeException("Invalid Parameter"); } else if (govofcDiv == null) { element = new GovofcDiv(rs.getString("govofc_div_cd"), rs.getString("govofc_div_nm")); if (children.contains(element)) { continue; } } else if (hgdeptDiv == null) { element = new HgdeptDiv(rs.getString("hgdept_div_cd"), rs.getString("hgdept_div_nm")); if (children.contains(element)) { continue; } } else if (dept == null) { element = new Dept(rs.getString("dept_cd_nm"), rs.getString("dept_nm")); if (children.contains(element)) { continue; } } else { throw new RuntimeException("Invalid Parameter"); } children.add(element); } rs.close(); return children; } catch (SQLException e) { e.printStackTrace(); } return new ArrayList<>(); } }
42.111801
119
0.566372
86a5b7734f210203d06532b40fe4e1ad71807f9b
2,834
package mage.cards.n; import java.util.UUID; import mage.MageInt; import mage.Mana; import mage.abilities.common.SimpleActivatedAbility; import mage.abilities.costs.mana.ManaCostsImpl; import mage.abilities.effects.mana.BasicManaEffect; import mage.abilities.effects.common.continuous.BoostSourceEffect; import mage.abilities.mana.TriggeredManaAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Duration; import mage.constants.SubType; import mage.constants.Zone; import mage.filter.common.FilterControlledLandPermanent; import mage.game.Game; import mage.game.events.GameEvent; import mage.game.events.GameEvent.EventType; import mage.game.permanent.Permanent; /** * * @author jeffwadsworth */ public final class NirkanaRevenant extends CardImpl { public NirkanaRevenant(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{4}{B}{B}"); this.subtype.add(SubType.VAMPIRE); this.subtype.add(SubType.SHADE); this.power = new MageInt(4); this.toughness = new MageInt(4); // Whenever you tap a Swamp for mana, add {B}. this.addAbility(new NirkanaRevenantTriggeredAbility()); // {B}: Nirkana Revenant gets +1/+1 until end of turn. this.addAbility(new SimpleActivatedAbility(Zone.BATTLEFIELD, new BoostSourceEffect(1, 1, Duration.EndOfTurn), new ManaCostsImpl("{B}"))); } public NirkanaRevenant(final NirkanaRevenant card) { super(card); } @Override public NirkanaRevenant copy() { return new NirkanaRevenant(this); } } class NirkanaRevenantTriggeredAbility extends TriggeredManaAbility { private static final FilterControlledLandPermanent filter = new FilterControlledLandPermanent("Swamp"); static { filter.add(SubType.SWAMP.getPredicate()); } public NirkanaRevenantTriggeredAbility() { super(Zone.BATTLEFIELD, new BasicManaEffect(Mana.BlackMana(1)), false); this.usesStack = false; } public NirkanaRevenantTriggeredAbility(NirkanaRevenantTriggeredAbility ability) { super(ability); } @Override public boolean checkEventType(GameEvent event, Game game) { return event.getType() == EventType.TAPPED_FOR_MANA; } @Override public boolean checkTrigger(GameEvent event, Game game) { Permanent land = game.getPermanent(event.getTargetId()); return land != null && filter.match(land, this.getSourceId(), this.getControllerId(), game); } @Override public NirkanaRevenantTriggeredAbility copy() { return new NirkanaRevenantTriggeredAbility(this); } @Override public String getRule() { return "Whenever you tap a Swamp for mana, add {B}."; } }
30.804348
145
0.718772
05e7c268dc5e8d48ea2524afbd2ffb2c4f64fc02
2,104
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.intentions.closure; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; import org.jetbrains.plugins.groovy.intentions.base.Intention; import org.jetbrains.plugins.groovy.intentions.base.PsiElementPredicate; import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList; import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression; import org.jetbrains.plugins.groovy.lang.psi.impl.PsiImplUtil; public class MakeClosureCallExplicitIntention extends Intention { @Override @NotNull public PsiElementPredicate getElementPredicate() { return ImplicitClosureCallPredicate.INSTANCE; } @Override public void processIntention(@NotNull PsiElement element, @NotNull Project project, Editor editor) throws IncorrectOperationException { final GrMethodCallExpression expression = (GrMethodCallExpression) element; final GrExpression invokedExpression = expression.getInvokedExpression(); final GrArgumentList argList = expression.getArgumentList(); final GrClosableBlock[] closureArgs = expression.getClosureArguments(); final StringBuilder newExpression = new StringBuilder(); newExpression.append(invokedExpression.getText()); newExpression.append(".call"); newExpression.append(argList.getText()); for (GrClosableBlock closureArg : closureArgs) { newExpression.append(closureArg.getText()); } PsiImplUtil.replaceExpression(newExpression.toString(), expression); } }
47.818182
140
0.77424
f8279a54a4b897cb72cf25d9eebf0a0c0cc60ef3
2,727
package com.stay4it.im.home; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import com.stay4it.im.BaseActivity; import com.stay4it.im.IMApplication; import com.stay4it.im.R; import com.stay4it.im.untils.Constants; import com.stay4it.im.untils.PrefsAccessor; import com.stay4it.im.untils.TextUtil; /** * @author Stay * @version create time:Apr 8, 2015 2:47:04 PM */ public class WelcomeActivity extends BaseActivity implements OnClickListener { private Button select_login_btn; private Button select_register_btn; private View select_lv; private static final int ACTION_LOGIN = 0; private static final int ACTION_HOME = 1; private Handler mHandler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); Intent intent = new Intent(); switch (msg.what) { case ACTION_LOGIN: intent.setClass(WelcomeActivity.this, LoginActivity.class); break; case ACTION_HOME: intent.setClass(WelcomeActivity.this, HomeActivity.class); break; default: break; } startActivity(intent); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { IMApplication.mAppState = 0; super.onCreate(savedInstanceState); } @Override protected void setContentView() { setContentView(R.layout.activity_welcome); } @Override protected void initializeView() { select_lv = findViewById(R.id.select_lv); select_login_btn = (Button)findViewById(R.id.select_login_btn); select_register_btn = (Button)findViewById(R.id.select_register_btn); select_login_btn.setOnClickListener(this); select_register_btn.setOnClickListener(this); } @Override protected void initializeData() { String account = PrefsAccessor.getInstance(this).getString(Constants.KEY_ACCOUNT); String pwd = PrefsAccessor.getInstance(this).getString(Constants.KEY_PASSWORD); if (TextUtil.isValidate(account,pwd)) { IMApplication.initializeProfile(); if (IMApplication.getProfile() == null) { mHandler.sendEmptyMessageDelayed(ACTION_LOGIN, 2000); }else { IMApplication.mAppState = 1; mHandler.sendEmptyMessageDelayed(ACTION_HOME, 2000); } }else if(TextUtil.isValidate(account)){ mHandler.sendEmptyMessageDelayed(ACTION_LOGIN, 2000); }else { select_lv.setVisibility(View.VISIBLE); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.select_login_btn: startActivity(new Intent(this, LoginActivity.class)); finish(); break; case R.id.select_register_btn: break; default: break; } } }
25.971429
84
0.748808
e1ecddc7b2887eeda82095daa673b5ee9c32553a
825
package org.freefinder.registration; /** * Created by rade on 13.12.17.. */ public interface RegistrationContract { // Interaction View <-> Presenter interfaces interface View { void showProgress(boolean isLoading); void successfulRegistrationRedirection(); void showRegistrationError(); } interface UserActionsListener { void submitRegistration(String email, String password, String repeatedPassword); } // Interaction Presenter <-> Model interfaces interface Model { void register(String email, String password, String repeatedPassword); } interface RegistrationStatus { void onSuccess(); void onFailure(); } }
24.264706
57
0.590303
00dae78380a2260529a4078ac3d871f709df0966
7,629
/* * Copyright 2018 iserge. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.cleanlogic.cesiumjs4gwt.showcase.examples; import com.google.gwt.core.client.GWT; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.user.client.ui.AbsolutePanel; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.FlexTable; import com.google.gwt.user.client.ui.HTML; import org.cesiumjs.cs.Cesium; import org.cesiumjs.cs.core.Cartesian3; import org.cesiumjs.cs.datasources.graphics.ModelGraphics; import org.cesiumjs.cs.datasources.graphics.options.ModelGraphicsOptions; import org.cesiumjs.cs.datasources.options.EntityOptions; import org.cesiumjs.cs.datasources.properties.ConstantPositionProperty; import org.cesiumjs.cs.datasources.properties.ConstantProperty; import org.cesiumjs.cs.scene.PostProcessStageComposite; import org.cesiumjs.cs.scene.PostProcessStageLibrary; import org.cesiumjs.cs.widgets.ViewerPanel; import org.cleanlogic.cesiumjs4gwt.showcase.basic.AbstractExample; import org.cleanlogic.cesiumjs4gwt.showcase.components.store.ShowcaseExampleStore; import org.cleanlogic.cesiumjs4gwt.showcase.examples.slider.Slider; import org.cleanlogic.cesiumjs4gwt.showcase.examples.slider.SliderEvent; import org.cleanlogic.cesiumjs4gwt.showcase.examples.slider.SliderListener; import javax.inject.Inject; /** * @author Serge Silaev aka iSergio */ public class DepthOfField extends AbstractExample { private final int numberOfBalloons = 13; private final double lonIncrement = 0.00025; private final double initialLon = -122.99875; private final double lat = 44.0503706; private final double height = 100.0; private ViewerPanel csVPanel; private CheckBox depthOfFieldCBox; private Slider focalDistanceSlider; private Slider deltaSlider; private Slider sigmaSlider; private Slider stepSizeSlider; private PostProcessStageComposite depthOfField; @Inject public DepthOfField(ShowcaseExampleStore store) { super("Depth of Field", "Depth of field", new String[]{"Depth of field", "Post processing"}, store); } @Override public void buildPanel() { csVPanel = new ViewerPanel(); for (int i = 0; i < numberOfBalloons; i++) { double lon = initialLon + i * lonIncrement; createModel(lon, lat, height); } depthOfFieldCBox = new CheckBox(); depthOfFieldCBox.setValue(true); depthOfFieldCBox.addValueChangeHandler(new MValueChangeHandler()); focalDistanceSlider = new Slider("focalDistanceSlider", 0, 500, 87); focalDistanceSlider.setStep(1); focalDistanceSlider.setWidth("150px"); focalDistanceSlider.addListener(new MSliderListener()); deltaSlider = new Slider("deltaSlider", 10, 200, 100); deltaSlider.setStep(1); deltaSlider.setWidth("150px"); deltaSlider.addListener(new MSliderListener()); sigmaSlider = new Slider("sigmaSlider", 50, 500, 378); sigmaSlider.setStep(1); sigmaSlider.setWidth("150px"); sigmaSlider.addListener(new MSliderListener()); stepSizeSlider = new Slider("stepSizeSlider", 0, 700, 246); stepSizeSlider.setStep(1); stepSizeSlider.setWidth("150px"); stepSizeSlider.addListener(new MSliderListener()); FlexTable flexTable = new FlexTable(); flexTable.setHTML(1, 0, "<font color=\"white\">Depth Of Field</font>"); flexTable.setWidget(1, 1, depthOfFieldCBox); flexTable.setHTML(2, 0, "<font color=\"white\">Focal Distance</font>"); flexTable.setWidget(2, 1, focalDistanceSlider); flexTable.setHTML(3, 0, "<font color=\"white\">Delta</font>"); flexTable.setWidget(3, 1, deltaSlider); flexTable.setHTML(4, 0, "<font color=\"white\">Sigma</font>"); flexTable.setWidget(4, 1, sigmaSlider); flexTable.setHTML(5, 0, "<font color=\"white\">Step Size</font>"); flexTable.setWidget(5, 1, stepSizeSlider); AbsolutePanel aPanel = new AbsolutePanel(); aPanel.add(csVPanel); aPanel.add(flexTable, 20, 20); contentPanel.add(new HTML("<p>Post processing effects.</p>")); contentPanel.add(aPanel); initWidget(contentPanel); depthOfField = csVPanel.getViewer().scene().postProcessStages .add(PostProcessStageLibrary.createDepthOfFieldStage()); if (!PostProcessStageLibrary.isDepthOfFieldSupported(csVPanel.getViewer().scene())) { Cesium.log("This browser does not support the depth of field post process."); } updatePostProcess(); Cartesian3 target = Cartesian3.fromDegrees(initialLon + lonIncrement, lat, height + 7.5); Cartesian3 offset = new Cartesian3(-37.048378684557974, -24.852967044804245, 4.352023653686047); csVPanel.getViewer().scene().camera().lookAt(target, offset); } private void createModel(double lon, double lat, double height) { Cartesian3 position = Cartesian3.fromDegrees(lon, lat, height); ModelGraphicsOptions modelGraphicsOptions = new ModelGraphicsOptions(); modelGraphicsOptions.uri = new ConstantProperty<>( GWT.getModuleBaseURL() + "SampleData/models/CesiumBalloon/CesiumBalloon.glb"); EntityOptions options = new EntityOptions(); options.name = GWT.getModuleBaseURL() + "SampleData/models/CesiumBalloon/CesiumBalloon.glb"; options.position = new ConstantPositionProperty(position); options.model = new ModelGraphics(modelGraphicsOptions); csVPanel.getViewer().entities().add(options); } private void updatePostProcess() { depthOfField.enabled = depthOfFieldCBox.getValue(); depthOfField.uniforms.setProperty("focalDistance", focalDistanceSlider.getValue()); depthOfField.uniforms.setProperty("delta", deltaSlider.getValue() / 100.); depthOfField.uniforms.setProperty("sigma", sigmaSlider.getValue() / 100.); depthOfField.uniforms.setProperty("stepSize", stepSizeSlider.getValue() / 100.); } @Override public String[] getSourceCodeURLs() { String[] sourceCodeURLs = new String[1]; sourceCodeURLs[0] = GWT.getModuleBaseURL() + "examples/" + "DepthOfField.txt"; return sourceCodeURLs; } private class MValueChangeHandler implements ValueChangeHandler<Boolean> { @Override public void onValueChange(ValueChangeEvent<Boolean> event) { updatePostProcess(); } } private class MSliderListener implements SliderListener { @Override public void onStart(SliderEvent e) { // } @Override public boolean onSlide(SliderEvent e) { updatePostProcess(); return true; } @Override public void onChange(SliderEvent e) { // } @Override public void onStop(SliderEvent e) { // } } }
40.152632
108
0.697863
760b36ef04d22e1bdb026f7895b92236b299d219
44,449
/* * Copyright (C) 2009-2013 Typesafe Inc. <http://www.typesafe.com> */ package play.mvc; import play.api.libs.iteratee.Concurrent; import play.api.libs.iteratee.Enumerator; import play.api.mvc.*; import play.core.j.JavaResults; import play.libs.*; import play.libs.F.*; import play.twirl.api.Content; import java.io.*; import java.util.*; import com.fasterxml.jackson.databind.JsonNode; /** * Common results. */ public class Results { static Codec utf8 = Codec.javaSupported("utf-8"); static int defaultChunkSize = 1024 * 8; // -- Constructor methods /** * Generates a 501 NOT_IMPLEMENTED simple result. */ public static Result TODO = new Todo(); // -- Status /** * Generates a simple result. */ public static Status status(int status) { return new Status(play.core.j.JavaResults.Status(status)); } /** * Generates a simple result. */ public static Status status(int status, Content content) { return new Status(play.core.j.JavaResults.Status(status), content, utf8); } /** * Generates a simple result. */ public static Status status(int status, Content content, String charset) { return new Status(play.core.j.JavaResults.Status(status), content, Codec.javaSupported(charset)); } /** * Generates a simple result. */ public static Status status(int status, String content) { return new Status(play.core.j.JavaResults.Status(status), content, utf8); } /** * Generates a simple result. */ public static Status status(int status, String content, String charset) { return new Status(play.core.j.JavaResults.Status(status), content, Codec.javaSupported(charset)); } /** * Generates a simple result. */ public static Status status(int status, JsonNode content) { return new Status(play.core.j.JavaResults.Status(status), content, utf8); } /** * Generates a simple result. */ public static Status status(int status, JsonNode content, String charset) { return new Status(play.core.j.JavaResults.Status(status), content, Codec.javaSupported(charset)); } /** * Generates a simple result. */ public static Status status(int status, byte[] content) { return new Status(play.core.j.JavaResults.Status(status), content); } /** * Generates a chunked result. */ public static Status status(int status, InputStream content) { return status(status, content, defaultChunkSize); } /** * Generates a chunked result. */ public static Status status(int status, InputStream content, int chunkSize) { return new Status(play.core.j.JavaResults.Status(status), content, chunkSize); } /** * Generates a chunked result. */ public static Status status(int status, File content) { return new Status(play.core.j.JavaResults.Status(status), content); } /** * Generates a simple result. */ public static Status status(int status, File content, int chunkSize) { return new Status(play.core.j.JavaResults.Status(status), content, chunkSize); } /** * Generates a chunked result. */ public static Status status(int status, Chunks<?> chunks) { return new Status(play.core.j.JavaResults.Status(status), chunks); } // -- OK /** * Generates a 200 OK simple result. */ public static Status ok() { return new Status(play.core.j.JavaResults.Ok()); } /** * Generates a 200 OK simple result. */ public static Status ok(Content content) { return new Status(play.core.j.JavaResults.Ok(), content, utf8); } /** * Generates a 200 OK simple result. */ public static Status ok(Content content, String charset) { return new Status(play.core.j.JavaResults.Ok(), content, Codec.javaSupported(charset)); } /** * Generates a 200 OK simple result. */ public static Status ok(String content) { return new Status(play.core.j.JavaResults.Ok(), content, utf8); } /** * Generates a 200 OK simple result. */ public static Status ok(String content, String charset) { return new Status(play.core.j.JavaResults.Ok(), content, Codec.javaSupported(charset)); } /** * Generates a 200 OK simple result. */ public static Status ok(JsonNode content) { return new Status(play.core.j.JavaResults.Ok(), content, utf8); } /** * Generates a 200 OK simple result. */ public static Status ok(JsonNode content, String charset) { return new Status(play.core.j.JavaResults.Ok(), content, Codec.javaSupported(charset)); } /** * Generates a 200 OK simple result. */ public static Status ok(byte[] content) { return new Status(play.core.j.JavaResults.Ok(), content); } /** * Generates a 200 OK chunked result. */ public static Status ok(InputStream content) { return ok(content, defaultChunkSize); } /** * Generates a 200 OK chunked result. */ public static Status ok(InputStream content, int chunkSize) { return new Status(play.core.j.JavaResults.Ok(), content, chunkSize); } /** * Generates a 200 OK file result as an attachment. * * @param content The file to send. */ public static Status ok(File content) { return new Status(play.core.j.JavaResults.Ok(), content); } /** * Generates a 200 OK file result. * * @param content The file to send. * @param inline Whether the file should be sent inline, or as an attachment. */ public static Status ok(File content, boolean inline) { return new Status(JavaResults.Ok(), content, inline); } /** * Generates a 200 OK file result as an attachment. * * @param content The file to send. * @param filename The name to send the file as. */ public static Status ok(File content, String filename) { return new Status(JavaResults.Ok(), content, true, filename); } /** * Generates a 200 OK file result, sent as a chunked response. * * @deprecated Since the length of the file is known, there is little reason to send a file as chunked. */ @Deprecated public static Status ok(File content, int chunkSize) { return new Status(play.core.j.JavaResults.Ok(), content, chunkSize); } /** * Generates a 200 OK chunked result. */ public static Status ok(Chunks<?> chunks) { return new Status(play.core.j.JavaResults.Ok(), chunks); } // -- CREATED /** * Generates a 201 CREATED simple result. */ public static Status created() { return new Status(play.core.j.JavaResults.Created()); } /** * Generates a 201 CREATED simple result. */ public static Status created(Content content) { return new Status(play.core.j.JavaResults.Created(), content, utf8); } /** * Generates a 201 CREATED simple result. */ public static Status created(Content content, String charset) { return new Status(play.core.j.JavaResults.Created(), content, Codec.javaSupported(charset)); } /** * Generates a 201 CREATED simple result. */ public static Status created(String content) { return new Status(play.core.j.JavaResults.Created(), content, utf8); } /** * Generates a 201 CREATED simple result. */ public static Status created(String content, String charset) { return new Status(play.core.j.JavaResults.Created(), content, Codec.javaSupported(charset)); } /** * Generates a 201 CREATED simple result. */ public static Status created(JsonNode content) { return new Status(play.core.j.JavaResults.Created(), content, utf8); } /** * Generates a 201 CREATED simple result. */ public static Status created(JsonNode content, String charset) { return new Status(play.core.j.JavaResults.Created(), content, Codec.javaSupported(charset)); } /** * Generates a 201 CREATED simple result. */ public static Status created(byte[] content) { return new Status(play.core.j.JavaResults.Created(), content); } /** * Generates a 201 CREATED chunked result. */ public static Status created(InputStream content) { return created(content, defaultChunkSize); } /** * Generates a 201 CREATED chunked result. */ public static Status created(InputStream content, int chunkSize) { return new Status(play.core.j.JavaResults.Created(), content, chunkSize); } /** * Generates a 201 CREATED file result as an attachment. * * @param content The file to send. */ public static Status created(File content) { return new Status(play.core.j.JavaResults.Created(), content); } /** * Generates a 201 CREATED file result. * * @param content The file to send. * @param inline Whether the file should be sent inline, or as an attachment. */ public static Status created(File content, boolean inline) { return new Status(JavaResults.Created(), content, inline); } /** * Generates a 201 CREATED file result as an attachment. * * @param content The file to send. * @param filename The name to send the file as. */ public static Status created(File content, String filename) { return new Status(JavaResults.Created(), content, true, filename); } /** * Generates a 201 CREATED file result, sent as a chunked response. * * @deprecated Since the length of the file is known, there is little reason to send a file as chunked. */ @Deprecated public static Status created(File content, int chunkSize) { return new Status(play.core.j.JavaResults.Created(), content, chunkSize); } /** * Generates a 201 CREATED chunked result. */ public static Status created(Chunks<?> chunks) { return new Status(play.core.j.JavaResults.Created(), chunks); } // -- NO_CONTENT /** * Generates a 204 NO_CONTENT simple result. */ public static Status noContent() { return new Status(play.core.j.JavaResults.Status(204)); } // -- INTERNAL_SERVER_ERROR /** * Generates a 500 INTERNAL_SERVER_ERROR simple result. */ public static Status internalServerError() { return new Status(play.core.j.JavaResults.InternalServerError()); } /** * Generates a 500 INTERNAL_SERVER_ERROR simple result. */ public static Status internalServerError(Content content) { return new Status(play.core.j.JavaResults.InternalServerError(), content, utf8); } /** * Generates a 500 INTERNAL_SERVER_ERROR simple result. */ public static Status internalServerError(Content content, String charset) { return new Status(play.core.j.JavaResults.InternalServerError(), content, Codec.javaSupported(charset)); } /** * Generates a 500 INTERNAL_SERVER_ERROR simple result. */ public static Status internalServerError(String content) { return new Status(play.core.j.JavaResults.InternalServerError(), content, utf8); } /** * Generates a 500 INTERNAL_SERVER_ERROR simple result. */ public static Status internalServerError(String content, String charset) { return new Status(play.core.j.JavaResults.InternalServerError(), content, Codec.javaSupported(charset)); } /** * Generates a 500 INTERNAL_SERVER_ERROR simple result. */ public static Status internalServerError(JsonNode content) { return new Status(play.core.j.JavaResults.InternalServerError(), content, utf8); } /** * Generates a 500 INTERNAL_SERVER_ERROR simple result. */ public static Status internalServerError(JsonNode content, String charset) { return new Status(play.core.j.JavaResults.InternalServerError(), content, Codec.javaSupported(charset)); } /** * Generates a 500 INTERNAL_SERVER_ERROR simple result. */ public static Status internalServerError(byte[] content) { return new Status(play.core.j.JavaResults.InternalServerError(), content); } /** * Generates a 500 INTERNAL_SERVER_ERROR chunked result. */ public static Status internalServerError(InputStream content) { return internalServerError(content, defaultChunkSize); } /** * Generates a 500 INTERNAL_SERVER_ERROR chunked result. */ public static Status internalServerError(InputStream content, int chunkSize) { return new Status(play.core.j.JavaResults.InternalServerError(), content, chunkSize); } /** * Generates a 500 INTERNAL_SERVER_ERROR file result as an attachment. * * @param content The file to send. */ public static Status internalServerError(File content) { return new Status(play.core.j.JavaResults.InternalServerError(), content); } /** * Generates a 500 INTERNAL_SERVER_ERROR file result. * * @param content The file to send. * @param inline Whether the file should be sent inline, or as an attachment. */ public static Status internalServerError(File content, boolean inline) { return new Status(JavaResults.InternalServerError(), content, inline); } /** * Generates a 500 INTERNAL_SERVER_ERROR file result as an attachment. * * @param content The file to send. * @param filename The name to send the file as. */ public static Status internalServerError(File content, String filename) { return new Status(JavaResults.InternalServerError(), content, true, filename); } /** * Generates a 500 INTERNAL_SERVER_ERROR file result, sent as a chunked response. * * @deprecated Since the length of the file is known, there is little reason to send a file as chunked. */ @Deprecated public static Status internalServerError(File content, int chunkSize) { return new Status(play.core.j.JavaResults.InternalServerError(), content, chunkSize); } /** * Generates a 500 INTERNAL_SERVER_ERROR chunked result. */ public static Status internalServerError(Chunks<?> chunks) { return new Status(play.core.j.JavaResults.InternalServerError(), chunks); } // -- NOT_FOUND /** * Generates a 404 NOT_FOUND simple result. */ public static Status notFound() { return new Status(play.core.j.JavaResults.NotFound()); } /** * Generates a 404 NOT_FOUND simple result. */ public static Status notFound(Content content) { return new Status(play.core.j.JavaResults.NotFound(), content, utf8); } /** * Generates a 404 NOT_FOUND simple result. */ public static Status notFound(Content content, String charset) { return new Status(play.core.j.JavaResults.NotFound(), content, Codec.javaSupported(charset)); } /** * Generates a 404 NOT_FOUND simple result. */ public static Status notFound(String content) { return new Status(play.core.j.JavaResults.NotFound(), content, utf8); } /** * Generates a 404 NOT_FOUND simple result. */ public static Status notFound(String content, String charset) { return new Status(play.core.j.JavaResults.NotFound(), content, Codec.javaSupported(charset)); } /** * Generates a 404 NOT_FOUND simple result. */ public static Status notFound(JsonNode content) { return new Status(play.core.j.JavaResults.NotFound(), content, utf8); } /** * Generates a 404 NOT_FOUND simple result. */ public static Status notFound(JsonNode content, String charset) { return new Status(play.core.j.JavaResults.NotFound(), content, Codec.javaSupported(charset)); } /** * Generates a 404 NOT_FOUND simple result. */ public static Status notFound(byte[] content) { return new Status(play.core.j.JavaResults.NotFound(), content); } /** * Generates a 404 NOT_FOUND chunked result. */ public static Status notFound(InputStream content) { return notFound(content, defaultChunkSize); } /** * Generates a 404 NOT_FOUND chunked result. */ public static Status notFound(InputStream content, int chunkSize) { return new Status(play.core.j.JavaResults.NotFound(), content, chunkSize); } /** * Generates a 404 NOT_FOUND file result as an attachment. * * @param content The file to send. */ public static Status notFound(File content) { return new Status(play.core.j.JavaResults.NotFound(), content); } /** * Generates a 404 NOT_FOUND file result. * * @param content The file to send. * @param inline Whether the file should be sent inline, or as an attachment. */ public static Status notFound(File content, boolean inline) { return new Status(JavaResults.NotFound(), content, inline); } /** * Generates a 404 NOT_FOUND file result as an attachment. * * @param content The file to send. * @param filename The name to send the file as. */ public static Status notFound(File content, String filename) { return new Status(JavaResults.NotFound(), content, true, filename); } /** * Generates a 404 NOT_FOUND file result, sent as a chunked response. * * @deprecated Since the length of the file is known, there is little reason to send a file as chunked. */ @Deprecated public static Status notFound(File content, int chunkSize) { return new Status(play.core.j.JavaResults.NotFound(), content, chunkSize); } /** * Generates a 404 NOT_FOUND chunked result. */ public static Status notFound(Chunks<?> chunks) { return new Status(play.core.j.JavaResults.NotFound(), chunks); } // -- FORBIDDEN /** * Generates a 403 FORBIDDEN simple result. */ public static Status forbidden() { return new Status(play.core.j.JavaResults.Forbidden()); } /** * Generates a 403 FORBIDDEN simple result. */ public static Status forbidden(Content content) { return new Status(play.core.j.JavaResults.Forbidden(), content, utf8); } /** * Generates a 403 FORBIDDEN simple result. */ public static Status forbidden(Content content, String charset) { return new Status(play.core.j.JavaResults.Forbidden(), content, Codec.javaSupported(charset)); } /** * Generates a 403 FORBIDDEN simple result. */ public static Status forbidden(String content) { return new Status(play.core.j.JavaResults.Forbidden(), content, utf8); } /** * Generates a 403 FORBIDDEN simple result. */ public static Status forbidden(String content, String charset) { return new Status(play.core.j.JavaResults.Forbidden(), content, Codec.javaSupported(charset)); } /** * Generates a 403 FORBIDDEN simple result. */ public static Status forbidden(JsonNode content) { return new Status(play.core.j.JavaResults.Forbidden(), content, utf8); } /** * Generates a 403 FORBIDDEN simple result. */ public static Status forbidden(JsonNode content, String charset) { return new Status(play.core.j.JavaResults.Forbidden(), content, Codec.javaSupported(charset)); } /** * Generates a 403 FORBIDDEN simple result. */ public static Status forbidden(byte[] content) { return new Status(play.core.j.JavaResults.Forbidden(), content); } /** * Generates a 403 FORBIDDEN chunked result. */ public static Status forbidden(InputStream content) { return forbidden(content, defaultChunkSize); } /** * Generates a 403 FORBIDDEN chunked result. */ public static Status forbidden(InputStream content, int chunkSize) { return new Status(play.core.j.JavaResults.Forbidden(), content, chunkSize); } /** * Generates a 403 FORBIDDEN file result as an attachment. * * @param content The file to send. */ public static Status forbidden(File content) { return new Status(play.core.j.JavaResults.Forbidden(), content); } /** * Generates a 403 FORBIDDEN file result. * * @param content The file to send. * @param inline Whether the file should be sent inline, or as an attachment. */ public static Status forbidden(File content, boolean inline) { return new Status(JavaResults.Forbidden(), content, inline); } /** * Generates a 403 FORBIDDEN file result as an attachment. * * @param content The file to send. * @param filename The name to send the file as. */ public static Status forbidden(File content, String filename) { return new Status(JavaResults.Forbidden(), content, true, filename); } /** * Generates a 403 FORBIDDEN file result, sent as a chunked response. * * @deprecated Since the length of the file is known, there is little reason to send a file as chunked. */ @Deprecated public static Status forbidden(File content, int chunkSize) { return new Status(play.core.j.JavaResults.Forbidden(), content, chunkSize); } /** * Generates a 403 FORBIDDEN chunked result. */ public static Status forbidden(Chunks<?> chunks) { return new Status(play.core.j.JavaResults.Forbidden(), chunks); } // -- UNAUTHORIZED /** * Generates a 401 UNAUTHORIZED simple result. */ public static Status unauthorized() { return new Status(play.core.j.JavaResults.Unauthorized()); } /** * Generates a 401 UNAUTHORIZED simple result. */ public static Status unauthorized(Content content) { return new Status(play.core.j.JavaResults.Unauthorized(), content, utf8); } /** * Generates a 401 UNAUTHORIZED simple result. */ public static Status unauthorized(Content content, String charset) { return new Status(play.core.j.JavaResults.Unauthorized(), content, Codec.javaSupported(charset)); } /** * Generates a 401 UNAUTHORIZED simple result. */ public static Status unauthorized(String content) { return new Status(play.core.j.JavaResults.Unauthorized(), content, utf8); } /** * Generates a 401 UNAUTHORIZED simple result. */ public static Status unauthorized(String content, String charset) { return new Status(play.core.j.JavaResults.Unauthorized(), content, Codec.javaSupported(charset)); } /** * Generates a 401 UNAUTHORIZED simple result. */ public static Status unauthorized(JsonNode content) { return new Status(play.core.j.JavaResults.Unauthorized(), content, utf8); } /** * Generates a 401 UNAUTHORIZED simple result. */ public static Status unauthorized(JsonNode content, String charset) { return new Status(play.core.j.JavaResults.Unauthorized(), content, Codec.javaSupported(charset)); } /** * Generates a 401 UNAUTHORIZED simple result. */ public static Status unauthorized(byte[] content) { return new Status(play.core.j.JavaResults.Unauthorized(), content); } /** * Generates a 401 UNAUTHORIZED chunked result. */ public static Status unauthorized(InputStream content) { return unauthorized(content, defaultChunkSize); } /** * Generates a 401 UNAUTHORIZED chunked result. */ public static Status unauthorized(InputStream content, int chunkSize) { return new Status(play.core.j.JavaResults.Unauthorized(), content, chunkSize); } /** * Generates a 401 UNAUTHORIZED file result as an attachment. * * @param content The file to send. */ public static Status unauthorized(File content) { return new Status(play.core.j.JavaResults.Unauthorized(), content); } /** * Generates a 401 UNAUTHORIZED file result. * * @param content The file to send. * @param inline Whether the file should be sent inline, or as an attachment. */ public static Status unauthorized(File content, boolean inline) { return new Status(JavaResults.Unauthorized(), content, inline); } /** * Generates a 401 UNAUTHORIZED file result as an attachment. * * @param content The file to send. * @param filename The name to send the file as. */ public static Status unauthorized(File content, String filename) { return new Status(JavaResults.Unauthorized(), content, true, filename); } /** * Generates a 401 UNAUTHORIZED file result, sent as a chunked response. * * @deprecated Since the length of the file is known, there is little reason to send a file as chunked. */ @Deprecated public static Status unauthorized(File content, int chunkSize) { return new Status(play.core.j.JavaResults.Unauthorized(), content, chunkSize); } /** * Generates a 401 UNAUTHORIZED chunked result. */ public static Status unauthorized(Chunks<?> chunks) { return new Status(play.core.j.JavaResults.Unauthorized(), chunks); } // -- BAD_REQUEST /** * Generates a 400 BAD_REQUEST simple result. */ public static Status badRequest() { return new Status(play.core.j.JavaResults.BadRequest()); } /** * Generates a 400 BAD_REQUEST simple result. */ public static Status badRequest(Content content) { return new Status(play.core.j.JavaResults.BadRequest(), content, utf8); } /** * Generates a 400 BAD_REQUEST simple result. */ public static Status badRequest(Content content, String charset) { return new Status(play.core.j.JavaResults.BadRequest(), content, Codec.javaSupported(charset)); } /** * Generates a 400 BAD_REQUEST simple result. */ public static Status badRequest(String content) { return new Status(play.core.j.JavaResults.BadRequest(), content, utf8); } /** * Generates a 400 BAD_REQUEST simple result. */ public static Status badRequest(String content, String charset) { return new Status(play.core.j.JavaResults.BadRequest(), content, Codec.javaSupported(charset)); } /** * Generates a 400 BAD_REQUEST simple result. */ public static Status badRequest(JsonNode content) { return new Status(play.core.j.JavaResults.BadRequest(), content, utf8); } /** * Generates a 400 BAD_REQUEST simple result. */ public static Status badRequest(JsonNode content, String charset) { return new Status(play.core.j.JavaResults.BadRequest(), content, Codec.javaSupported(charset)); } /** * Generates a 400 BAD_REQUEST simple result. */ public static Status badRequest(byte[] content) { return new Status(play.core.j.JavaResults.BadRequest(), content); } /** * Generates a 400 BAD_REQUEST chunked result. */ public static Status badRequest(InputStream content) { return badRequest(content, defaultChunkSize); } /** * Generates a 400 BAD_REQUEST chunked result. */ public static Status badRequest(InputStream content, int chunkSize) { return new Status(play.core.j.JavaResults.BadRequest(), content, chunkSize); } /** * Generates a 400 BAD_REQUEST file result as an attachment. * * @param content The file to send. */ public static Status badRequest(File content) { return new Status(play.core.j.JavaResults.BadRequest(), content); } /** * Generates a 400 BAD_REQUEST file result. * * @param content The file to send. * @param inline Whether the file should be sent inline, or as an attachment. */ public static Status badRequest(File content, boolean inline) { return new Status(JavaResults.BadRequest(), content, inline); } /** * Generates a 400 BAD_REQUEST file result as an attachment. * * @param content The file to send. * @param filename The name to send the file as. */ public static Status badRequest(File content, String filename) { return new Status(JavaResults.BadRequest(), content, true, filename); } /** * Generates a 400 BAD_REQUEST file result, sent as a chunked response. * * @deprecated Since the length of the file is known, there is little reason to send a file as chunked. */ @Deprecated public static Status badRequest(File content, int chunkSize) { return new Status(play.core.j.JavaResults.BadRequest(), content, chunkSize); } /** * Generates a 400 BAD_REQUEST chunked result. */ public static Status badRequest(Chunks<?> chunks) { return new Status(play.core.j.JavaResults.BadRequest(), chunks); } // -- Redirect /** * Generates a 303 SEE_OTHER simple result. * * @param url The url to redirect. */ public static Result redirect(String url) { return new Redirect(303, url); } /** * Generates a 303 SEE_OTHER simple result. * * @param call Call defining the url to redirect (typically comes from reverse router). */ public static Result redirect(Call call) { return new Redirect(303, call.url()); } // -- Found /** * Generates a 302 FOUND simple result. * * @param url The url to redirect. */ public static Result found(String url) { return new Redirect(302, url); } /** * Generates a 302 FOUND simple result. * * @param call Call defining the url to redirect (typically comes from reverse router). */ public static Result found(Call call) { return new Redirect(302, call.url()); } // -- Moved Permanently /** * Generates a 301 MOVED_PERMANENTLY simple result. * * @param url The url to redirect. */ public static Result movedPermanently(String url) { return new Redirect(301, url); } /** * Generates a 301 MOVED_PERMANENTLY simple result. * * @param call Call defining the url to redirect (typically comes from reverse router). */ public static Result movedPermanently(Call call) { return new Redirect(301, call.url()); } // -- See Other /** * Generates a 303 SEE_OTHER simple result. * * @param url The url to redirect. */ public static Result seeOther(String url) { return new Redirect(303, url); } /** * Generates a 303 SEE_OTHER simple result. * * @param call Call defining the url to redirect (typically comes from reverse router). */ public static Result seeOther(Call call) { return new Redirect(303, call.url()); } // -- Temporary Redirect /** * Generates a 307 TEMPORARY_REDIRECT simple result. * * @param url The url to redirect. */ public static Result temporaryRedirect(String url) { return new Redirect(307, url); } /** * Generates a 307 TEMPORARY_REDIRECT simple result. * * @param call Call defining the url to redirect (typically comes from reverse router). */ public static Result temporaryRedirect(Call call) { return new Redirect(307, call.url()); } // -- Definitions /** * A Chunked result. */ public abstract static class Chunks<A> { final Enumerator<A> enumerator; final play.api.http.Writeable<A> writable; public Chunks(play.api.http.Writeable<A> writable) { final Chunks<A> self = this; this.writable = writable; final RedeemablePromise<Object> disconnected = RedeemablePromise.<Object>empty(); this.enumerator = play.core.j.JavaResults.chunked(new Callback<Concurrent.Channel<A>>() { @Override public void invoke(Concurrent.Channel<A> channel) { Chunks.Out<A> chunked = new Chunks.Out<A>(channel, disconnected); self.onReady(chunked); } }, new Callback0() { @Override public void invoke() throws Throwable { disconnected.success(null); } }); } /** * Called when the Chunked stream is ready. * * @param out The out stream. */ public abstract void onReady(Chunks.Out<A> out); /** * A Chunked stream. */ public static class Out<A> { /** A Promise that will be redeemed to null when the channel is disconnected. */ final RedeemablePromise<Object> disconnected; final play.api.libs.iteratee.Concurrent.Channel<A> channel; public Out(play.api.libs.iteratee.Concurrent.Channel<A> channel, RedeemablePromise<Object> disconnected) { this.channel = channel; this.disconnected = disconnected; } public Out(play.api.libs.iteratee.Concurrent.Channel<A> channel, List<Callback0> disconnectedCallbacks) { this.channel = channel; this.disconnected = RedeemablePromise.<Object>empty(); for(Callback0 callback: disconnectedCallbacks) { onDisconnected(callback); } } /** * Write a Chunk. */ public void write(A chunk) { channel.push(chunk); } /** * Attach a callback to be called when the socket is disconnected. */ public void onDisconnected(final Callback0 callback) { disconnected.onRedeem(new Callback<Object>() { public void invoke(Object ignored) throws Throwable { callback.invoke(); } }); } /** * Closes the stream. */ public void close() { channel.eofAndEnd(); } } } /** * Chunked result based on String chunks. */ public abstract static class StringChunks extends Chunks<String> { public StringChunks() { this(utf8); } public StringChunks(String codec) { this(Codec.javaSupported(codec)); } public StringChunks(Codec codec) { super(play.core.j.JavaResults.writeString(codec)); } /** * Creates a StringChunks. The abstract {@code onReady} method is * implemented using the specified {@code Callback<Chunks.Out<String>>}. * * Uses UTF-8 by default. * * @param callback the callback used to implement onReady * @return a new StringChunks * @throws NullPointerException if the specified callback is null */ public static StringChunks whenReady(Callback<Chunks.Out<String>> callback) { return whenReady(utf8, callback); } /** * Creates a StringChunks. The abstract {@code onReady} method is * implemented using the specified {@code Callback<Chunks.Out<String>>}. * * @param codec the Codec charset used * @param callback the callback used to implement onReady * @return a new StringChunks * @throws NullPointerException if the specified callback is null */ public static StringChunks whenReady(String codec, Callback<Chunks.Out<String>> callback) { return whenReady(Codec.javaSupported(codec), callback); } /** * Creates a StringChunks. The abstract {@code onReady} method is * implemented using the specified {@code Callback<Chunks.Out<String>>}. * * @param codec the Codec used * @param callback the callback used to implement onReady * @return a new StringChunks * @throws NullPointerException if the specified callback is null */ public static StringChunks whenReady(Codec codec, Callback<Chunks.Out<String>> callback) { return new WhenReadyStringChunks(codec, callback); } /** * An extension of StringChunks that obtains its onReady from * the specified {@code Callback<Chunks.Out<String>>}. */ static final class WhenReadyStringChunks extends StringChunks { private final Callback<Chunks.Out<String>> callback; WhenReadyStringChunks(Codec codec, Callback<Chunks.Out<String>> callback) { super(codec); if (callback == null) throw new NullPointerException("StringChunks onReady callback cannot be null"); this.callback = callback; } @Override public void onReady(Chunks.Out<String> out) { try { callback.invoke(out); } catch (Throwable e) { play.PlayInternal.logger().error("Exception in StringChunks.onReady", e); } } } } /** * Chunked result based on byte[] chunks. */ public abstract static class ByteChunks extends Chunks<byte[]> { public ByteChunks() { super(play.core.j.JavaResults.writeBytes()); } /** * Creates a ByteChunks. The abstract {@code onReady} method is * implemented using the specified {@code Callback<Chunks.Out<byte[]>>}. * * @param callback the callback used to implement onReady * @return a new ByteChunks * @throws NullPointerException if the specified callback is null */ public static ByteChunks whenReady(Callback<Chunks.Out<byte[]>> callback) { return new WhenReadyByteChunks(callback); } /** * An extension of ByteChunks that obtains its onReady from * the specified {@code Callback<Chunks.Out<byte[]>>}. */ static final class WhenReadyByteChunks extends ByteChunks { private final Callback<Chunks.Out<byte[]>> callback; WhenReadyByteChunks(Callback<Chunks.Out<byte[]>> callback) { super(); if (callback == null) throw new NullPointerException("ByteChunks onReady callback cannot be null"); this.callback = callback; } @Override public void onReady(Chunks.Out<byte[]> out) { try { callback.invoke(out); } catch (Throwable e) { play.PlayInternal.logger().error("Exception in ByteChunks.onReady", e); } } } } /** * A 501 NOT_IMPLEMENTED simple result. */ public static class Todo implements Result { final private play.api.mvc.Result wrappedResult; public Todo() { wrappedResult = play.core.j.JavaResults.NotImplemented().apply( views.html.defaultpages.todo.render(), play.core.j.JavaResults.writeContent("text/html", utf8) ); } public play.api.mvc.Result toScala() { return this.wrappedResult; } } /** * A simple result. */ public static class Status implements Result { private play.api.mvc.Result wrappedResult; public Status(play.api.mvc.Results.Status status) { wrappedResult = status.apply( play.core.j.JavaResults.empty(), play.core.j.JavaResults.writeEmptyContent() ); } public Status(play.api.mvc.Results.Status status, String content, Codec codec) { if(content == null) { throw new NullPointerException("null content"); } wrappedResult = status.apply( content, play.core.j.JavaResults.writeString(codec) ); } public Status(play.api.mvc.Results.Status status, JsonNode content, Codec codec) { if(content == null) { throw new NullPointerException("null content"); } wrappedResult = status.apply( content, play.core.j.JavaResults.writeJson(codec) ); } public Status(play.api.mvc.Results.Status status, Content content, Codec codec) { if(content == null) { throw new NullPointerException("null content"); } wrappedResult = status.apply( content, play.core.j.JavaResults.writeContent(content.contentType(), codec) ); } public <A> Status(play.api.mvc.Results.Status status, Chunks<A> chunks) { if(chunks == null) { throw new NullPointerException("null content"); } wrappedResult = status.chunked(chunks.enumerator, chunks.writable); } public Status(play.api.mvc.Results.Status status, byte[] content) { if(content == null) { throw new NullPointerException("null content"); } wrappedResult = status.apply( content, play.core.j.JavaResults.writeBytes() ); } public Status(play.api.mvc.Results.Status status, File content) { this(status, content, false); } public Status(play.api.mvc.Results.Status status, File content, boolean inline) { this(status, content, inline, content.getName()); } public Status(play.api.mvc.Results.Status status, File content, boolean inline, String filename) { if(content == null) { throw new NullPointerException("null content"); } wrappedResult = play.core.j.JavaResults.sendFile(status, content, inline, filename); } public Status(play.api.mvc.Results.Status status, File content, int chunkSize) { if(content == null) { throw new NullPointerException("null content"); } wrappedResult = status.chunked( play.core.j.JavaResults.chunked(content, chunkSize), play.core.j.JavaResults.writeBytes(Scala.orNull(play.api.libs.MimeTypes.forFileName(content.getName()))) ); } public Status(play.api.mvc.Results.Status status, InputStream content, int chunkSize) { if(content == null) { throw new NullPointerException("null content"); } wrappedResult = status.chunked( play.core.j.JavaResults.chunked(content, chunkSize), play.core.j.JavaResults.writeBytes() ); } public play.api.mvc.Result toScala() { return wrappedResult; } /** * Change the Content-Type header for this result. */ public Status as(String contentType) { wrappedResult = wrappedResult.as(contentType); return this; } public String toString() { return wrappedResult.toString(); } } /** * A redirect result. */ public static class Redirect implements Result { final private play.api.mvc.Result wrappedResult; public Redirect(int status, String url) { wrappedResult = play.core.j.JavaResults.Redirect(url, status); } public play.api.mvc.Result toScala() { return this.wrappedResult; } } }
31.061495
124
0.617292
c967390ada2d6096f16b997ee8c43904a3b307eb
432
package net.bnfour.phone2web2tg_forwarder; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.POST; // lol, what a typo in "dotnet". Stays this way public interface IDontnetTelegramForwarderApi { // so seems like retrofit doesn't like empty strings here // it also add slash between base url and request path by itself @POST("smsnotify/") Call<Response> sendRequest(@Body Request request); }
30.857143
68
0.756944
15009b402011973fd3ac0c3e1e6bfbdf1954ca31
337
package net.cactusthorn.maven; import static org.junit.Assert.assertEquals; import org.junit.Test; @SuppressWarnings("checkstyle:magicnumber") public class DemoSubOneTest { @Test public void plus() { DemoSubOne demo = new DemoSubOne(); long value = demo.plus(150L); assertEquals(250L, value); } }
19.823529
44
0.68546
4d37cddbb464c42b2c73c6440591833075c02ba2
21,269
/* * CPAchecker is a tool for configurable software verification. * This file is part of CPAchecker. * * Copyright (C) 2007-2018 Dirk Beyer * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * * CPAchecker web page: * http://cpachecker.sosy-lab.org */ package org.sosy_lab.cpachecker.core.algorithm.bmc.pdr; import static org.sosy_lab.cpachecker.core.algorithm.bmc.BMCHelper.END_STATE_FILTER; import static org.sosy_lab.cpachecker.core.algorithm.bmc.BMCHelper.getLocationPredicate; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import com.google.common.collect.LinkedHashMultimap; import com.google.common.collect.Multimap; import com.google.common.collect.Sets; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.OptionalInt; import java.util.Set; import java.util.function.Function; import java.util.function.UnaryOperator; import java.util.stream.Collectors; import org.checkerframework.checker.nullness.qual.Nullable; import org.sosy_lab.common.log.LogManager; import org.sosy_lab.cpachecker.cfa.model.CFANode; import org.sosy_lab.cpachecker.cfa.model.FunctionEntryNode; import org.sosy_lab.cpachecker.cfa.types.c.CType; import org.sosy_lab.cpachecker.core.algorithm.Algorithm; import org.sosy_lab.cpachecker.core.algorithm.Algorithm.AlgorithmStatus; import org.sosy_lab.cpachecker.core.algorithm.bmc.BMCHelper; import org.sosy_lab.cpachecker.core.algorithm.bmc.CounterexampleToInductivity; import org.sosy_lab.cpachecker.core.algorithm.bmc.ModelValue; import org.sosy_lab.cpachecker.core.algorithm.bmc.UnrolledReachedSet; import org.sosy_lab.cpachecker.core.algorithm.bmc.candidateinvariants.CandidateInvariant; import org.sosy_lab.cpachecker.core.algorithm.bmc.candidateinvariants.CandidateInvariantCombination; import org.sosy_lab.cpachecker.core.interfaces.AbstractState; import org.sosy_lab.cpachecker.core.interfaces.ConfigurableProgramAnalysis; import org.sosy_lab.cpachecker.core.interfaces.Precision; import org.sosy_lab.cpachecker.core.interfaces.StateSpacePartition; import org.sosy_lab.cpachecker.core.reachedset.ReachedSet; import org.sosy_lab.cpachecker.cpa.input.InputState; import org.sosy_lab.cpachecker.cpa.predicate.PredicateAbstractState; import org.sosy_lab.cpachecker.exceptions.CPAException; import org.sosy_lab.cpachecker.exceptions.CPATransferException; import org.sosy_lab.cpachecker.util.AbstractStates; import org.sosy_lab.cpachecker.util.Pair; import org.sosy_lab.cpachecker.util.predicates.pathformula.PathFormula; import org.sosy_lab.cpachecker.util.predicates.pathformula.PathFormulaManager; import org.sosy_lab.cpachecker.util.predicates.pathformula.SSAMap; import org.sosy_lab.cpachecker.util.predicates.smt.FormulaManagerView; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.BooleanFormulaManager; import org.sosy_lab.java_smt.api.Formula; import org.sosy_lab.java_smt.api.Model.ValueAssignment; class PartialTransitionRelation implements Comparable<PartialTransitionRelation> { private final CFANode startLocation; private final LogManager logger; private final UnrolledReachedSet reachedSet; private final Set<CFANode> loopHeads; private final FormulaManagerView fmgr; private final BooleanFormulaManager bfmgr; private final PathFormulaManager pmgr; private @Nullable Set<AbstractState> currentEndStates = null; private @Nullable Map<String, Formula> currentVariables = null; private int lastK = -1; public PartialTransitionRelation( CFANode pStartLocation, Algorithm pAlgorithm, ConfigurableProgramAnalysis pCpa, FormulaManagerView pFmgr, PathFormulaManager pPmgr, LogManager pLogger, ReachedSet pReachedSet, Set<CFANode> pLoopHeads) { startLocation = Objects.requireNonNull(pStartLocation); logger = Objects.requireNonNull(pLogger); loopHeads = Objects.requireNonNull(pLoopHeads); reachedSet = new UnrolledReachedSet(pAlgorithm, pCpa, pLoopHeads, pReachedSet, this::ensureK); fmgr = Objects.requireNonNull(pFmgr); bfmgr = pFmgr.getBooleanFormulaManager(); pmgr = Objects.requireNonNull(pPmgr); } public int getDesiredK() { return reachedSet.getDesiredK(); } public void setDesiredK(int pK) { if (pK < reachedSet.getCurrentMaxK()) { throw new IllegalArgumentException( "The length of this transition relation is " + reachedSet.getCurrentMaxK() + " and cannot be decreased."); } reachedSet.setDesiredK(pK); } public AlgorithmStatus ensureK() throws InterruptedException, CPAException { if (reachedSet.getDesiredK() > lastK) { currentEndStates = null; currentVariables = null; } return reachedSet.ensureK(); } public CFANode getStartLocation() { return startLocation; } public Set<AbstractState> getEndStates() { int desiredK = getDesiredK(); if (currentEndStates != null && lastK == desiredK) { return currentEndStates; } currentEndStates = filterIterationsUpTo(reachedSet.getReachedSet(), desiredK) .filter( END_STATE_FILTER.or( getLocationPredicate(loopHeads) .and( state -> !Iterables.isEmpty( filterIteration(Collections.singleton(state), desiredK)))) ::test) .toSet(); currentVariables = null; lastK = desiredK; return currentEndStates; } public boolean transitionsTo(PartialTransitionRelation pOther) { return Iterables.contains( AbstractStates.extractLocations(getEndStates()), pOther.getStartLocation()); } @Override public int compareTo(PartialTransitionRelation pOther) { return startLocation.compareTo(pOther.startLocation); } @Override public boolean equals(Object pOther) { if (this == pOther) { return true; } if (pOther instanceof PartialTransitionRelation) { PartialTransitionRelation other = (PartialTransitionRelation) pOther; return startLocation.equals(other.startLocation) && bfmgr.equals(other.bfmgr) && fmgr.equals(other.fmgr) && pmgr.equals(other.pmgr) && reachedSet.equals(other.reachedSet) && logger.equals(other.logger) && loopHeads.equals(other.loopHeads); } return false; } @Override public int hashCode() { return Objects.hash(startLocation, bfmgr, fmgr, pmgr, reachedSet, logger, loopHeads); } private AlgorithmStatus ensureK( Algorithm pAlgorithm, ConfigurableProgramAnalysis pCpa, ReachedSet pReachedSet) throws InterruptedException, CPAException { if (pReachedSet.size() < 1) { AbstractState initialState = pCpa.getInitialState(startLocation, StateSpacePartition.getDefaultPartition()); Precision precision = pCpa.getInitialPrecision(startLocation, StateSpacePartition.getDefaultPartition()); pReachedSet.add(initialState, precision); if (pReachedSet.isEmpty()) { return AlgorithmStatus.SOUND_AND_PRECISE; } } return BMCHelper.unroll(logger, pReachedSet, pAlgorithm, pCpa); } public UnrolledReachedSet getReachedSet() { return reachedSet; } private FluentIterable<AbstractState> filterIteration( Iterable<AbstractState> pStates, int pIteration) { return filterIterationsBetween(pStates, pIteration, pIteration); } private FluentIterable<AbstractState> filterIterationsUpTo( Iterable<AbstractState> pStates, int pIteration) { return filterIterationsBetween(pStates, 0, pIteration); } private FluentIterable<AbstractState> filterIterationsBetween( Iterable<AbstractState> pStates, int pMinIt, int pMaxIt) { if (pMinIt > pMaxIt) { throw new IllegalArgumentException( String.format("Minimum (%d) not lower than maximum (%d)", pMinIt, pMaxIt)); } if (pMinIt < 0) { throw new IllegalArgumentException("Minimum must not be lower than 0 but is " + pMinIt); } int min = pMinIt; int max = pMaxIt; Set<CFANode> startLocations = loopHeads; if (startLocation.getNumEnteringEdges() == 0 && startLocation instanceof FunctionEntryNode) { startLocations = Sets.union(startLocations, Collections.singleton(startLocation)); --min; --max; if (max < 0) { ReachedSet reached = reachedSet.getReachedSet(); if (reached.isEmpty()) { return FluentIterable.of(); } return FluentIterable.of(reached.getFirstState()); } else { min = Math.max(0, min); max = Math.max(0, max); } } return BMCHelper.filterIterationsBetween(pStates, min, max, startLocations); } public Map<String, Formula> getVariables() { int desiredK = getDesiredK(); if (currentVariables != null && lastK == desiredK) { return currentVariables; } currentEndStates = null; Set<CFANode> relevantLocations = Sets.union(loopHeads, Collections.singleton(startLocation)); Iterable<AbstractState> relevantStates = filterIterationsUpTo( AbstractStates.filterLocations(reachedSet.getReachedSet(), relevantLocations), desiredK); currentVariables = AbstractStates.projectToType(relevantStates, PredicateAbstractState.class) .stream() .map(PartialTransitionRelation::getPathFormula) .flatMap( pathFormula -> { SSAMap ssaMap = pathFormula.getSsa(); return ssaMap .allVariables() .stream() .filter(name -> !name.startsWith("*")) .map( name -> { return pmgr.makeFormulaForUninstantiatedVariable( name, ssaMap.getType(name), pathFormula.getPointerTargetSet(), false); }); }) .distinct() .collect( Collectors.toMap( f -> fmgr.extractVariableNames(f).iterator().next(), Function.identity())); lastK = desiredK; return currentVariables; } public BooleanFormula getPredecessorAssertions(Iterable<CandidateInvariant> pPredecessorAssertions) throws CPATransferException, InterruptedException { return getStateAssertions( pPredecessorAssertions, states -> filterIterationsUpTo(states, getDesiredK() - 1), 1); } public BooleanFormula getSuccessorAssertion(CandidateInvariant pSuccessorAssertion) throws CPATransferException, InterruptedException { return getSuccessorAssertions(Collections.singleton(pSuccessorAssertion)); } public BooleanFormula getSuccessorAssertions(Iterable<CandidateInvariant> pSuccessorAssertions) throws CPATransferException, InterruptedException { return getStateAssertions( pSuccessorAssertions, states -> filterIteration(states, getDesiredK()), 2); } private BooleanFormula getStateAssertions( Iterable<CandidateInvariant> pAssertions, UnaryOperator<Iterable<AbstractState>> pStateFilter, int pDefaultIndex) throws CPATransferException, InterruptedException { BooleanFormula assertions = bfmgr.makeBoolean(true); for (CandidateInvariant assertion : pAssertions) { for (CandidateInvariant conjunctivePart : CandidateInvariantCombination.getConjunctiveParts(assertion)) { assertions = bfmgr.and(assertions, getStateAssertion(conjunctivePart, pStateFilter, pDefaultIndex)); } } return assertions; } private BooleanFormula getStateAssertion( CandidateInvariant pAssertion, UnaryOperator<Iterable<AbstractState>> pStateFilter, int pDefaultIndex) throws CPATransferException, InterruptedException { ReachedSet reached = reachedSet.getReachedSet(); Set<AbstractState> states = filterIterationsUpTo( pStateFilter.apply(pAssertion.filterApplicable(reached)), getDesiredK()) .toSet(); BooleanFormula stateAssertionFormula = bfmgr.makeTrue(); for (AbstractState state : states) { BooleanFormula stateFormula = getStateFormula(state); // Use index 2 for successor locations BooleanFormula invariantFormula = instantiateAt(state, pAssertion, pDefaultIndex); stateAssertionFormula = bfmgr.and(stateAssertionFormula, bfmgr.implication(stateFormula, invariantFormula)); } return stateAssertionFormula; } private BooleanFormula getStateFormula(AbstractState state) { BooleanFormula startLocationFormula = getStartLocationFormula(); BooleanFormula stateFormula = getPathFormula(state).getFormula(); stateFormula = bfmgr.and(startLocationFormula, stateFormula); if (getEndStates().contains(state)) { BooleanFormula endLocationFormula = bfmgr.makeFalse(); for (CFANode endLocation : AbstractStates.extractLocations(state)) { endLocationFormula = bfmgr.or( endLocationFormula, TotalTransitionRelation.getPrimedLocationFormula(fmgr, endLocation)); } stateFormula = bfmgr.and(stateFormula, endLocationFormula); } return stateFormula; } void collectSuccessorViolationAssertions( CandidateInvariant pCandidateInvariant, Multimap<BooleanFormula, BooleanFormula> pCollection) throws CPATransferException, InterruptedException { ReachedSet reached = reachedSet.getReachedSet(); Iterable<AbstractState> assertionStates = filterIteration(pCandidateInvariant.filterApplicable(reached), getDesiredK()); for (AbstractState state : assertionStates) { BooleanFormula stateFormula = getStateFormula(state); // Use index 2 for successor locations BooleanFormula invariantFormula = instantiateAt(state, pCandidateInvariant, 2); pCollection.put(stateFormula, bfmgr.not(invariantFormula)); } } private BooleanFormula instantiateAt( AbstractState pState, CandidateInvariant pCandidateInvariant, int pDefaultIndex) throws CPATransferException, InterruptedException { PathFormula pathFormula = getPathFormula(pState); SSAMap ssaMap = pathFormula.getSsa().withDefault(pDefaultIndex); // Use index 2 for successor locations pathFormula = pmgr.makeNewPathFormula(pathFormula, ssaMap, pathFormula.getPointerTargetSet()); BooleanFormula uninstantiatedFormula = pCandidateInvariant.getFormula(fmgr, pmgr, pathFormula); return fmgr.instantiate(uninstantiatedFormula, ssaMap); } public BooleanFormula getStartLocationFormula() { return TotalTransitionRelation.getUnprimedLocationFormula(fmgr, startLocation); } public BooleanFormula getFormula() { Set<AbstractState> endStates = getEndStates(); ReachedSet reached = reachedSet.getReachedSet(); if (reached.isEmpty() || endStates.isEmpty()) { return bfmgr.makeFalse(); } // Create the transition formula for each end state and disjoin them BooleanFormula transition = bfmgr.makeFalse(); for (AbstractState endState : endStates) { // Build the state formula BooleanFormula endStateFormula = getStateFormula(endState); transition = bfmgr.or(transition, endStateFormula); } return transition; } public CtiWithInputs getCtiWithInputs(List<ValueAssignment> pModelAssignments) { Map<String, CType> types = new HashMap<>(); Multimap<String, Integer> inputs = extractInputs( filterIterationsUpTo(getReachedSet().getReachedSet(), getDesiredK() + 1), types); Map<String, Formula> variables = getVariables(); ImmutableMap.Builder<String, ModelValue> modelBuilder = ImmutableMap.builder(); for (ValueAssignment valueAssignment : pModelAssignments) { if (!valueAssignment.isFunction()) { String fullName = valueAssignment.getName(); Pair<String, OptionalInt> pair = FormulaManagerView.parseName(fullName); String actualName = pair.getFirst(); OptionalInt index = pair.getSecond(); Object value = valueAssignment.getValue(); if (index.isPresent() && index.orElseThrow() == 1 && value instanceof Number && (actualName.equals(TotalTransitionRelation.getLocationVariableName()) || (variables.containsKey(actualName) && !inputs.get(actualName).contains(index.orElseThrow())))) { BooleanFormula assignment = fmgr.uninstantiate(valueAssignment.getAssignmentAsFormula()); ModelValue modelValue = new ModelValue( actualName, fmgr.dumpFormula(assignment).toString(), assignment::toString); modelBuilder.put(actualName, modelValue); } } } Map<String, ModelValue> model = modelBuilder.build(); CounterexampleToInductivity cti = new CounterexampleToInductivity(startLocation, model); return new CtiWithInputs( cti, getInputAssignments(fmgr, variables, getReachedSet().getReachedSet(), pModelAssignments)); } private static BooleanFormula getInputAssignments( FormulaManagerView pFmgr, Map<String, Formula> pVariables, Iterable<AbstractState> pReached, Iterable<ValueAssignment> pModelAssignments) { BooleanFormulaManager bfmgr = pFmgr.getBooleanFormulaManager(); BooleanFormula inputAssignments = bfmgr.makeTrue(); Map<String, CType> types = new HashMap<>(); Multimap<String, Integer> inputs = extractInputs(pReached, types); if (inputs.isEmpty()) { return inputAssignments; } for (ValueAssignment valueAssignment : pModelAssignments) { if (!valueAssignment.isFunction()) { String fullName = valueAssignment.getName(); Pair<String, OptionalInt> pair = FormulaManagerView.parseName(fullName); String actualName = pair.getFirst(); OptionalInt index = pair.getSecond(); // We consider as inputs // a) those that have an SSA index and are contained in our list of input variables and // b) those that have no SSA index and are not known as actual variables, // such as __ADDRESS_OF: if ((index.isPresent() && inputs.get(actualName).contains(index.orElseThrow())) || (!index.isPresent() && !pVariables.containsKey(actualName))) { inputAssignments = bfmgr.and(inputAssignments, valueAssignment.getAssignmentAsFormula()); } } } return inputAssignments; } private static Multimap<String, Integer> extractInputs( Iterable<AbstractState> pReached, Map<String, CType> types) { Multimap<String, Integer> inputs = LinkedHashMultimap.create(); for (AbstractState s : pReached) { InputState is = AbstractStates.extractStateByType(s, InputState.class); if (is != null) { PredicateAbstractState pas = AbstractStates.extractStateByType(s, PredicateAbstractState.class); SSAMap ssaMap = pas.getPathFormula().getSsa(); for (String input : is.getInputs()) { if (ssaMap.containsVariable(input)) { inputs.put(input, ssaMap.getIndex(input) - 1); types.put(input, ssaMap.getType(input)); } } for (String varName : ssaMap.allVariables()) { types.put(varName, ssaMap.getType(varName)); } } } return inputs; } private static PathFormula getPathFormula(AbstractState pPas) { PredicateAbstractState pas = AbstractStates.extractStateByType(pPas, PredicateAbstractState.class); return getPathFormula(pas); } private static PathFormula getPathFormula(PredicateAbstractState pPas) { if (pPas.isAbstractionState()) { return pPas.getAbstractionFormula().getBlockFormula(); } return pPas.getPathFormula(); } static class CtiWithInputs { private final CounterexampleToInductivity cti; private final BooleanFormula inputs; public CtiWithInputs(CounterexampleToInductivity pCti, BooleanFormula pInputs) { cti = Objects.requireNonNull(pCti); inputs = Objects.requireNonNull(pInputs); } @Override public String toString() { return cti + " with inputs " + inputs; } public CounterexampleToInductivity getCti() { return cti; } public BooleanFormula getInputs() { return inputs; } } }
38.954212
153
0.706991
9ade2013196ff5ca7bbbcac73c81e7e3fd96b0bd
261
package com.example.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.example.model.JettyFormula; public interface JettyFormulaRepository extends JpaRepository<JettyFormula, Long> { JettyFormula findByName(String name); }
26.1
83
0.83908
158ee50c1cc141c28a1088778acd484a2aaac808
561
package com.easykotlin.learn.study10; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class ShellUtilDemo { @Test public void testExecuteShellCmd() { String result = ShellUtil.execute("adb devices"); System.out.println(result); } @Test public void testExecuteShellCmd2() { String[] cmds = {".", "-c", "ls -al .. | grep .kt$"}; String result = ShellUtil.execute(cmds); System.out.println(result); } }
24.391304
62
0.620321
04519700e9915fe94d77c3302ad45333d3f238d3
4,268
package org.openregistry.core.domain.jpa; import org.hibernate.annotations.Index; import org.hibernate.envers.Audited; import org.openregistry.core.domain.AuxiliaryIdentifier; import org.openregistry.core.domain.AuxiliaryProgram; import org.openregistry.core.domain.Type; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.openregistry.core.domain.internal.Entity; import javax.persistence.*; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Created by IntelliJ IDEA. * User: nah67 * Date: 10/20/11 * Time: 3:34 PM * To change this template use File | Settings | File Templates. */ @javax.persistence.Entity(name="AUX_PROGRAMS") @Table(name="AUX_PROGRAMS") @Audited @org.hibernate.annotations.Table(appliesTo = "AUX_PROGRAMS", indexes = { @Index(name = "AUTH_PROGRAM_NAME_IDX", columnNames = "PROGRAM_NAME") }) public class JpaAuxiliaryProgramImpl extends Entity implements AuxiliaryProgram { protected static final Logger logger = LoggerFactory.getLogger(JpaAuxiliaryProgramImpl.class); @Id @Column(name="id") @GeneratedValue(strategy = GenerationType.AUTO, generator = "AUX_PROGRAMS_SEQ") @SequenceGenerator(name="AUX_PROGRAMS_SEQ",sequenceName="AUX_PROGRAMS_SEQ",initialValue=1,allocationSize=50) private Long id; @Column(name="PROGRAM_NAME",nullable=false) private String programName; @Column(name="SPONSOR_ID", nullable = false) private Long sponsorId; @ManyToOne(optional = false, targetEntity = JpaTypeImpl.class) @JoinColumn(name="SPONSOR_T") private Type sponsorType; @Column(name = "AFFILIATION_DATE", nullable = false) @Temporal(TemporalType.DATE) private Date affiliationDate; @Column(name = "TERMINATION_DATE") @Temporal(TemporalType.DATE) private Date terminationDate; @OneToMany(cascade = CascadeType.ALL, mappedBy = "program", fetch = FetchType.EAGER, targetEntity = JpaAuxiliaryIdentifierImpl.class) //@OneToMany(cascade = CascadeType.ALL, mappedBy = "program", fetch = FetchType.EAGER) //@org.hibernate.annotations.Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN) private Set<AuxiliaryIdentifier> identifiers = new HashSet<AuxiliaryIdentifier>(); @Override public Long getId() { return id; } @Override public String getProgramName() { return programName; //To change body of implemented methods use File | Settings | File Templates. } @Override public Long getSponsorId() { return sponsorId; //To change body of implemented methods use File | Settings | File Templates. } @Override public Type getSponsorType() { return sponsorType; //To change body of implemented methods use File | Settings | File Templates. } @Override public Date getAffiliationDate() { return affiliationDate; //To change body of implemented methods use File | Settings | File Templates. } @Override public Date getTerminationDate() { return terminationDate; //To change body of implemented methods use File | Settings | File Templates. } @Override public void setProgramName(String auxiliaryProgramName) { this.programName = auxiliaryProgramName; } @Override public void setSponsorType(Type sponsorType) { this.sponsorType = sponsorType; } @Override public void setAffiliationDate(Date affiliationDate) { this.affiliationDate = affiliationDate; } @Override public void setTerminationDate(Date terminationDate) { this.terminationDate = terminationDate; } @Override public Set<AuxiliaryIdentifier> getIdentifiers() { return identifiers; } @Override public void addAuxiliaryIdentifier(AuxiliaryIdentifier identifier) { identifiers.add(identifier); } @Override public void removeAuxiliaryIdentifier(AuxiliaryIdentifier identifier) { identifiers.remove(identifier); } @Override public void setSponsorId(Long sponsorId) { this.sponsorId = sponsorId; } }
31.850746
138
0.698219
4a8aa6016200d739ce8df3c6661eae7fec0decb6
1,176
/* * Copyright 2015 S. Webber * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.oakgp.rank; import java.util.Collection; import org.oakgp.node.Node; /** Ranks and sorts the fitness of {@code Node} instances. */ @FunctionalInterface public interface GenerationRanker { /** * Returns the sorted result of evaluating the fitness of each of the specified nodes. * * @param input * the {@code Node} instances to evaluate the fitness of * @return a collection of {@code RankedCandidate} - one for each {@code Node} specified in {@code input} - sorted by fitness */ RankedCandidates rank(Collection<Node> input); }
34.588235
128
0.717687
c2bae1b1a86b911476c26c93ea0134886c9c0abc
4,955
/* * Licensed to Crate under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. Crate licenses this file * to you under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * * However, if you have executed another commercial license agreement * with Crate these terms will supersede the license and you may use the * software solely pursuant to the terms of the relevant commercial * agreement. */ package io.crate.execution.jobs.transport; import static io.crate.testing.DiscoveryNodes.newNode; import static org.hamcrest.Matchers.is; import static org.mockito.Mockito.mock; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import org.elasticsearch.Version; import org.elasticsearch.action.ActionListener; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.transport.Transport; import org.elasticsearch.transport.TransportService; import org.junit.Test; import io.crate.exceptions.TaskMissing; import io.crate.execution.engine.collect.stats.JobsLogs; import io.crate.execution.jobs.DummyTask; import io.crate.execution.jobs.NodeLimits; import io.crate.execution.jobs.RootTask; import io.crate.execution.jobs.TasksService; import io.crate.execution.jobs.kill.KillJobsRequest; import io.crate.execution.jobs.kill.TransportKillJobsNodeAction; import io.crate.test.integration.CrateDummyClusterServiceUnitTest; public class NodeDisconnectJobMonitorServiceTest extends CrateDummyClusterServiceUnitTest { private TasksService tasksInstance() throws Exception { return new TasksService(clusterService, new JobsLogs(() -> true)); } @Test public void testOnNodeDisconnectedKillsJobOriginatingFromThatNode() throws Exception { TasksService tasksService = tasksInstance(); RootTask.Builder builder = tasksService.newBuilder(UUID.randomUUID()); builder.addTask(new DummyTask()); RootTask context = tasksService.createTask(builder); NodeDisconnectJobMonitorService monitorService = new NodeDisconnectJobMonitorService( tasksService, new NodeLimits(), mock(TransportService.class), mock(TransportKillJobsNodeAction.class)); monitorService.onNodeDisconnected( new DiscoveryNode(NODE_ID, buildNewFakeTransportAddress(), Version.CURRENT), mock(Transport.Connection.class) ); expectedException.expect(TaskMissing.class); tasksService.getTask(context.jobId()); monitorService.close(); } @Test public void testOnParticipatingNodeDisconnectedKillsJob() throws Exception { TasksService tasksService = tasksInstance(); DiscoveryNode coordinator = newNode("coordinator"); DiscoveryNode dataNode = newNode("dataNode"); RootTask.Builder builder = tasksService.newBuilder(UUID.randomUUID(), "dummy-user", coordinator.getId(), Arrays.asList(coordinator.getId(), dataNode.getId())); builder.addTask(new DummyTask()); tasksService.createTask(builder); // add a second job that is coordinated by the other node to make sure the the broadcast logic is run // even though there are jobs coordinated by the disconnected node builder = tasksService.newBuilder(UUID.randomUUID(), "dummy-user", dataNode.getId(), Collections.emptySet()); builder.addTask(new DummyTask()); tasksService.createTask(builder); AtomicInteger broadcasts = new AtomicInteger(0); TransportKillJobsNodeAction killAction = new TransportKillJobsNodeAction( tasksService, clusterService, mock(TransportService.class) ) { @Override public void broadcast(KillJobsRequest request, ActionListener<Long> listener, Collection<String> excludedNodeIds) { broadcasts.incrementAndGet(); } }; NodeDisconnectJobMonitorService monitorService = new NodeDisconnectJobMonitorService( tasksService, new NodeLimits(), mock(TransportService.class), killAction); monitorService.onNodeDisconnected(dataNode, mock(Transport.Connection.class)); assertThat(broadcasts.get(), is(1)); monitorService.close(); } }
40.950413
167
0.733401
1adf082f64ff69155f283147adbfe2f423c2ca19
2,344
package com.smartcodeltd.jenkinsci.plugins.buildmonitor.order; import hudson.model.Job; import hudson.model.Result; import hudson.model.Run; import java.io.Serializable; import java.util.Comparator; import java.util.ListIterator; import java.util.regex.Pattern; import static com.smartcodeltd.jenkinsci.plugins.buildmonitor.RegexMatcher.selectSpecificBuild; public class ByStatusWithRegex implements Comparator<JobByRegexForStatusTemplate>, Serializable { @Override public int compare(JobByRegexForStatusTemplate a, JobByRegexForStatusTemplate b) { return bothProjectsHaveBuildHistory(a, b) ? compareRecentlyCompletedBuilds(a, b) : compareProjects(a, b); } private boolean bothProjectsHaveBuildHistory(JobByRegexForStatusTemplate a, JobByRegexForStatusTemplate b) { return a.getProjects().getLastCompletedBuild() != null && b.getProjects().getLastCompletedBuild() != null; } private int compareProjects(JobByRegexForStatusTemplate a, JobByRegexForStatusTemplate b) { Run<?, ?> recentBuildOfA = a.getProjects().getLastCompletedBuild(); Run<?, ?> recentBuildOfB = b.getProjects().getLastCompletedBuild(); if (recentBuildOfA == null && recentBuildOfB != null) { return -1; } else if (recentBuildOfA != null && recentBuildOfB == null) { return 1; } else { return 0; } } private int compareRecentlyCompletedBuilds(JobByRegexForStatusTemplate a, JobByRegexForStatusTemplate b) { Result lastResultOfA = iterateByJobs(a); Result lastResultOfB = iterateByJobs(b); if (lastResultOfA == null && lastResultOfB == null) { return 0; } else if (lastResultOfA == null) { return -1; } else if (lastResultOfB == null) { return 1; } else if (lastResultOfA.isWorseThan(lastResultOfB)) { return -1; } else if (lastResultOfA.isBetterThan(lastResultOfB)) { return 1; } else { return 0; } } private Result iterateByJobs(JobByRegexForStatusTemplate job){ Job<?,?> j = job.getProjects(); Run run = selectSpecificBuild(j, job.regex); return run == null ? j.getLastCompletedBuild().getResult(): run.getResult(); } }
36.061538
114
0.665956
a20c1d9f96416dcd08457200d6ea418b62515db3
4,432
package shree.firebaseandroid.fragments; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.annotation.DrawableRes; import android.support.v4.app.Fragment; import android.util.Base64; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import java.io.ByteArrayOutputStream; import de.hdodenhof.circleimageview.CircleImageView; import shree.firebaseandroid.Dashboard; import shree.firebaseandroid.Login; import shree.firebaseandroid.ProjectActivities; import shree.firebaseandroid.R; import shree.firebaseandroid.utils.SessionManager; import shree.firebaseandroid.view.ProfileDetails; /** * A simple {@link Fragment} subclass. */ public class MeFragment extends Fragment { View view; TextView username; LinearLayout profile,location,setting,myactivity; ImageView userimage; private SessionManager session; byte[] imageBytes; String imageString; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment view=inflater.inflate(R.layout.fragment_me, container, false); username=(TextView)view.findViewById(R.id.profile_username); profile=(LinearLayout)view.findViewById(R.id.myprofile); location=(LinearLayout)view.findViewById(R.id.loutlocation); setting=(LinearLayout)view.findViewById(R.id.loutsetting); myactivity=(LinearLayout)view.findViewById(R.id.llmyactivity); userimage=(ImageView)view.findViewById(R.id.imguser); session = new SessionManager(getActivity()); username.setText(session.getName()); imageString=session.getCreatorId(); if(imageString.length()>5) { //decode base64 string to image imageBytes = Base64.decode(imageString, Base64.DEFAULT); Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length); userimage.setImageBitmap(decodedImage); } profile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i =new Intent(getActivity(), ProfileDetails.class); startActivity(i); } }); location.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new android.support.v7.app.AlertDialog.Builder(getActivity()) .setTitle("Your RRC Location is") .setIcon(R.drawable.location_icon_36x36) .setMessage("\n"+session.getLocations()) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { arg0.dismiss(); } }).create().show(); } }); myactivity.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String projectname=FragmentProjects.projectdata.get(0).getProgramName().toString(); String projecticon="R.drawable.lnt_icon_96x96"; String projectid=FragmentProjects.projectdata.get(0).getProgramid().toString(); Intent i =new Intent(getActivity(), ProjectActivities.class); i.putExtra("project_id",projectid); i.putExtra("project_name", projectname); i.putExtra("project_icon", projecticon); startActivity(i); } }); setting.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { logout(); } }); return view; } private void logout(){ session.setLoggedin(false); getActivity().finish(); startActivity(new Intent(getActivity(),Login.class)); } }
35.741935
104
0.648014
831445fd08be68abe58d8f7721096bb562f62099
2,386
package com.company; import java.util.Scanner; public class Main { public static void main(String[] args) { // declaring the constant maximum size assigning 25 to it final int MAX = 25; // int[] bf = new int[MAX], ff = new int[MAX]; /* * DECLARING VARIABLES frag- fragment , block - identifies particular block file * - identifies particular file temp - temporal location in memory i - index of * list of data nb - number of blocks nf - number of files lowest - **/ int[] frag = new int[MAX], block = new int[MAX], file = new int[MAX]; int i, numOfBlocks, numOfFiles, temp, lowest = 10000; // creating scanner class Scanner input = new Scanner(System.in); // prompting System.out.print("\nEnter the number of blocks:"); numOfBlocks = input.nextInt(); System.out.print("Enter the number of files:"); numOfFiles = input.nextInt(); // prompting user to enter size of block based on number of blocks entered System.out.println("\nEnter the size of the blocks:-"); for (i = 1; i <= numOfBlocks; i++) { System.out.print("Block " + i + ":"); } block[i] = input.nextInt(); // accepting input // prompting user to enter size of file based on number of files entered System.out.println("Enter the size of the files :-"); for (i = 1; i <= numOfFiles; i++) { System.out.print("File " + i + ":"); file[i] = input.nextInt(); } for (i = 1; i <= numOfFiles; i++) { for (int j = 1; j <= numOfBlocks; j++) { if (bf[j] != 1) { temp = block[j] - file[i]; if (temp >= 0) { if (lowest > temp) { ff[i] = j; lowest = temp; } } } } frag[i] = lowest; bf[ff[i]] = 1; lowest = 10000; } System.out.print("\nFile No\tFile Size \tBlock No\tBlock Size\tFragment"); for (i = 1; i <= numOfFiles && ff[i] != 0; i++) { System.out.print("\n" + i + "\t\t" + file[i] + "\t\t" + ff[i] + "\t\t" + block[ff[i]] + "\t\t" + frag[i]); } } }
33.605634
118
0.484912